{"commit": "fa3c3f9cab1c45b449bd57e238c511c79637e314", "message": "Break weight tying when quantizing input embedding (#37905)", "old_file": "src/transformers/utils/quantization_config.py", "new_file": "src/transformers/utils/quantization_config.py", "status": "M", "old_contents": "\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.include_embedding = include_embedding\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )", "new_contents": "\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n untie_embedding_weights: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n untie_embedding_weights (`bool`, default to `False`):\n Whether to untie the weights when we are quantizing input embedding weights that is tied\n to other weights.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n untie_embedding_weights: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.include_embedding = include_embedding\n self.untie_embedding_weights = untie_embedding_weights\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )", "text": "<|original_code|>\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.include_embedding = include_embedding\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )\n<|edits_diff|>\n--- src/transformers/utils/quantization_config.py\n+++ src/transformers/utils/quantization_config.py\n@@ -20,6 +20,7 @@\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n+ untie_embedding_weights: bool\n \n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n \n@@ -34,6 +35,9 @@\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n+ untie_embedding_weights (`bool`, default to `False`):\n+ Whether to untie the weights when we are quantizing input embedding weights that is tied\n+ to other weights.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n@@ -79,6 +83,7 @@\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n+ untie_embedding_weights: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n<|current_version|>\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n untie_embedding_weights: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n untie_embedding_weights (`bool`, default to `False`):\n Whether to untie the weights when we are quantizing input embedding weights that is tied\n to other weights.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n untie_embedding_weights: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.include_embedding = include_embedding\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )\n<|next_version|>\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n untie_embedding_weights: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n untie_embedding_weights (`bool`, default to `False`):\n Whether to untie the weights when we are quantizing input embedding weights that is tied\n to other weights.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n untie_embedding_weights: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.include_embedding = include_embedding\n self.untie_embedding_weights = untie_embedding_weights\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )\n", "current_contents": "\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n untie_embedding_weights: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n untie_embedding_weights (`bool`, default to `False`):\n Whether to untie the weights when we are quantizing input embedding weights that is tied\n to other weights.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n untie_embedding_weights: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.include_embedding = include_embedding\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )"} {"commit": "86777b5e2f651d7f7c46db919beb13893743a5b5", "message": "Support `AOPerModuleConfig` and `include_embedding` (#37802)", "old_file": "src/transformers/utils/quantization_config.py", "new_file": "src/transformers/utils/quantization_config.py", "status": "M", "old_contents": " self.post_init()\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )", "new_contents": " self.post_init()\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.include_embedding = include_embedding\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )", "text": "<|original_code|>\n self.post_init()\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )\n<|edits_diff|>\n--- src/transformers/utils/quantization_config.py\n+++ src/transformers/utils/quantization_config.py\n@@ -20,6 +20,7 @@\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n+ include_embedding: bool\n \n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n \n@@ -31,6 +32,9 @@\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n+ inlcude_embedding (`bool`, default to `False`):\n+ Whether to include embedding in quantization or not, input embedding will be removed from\n+ the module_not_to_convert list as well if this flag is set.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n@@ -75,6 +79,7 @@\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n+ include_embedding: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n<|current_version|>\n self.post_init()\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )\n<|next_version|>\n self.post_init()\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.include_embedding = include_embedding\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )\n", "current_contents": " self.post_init()\n\n def post_init(self):\n r\"\"\"\n Safety checker that arguments are correct - also replaces some NoneType arguments with their default values.\n \"\"\"\n if self.bits not in [2, 3, 4]:\n raise ValueError(\"bits must be 2, 3, or 4\")\n if self.p not in [1, 2]:\n raise ValueError(\"p must be 1 or 2. 2 is always better in practice\")\n if self.group_size not in [64, 128, 256]:\n raise ValueError(\"group_size must be 64, 128, or 256\")\n if self.hadamard_size % self.group_size != 0:\n raise ValueError(\"hadamard_size must be divisible by group_size\")\n\n\n@dataclass\nclass TorchAoConfig(QuantizationConfigMixin):\n quant_method: QuantizationMethod\n quant_type: Union[str, \"AOBaseConfig\"] # noqa: F821\n modules_to_not_convert: Optional[List]\n quant_type_kwargs: Dict[str, Any]\n include_embedding: bool\n\n \"\"\"This is a config class for torchao quantization/sparsity techniques.\n\n Args:\n quant_type (`Union[str, AOBaseConfig]`):\n The type of quantization we want to use. Can be either:\n - A string: currently supporting: `int4_weight_only`, `int8_weight_only` and `int8_dynamic_activation_int8_weight`.\n - An AOBaseConfig instance: for more advanced configuration options.\n modules_to_not_convert (`list`, *optional*, default to `None`):\n The list of modules to not quantize, useful for quantizing models that explicitly require to have\n some modules left in their original precision.\n inlcude_embedding (`bool`, default to `False`):\n Whether to include embedding in quantization or not, input embedding will be removed from\n the module_not_to_convert list as well if this flag is set.\n kwargs (`Dict[str, Any]`, *optional*):\n The keyword arguments for the chosen type of quantization, for example, int4_weight_only quantization supports two keyword arguments\n `group_size` and `inner_k_tiles` currently. More API examples and documentation of arguments can be found in\n https://github.com/pytorch/ao/tree/main/torchao/quantization#other-available-quantization-techniques\n\n Example:\n\n ```python\n # AOBaseConfig-based configuration\n config = Int4WeightOnlyConfig(group_size=32)\n quantization_config = TorchAoConfig(config)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # String-based configuration\n quantization_config = TorchAoConfig(\"int4_weight_only\", group_size=32)\n # int4_weight_only quant is only working with *torch.bfloat16* dtype right now\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n\n # autoquant\n # `autoquant` is a convenient way for users to search for the best quantization for each layer\n # `min_sqnr` is an option to control the accuracy of the model, higher value means the model is more\n # accurate, we can start with 30 and adjust it to larger or smaller (e.g. 40, 20)\n # defaults to None, which means we'll try to get the best performing quantized model without\n # considering accuracy\n quantization_config = TorchAoConfig(\"autoquant\", min_sqnr=30)\n model = AutoModelForCausalLM.from_pretrained(model_id, device_map=\"cuda\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)\n # run through example inputs, quantization methods will be selected based on the shape of example input\n tokenizer = AutoTokenizer.from_pretrained(model_name)\n input_text = \"What are we having for dinner?\"\n input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")\n MAX_NEW_TOKENS = 1000\n model.generate(**input_ids, max_new_tokens=MAX_NEW_TOKENS, cache_implementation=\"static\")\n # manually ran finalize_autoquant if needed\n if hasattr(quantized_model, \"finalize_autoquant\"):\n print(\"finalizing autoquant\")\n quantized_model.finalize_autoquant()\n\n ```\n \"\"\"\n\n def __init__(\n self,\n quant_type: Union[str, \"AOBaseConfig\"], # noqa: F821\n modules_to_not_convert: Optional[List] = None,\n include_embedding: bool = False,\n **kwargs,\n ):\n self.quant_method = QuantizationMethod.TORCHAO\n self.quant_type = quant_type\n self.modules_to_not_convert = modules_to_not_convert\n self.quant_type_kwargs = kwargs.get(\"quant_type_kwargs\", kwargs)\n self.post_init()\n\n @staticmethod\n def _get_ao_version() -> version.Version:\n \"\"\"Centralized check for TorchAO availability and version requirements.\"\"\"\n if not is_torchao_available():\n raise ValueError(\"TorchAoConfig requires torchao to be installed. Install with `pip install torchao`\")\n\n return version.parse(importlib.metadata.version(\"torchao\"))\n\n def post_init(self):\n \"\"\"Validate configuration and set defaults.\"\"\"\n ao_version = self._get_ao_version()\n\n # Handle quant_type based on type and version\n if isinstance(self.quant_type, str):\n self._validate_string_quant_type()\n elif ao_version > version.parse(\"0.9.0\"):\n from torchao.quantization.quant_api import AOBaseConfig\n\n if not isinstance(self.quant_type, AOBaseConfig):\n raise ValueError(\n f\"quant_type must be either a string or an AOBaseConfig instance, got {type(self.quant_type)}\"\n )"} {"commit": "2933894985b8b69fb65c5f0e7676f2be88f965b9", "message": "Fix error of HPU TP (#37782)", "old_file": "src/transformers/modeling_utils.py", "new_file": "src/transformers/modeling_utils.py", "status": "M", "old_contents": " if tp_plan is not None:\n if not is_torch_greater_or_equal(\"2.5\"):\n raise EnvironmentError(\"tensor parallel is only supported for `torch>=2.5`.\")\n\n # Detect the accelerator on the machine. If no accelerator is available, it returns CPU.\n device_type = torch._C._get_accelerator().type\n\n if not torch.distributed.is_initialized():\n try:\n rank = int(os.environ[\"RANK\"])\n world_size = int(os.environ[\"WORLD_SIZE\"])\n if device_type == \"cuda\":\n torch.distributed.init_process_group(\n \"nccl\", rank=rank, world_size=world_size, init_method=\"env://\"\n )\n torch.cuda.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"cpu\":\n cpu_backend = \"ccl\" if int(os.environ.get(\"CCL_WORKER_COUNT\", 0)) else \"gloo\"\n torch.distributed.init_process_group(cpu_backend, rank=rank, world_size=world_size)\n elif device_type == \"xpu\":\n torch.distributed.init_process_group(\"ccl\", rank=rank, world_size=world_size)\n torch.xpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n\n except Exception as e:\n raise EnvironmentError(\n \"We tried to initialize torch.distributed for you, but it failed, make\"\n \"sure you init torch distributed in your script to use `tp_plan='auto'`\"\n ) from e\n\n # Get device with index assuming equal number of devices per host\n if device_type == \"xpu\":\n index = torch.xpu.current_device()\n else:\n index = None if device_type == \"cpu\" else torch.cuda.current_device()\n tp_device = torch.device(device_type, index)\n\n if index is not None and index > 0:\n import sys\n\n sys.stdout = open(os.devnull, \"w\")\n sys.stderr = open(os.devnull, \"w\")\n # This is the easiest way to dispatch to the current process device\n device_map = tp_device\n\n # Assuming sharding the model onto the world when tp_size not provided\n tp_size = tp_size if tp_size is not None else torch.distributed.get_world_size()\n device_mesh = torch.distributed.init_device_mesh(tp_device.type, (tp_size,))\n\n if use_auth_token is not None:\n warnings.warn(\n \"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.\",\n FutureWarning,\n )\n if token is not None:\n raise ValueError(\n \"`token` and `use_auth_token` are both specified. Please set only the argument `token`.\"", "new_contents": " if tp_plan is not None:\n if not is_torch_greater_or_equal(\"2.5\"):\n raise EnvironmentError(\"tensor parallel is only supported for `torch>=2.5`.\")\n\n # Detect the accelerator on the machine. If no accelerator is available, it returns CPU.\n device_type = torch._C._get_accelerator().type\n\n if not torch.distributed.is_initialized():\n try:\n rank = int(os.environ[\"RANK\"])\n world_size = int(os.environ[\"WORLD_SIZE\"])\n if device_type == \"cuda\":\n torch.distributed.init_process_group(\n \"nccl\", rank=rank, world_size=world_size, init_method=\"env://\"\n )\n torch.cuda.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"cpu\":\n cpu_backend = \"ccl\" if int(os.environ.get(\"CCL_WORKER_COUNT\", 0)) else \"gloo\"\n torch.distributed.init_process_group(cpu_backend, rank=rank, world_size=world_size)\n elif device_type == \"xpu\":\n torch.distributed.init_process_group(\"ccl\", rank=rank, world_size=world_size)\n torch.xpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"hpu\":\n torch.distributed.init_process_group(\"hccl\", rank=rank, world_size=world_size)\n torch.hpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n\n except Exception as e:\n raise EnvironmentError(\n \"We tried to initialize torch.distributed for you, but it failed, make\"\n \"sure you init torch distributed in your script to use `tp_plan='auto'`\"\n ) from e\n\n # Get device with index assuming equal number of devices per host\n if device_type == \"xpu\":\n index = torch.xpu.current_device()\n elif device_type == \"hpu\":\n index = torch.hpu.current_device()\n else:\n index = None if device_type == \"cpu\" else torch.cuda.current_device()\n tp_device = torch.device(device_type, index)\n\n if index is not None and index > 0:\n import sys\n\n sys.stdout = open(os.devnull, \"w\")\n sys.stderr = open(os.devnull, \"w\")\n # This is the easiest way to dispatch to the current process device\n device_map = tp_device\n\n # Assuming sharding the model onto the world when tp_size not provided\n tp_size = tp_size if tp_size is not None else torch.distributed.get_world_size()\n device_mesh = torch.distributed.init_device_mesh(tp_device.type, (tp_size,))\n\n if use_auth_token is not None:\n warnings.warn(\n \"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.\",\n FutureWarning,\n )\n if token is not None:\n raise ValueError(\n \"`token` and `use_auth_token` are both specified. Please set only the argument `token`.\"", "text": "<|original_code|>\n if tp_plan is not None:\n if not is_torch_greater_or_equal(\"2.5\"):\n raise EnvironmentError(\"tensor parallel is only supported for `torch>=2.5`.\")\n\n # Detect the accelerator on the machine. If no accelerator is available, it returns CPU.\n device_type = torch._C._get_accelerator().type\n\n if not torch.distributed.is_initialized():\n try:\n rank = int(os.environ[\"RANK\"])\n world_size = int(os.environ[\"WORLD_SIZE\"])\n if device_type == \"cuda\":\n torch.distributed.init_process_group(\n \"nccl\", rank=rank, world_size=world_size, init_method=\"env://\"\n )\n torch.cuda.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"cpu\":\n cpu_backend = \"ccl\" if int(os.environ.get(\"CCL_WORKER_COUNT\", 0)) else \"gloo\"\n torch.distributed.init_process_group(cpu_backend, rank=rank, world_size=world_size)\n elif device_type == \"xpu\":\n torch.distributed.init_process_group(\"ccl\", rank=rank, world_size=world_size)\n torch.xpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n\n except Exception as e:\n raise EnvironmentError(\n \"We tried to initialize torch.distributed for you, but it failed, make\"\n \"sure you init torch distributed in your script to use `tp_plan='auto'`\"\n ) from e\n\n # Get device with index assuming equal number of devices per host\n if device_type == \"xpu\":\n index = torch.xpu.current_device()\n else:\n index = None if device_type == \"cpu\" else torch.cuda.current_device()\n tp_device = torch.device(device_type, index)\n\n if index is not None and index > 0:\n import sys\n\n sys.stdout = open(os.devnull, \"w\")\n sys.stderr = open(os.devnull, \"w\")\n # This is the easiest way to dispatch to the current process device\n device_map = tp_device\n\n # Assuming sharding the model onto the world when tp_size not provided\n tp_size = tp_size if tp_size is not None else torch.distributed.get_world_size()\n device_mesh = torch.distributed.init_device_mesh(tp_device.type, (tp_size,))\n\n if use_auth_token is not None:\n warnings.warn(\n \"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.\",\n FutureWarning,\n )\n if token is not None:\n raise ValueError(\n \"`token` and `use_auth_token` are both specified. Please set only the argument `token`.\"\n<|edits_diff|>\n--- src/transformers/modeling_utils.py\n+++ src/transformers/modeling_utils.py\n@@ -20,6 +20,9 @@\n elif device_type == \"xpu\":\n torch.distributed.init_process_group(\"ccl\", rank=rank, world_size=world_size)\n torch.xpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n+ elif device_type == \"hpu\":\n+ torch.distributed.init_process_group(\"hccl\", rank=rank, world_size=world_size)\n+ torch.hpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n \n except Exception as e:\n raise EnvironmentError(\n<|current_version|>\n if tp_plan is not None:\n if not is_torch_greater_or_equal(\"2.5\"):\n raise EnvironmentError(\"tensor parallel is only supported for `torch>=2.5`.\")\n\n # Detect the accelerator on the machine. If no accelerator is available, it returns CPU.\n device_type = torch._C._get_accelerator().type\n\n if not torch.distributed.is_initialized():\n try:\n rank = int(os.environ[\"RANK\"])\n world_size = int(os.environ[\"WORLD_SIZE\"])\n if device_type == \"cuda\":\n torch.distributed.init_process_group(\n \"nccl\", rank=rank, world_size=world_size, init_method=\"env://\"\n )\n torch.cuda.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"cpu\":\n cpu_backend = \"ccl\" if int(os.environ.get(\"CCL_WORKER_COUNT\", 0)) else \"gloo\"\n torch.distributed.init_process_group(cpu_backend, rank=rank, world_size=world_size)\n elif device_type == \"xpu\":\n torch.distributed.init_process_group(\"ccl\", rank=rank, world_size=world_size)\n torch.xpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"hpu\":\n torch.distributed.init_process_group(\"hccl\", rank=rank, world_size=world_size)\n torch.hpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n\n except Exception as e:\n raise EnvironmentError(\n \"We tried to initialize torch.distributed for you, but it failed, make\"\n \"sure you init torch distributed in your script to use `tp_plan='auto'`\"\n ) from e\n\n # Get device with index assuming equal number of devices per host\n if device_type == \"xpu\":\n index = torch.xpu.current_device()\n else:\n index = None if device_type == \"cpu\" else torch.cuda.current_device()\n tp_device = torch.device(device_type, index)\n\n if index is not None and index > 0:\n import sys\n\n sys.stdout = open(os.devnull, \"w\")\n sys.stderr = open(os.devnull, \"w\")\n # This is the easiest way to dispatch to the current process device\n device_map = tp_device\n\n # Assuming sharding the model onto the world when tp_size not provided\n tp_size = tp_size if tp_size is not None else torch.distributed.get_world_size()\n device_mesh = torch.distributed.init_device_mesh(tp_device.type, (tp_size,))\n\n if use_auth_token is not None:\n warnings.warn(\n \"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.\",\n FutureWarning,\n )\n if token is not None:\n raise ValueError(\n \"`token` and `use_auth_token` are both specified. Please set only the argument `token`.\"\n<|next_version|>\n if tp_plan is not None:\n if not is_torch_greater_or_equal(\"2.5\"):\n raise EnvironmentError(\"tensor parallel is only supported for `torch>=2.5`.\")\n\n # Detect the accelerator on the machine. If no accelerator is available, it returns CPU.\n device_type = torch._C._get_accelerator().type\n\n if not torch.distributed.is_initialized():\n try:\n rank = int(os.environ[\"RANK\"])\n world_size = int(os.environ[\"WORLD_SIZE\"])\n if device_type == \"cuda\":\n torch.distributed.init_process_group(\n \"nccl\", rank=rank, world_size=world_size, init_method=\"env://\"\n )\n torch.cuda.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"cpu\":\n cpu_backend = \"ccl\" if int(os.environ.get(\"CCL_WORKER_COUNT\", 0)) else \"gloo\"\n torch.distributed.init_process_group(cpu_backend, rank=rank, world_size=world_size)\n elif device_type == \"xpu\":\n torch.distributed.init_process_group(\"ccl\", rank=rank, world_size=world_size)\n torch.xpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"hpu\":\n torch.distributed.init_process_group(\"hccl\", rank=rank, world_size=world_size)\n torch.hpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n\n except Exception as e:\n raise EnvironmentError(\n \"We tried to initialize torch.distributed for you, but it failed, make\"\n \"sure you init torch distributed in your script to use `tp_plan='auto'`\"\n ) from e\n\n # Get device with index assuming equal number of devices per host\n if device_type == \"xpu\":\n index = torch.xpu.current_device()\n elif device_type == \"hpu\":\n index = torch.hpu.current_device()\n else:\n index = None if device_type == \"cpu\" else torch.cuda.current_device()\n tp_device = torch.device(device_type, index)\n\n if index is not None and index > 0:\n import sys\n\n sys.stdout = open(os.devnull, \"w\")\n sys.stderr = open(os.devnull, \"w\")\n # This is the easiest way to dispatch to the current process device\n device_map = tp_device\n\n # Assuming sharding the model onto the world when tp_size not provided\n tp_size = tp_size if tp_size is not None else torch.distributed.get_world_size()\n device_mesh = torch.distributed.init_device_mesh(tp_device.type, (tp_size,))\n\n if use_auth_token is not None:\n warnings.warn(\n \"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.\",\n FutureWarning,\n )\n if token is not None:\n raise ValueError(\n \"`token` and `use_auth_token` are both specified. Please set only the argument `token`.\"\n", "current_contents": " if tp_plan is not None:\n if not is_torch_greater_or_equal(\"2.5\"):\n raise EnvironmentError(\"tensor parallel is only supported for `torch>=2.5`.\")\n\n # Detect the accelerator on the machine. If no accelerator is available, it returns CPU.\n device_type = torch._C._get_accelerator().type\n\n if not torch.distributed.is_initialized():\n try:\n rank = int(os.environ[\"RANK\"])\n world_size = int(os.environ[\"WORLD_SIZE\"])\n if device_type == \"cuda\":\n torch.distributed.init_process_group(\n \"nccl\", rank=rank, world_size=world_size, init_method=\"env://\"\n )\n torch.cuda.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"cpu\":\n cpu_backend = \"ccl\" if int(os.environ.get(\"CCL_WORKER_COUNT\", 0)) else \"gloo\"\n torch.distributed.init_process_group(cpu_backend, rank=rank, world_size=world_size)\n elif device_type == \"xpu\":\n torch.distributed.init_process_group(\"ccl\", rank=rank, world_size=world_size)\n torch.xpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n elif device_type == \"hpu\":\n torch.distributed.init_process_group(\"hccl\", rank=rank, world_size=world_size)\n torch.hpu.set_device(int(os.environ[\"LOCAL_RANK\"]))\n\n except Exception as e:\n raise EnvironmentError(\n \"We tried to initialize torch.distributed for you, but it failed, make\"\n \"sure you init torch distributed in your script to use `tp_plan='auto'`\"\n ) from e\n\n # Get device with index assuming equal number of devices per host\n if device_type == \"xpu\":\n index = torch.xpu.current_device()\n else:\n index = None if device_type == \"cpu\" else torch.cuda.current_device()\n tp_device = torch.device(device_type, index)\n\n if index is not None and index > 0:\n import sys\n\n sys.stdout = open(os.devnull, \"w\")\n sys.stderr = open(os.devnull, \"w\")\n # This is the easiest way to dispatch to the current process device\n device_map = tp_device\n\n # Assuming sharding the model onto the world when tp_size not provided\n tp_size = tp_size if tp_size is not None else torch.distributed.get_world_size()\n device_mesh = torch.distributed.init_device_mesh(tp_device.type, (tp_size,))\n\n if use_auth_token is not None:\n warnings.warn(\n \"The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.\",\n FutureWarning,\n )\n if token is not None:\n raise ValueError(\n \"`token` and `use_auth_token` are both specified. Please set only the argument `token`.\""} {"commit": "77aa9fc0767439fab61108d960cec8ec37c6723e", "message": "[generate] Fix encoder decoder models attention mask (#36018)", "old_file": "src/transformers/generation/utils.py", "new_file": "src/transformers/generation/utils.py", "status": "M", "old_contents": " inputs_embeds is not None # Exception 1\n or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3\n ):\n input_ids = input_ids[:, -cache_position.shape[0] :]\n elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the \"else\", a no op, is Exception 2)\n input_ids = input_ids[:, cache_position]\n\n # 3. Prepare base model inputs\n input_ids_key = \"decoder_input_ids\" if self.config.is_encoder_decoder else \"input_ids\"\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.\n if not self.config.is_encoder_decoder:\n if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:\n model_inputs[input_ids_key] = None\n model_inputs[\"inputs_embeds\"] = inputs_embeds\n else:\n # `clone` calls in this function ensure a consistent stride. See #32227\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n model_inputs[\"inputs_embeds\"] = None\n else:\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n\n # 4. Create missing `position_ids` on the fly\n attention_mask = (\n kwargs.pop(\"decoder_attention_mask\", None) if self.config.is_encoder_decoder else attention_mask\n )\n attention_mask_key = \"decoder_attention_mask\" if self.config.is_encoder_decoder else \"attention_mask\"\n position_ids_key = \"decoder_position_ids\" if self.config.is_encoder_decoder else \"position_ids\"\n if (\n attention_mask is not None\n and kwargs.get(position_ids_key) is None\n and position_ids_key in set(inspect.signature(self.forward).parameters.keys())\n ):\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n kwargs[position_ids_key] = position_ids # placed in kwargs for further processing (see below)\n\n # 5. Slice model inputs if it's an input that should have the same length as `input_ids`\n for model_input_name in [\"position_ids\", \"token_type_ids\", \"decoder_position_ids\"]:\n model_input = kwargs.get(model_input_name)\n if model_input is not None:\n if past_key_values is not None:\n current_input_length = (\n model_inputs[\"inputs_embeds\"].shape[1]\n if model_inputs.get(\"inputs_embeds\") is not None\n else model_inputs[input_ids_key].shape[1]\n )\n model_input = model_input[:, -current_input_length:]\n model_input = model_input.clone(memory_format=torch.contiguous_format)\n model_inputs[model_input_name] = model_input\n\n # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)\n if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:\n if model_inputs[\"inputs_embeds\"] is not None:\n batch_size, sequence_length, _ = model_inputs[\"inputs_embeds\"].shape\n device = model_inputs[\"inputs_embeds\"].device\n else:\n batch_size, sequence_length = model_inputs[input_ids_key].shape\n device = model_inputs[input_ids_key].device\n\n # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create\n # the 4D causal mask exists, it should be present in the base model (XXXModel class).\n base_model = getattr(self, self.base_model_prefix, None)\n if base_model is None:\n causal_mask_creation_function = getattr(\n self, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n else:\n causal_mask_creation_function = getattr(\n base_model, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n if causal_mask_creation_function is None:\n logger.warning_once(\n f\"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method \"\n \"defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're \"\n \"writing code, see Llama for an example implementation. If you're a user, please report this \"\n \"issue on GitHub.\"\n )\n else:\n attention_mask = causal_mask_creation_function(\n attention_mask,\n sequence_length=sequence_length,\n target_length=past_key_values.get_max_cache_shape(),\n dtype=self.dtype,\n device=device,\n cache_position=cache_position,\n batch_size=batch_size,\n config=self.config,\n past_key_values=past_key_values,\n )\n if attention_mask is not None:\n model_inputs[attention_mask_key] = attention_mask\n\n # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).\n for key, value in kwargs.items():\n if key not in model_inputs:\n model_inputs[key] = value\n\n # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)\n model_inputs.pop(\"labels\", None)\n return model_inputs\n\n def _prepare_model_inputs(\n self,\n inputs: Optional[torch.Tensor] = None,\n bos_token_id: Optional[torch.Tensor] = None,\n model_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:\n \"\"\"\n This function extracts the model-specific `inputs` for generation.\n \"\"\"\n # 1. retrieve all kwargs that are non-None or non-model input related.\n # some encoder-decoder models have different names for model and encoder\n if (\n self.config.is_encoder_decoder\n and hasattr(self, \"encoder\")", "new_contents": " inputs_embeds is not None # Exception 1\n or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3\n ):\n input_ids = input_ids[:, -cache_position.shape[0] :]\n elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the \"else\", a no op, is Exception 2)\n input_ids = input_ids[:, cache_position]\n\n # 3. Prepare base model inputs\n input_ids_key = \"decoder_input_ids\" if self.config.is_encoder_decoder else \"input_ids\"\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.\n if not self.config.is_encoder_decoder:\n if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:\n model_inputs[input_ids_key] = None\n model_inputs[\"inputs_embeds\"] = inputs_embeds\n else:\n # `clone` calls in this function ensure a consistent stride. See #32227\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n model_inputs[\"inputs_embeds\"] = None\n else:\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n\n # 4. Create missing `position_ids` on the fly\n encoder_attention_mask = attention_mask if self.config.is_encoder_decoder else None\n attention_mask = (\n kwargs.pop(\"decoder_attention_mask\", None) if self.config.is_encoder_decoder else attention_mask\n )\n attention_mask_key = \"decoder_attention_mask\" if self.config.is_encoder_decoder else \"attention_mask\"\n position_ids_key = \"decoder_position_ids\" if self.config.is_encoder_decoder else \"position_ids\"\n if (\n attention_mask is not None\n and kwargs.get(position_ids_key) is None\n and position_ids_key in set(inspect.signature(self.forward).parameters.keys())\n ):\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n kwargs[position_ids_key] = position_ids # placed in kwargs for further processing (see below)\n\n # 5. Slice model inputs if it's an input that should have the same length as `input_ids`\n for model_input_name in [\"position_ids\", \"token_type_ids\", \"decoder_position_ids\"]:\n model_input = kwargs.get(model_input_name)\n if model_input is not None:\n if past_key_values is not None:\n current_input_length = (\n model_inputs[\"inputs_embeds\"].shape[1]\n if model_inputs.get(\"inputs_embeds\") is not None\n else model_inputs[input_ids_key].shape[1]\n )\n model_input = model_input[:, -current_input_length:]\n model_input = model_input.clone(memory_format=torch.contiguous_format)\n model_inputs[model_input_name] = model_input\n\n # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)\n if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:\n if model_inputs[\"inputs_embeds\"] is not None:\n batch_size, sequence_length, _ = model_inputs[\"inputs_embeds\"].shape\n device = model_inputs[\"inputs_embeds\"].device\n else:\n batch_size, sequence_length = model_inputs[input_ids_key].shape\n device = model_inputs[input_ids_key].device\n\n # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create\n # the 4D causal mask exists, it should be present in the base model (XXXModel class).\n base_model = getattr(self, self.base_model_prefix, None)\n if base_model is None:\n causal_mask_creation_function = getattr(\n self, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n else:\n causal_mask_creation_function = getattr(\n base_model, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n if causal_mask_creation_function is None:\n logger.warning_once(\n f\"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method \"\n \"defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're \"\n \"writing code, see Llama for an example implementation. If you're a user, please report this \"\n \"issue on GitHub.\"\n )\n else:\n attention_mask = causal_mask_creation_function(\n attention_mask,\n sequence_length=sequence_length,\n target_length=past_key_values.get_max_cache_shape(),\n dtype=self.dtype,\n device=device,\n cache_position=cache_position,\n batch_size=batch_size,\n config=self.config,\n past_key_values=past_key_values,\n )\n if attention_mask is not None:\n model_inputs[attention_mask_key] = attention_mask\n\n if encoder_attention_mask is not None:\n model_inputs[\"attention_mask\"] = encoder_attention_mask\n\n # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).\n for key, value in kwargs.items():\n if key not in model_inputs:\n model_inputs[key] = value\n\n # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)\n model_inputs.pop(\"labels\", None)\n return model_inputs\n\n def _prepare_model_inputs(\n self,\n inputs: Optional[torch.Tensor] = None,\n bos_token_id: Optional[torch.Tensor] = None,\n model_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:\n \"\"\"\n This function extracts the model-specific `inputs` for generation.\n \"\"\"\n # 1. retrieve all kwargs that are non-None or non-model input related.\n # some encoder-decoder models have different names for model and encoder\n if (\n self.config.is_encoder_decoder\n and hasattr(self, \"encoder\")", "text": "<|original_code|>\n inputs_embeds is not None # Exception 1\n or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3\n ):\n input_ids = input_ids[:, -cache_position.shape[0] :]\n elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the \"else\", a no op, is Exception 2)\n input_ids = input_ids[:, cache_position]\n\n # 3. Prepare base model inputs\n input_ids_key = \"decoder_input_ids\" if self.config.is_encoder_decoder else \"input_ids\"\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.\n if not self.config.is_encoder_decoder:\n if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:\n model_inputs[input_ids_key] = None\n model_inputs[\"inputs_embeds\"] = inputs_embeds\n else:\n # `clone` calls in this function ensure a consistent stride. See #32227\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n model_inputs[\"inputs_embeds\"] = None\n else:\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n\n # 4. Create missing `position_ids` on the fly\n attention_mask = (\n kwargs.pop(\"decoder_attention_mask\", None) if self.config.is_encoder_decoder else attention_mask\n )\n attention_mask_key = \"decoder_attention_mask\" if self.config.is_encoder_decoder else \"attention_mask\"\n position_ids_key = \"decoder_position_ids\" if self.config.is_encoder_decoder else \"position_ids\"\n if (\n attention_mask is not None\n and kwargs.get(position_ids_key) is None\n and position_ids_key in set(inspect.signature(self.forward).parameters.keys())\n ):\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n kwargs[position_ids_key] = position_ids # placed in kwargs for further processing (see below)\n\n # 5. Slice model inputs if it's an input that should have the same length as `input_ids`\n for model_input_name in [\"position_ids\", \"token_type_ids\", \"decoder_position_ids\"]:\n model_input = kwargs.get(model_input_name)\n if model_input is not None:\n if past_key_values is not None:\n current_input_length = (\n model_inputs[\"inputs_embeds\"].shape[1]\n if model_inputs.get(\"inputs_embeds\") is not None\n else model_inputs[input_ids_key].shape[1]\n )\n model_input = model_input[:, -current_input_length:]\n model_input = model_input.clone(memory_format=torch.contiguous_format)\n model_inputs[model_input_name] = model_input\n\n # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)\n if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:\n if model_inputs[\"inputs_embeds\"] is not None:\n batch_size, sequence_length, _ = model_inputs[\"inputs_embeds\"].shape\n device = model_inputs[\"inputs_embeds\"].device\n else:\n batch_size, sequence_length = model_inputs[input_ids_key].shape\n device = model_inputs[input_ids_key].device\n\n # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create\n # the 4D causal mask exists, it should be present in the base model (XXXModel class).\n base_model = getattr(self, self.base_model_prefix, None)\n if base_model is None:\n causal_mask_creation_function = getattr(\n self, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n else:\n causal_mask_creation_function = getattr(\n base_model, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n if causal_mask_creation_function is None:\n logger.warning_once(\n f\"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method \"\n \"defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're \"\n \"writing code, see Llama for an example implementation. If you're a user, please report this \"\n \"issue on GitHub.\"\n )\n else:\n attention_mask = causal_mask_creation_function(\n attention_mask,\n sequence_length=sequence_length,\n target_length=past_key_values.get_max_cache_shape(),\n dtype=self.dtype,\n device=device,\n cache_position=cache_position,\n batch_size=batch_size,\n config=self.config,\n past_key_values=past_key_values,\n )\n if attention_mask is not None:\n model_inputs[attention_mask_key] = attention_mask\n\n # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).\n for key, value in kwargs.items():\n if key not in model_inputs:\n model_inputs[key] = value\n\n # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)\n model_inputs.pop(\"labels\", None)\n return model_inputs\n\n def _prepare_model_inputs(\n self,\n inputs: Optional[torch.Tensor] = None,\n bos_token_id: Optional[torch.Tensor] = None,\n model_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:\n \"\"\"\n This function extracts the model-specific `inputs` for generation.\n \"\"\"\n # 1. retrieve all kwargs that are non-None or non-model input related.\n # some encoder-decoder models have different names for model and encoder\n if (\n self.config.is_encoder_decoder\n and hasattr(self, \"encoder\")\n<|edits_diff|>\n--- src/transformers/generation/utils.py\n+++ src/transformers/generation/utils.py\n@@ -20,6 +20,7 @@\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n \n # 4. Create missing `position_ids` on the fly\n+ encoder_attention_mask = attention_mask if self.config.is_encoder_decoder else None\n attention_mask = (\n kwargs.pop(\"decoder_attention_mask\", None) if self.config.is_encoder_decoder else attention_mask\n )\n<|current_version|>\n inputs_embeds is not None # Exception 1\n or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3\n ):\n input_ids = input_ids[:, -cache_position.shape[0] :]\n elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the \"else\", a no op, is Exception 2)\n input_ids = input_ids[:, cache_position]\n\n # 3. Prepare base model inputs\n input_ids_key = \"decoder_input_ids\" if self.config.is_encoder_decoder else \"input_ids\"\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.\n if not self.config.is_encoder_decoder:\n if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:\n model_inputs[input_ids_key] = None\n model_inputs[\"inputs_embeds\"] = inputs_embeds\n else:\n # `clone` calls in this function ensure a consistent stride. See #32227\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n model_inputs[\"inputs_embeds\"] = None\n else:\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n\n # 4. Create missing `position_ids` on the fly\n encoder_attention_mask = attention_mask if self.config.is_encoder_decoder else None\n attention_mask = (\n kwargs.pop(\"decoder_attention_mask\", None) if self.config.is_encoder_decoder else attention_mask\n )\n attention_mask_key = \"decoder_attention_mask\" if self.config.is_encoder_decoder else \"attention_mask\"\n position_ids_key = \"decoder_position_ids\" if self.config.is_encoder_decoder else \"position_ids\"\n if (\n attention_mask is not None\n and kwargs.get(position_ids_key) is None\n and position_ids_key in set(inspect.signature(self.forward).parameters.keys())\n ):\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n kwargs[position_ids_key] = position_ids # placed in kwargs for further processing (see below)\n\n # 5. Slice model inputs if it's an input that should have the same length as `input_ids`\n for model_input_name in [\"position_ids\", \"token_type_ids\", \"decoder_position_ids\"]:\n model_input = kwargs.get(model_input_name)\n if model_input is not None:\n if past_key_values is not None:\n current_input_length = (\n model_inputs[\"inputs_embeds\"].shape[1]\n if model_inputs.get(\"inputs_embeds\") is not None\n else model_inputs[input_ids_key].shape[1]\n )\n model_input = model_input[:, -current_input_length:]\n model_input = model_input.clone(memory_format=torch.contiguous_format)\n model_inputs[model_input_name] = model_input\n\n # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)\n if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:\n if model_inputs[\"inputs_embeds\"] is not None:\n batch_size, sequence_length, _ = model_inputs[\"inputs_embeds\"].shape\n device = model_inputs[\"inputs_embeds\"].device\n else:\n batch_size, sequence_length = model_inputs[input_ids_key].shape\n device = model_inputs[input_ids_key].device\n\n # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create\n # the 4D causal mask exists, it should be present in the base model (XXXModel class).\n base_model = getattr(self, self.base_model_prefix, None)\n if base_model is None:\n causal_mask_creation_function = getattr(\n self, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n else:\n causal_mask_creation_function = getattr(\n base_model, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n if causal_mask_creation_function is None:\n logger.warning_once(\n f\"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method \"\n \"defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're \"\n \"writing code, see Llama for an example implementation. If you're a user, please report this \"\n \"issue on GitHub.\"\n )\n else:\n attention_mask = causal_mask_creation_function(\n attention_mask,\n sequence_length=sequence_length,\n target_length=past_key_values.get_max_cache_shape(),\n dtype=self.dtype,\n device=device,\n cache_position=cache_position,\n batch_size=batch_size,\n config=self.config,\n past_key_values=past_key_values,\n )\n if attention_mask is not None:\n model_inputs[attention_mask_key] = attention_mask\n\n # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).\n for key, value in kwargs.items():\n if key not in model_inputs:\n model_inputs[key] = value\n\n # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)\n model_inputs.pop(\"labels\", None)\n return model_inputs\n\n def _prepare_model_inputs(\n self,\n inputs: Optional[torch.Tensor] = None,\n bos_token_id: Optional[torch.Tensor] = None,\n model_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:\n \"\"\"\n This function extracts the model-specific `inputs` for generation.\n \"\"\"\n # 1. retrieve all kwargs that are non-None or non-model input related.\n # some encoder-decoder models have different names for model and encoder\n if (\n self.config.is_encoder_decoder\n and hasattr(self, \"encoder\")\n<|next_version|>\n inputs_embeds is not None # Exception 1\n or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3\n ):\n input_ids = input_ids[:, -cache_position.shape[0] :]\n elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the \"else\", a no op, is Exception 2)\n input_ids = input_ids[:, cache_position]\n\n # 3. Prepare base model inputs\n input_ids_key = \"decoder_input_ids\" if self.config.is_encoder_decoder else \"input_ids\"\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.\n if not self.config.is_encoder_decoder:\n if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:\n model_inputs[input_ids_key] = None\n model_inputs[\"inputs_embeds\"] = inputs_embeds\n else:\n # `clone` calls in this function ensure a consistent stride. See #32227\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n model_inputs[\"inputs_embeds\"] = None\n else:\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n\n # 4. Create missing `position_ids` on the fly\n encoder_attention_mask = attention_mask if self.config.is_encoder_decoder else None\n attention_mask = (\n kwargs.pop(\"decoder_attention_mask\", None) if self.config.is_encoder_decoder else attention_mask\n )\n attention_mask_key = \"decoder_attention_mask\" if self.config.is_encoder_decoder else \"attention_mask\"\n position_ids_key = \"decoder_position_ids\" if self.config.is_encoder_decoder else \"position_ids\"\n if (\n attention_mask is not None\n and kwargs.get(position_ids_key) is None\n and position_ids_key in set(inspect.signature(self.forward).parameters.keys())\n ):\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n kwargs[position_ids_key] = position_ids # placed in kwargs for further processing (see below)\n\n # 5. Slice model inputs if it's an input that should have the same length as `input_ids`\n for model_input_name in [\"position_ids\", \"token_type_ids\", \"decoder_position_ids\"]:\n model_input = kwargs.get(model_input_name)\n if model_input is not None:\n if past_key_values is not None:\n current_input_length = (\n model_inputs[\"inputs_embeds\"].shape[1]\n if model_inputs.get(\"inputs_embeds\") is not None\n else model_inputs[input_ids_key].shape[1]\n )\n model_input = model_input[:, -current_input_length:]\n model_input = model_input.clone(memory_format=torch.contiguous_format)\n model_inputs[model_input_name] = model_input\n\n # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)\n if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:\n if model_inputs[\"inputs_embeds\"] is not None:\n batch_size, sequence_length, _ = model_inputs[\"inputs_embeds\"].shape\n device = model_inputs[\"inputs_embeds\"].device\n else:\n batch_size, sequence_length = model_inputs[input_ids_key].shape\n device = model_inputs[input_ids_key].device\n\n # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create\n # the 4D causal mask exists, it should be present in the base model (XXXModel class).\n base_model = getattr(self, self.base_model_prefix, None)\n if base_model is None:\n causal_mask_creation_function = getattr(\n self, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n else:\n causal_mask_creation_function = getattr(\n base_model, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n if causal_mask_creation_function is None:\n logger.warning_once(\n f\"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method \"\n \"defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're \"\n \"writing code, see Llama for an example implementation. If you're a user, please report this \"\n \"issue on GitHub.\"\n )\n else:\n attention_mask = causal_mask_creation_function(\n attention_mask,\n sequence_length=sequence_length,\n target_length=past_key_values.get_max_cache_shape(),\n dtype=self.dtype,\n device=device,\n cache_position=cache_position,\n batch_size=batch_size,\n config=self.config,\n past_key_values=past_key_values,\n )\n if attention_mask is not None:\n model_inputs[attention_mask_key] = attention_mask\n\n if encoder_attention_mask is not None:\n model_inputs[\"attention_mask\"] = encoder_attention_mask\n\n # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).\n for key, value in kwargs.items():\n if key not in model_inputs:\n model_inputs[key] = value\n\n # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)\n model_inputs.pop(\"labels\", None)\n return model_inputs\n\n def _prepare_model_inputs(\n self,\n inputs: Optional[torch.Tensor] = None,\n bos_token_id: Optional[torch.Tensor] = None,\n model_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:\n \"\"\"\n This function extracts the model-specific `inputs` for generation.\n \"\"\"\n # 1. retrieve all kwargs that are non-None or non-model input related.\n # some encoder-decoder models have different names for model and encoder\n if (\n self.config.is_encoder_decoder\n and hasattr(self, \"encoder\")\n", "current_contents": " inputs_embeds is not None # Exception 1\n or (is_torchdynamo_compiling() or cache_position[-1] >= input_ids.shape[1]) # Exception 3\n ):\n input_ids = input_ids[:, -cache_position.shape[0] :]\n elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the \"else\", a no op, is Exception 2)\n input_ids = input_ids[:, cache_position]\n\n # 3. Prepare base model inputs\n input_ids_key = \"decoder_input_ids\" if self.config.is_encoder_decoder else \"input_ids\"\n # if `inputs_embeds` are passed, we only want to use them in the 1st generation step for every prompt.\n if not self.config.is_encoder_decoder:\n if inputs_embeds is not None and len(cache_position) == inputs_embeds.shape[1]:\n model_inputs[input_ids_key] = None\n model_inputs[\"inputs_embeds\"] = inputs_embeds\n else:\n # `clone` calls in this function ensure a consistent stride. See #32227\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n model_inputs[\"inputs_embeds\"] = None\n else:\n model_inputs[input_ids_key] = input_ids.clone(memory_format=torch.contiguous_format)\n\n # 4. Create missing `position_ids` on the fly\n encoder_attention_mask = attention_mask if self.config.is_encoder_decoder else None\n attention_mask = (\n kwargs.pop(\"decoder_attention_mask\", None) if self.config.is_encoder_decoder else attention_mask\n )\n attention_mask_key = \"decoder_attention_mask\" if self.config.is_encoder_decoder else \"attention_mask\"\n position_ids_key = \"decoder_position_ids\" if self.config.is_encoder_decoder else \"position_ids\"\n if (\n attention_mask is not None\n and kwargs.get(position_ids_key) is None\n and position_ids_key in set(inspect.signature(self.forward).parameters.keys())\n ):\n position_ids = attention_mask.long().cumsum(-1) - 1\n position_ids.masked_fill_(attention_mask == 0, 1)\n kwargs[position_ids_key] = position_ids # placed in kwargs for further processing (see below)\n\n # 5. Slice model inputs if it's an input that should have the same length as `input_ids`\n for model_input_name in [\"position_ids\", \"token_type_ids\", \"decoder_position_ids\"]:\n model_input = kwargs.get(model_input_name)\n if model_input is not None:\n if past_key_values is not None:\n current_input_length = (\n model_inputs[\"inputs_embeds\"].shape[1]\n if model_inputs.get(\"inputs_embeds\") is not None\n else model_inputs[input_ids_key].shape[1]\n )\n model_input = model_input[:, -current_input_length:]\n model_input = model_input.clone(memory_format=torch.contiguous_format)\n model_inputs[model_input_name] = model_input\n\n # 6. Create 4D attention mask is we are using a `StaticCache` (important for performant compiled forward pass)\n if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:\n if model_inputs[\"inputs_embeds\"] is not None:\n batch_size, sequence_length, _ = model_inputs[\"inputs_embeds\"].shape\n device = model_inputs[\"inputs_embeds\"].device\n else:\n batch_size, sequence_length = model_inputs[input_ids_key].shape\n device = model_inputs[input_ids_key].device\n\n # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create\n # the 4D causal mask exists, it should be present in the base model (XXXModel class).\n base_model = getattr(self, self.base_model_prefix, None)\n if base_model is None:\n causal_mask_creation_function = getattr(\n self, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n else:\n causal_mask_creation_function = getattr(\n base_model, \"_prepare_4d_causal_attention_mask_with_cache_position\", None\n )\n if causal_mask_creation_function is None:\n logger.warning_once(\n f\"{self.__class__.__name__} has no `_prepare_4d_causal_attention_mask_with_cache_position` method \"\n \"defined in its base modeling class. Compiled forward passes will be sub-optimal. If you're \"\n \"writing code, see Llama for an example implementation. If you're a user, please report this \"\n \"issue on GitHub.\"\n )\n else:\n attention_mask = causal_mask_creation_function(\n attention_mask,\n sequence_length=sequence_length,\n target_length=past_key_values.get_max_cache_shape(),\n dtype=self.dtype,\n device=device,\n cache_position=cache_position,\n batch_size=batch_size,\n config=self.config,\n past_key_values=past_key_values,\n )\n if attention_mask is not None:\n model_inputs[attention_mask_key] = attention_mask\n\n # 7. Forward ALL kwargs that are uninitialized (e.g. `use_cache`).\n for key, value in kwargs.items():\n if key not in model_inputs:\n model_inputs[key] = value\n\n # 8. Remove unexpected `generate` inputs (TODO @joao: fix trainer and examples)\n model_inputs.pop(\"labels\", None)\n return model_inputs\n\n def _prepare_model_inputs(\n self,\n inputs: Optional[torch.Tensor] = None,\n bos_token_id: Optional[torch.Tensor] = None,\n model_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n ) -> Tuple[torch.Tensor, Optional[str], Dict[str, torch.Tensor]]:\n \"\"\"\n This function extracts the model-specific `inputs` for generation.\n \"\"\"\n # 1. retrieve all kwargs that are non-None or non-model input related.\n # some encoder-decoder models have different names for model and encoder\n if (\n self.config.is_encoder_decoder\n and hasattr(self, \"encoder\")"} {"commit": "cb586a39994ae4ca9dfca2993b8e298897fd4e5b", "message": "Add require_read_token to fp8 tests (#36189)", "old_file": "tests/quantization/finegrained_fp8/test_fp8.py", "new_file": "tests/quantization/finegrained_fp8/test_fp8.py", "status": "M", "old_contents": "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport gc\nimport tempfile\nimport unittest\n\nfrom transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM\nfrom transformers.testing_utils import (\n require_accelerate,\n require_torch_gpu,\n require_torch_multi_gpu,\n slow,\n)\nfrom transformers.utils import is_accelerate_available, is_torch_available\n\n\nif is_torch_available():\n import torch\n\nif is_accelerate_available():\n from accelerate import init_empty_weights\n\n\n@require_torch_gpu\nclass FineGrainedFP8ConfigTest(unittest.TestCase):\n def test_to_dict(self):\n \"\"\"\n Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object\n \"\"\"\n quantization_config = FineGrainedFP8Config()\n config_to_dict = quantization_config.to_dict()\n\n for key in config_to_dict:\n self.assertEqual(getattr(quantization_config, key), config_to_dict[key])\n\n def test_from_dict(self):\n \"\"\"\n Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict\n \"\"\"\n dict = {\"modules_to_not_convert\": [\"lm_head.weight\"], \"quant_method\": \"fp8\"}\n quantization_config = FineGrainedFP8Config.from_dict(dict)\n\n self.assertEqual(dict[\"modules_to_not_convert\"], quantization_config.modules_to_not_convert)\n self.assertEqual(dict[\"quant_method\"], quantization_config.quant_method)\n\n\n@slow\n@require_accelerate\n@require_torch_gpu\nclass FP8QuantizerTest(unittest.TestCase):\n model_name = \"meta-llama/Llama-3.2-1B\"\n input_text = \"Once upon a time\"\n max_new_tokens = 10\n EXPECTED_OUTPUT = \"Once upon a time, there was a man who was very rich.\"\n device_map = \"cuda\"\n offload_device_map = {\n \"model.embed_tokens\": 0,\n \"model.layers.0\": 0,\n \"model.layers.1\": 0,\n \"model.layers.2\": 0,\n \"model.layers.3\": 0,\n \"model.layers.4\": 0,\n \"model.layers.5\": 0,\n \"model.layers.6\": 0,\n \"model.layers.7\": \"cpu\",\n \"model.layers.8\": \"cpu\",\n \"model.layers.9\": \"cpu\",\n \"model.layers.10\": \"cpu\",\n \"model.layers.11\": \"cpu\",\n \"model.layers.12\": \"cpu\",\n \"model.layers.13\": \"cpu\",\n \"model.layers.14\": \"cpu\",", "new_contents": "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport gc\nimport tempfile\nimport unittest\n\nfrom transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM\nfrom transformers.testing_utils import (\n require_accelerate,\n require_read_token,\n require_torch_gpu,\n require_torch_multi_gpu,\n slow,\n)\nfrom transformers.utils import is_accelerate_available, is_torch_available\n\n\nif is_torch_available():\n import torch\n\nif is_accelerate_available():\n from accelerate import init_empty_weights\n\n\n@require_torch_gpu\nclass FineGrainedFP8ConfigTest(unittest.TestCase):\n def test_to_dict(self):\n \"\"\"\n Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object\n \"\"\"\n quantization_config = FineGrainedFP8Config()\n config_to_dict = quantization_config.to_dict()\n\n for key in config_to_dict:\n self.assertEqual(getattr(quantization_config, key), config_to_dict[key])\n\n def test_from_dict(self):\n \"\"\"\n Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict\n \"\"\"\n dict = {\"modules_to_not_convert\": [\"lm_head.weight\"], \"quant_method\": \"fp8\"}\n quantization_config = FineGrainedFP8Config.from_dict(dict)\n\n self.assertEqual(dict[\"modules_to_not_convert\"], quantization_config.modules_to_not_convert)\n self.assertEqual(dict[\"quant_method\"], quantization_config.quant_method)\n\n\n@slow\n@require_accelerate\n@require_read_token\n@require_torch_gpu\nclass FP8QuantizerTest(unittest.TestCase):\n model_name = \"meta-llama/Llama-3.2-1B\"\n input_text = \"Once upon a time\"\n max_new_tokens = 10\n EXPECTED_OUTPUT = \"Once upon a time, there was a man who was very rich.\"\n device_map = \"cuda\"\n offload_device_map = {\n \"model.embed_tokens\": 0,\n \"model.layers.0\": 0,\n \"model.layers.1\": 0,\n \"model.layers.2\": 0,\n \"model.layers.3\": 0,\n \"model.layers.4\": 0,\n \"model.layers.5\": 0,\n \"model.layers.6\": 0,\n \"model.layers.7\": \"cpu\",\n \"model.layers.8\": \"cpu\",\n \"model.layers.9\": \"cpu\",\n \"model.layers.10\": \"cpu\",\n \"model.layers.11\": \"cpu\",\n \"model.layers.12\": \"cpu\",\n \"model.layers.13\": \"cpu\",\n \"model.layers.14\": \"cpu\",", "text": "<|original_code|>\n# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport gc\nimport tempfile\nimport unittest\n\nfrom transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM\nfrom transformers.testing_utils import (\n require_accelerate,\n require_torch_gpu,\n require_torch_multi_gpu,\n slow,\n)\nfrom transformers.utils import is_accelerate_available, is_torch_available\n\n\nif is_torch_available():\n import torch\n\nif is_accelerate_available():\n from accelerate import init_empty_weights\n\n\n@require_torch_gpu\nclass FineGrainedFP8ConfigTest(unittest.TestCase):\n def test_to_dict(self):\n \"\"\"\n Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object\n \"\"\"\n quantization_config = FineGrainedFP8Config()\n config_to_dict = quantization_config.to_dict()\n\n for key in config_to_dict:\n self.assertEqual(getattr(quantization_config, key), config_to_dict[key])\n\n def test_from_dict(self):\n \"\"\"\n Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict\n \"\"\"\n dict = {\"modules_to_not_convert\": [\"lm_head.weight\"], \"quant_method\": \"fp8\"}\n quantization_config = FineGrainedFP8Config.from_dict(dict)\n\n self.assertEqual(dict[\"modules_to_not_convert\"], quantization_config.modules_to_not_convert)\n self.assertEqual(dict[\"quant_method\"], quantization_config.quant_method)\n\n\n@slow\n@require_accelerate\n@require_torch_gpu\nclass FP8QuantizerTest(unittest.TestCase):\n model_name = \"meta-llama/Llama-3.2-1B\"\n input_text = \"Once upon a time\"\n max_new_tokens = 10\n EXPECTED_OUTPUT = \"Once upon a time, there was a man who was very rich.\"\n device_map = \"cuda\"\n offload_device_map = {\n \"model.embed_tokens\": 0,\n \"model.layers.0\": 0,\n \"model.layers.1\": 0,\n \"model.layers.2\": 0,\n \"model.layers.3\": 0,\n \"model.layers.4\": 0,\n \"model.layers.5\": 0,\n \"model.layers.6\": 0,\n \"model.layers.7\": \"cpu\",\n \"model.layers.8\": \"cpu\",\n \"model.layers.9\": \"cpu\",\n \"model.layers.10\": \"cpu\",\n \"model.layers.11\": \"cpu\",\n \"model.layers.12\": \"cpu\",\n \"model.layers.13\": \"cpu\",\n \"model.layers.14\": \"cpu\",\n<|edits_diff|>\n--- tests/quantization/finegrained_fp8/test_fp8.py\n+++ tests/quantization/finegrained_fp8/test_fp8.py\n@@ -20,6 +20,7 @@\n from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM\n from transformers.testing_utils import (\n require_accelerate,\n+ require_read_token,\n require_torch_gpu,\n require_torch_multi_gpu,\n slow,\n<|current_version|>\n# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport gc\nimport tempfile\nimport unittest\n\nfrom transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM\nfrom transformers.testing_utils import (\n require_accelerate,\n require_read_token,\n require_torch_gpu,\n require_torch_multi_gpu,\n slow,\n)\nfrom transformers.utils import is_accelerate_available, is_torch_available\n\n\nif is_torch_available():\n import torch\n\nif is_accelerate_available():\n from accelerate import init_empty_weights\n\n\n@require_torch_gpu\nclass FineGrainedFP8ConfigTest(unittest.TestCase):\n def test_to_dict(self):\n \"\"\"\n Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object\n \"\"\"\n quantization_config = FineGrainedFP8Config()\n config_to_dict = quantization_config.to_dict()\n\n for key in config_to_dict:\n self.assertEqual(getattr(quantization_config, key), config_to_dict[key])\n\n def test_from_dict(self):\n \"\"\"\n Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict\n \"\"\"\n dict = {\"modules_to_not_convert\": [\"lm_head.weight\"], \"quant_method\": \"fp8\"}\n quantization_config = FineGrainedFP8Config.from_dict(dict)\n\n self.assertEqual(dict[\"modules_to_not_convert\"], quantization_config.modules_to_not_convert)\n self.assertEqual(dict[\"quant_method\"], quantization_config.quant_method)\n\n\n@slow\n@require_accelerate\n@require_torch_gpu\nclass FP8QuantizerTest(unittest.TestCase):\n model_name = \"meta-llama/Llama-3.2-1B\"\n input_text = \"Once upon a time\"\n max_new_tokens = 10\n EXPECTED_OUTPUT = \"Once upon a time, there was a man who was very rich.\"\n device_map = \"cuda\"\n offload_device_map = {\n \"model.embed_tokens\": 0,\n \"model.layers.0\": 0,\n \"model.layers.1\": 0,\n \"model.layers.2\": 0,\n \"model.layers.3\": 0,\n \"model.layers.4\": 0,\n \"model.layers.5\": 0,\n \"model.layers.6\": 0,\n \"model.layers.7\": \"cpu\",\n \"model.layers.8\": \"cpu\",\n \"model.layers.9\": \"cpu\",\n \"model.layers.10\": \"cpu\",\n \"model.layers.11\": \"cpu\",\n \"model.layers.12\": \"cpu\",\n \"model.layers.13\": \"cpu\",\n \"model.layers.14\": \"cpu\",\n<|next_version|>\n# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport gc\nimport tempfile\nimport unittest\n\nfrom transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM\nfrom transformers.testing_utils import (\n require_accelerate,\n require_read_token,\n require_torch_gpu,\n require_torch_multi_gpu,\n slow,\n)\nfrom transformers.utils import is_accelerate_available, is_torch_available\n\n\nif is_torch_available():\n import torch\n\nif is_accelerate_available():\n from accelerate import init_empty_weights\n\n\n@require_torch_gpu\nclass FineGrainedFP8ConfigTest(unittest.TestCase):\n def test_to_dict(self):\n \"\"\"\n Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object\n \"\"\"\n quantization_config = FineGrainedFP8Config()\n config_to_dict = quantization_config.to_dict()\n\n for key in config_to_dict:\n self.assertEqual(getattr(quantization_config, key), config_to_dict[key])\n\n def test_from_dict(self):\n \"\"\"\n Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict\n \"\"\"\n dict = {\"modules_to_not_convert\": [\"lm_head.weight\"], \"quant_method\": \"fp8\"}\n quantization_config = FineGrainedFP8Config.from_dict(dict)\n\n self.assertEqual(dict[\"modules_to_not_convert\"], quantization_config.modules_to_not_convert)\n self.assertEqual(dict[\"quant_method\"], quantization_config.quant_method)\n\n\n@slow\n@require_accelerate\n@require_read_token\n@require_torch_gpu\nclass FP8QuantizerTest(unittest.TestCase):\n model_name = \"meta-llama/Llama-3.2-1B\"\n input_text = \"Once upon a time\"\n max_new_tokens = 10\n EXPECTED_OUTPUT = \"Once upon a time, there was a man who was very rich.\"\n device_map = \"cuda\"\n offload_device_map = {\n \"model.embed_tokens\": 0,\n \"model.layers.0\": 0,\n \"model.layers.1\": 0,\n \"model.layers.2\": 0,\n \"model.layers.3\": 0,\n \"model.layers.4\": 0,\n \"model.layers.5\": 0,\n \"model.layers.6\": 0,\n \"model.layers.7\": \"cpu\",\n \"model.layers.8\": \"cpu\",\n \"model.layers.9\": \"cpu\",\n \"model.layers.10\": \"cpu\",\n \"model.layers.11\": \"cpu\",\n \"model.layers.12\": \"cpu\",\n \"model.layers.13\": \"cpu\",\n \"model.layers.14\": \"cpu\",\n", "current_contents": "# coding=utf-8\n# Copyright 2025 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport gc\nimport tempfile\nimport unittest\n\nfrom transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM\nfrom transformers.testing_utils import (\n require_accelerate,\n require_read_token,\n require_torch_gpu,\n require_torch_multi_gpu,\n slow,\n)\nfrom transformers.utils import is_accelerate_available, is_torch_available\n\n\nif is_torch_available():\n import torch\n\nif is_accelerate_available():\n from accelerate import init_empty_weights\n\n\n@require_torch_gpu\nclass FineGrainedFP8ConfigTest(unittest.TestCase):\n def test_to_dict(self):\n \"\"\"\n Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object\n \"\"\"\n quantization_config = FineGrainedFP8Config()\n config_to_dict = quantization_config.to_dict()\n\n for key in config_to_dict:\n self.assertEqual(getattr(quantization_config, key), config_to_dict[key])\n\n def test_from_dict(self):\n \"\"\"\n Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict\n \"\"\"\n dict = {\"modules_to_not_convert\": [\"lm_head.weight\"], \"quant_method\": \"fp8\"}\n quantization_config = FineGrainedFP8Config.from_dict(dict)\n\n self.assertEqual(dict[\"modules_to_not_convert\"], quantization_config.modules_to_not_convert)\n self.assertEqual(dict[\"quant_method\"], quantization_config.quant_method)\n\n\n@slow\n@require_accelerate\n@require_torch_gpu\nclass FP8QuantizerTest(unittest.TestCase):\n model_name = \"meta-llama/Llama-3.2-1B\"\n input_text = \"Once upon a time\"\n max_new_tokens = 10\n EXPECTED_OUTPUT = \"Once upon a time, there was a man who was very rich.\"\n device_map = \"cuda\"\n offload_device_map = {\n \"model.embed_tokens\": 0,\n \"model.layers.0\": 0,\n \"model.layers.1\": 0,\n \"model.layers.2\": 0,\n \"model.layers.3\": 0,\n \"model.layers.4\": 0,\n \"model.layers.5\": 0,\n \"model.layers.6\": 0,\n \"model.layers.7\": \"cpu\",\n \"model.layers.8\": \"cpu\",\n \"model.layers.9\": \"cpu\",\n \"model.layers.10\": \"cpu\",\n \"model.layers.11\": \"cpu\",\n \"model.layers.12\": \"cpu\",\n \"model.layers.13\": \"cpu\",\n \"model.layers.14\": \"cpu\","} {"commit": "845b0a261601d845d87a186163c303d98100d0b9", "message": "Efficient Inference Kernel for SpQR (#34976)", "old_file": "src/transformers/quantizers/auto.py", "new_file": "src/transformers/quantizers/auto.py", "status": "M", "old_contents": "# See the License for the specific language governing permissions and\n# limitations under the License.\nimport warnings\nfrom typing import Dict, Optional, Union\n\nfrom ..models.auto.configuration_auto import AutoConfig\nfrom ..utils import logging\nfrom ..utils.quantization_config import (\n AqlmConfig,\n AwqConfig,\n BitNetConfig,\n BitsAndBytesConfig,\n CompressedTensorsConfig,\n EetqConfig,\n FbgemmFp8Config,\n FineGrainedFP8Config,\n GPTQConfig,\n HiggsConfig,\n HqqConfig,\n QuantizationConfigMixin,\n QuantizationMethod,\n QuantoConfig,\n TorchAoConfig,\n VptqConfig,\n)\nfrom .quantizer_aqlm import AqlmHfQuantizer\nfrom .quantizer_awq import AwqQuantizer\nfrom .quantizer_bitnet import BitNetHfQuantizer\nfrom .quantizer_bnb_4bit import Bnb4BitHfQuantizer\nfrom .quantizer_bnb_8bit import Bnb8BitHfQuantizer\nfrom .quantizer_compressed_tensors import CompressedTensorsHfQuantizer\nfrom .quantizer_eetq import EetqHfQuantizer\nfrom .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer\nfrom .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer\nfrom .quantizer_gptq import GptqHfQuantizer\nfrom .quantizer_higgs import HiggsHfQuantizer\nfrom .quantizer_hqq import HqqHfQuantizer\nfrom .quantizer_quanto import QuantoHfQuantizer\nfrom .quantizer_torchao import TorchAoHfQuantizer\nfrom .quantizer_vptq import VptqHfQuantizer\n\n\nAUTO_QUANTIZER_MAPPING = {\n \"awq\": AwqQuantizer,\n \"bitsandbytes_4bit\": Bnb4BitHfQuantizer,\n \"bitsandbytes_8bit\": Bnb8BitHfQuantizer,\n \"gptq\": GptqHfQuantizer,\n \"aqlm\": AqlmHfQuantizer,\n \"quanto\": QuantoHfQuantizer,\n \"eetq\": EetqHfQuantizer,\n \"higgs\": HiggsHfQuantizer,\n \"hqq\": HqqHfQuantizer,\n \"compressed-tensors\": CompressedTensorsHfQuantizer,\n \"fbgemm_fp8\": FbgemmFp8HfQuantizer,\n \"torchao\": TorchAoHfQuantizer,\n \"bitnet\": BitNetHfQuantizer,\n \"vptq\": VptqHfQuantizer,\n \"fp8\": FineGrainedFP8HfQuantizer,\n}\n\nAUTO_QUANTIZATION_CONFIG_MAPPING = {\n \"awq\": AwqConfig,\n \"bitsandbytes_4bit\": BitsAndBytesConfig,\n \"bitsandbytes_8bit\": BitsAndBytesConfig,\n \"eetq\": EetqConfig,\n \"gptq\": GPTQConfig,\n \"aqlm\": AqlmConfig,\n \"quanto\": QuantoConfig,\n \"hqq\": HqqConfig,\n \"compressed-tensors\": CompressedTensorsConfig,\n \"fbgemm_fp8\": FbgemmFp8Config,\n \"higgs\": HiggsConfig,\n \"torchao\": TorchAoConfig,\n \"bitnet\": BitNetConfig,\n \"vptq\": VptqConfig,\n \"fp8\": FineGrainedFP8Config,\n}\n\nlogger = logging.get_logger(__name__)\n\n\nclass AutoQuantizationConfig:\n \"\"\"\n The Auto-HF quantization config class that takes care of automatically dispatching to the correct\n quantization config given a quantization config stored in a dictionary.\n \"\"\"\n\n @classmethod\n def from_dict(cls, quantization_config_dict: Dict):\n quant_method = quantization_config_dict.get(\"quant_method\", None)\n # We need a special care for bnb models to make sure everything is BC ..\n if quantization_config_dict.get(\"load_in_8bit\", False) or quantization_config_dict.get(\"load_in_4bit\", False):\n suffix = \"_4bit\" if quantization_config_dict.get(\"load_in_4bit\", False) else \"_8bit\"\n quant_method = QuantizationMethod.BITS_AND_BYTES + suffix\n elif quant_method is None:\n raise ValueError(\n \"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized\"\n )\n", "new_contents": "# See the License for the specific language governing permissions and\n# limitations under the License.\nimport warnings\nfrom typing import Dict, Optional, Union\n\nfrom ..models.auto.configuration_auto import AutoConfig\nfrom ..utils import logging\nfrom ..utils.quantization_config import (\n AqlmConfig,\n AwqConfig,\n BitNetConfig,\n BitsAndBytesConfig,\n CompressedTensorsConfig,\n EetqConfig,\n FbgemmFp8Config,\n FineGrainedFP8Config,\n GPTQConfig,\n HiggsConfig,\n HqqConfig,\n QuantizationConfigMixin,\n QuantizationMethod,\n QuantoConfig,\n SpQRConfig,\n TorchAoConfig,\n VptqConfig,\n)\nfrom .quantizer_aqlm import AqlmHfQuantizer\nfrom .quantizer_awq import AwqQuantizer\nfrom .quantizer_bitnet import BitNetHfQuantizer\nfrom .quantizer_bnb_4bit import Bnb4BitHfQuantizer\nfrom .quantizer_bnb_8bit import Bnb8BitHfQuantizer\nfrom .quantizer_compressed_tensors import CompressedTensorsHfQuantizer\nfrom .quantizer_eetq import EetqHfQuantizer\nfrom .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer\nfrom .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer\nfrom .quantizer_gptq import GptqHfQuantizer\nfrom .quantizer_higgs import HiggsHfQuantizer\nfrom .quantizer_hqq import HqqHfQuantizer\nfrom .quantizer_quanto import QuantoHfQuantizer\nfrom .quantizer_spqr import SpQRHfQuantizer\nfrom .quantizer_torchao import TorchAoHfQuantizer\nfrom .quantizer_vptq import VptqHfQuantizer\n\n\nAUTO_QUANTIZER_MAPPING = {\n \"awq\": AwqQuantizer,\n \"bitsandbytes_4bit\": Bnb4BitHfQuantizer,\n \"bitsandbytes_8bit\": Bnb8BitHfQuantizer,\n \"gptq\": GptqHfQuantizer,\n \"aqlm\": AqlmHfQuantizer,\n \"quanto\": QuantoHfQuantizer,\n \"eetq\": EetqHfQuantizer,\n \"higgs\": HiggsHfQuantizer,\n \"hqq\": HqqHfQuantizer,\n \"compressed-tensors\": CompressedTensorsHfQuantizer,\n \"fbgemm_fp8\": FbgemmFp8HfQuantizer,\n \"torchao\": TorchAoHfQuantizer,\n \"bitnet\": BitNetHfQuantizer,\n \"vptq\": VptqHfQuantizer,\n \"spqr\": SpQRHfQuantizer,\n \"fp8\": FineGrainedFP8HfQuantizer,\n}\n\nAUTO_QUANTIZATION_CONFIG_MAPPING = {\n \"awq\": AwqConfig,\n \"bitsandbytes_4bit\": BitsAndBytesConfig,\n \"bitsandbytes_8bit\": BitsAndBytesConfig,\n \"eetq\": EetqConfig,\n \"gptq\": GPTQConfig,\n \"aqlm\": AqlmConfig,\n \"quanto\": QuantoConfig,\n \"hqq\": HqqConfig,\n \"compressed-tensors\": CompressedTensorsConfig,\n \"fbgemm_fp8\": FbgemmFp8Config,\n \"higgs\": HiggsConfig,\n \"torchao\": TorchAoConfig,\n \"bitnet\": BitNetConfig,\n \"vptq\": VptqConfig,\n \"spqr\": SpQRConfig,\n \"fp8\": FineGrainedFP8Config,\n}\n\nlogger = logging.get_logger(__name__)\n\n\nclass AutoQuantizationConfig:\n \"\"\"\n The Auto-HF quantization config class that takes care of automatically dispatching to the correct\n quantization config given a quantization config stored in a dictionary.\n \"\"\"\n\n @classmethod\n def from_dict(cls, quantization_config_dict: Dict):\n quant_method = quantization_config_dict.get(\"quant_method\", None)\n # We need a special care for bnb models to make sure everything is BC ..\n if quantization_config_dict.get(\"load_in_8bit\", False) or quantization_config_dict.get(\"load_in_4bit\", False):\n suffix = \"_4bit\" if quantization_config_dict.get(\"load_in_4bit\", False) else \"_8bit\"\n quant_method = QuantizationMethod.BITS_AND_BYTES + suffix\n elif quant_method is None:\n raise ValueError(\n \"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized\"\n )\n", "text": "<|original_code|>\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport warnings\nfrom typing import Dict, Optional, Union\n\nfrom ..models.auto.configuration_auto import AutoConfig\nfrom ..utils import logging\nfrom ..utils.quantization_config import (\n AqlmConfig,\n AwqConfig,\n BitNetConfig,\n BitsAndBytesConfig,\n CompressedTensorsConfig,\n EetqConfig,\n FbgemmFp8Config,\n FineGrainedFP8Config,\n GPTQConfig,\n HiggsConfig,\n HqqConfig,\n QuantizationConfigMixin,\n QuantizationMethod,\n QuantoConfig,\n TorchAoConfig,\n VptqConfig,\n)\nfrom .quantizer_aqlm import AqlmHfQuantizer\nfrom .quantizer_awq import AwqQuantizer\nfrom .quantizer_bitnet import BitNetHfQuantizer\nfrom .quantizer_bnb_4bit import Bnb4BitHfQuantizer\nfrom .quantizer_bnb_8bit import Bnb8BitHfQuantizer\nfrom .quantizer_compressed_tensors import CompressedTensorsHfQuantizer\nfrom .quantizer_eetq import EetqHfQuantizer\nfrom .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer\nfrom .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer\nfrom .quantizer_gptq import GptqHfQuantizer\nfrom .quantizer_higgs import HiggsHfQuantizer\nfrom .quantizer_hqq import HqqHfQuantizer\nfrom .quantizer_quanto import QuantoHfQuantizer\nfrom .quantizer_torchao import TorchAoHfQuantizer\nfrom .quantizer_vptq import VptqHfQuantizer\n\n\nAUTO_QUANTIZER_MAPPING = {\n \"awq\": AwqQuantizer,\n \"bitsandbytes_4bit\": Bnb4BitHfQuantizer,\n \"bitsandbytes_8bit\": Bnb8BitHfQuantizer,\n \"gptq\": GptqHfQuantizer,\n \"aqlm\": AqlmHfQuantizer,\n \"quanto\": QuantoHfQuantizer,\n \"eetq\": EetqHfQuantizer,\n \"higgs\": HiggsHfQuantizer,\n \"hqq\": HqqHfQuantizer,\n \"compressed-tensors\": CompressedTensorsHfQuantizer,\n \"fbgemm_fp8\": FbgemmFp8HfQuantizer,\n \"torchao\": TorchAoHfQuantizer,\n \"bitnet\": BitNetHfQuantizer,\n \"vptq\": VptqHfQuantizer,\n \"fp8\": FineGrainedFP8HfQuantizer,\n}\n\nAUTO_QUANTIZATION_CONFIG_MAPPING = {\n \"awq\": AwqConfig,\n \"bitsandbytes_4bit\": BitsAndBytesConfig,\n \"bitsandbytes_8bit\": BitsAndBytesConfig,\n \"eetq\": EetqConfig,\n \"gptq\": GPTQConfig,\n \"aqlm\": AqlmConfig,\n \"quanto\": QuantoConfig,\n \"hqq\": HqqConfig,\n \"compressed-tensors\": CompressedTensorsConfig,\n \"fbgemm_fp8\": FbgemmFp8Config,\n \"higgs\": HiggsConfig,\n \"torchao\": TorchAoConfig,\n \"bitnet\": BitNetConfig,\n \"vptq\": VptqConfig,\n \"fp8\": FineGrainedFP8Config,\n}\n\nlogger = logging.get_logger(__name__)\n\n\nclass AutoQuantizationConfig:\n \"\"\"\n The Auto-HF quantization config class that takes care of automatically dispatching to the correct\n quantization config given a quantization config stored in a dictionary.\n \"\"\"\n\n @classmethod\n def from_dict(cls, quantization_config_dict: Dict):\n quant_method = quantization_config_dict.get(\"quant_method\", None)\n # We need a special care for bnb models to make sure everything is BC ..\n if quantization_config_dict.get(\"load_in_8bit\", False) or quantization_config_dict.get(\"load_in_4bit\", False):\n suffix = \"_4bit\" if quantization_config_dict.get(\"load_in_4bit\", False) else \"_8bit\"\n quant_method = QuantizationMethod.BITS_AND_BYTES + suffix\n elif quant_method is None:\n raise ValueError(\n \"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized\"\n )\n\n<|edits_diff|>\n--- src/transformers/quantizers/auto.py\n+++ src/transformers/quantizers/auto.py\n@@ -20,6 +20,7 @@\n QuantizationConfigMixin,\n QuantizationMethod,\n QuantoConfig,\n+ SpQRConfig,\n TorchAoConfig,\n VptqConfig,\n )\n@@ -36,6 +37,7 @@\n from .quantizer_higgs import HiggsHfQuantizer\n from .quantizer_hqq import HqqHfQuantizer\n from .quantizer_quanto import QuantoHfQuantizer\n+from .quantizer_spqr import SpQRHfQuantizer\n from .quantizer_torchao import TorchAoHfQuantizer\n from .quantizer_vptq import VptqHfQuantizer\n \n@@ -55,6 +57,7 @@\n \"torchao\": TorchAoHfQuantizer,\n \"bitnet\": BitNetHfQuantizer,\n \"vptq\": VptqHfQuantizer,\n+ \"spqr\": SpQRHfQuantizer,\n \"fp8\": FineGrainedFP8HfQuantizer,\n }\n \n<|current_version|>\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport warnings\nfrom typing import Dict, Optional, Union\n\nfrom ..models.auto.configuration_auto import AutoConfig\nfrom ..utils import logging\nfrom ..utils.quantization_config import (\n AqlmConfig,\n AwqConfig,\n BitNetConfig,\n BitsAndBytesConfig,\n CompressedTensorsConfig,\n EetqConfig,\n FbgemmFp8Config,\n FineGrainedFP8Config,\n GPTQConfig,\n HiggsConfig,\n HqqConfig,\n QuantizationConfigMixin,\n QuantizationMethod,\n QuantoConfig,\n SpQRConfig,\n TorchAoConfig,\n VptqConfig,\n)\nfrom .quantizer_aqlm import AqlmHfQuantizer\nfrom .quantizer_awq import AwqQuantizer\nfrom .quantizer_bitnet import BitNetHfQuantizer\nfrom .quantizer_bnb_4bit import Bnb4BitHfQuantizer\nfrom .quantizer_bnb_8bit import Bnb8BitHfQuantizer\nfrom .quantizer_compressed_tensors import CompressedTensorsHfQuantizer\nfrom .quantizer_eetq import EetqHfQuantizer\nfrom .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer\nfrom .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer\nfrom .quantizer_gptq import GptqHfQuantizer\nfrom .quantizer_higgs import HiggsHfQuantizer\nfrom .quantizer_hqq import HqqHfQuantizer\nfrom .quantizer_quanto import QuantoHfQuantizer\nfrom .quantizer_spqr import SpQRHfQuantizer\nfrom .quantizer_torchao import TorchAoHfQuantizer\nfrom .quantizer_vptq import VptqHfQuantizer\n\n\nAUTO_QUANTIZER_MAPPING = {\n \"awq\": AwqQuantizer,\n \"bitsandbytes_4bit\": Bnb4BitHfQuantizer,\n \"bitsandbytes_8bit\": Bnb8BitHfQuantizer,\n \"gptq\": GptqHfQuantizer,\n \"aqlm\": AqlmHfQuantizer,\n \"quanto\": QuantoHfQuantizer,\n \"eetq\": EetqHfQuantizer,\n \"higgs\": HiggsHfQuantizer,\n \"hqq\": HqqHfQuantizer,\n \"compressed-tensors\": CompressedTensorsHfQuantizer,\n \"fbgemm_fp8\": FbgemmFp8HfQuantizer,\n \"torchao\": TorchAoHfQuantizer,\n \"bitnet\": BitNetHfQuantizer,\n \"vptq\": VptqHfQuantizer,\n \"spqr\": SpQRHfQuantizer,\n \"fp8\": FineGrainedFP8HfQuantizer,\n}\n\nAUTO_QUANTIZATION_CONFIG_MAPPING = {\n \"awq\": AwqConfig,\n \"bitsandbytes_4bit\": BitsAndBytesConfig,\n \"bitsandbytes_8bit\": BitsAndBytesConfig,\n \"eetq\": EetqConfig,\n \"gptq\": GPTQConfig,\n \"aqlm\": AqlmConfig,\n \"quanto\": QuantoConfig,\n \"hqq\": HqqConfig,\n \"compressed-tensors\": CompressedTensorsConfig,\n \"fbgemm_fp8\": FbgemmFp8Config,\n \"higgs\": HiggsConfig,\n \"torchao\": TorchAoConfig,\n \"bitnet\": BitNetConfig,\n \"vptq\": VptqConfig,\n \"fp8\": FineGrainedFP8Config,\n}\n\nlogger = logging.get_logger(__name__)\n\n\nclass AutoQuantizationConfig:\n \"\"\"\n The Auto-HF quantization config class that takes care of automatically dispatching to the correct\n quantization config given a quantization config stored in a dictionary.\n \"\"\"\n\n @classmethod\n def from_dict(cls, quantization_config_dict: Dict):\n quant_method = quantization_config_dict.get(\"quant_method\", None)\n # We need a special care for bnb models to make sure everything is BC ..\n if quantization_config_dict.get(\"load_in_8bit\", False) or quantization_config_dict.get(\"load_in_4bit\", False):\n suffix = \"_4bit\" if quantization_config_dict.get(\"load_in_4bit\", False) else \"_8bit\"\n quant_method = QuantizationMethod.BITS_AND_BYTES + suffix\n elif quant_method is None:\n raise ValueError(\n \"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized\"\n )\n\n<|next_version|>\n# See the License for the specific language governing permissions and\n# limitations under the License.\nimport warnings\nfrom typing import Dict, Optional, Union\n\nfrom ..models.auto.configuration_auto import AutoConfig\nfrom ..utils import logging\nfrom ..utils.quantization_config import (\n AqlmConfig,\n AwqConfig,\n BitNetConfig,\n BitsAndBytesConfig,\n CompressedTensorsConfig,\n EetqConfig,\n FbgemmFp8Config,\n FineGrainedFP8Config,\n GPTQConfig,\n HiggsConfig,\n HqqConfig,\n QuantizationConfigMixin,\n QuantizationMethod,\n QuantoConfig,\n SpQRConfig,\n TorchAoConfig,\n VptqConfig,\n)\nfrom .quantizer_aqlm import AqlmHfQuantizer\nfrom .quantizer_awq import AwqQuantizer\nfrom .quantizer_bitnet import BitNetHfQuantizer\nfrom .quantizer_bnb_4bit import Bnb4BitHfQuantizer\nfrom .quantizer_bnb_8bit import Bnb8BitHfQuantizer\nfrom .quantizer_compressed_tensors import CompressedTensorsHfQuantizer\nfrom .quantizer_eetq import EetqHfQuantizer\nfrom .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer\nfrom .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer\nfrom .quantizer_gptq import GptqHfQuantizer\nfrom .quantizer_higgs import HiggsHfQuantizer\nfrom .quantizer_hqq import HqqHfQuantizer\nfrom .quantizer_quanto import QuantoHfQuantizer\nfrom .quantizer_spqr import SpQRHfQuantizer\nfrom .quantizer_torchao import TorchAoHfQuantizer\nfrom .quantizer_vptq import VptqHfQuantizer\n\n\nAUTO_QUANTIZER_MAPPING = {\n \"awq\": AwqQuantizer,\n \"bitsandbytes_4bit\": Bnb4BitHfQuantizer,\n \"bitsandbytes_8bit\": Bnb8BitHfQuantizer,\n \"gptq\": GptqHfQuantizer,\n \"aqlm\": AqlmHfQuantizer,\n \"quanto\": QuantoHfQuantizer,\n \"eetq\": EetqHfQuantizer,\n \"higgs\": HiggsHfQuantizer,\n \"hqq\": HqqHfQuantizer,\n \"compressed-tensors\": CompressedTensorsHfQuantizer,\n \"fbgemm_fp8\": FbgemmFp8HfQuantizer,\n \"torchao\": TorchAoHfQuantizer,\n \"bitnet\": BitNetHfQuantizer,\n \"vptq\": VptqHfQuantizer,\n \"spqr\": SpQRHfQuantizer,\n \"fp8\": FineGrainedFP8HfQuantizer,\n}\n\nAUTO_QUANTIZATION_CONFIG_MAPPING = {\n \"awq\": AwqConfig,\n \"bitsandbytes_4bit\": BitsAndBytesConfig,\n \"bitsandbytes_8bit\": BitsAndBytesConfig,\n \"eetq\": EetqConfig,\n \"gptq\": GPTQConfig,\n \"aqlm\": AqlmConfig,\n \"quanto\": QuantoConfig,\n \"hqq\": HqqConfig,\n \"compressed-tensors\": CompressedTensorsConfig,\n \"fbgemm_fp8\": FbgemmFp8Config,\n \"higgs\": HiggsConfig,\n \"torchao\": TorchAoConfig,\n \"bitnet\": BitNetConfig,\n \"vptq\": VptqConfig,\n \"spqr\": SpQRConfig,\n \"fp8\": FineGrainedFP8Config,\n}\n\nlogger = logging.get_logger(__name__)\n\n\nclass AutoQuantizationConfig:\n \"\"\"\n The Auto-HF quantization config class that takes care of automatically dispatching to the correct\n quantization config given a quantization config stored in a dictionary.\n \"\"\"\n\n @classmethod\n def from_dict(cls, quantization_config_dict: Dict):\n quant_method = quantization_config_dict.get(\"quant_method\", None)\n # We need a special care for bnb models to make sure everything is BC ..\n if quantization_config_dict.get(\"load_in_8bit\", False) or quantization_config_dict.get(\"load_in_4bit\", False):\n suffix = \"_4bit\" if quantization_config_dict.get(\"load_in_4bit\", False) else \"_8bit\"\n quant_method = QuantizationMethod.BITS_AND_BYTES + suffix\n elif quant_method is None:\n raise ValueError(\n \"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized\"\n )\n\n", "current_contents": "# See the License for the specific language governing permissions and\n# limitations under the License.\nimport warnings\nfrom typing import Dict, Optional, Union\n\nfrom ..models.auto.configuration_auto import AutoConfig\nfrom ..utils import logging\nfrom ..utils.quantization_config import (\n AqlmConfig,\n AwqConfig,\n BitNetConfig,\n BitsAndBytesConfig,\n CompressedTensorsConfig,\n EetqConfig,\n FbgemmFp8Config,\n FineGrainedFP8Config,\n GPTQConfig,\n HiggsConfig,\n HqqConfig,\n QuantizationConfigMixin,\n QuantizationMethod,\n QuantoConfig,\n SpQRConfig,\n TorchAoConfig,\n VptqConfig,\n)\nfrom .quantizer_aqlm import AqlmHfQuantizer\nfrom .quantizer_awq import AwqQuantizer\nfrom .quantizer_bitnet import BitNetHfQuantizer\nfrom .quantizer_bnb_4bit import Bnb4BitHfQuantizer\nfrom .quantizer_bnb_8bit import Bnb8BitHfQuantizer\nfrom .quantizer_compressed_tensors import CompressedTensorsHfQuantizer\nfrom .quantizer_eetq import EetqHfQuantizer\nfrom .quantizer_fbgemm_fp8 import FbgemmFp8HfQuantizer\nfrom .quantizer_finegrained_fp8 import FineGrainedFP8HfQuantizer\nfrom .quantizer_gptq import GptqHfQuantizer\nfrom .quantizer_higgs import HiggsHfQuantizer\nfrom .quantizer_hqq import HqqHfQuantizer\nfrom .quantizer_quanto import QuantoHfQuantizer\nfrom .quantizer_spqr import SpQRHfQuantizer\nfrom .quantizer_torchao import TorchAoHfQuantizer\nfrom .quantizer_vptq import VptqHfQuantizer\n\n\nAUTO_QUANTIZER_MAPPING = {\n \"awq\": AwqQuantizer,\n \"bitsandbytes_4bit\": Bnb4BitHfQuantizer,\n \"bitsandbytes_8bit\": Bnb8BitHfQuantizer,\n \"gptq\": GptqHfQuantizer,\n \"aqlm\": AqlmHfQuantizer,\n \"quanto\": QuantoHfQuantizer,\n \"eetq\": EetqHfQuantizer,\n \"higgs\": HiggsHfQuantizer,\n \"hqq\": HqqHfQuantizer,\n \"compressed-tensors\": CompressedTensorsHfQuantizer,\n \"fbgemm_fp8\": FbgemmFp8HfQuantizer,\n \"torchao\": TorchAoHfQuantizer,\n \"bitnet\": BitNetHfQuantizer,\n \"vptq\": VptqHfQuantizer,\n \"spqr\": SpQRHfQuantizer,\n \"fp8\": FineGrainedFP8HfQuantizer,\n}\n\nAUTO_QUANTIZATION_CONFIG_MAPPING = {\n \"awq\": AwqConfig,\n \"bitsandbytes_4bit\": BitsAndBytesConfig,\n \"bitsandbytes_8bit\": BitsAndBytesConfig,\n \"eetq\": EetqConfig,\n \"gptq\": GPTQConfig,\n \"aqlm\": AqlmConfig,\n \"quanto\": QuantoConfig,\n \"hqq\": HqqConfig,\n \"compressed-tensors\": CompressedTensorsConfig,\n \"fbgemm_fp8\": FbgemmFp8Config,\n \"higgs\": HiggsConfig,\n \"torchao\": TorchAoConfig,\n \"bitnet\": BitNetConfig,\n \"vptq\": VptqConfig,\n \"fp8\": FineGrainedFP8Config,\n}\n\nlogger = logging.get_logger(__name__)\n\n\nclass AutoQuantizationConfig:\n \"\"\"\n The Auto-HF quantization config class that takes care of automatically dispatching to the correct\n quantization config given a quantization config stored in a dictionary.\n \"\"\"\n\n @classmethod\n def from_dict(cls, quantization_config_dict: Dict):\n quant_method = quantization_config_dict.get(\"quant_method\", None)\n # We need a special care for bnb models to make sure everything is BC ..\n if quantization_config_dict.get(\"load_in_8bit\", False) or quantization_config_dict.get(\"load_in_4bit\", False):\n suffix = \"_4bit\" if quantization_config_dict.get(\"load_in_4bit\", False) else \"_8bit\"\n quant_method = QuantizationMethod.BITS_AND_BYTES + suffix\n elif quant_method is None:\n raise ValueError(\n \"The model's quantization config from the arguments has no `quant_method` attribute. Make sure that the model has been correctly quantized\"\n )\n"} {"commit": "fa56dcc2ab748a2d98218b4918742e25454ef0d2", "message": "Refactoring of ImageProcessorFast (#35069)", "old_file": "src/transformers/commands/transformers_cli.py", "new_file": "src/transformers/commands/transformers_cli.py", "status": "M", "old_contents": "#!/usr/bin/env python\n# Copyright 2020 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom transformers import HfArgumentParser\n\nfrom .add_new_model_like import AddNewModelLikeCommand\nfrom .chat import ChatCommand\nfrom .convert import ConvertCommand\nfrom .download import DownloadCommand\nfrom .env import EnvironmentCommand\nfrom .lfs import LfsCommands\nfrom .run import RunCommand\nfrom .serving import ServeCommand\nfrom .user import UserCommands\n\n\ndef main():\n parser = HfArgumentParser(prog=\"Transformers CLI tool\", usage=\"transformers-cli []\")\n commands_parser = parser.add_subparsers(help=\"transformers-cli command helpers\")\n\n # Register commands\n ChatCommand.register_subcommand(commands_parser)\n ConvertCommand.register_subcommand(commands_parser)\n DownloadCommand.register_subcommand(commands_parser)\n EnvironmentCommand.register_subcommand(commands_parser)\n RunCommand.register_subcommand(commands_parser)\n ServeCommand.register_subcommand(commands_parser)\n UserCommands.register_subcommand(commands_parser)\n AddNewModelLikeCommand.register_subcommand(commands_parser)\n LfsCommands.register_subcommand(commands_parser)\n\n # Let's go\n args = parser.parse_args()\n\n if not hasattr(args, \"func\"):\n parser.print_help()\n exit(1)\n\n # Run\n service = args.func(args)\n service.run()\n\n\nif __name__ == \"__main__\":\n main()\n", "new_contents": "#!/usr/bin/env python\n# Copyright 2020 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom transformers import HfArgumentParser\n\nfrom .add_fast_image_processor import AddFastImageProcessorCommand\nfrom .add_new_model_like import AddNewModelLikeCommand\nfrom .chat import ChatCommand\nfrom .convert import ConvertCommand\nfrom .download import DownloadCommand\nfrom .env import EnvironmentCommand\nfrom .lfs import LfsCommands\nfrom .run import RunCommand\nfrom .serving import ServeCommand\nfrom .user import UserCommands\n\n\ndef main():\n parser = HfArgumentParser(prog=\"Transformers CLI tool\", usage=\"transformers-cli []\")\n commands_parser = parser.add_subparsers(help=\"transformers-cli command helpers\")\n\n # Register commands\n ChatCommand.register_subcommand(commands_parser)\n ConvertCommand.register_subcommand(commands_parser)\n DownloadCommand.register_subcommand(commands_parser)\n EnvironmentCommand.register_subcommand(commands_parser)\n RunCommand.register_subcommand(commands_parser)\n ServeCommand.register_subcommand(commands_parser)\n UserCommands.register_subcommand(commands_parser)\n AddNewModelLikeCommand.register_subcommand(commands_parser)\n LfsCommands.register_subcommand(commands_parser)\n AddFastImageProcessorCommand.register_subcommand(commands_parser)\n\n # Let's go\n args = parser.parse_args()\n\n if not hasattr(args, \"func\"):\n parser.print_help()\n exit(1)\n\n # Run\n service = args.func(args)\n service.run()\n\n\nif __name__ == \"__main__\":\n main()\n", "text": "<|original_code|>\n#!/usr/bin/env python\n# Copyright 2020 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom transformers import HfArgumentParser\n\nfrom .add_new_model_like import AddNewModelLikeCommand\nfrom .chat import ChatCommand\nfrom .convert import ConvertCommand\nfrom .download import DownloadCommand\nfrom .env import EnvironmentCommand\nfrom .lfs import LfsCommands\nfrom .run import RunCommand\nfrom .serving import ServeCommand\nfrom .user import UserCommands\n\n\ndef main():\n parser = HfArgumentParser(prog=\"Transformers CLI tool\", usage=\"transformers-cli []\")\n commands_parser = parser.add_subparsers(help=\"transformers-cli command helpers\")\n\n # Register commands\n ChatCommand.register_subcommand(commands_parser)\n ConvertCommand.register_subcommand(commands_parser)\n DownloadCommand.register_subcommand(commands_parser)\n EnvironmentCommand.register_subcommand(commands_parser)\n RunCommand.register_subcommand(commands_parser)\n ServeCommand.register_subcommand(commands_parser)\n UserCommands.register_subcommand(commands_parser)\n AddNewModelLikeCommand.register_subcommand(commands_parser)\n LfsCommands.register_subcommand(commands_parser)\n\n # Let's go\n args = parser.parse_args()\n\n if not hasattr(args, \"func\"):\n parser.print_help()\n exit(1)\n\n # Run\n service = args.func(args)\n service.run()\n\n\nif __name__ == \"__main__\":\n main()\n\n<|edits_diff|>\n--- src/transformers/commands/transformers_cli.py\n+++ src/transformers/commands/transformers_cli.py\n@@ -15,6 +15,7 @@\n \n from transformers import HfArgumentParser\n \n+from .add_fast_image_processor import AddFastImageProcessorCommand\n from .add_new_model_like import AddNewModelLikeCommand\n from .chat import ChatCommand\n from .convert import ConvertCommand\n<|current_version|>\n#!/usr/bin/env python\n# Copyright 2020 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom transformers import HfArgumentParser\n\nfrom .add_fast_image_processor import AddFastImageProcessorCommand\nfrom .add_new_model_like import AddNewModelLikeCommand\nfrom .chat import ChatCommand\nfrom .convert import ConvertCommand\nfrom .download import DownloadCommand\nfrom .env import EnvironmentCommand\nfrom .lfs import LfsCommands\nfrom .run import RunCommand\nfrom .serving import ServeCommand\nfrom .user import UserCommands\n\n\ndef main():\n parser = HfArgumentParser(prog=\"Transformers CLI tool\", usage=\"transformers-cli []\")\n commands_parser = parser.add_subparsers(help=\"transformers-cli command helpers\")\n\n # Register commands\n ChatCommand.register_subcommand(commands_parser)\n ConvertCommand.register_subcommand(commands_parser)\n DownloadCommand.register_subcommand(commands_parser)\n EnvironmentCommand.register_subcommand(commands_parser)\n RunCommand.register_subcommand(commands_parser)\n ServeCommand.register_subcommand(commands_parser)\n UserCommands.register_subcommand(commands_parser)\n AddNewModelLikeCommand.register_subcommand(commands_parser)\n LfsCommands.register_subcommand(commands_parser)\n\n # Let's go\n args = parser.parse_args()\n\n if not hasattr(args, \"func\"):\n parser.print_help()\n exit(1)\n\n # Run\n service = args.func(args)\n service.run()\n\n\nif __name__ == \"__main__\":\n main()\n\n<|next_version|>\n#!/usr/bin/env python\n# Copyright 2020 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom transformers import HfArgumentParser\n\nfrom .add_fast_image_processor import AddFastImageProcessorCommand\nfrom .add_new_model_like import AddNewModelLikeCommand\nfrom .chat import ChatCommand\nfrom .convert import ConvertCommand\nfrom .download import DownloadCommand\nfrom .env import EnvironmentCommand\nfrom .lfs import LfsCommands\nfrom .run import RunCommand\nfrom .serving import ServeCommand\nfrom .user import UserCommands\n\n\ndef main():\n parser = HfArgumentParser(prog=\"Transformers CLI tool\", usage=\"transformers-cli []\")\n commands_parser = parser.add_subparsers(help=\"transformers-cli command helpers\")\n\n # Register commands\n ChatCommand.register_subcommand(commands_parser)\n ConvertCommand.register_subcommand(commands_parser)\n DownloadCommand.register_subcommand(commands_parser)\n EnvironmentCommand.register_subcommand(commands_parser)\n RunCommand.register_subcommand(commands_parser)\n ServeCommand.register_subcommand(commands_parser)\n UserCommands.register_subcommand(commands_parser)\n AddNewModelLikeCommand.register_subcommand(commands_parser)\n LfsCommands.register_subcommand(commands_parser)\n AddFastImageProcessorCommand.register_subcommand(commands_parser)\n\n # Let's go\n args = parser.parse_args()\n\n if not hasattr(args, \"func\"):\n parser.print_help()\n exit(1)\n\n # Run\n service = args.func(args)\n service.run()\n\n\nif __name__ == \"__main__\":\n main()\n\n", "current_contents": "#!/usr/bin/env python\n# Copyright 2020 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom transformers import HfArgumentParser\n\nfrom .add_fast_image_processor import AddFastImageProcessorCommand\nfrom .add_new_model_like import AddNewModelLikeCommand\nfrom .chat import ChatCommand\nfrom .convert import ConvertCommand\nfrom .download import DownloadCommand\nfrom .env import EnvironmentCommand\nfrom .lfs import LfsCommands\nfrom .run import RunCommand\nfrom .serving import ServeCommand\nfrom .user import UserCommands\n\n\ndef main():\n parser = HfArgumentParser(prog=\"Transformers CLI tool\", usage=\"transformers-cli []\")\n commands_parser = parser.add_subparsers(help=\"transformers-cli command helpers\")\n\n # Register commands\n ChatCommand.register_subcommand(commands_parser)\n ConvertCommand.register_subcommand(commands_parser)\n DownloadCommand.register_subcommand(commands_parser)\n EnvironmentCommand.register_subcommand(commands_parser)\n RunCommand.register_subcommand(commands_parser)\n ServeCommand.register_subcommand(commands_parser)\n UserCommands.register_subcommand(commands_parser)\n AddNewModelLikeCommand.register_subcommand(commands_parser)\n LfsCommands.register_subcommand(commands_parser)\n\n # Let's go\n args = parser.parse_args()\n\n if not hasattr(args, \"func\"):\n parser.print_help()\n exit(1)\n\n # Run\n service = args.func(args)\n service.run()\n\n\nif __name__ == \"__main__\":\n main()\n"} {"commit": "9afb904b158dce9870c987480423bba6f343ca4c", "message": "Refactor (and fix) gpt_neox (#35610)", "old_file": "src/transformers/integrations/flex_attention.py", "new_file": "src/transformers/integrations/flex_attention.py", "status": "M", "old_contents": "from typing import Optional, Tuple\n\nimport torch\n\nfrom ..utils import is_torch_flex_attn_available\n\n\nif is_torch_flex_attn_available():\n from torch.nn.attention.flex_attention import flex_attention\n\n\ndef flex_attention_forward(\n module: torch.nn.Module,\n query: torch.Tensor,\n key: torch.Tensor,\n value: torch.Tensor,\n attention_mask: Optional[torch.Tensor],\n scaling: Optional[float] = None,\n softcap: Optional[float] = None,\n **kwargs,\n) -> Tuple[torch.Tensor, torch.Tensor]:\n causal_mask = attention_mask\n if causal_mask is not None:\n causal_mask = causal_mask[:, :, :, : key.shape[-2]]\n\n def causal_mod(score, b, h, q_idx, kv_idx):\n if softcap is not None:\n score = softcap * torch.tanh(score / softcap)\n if causal_mask is not None:\n score = score + causal_mask[b][0][q_idx][kv_idx]\n return score\n\n attn_output, attention_weights = flex_attention(\n query,\n key,\n value,\n score_mod=causal_mod,\n enable_gqa=True,\n scale=scaling,\n # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.\n # For simplification, we thus always return it as no additional computations are introduced.\n return_lse=True,\n )\n # lse is returned in float32\n attention_weights = attention_weights.to(value.dtype)\n attn_output = attn_output.transpose(1, 2).contiguous()\n\n return attn_output, attention_weights\n", "new_contents": "from typing import Optional, Tuple\n\nimport torch\n\nfrom ..utils import is_torch_flex_attn_available\n\n\nif is_torch_flex_attn_available():\n from torch.nn.attention.flex_attention import flex_attention\n\n\ndef flex_attention_forward(\n module: torch.nn.Module,\n query: torch.Tensor,\n key: torch.Tensor,\n value: torch.Tensor,\n attention_mask: Optional[torch.Tensor],\n scaling: Optional[float] = None,\n softcap: Optional[float] = None,\n head_mask: Optional[torch.Tensor] = None,\n **kwargs,\n) -> Tuple[torch.Tensor, torch.Tensor]:\n causal_mask = attention_mask\n if causal_mask is not None:\n causal_mask = causal_mask[:, :, :, : key.shape[-2]]\n\n def causal_mod(score, b, h, q_idx, kv_idx):\n if softcap is not None:\n score = softcap * torch.tanh(score / softcap)\n if causal_mask is not None:\n score = score + causal_mask[b][0][q_idx][kv_idx]\n if head_mask is not None:\n score = score + head_mask[b][h][0][0]\n return score\n\n attn_output, attention_weights = flex_attention(\n query,\n key,\n value,\n score_mod=causal_mod,\n enable_gqa=True,\n scale=scaling,\n # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.\n # For simplification, we thus always return it as no additional computations are introduced.\n return_lse=True,\n )\n # lse is returned in float32\n attention_weights = attention_weights.to(value.dtype)\n attn_output = attn_output.transpose(1, 2).contiguous()\n\n return attn_output, attention_weights\n", "text": "<|original_code|>\nfrom typing import Optional, Tuple\n\nimport torch\n\nfrom ..utils import is_torch_flex_attn_available\n\n\nif is_torch_flex_attn_available():\n from torch.nn.attention.flex_attention import flex_attention\n\n\ndef flex_attention_forward(\n module: torch.nn.Module,\n query: torch.Tensor,\n key: torch.Tensor,\n value: torch.Tensor,\n attention_mask: Optional[torch.Tensor],\n scaling: Optional[float] = None,\n softcap: Optional[float] = None,\n **kwargs,\n) -> Tuple[torch.Tensor, torch.Tensor]:\n causal_mask = attention_mask\n if causal_mask is not None:\n causal_mask = causal_mask[:, :, :, : key.shape[-2]]\n\n def causal_mod(score, b, h, q_idx, kv_idx):\n if softcap is not None:\n score = softcap * torch.tanh(score / softcap)\n if causal_mask is not None:\n score = score + causal_mask[b][0][q_idx][kv_idx]\n return score\n\n attn_output, attention_weights = flex_attention(\n query,\n key,\n value,\n score_mod=causal_mod,\n enable_gqa=True,\n scale=scaling,\n # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.\n # For simplification, we thus always return it as no additional computations are introduced.\n return_lse=True,\n )\n # lse is returned in float32\n attention_weights = attention_weights.to(value.dtype)\n attn_output = attn_output.transpose(1, 2).contiguous()\n\n return attn_output, attention_weights\n\n<|edits_diff|>\n--- src/transformers/integrations/flex_attention.py\n+++ src/transformers/integrations/flex_attention.py\n@@ -17,6 +17,7 @@\n attention_mask: Optional[torch.Tensor],\n scaling: Optional[float] = None,\n softcap: Optional[float] = None,\n+ head_mask: Optional[torch.Tensor] = None,\n **kwargs,\n ) -> Tuple[torch.Tensor, torch.Tensor]:\n causal_mask = attention_mask\n<|current_version|>\nfrom typing import Optional, Tuple\n\nimport torch\n\nfrom ..utils import is_torch_flex_attn_available\n\n\nif is_torch_flex_attn_available():\n from torch.nn.attention.flex_attention import flex_attention\n\n\ndef flex_attention_forward(\n module: torch.nn.Module,\n query: torch.Tensor,\n key: torch.Tensor,\n value: torch.Tensor,\n attention_mask: Optional[torch.Tensor],\n scaling: Optional[float] = None,\n softcap: Optional[float] = None,\n head_mask: Optional[torch.Tensor] = None,\n **kwargs,\n) -> Tuple[torch.Tensor, torch.Tensor]:\n causal_mask = attention_mask\n if causal_mask is not None:\n causal_mask = causal_mask[:, :, :, : key.shape[-2]]\n\n def causal_mod(score, b, h, q_idx, kv_idx):\n if softcap is not None:\n score = softcap * torch.tanh(score / softcap)\n if causal_mask is not None:\n score = score + causal_mask[b][0][q_idx][kv_idx]\n return score\n\n attn_output, attention_weights = flex_attention(\n query,\n key,\n value,\n score_mod=causal_mod,\n enable_gqa=True,\n scale=scaling,\n # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.\n # For simplification, we thus always return it as no additional computations are introduced.\n return_lse=True,\n )\n # lse is returned in float32\n attention_weights = attention_weights.to(value.dtype)\n attn_output = attn_output.transpose(1, 2).contiguous()\n\n return attn_output, attention_weights\n\n<|next_version|>\nfrom typing import Optional, Tuple\n\nimport torch\n\nfrom ..utils import is_torch_flex_attn_available\n\n\nif is_torch_flex_attn_available():\n from torch.nn.attention.flex_attention import flex_attention\n\n\ndef flex_attention_forward(\n module: torch.nn.Module,\n query: torch.Tensor,\n key: torch.Tensor,\n value: torch.Tensor,\n attention_mask: Optional[torch.Tensor],\n scaling: Optional[float] = None,\n softcap: Optional[float] = None,\n head_mask: Optional[torch.Tensor] = None,\n **kwargs,\n) -> Tuple[torch.Tensor, torch.Tensor]:\n causal_mask = attention_mask\n if causal_mask is not None:\n causal_mask = causal_mask[:, :, :, : key.shape[-2]]\n\n def causal_mod(score, b, h, q_idx, kv_idx):\n if softcap is not None:\n score = softcap * torch.tanh(score / softcap)\n if causal_mask is not None:\n score = score + causal_mask[b][0][q_idx][kv_idx]\n if head_mask is not None:\n score = score + head_mask[b][h][0][0]\n return score\n\n attn_output, attention_weights = flex_attention(\n query,\n key,\n value,\n score_mod=causal_mod,\n enable_gqa=True,\n scale=scaling,\n # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.\n # For simplification, we thus always return it as no additional computations are introduced.\n return_lse=True,\n )\n # lse is returned in float32\n attention_weights = attention_weights.to(value.dtype)\n attn_output = attn_output.transpose(1, 2).contiguous()\n\n return attn_output, attention_weights\n\n", "current_contents": "from typing import Optional, Tuple\n\nimport torch\n\nfrom ..utils import is_torch_flex_attn_available\n\n\nif is_torch_flex_attn_available():\n from torch.nn.attention.flex_attention import flex_attention\n\n\ndef flex_attention_forward(\n module: torch.nn.Module,\n query: torch.Tensor,\n key: torch.Tensor,\n value: torch.Tensor,\n attention_mask: Optional[torch.Tensor],\n scaling: Optional[float] = None,\n softcap: Optional[float] = None,\n head_mask: Optional[torch.Tensor] = None,\n **kwargs,\n) -> Tuple[torch.Tensor, torch.Tensor]:\n causal_mask = attention_mask\n if causal_mask is not None:\n causal_mask = causal_mask[:, :, :, : key.shape[-2]]\n\n def causal_mod(score, b, h, q_idx, kv_idx):\n if softcap is not None:\n score = softcap * torch.tanh(score / softcap)\n if causal_mask is not None:\n score = score + causal_mask[b][0][q_idx][kv_idx]\n return score\n\n attn_output, attention_weights = flex_attention(\n query,\n key,\n value,\n score_mod=causal_mod,\n enable_gqa=True,\n scale=scaling,\n # Last time checked on PyTorch == 2.5.1: Flex Attention always computes the lse regardless.\n # For simplification, we thus always return it as no additional computations are introduced.\n return_lse=True,\n )\n # lse is returned in float32\n attention_weights = attention_weights.to(value.dtype)\n attn_output = attn_output.transpose(1, 2).contiguous()\n\n return attn_output, attention_weights\n"} {"commit": "373e50e9703024eeb09f97945fdefde80acc2619", "message": "Init cache on meta device (#35164)", "old_file": "tests/test_modeling_common.py", "new_file": "tests/test_modeling_common.py", "status": "M", "old_contents": " self.skipTest(reason=\"Model architecture does not support attentions\")\n\n for model_class in self.all_generative_model_classes:\n if not model_class._supports_flash_attn_2:\n self.skipTest(f\"{model_class.__name__} does not support Flash Attention 2\")\n\n config, _ = self.model_tester.prepare_config_and_inputs_for_common()\n # TODO: to change it in the future with other relevant auto classes\n fa2_model = model_class._from_config(\n config, attn_implementation=\"flash_attention_2\", torch_dtype=torch.bfloat16\n ).to(torch_device)\n\n dummy_input = torch.LongTensor([[0, 2, 3, 4], [0, 2, 3, 4]]).to(torch_device)\n dummy_attention_mask = torch.LongTensor([[1, 1, 1, 1], [0, 1, 1, 1]]).to(torch_device)\n\n fa2_correctly_converted = False\n\n for _, module in fa2_model.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n self.assertTrue(fa2_correctly_converted)\n\n _ = fa2_model(input_ids=dummy_input, attention_mask=dummy_attention_mask)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n fa2_model.save_pretrained(tmpdirname)\n\n model_from_pretrained = model_class.from_pretrained(tmpdirname)\n\n self.assertTrue(model_from_pretrained.config._attn_implementation != \"flash_attention_2\")\n\n fa2_correctly_converted = False\n\n for _, module in model_from_pretrained.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n self.assertFalse(fa2_correctly_converted)\n\n def _get_custom_4d_mask_test_data(self):\n # Sequence in which all but the last token is the same\n input_ids = torch.tensor(\n [[10, 11, 12, 13], [10, 11, 12, 14], [10, 11, 12, 15]], device=torch_device, dtype=torch.int64\n )\n position_ids = torch.tensor([[0, 1, 2, 3]] * 3, device=torch_device, dtype=torch.int64)\n\n # Combining common prefix with the unique ending tokens:\n input_ids_shared_prefix = torch.cat([input_ids[0][:-1], input_ids[:, -1]]).unsqueeze(0)\n\n # Creating a 4D mask where each of the last 3 tokens do not attend to each other.\n mask_shared_prefix = torch.tensor(\n [\n [\n [\n [1, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [1, 1, 1, 1, 0, 0],\n [1, 1, 1, 0, 1, 0],\n [1, 1, 1, 0, 0, 1],\n ]", "new_contents": " self.skipTest(reason=\"Model architecture does not support attentions\")\n\n for model_class in self.all_generative_model_classes:\n if not model_class._supports_flash_attn_2:\n self.skipTest(f\"{model_class.__name__} does not support Flash Attention 2\")\n\n config, _ = self.model_tester.prepare_config_and_inputs_for_common()\n # TODO: to change it in the future with other relevant auto classes\n fa2_model = model_class._from_config(\n config, attn_implementation=\"flash_attention_2\", torch_dtype=torch.bfloat16\n ).to(torch_device)\n\n dummy_input = torch.LongTensor([[0, 2, 3, 4], [0, 2, 3, 4]]).to(torch_device)\n dummy_attention_mask = torch.LongTensor([[1, 1, 1, 1], [0, 1, 1, 1]]).to(torch_device)\n\n fa2_correctly_converted = False\n\n for _, module in fa2_model.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n fa2_correctly_converted = (\n fa2_correctly_converted\n if not model_class._supports_flex_attn\n else fa2_model.config._attn_implementation == \"flash_attention_2\"\n )\n self.assertTrue(fa2_correctly_converted)\n\n _ = fa2_model(input_ids=dummy_input, attention_mask=dummy_attention_mask)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n fa2_model.save_pretrained(tmpdirname)\n\n model_from_pretrained = model_class.from_pretrained(tmpdirname)\n\n self.assertTrue(model_from_pretrained.config._attn_implementation != \"flash_attention_2\")\n\n fa2_correctly_converted = False\n\n for _, module in model_from_pretrained.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n fa2_correctly_converted = (\n fa2_correctly_converted\n if not model_class._supports_flex_attn\n else model_from_pretrained.config._attn_implementation == \"flash_attention_2\"\n )\n self.assertFalse(fa2_correctly_converted)\n\n def _get_custom_4d_mask_test_data(self):\n # Sequence in which all but the last token is the same\n input_ids = torch.tensor(\n [[10, 11, 12, 13], [10, 11, 12, 14], [10, 11, 12, 15]], device=torch_device, dtype=torch.int64\n )\n position_ids = torch.tensor([[0, 1, 2, 3]] * 3, device=torch_device, dtype=torch.int64)\n\n # Combining common prefix with the unique ending tokens:\n input_ids_shared_prefix = torch.cat([input_ids[0][:-1], input_ids[:, -1]]).unsqueeze(0)\n\n # Creating a 4D mask where each of the last 3 tokens do not attend to each other.\n mask_shared_prefix = torch.tensor(\n [\n [\n [\n [1, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [1, 1, 1, 1, 0, 0],\n [1, 1, 1, 0, 1, 0],\n [1, 1, 1, 0, 0, 1],\n ]", "text": "<|original_code|>\n self.skipTest(reason=\"Model architecture does not support attentions\")\n\n for model_class in self.all_generative_model_classes:\n if not model_class._supports_flash_attn_2:\n self.skipTest(f\"{model_class.__name__} does not support Flash Attention 2\")\n\n config, _ = self.model_tester.prepare_config_and_inputs_for_common()\n # TODO: to change it in the future with other relevant auto classes\n fa2_model = model_class._from_config(\n config, attn_implementation=\"flash_attention_2\", torch_dtype=torch.bfloat16\n ).to(torch_device)\n\n dummy_input = torch.LongTensor([[0, 2, 3, 4], [0, 2, 3, 4]]).to(torch_device)\n dummy_attention_mask = torch.LongTensor([[1, 1, 1, 1], [0, 1, 1, 1]]).to(torch_device)\n\n fa2_correctly_converted = False\n\n for _, module in fa2_model.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n self.assertTrue(fa2_correctly_converted)\n\n _ = fa2_model(input_ids=dummy_input, attention_mask=dummy_attention_mask)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n fa2_model.save_pretrained(tmpdirname)\n\n model_from_pretrained = model_class.from_pretrained(tmpdirname)\n\n self.assertTrue(model_from_pretrained.config._attn_implementation != \"flash_attention_2\")\n\n fa2_correctly_converted = False\n\n for _, module in model_from_pretrained.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n self.assertFalse(fa2_correctly_converted)\n\n def _get_custom_4d_mask_test_data(self):\n # Sequence in which all but the last token is the same\n input_ids = torch.tensor(\n [[10, 11, 12, 13], [10, 11, 12, 14], [10, 11, 12, 15]], device=torch_device, dtype=torch.int64\n )\n position_ids = torch.tensor([[0, 1, 2, 3]] * 3, device=torch_device, dtype=torch.int64)\n\n # Combining common prefix with the unique ending tokens:\n input_ids_shared_prefix = torch.cat([input_ids[0][:-1], input_ids[:, -1]]).unsqueeze(0)\n\n # Creating a 4D mask where each of the last 3 tokens do not attend to each other.\n mask_shared_prefix = torch.tensor(\n [\n [\n [\n [1, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [1, 1, 1, 1, 0, 0],\n [1, 1, 1, 0, 1, 0],\n [1, 1, 1, 0, 0, 1],\n ]\n<|edits_diff|>\n--- tests/test_modeling_common.py\n+++ tests/test_modeling_common.py\n@@ -20,6 +20,11 @@\n fa2_correctly_converted = True\n break\n \n+ fa2_correctly_converted = (\n+ fa2_correctly_converted\n+ if not model_class._supports_flex_attn\n+ else fa2_model.config._attn_implementation == \"flash_attention_2\"\n+ )\n self.assertTrue(fa2_correctly_converted)\n \n _ = fa2_model(input_ids=dummy_input, attention_mask=dummy_attention_mask)\n<|current_version|>\n self.skipTest(reason=\"Model architecture does not support attentions\")\n\n for model_class in self.all_generative_model_classes:\n if not model_class._supports_flash_attn_2:\n self.skipTest(f\"{model_class.__name__} does not support Flash Attention 2\")\n\n config, _ = self.model_tester.prepare_config_and_inputs_for_common()\n # TODO: to change it in the future with other relevant auto classes\n fa2_model = model_class._from_config(\n config, attn_implementation=\"flash_attention_2\", torch_dtype=torch.bfloat16\n ).to(torch_device)\n\n dummy_input = torch.LongTensor([[0, 2, 3, 4], [0, 2, 3, 4]]).to(torch_device)\n dummy_attention_mask = torch.LongTensor([[1, 1, 1, 1], [0, 1, 1, 1]]).to(torch_device)\n\n fa2_correctly_converted = False\n\n for _, module in fa2_model.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n fa2_correctly_converted = (\n fa2_correctly_converted\n if not model_class._supports_flex_attn\n else fa2_model.config._attn_implementation == \"flash_attention_2\"\n )\n self.assertTrue(fa2_correctly_converted)\n\n _ = fa2_model(input_ids=dummy_input, attention_mask=dummy_attention_mask)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n fa2_model.save_pretrained(tmpdirname)\n\n model_from_pretrained = model_class.from_pretrained(tmpdirname)\n\n self.assertTrue(model_from_pretrained.config._attn_implementation != \"flash_attention_2\")\n\n fa2_correctly_converted = False\n\n for _, module in model_from_pretrained.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n self.assertFalse(fa2_correctly_converted)\n\n def _get_custom_4d_mask_test_data(self):\n # Sequence in which all but the last token is the same\n input_ids = torch.tensor(\n [[10, 11, 12, 13], [10, 11, 12, 14], [10, 11, 12, 15]], device=torch_device, dtype=torch.int64\n )\n position_ids = torch.tensor([[0, 1, 2, 3]] * 3, device=torch_device, dtype=torch.int64)\n\n # Combining common prefix with the unique ending tokens:\n input_ids_shared_prefix = torch.cat([input_ids[0][:-1], input_ids[:, -1]]).unsqueeze(0)\n\n # Creating a 4D mask where each of the last 3 tokens do not attend to each other.\n mask_shared_prefix = torch.tensor(\n [\n [\n [\n [1, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [1, 1, 1, 1, 0, 0],\n [1, 1, 1, 0, 1, 0],\n [1, 1, 1, 0, 0, 1],\n ]\n<|next_version|>\n self.skipTest(reason=\"Model architecture does not support attentions\")\n\n for model_class in self.all_generative_model_classes:\n if not model_class._supports_flash_attn_2:\n self.skipTest(f\"{model_class.__name__} does not support Flash Attention 2\")\n\n config, _ = self.model_tester.prepare_config_and_inputs_for_common()\n # TODO: to change it in the future with other relevant auto classes\n fa2_model = model_class._from_config(\n config, attn_implementation=\"flash_attention_2\", torch_dtype=torch.bfloat16\n ).to(torch_device)\n\n dummy_input = torch.LongTensor([[0, 2, 3, 4], [0, 2, 3, 4]]).to(torch_device)\n dummy_attention_mask = torch.LongTensor([[1, 1, 1, 1], [0, 1, 1, 1]]).to(torch_device)\n\n fa2_correctly_converted = False\n\n for _, module in fa2_model.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n fa2_correctly_converted = (\n fa2_correctly_converted\n if not model_class._supports_flex_attn\n else fa2_model.config._attn_implementation == \"flash_attention_2\"\n )\n self.assertTrue(fa2_correctly_converted)\n\n _ = fa2_model(input_ids=dummy_input, attention_mask=dummy_attention_mask)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n fa2_model.save_pretrained(tmpdirname)\n\n model_from_pretrained = model_class.from_pretrained(tmpdirname)\n\n self.assertTrue(model_from_pretrained.config._attn_implementation != \"flash_attention_2\")\n\n fa2_correctly_converted = False\n\n for _, module in model_from_pretrained.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n fa2_correctly_converted = (\n fa2_correctly_converted\n if not model_class._supports_flex_attn\n else model_from_pretrained.config._attn_implementation == \"flash_attention_2\"\n )\n self.assertFalse(fa2_correctly_converted)\n\n def _get_custom_4d_mask_test_data(self):\n # Sequence in which all but the last token is the same\n input_ids = torch.tensor(\n [[10, 11, 12, 13], [10, 11, 12, 14], [10, 11, 12, 15]], device=torch_device, dtype=torch.int64\n )\n position_ids = torch.tensor([[0, 1, 2, 3]] * 3, device=torch_device, dtype=torch.int64)\n\n # Combining common prefix with the unique ending tokens:\n input_ids_shared_prefix = torch.cat([input_ids[0][:-1], input_ids[:, -1]]).unsqueeze(0)\n\n # Creating a 4D mask where each of the last 3 tokens do not attend to each other.\n mask_shared_prefix = torch.tensor(\n [\n [\n [\n [1, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [1, 1, 1, 1, 0, 0],\n [1, 1, 1, 0, 1, 0],\n [1, 1, 1, 0, 0, 1],\n ]\n", "current_contents": " self.skipTest(reason=\"Model architecture does not support attentions\")\n\n for model_class in self.all_generative_model_classes:\n if not model_class._supports_flash_attn_2:\n self.skipTest(f\"{model_class.__name__} does not support Flash Attention 2\")\n\n config, _ = self.model_tester.prepare_config_and_inputs_for_common()\n # TODO: to change it in the future with other relevant auto classes\n fa2_model = model_class._from_config(\n config, attn_implementation=\"flash_attention_2\", torch_dtype=torch.bfloat16\n ).to(torch_device)\n\n dummy_input = torch.LongTensor([[0, 2, 3, 4], [0, 2, 3, 4]]).to(torch_device)\n dummy_attention_mask = torch.LongTensor([[1, 1, 1, 1], [0, 1, 1, 1]]).to(torch_device)\n\n fa2_correctly_converted = False\n\n for _, module in fa2_model.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n fa2_correctly_converted = (\n fa2_correctly_converted\n if not model_class._supports_flex_attn\n else fa2_model.config._attn_implementation == \"flash_attention_2\"\n )\n self.assertTrue(fa2_correctly_converted)\n\n _ = fa2_model(input_ids=dummy_input, attention_mask=dummy_attention_mask)\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n fa2_model.save_pretrained(tmpdirname)\n\n model_from_pretrained = model_class.from_pretrained(tmpdirname)\n\n self.assertTrue(model_from_pretrained.config._attn_implementation != \"flash_attention_2\")\n\n fa2_correctly_converted = False\n\n for _, module in model_from_pretrained.named_modules():\n if \"FlashAttention\" in module.__class__.__name__:\n fa2_correctly_converted = True\n break\n\n self.assertFalse(fa2_correctly_converted)\n\n def _get_custom_4d_mask_test_data(self):\n # Sequence in which all but the last token is the same\n input_ids = torch.tensor(\n [[10, 11, 12, 13], [10, 11, 12, 14], [10, 11, 12, 15]], device=torch_device, dtype=torch.int64\n )\n position_ids = torch.tensor([[0, 1, 2, 3]] * 3, device=torch_device, dtype=torch.int64)\n\n # Combining common prefix with the unique ending tokens:\n input_ids_shared_prefix = torch.cat([input_ids[0][:-1], input_ids[:, -1]]).unsqueeze(0)\n\n # Creating a 4D mask where each of the last 3 tokens do not attend to each other.\n mask_shared_prefix = torch.tensor(\n [\n [\n [\n [1, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0],\n [1, 1, 1, 0, 0, 0],\n [1, 1, 1, 1, 0, 0],\n [1, 1, 1, 0, 1, 0],\n [1, 1, 1, 0, 0, 1],\n ]"} {"commit": "abe57b6f17f91acb5adab28b40d0cbc85b497b5f", "message": "Add SuperGlue model (#29886)", "old_file": "tests/models/superpoint/test_image_processing_superpoint.py", "new_file": "tests/models/superpoint/test_image_processing_superpoint.py", "status": "M", "old_contents": "\n\nif is_torch_available():\n import torch\n\n from transformers.models.superpoint.modeling_superpoint import SuperPointKeypointDescriptionOutput\n\nif is_vision_available():\n from transformers import SuperPointImageProcessor\n\n\nclass SuperPointImageProcessingTester:\n def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n ):\n size = size if size is not None else {\"height\": 480, \"width\": 640}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n\n def prepare_image_processor_dict(self):\n return {\n \"do_resize\": self.do_resize,\n \"size\": self.size,\n }\n\n def expected_output_image_shape(self, images):\n return self.num_channels, self.size[\"height\"], self.size[\"width\"]\n\n def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):\n return prepare_image_inputs(\n batch_size=self.batch_size,\n num_channels=self.num_channels,\n min_resolution=self.min_resolution,\n max_resolution=self.max_resolution,\n equal_resolution=equal_resolution,\n numpify=numpify,\n torchify=torchify,\n )\n\n def prepare_keypoint_detection_output(self, pixel_values):\n max_number_keypoints = 50\n batch_size = len(pixel_values)\n mask = torch.zeros((batch_size, max_number_keypoints))\n keypoints = torch.zeros((batch_size, max_number_keypoints, 2))\n scores = torch.zeros((batch_size, max_number_keypoints))\n descriptors = torch.zeros((batch_size, max_number_keypoints, 16))\n for i in range(batch_size):\n random_number_keypoints = np.random.randint(0, max_number_keypoints)\n mask[i, :random_number_keypoints] = 1\n keypoints[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 2))\n scores[i, :random_number_keypoints] = torch.rand((random_number_keypoints,))\n descriptors[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 16))\n return SuperPointKeypointDescriptionOutput(\n loss=None, keypoints=keypoints, scores=scores, descriptors=descriptors, mask=mask, hidden_states=None\n )\n\n\n@require_torch\n@require_vision\nclass SuperPointImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):\n image_processing_class = SuperPointImageProcessor if is_vision_available() else None\n\n def setUp(self) -> None:\n super().setUp()\n self.image_processor_tester = SuperPointImageProcessingTester(self)\n\n @property\n def image_processor_dict(self):\n return self.image_processor_tester.prepare_image_processor_dict()\n\n def test_image_processing(self):\n image_processing = self.image_processing_class(**self.image_processor_dict)\n self.assertTrue(hasattr(image_processing, \"do_resize\"))\n self.assertTrue(hasattr(image_processing, \"size\"))\n self.assertTrue(hasattr(image_processing, \"do_rescale\"))\n self.assertTrue(hasattr(image_processing, \"rescale_factor\"))\n\n def test_image_processor_from_dict_with_kwargs(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n self.assertEqual(image_processor.size, {\"height\": 480, \"width\": 640})\n\n image_processor = self.image_processing_class.from_dict(\n self.image_processor_dict, size={\"height\": 42, \"width\": 42}\n )\n self.assertEqual(image_processor.size, {\"height\": 42, \"width\": 42})\n\n @unittest.skip(reason=\"SuperPointImageProcessor is always supposed to return a grayscaled image\")\n def test_call_numpy_4_channels(self):\n pass\n\n def test_input_image_properly_converted_to_grayscale(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n image_inputs = self.image_processor_tester.prepare_image_inputs()\n pre_processed_images = image_processor.preprocess(image_inputs)\n for image in pre_processed_images[\"pixel_values\"]:\n self.assertTrue(np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...]))\n\n @require_torch\n def test_post_processing_keypoint_detection(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)", "new_contents": "\n\nif is_torch_available():\n import torch\n\n from transformers.models.superpoint.modeling_superpoint import SuperPointKeypointDescriptionOutput\n\nif is_vision_available():\n from transformers import SuperPointImageProcessor\n\n\nclass SuperPointImageProcessingTester:\n def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n do_grayscale=True,\n ):\n size = size if size is not None else {\"height\": 480, \"width\": 640}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.do_grayscale = do_grayscale\n\n def prepare_image_processor_dict(self):\n return {\n \"do_resize\": self.do_resize,\n \"size\": self.size,\n \"do_grayscale\": self.do_grayscale,\n }\n\n def expected_output_image_shape(self, images):\n return self.num_channels, self.size[\"height\"], self.size[\"width\"]\n\n def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):\n return prepare_image_inputs(\n batch_size=self.batch_size,\n num_channels=self.num_channels,\n min_resolution=self.min_resolution,\n max_resolution=self.max_resolution,\n equal_resolution=equal_resolution,\n numpify=numpify,\n torchify=torchify,\n )\n\n def prepare_keypoint_detection_output(self, pixel_values):\n max_number_keypoints = 50\n batch_size = len(pixel_values)\n mask = torch.zeros((batch_size, max_number_keypoints))\n keypoints = torch.zeros((batch_size, max_number_keypoints, 2))\n scores = torch.zeros((batch_size, max_number_keypoints))\n descriptors = torch.zeros((batch_size, max_number_keypoints, 16))\n for i in range(batch_size):\n random_number_keypoints = np.random.randint(0, max_number_keypoints)\n mask[i, :random_number_keypoints] = 1\n keypoints[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 2))\n scores[i, :random_number_keypoints] = torch.rand((random_number_keypoints,))\n descriptors[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 16))\n return SuperPointKeypointDescriptionOutput(\n loss=None, keypoints=keypoints, scores=scores, descriptors=descriptors, mask=mask, hidden_states=None\n )\n\n\n@require_torch\n@require_vision\nclass SuperPointImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):\n image_processing_class = SuperPointImageProcessor if is_vision_available() else None\n\n def setUp(self) -> None:\n super().setUp()\n self.image_processor_tester = SuperPointImageProcessingTester(self)\n\n @property\n def image_processor_dict(self):\n return self.image_processor_tester.prepare_image_processor_dict()\n\n def test_image_processing(self):\n image_processing = self.image_processing_class(**self.image_processor_dict)\n self.assertTrue(hasattr(image_processing, \"do_resize\"))\n self.assertTrue(hasattr(image_processing, \"size\"))\n self.assertTrue(hasattr(image_processing, \"do_rescale\"))\n self.assertTrue(hasattr(image_processing, \"rescale_factor\"))\n self.assertTrue(hasattr(image_processing, \"do_grayscale\"))\n\n def test_image_processor_from_dict_with_kwargs(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n self.assertEqual(image_processor.size, {\"height\": 480, \"width\": 640})\n\n image_processor = self.image_processing_class.from_dict(\n self.image_processor_dict, size={\"height\": 42, \"width\": 42}\n )\n self.assertEqual(image_processor.size, {\"height\": 42, \"width\": 42})\n\n @unittest.skip(reason=\"SuperPointImageProcessor is always supposed to return a grayscaled image\")\n def test_call_numpy_4_channels(self):\n pass\n\n def test_input_image_properly_converted_to_grayscale(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n image_inputs = self.image_processor_tester.prepare_image_inputs()\n pre_processed_images = image_processor.preprocess(image_inputs)\n for image in pre_processed_images[\"pixel_values\"]:\n self.assertTrue(np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...]))\n\n @require_torch\n def test_post_processing_keypoint_detection(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)", "text": "<|original_code|>\n\n\nif is_torch_available():\n import torch\n\n from transformers.models.superpoint.modeling_superpoint import SuperPointKeypointDescriptionOutput\n\nif is_vision_available():\n from transformers import SuperPointImageProcessor\n\n\nclass SuperPointImageProcessingTester:\n def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n ):\n size = size if size is not None else {\"height\": 480, \"width\": 640}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n\n def prepare_image_processor_dict(self):\n return {\n \"do_resize\": self.do_resize,\n \"size\": self.size,\n }\n\n def expected_output_image_shape(self, images):\n return self.num_channels, self.size[\"height\"], self.size[\"width\"]\n\n def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):\n return prepare_image_inputs(\n batch_size=self.batch_size,\n num_channels=self.num_channels,\n min_resolution=self.min_resolution,\n max_resolution=self.max_resolution,\n equal_resolution=equal_resolution,\n numpify=numpify,\n torchify=torchify,\n )\n\n def prepare_keypoint_detection_output(self, pixel_values):\n max_number_keypoints = 50\n batch_size = len(pixel_values)\n mask = torch.zeros((batch_size, max_number_keypoints))\n keypoints = torch.zeros((batch_size, max_number_keypoints, 2))\n scores = torch.zeros((batch_size, max_number_keypoints))\n descriptors = torch.zeros((batch_size, max_number_keypoints, 16))\n for i in range(batch_size):\n random_number_keypoints = np.random.randint(0, max_number_keypoints)\n mask[i, :random_number_keypoints] = 1\n keypoints[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 2))\n scores[i, :random_number_keypoints] = torch.rand((random_number_keypoints,))\n descriptors[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 16))\n return SuperPointKeypointDescriptionOutput(\n loss=None, keypoints=keypoints, scores=scores, descriptors=descriptors, mask=mask, hidden_states=None\n )\n\n\n@require_torch\n@require_vision\nclass SuperPointImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):\n image_processing_class = SuperPointImageProcessor if is_vision_available() else None\n\n def setUp(self) -> None:\n super().setUp()\n self.image_processor_tester = SuperPointImageProcessingTester(self)\n\n @property\n def image_processor_dict(self):\n return self.image_processor_tester.prepare_image_processor_dict()\n\n def test_image_processing(self):\n image_processing = self.image_processing_class(**self.image_processor_dict)\n self.assertTrue(hasattr(image_processing, \"do_resize\"))\n self.assertTrue(hasattr(image_processing, \"size\"))\n self.assertTrue(hasattr(image_processing, \"do_rescale\"))\n self.assertTrue(hasattr(image_processing, \"rescale_factor\"))\n\n def test_image_processor_from_dict_with_kwargs(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n self.assertEqual(image_processor.size, {\"height\": 480, \"width\": 640})\n\n image_processor = self.image_processing_class.from_dict(\n self.image_processor_dict, size={\"height\": 42, \"width\": 42}\n )\n self.assertEqual(image_processor.size, {\"height\": 42, \"width\": 42})\n\n @unittest.skip(reason=\"SuperPointImageProcessor is always supposed to return a grayscaled image\")\n def test_call_numpy_4_channels(self):\n pass\n\n def test_input_image_properly_converted_to_grayscale(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n image_inputs = self.image_processor_tester.prepare_image_inputs()\n pre_processed_images = image_processor.preprocess(image_inputs)\n for image in pre_processed_images[\"pixel_values\"]:\n self.assertTrue(np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...]))\n\n @require_torch\n def test_post_processing_keypoint_detection(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n<|edits_diff|>\n--- tests/models/superpoint/test_image_processing_superpoint.py\n+++ tests/models/superpoint/test_image_processing_superpoint.py\n@@ -20,6 +20,7 @@\n max_resolution=400,\n do_resize=True,\n size=None,\n+ do_grayscale=True,\n ):\n size = size if size is not None else {\"height\": 480, \"width\": 640}\n self.parent = parent\n@@ -30,11 +31,13 @@\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n+ self.do_grayscale = do_grayscale\n \n def prepare_image_processor_dict(self):\n return {\n \"do_resize\": self.do_resize,\n \"size\": self.size,\n+ \"do_grayscale\": self.do_grayscale,\n }\n \n def expected_output_image_shape(self, images):\n<|current_version|>\n\n\nif is_torch_available():\n import torch\n\n from transformers.models.superpoint.modeling_superpoint import SuperPointKeypointDescriptionOutput\n\nif is_vision_available():\n from transformers import SuperPointImageProcessor\n\n\nclass SuperPointImageProcessingTester:\n def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n do_grayscale=True,\n ):\n size = size if size is not None else {\"height\": 480, \"width\": 640}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.do_grayscale = do_grayscale\n\n def prepare_image_processor_dict(self):\n return {\n \"do_resize\": self.do_resize,\n \"size\": self.size,\n \"do_grayscale\": self.do_grayscale,\n }\n\n def expected_output_image_shape(self, images):\n return self.num_channels, self.size[\"height\"], self.size[\"width\"]\n\n def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):\n return prepare_image_inputs(\n batch_size=self.batch_size,\n num_channels=self.num_channels,\n min_resolution=self.min_resolution,\n max_resolution=self.max_resolution,\n equal_resolution=equal_resolution,\n numpify=numpify,\n torchify=torchify,\n )\n\n def prepare_keypoint_detection_output(self, pixel_values):\n max_number_keypoints = 50\n batch_size = len(pixel_values)\n mask = torch.zeros((batch_size, max_number_keypoints))\n keypoints = torch.zeros((batch_size, max_number_keypoints, 2))\n scores = torch.zeros((batch_size, max_number_keypoints))\n descriptors = torch.zeros((batch_size, max_number_keypoints, 16))\n for i in range(batch_size):\n random_number_keypoints = np.random.randint(0, max_number_keypoints)\n mask[i, :random_number_keypoints] = 1\n keypoints[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 2))\n scores[i, :random_number_keypoints] = torch.rand((random_number_keypoints,))\n descriptors[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 16))\n return SuperPointKeypointDescriptionOutput(\n loss=None, keypoints=keypoints, scores=scores, descriptors=descriptors, mask=mask, hidden_states=None\n )\n\n\n@require_torch\n@require_vision\nclass SuperPointImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):\n image_processing_class = SuperPointImageProcessor if is_vision_available() else None\n\n def setUp(self) -> None:\n super().setUp()\n self.image_processor_tester = SuperPointImageProcessingTester(self)\n\n @property\n def image_processor_dict(self):\n return self.image_processor_tester.prepare_image_processor_dict()\n\n def test_image_processing(self):\n image_processing = self.image_processing_class(**self.image_processor_dict)\n self.assertTrue(hasattr(image_processing, \"do_resize\"))\n self.assertTrue(hasattr(image_processing, \"size\"))\n self.assertTrue(hasattr(image_processing, \"do_rescale\"))\n self.assertTrue(hasattr(image_processing, \"rescale_factor\"))\n\n def test_image_processor_from_dict_with_kwargs(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n self.assertEqual(image_processor.size, {\"height\": 480, \"width\": 640})\n\n image_processor = self.image_processing_class.from_dict(\n self.image_processor_dict, size={\"height\": 42, \"width\": 42}\n )\n self.assertEqual(image_processor.size, {\"height\": 42, \"width\": 42})\n\n @unittest.skip(reason=\"SuperPointImageProcessor is always supposed to return a grayscaled image\")\n def test_call_numpy_4_channels(self):\n pass\n\n def test_input_image_properly_converted_to_grayscale(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n image_inputs = self.image_processor_tester.prepare_image_inputs()\n pre_processed_images = image_processor.preprocess(image_inputs)\n for image in pre_processed_images[\"pixel_values\"]:\n self.assertTrue(np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...]))\n\n @require_torch\n def test_post_processing_keypoint_detection(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n<|next_version|>\n\n\nif is_torch_available():\n import torch\n\n from transformers.models.superpoint.modeling_superpoint import SuperPointKeypointDescriptionOutput\n\nif is_vision_available():\n from transformers import SuperPointImageProcessor\n\n\nclass SuperPointImageProcessingTester:\n def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n do_grayscale=True,\n ):\n size = size if size is not None else {\"height\": 480, \"width\": 640}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.do_grayscale = do_grayscale\n\n def prepare_image_processor_dict(self):\n return {\n \"do_resize\": self.do_resize,\n \"size\": self.size,\n \"do_grayscale\": self.do_grayscale,\n }\n\n def expected_output_image_shape(self, images):\n return self.num_channels, self.size[\"height\"], self.size[\"width\"]\n\n def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):\n return prepare_image_inputs(\n batch_size=self.batch_size,\n num_channels=self.num_channels,\n min_resolution=self.min_resolution,\n max_resolution=self.max_resolution,\n equal_resolution=equal_resolution,\n numpify=numpify,\n torchify=torchify,\n )\n\n def prepare_keypoint_detection_output(self, pixel_values):\n max_number_keypoints = 50\n batch_size = len(pixel_values)\n mask = torch.zeros((batch_size, max_number_keypoints))\n keypoints = torch.zeros((batch_size, max_number_keypoints, 2))\n scores = torch.zeros((batch_size, max_number_keypoints))\n descriptors = torch.zeros((batch_size, max_number_keypoints, 16))\n for i in range(batch_size):\n random_number_keypoints = np.random.randint(0, max_number_keypoints)\n mask[i, :random_number_keypoints] = 1\n keypoints[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 2))\n scores[i, :random_number_keypoints] = torch.rand((random_number_keypoints,))\n descriptors[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 16))\n return SuperPointKeypointDescriptionOutput(\n loss=None, keypoints=keypoints, scores=scores, descriptors=descriptors, mask=mask, hidden_states=None\n )\n\n\n@require_torch\n@require_vision\nclass SuperPointImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):\n image_processing_class = SuperPointImageProcessor if is_vision_available() else None\n\n def setUp(self) -> None:\n super().setUp()\n self.image_processor_tester = SuperPointImageProcessingTester(self)\n\n @property\n def image_processor_dict(self):\n return self.image_processor_tester.prepare_image_processor_dict()\n\n def test_image_processing(self):\n image_processing = self.image_processing_class(**self.image_processor_dict)\n self.assertTrue(hasattr(image_processing, \"do_resize\"))\n self.assertTrue(hasattr(image_processing, \"size\"))\n self.assertTrue(hasattr(image_processing, \"do_rescale\"))\n self.assertTrue(hasattr(image_processing, \"rescale_factor\"))\n self.assertTrue(hasattr(image_processing, \"do_grayscale\"))\n\n def test_image_processor_from_dict_with_kwargs(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n self.assertEqual(image_processor.size, {\"height\": 480, \"width\": 640})\n\n image_processor = self.image_processing_class.from_dict(\n self.image_processor_dict, size={\"height\": 42, \"width\": 42}\n )\n self.assertEqual(image_processor.size, {\"height\": 42, \"width\": 42})\n\n @unittest.skip(reason=\"SuperPointImageProcessor is always supposed to return a grayscaled image\")\n def test_call_numpy_4_channels(self):\n pass\n\n def test_input_image_properly_converted_to_grayscale(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n image_inputs = self.image_processor_tester.prepare_image_inputs()\n pre_processed_images = image_processor.preprocess(image_inputs)\n for image in pre_processed_images[\"pixel_values\"]:\n self.assertTrue(np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...]))\n\n @require_torch\n def test_post_processing_keypoint_detection(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n", "current_contents": "\n\nif is_torch_available():\n import torch\n\n from transformers.models.superpoint.modeling_superpoint import SuperPointKeypointDescriptionOutput\n\nif is_vision_available():\n from transformers import SuperPointImageProcessor\n\n\nclass SuperPointImageProcessingTester:\n def __init__(\n self,\n parent,\n batch_size=7,\n num_channels=3,\n image_size=18,\n min_resolution=30,\n max_resolution=400,\n do_resize=True,\n size=None,\n do_grayscale=True,\n ):\n size = size if size is not None else {\"height\": 480, \"width\": 640}\n self.parent = parent\n self.batch_size = batch_size\n self.num_channels = num_channels\n self.image_size = image_size\n self.min_resolution = min_resolution\n self.max_resolution = max_resolution\n self.do_resize = do_resize\n self.size = size\n self.do_grayscale = do_grayscale\n\n def prepare_image_processor_dict(self):\n return {\n \"do_resize\": self.do_resize,\n \"size\": self.size,\n \"do_grayscale\": self.do_grayscale,\n }\n\n def expected_output_image_shape(self, images):\n return self.num_channels, self.size[\"height\"], self.size[\"width\"]\n\n def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):\n return prepare_image_inputs(\n batch_size=self.batch_size,\n num_channels=self.num_channels,\n min_resolution=self.min_resolution,\n max_resolution=self.max_resolution,\n equal_resolution=equal_resolution,\n numpify=numpify,\n torchify=torchify,\n )\n\n def prepare_keypoint_detection_output(self, pixel_values):\n max_number_keypoints = 50\n batch_size = len(pixel_values)\n mask = torch.zeros((batch_size, max_number_keypoints))\n keypoints = torch.zeros((batch_size, max_number_keypoints, 2))\n scores = torch.zeros((batch_size, max_number_keypoints))\n descriptors = torch.zeros((batch_size, max_number_keypoints, 16))\n for i in range(batch_size):\n random_number_keypoints = np.random.randint(0, max_number_keypoints)\n mask[i, :random_number_keypoints] = 1\n keypoints[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 2))\n scores[i, :random_number_keypoints] = torch.rand((random_number_keypoints,))\n descriptors[i, :random_number_keypoints] = torch.rand((random_number_keypoints, 16))\n return SuperPointKeypointDescriptionOutput(\n loss=None, keypoints=keypoints, scores=scores, descriptors=descriptors, mask=mask, hidden_states=None\n )\n\n\n@require_torch\n@require_vision\nclass SuperPointImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):\n image_processing_class = SuperPointImageProcessor if is_vision_available() else None\n\n def setUp(self) -> None:\n super().setUp()\n self.image_processor_tester = SuperPointImageProcessingTester(self)\n\n @property\n def image_processor_dict(self):\n return self.image_processor_tester.prepare_image_processor_dict()\n\n def test_image_processing(self):\n image_processing = self.image_processing_class(**self.image_processor_dict)\n self.assertTrue(hasattr(image_processing, \"do_resize\"))\n self.assertTrue(hasattr(image_processing, \"size\"))\n self.assertTrue(hasattr(image_processing, \"do_rescale\"))\n self.assertTrue(hasattr(image_processing, \"rescale_factor\"))\n\n def test_image_processor_from_dict_with_kwargs(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n self.assertEqual(image_processor.size, {\"height\": 480, \"width\": 640})\n\n image_processor = self.image_processing_class.from_dict(\n self.image_processor_dict, size={\"height\": 42, \"width\": 42}\n )\n self.assertEqual(image_processor.size, {\"height\": 42, \"width\": 42})\n\n @unittest.skip(reason=\"SuperPointImageProcessor is always supposed to return a grayscaled image\")\n def test_call_numpy_4_channels(self):\n pass\n\n def test_input_image_properly_converted_to_grayscale(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)\n image_inputs = self.image_processor_tester.prepare_image_inputs()\n pre_processed_images = image_processor.preprocess(image_inputs)\n for image in pre_processed_images[\"pixel_values\"]:\n self.assertTrue(np.all(image[0, ...] == image[1, ...]) and np.all(image[1, ...] == image[2, ...]))\n\n @require_torch\n def test_post_processing_keypoint_detection(self):\n image_processor = self.image_processing_class.from_dict(self.image_processor_dict)"} {"commit": "e94c13ce74990eb682aead3fd976df45beee93d6", "message": "✨ Add allow disabling `redirect_slashes` at the FastAPI app level (#3432)", "old_file": "fastapi/applications.py", "new_file": "fastapi/applications.py", "status": "M", "old_contents": "from starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import ASGIApp, Lifespan, Receive, Scope, Send\n\nAppType = TypeVar(\"AppType\", bound=\"FastAPI\")\n\n\nclass FastAPI(Starlette):\n def __init__(\n self: AppType,\n *,\n debug: bool = False,\n routes: Optional[List[BaseRoute]] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n dependencies: Optional[Sequence[Depends]] = None,\n default_response_class: Type[Response] = Default(JSONResponse),\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,\n middleware: Optional[Sequence[Middleware]] = None,\n exception_handlers: Optional[\n Dict[\n Union[int, Type[Exception]],\n Callable[[Request, Any], Coroutine[Any, Any, Response]],\n ]\n ] = None,\n on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n lifespan: Optional[Lifespan[AppType]] = None,\n terms_of_service: Optional[str] = None,\n contact: Optional[Dict[str, Union[str, Any]]] = None,\n license_info: Optional[Dict[str, Union[str, Any]]] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n root_path_in_servers: bool = True,\n responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n callbacks: Optional[List[BaseRoute]] = None,\n deprecated: Optional[bool] = None,\n include_in_schema: bool = True,\n swagger_ui_parameters: Optional[Dict[str, Any]] = None,\n generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(\n generate_unique_id\n ),\n **extra: Any,\n ) -> None:\n self.debug = debug\n self.title = title\n self.description = description\n self.version = version\n self.terms_of_service = terms_of_service\n self.contact = contact\n self.license_info = license_info\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n self.root_path_in_servers = root_path_in_servers\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.swagger_ui_parameters = swagger_ui_parameters\n self.servers = servers or []\n self.extra = extra\n self.openapi_version = \"3.0.2\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications/\"\n )\n self.root_path = root_path or openapi_prefix\n self.state: State = State()\n self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}\n self.router: routing.APIRouter = routing.APIRouter(\n routes=routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n lifespan=lifespan,\n default_response_class=default_response_class,\n dependencies=dependencies,\n callbacks=callbacks,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n responses=responses,\n generate_unique_id_function=generate_unique_id_function,\n )\n self.exception_handlers: Dict[\n Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]\n ] = ({} if exception_handlers is None else dict(exception_handlers))\n self.exception_handlers.setdefault(HTTPException, http_exception_handler)\n self.exception_handlers.setdefault(\n RequestValidationError, request_validation_exception_handler\n )\n self.exception_handlers.setdefault(\n WebSocketRequestValidationError,\n # Starlette still has incorrect type specification for the handlers\n websocket_request_validation_exception_handler, # type: ignore\n )", "new_contents": "from starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import ASGIApp, Lifespan, Receive, Scope, Send\n\nAppType = TypeVar(\"AppType\", bound=\"FastAPI\")\n\n\nclass FastAPI(Starlette):\n def __init__(\n self: AppType,\n *,\n debug: bool = False,\n routes: Optional[List[BaseRoute]] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n dependencies: Optional[Sequence[Depends]] = None,\n default_response_class: Type[Response] = Default(JSONResponse),\n redirect_slashes: bool = True,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,\n middleware: Optional[Sequence[Middleware]] = None,\n exception_handlers: Optional[\n Dict[\n Union[int, Type[Exception]],\n Callable[[Request, Any], Coroutine[Any, Any, Response]],\n ]\n ] = None,\n on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n lifespan: Optional[Lifespan[AppType]] = None,\n terms_of_service: Optional[str] = None,\n contact: Optional[Dict[str, Union[str, Any]]] = None,\n license_info: Optional[Dict[str, Union[str, Any]]] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n root_path_in_servers: bool = True,\n responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n callbacks: Optional[List[BaseRoute]] = None,\n deprecated: Optional[bool] = None,\n include_in_schema: bool = True,\n swagger_ui_parameters: Optional[Dict[str, Any]] = None,\n generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(\n generate_unique_id\n ),\n **extra: Any,\n ) -> None:\n self.debug = debug\n self.title = title\n self.description = description\n self.version = version\n self.terms_of_service = terms_of_service\n self.contact = contact\n self.license_info = license_info\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n self.root_path_in_servers = root_path_in_servers\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.swagger_ui_parameters = swagger_ui_parameters\n self.servers = servers or []\n self.extra = extra\n self.openapi_version = \"3.0.2\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications/\"\n )\n self.root_path = root_path or openapi_prefix\n self.state: State = State()\n self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}\n self.router: routing.APIRouter = routing.APIRouter(\n routes=routes,\n redirect_slashes=redirect_slashes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n lifespan=lifespan,\n default_response_class=default_response_class,\n dependencies=dependencies,\n callbacks=callbacks,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n responses=responses,\n generate_unique_id_function=generate_unique_id_function,\n )\n self.exception_handlers: Dict[\n Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]\n ] = ({} if exception_handlers is None else dict(exception_handlers))\n self.exception_handlers.setdefault(HTTPException, http_exception_handler)\n self.exception_handlers.setdefault(\n RequestValidationError, request_validation_exception_handler\n )\n self.exception_handlers.setdefault(\n WebSocketRequestValidationError,\n # Starlette still has incorrect type specification for the handlers\n websocket_request_validation_exception_handler, # type: ignore\n )", "text": "<|original_code|>\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import ASGIApp, Lifespan, Receive, Scope, Send\n\nAppType = TypeVar(\"AppType\", bound=\"FastAPI\")\n\n\nclass FastAPI(Starlette):\n def __init__(\n self: AppType,\n *,\n debug: bool = False,\n routes: Optional[List[BaseRoute]] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n dependencies: Optional[Sequence[Depends]] = None,\n default_response_class: Type[Response] = Default(JSONResponse),\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,\n middleware: Optional[Sequence[Middleware]] = None,\n exception_handlers: Optional[\n Dict[\n Union[int, Type[Exception]],\n Callable[[Request, Any], Coroutine[Any, Any, Response]],\n ]\n ] = None,\n on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n lifespan: Optional[Lifespan[AppType]] = None,\n terms_of_service: Optional[str] = None,\n contact: Optional[Dict[str, Union[str, Any]]] = None,\n license_info: Optional[Dict[str, Union[str, Any]]] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n root_path_in_servers: bool = True,\n responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n callbacks: Optional[List[BaseRoute]] = None,\n deprecated: Optional[bool] = None,\n include_in_schema: bool = True,\n swagger_ui_parameters: Optional[Dict[str, Any]] = None,\n generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(\n generate_unique_id\n ),\n **extra: Any,\n ) -> None:\n self.debug = debug\n self.title = title\n self.description = description\n self.version = version\n self.terms_of_service = terms_of_service\n self.contact = contact\n self.license_info = license_info\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n self.root_path_in_servers = root_path_in_servers\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.swagger_ui_parameters = swagger_ui_parameters\n self.servers = servers or []\n self.extra = extra\n self.openapi_version = \"3.0.2\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications/\"\n )\n self.root_path = root_path or openapi_prefix\n self.state: State = State()\n self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}\n self.router: routing.APIRouter = routing.APIRouter(\n routes=routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n lifespan=lifespan,\n default_response_class=default_response_class,\n dependencies=dependencies,\n callbacks=callbacks,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n responses=responses,\n generate_unique_id_function=generate_unique_id_function,\n )\n self.exception_handlers: Dict[\n Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]\n ] = ({} if exception_handlers is None else dict(exception_handlers))\n self.exception_handlers.setdefault(HTTPException, http_exception_handler)\n self.exception_handlers.setdefault(\n RequestValidationError, request_validation_exception_handler\n )\n self.exception_handlers.setdefault(\n WebSocketRequestValidationError,\n # Starlette still has incorrect type specification for the handlers\n websocket_request_validation_exception_handler, # type: ignore\n )\n<|edits_diff|>\n--- fastapi/applications.py\n+++ fastapi/applications.py\n@@ -20,6 +20,7 @@\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n dependencies: Optional[Sequence[Depends]] = None,\n default_response_class: Type[Response] = Default(JSONResponse),\n+ redirect_slashes: bool = True,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n<|current_version|>\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import ASGIApp, Lifespan, Receive, Scope, Send\n\nAppType = TypeVar(\"AppType\", bound=\"FastAPI\")\n\n\nclass FastAPI(Starlette):\n def __init__(\n self: AppType,\n *,\n debug: bool = False,\n routes: Optional[List[BaseRoute]] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n dependencies: Optional[Sequence[Depends]] = None,\n default_response_class: Type[Response] = Default(JSONResponse),\n redirect_slashes: bool = True,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,\n middleware: Optional[Sequence[Middleware]] = None,\n exception_handlers: Optional[\n Dict[\n Union[int, Type[Exception]],\n Callable[[Request, Any], Coroutine[Any, Any, Response]],\n ]\n ] = None,\n on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n lifespan: Optional[Lifespan[AppType]] = None,\n terms_of_service: Optional[str] = None,\n contact: Optional[Dict[str, Union[str, Any]]] = None,\n license_info: Optional[Dict[str, Union[str, Any]]] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n root_path_in_servers: bool = True,\n responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n callbacks: Optional[List[BaseRoute]] = None,\n deprecated: Optional[bool] = None,\n include_in_schema: bool = True,\n swagger_ui_parameters: Optional[Dict[str, Any]] = None,\n generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(\n generate_unique_id\n ),\n **extra: Any,\n ) -> None:\n self.debug = debug\n self.title = title\n self.description = description\n self.version = version\n self.terms_of_service = terms_of_service\n self.contact = contact\n self.license_info = license_info\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n self.root_path_in_servers = root_path_in_servers\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.swagger_ui_parameters = swagger_ui_parameters\n self.servers = servers or []\n self.extra = extra\n self.openapi_version = \"3.0.2\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications/\"\n )\n self.root_path = root_path or openapi_prefix\n self.state: State = State()\n self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}\n self.router: routing.APIRouter = routing.APIRouter(\n routes=routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n lifespan=lifespan,\n default_response_class=default_response_class,\n dependencies=dependencies,\n callbacks=callbacks,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n responses=responses,\n generate_unique_id_function=generate_unique_id_function,\n )\n self.exception_handlers: Dict[\n Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]\n ] = ({} if exception_handlers is None else dict(exception_handlers))\n self.exception_handlers.setdefault(HTTPException, http_exception_handler)\n self.exception_handlers.setdefault(\n RequestValidationError, request_validation_exception_handler\n )\n self.exception_handlers.setdefault(\n WebSocketRequestValidationError,\n # Starlette still has incorrect type specification for the handlers\n websocket_request_validation_exception_handler, # type: ignore\n )\n<|next_version|>\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import ASGIApp, Lifespan, Receive, Scope, Send\n\nAppType = TypeVar(\"AppType\", bound=\"FastAPI\")\n\n\nclass FastAPI(Starlette):\n def __init__(\n self: AppType,\n *,\n debug: bool = False,\n routes: Optional[List[BaseRoute]] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n dependencies: Optional[Sequence[Depends]] = None,\n default_response_class: Type[Response] = Default(JSONResponse),\n redirect_slashes: bool = True,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,\n middleware: Optional[Sequence[Middleware]] = None,\n exception_handlers: Optional[\n Dict[\n Union[int, Type[Exception]],\n Callable[[Request, Any], Coroutine[Any, Any, Response]],\n ]\n ] = None,\n on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n lifespan: Optional[Lifespan[AppType]] = None,\n terms_of_service: Optional[str] = None,\n contact: Optional[Dict[str, Union[str, Any]]] = None,\n license_info: Optional[Dict[str, Union[str, Any]]] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n root_path_in_servers: bool = True,\n responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n callbacks: Optional[List[BaseRoute]] = None,\n deprecated: Optional[bool] = None,\n include_in_schema: bool = True,\n swagger_ui_parameters: Optional[Dict[str, Any]] = None,\n generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(\n generate_unique_id\n ),\n **extra: Any,\n ) -> None:\n self.debug = debug\n self.title = title\n self.description = description\n self.version = version\n self.terms_of_service = terms_of_service\n self.contact = contact\n self.license_info = license_info\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n self.root_path_in_servers = root_path_in_servers\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.swagger_ui_parameters = swagger_ui_parameters\n self.servers = servers or []\n self.extra = extra\n self.openapi_version = \"3.0.2\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications/\"\n )\n self.root_path = root_path or openapi_prefix\n self.state: State = State()\n self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}\n self.router: routing.APIRouter = routing.APIRouter(\n routes=routes,\n redirect_slashes=redirect_slashes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n lifespan=lifespan,\n default_response_class=default_response_class,\n dependencies=dependencies,\n callbacks=callbacks,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n responses=responses,\n generate_unique_id_function=generate_unique_id_function,\n )\n self.exception_handlers: Dict[\n Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]\n ] = ({} if exception_handlers is None else dict(exception_handlers))\n self.exception_handlers.setdefault(HTTPException, http_exception_handler)\n self.exception_handlers.setdefault(\n RequestValidationError, request_validation_exception_handler\n )\n self.exception_handlers.setdefault(\n WebSocketRequestValidationError,\n # Starlette still has incorrect type specification for the handlers\n websocket_request_validation_exception_handler, # type: ignore\n )\n", "current_contents": "from starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import ASGIApp, Lifespan, Receive, Scope, Send\n\nAppType = TypeVar(\"AppType\", bound=\"FastAPI\")\n\n\nclass FastAPI(Starlette):\n def __init__(\n self: AppType,\n *,\n debug: bool = False,\n routes: Optional[List[BaseRoute]] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n dependencies: Optional[Sequence[Depends]] = None,\n default_response_class: Type[Response] = Default(JSONResponse),\n redirect_slashes: bool = True,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[Dict[str, Any]] = None,\n middleware: Optional[Sequence[Middleware]] = None,\n exception_handlers: Optional[\n Dict[\n Union[int, Type[Exception]],\n Callable[[Request, Any], Coroutine[Any, Any, Response]],\n ]\n ] = None,\n on_startup: Optional[Sequence[Callable[[], Any]]] = None,\n on_shutdown: Optional[Sequence[Callable[[], Any]]] = None,\n lifespan: Optional[Lifespan[AppType]] = None,\n terms_of_service: Optional[str] = None,\n contact: Optional[Dict[str, Union[str, Any]]] = None,\n license_info: Optional[Dict[str, Union[str, Any]]] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n root_path_in_servers: bool = True,\n responses: Optional[Dict[Union[int, str], Dict[str, Any]]] = None,\n callbacks: Optional[List[BaseRoute]] = None,\n deprecated: Optional[bool] = None,\n include_in_schema: bool = True,\n swagger_ui_parameters: Optional[Dict[str, Any]] = None,\n generate_unique_id_function: Callable[[routing.APIRoute], str] = Default(\n generate_unique_id\n ),\n **extra: Any,\n ) -> None:\n self.debug = debug\n self.title = title\n self.description = description\n self.version = version\n self.terms_of_service = terms_of_service\n self.contact = contact\n self.license_info = license_info\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n self.root_path_in_servers = root_path_in_servers\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.swagger_ui_parameters = swagger_ui_parameters\n self.servers = servers or []\n self.extra = extra\n self.openapi_version = \"3.0.2\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications/\"\n )\n self.root_path = root_path or openapi_prefix\n self.state: State = State()\n self.dependency_overrides: Dict[Callable[..., Any], Callable[..., Any]] = {}\n self.router: routing.APIRouter = routing.APIRouter(\n routes=routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n lifespan=lifespan,\n default_response_class=default_response_class,\n dependencies=dependencies,\n callbacks=callbacks,\n deprecated=deprecated,\n include_in_schema=include_in_schema,\n responses=responses,\n generate_unique_id_function=generate_unique_id_function,\n )\n self.exception_handlers: Dict[\n Any, Callable[[Request, Any], Union[Response, Awaitable[Response]]]\n ] = ({} if exception_handlers is None else dict(exception_handlers))\n self.exception_handlers.setdefault(HTTPException, http_exception_handler)\n self.exception_handlers.setdefault(\n RequestValidationError, request_validation_exception_handler\n )\n self.exception_handlers.setdefault(\n WebSocketRequestValidationError,\n # Starlette still has incorrect type specification for the handlers\n websocket_request_validation_exception_handler, # type: ignore\n )"} {"commit": "ca2fae0588260f93f886aa59f689e3018e934a27", "message": "✨ Add support for `FrozenSet` in parameters (e.g. query) (#2938)", "old_file": "fastapi/dependencies/utils.py", "new_file": "fastapi/dependencies/utils.py", "status": "M", "old_contents": " Type,\n Union,\n cast,\n)\n\nimport anyio\nfrom fastapi import params\nfrom fastapi.concurrency import (\n AsyncExitStack,\n asynccontextmanager,\n contextmanager_in_threadpool,\n)\nfrom fastapi.dependencies.models import Dependant, SecurityRequirement\nfrom fastapi.logger import logger\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.oauth2 import OAuth2, SecurityScopes\nfrom fastapi.security.open_id_connect_url import OpenIdConnect\nfrom fastapi.utils import create_response_field, get_path_param_names\nfrom pydantic import BaseModel, create_model\nfrom pydantic.error_wrappers import ErrorWrapper\nfrom pydantic.errors import MissingError\nfrom pydantic.fields import (\n SHAPE_LIST,\n SHAPE_SEQUENCE,\n SHAPE_SET,\n SHAPE_SINGLETON,\n SHAPE_TUPLE,\n SHAPE_TUPLE_ELLIPSIS,\n FieldInfo,\n ModelField,\n Required,\n Undefined,\n)\nfrom pydantic.schema import get_annotation_from_field_info\nfrom pydantic.typing import ForwardRef, evaluate_forwardref\nfrom pydantic.utils import lenient_issubclass\nfrom starlette.background import BackgroundTasks\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.datastructures import FormData, Headers, QueryParams, UploadFile\nfrom starlette.requests import HTTPConnection, Request\nfrom starlette.responses import Response\nfrom starlette.websockets import WebSocket\n\nsequence_shapes = {\n SHAPE_LIST,\n SHAPE_SET,\n SHAPE_TUPLE,\n SHAPE_SEQUENCE,\n SHAPE_TUPLE_ELLIPSIS,\n}\nsequence_types = (list, set, tuple)\nsequence_shape_to_type = {\n SHAPE_LIST: list,\n SHAPE_SET: set,\n SHAPE_TUPLE: tuple,\n SHAPE_SEQUENCE: list,\n SHAPE_TUPLE_ELLIPSIS: list,\n}\n\n\nmultipart_not_installed_error = (\n 'Form data requires \"python-multipart\" to be installed. \\n'\n 'You can install \"python-multipart\" with: \\n\\n'\n \"pip install python-multipart\\n\"\n)\nmultipart_incorrect_install_error = (\n 'Form data requires \"python-multipart\" to be installed. '\n 'It seems you installed \"multipart\" instead. \\n'\n 'You can remove \"multipart\" with: \\n\\n'\n \"pip uninstall multipart\\n\\n\"", "new_contents": " Type,\n Union,\n cast,\n)\n\nimport anyio\nfrom fastapi import params\nfrom fastapi.concurrency import (\n AsyncExitStack,\n asynccontextmanager,\n contextmanager_in_threadpool,\n)\nfrom fastapi.dependencies.models import Dependant, SecurityRequirement\nfrom fastapi.logger import logger\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.oauth2 import OAuth2, SecurityScopes\nfrom fastapi.security.open_id_connect_url import OpenIdConnect\nfrom fastapi.utils import create_response_field, get_path_param_names\nfrom pydantic import BaseModel, create_model\nfrom pydantic.error_wrappers import ErrorWrapper\nfrom pydantic.errors import MissingError\nfrom pydantic.fields import (\n SHAPE_FROZENSET,\n SHAPE_LIST,\n SHAPE_SEQUENCE,\n SHAPE_SET,\n SHAPE_SINGLETON,\n SHAPE_TUPLE,\n SHAPE_TUPLE_ELLIPSIS,\n FieldInfo,\n ModelField,\n Required,\n Undefined,\n)\nfrom pydantic.schema import get_annotation_from_field_info\nfrom pydantic.typing import ForwardRef, evaluate_forwardref\nfrom pydantic.utils import lenient_issubclass\nfrom starlette.background import BackgroundTasks\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.datastructures import FormData, Headers, QueryParams, UploadFile\nfrom starlette.requests import HTTPConnection, Request\nfrom starlette.responses import Response\nfrom starlette.websockets import WebSocket\n\nsequence_shapes = {\n SHAPE_LIST,\n SHAPE_SET,\n SHAPE_FROZENSET,\n SHAPE_TUPLE,\n SHAPE_SEQUENCE,\n SHAPE_TUPLE_ELLIPSIS,\n}\nsequence_types = (list, set, tuple)\nsequence_shape_to_type = {\n SHAPE_LIST: list,\n SHAPE_SET: set,\n SHAPE_TUPLE: tuple,\n SHAPE_SEQUENCE: list,\n SHAPE_TUPLE_ELLIPSIS: list,\n}\n\n\nmultipart_not_installed_error = (\n 'Form data requires \"python-multipart\" to be installed. \\n'\n 'You can install \"python-multipart\" with: \\n\\n'\n \"pip install python-multipart\\n\"\n)\nmultipart_incorrect_install_error = (\n 'Form data requires \"python-multipart\" to be installed. '\n 'It seems you installed \"multipart\" instead. \\n'\n 'You can remove \"multipart\" with: \\n\\n'\n \"pip uninstall multipart\\n\\n\"", "text": "<|original_code|>\n Type,\n Union,\n cast,\n)\n\nimport anyio\nfrom fastapi import params\nfrom fastapi.concurrency import (\n AsyncExitStack,\n asynccontextmanager,\n contextmanager_in_threadpool,\n)\nfrom fastapi.dependencies.models import Dependant, SecurityRequirement\nfrom fastapi.logger import logger\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.oauth2 import OAuth2, SecurityScopes\nfrom fastapi.security.open_id_connect_url import OpenIdConnect\nfrom fastapi.utils import create_response_field, get_path_param_names\nfrom pydantic import BaseModel, create_model\nfrom pydantic.error_wrappers import ErrorWrapper\nfrom pydantic.errors import MissingError\nfrom pydantic.fields import (\n SHAPE_LIST,\n SHAPE_SEQUENCE,\n SHAPE_SET,\n SHAPE_SINGLETON,\n SHAPE_TUPLE,\n SHAPE_TUPLE_ELLIPSIS,\n FieldInfo,\n ModelField,\n Required,\n Undefined,\n)\nfrom pydantic.schema import get_annotation_from_field_info\nfrom pydantic.typing import ForwardRef, evaluate_forwardref\nfrom pydantic.utils import lenient_issubclass\nfrom starlette.background import BackgroundTasks\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.datastructures import FormData, Headers, QueryParams, UploadFile\nfrom starlette.requests import HTTPConnection, Request\nfrom starlette.responses import Response\nfrom starlette.websockets import WebSocket\n\nsequence_shapes = {\n SHAPE_LIST,\n SHAPE_SET,\n SHAPE_TUPLE,\n SHAPE_SEQUENCE,\n SHAPE_TUPLE_ELLIPSIS,\n}\nsequence_types = (list, set, tuple)\nsequence_shape_to_type = {\n SHAPE_LIST: list,\n SHAPE_SET: set,\n SHAPE_TUPLE: tuple,\n SHAPE_SEQUENCE: list,\n SHAPE_TUPLE_ELLIPSIS: list,\n}\n\n\nmultipart_not_installed_error = (\n 'Form data requires \"python-multipart\" to be installed. \\n'\n 'You can install \"python-multipart\" with: \\n\\n'\n \"pip install python-multipart\\n\"\n)\nmultipart_incorrect_install_error = (\n 'Form data requires \"python-multipart\" to be installed. '\n 'It seems you installed \"multipart\" instead. \\n'\n 'You can remove \"multipart\" with: \\n\\n'\n \"pip uninstall multipart\\n\\n\"\n<|edits_diff|>\n--- fastapi/dependencies/utils.py\n+++ fastapi/dependencies/utils.py\n@@ -20,6 +20,7 @@\n from pydantic.error_wrappers import ErrorWrapper\n from pydantic.errors import MissingError\n from pydantic.fields import (\n+ SHAPE_FROZENSET,\n SHAPE_LIST,\n SHAPE_SEQUENCE,\n SHAPE_SET,\n<|current_version|>\n Type,\n Union,\n cast,\n)\n\nimport anyio\nfrom fastapi import params\nfrom fastapi.concurrency import (\n AsyncExitStack,\n asynccontextmanager,\n contextmanager_in_threadpool,\n)\nfrom fastapi.dependencies.models import Dependant, SecurityRequirement\nfrom fastapi.logger import logger\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.oauth2 import OAuth2, SecurityScopes\nfrom fastapi.security.open_id_connect_url import OpenIdConnect\nfrom fastapi.utils import create_response_field, get_path_param_names\nfrom pydantic import BaseModel, create_model\nfrom pydantic.error_wrappers import ErrorWrapper\nfrom pydantic.errors import MissingError\nfrom pydantic.fields import (\n SHAPE_FROZENSET,\n SHAPE_LIST,\n SHAPE_SEQUENCE,\n SHAPE_SET,\n SHAPE_SINGLETON,\n SHAPE_TUPLE,\n SHAPE_TUPLE_ELLIPSIS,\n FieldInfo,\n ModelField,\n Required,\n Undefined,\n)\nfrom pydantic.schema import get_annotation_from_field_info\nfrom pydantic.typing import ForwardRef, evaluate_forwardref\nfrom pydantic.utils import lenient_issubclass\nfrom starlette.background import BackgroundTasks\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.datastructures import FormData, Headers, QueryParams, UploadFile\nfrom starlette.requests import HTTPConnection, Request\nfrom starlette.responses import Response\nfrom starlette.websockets import WebSocket\n\nsequence_shapes = {\n SHAPE_LIST,\n SHAPE_SET,\n SHAPE_TUPLE,\n SHAPE_SEQUENCE,\n SHAPE_TUPLE_ELLIPSIS,\n}\nsequence_types = (list, set, tuple)\nsequence_shape_to_type = {\n SHAPE_LIST: list,\n SHAPE_SET: set,\n SHAPE_TUPLE: tuple,\n SHAPE_SEQUENCE: list,\n SHAPE_TUPLE_ELLIPSIS: list,\n}\n\n\nmultipart_not_installed_error = (\n 'Form data requires \"python-multipart\" to be installed. \\n'\n 'You can install \"python-multipart\" with: \\n\\n'\n \"pip install python-multipart\\n\"\n)\nmultipart_incorrect_install_error = (\n 'Form data requires \"python-multipart\" to be installed. '\n 'It seems you installed \"multipart\" instead. \\n'\n 'You can remove \"multipart\" with: \\n\\n'\n \"pip uninstall multipart\\n\\n\"\n<|next_version|>\n Type,\n Union,\n cast,\n)\n\nimport anyio\nfrom fastapi import params\nfrom fastapi.concurrency import (\n AsyncExitStack,\n asynccontextmanager,\n contextmanager_in_threadpool,\n)\nfrom fastapi.dependencies.models import Dependant, SecurityRequirement\nfrom fastapi.logger import logger\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.oauth2 import OAuth2, SecurityScopes\nfrom fastapi.security.open_id_connect_url import OpenIdConnect\nfrom fastapi.utils import create_response_field, get_path_param_names\nfrom pydantic import BaseModel, create_model\nfrom pydantic.error_wrappers import ErrorWrapper\nfrom pydantic.errors import MissingError\nfrom pydantic.fields import (\n SHAPE_FROZENSET,\n SHAPE_LIST,\n SHAPE_SEQUENCE,\n SHAPE_SET,\n SHAPE_SINGLETON,\n SHAPE_TUPLE,\n SHAPE_TUPLE_ELLIPSIS,\n FieldInfo,\n ModelField,\n Required,\n Undefined,\n)\nfrom pydantic.schema import get_annotation_from_field_info\nfrom pydantic.typing import ForwardRef, evaluate_forwardref\nfrom pydantic.utils import lenient_issubclass\nfrom starlette.background import BackgroundTasks\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.datastructures import FormData, Headers, QueryParams, UploadFile\nfrom starlette.requests import HTTPConnection, Request\nfrom starlette.responses import Response\nfrom starlette.websockets import WebSocket\n\nsequence_shapes = {\n SHAPE_LIST,\n SHAPE_SET,\n SHAPE_FROZENSET,\n SHAPE_TUPLE,\n SHAPE_SEQUENCE,\n SHAPE_TUPLE_ELLIPSIS,\n}\nsequence_types = (list, set, tuple)\nsequence_shape_to_type = {\n SHAPE_LIST: list,\n SHAPE_SET: set,\n SHAPE_TUPLE: tuple,\n SHAPE_SEQUENCE: list,\n SHAPE_TUPLE_ELLIPSIS: list,\n}\n\n\nmultipart_not_installed_error = (\n 'Form data requires \"python-multipart\" to be installed. \\n'\n 'You can install \"python-multipart\" with: \\n\\n'\n \"pip install python-multipart\\n\"\n)\nmultipart_incorrect_install_error = (\n 'Form data requires \"python-multipart\" to be installed. '\n 'It seems you installed \"multipart\" instead. \\n'\n 'You can remove \"multipart\" with: \\n\\n'\n \"pip uninstall multipart\\n\\n\"\n", "current_contents": " Type,\n Union,\n cast,\n)\n\nimport anyio\nfrom fastapi import params\nfrom fastapi.concurrency import (\n AsyncExitStack,\n asynccontextmanager,\n contextmanager_in_threadpool,\n)\nfrom fastapi.dependencies.models import Dependant, SecurityRequirement\nfrom fastapi.logger import logger\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.oauth2 import OAuth2, SecurityScopes\nfrom fastapi.security.open_id_connect_url import OpenIdConnect\nfrom fastapi.utils import create_response_field, get_path_param_names\nfrom pydantic import BaseModel, create_model\nfrom pydantic.error_wrappers import ErrorWrapper\nfrom pydantic.errors import MissingError\nfrom pydantic.fields import (\n SHAPE_FROZENSET,\n SHAPE_LIST,\n SHAPE_SEQUENCE,\n SHAPE_SET,\n SHAPE_SINGLETON,\n SHAPE_TUPLE,\n SHAPE_TUPLE_ELLIPSIS,\n FieldInfo,\n ModelField,\n Required,\n Undefined,\n)\nfrom pydantic.schema import get_annotation_from_field_info\nfrom pydantic.typing import ForwardRef, evaluate_forwardref\nfrom pydantic.utils import lenient_issubclass\nfrom starlette.background import BackgroundTasks\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.datastructures import FormData, Headers, QueryParams, UploadFile\nfrom starlette.requests import HTTPConnection, Request\nfrom starlette.responses import Response\nfrom starlette.websockets import WebSocket\n\nsequence_shapes = {\n SHAPE_LIST,\n SHAPE_SET,\n SHAPE_TUPLE,\n SHAPE_SEQUENCE,\n SHAPE_TUPLE_ELLIPSIS,\n}\nsequence_types = (list, set, tuple)\nsequence_shape_to_type = {\n SHAPE_LIST: list,\n SHAPE_SET: set,\n SHAPE_TUPLE: tuple,\n SHAPE_SEQUENCE: list,\n SHAPE_TUPLE_ELLIPSIS: list,\n}\n\n\nmultipart_not_installed_error = (\n 'Form data requires \"python-multipart\" to be installed. \\n'\n 'You can install \"python-multipart\" with: \\n\\n'\n \"pip install python-multipart\\n\"\n)\nmultipart_incorrect_install_error = (\n 'Form data requires \"python-multipart\" to be installed. '\n 'It seems you installed \"multipart\" instead. \\n'\n 'You can remove \"multipart\" with: \\n\\n'\n \"pip uninstall multipart\\n\\n\""} {"commit": "96fdfc53cc47f30cff59bb847c2c19b79fd9efcd", "message": "✨ Support `dataclasses` in responses (#3576)", "old_file": "fastapi/encoders.py", "new_file": "fastapi/encoders.py", "status": "M", "old_contents": "from collections import defaultdict\nfrom enum import Enum\nfrom pathlib import PurePath\nfrom types import GeneratorType\nfrom typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union\n\nfrom pydantic import BaseModel\nfrom pydantic.json import ENCODERS_BY_TYPE\n\nSetIntStr = Set[Union[int, str]]\nDictIntStrAny = Dict[Union[int, str], Any]\n\n\ndef generate_encoders_by_class_tuples(\n type_encoder_map: Dict[Any, Callable[[Any], Any]]\n) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:\n encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(\n tuple\n )\n for type_, encoder in type_encoder_map.items():\n encoders_by_class_tuples[encoder] += (type_,)\n return encoders_by_class_tuples\n\n\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)\n\n\ndef jsonable_encoder(\n obj: Any,\n include: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n by_alias: bool = True,\n exclude_unset: bool = False,\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n custom_encoder: Dict[Any, Callable[[Any], Any]] = {},\n sqlalchemy_safe: bool = True,\n) -> Any:\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, BaseModel):\n encoder = getattr(obj.__config__, \"json_encoders\", {})\n if custom_encoder:\n encoder.update(custom_encoder)\n obj_dict = obj.dict(\n include=include, # type: ignore # in Pydantic\n exclude=exclude, # type: ignore # in Pydantic\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n custom_encoder=encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if isinstance(obj, dict):\n encoded_dict = {}\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and ((include and key in include) or not exclude or key not in exclude)\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,", "new_contents": "import dataclasses\nfrom collections import defaultdict\nfrom enum import Enum\nfrom pathlib import PurePath\nfrom types import GeneratorType\nfrom typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union\n\nfrom pydantic import BaseModel\nfrom pydantic.json import ENCODERS_BY_TYPE\n\nSetIntStr = Set[Union[int, str]]\nDictIntStrAny = Dict[Union[int, str], Any]\n\n\ndef generate_encoders_by_class_tuples(\n type_encoder_map: Dict[Any, Callable[[Any], Any]]\n) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:\n encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(\n tuple\n )\n for type_, encoder in type_encoder_map.items():\n encoders_by_class_tuples[encoder] += (type_,)\n return encoders_by_class_tuples\n\n\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)\n\n\ndef jsonable_encoder(\n obj: Any,\n include: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n by_alias: bool = True,\n exclude_unset: bool = False,\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n custom_encoder: Dict[Any, Callable[[Any], Any]] = {},\n sqlalchemy_safe: bool = True,\n) -> Any:\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, BaseModel):\n encoder = getattr(obj.__config__, \"json_encoders\", {})\n if custom_encoder:\n encoder.update(custom_encoder)\n obj_dict = obj.dict(\n include=include, # type: ignore # in Pydantic\n exclude=exclude, # type: ignore # in Pydantic\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n custom_encoder=encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if dataclasses.is_dataclass(obj):\n return dataclasses.asdict(obj)\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if isinstance(obj, dict):\n encoded_dict = {}\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and ((include and key in include) or not exclude or key not in exclude)\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,", "text": "<|original_code|>\nfrom collections import defaultdict\nfrom enum import Enum\nfrom pathlib import PurePath\nfrom types import GeneratorType\nfrom typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union\n\nfrom pydantic import BaseModel\nfrom pydantic.json import ENCODERS_BY_TYPE\n\nSetIntStr = Set[Union[int, str]]\nDictIntStrAny = Dict[Union[int, str], Any]\n\n\ndef generate_encoders_by_class_tuples(\n type_encoder_map: Dict[Any, Callable[[Any], Any]]\n) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:\n encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(\n tuple\n )\n for type_, encoder in type_encoder_map.items():\n encoders_by_class_tuples[encoder] += (type_,)\n return encoders_by_class_tuples\n\n\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)\n\n\ndef jsonable_encoder(\n obj: Any,\n include: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n by_alias: bool = True,\n exclude_unset: bool = False,\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n custom_encoder: Dict[Any, Callable[[Any], Any]] = {},\n sqlalchemy_safe: bool = True,\n) -> Any:\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, BaseModel):\n encoder = getattr(obj.__config__, \"json_encoders\", {})\n if custom_encoder:\n encoder.update(custom_encoder)\n obj_dict = obj.dict(\n include=include, # type: ignore # in Pydantic\n exclude=exclude, # type: ignore # in Pydantic\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n custom_encoder=encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if isinstance(obj, dict):\n encoded_dict = {}\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and ((include and key in include) or not exclude or key not in exclude)\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n<|edits_diff|>\n--- fastapi/encoders.py\n+++ fastapi/encoders.py\n@@ -1,3 +1,4 @@\n+import dataclasses\n from collections import defaultdict\n from enum import Enum\n from pathlib import PurePath\n<|current_version|>\nimport dataclasses\nfrom collections import defaultdict\nfrom enum import Enum\nfrom pathlib import PurePath\nfrom types import GeneratorType\nfrom typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union\n\nfrom pydantic import BaseModel\nfrom pydantic.json import ENCODERS_BY_TYPE\n\nSetIntStr = Set[Union[int, str]]\nDictIntStrAny = Dict[Union[int, str], Any]\n\n\ndef generate_encoders_by_class_tuples(\n type_encoder_map: Dict[Any, Callable[[Any], Any]]\n) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:\n encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(\n tuple\n )\n for type_, encoder in type_encoder_map.items():\n encoders_by_class_tuples[encoder] += (type_,)\n return encoders_by_class_tuples\n\n\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)\n\n\ndef jsonable_encoder(\n obj: Any,\n include: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n by_alias: bool = True,\n exclude_unset: bool = False,\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n custom_encoder: Dict[Any, Callable[[Any], Any]] = {},\n sqlalchemy_safe: bool = True,\n) -> Any:\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, BaseModel):\n encoder = getattr(obj.__config__, \"json_encoders\", {})\n if custom_encoder:\n encoder.update(custom_encoder)\n obj_dict = obj.dict(\n include=include, # type: ignore # in Pydantic\n exclude=exclude, # type: ignore # in Pydantic\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n custom_encoder=encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if isinstance(obj, dict):\n encoded_dict = {}\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and ((include and key in include) or not exclude or key not in exclude)\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n<|next_version|>\nimport dataclasses\nfrom collections import defaultdict\nfrom enum import Enum\nfrom pathlib import PurePath\nfrom types import GeneratorType\nfrom typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union\n\nfrom pydantic import BaseModel\nfrom pydantic.json import ENCODERS_BY_TYPE\n\nSetIntStr = Set[Union[int, str]]\nDictIntStrAny = Dict[Union[int, str], Any]\n\n\ndef generate_encoders_by_class_tuples(\n type_encoder_map: Dict[Any, Callable[[Any], Any]]\n) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:\n encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(\n tuple\n )\n for type_, encoder in type_encoder_map.items():\n encoders_by_class_tuples[encoder] += (type_,)\n return encoders_by_class_tuples\n\n\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)\n\n\ndef jsonable_encoder(\n obj: Any,\n include: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n by_alias: bool = True,\n exclude_unset: bool = False,\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n custom_encoder: Dict[Any, Callable[[Any], Any]] = {},\n sqlalchemy_safe: bool = True,\n) -> Any:\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, BaseModel):\n encoder = getattr(obj.__config__, \"json_encoders\", {})\n if custom_encoder:\n encoder.update(custom_encoder)\n obj_dict = obj.dict(\n include=include, # type: ignore # in Pydantic\n exclude=exclude, # type: ignore # in Pydantic\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n custom_encoder=encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if dataclasses.is_dataclass(obj):\n return dataclasses.asdict(obj)\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if isinstance(obj, dict):\n encoded_dict = {}\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and ((include and key in include) or not exclude or key not in exclude)\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n", "current_contents": "import dataclasses\nfrom collections import defaultdict\nfrom enum import Enum\nfrom pathlib import PurePath\nfrom types import GeneratorType\nfrom typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union\n\nfrom pydantic import BaseModel\nfrom pydantic.json import ENCODERS_BY_TYPE\n\nSetIntStr = Set[Union[int, str]]\nDictIntStrAny = Dict[Union[int, str], Any]\n\n\ndef generate_encoders_by_class_tuples(\n type_encoder_map: Dict[Any, Callable[[Any], Any]]\n) -> Dict[Callable[[Any], Any], Tuple[Any, ...]]:\n encoders_by_class_tuples: Dict[Callable[[Any], Any], Tuple[Any, ...]] = defaultdict(\n tuple\n )\n for type_, encoder in type_encoder_map.items():\n encoders_by_class_tuples[encoder] += (type_,)\n return encoders_by_class_tuples\n\n\nencoders_by_class_tuples = generate_encoders_by_class_tuples(ENCODERS_BY_TYPE)\n\n\ndef jsonable_encoder(\n obj: Any,\n include: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n exclude: Optional[Union[SetIntStr, DictIntStrAny]] = None,\n by_alias: bool = True,\n exclude_unset: bool = False,\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n custom_encoder: Dict[Any, Callable[[Any], Any]] = {},\n sqlalchemy_safe: bool = True,\n) -> Any:\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, BaseModel):\n encoder = getattr(obj.__config__, \"json_encoders\", {})\n if custom_encoder:\n encoder.update(custom_encoder)\n obj_dict = obj.dict(\n include=include, # type: ignore # in Pydantic\n exclude=exclude, # type: ignore # in Pydantic\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n custom_encoder=encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if isinstance(obj, dict):\n encoded_dict = {}\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and ((include and key in include) or not exclude or key not in exclude)\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,"} {"commit": "b591de2ace297c1da537e50f64b4066f96553247", "message": "✨ Add support for OpenAPI servers metadata (#1547)", "old_file": "fastapi/applications.py", "new_file": "fastapi/applications.py", "status": "M", "old_contents": "from fastapi.utils import warning_response_model_skip_defaults_deprecated\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import Receive, Scope, Send\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n *,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n middleware: Sequence[Middleware] = None,\n exception_handlers: Dict[Union[int, Type[Exception]], Callable] = None,\n on_startup: Sequence[Callable] = None,\n on_shutdown: Sequence[Callable] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.state = State()\n self.router: routing.APIRouter = routing.APIRouter(\n routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n )\n self.exception_handlers = (\n {} if exception_handlers is None else dict(exception_handlers)\n )\n\n self.user_middleware = [] if middleware is None else list(middleware)\n self.middleware_stack = self.build_middleware_stack()\n\n self.title = title\n self.description = description\n self.version = version\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications-proxy/\"\n )\n self.root_path = root_path or openapi_prefix\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n self.setup()\n\n def openapi(self, openapi_prefix: str = \"\") -> Dict:\n if not self.openapi_schema:\n self.openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n openapi_version=self.openapi_version,\n description=self.description,\n routes=self.routes,\n openapi_prefix=openapi_prefix,\n tags=self.openapi_tags,\n )\n return self.openapi_schema\n\n def setup(self) -> None:\n if self.openapi_url:\n\n async def openapi(req: Request) -> JSONResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n return JSONResponse(self.openapi(root_path))\n\n self.add_route(self.openapi_url, openapi, include_in_schema=False)\n if self.openapi_url and self.docs_url:\n\n async def swagger_ui_html(req: Request) -> HTMLResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n openapi_url = root_path + self.openapi_url\n oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url\n if oauth2_redirect_url:\n oauth2_redirect_url = root_path + oauth2_redirect_url\n return get_swagger_ui_html(\n openapi_url=openapi_url,\n title=self.title + \" - Swagger UI\",\n oauth2_redirect_url=oauth2_redirect_url,\n init_oauth=self.swagger_ui_init_oauth,", "new_contents": "from fastapi.utils import warning_response_model_skip_defaults_deprecated\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import Receive, Scope, Send\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n *,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n middleware: Sequence[Middleware] = None,\n exception_handlers: Dict[Union[int, Type[Exception]], Callable] = None,\n on_startup: Sequence[Callable] = None,\n on_shutdown: Sequence[Callable] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.state = State()\n self.router: routing.APIRouter = routing.APIRouter(\n routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n )\n self.exception_handlers = (\n {} if exception_handlers is None else dict(exception_handlers)\n )\n\n self.user_middleware = [] if middleware is None else list(middleware)\n self.middleware_stack = self.build_middleware_stack()\n\n self.title = title\n self.description = description\n self.version = version\n self.servers = servers\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications-proxy/\"\n )\n self.root_path = root_path or openapi_prefix\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n self.setup()\n\n def openapi(self, openapi_prefix: str = \"\") -> Dict:\n if not self.openapi_schema:\n self.openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n openapi_version=self.openapi_version,\n description=self.description,\n routes=self.routes,\n openapi_prefix=openapi_prefix,\n tags=self.openapi_tags,\n servers=self.servers,\n )\n return self.openapi_schema\n\n def setup(self) -> None:\n if self.openapi_url:\n\n async def openapi(req: Request) -> JSONResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n return JSONResponse(self.openapi(root_path))\n\n self.add_route(self.openapi_url, openapi, include_in_schema=False)\n if self.openapi_url and self.docs_url:\n\n async def swagger_ui_html(req: Request) -> HTMLResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n openapi_url = root_path + self.openapi_url\n oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url\n if oauth2_redirect_url:\n oauth2_redirect_url = root_path + oauth2_redirect_url\n return get_swagger_ui_html(\n openapi_url=openapi_url,\n title=self.title + \" - Swagger UI\",\n oauth2_redirect_url=oauth2_redirect_url,\n init_oauth=self.swagger_ui_init_oauth,", "text": "<|original_code|>\nfrom fastapi.utils import warning_response_model_skip_defaults_deprecated\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import Receive, Scope, Send\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n *,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n middleware: Sequence[Middleware] = None,\n exception_handlers: Dict[Union[int, Type[Exception]], Callable] = None,\n on_startup: Sequence[Callable] = None,\n on_shutdown: Sequence[Callable] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.state = State()\n self.router: routing.APIRouter = routing.APIRouter(\n routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n )\n self.exception_handlers = (\n {} if exception_handlers is None else dict(exception_handlers)\n )\n\n self.user_middleware = [] if middleware is None else list(middleware)\n self.middleware_stack = self.build_middleware_stack()\n\n self.title = title\n self.description = description\n self.version = version\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications-proxy/\"\n )\n self.root_path = root_path or openapi_prefix\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n self.setup()\n\n def openapi(self, openapi_prefix: str = \"\") -> Dict:\n if not self.openapi_schema:\n self.openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n openapi_version=self.openapi_version,\n description=self.description,\n routes=self.routes,\n openapi_prefix=openapi_prefix,\n tags=self.openapi_tags,\n )\n return self.openapi_schema\n\n def setup(self) -> None:\n if self.openapi_url:\n\n async def openapi(req: Request) -> JSONResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n return JSONResponse(self.openapi(root_path))\n\n self.add_route(self.openapi_url, openapi, include_in_schema=False)\n if self.openapi_url and self.docs_url:\n\n async def swagger_ui_html(req: Request) -> HTMLResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n openapi_url = root_path + self.openapi_url\n oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url\n if oauth2_redirect_url:\n oauth2_redirect_url = root_path + oauth2_redirect_url\n return get_swagger_ui_html(\n openapi_url=openapi_url,\n title=self.title + \" - Swagger UI\",\n oauth2_redirect_url=oauth2_redirect_url,\n init_oauth=self.swagger_ui_init_oauth,\n<|edits_diff|>\n--- fastapi/applications.py\n+++ fastapi/applications.py\n@@ -20,6 +20,7 @@\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n+ servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n@@ -52,6 +53,7 @@\n self.title = title\n self.description = description\n self.version = version\n+ self.servers = servers\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n # TODO: remove when discarding the openapi_prefix parameter\n<|current_version|>\nfrom fastapi.utils import warning_response_model_skip_defaults_deprecated\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import Receive, Scope, Send\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n *,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n middleware: Sequence[Middleware] = None,\n exception_handlers: Dict[Union[int, Type[Exception]], Callable] = None,\n on_startup: Sequence[Callable] = None,\n on_shutdown: Sequence[Callable] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.state = State()\n self.router: routing.APIRouter = routing.APIRouter(\n routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n )\n self.exception_handlers = (\n {} if exception_handlers is None else dict(exception_handlers)\n )\n\n self.user_middleware = [] if middleware is None else list(middleware)\n self.middleware_stack = self.build_middleware_stack()\n\n self.title = title\n self.description = description\n self.version = version\n self.servers = servers\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications-proxy/\"\n )\n self.root_path = root_path or openapi_prefix\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n self.setup()\n\n def openapi(self, openapi_prefix: str = \"\") -> Dict:\n if not self.openapi_schema:\n self.openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n openapi_version=self.openapi_version,\n description=self.description,\n routes=self.routes,\n openapi_prefix=openapi_prefix,\n tags=self.openapi_tags,\n )\n return self.openapi_schema\n\n def setup(self) -> None:\n if self.openapi_url:\n\n async def openapi(req: Request) -> JSONResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n return JSONResponse(self.openapi(root_path))\n\n self.add_route(self.openapi_url, openapi, include_in_schema=False)\n if self.openapi_url and self.docs_url:\n\n async def swagger_ui_html(req: Request) -> HTMLResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n openapi_url = root_path + self.openapi_url\n oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url\n if oauth2_redirect_url:\n oauth2_redirect_url = root_path + oauth2_redirect_url\n return get_swagger_ui_html(\n openapi_url=openapi_url,\n title=self.title + \" - Swagger UI\",\n oauth2_redirect_url=oauth2_redirect_url,\n init_oauth=self.swagger_ui_init_oauth,\n<|next_version|>\nfrom fastapi.utils import warning_response_model_skip_defaults_deprecated\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import Receive, Scope, Send\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n *,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n middleware: Sequence[Middleware] = None,\n exception_handlers: Dict[Union[int, Type[Exception]], Callable] = None,\n on_startup: Sequence[Callable] = None,\n on_shutdown: Sequence[Callable] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.state = State()\n self.router: routing.APIRouter = routing.APIRouter(\n routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n )\n self.exception_handlers = (\n {} if exception_handlers is None else dict(exception_handlers)\n )\n\n self.user_middleware = [] if middleware is None else list(middleware)\n self.middleware_stack = self.build_middleware_stack()\n\n self.title = title\n self.description = description\n self.version = version\n self.servers = servers\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications-proxy/\"\n )\n self.root_path = root_path or openapi_prefix\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n self.setup()\n\n def openapi(self, openapi_prefix: str = \"\") -> Dict:\n if not self.openapi_schema:\n self.openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n openapi_version=self.openapi_version,\n description=self.description,\n routes=self.routes,\n openapi_prefix=openapi_prefix,\n tags=self.openapi_tags,\n servers=self.servers,\n )\n return self.openapi_schema\n\n def setup(self) -> None:\n if self.openapi_url:\n\n async def openapi(req: Request) -> JSONResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n return JSONResponse(self.openapi(root_path))\n\n self.add_route(self.openapi_url, openapi, include_in_schema=False)\n if self.openapi_url and self.docs_url:\n\n async def swagger_ui_html(req: Request) -> HTMLResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n openapi_url = root_path + self.openapi_url\n oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url\n if oauth2_redirect_url:\n oauth2_redirect_url = root_path + oauth2_redirect_url\n return get_swagger_ui_html(\n openapi_url=openapi_url,\n title=self.title + \" - Swagger UI\",\n oauth2_redirect_url=oauth2_redirect_url,\n init_oauth=self.swagger_ui_init_oauth,\n", "current_contents": "from fastapi.utils import warning_response_model_skip_defaults_deprecated\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware import Middleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\nfrom starlette.types import Receive, Scope, Send\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n *,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n title: str = \"FastAPI\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_tags: Optional[List[Dict[str, Any]]] = None,\n servers: Optional[List[Dict[str, Union[str, Any]]]] = None,\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n middleware: Sequence[Middleware] = None,\n exception_handlers: Dict[Union[int, Type[Exception]], Callable] = None,\n on_startup: Sequence[Callable] = None,\n on_shutdown: Sequence[Callable] = None,\n openapi_prefix: str = \"\",\n root_path: str = \"\",\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.state = State()\n self.router: routing.APIRouter = routing.APIRouter(\n routes,\n dependency_overrides_provider=self,\n on_startup=on_startup,\n on_shutdown=on_shutdown,\n )\n self.exception_handlers = (\n {} if exception_handlers is None else dict(exception_handlers)\n )\n\n self.user_middleware = [] if middleware is None else list(middleware)\n self.middleware_stack = self.build_middleware_stack()\n\n self.title = title\n self.description = description\n self.version = version\n self.servers = servers\n self.openapi_url = openapi_url\n self.openapi_tags = openapi_tags\n # TODO: remove when discarding the openapi_prefix parameter\n if openapi_prefix:\n logger.warning(\n '\"openapi_prefix\" has been deprecated in favor of \"root_path\", which '\n \"follows more closely the ASGI standard, is simpler, and more \"\n \"automatic. Check the docs at \"\n \"https://fastapi.tiangolo.com/advanced/sub-applications-proxy/\"\n )\n self.root_path = root_path or openapi_prefix\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n assert self.version, \"A version must be provided for OpenAPI, e.g.: '2.1.0'\"\n self.openapi_schema: Optional[Dict[str, Any]] = None\n self.setup()\n\n def openapi(self, openapi_prefix: str = \"\") -> Dict:\n if not self.openapi_schema:\n self.openapi_schema = get_openapi(\n title=self.title,\n version=self.version,\n openapi_version=self.openapi_version,\n description=self.description,\n routes=self.routes,\n openapi_prefix=openapi_prefix,\n tags=self.openapi_tags,\n )\n return self.openapi_schema\n\n def setup(self) -> None:\n if self.openapi_url:\n\n async def openapi(req: Request) -> JSONResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n return JSONResponse(self.openapi(root_path))\n\n self.add_route(self.openapi_url, openapi, include_in_schema=False)\n if self.openapi_url and self.docs_url:\n\n async def swagger_ui_html(req: Request) -> HTMLResponse:\n root_path = req.scope.get(\"root_path\", \"\").rstrip(\"/\")\n openapi_url = root_path + self.openapi_url\n oauth2_redirect_url = self.swagger_ui_oauth2_redirect_url\n if oauth2_redirect_url:\n oauth2_redirect_url = root_path + oauth2_redirect_url\n return get_swagger_ui_html(\n openapi_url=openapi_url,\n title=self.title + \" - Swagger UI\",\n oauth2_redirect_url=oauth2_redirect_url,\n init_oauth=self.swagger_ui_init_oauth,"} {"commit": "6c7da43e517afbc4b521429c7908ec3a335bc473", "message": ":arrow_up: Upgrade Starlette to 0.12.9 and add State (#593)", "old_file": "fastapi/applications.py", "new_file": "fastapi/applications.py", "status": "M", "old_contents": "from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union\n\nfrom fastapi import routing\nfrom fastapi.encoders import DictIntStrAny, SetIntStr\nfrom fastapi.exception_handlers import (\n http_exception_handler,\n request_validation_exception_handler,\n)\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.params import Depends\nfrom starlette.applications import Starlette\nfrom starlette.exceptions import ExceptionMiddleware, HTTPException\nfrom starlette.middleware.errors import ServerErrorMiddleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n template_directory: str = None,\n title: str = \"Fast API\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_prefix: str = \"\",\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.router: routing.APIRouter = routing.APIRouter(\n routes, dependency_overrides_provider=self\n )\n self.exception_middleware = ExceptionMiddleware(self.router, debug=debug)\n self.error_middleware = ServerErrorMiddleware(\n self.exception_middleware, debug=debug\n )\n\n self.title = title\n self.description = description\n self.version = version\n self.openapi_url = openapi_url\n self.openapi_prefix = openapi_prefix.rstrip(\"/\")\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"", "new_contents": "from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union\n\nfrom fastapi import routing\nfrom fastapi.encoders import DictIntStrAny, SetIntStr\nfrom fastapi.exception_handlers import (\n http_exception_handler,\n request_validation_exception_handler,\n)\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.params import Depends\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import ExceptionMiddleware, HTTPException\nfrom starlette.middleware.errors import ServerErrorMiddleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n template_directory: str = None,\n title: str = \"Fast API\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_prefix: str = \"\",\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.state = State()\n self.router: routing.APIRouter = routing.APIRouter(\n routes, dependency_overrides_provider=self\n )\n self.exception_middleware = ExceptionMiddleware(self.router, debug=debug)\n self.error_middleware = ServerErrorMiddleware(\n self.exception_middleware, debug=debug\n )\n\n self.title = title\n self.description = description\n self.version = version\n self.openapi_url = openapi_url\n self.openapi_prefix = openapi_prefix.rstrip(\"/\")\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"", "text": "<|original_code|>\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union\n\nfrom fastapi import routing\nfrom fastapi.encoders import DictIntStrAny, SetIntStr\nfrom fastapi.exception_handlers import (\n http_exception_handler,\n request_validation_exception_handler,\n)\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.params import Depends\nfrom starlette.applications import Starlette\nfrom starlette.exceptions import ExceptionMiddleware, HTTPException\nfrom starlette.middleware.errors import ServerErrorMiddleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n template_directory: str = None,\n title: str = \"Fast API\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_prefix: str = \"\",\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.router: routing.APIRouter = routing.APIRouter(\n routes, dependency_overrides_provider=self\n )\n self.exception_middleware = ExceptionMiddleware(self.router, debug=debug)\n self.error_middleware = ServerErrorMiddleware(\n self.exception_middleware, debug=debug\n )\n\n self.title = title\n self.description = description\n self.version = version\n self.openapi_url = openapi_url\n self.openapi_prefix = openapi_prefix.rstrip(\"/\")\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n<|edits_diff|>\n--- fastapi/applications.py\n+++ fastapi/applications.py\n@@ -15,6 +15,7 @@\n from fastapi.openapi.utils import get_openapi\n from fastapi.params import Depends\n from starlette.applications import Starlette\n+from starlette.datastructures import State\n from starlette.exceptions import ExceptionMiddleware, HTTPException\n from starlette.middleware.errors import ServerErrorMiddleware\n from starlette.requests import Request\n<|current_version|>\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union\n\nfrom fastapi import routing\nfrom fastapi.encoders import DictIntStrAny, SetIntStr\nfrom fastapi.exception_handlers import (\n http_exception_handler,\n request_validation_exception_handler,\n)\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.params import Depends\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import ExceptionMiddleware, HTTPException\nfrom starlette.middleware.errors import ServerErrorMiddleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n template_directory: str = None,\n title: str = \"Fast API\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_prefix: str = \"\",\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.router: routing.APIRouter = routing.APIRouter(\n routes, dependency_overrides_provider=self\n )\n self.exception_middleware = ExceptionMiddleware(self.router, debug=debug)\n self.error_middleware = ServerErrorMiddleware(\n self.exception_middleware, debug=debug\n )\n\n self.title = title\n self.description = description\n self.version = version\n self.openapi_url = openapi_url\n self.openapi_prefix = openapi_prefix.rstrip(\"/\")\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n<|next_version|>\nfrom typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union\n\nfrom fastapi import routing\nfrom fastapi.encoders import DictIntStrAny, SetIntStr\nfrom fastapi.exception_handlers import (\n http_exception_handler,\n request_validation_exception_handler,\n)\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.params import Depends\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import ExceptionMiddleware, HTTPException\nfrom starlette.middleware.errors import ServerErrorMiddleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n template_directory: str = None,\n title: str = \"Fast API\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_prefix: str = \"\",\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.state = State()\n self.router: routing.APIRouter = routing.APIRouter(\n routes, dependency_overrides_provider=self\n )\n self.exception_middleware = ExceptionMiddleware(self.router, debug=debug)\n self.error_middleware = ServerErrorMiddleware(\n self.exception_middleware, debug=debug\n )\n\n self.title = title\n self.description = description\n self.version = version\n self.openapi_url = openapi_url\n self.openapi_prefix = openapi_prefix.rstrip(\"/\")\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\"\n", "current_contents": "from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union\n\nfrom fastapi import routing\nfrom fastapi.encoders import DictIntStrAny, SetIntStr\nfrom fastapi.exception_handlers import (\n http_exception_handler,\n request_validation_exception_handler,\n)\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi.openapi.docs import (\n get_redoc_html,\n get_swagger_ui_html,\n get_swagger_ui_oauth2_redirect_html,\n)\nfrom fastapi.openapi.utils import get_openapi\nfrom fastapi.params import Depends\nfrom starlette.applications import Starlette\nfrom starlette.datastructures import State\nfrom starlette.exceptions import ExceptionMiddleware, HTTPException\nfrom starlette.middleware.errors import ServerErrorMiddleware\nfrom starlette.requests import Request\nfrom starlette.responses import HTMLResponse, JSONResponse, Response\nfrom starlette.routing import BaseRoute\n\n\nclass FastAPI(Starlette):\n def __init__(\n self,\n debug: bool = False,\n routes: List[BaseRoute] = None,\n template_directory: str = None,\n title: str = \"Fast API\",\n description: str = \"\",\n version: str = \"0.1.0\",\n openapi_url: Optional[str] = \"/openapi.json\",\n openapi_prefix: str = \"\",\n default_response_class: Type[Response] = JSONResponse,\n docs_url: Optional[str] = \"/docs\",\n redoc_url: Optional[str] = \"/redoc\",\n swagger_ui_oauth2_redirect_url: Optional[str] = \"/docs/oauth2-redirect\",\n swagger_ui_init_oauth: Optional[dict] = None,\n **extra: Dict[str, Any],\n ) -> None:\n self.default_response_class = default_response_class\n self._debug = debug\n self.router: routing.APIRouter = routing.APIRouter(\n routes, dependency_overrides_provider=self\n )\n self.exception_middleware = ExceptionMiddleware(self.router, debug=debug)\n self.error_middleware = ServerErrorMiddleware(\n self.exception_middleware, debug=debug\n )\n\n self.title = title\n self.description = description\n self.version = version\n self.openapi_url = openapi_url\n self.openapi_prefix = openapi_prefix.rstrip(\"/\")\n self.docs_url = docs_url\n self.redoc_url = redoc_url\n self.swagger_ui_oauth2_redirect_url = swagger_ui_oauth2_redirect_url\n self.swagger_ui_init_oauth = swagger_ui_init_oauth\n self.extra = extra\n self.dependency_overrides: Dict[Callable, Callable] = {}\n\n self.openapi_version = \"3.0.2\"\n\n if self.openapi_url:\n assert self.title, \"A title must be provided for OpenAPI, e.g.: 'My API'\""} {"commit": "c90c4fb6c1ed5d8d8f32dd2e31a022a2bb4aca41", "message": ":sparkles: Allow disabling Google fonts in ReDoc (#481)", "old_file": "fastapi/openapi/docs.py", "new_file": "fastapi/openapi/docs.py", "status": "M", "old_contents": " html += \"\"\"\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n deepLinking: true\n })\n \n Free AI Image Generator No sign-up. Instant results. Open Now \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_redoc_html(\n *,\n openapi_url: str,\n title: str,\n redoc_js_url: str = \"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\",\n redoc_favicon_url: str = \"https://fastapi.tiangolo.com/img/favicon.png\",\n) -> HTMLResponse:\n html = f\"\"\"\n \n \n \n {title}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:\n html = \"\"\"\n \n ", "new_contents": " html += \"\"\"\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n deepLinking: true\n })\n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_redoc_html(\n *,\n openapi_url: str,\n title: str,\n redoc_js_url: str = \"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\",\n redoc_favicon_url: str = \"https://fastapi.tiangolo.com/img/favicon.png\",\n with_google_fonts: bool = True,\n) -> HTMLResponse:\n html = f\"\"\"\n \n \n \n {title}\n \n \n \n \"\"\"\n if with_google_fonts:\n html += \"\"\"\n \n \"\"\"\n html += f\"\"\"\n \n \n \n \n \n \n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:\n html = \"\"\"\n \n ", "text": "<|original_code|>\n html += \"\"\"\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n deepLinking: true\n })\n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_redoc_html(\n *,\n openapi_url: str,\n title: str,\n redoc_js_url: str = \"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\",\n redoc_favicon_url: str = \"https://fastapi.tiangolo.com/img/favicon.png\",\n) -> HTMLResponse:\n html = f\"\"\"\n \n \n \n {title}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:\n html = \"\"\"\n \n \n<|edits_diff|>\n--- fastapi/openapi/docs.py\n+++ fastapi/openapi/docs.py\n@@ -20,6 +20,7 @@\n title: str,\n redoc_js_url: str = \"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\",\n redoc_favicon_url: str = \"https://fastapi.tiangolo.com/img/favicon.png\",\n+ with_google_fonts: bool = True,\n ) -> HTMLResponse:\n html = f\"\"\"\n \n@@ -29,6 +30,9 @@\n \n \n \n+ \"\"\"\n+ if with_google_fonts:\n+ html += \"\"\"\n \n \n \n \n \n \"\"\"\n if with_google_fonts:\n html += \"\"\"\n \n \n \n \n \n \n \n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:\n html = \"\"\"\n \n \n<|next_version|>\n html += \"\"\"\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n deepLinking: true\n })\n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_redoc_html(\n *,\n openapi_url: str,\n title: str,\n redoc_js_url: str = \"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\",\n redoc_favicon_url: str = \"https://fastapi.tiangolo.com/img/favicon.png\",\n with_google_fonts: bool = True,\n) -> HTMLResponse:\n html = f\"\"\"\n \n \n \n {title}\n \n \n \n \"\"\"\n if with_google_fonts:\n html += \"\"\"\n \n \"\"\"\n html += f\"\"\"\n \n \n \n \n \n \n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:\n html = \"\"\"\n \n \n", "current_contents": " html += \"\"\"\n dom_id: '#swagger-ui',\n presets: [\n SwaggerUIBundle.presets.apis,\n SwaggerUIBundle.SwaggerUIStandalonePreset\n ],\n layout: \"BaseLayout\",\n deepLinking: true\n })\n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_redoc_html(\n *,\n openapi_url: str,\n title: str,\n redoc_js_url: str = \"https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js\",\n redoc_favicon_url: str = \"https://fastapi.tiangolo.com/img/favicon.png\",\n with_google_fonts: bool = True,\n) -> HTMLResponse:\n html = f\"\"\"\n \n \n \n {title}\n \n \n \n \"\"\"\n if with_google_fonts:\n html += \"\"\"\n \n \n \n \n \n \n \n \n \n \n \"\"\"\n return HTMLResponse(html)\n\n\ndef get_swagger_ui_oauth2_redirect_html() -> HTMLResponse:\n html = \"\"\"\n \n "} {"commit": "90af86814637a2384fe81fcc7cca394c13d9170a", "message": ":sparkles: Add security checks for HTTP utils", "old_file": "fastapi/security/http.py", "new_file": "fastapi/security/http.py", "status": "M", "old_contents": " try:\n data = b64decode(param).decode(\"ascii\")\n except (ValueError, UnicodeDecodeError, binascii.Error):\n raise invalid_user_credentials_exc\n username, separator, password = data.partition(\":\")\n if not (separator):\n raise invalid_user_credentials_exc\n return HTTPBasicCredentials(username=username, password=password)\n\n\nclass HTTPBearer(HTTPBase):\n def __init__(self, *, bearerFormat: str = None, scheme_name: str = None):\n self.model = HTTPBearerModel(bearerFormat=bearerFormat)\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n\nclass HTTPDigest(HTTPBase):\n def __init__(self, *, scheme_name: str = None):\n self.model = HTTPBaseModel(scheme=\"digest\")\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n", "new_contents": " try:\n data = b64decode(param).decode(\"ascii\")\n except (ValueError, UnicodeDecodeError, binascii.Error):\n raise invalid_user_credentials_exc\n username, separator, password = data.partition(\":\")\n if not (separator):\n raise invalid_user_credentials_exc\n return HTTPBasicCredentials(username=username, password=password)\n\n\nclass HTTPBearer(HTTPBase):\n def __init__(self, *, bearerFormat: str = None, scheme_name: str = None):\n self.model = HTTPBearerModel(bearerFormat=bearerFormat)\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n if scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN,\n detail=\"Invalid authentication credentials\",\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n\nclass HTTPDigest(HTTPBase):\n def __init__(self, *, scheme_name: str = None):\n self.model = HTTPBaseModel(scheme=\"digest\")\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n if scheme.lower() != \"digest\":\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN,\n detail=\"Invalid authentication credentials\",\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n", "text": "<|original_code|>\n try:\n data = b64decode(param).decode(\"ascii\")\n except (ValueError, UnicodeDecodeError, binascii.Error):\n raise invalid_user_credentials_exc\n username, separator, password = data.partition(\":\")\n if not (separator):\n raise invalid_user_credentials_exc\n return HTTPBasicCredentials(username=username, password=password)\n\n\nclass HTTPBearer(HTTPBase):\n def __init__(self, *, bearerFormat: str = None, scheme_name: str = None):\n self.model = HTTPBearerModel(bearerFormat=bearerFormat)\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n\nclass HTTPDigest(HTTPBase):\n def __init__(self, *, scheme_name: str = None):\n self.model = HTTPBaseModel(scheme=\"digest\")\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n<|edits_diff|>\n--- fastapi/security/http.py\n+++ fastapi/security/http.py\n@@ -20,6 +20,11 @@\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n+ if scheme.lower() != \"bearer\":\n+ raise HTTPException(\n+ status_code=HTTP_403_FORBIDDEN,\n+ detail=\"Invalid authentication credentials\",\n+ )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n \n \n<|current_version|>\n try:\n data = b64decode(param).decode(\"ascii\")\n except (ValueError, UnicodeDecodeError, binascii.Error):\n raise invalid_user_credentials_exc\n username, separator, password = data.partition(\":\")\n if not (separator):\n raise invalid_user_credentials_exc\n return HTTPBasicCredentials(username=username, password=password)\n\n\nclass HTTPBearer(HTTPBase):\n def __init__(self, *, bearerFormat: str = None, scheme_name: str = None):\n self.model = HTTPBearerModel(bearerFormat=bearerFormat)\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n if scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN,\n detail=\"Invalid authentication credentials\",\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n\nclass HTTPDigest(HTTPBase):\n def __init__(self, *, scheme_name: str = None):\n self.model = HTTPBaseModel(scheme=\"digest\")\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n<|next_version|>\n try:\n data = b64decode(param).decode(\"ascii\")\n except (ValueError, UnicodeDecodeError, binascii.Error):\n raise invalid_user_credentials_exc\n username, separator, password = data.partition(\":\")\n if not (separator):\n raise invalid_user_credentials_exc\n return HTTPBasicCredentials(username=username, password=password)\n\n\nclass HTTPBearer(HTTPBase):\n def __init__(self, *, bearerFormat: str = None, scheme_name: str = None):\n self.model = HTTPBearerModel(bearerFormat=bearerFormat)\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n if scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN,\n detail=\"Invalid authentication credentials\",\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n\nclass HTTPDigest(HTTPBase):\n def __init__(self, *, scheme_name: str = None):\n self.model = HTTPBaseModel(scheme=\"digest\")\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n if scheme.lower() != \"digest\":\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN,\n detail=\"Invalid authentication credentials\",\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n", "current_contents": " try:\n data = b64decode(param).decode(\"ascii\")\n except (ValueError, UnicodeDecodeError, binascii.Error):\n raise invalid_user_credentials_exc\n username, separator, password = data.partition(\":\")\n if not (separator):\n raise invalid_user_credentials_exc\n return HTTPBasicCredentials(username=username, password=password)\n\n\nclass HTTPBearer(HTTPBase):\n def __init__(self, *, bearerFormat: str = None, scheme_name: str = None):\n self.model = HTTPBearerModel(bearerFormat=bearerFormat)\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n if scheme.lower() != \"bearer\":\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN,\n detail=\"Invalid authentication credentials\",\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n\n\nclass HTTPDigest(HTTPBase):\n def __init__(self, *, scheme_name: str = None):\n self.model = HTTPBaseModel(scheme=\"digest\")\n self.scheme_name = scheme_name or self.__class__.__name__\n\n async def __call__(self, request: Request) -> str:\n authorization: str = request.headers.get(\"Authorization\")\n scheme, credentials = get_authorization_scheme_param(authorization)\n if not (authorization and scheme and credentials):\n raise HTTPException(\n status_code=HTTP_403_FORBIDDEN, detail=\"Not authenticated\"\n )\n return HTTPAuthorizationCredentials(scheme=scheme, credentials=credentials)\n"} {"commit": "252188c6868942071aa9959fe505aef2ee90896f", "message": ":white_check_mark: Update tests for HTML content and remove unneeded tests", "old_file": "tests/test_application.py", "new_file": "tests/test_application.py", "status": "M", "old_contents": " },\n },\n}\n\n\n@pytest.mark.parametrize(\n \"path,expected_status,expected_response\",\n [\n (\"/api_route\", 200, {\"message\": \"Hello World\"}),\n (\"/nonexistent\", 404, {\"detail\": \"Not Found\"}),\n (\"/openapi.json\", 200, openapi_schema),\n ],\n)\ndef test_get_path(path, expected_status, expected_response):\n response = client.get(path)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n\n\ndef test_swagger_ui():\n response = client.get(\"/docs\")\n assert response.status_code == 200\n assert \"swagger-ui-dist\" in response.text\n\n\ndef test_redoc():\n response = client.get(\"/redoc\")\n assert response.status_code == 200\n assert \"redoc@next\" in response.text\n", "new_contents": " },\n },\n}\n\n\n@pytest.mark.parametrize(\n \"path,expected_status,expected_response\",\n [\n (\"/api_route\", 200, {\"message\": \"Hello World\"}),\n (\"/nonexistent\", 404, {\"detail\": \"Not Found\"}),\n (\"/openapi.json\", 200, openapi_schema),\n ],\n)\ndef test_get_path(path, expected_status, expected_response):\n response = client.get(path)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n\n\ndef test_swagger_ui():\n response = client.get(\"/docs\")\n assert response.status_code == 200\n assert response.headers[\"content-type\"] == \"text/html; charset=utf-8\"\n assert \"swagger-ui-dist\" in response.text\n\n\ndef test_redoc():\n response = client.get(\"/redoc\")\n assert response.status_code == 200\n assert response.headers[\"content-type\"] == \"text/html; charset=utf-8\"\n assert \"redoc@next\" in response.text\n", "text": "<|original_code|>\n },\n },\n}\n\n\n@pytest.mark.parametrize(\n \"path,expected_status,expected_response\",\n [\n (\"/api_route\", 200, {\"message\": \"Hello World\"}),\n (\"/nonexistent\", 404, {\"detail\": \"Not Found\"}),\n (\"/openapi.json\", 200, openapi_schema),\n ],\n)\ndef test_get_path(path, expected_status, expected_response):\n response = client.get(path)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n\n\ndef test_swagger_ui():\n response = client.get(\"/docs\")\n assert response.status_code == 200\n assert \"swagger-ui-dist\" in response.text\n\n\ndef test_redoc():\n response = client.get(\"/redoc\")\n assert response.status_code == 200\n assert \"redoc@next\" in response.text\n\n<|edits_diff|>\n--- tests/test_application.py\n+++ tests/test_application.py\n@@ -20,6 +20,7 @@\n def test_swagger_ui():\n response = client.get(\"/docs\")\n assert response.status_code == 200\n+ assert response.headers[\"content-type\"] == \"text/html; charset=utf-8\"\n assert \"swagger-ui-dist\" in response.text\n \n \n<|current_version|>\n },\n },\n}\n\n\n@pytest.mark.parametrize(\n \"path,expected_status,expected_response\",\n [\n (\"/api_route\", 200, {\"message\": \"Hello World\"}),\n (\"/nonexistent\", 404, {\"detail\": \"Not Found\"}),\n (\"/openapi.json\", 200, openapi_schema),\n ],\n)\ndef test_get_path(path, expected_status, expected_response):\n response = client.get(path)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n\n\ndef test_swagger_ui():\n response = client.get(\"/docs\")\n assert response.status_code == 200\n assert response.headers[\"content-type\"] == \"text/html; charset=utf-8\"\n assert \"swagger-ui-dist\" in response.text\n\n\ndef test_redoc():\n response = client.get(\"/redoc\")\n assert response.status_code == 200\n assert \"redoc@next\" in response.text\n\n<|next_version|>\n },\n },\n}\n\n\n@pytest.mark.parametrize(\n \"path,expected_status,expected_response\",\n [\n (\"/api_route\", 200, {\"message\": \"Hello World\"}),\n (\"/nonexistent\", 404, {\"detail\": \"Not Found\"}),\n (\"/openapi.json\", 200, openapi_schema),\n ],\n)\ndef test_get_path(path, expected_status, expected_response):\n response = client.get(path)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n\n\ndef test_swagger_ui():\n response = client.get(\"/docs\")\n assert response.status_code == 200\n assert response.headers[\"content-type\"] == \"text/html; charset=utf-8\"\n assert \"swagger-ui-dist\" in response.text\n\n\ndef test_redoc():\n response = client.get(\"/redoc\")\n assert response.status_code == 200\n assert response.headers[\"content-type\"] == \"text/html; charset=utf-8\"\n assert \"redoc@next\" in response.text\n\n", "current_contents": " },\n },\n}\n\n\n@pytest.mark.parametrize(\n \"path,expected_status,expected_response\",\n [\n (\"/api_route\", 200, {\"message\": \"Hello World\"}),\n (\"/nonexistent\", 404, {\"detail\": \"Not Found\"}),\n (\"/openapi.json\", 200, openapi_schema),\n ],\n)\ndef test_get_path(path, expected_status, expected_response):\n response = client.get(path)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n\n\ndef test_swagger_ui():\n response = client.get(\"/docs\")\n assert response.status_code == 200\n assert response.headers[\"content-type\"] == \"text/html; charset=utf-8\"\n assert \"swagger-ui-dist\" in response.text\n\n\ndef test_redoc():\n response = client.get(\"/redoc\")\n assert response.status_code == 200\n assert \"redoc@next\" in response.text\n"} {"commit": "0dbbac961ee251309aa7ec6deee658da83b0eaf0", "message": "Gaussian mixture lower bounds (#28559)", "old_file": "sklearn/mixture/_base.py", "new_file": "sklearn/mixture/_base.py", "status": "M", "old_contents": " y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n labels : array, shape (n_samples,)\n Component labels.\n \"\"\"\n X = validate_data(self, X, dtype=[np.float64, np.float32], ensure_min_samples=2)\n if X.shape[0] < self.n_components:\n raise ValueError(\n \"Expected n_samples >= n_components \"\n f\"but got n_components = {self.n_components}, \"\n f\"n_samples = {X.shape[0]}\"\n )\n self._check_parameters(X)\n\n # if we enable warm_start, we will have a unique initialisation\n do_init = not (self.warm_start and hasattr(self, \"converged_\"))\n n_init = self.n_init if do_init else 1\n\n max_lower_bound = -np.inf\n self.converged_ = False\n\n random_state = check_random_state(self.random_state)\n\n n_samples, _ = X.shape\n for init in range(n_init):\n self._print_verbose_msg_init_beg(init)\n\n if do_init:\n self._initialize_parameters(X, random_state)\n\n lower_bound = -np.inf if do_init else self.lower_bound_\n\n if self.max_iter == 0:\n best_params = self._get_parameters()\n best_n_iter = 0\n else:\n converged = False\n for n_iter in range(1, self.max_iter + 1):\n prev_lower_bound = lower_bound\n\n log_prob_norm, log_resp = self._e_step(X)\n self._m_step(X, log_resp)\n lower_bound = self._compute_lower_bound(log_resp, log_prob_norm)\n\n change = lower_bound - prev_lower_bound\n self._print_verbose_msg_iter_end(n_iter, change)\n\n if abs(change) < self.tol:\n converged = True\n break\n\n self._print_verbose_msg_init_end(lower_bound, converged)\n\n if lower_bound > max_lower_bound or max_lower_bound == -np.inf:\n max_lower_bound = lower_bound\n best_params = self._get_parameters()\n best_n_iter = n_iter\n self.converged_ = converged\n\n # Should only warn about convergence if max_iter > 0, otherwise\n # the user is assumed to have used 0-iters initialization\n # to get the initial means.\n if not self.converged_ and self.max_iter > 0:\n warnings.warn(\n (\n \"Best performing initialization did not converge. \"\n \"Try different init parameters, or increase max_iter, \"\n \"tol, or check for degenerate data.\"\n ),\n ConvergenceWarning,\n )\n\n self._set_parameters(best_params)\n self.n_iter_ = best_n_iter\n self.lower_bound_ = max_lower_bound\n\n # Always do a final e-step to guarantee that the labels returned by\n # fit_predict(X) are always consistent with fit(X).predict(X)\n # for any value of max_iter and tol (and any random_state).\n _, log_resp = self._e_step(X)\n\n return log_resp.argmax(axis=1)\n\n def _e_step(self, X):\n \"\"\"E step.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n\n Returns\n -------\n log_prob_norm : float\n Mean of the logarithms of the probabilities of each sample in X\n\n log_responsibility : array, shape (n_samples, n_components)\n Logarithm of the posterior probabilities (or responsibilities) of\n the point of each sample in X.\n \"\"\"", "new_contents": " y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n labels : array, shape (n_samples,)\n Component labels.\n \"\"\"\n X = validate_data(self, X, dtype=[np.float64, np.float32], ensure_min_samples=2)\n if X.shape[0] < self.n_components:\n raise ValueError(\n \"Expected n_samples >= n_components \"\n f\"but got n_components = {self.n_components}, \"\n f\"n_samples = {X.shape[0]}\"\n )\n self._check_parameters(X)\n\n # if we enable warm_start, we will have a unique initialisation\n do_init = not (self.warm_start and hasattr(self, \"converged_\"))\n n_init = self.n_init if do_init else 1\n\n max_lower_bound = -np.inf\n best_lower_bounds = []\n self.converged_ = False\n\n random_state = check_random_state(self.random_state)\n\n n_samples, _ = X.shape\n for init in range(n_init):\n self._print_verbose_msg_init_beg(init)\n\n if do_init:\n self._initialize_parameters(X, random_state)\n\n lower_bound = -np.inf if do_init else self.lower_bound_\n current_lower_bounds = []\n\n if self.max_iter == 0:\n best_params = self._get_parameters()\n best_n_iter = 0\n else:\n converged = False\n for n_iter in range(1, self.max_iter + 1):\n prev_lower_bound = lower_bound\n\n log_prob_norm, log_resp = self._e_step(X)\n self._m_step(X, log_resp)\n lower_bound = self._compute_lower_bound(log_resp, log_prob_norm)\n current_lower_bounds.append(lower_bound)\n\n change = lower_bound - prev_lower_bound\n self._print_verbose_msg_iter_end(n_iter, change)\n\n if abs(change) < self.tol:\n converged = True\n break\n\n self._print_verbose_msg_init_end(lower_bound, converged)\n\n if lower_bound > max_lower_bound or max_lower_bound == -np.inf:\n max_lower_bound = lower_bound\n best_params = self._get_parameters()\n best_n_iter = n_iter\n best_lower_bounds = current_lower_bounds\n self.converged_ = converged\n\n # Should only warn about convergence if max_iter > 0, otherwise\n # the user is assumed to have used 0-iters initialization\n # to get the initial means.\n if not self.converged_ and self.max_iter > 0:\n warnings.warn(\n (\n \"Best performing initialization did not converge. \"\n \"Try different init parameters, or increase max_iter, \"\n \"tol, or check for degenerate data.\"\n ),\n ConvergenceWarning,\n )\n\n self._set_parameters(best_params)\n self.n_iter_ = best_n_iter\n self.lower_bound_ = max_lower_bound\n self.lower_bounds_ = best_lower_bounds\n\n # Always do a final e-step to guarantee that the labels returned by\n # fit_predict(X) are always consistent with fit(X).predict(X)\n # for any value of max_iter and tol (and any random_state).\n _, log_resp = self._e_step(X)\n\n return log_resp.argmax(axis=1)\n\n def _e_step(self, X):\n \"\"\"E step.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n\n Returns\n -------\n log_prob_norm : float\n Mean of the logarithms of the probabilities of each sample in X\n\n log_responsibility : array, shape (n_samples, n_components)\n Logarithm of the posterior probabilities (or responsibilities) of\n the point of each sample in X.\n \"\"\"", "text": "<|original_code|>\n y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n labels : array, shape (n_samples,)\n Component labels.\n \"\"\"\n X = validate_data(self, X, dtype=[np.float64, np.float32], ensure_min_samples=2)\n if X.shape[0] < self.n_components:\n raise ValueError(\n \"Expected n_samples >= n_components \"\n f\"but got n_components = {self.n_components}, \"\n f\"n_samples = {X.shape[0]}\"\n )\n self._check_parameters(X)\n\n # if we enable warm_start, we will have a unique initialisation\n do_init = not (self.warm_start and hasattr(self, \"converged_\"))\n n_init = self.n_init if do_init else 1\n\n max_lower_bound = -np.inf\n self.converged_ = False\n\n random_state = check_random_state(self.random_state)\n\n n_samples, _ = X.shape\n for init in range(n_init):\n self._print_verbose_msg_init_beg(init)\n\n if do_init:\n self._initialize_parameters(X, random_state)\n\n lower_bound = -np.inf if do_init else self.lower_bound_\n\n if self.max_iter == 0:\n best_params = self._get_parameters()\n best_n_iter = 0\n else:\n converged = False\n for n_iter in range(1, self.max_iter + 1):\n prev_lower_bound = lower_bound\n\n log_prob_norm, log_resp = self._e_step(X)\n self._m_step(X, log_resp)\n lower_bound = self._compute_lower_bound(log_resp, log_prob_norm)\n\n change = lower_bound - prev_lower_bound\n self._print_verbose_msg_iter_end(n_iter, change)\n\n if abs(change) < self.tol:\n converged = True\n break\n\n self._print_verbose_msg_init_end(lower_bound, converged)\n\n if lower_bound > max_lower_bound or max_lower_bound == -np.inf:\n max_lower_bound = lower_bound\n best_params = self._get_parameters()\n best_n_iter = n_iter\n self.converged_ = converged\n\n # Should only warn about convergence if max_iter > 0, otherwise\n # the user is assumed to have used 0-iters initialization\n # to get the initial means.\n if not self.converged_ and self.max_iter > 0:\n warnings.warn(\n (\n \"Best performing initialization did not converge. \"\n \"Try different init parameters, or increase max_iter, \"\n \"tol, or check for degenerate data.\"\n ),\n ConvergenceWarning,\n )\n\n self._set_parameters(best_params)\n self.n_iter_ = best_n_iter\n self.lower_bound_ = max_lower_bound\n\n # Always do a final e-step to guarantee that the labels returned by\n # fit_predict(X) are always consistent with fit(X).predict(X)\n # for any value of max_iter and tol (and any random_state).\n _, log_resp = self._e_step(X)\n\n return log_resp.argmax(axis=1)\n\n def _e_step(self, X):\n \"\"\"E step.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n\n Returns\n -------\n log_prob_norm : float\n Mean of the logarithms of the probabilities of each sample in X\n\n log_responsibility : array, shape (n_samples, n_components)\n Logarithm of the posterior probabilities (or responsibilities) of\n the point of each sample in X.\n \"\"\"\n<|edits_diff|>\n--- sklearn/mixture/_base.py\n+++ sklearn/mixture/_base.py\n@@ -20,6 +20,7 @@\n n_init = self.n_init if do_init else 1\n \n max_lower_bound = -np.inf\n+ best_lower_bounds = []\n self.converged_ = False\n \n random_state = check_random_state(self.random_state)\n@@ -32,6 +33,7 @@\n self._initialize_parameters(X, random_state)\n \n lower_bound = -np.inf if do_init else self.lower_bound_\n+ current_lower_bounds = []\n \n if self.max_iter == 0:\n best_params = self._get_parameters()\n@@ -44,6 +46,7 @@\n log_prob_norm, log_resp = self._e_step(X)\n self._m_step(X, log_resp)\n lower_bound = self._compute_lower_bound(log_resp, log_prob_norm)\n+ current_lower_bounds.append(lower_bound)\n \n change = lower_bound - prev_lower_bound\n self._print_verbose_msg_iter_end(n_iter, change)\n@@ -58,6 +61,7 @@\n max_lower_bound = lower_bound\n best_params = self._get_parameters()\n best_n_iter = n_iter\n+ best_lower_bounds = current_lower_bounds\n self.converged_ = converged\n \n # Should only warn about convergence if max_iter > 0, otherwise\n<|current_version|>\n y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n labels : array, shape (n_samples,)\n Component labels.\n \"\"\"\n X = validate_data(self, X, dtype=[np.float64, np.float32], ensure_min_samples=2)\n if X.shape[0] < self.n_components:\n raise ValueError(\n \"Expected n_samples >= n_components \"\n f\"but got n_components = {self.n_components}, \"\n f\"n_samples = {X.shape[0]}\"\n )\n self._check_parameters(X)\n\n # if we enable warm_start, we will have a unique initialisation\n do_init = not (self.warm_start and hasattr(self, \"converged_\"))\n n_init = self.n_init if do_init else 1\n\n max_lower_bound = -np.inf\n best_lower_bounds = []\n self.converged_ = False\n\n random_state = check_random_state(self.random_state)\n\n n_samples, _ = X.shape\n for init in range(n_init):\n self._print_verbose_msg_init_beg(init)\n\n if do_init:\n self._initialize_parameters(X, random_state)\n\n lower_bound = -np.inf if do_init else self.lower_bound_\n current_lower_bounds = []\n\n if self.max_iter == 0:\n best_params = self._get_parameters()\n best_n_iter = 0\n else:\n converged = False\n for n_iter in range(1, self.max_iter + 1):\n prev_lower_bound = lower_bound\n\n log_prob_norm, log_resp = self._e_step(X)\n self._m_step(X, log_resp)\n lower_bound = self._compute_lower_bound(log_resp, log_prob_norm)\n current_lower_bounds.append(lower_bound)\n\n change = lower_bound - prev_lower_bound\n self._print_verbose_msg_iter_end(n_iter, change)\n\n if abs(change) < self.tol:\n converged = True\n break\n\n self._print_verbose_msg_init_end(lower_bound, converged)\n\n if lower_bound > max_lower_bound or max_lower_bound == -np.inf:\n max_lower_bound = lower_bound\n best_params = self._get_parameters()\n best_n_iter = n_iter\n best_lower_bounds = current_lower_bounds\n self.converged_ = converged\n\n # Should only warn about convergence if max_iter > 0, otherwise\n # the user is assumed to have used 0-iters initialization\n # to get the initial means.\n if not self.converged_ and self.max_iter > 0:\n warnings.warn(\n (\n \"Best performing initialization did not converge. \"\n \"Try different init parameters, or increase max_iter, \"\n \"tol, or check for degenerate data.\"\n ),\n ConvergenceWarning,\n )\n\n self._set_parameters(best_params)\n self.n_iter_ = best_n_iter\n self.lower_bound_ = max_lower_bound\n\n # Always do a final e-step to guarantee that the labels returned by\n # fit_predict(X) are always consistent with fit(X).predict(X)\n # for any value of max_iter and tol (and any random_state).\n _, log_resp = self._e_step(X)\n\n return log_resp.argmax(axis=1)\n\n def _e_step(self, X):\n \"\"\"E step.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n\n Returns\n -------\n log_prob_norm : float\n Mean of the logarithms of the probabilities of each sample in X\n\n log_responsibility : array, shape (n_samples, n_components)\n Logarithm of the posterior probabilities (or responsibilities) of\n the point of each sample in X.\n \"\"\"\n<|next_version|>\n y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n labels : array, shape (n_samples,)\n Component labels.\n \"\"\"\n X = validate_data(self, X, dtype=[np.float64, np.float32], ensure_min_samples=2)\n if X.shape[0] < self.n_components:\n raise ValueError(\n \"Expected n_samples >= n_components \"\n f\"but got n_components = {self.n_components}, \"\n f\"n_samples = {X.shape[0]}\"\n )\n self._check_parameters(X)\n\n # if we enable warm_start, we will have a unique initialisation\n do_init = not (self.warm_start and hasattr(self, \"converged_\"))\n n_init = self.n_init if do_init else 1\n\n max_lower_bound = -np.inf\n best_lower_bounds = []\n self.converged_ = False\n\n random_state = check_random_state(self.random_state)\n\n n_samples, _ = X.shape\n for init in range(n_init):\n self._print_verbose_msg_init_beg(init)\n\n if do_init:\n self._initialize_parameters(X, random_state)\n\n lower_bound = -np.inf if do_init else self.lower_bound_\n current_lower_bounds = []\n\n if self.max_iter == 0:\n best_params = self._get_parameters()\n best_n_iter = 0\n else:\n converged = False\n for n_iter in range(1, self.max_iter + 1):\n prev_lower_bound = lower_bound\n\n log_prob_norm, log_resp = self._e_step(X)\n self._m_step(X, log_resp)\n lower_bound = self._compute_lower_bound(log_resp, log_prob_norm)\n current_lower_bounds.append(lower_bound)\n\n change = lower_bound - prev_lower_bound\n self._print_verbose_msg_iter_end(n_iter, change)\n\n if abs(change) < self.tol:\n converged = True\n break\n\n self._print_verbose_msg_init_end(lower_bound, converged)\n\n if lower_bound > max_lower_bound or max_lower_bound == -np.inf:\n max_lower_bound = lower_bound\n best_params = self._get_parameters()\n best_n_iter = n_iter\n best_lower_bounds = current_lower_bounds\n self.converged_ = converged\n\n # Should only warn about convergence if max_iter > 0, otherwise\n # the user is assumed to have used 0-iters initialization\n # to get the initial means.\n if not self.converged_ and self.max_iter > 0:\n warnings.warn(\n (\n \"Best performing initialization did not converge. \"\n \"Try different init parameters, or increase max_iter, \"\n \"tol, or check for degenerate data.\"\n ),\n ConvergenceWarning,\n )\n\n self._set_parameters(best_params)\n self.n_iter_ = best_n_iter\n self.lower_bound_ = max_lower_bound\n self.lower_bounds_ = best_lower_bounds\n\n # Always do a final e-step to guarantee that the labels returned by\n # fit_predict(X) are always consistent with fit(X).predict(X)\n # for any value of max_iter and tol (and any random_state).\n _, log_resp = self._e_step(X)\n\n return log_resp.argmax(axis=1)\n\n def _e_step(self, X):\n \"\"\"E step.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n\n Returns\n -------\n log_prob_norm : float\n Mean of the logarithms of the probabilities of each sample in X\n\n log_responsibility : array, shape (n_samples, n_components)\n Logarithm of the posterior probabilities (or responsibilities) of\n the point of each sample in X.\n \"\"\"\n", "current_contents": " y : Ignored\n Not used, present for API consistency by convention.\n\n Returns\n -------\n labels : array, shape (n_samples,)\n Component labels.\n \"\"\"\n X = validate_data(self, X, dtype=[np.float64, np.float32], ensure_min_samples=2)\n if X.shape[0] < self.n_components:\n raise ValueError(\n \"Expected n_samples >= n_components \"\n f\"but got n_components = {self.n_components}, \"\n f\"n_samples = {X.shape[0]}\"\n )\n self._check_parameters(X)\n\n # if we enable warm_start, we will have a unique initialisation\n do_init = not (self.warm_start and hasattr(self, \"converged_\"))\n n_init = self.n_init if do_init else 1\n\n max_lower_bound = -np.inf\n best_lower_bounds = []\n self.converged_ = False\n\n random_state = check_random_state(self.random_state)\n\n n_samples, _ = X.shape\n for init in range(n_init):\n self._print_verbose_msg_init_beg(init)\n\n if do_init:\n self._initialize_parameters(X, random_state)\n\n lower_bound = -np.inf if do_init else self.lower_bound_\n current_lower_bounds = []\n\n if self.max_iter == 0:\n best_params = self._get_parameters()\n best_n_iter = 0\n else:\n converged = False\n for n_iter in range(1, self.max_iter + 1):\n prev_lower_bound = lower_bound\n\n log_prob_norm, log_resp = self._e_step(X)\n self._m_step(X, log_resp)\n lower_bound = self._compute_lower_bound(log_resp, log_prob_norm)\n current_lower_bounds.append(lower_bound)\n\n change = lower_bound - prev_lower_bound\n self._print_verbose_msg_iter_end(n_iter, change)\n\n if abs(change) < self.tol:\n converged = True\n break\n\n self._print_verbose_msg_init_end(lower_bound, converged)\n\n if lower_bound > max_lower_bound or max_lower_bound == -np.inf:\n max_lower_bound = lower_bound\n best_params = self._get_parameters()\n best_n_iter = n_iter\n best_lower_bounds = current_lower_bounds\n self.converged_ = converged\n\n # Should only warn about convergence if max_iter > 0, otherwise\n # the user is assumed to have used 0-iters initialization\n # to get the initial means.\n if not self.converged_ and self.max_iter > 0:\n warnings.warn(\n (\n \"Best performing initialization did not converge. \"\n \"Try different init parameters, or increase max_iter, \"\n \"tol, or check for degenerate data.\"\n ),\n ConvergenceWarning,\n )\n\n self._set_parameters(best_params)\n self.n_iter_ = best_n_iter\n self.lower_bound_ = max_lower_bound\n\n # Always do a final e-step to guarantee that the labels returned by\n # fit_predict(X) are always consistent with fit(X).predict(X)\n # for any value of max_iter and tol (and any random_state).\n _, log_resp = self._e_step(X)\n\n return log_resp.argmax(axis=1)\n\n def _e_step(self, X):\n \"\"\"E step.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n\n Returns\n -------\n log_prob_norm : float\n Mean of the logarithms of the probabilities of each sample in X\n\n log_responsibility : array, shape (n_samples, n_components)\n Logarithm of the posterior probabilities (or responsibilities) of\n the point of each sample in X.\n \"\"\""} {"commit": "d38a7e3103be4f65164c69b8ad7ad51fb9ca061e", "message": "TST Extend tests for `scipy.sparse/*array` in `sklearn/neighbors/tests/test_neighbors` (#27250)", "old_file": "sklearn/utils/fixes.py", "new_file": "sklearn/utils/fixes.py", "status": "M", "old_contents": "import scipy.sparse.linalg\nimport scipy.stats\nimport threadpoolctl\n\nimport sklearn\n\nfrom ..externals._packaging.version import parse as parse_version\nfrom .deprecation import deprecated\n\nnp_version = parse_version(np.__version__)\nnp_base_version = parse_version(np_version.base_version)\nsp_version = parse_version(scipy.__version__)\nsp_base_version = parse_version(sp_version.base_version)\n\n# TODO: We can consider removing the containers and importing\n# directly from SciPy when sparse matrices will be deprecated.\nCSR_CONTAINERS = [scipy.sparse.csr_matrix]\nCSC_CONTAINERS = [scipy.sparse.csc_matrix]\nCOO_CONTAINERS = [scipy.sparse.coo_matrix]\nLIL_CONTAINERS = [scipy.sparse.lil_matrix]\nDOK_CONTAINERS = [scipy.sparse.dok_matrix]\nBSR_CONTAINERS = [scipy.sparse.bsr_matrix]\n\nif parse_version(scipy.__version__) >= parse_version(\"1.8\"):\n # Sparse Arrays have been added in SciPy 1.8\n # TODO: When SciPy 1.8 is the minimum supported version,\n # those list can be created directly without this condition.\n # See: https://github.com/scikit-learn/scikit-learn/issues/27090\n CSR_CONTAINERS.append(scipy.sparse.csr_array)\n CSC_CONTAINERS.append(scipy.sparse.csc_array)\n COO_CONTAINERS.append(scipy.sparse.coo_array)\n LIL_CONTAINERS.append(scipy.sparse.lil_array)\n DOK_CONTAINERS.append(scipy.sparse.dok_array)\n BSR_CONTAINERS.append(scipy.sparse.bsr_array)\n\ntry:\n from scipy.optimize._linesearch import line_search_wolfe1, line_search_wolfe2\nexcept ImportError: # SciPy < 1.8\n from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 # type: ignore # noqa\n\n\ndef _object_dtype_isnan(X):\n return X != X\n\n\n# Rename the `method` kwarg to `interpolation` for NumPy < 1.22, because\n# `interpolation` kwarg was deprecated in favor of `method` in NumPy >= 1.22.\ndef _percentile(a, q, *, method=\"linear\", **kwargs):\n return np.percentile(a, q, interpolation=method, **kwargs)\n\n\nif np_version < parse_version(\"1.22\"):\n percentile = _percentile\nelse: # >= 1.22\n from numpy import percentile # type: ignore # noqa\n\n\n# compatibility fix for threadpoolctl >= 3.0.0", "new_contents": "import scipy.sparse.linalg\nimport scipy.stats\nimport threadpoolctl\n\nimport sklearn\n\nfrom ..externals._packaging.version import parse as parse_version\nfrom .deprecation import deprecated\n\nnp_version = parse_version(np.__version__)\nnp_base_version = parse_version(np_version.base_version)\nsp_version = parse_version(scipy.__version__)\nsp_base_version = parse_version(sp_version.base_version)\n\n# TODO: We can consider removing the containers and importing\n# directly from SciPy when sparse matrices will be deprecated.\nCSR_CONTAINERS = [scipy.sparse.csr_matrix]\nCSC_CONTAINERS = [scipy.sparse.csc_matrix]\nCOO_CONTAINERS = [scipy.sparse.coo_matrix]\nLIL_CONTAINERS = [scipy.sparse.lil_matrix]\nDOK_CONTAINERS = [scipy.sparse.dok_matrix]\nBSR_CONTAINERS = [scipy.sparse.bsr_matrix]\nDIA_CONTAINERS = [scipy.sparse.dia_matrix]\n\nif parse_version(scipy.__version__) >= parse_version(\"1.8\"):\n # Sparse Arrays have been added in SciPy 1.8\n # TODO: When SciPy 1.8 is the minimum supported version,\n # those list can be created directly without this condition.\n # See: https://github.com/scikit-learn/scikit-learn/issues/27090\n CSR_CONTAINERS.append(scipy.sparse.csr_array)\n CSC_CONTAINERS.append(scipy.sparse.csc_array)\n COO_CONTAINERS.append(scipy.sparse.coo_array)\n LIL_CONTAINERS.append(scipy.sparse.lil_array)\n DOK_CONTAINERS.append(scipy.sparse.dok_array)\n BSR_CONTAINERS.append(scipy.sparse.bsr_array)\n DIA_CONTAINERS.append(scipy.sparse.dia_array)\n\ntry:\n from scipy.optimize._linesearch import line_search_wolfe1, line_search_wolfe2\nexcept ImportError: # SciPy < 1.8\n from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 # type: ignore # noqa\n\n\ndef _object_dtype_isnan(X):\n return X != X\n\n\n# Rename the `method` kwarg to `interpolation` for NumPy < 1.22, because\n# `interpolation` kwarg was deprecated in favor of `method` in NumPy >= 1.22.\ndef _percentile(a, q, *, method=\"linear\", **kwargs):\n return np.percentile(a, q, interpolation=method, **kwargs)\n\n\nif np_version < parse_version(\"1.22\"):\n percentile = _percentile\nelse: # >= 1.22\n from numpy import percentile # type: ignore # noqa\n\n\n# compatibility fix for threadpoolctl >= 3.0.0", "text": "<|original_code|>\nimport scipy.sparse.linalg\nimport scipy.stats\nimport threadpoolctl\n\nimport sklearn\n\nfrom ..externals._packaging.version import parse as parse_version\nfrom .deprecation import deprecated\n\nnp_version = parse_version(np.__version__)\nnp_base_version = parse_version(np_version.base_version)\nsp_version = parse_version(scipy.__version__)\nsp_base_version = parse_version(sp_version.base_version)\n\n# TODO: We can consider removing the containers and importing\n# directly from SciPy when sparse matrices will be deprecated.\nCSR_CONTAINERS = [scipy.sparse.csr_matrix]\nCSC_CONTAINERS = [scipy.sparse.csc_matrix]\nCOO_CONTAINERS = [scipy.sparse.coo_matrix]\nLIL_CONTAINERS = [scipy.sparse.lil_matrix]\nDOK_CONTAINERS = [scipy.sparse.dok_matrix]\nBSR_CONTAINERS = [scipy.sparse.bsr_matrix]\n\nif parse_version(scipy.__version__) >= parse_version(\"1.8\"):\n # Sparse Arrays have been added in SciPy 1.8\n # TODO: When SciPy 1.8 is the minimum supported version,\n # those list can be created directly without this condition.\n # See: https://github.com/scikit-learn/scikit-learn/issues/27090\n CSR_CONTAINERS.append(scipy.sparse.csr_array)\n CSC_CONTAINERS.append(scipy.sparse.csc_array)\n COO_CONTAINERS.append(scipy.sparse.coo_array)\n LIL_CONTAINERS.append(scipy.sparse.lil_array)\n DOK_CONTAINERS.append(scipy.sparse.dok_array)\n BSR_CONTAINERS.append(scipy.sparse.bsr_array)\n\ntry:\n from scipy.optimize._linesearch import line_search_wolfe1, line_search_wolfe2\nexcept ImportError: # SciPy < 1.8\n from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 # type: ignore # noqa\n\n\ndef _object_dtype_isnan(X):\n return X != X\n\n\n# Rename the `method` kwarg to `interpolation` for NumPy < 1.22, because\n# `interpolation` kwarg was deprecated in favor of `method` in NumPy >= 1.22.\ndef _percentile(a, q, *, method=\"linear\", **kwargs):\n return np.percentile(a, q, interpolation=method, **kwargs)\n\n\nif np_version < parse_version(\"1.22\"):\n percentile = _percentile\nelse: # >= 1.22\n from numpy import percentile # type: ignore # noqa\n\n\n# compatibility fix for threadpoolctl >= 3.0.0\n<|edits_diff|>\n--- sklearn/utils/fixes.py\n+++ sklearn/utils/fixes.py\n@@ -20,6 +20,7 @@\n LIL_CONTAINERS = [scipy.sparse.lil_matrix]\n DOK_CONTAINERS = [scipy.sparse.dok_matrix]\n BSR_CONTAINERS = [scipy.sparse.bsr_matrix]\n+DIA_CONTAINERS = [scipy.sparse.dia_matrix]\n \n if parse_version(scipy.__version__) >= parse_version(\"1.8\"):\n # Sparse Arrays have been added in SciPy 1.8\n<|current_version|>\nimport scipy.sparse.linalg\nimport scipy.stats\nimport threadpoolctl\n\nimport sklearn\n\nfrom ..externals._packaging.version import parse as parse_version\nfrom .deprecation import deprecated\n\nnp_version = parse_version(np.__version__)\nnp_base_version = parse_version(np_version.base_version)\nsp_version = parse_version(scipy.__version__)\nsp_base_version = parse_version(sp_version.base_version)\n\n# TODO: We can consider removing the containers and importing\n# directly from SciPy when sparse matrices will be deprecated.\nCSR_CONTAINERS = [scipy.sparse.csr_matrix]\nCSC_CONTAINERS = [scipy.sparse.csc_matrix]\nCOO_CONTAINERS = [scipy.sparse.coo_matrix]\nLIL_CONTAINERS = [scipy.sparse.lil_matrix]\nDOK_CONTAINERS = [scipy.sparse.dok_matrix]\nBSR_CONTAINERS = [scipy.sparse.bsr_matrix]\nDIA_CONTAINERS = [scipy.sparse.dia_matrix]\n\nif parse_version(scipy.__version__) >= parse_version(\"1.8\"):\n # Sparse Arrays have been added in SciPy 1.8\n # TODO: When SciPy 1.8 is the minimum supported version,\n # those list can be created directly without this condition.\n # See: https://github.com/scikit-learn/scikit-learn/issues/27090\n CSR_CONTAINERS.append(scipy.sparse.csr_array)\n CSC_CONTAINERS.append(scipy.sparse.csc_array)\n COO_CONTAINERS.append(scipy.sparse.coo_array)\n LIL_CONTAINERS.append(scipy.sparse.lil_array)\n DOK_CONTAINERS.append(scipy.sparse.dok_array)\n BSR_CONTAINERS.append(scipy.sparse.bsr_array)\n\ntry:\n from scipy.optimize._linesearch import line_search_wolfe1, line_search_wolfe2\nexcept ImportError: # SciPy < 1.8\n from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 # type: ignore # noqa\n\n\ndef _object_dtype_isnan(X):\n return X != X\n\n\n# Rename the `method` kwarg to `interpolation` for NumPy < 1.22, because\n# `interpolation` kwarg was deprecated in favor of `method` in NumPy >= 1.22.\ndef _percentile(a, q, *, method=\"linear\", **kwargs):\n return np.percentile(a, q, interpolation=method, **kwargs)\n\n\nif np_version < parse_version(\"1.22\"):\n percentile = _percentile\nelse: # >= 1.22\n from numpy import percentile # type: ignore # noqa\n\n\n# compatibility fix for threadpoolctl >= 3.0.0\n<|next_version|>\nimport scipy.sparse.linalg\nimport scipy.stats\nimport threadpoolctl\n\nimport sklearn\n\nfrom ..externals._packaging.version import parse as parse_version\nfrom .deprecation import deprecated\n\nnp_version = parse_version(np.__version__)\nnp_base_version = parse_version(np_version.base_version)\nsp_version = parse_version(scipy.__version__)\nsp_base_version = parse_version(sp_version.base_version)\n\n# TODO: We can consider removing the containers and importing\n# directly from SciPy when sparse matrices will be deprecated.\nCSR_CONTAINERS = [scipy.sparse.csr_matrix]\nCSC_CONTAINERS = [scipy.sparse.csc_matrix]\nCOO_CONTAINERS = [scipy.sparse.coo_matrix]\nLIL_CONTAINERS = [scipy.sparse.lil_matrix]\nDOK_CONTAINERS = [scipy.sparse.dok_matrix]\nBSR_CONTAINERS = [scipy.sparse.bsr_matrix]\nDIA_CONTAINERS = [scipy.sparse.dia_matrix]\n\nif parse_version(scipy.__version__) >= parse_version(\"1.8\"):\n # Sparse Arrays have been added in SciPy 1.8\n # TODO: When SciPy 1.8 is the minimum supported version,\n # those list can be created directly without this condition.\n # See: https://github.com/scikit-learn/scikit-learn/issues/27090\n CSR_CONTAINERS.append(scipy.sparse.csr_array)\n CSC_CONTAINERS.append(scipy.sparse.csc_array)\n COO_CONTAINERS.append(scipy.sparse.coo_array)\n LIL_CONTAINERS.append(scipy.sparse.lil_array)\n DOK_CONTAINERS.append(scipy.sparse.dok_array)\n BSR_CONTAINERS.append(scipy.sparse.bsr_array)\n DIA_CONTAINERS.append(scipy.sparse.dia_array)\n\ntry:\n from scipy.optimize._linesearch import line_search_wolfe1, line_search_wolfe2\nexcept ImportError: # SciPy < 1.8\n from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 # type: ignore # noqa\n\n\ndef _object_dtype_isnan(X):\n return X != X\n\n\n# Rename the `method` kwarg to `interpolation` for NumPy < 1.22, because\n# `interpolation` kwarg was deprecated in favor of `method` in NumPy >= 1.22.\ndef _percentile(a, q, *, method=\"linear\", **kwargs):\n return np.percentile(a, q, interpolation=method, **kwargs)\n\n\nif np_version < parse_version(\"1.22\"):\n percentile = _percentile\nelse: # >= 1.22\n from numpy import percentile # type: ignore # noqa\n\n\n# compatibility fix for threadpoolctl >= 3.0.0\n", "current_contents": "import scipy.sparse.linalg\nimport scipy.stats\nimport threadpoolctl\n\nimport sklearn\n\nfrom ..externals._packaging.version import parse as parse_version\nfrom .deprecation import deprecated\n\nnp_version = parse_version(np.__version__)\nnp_base_version = parse_version(np_version.base_version)\nsp_version = parse_version(scipy.__version__)\nsp_base_version = parse_version(sp_version.base_version)\n\n# TODO: We can consider removing the containers and importing\n# directly from SciPy when sparse matrices will be deprecated.\nCSR_CONTAINERS = [scipy.sparse.csr_matrix]\nCSC_CONTAINERS = [scipy.sparse.csc_matrix]\nCOO_CONTAINERS = [scipy.sparse.coo_matrix]\nLIL_CONTAINERS = [scipy.sparse.lil_matrix]\nDOK_CONTAINERS = [scipy.sparse.dok_matrix]\nBSR_CONTAINERS = [scipy.sparse.bsr_matrix]\nDIA_CONTAINERS = [scipy.sparse.dia_matrix]\n\nif parse_version(scipy.__version__) >= parse_version(\"1.8\"):\n # Sparse Arrays have been added in SciPy 1.8\n # TODO: When SciPy 1.8 is the minimum supported version,\n # those list can be created directly without this condition.\n # See: https://github.com/scikit-learn/scikit-learn/issues/27090\n CSR_CONTAINERS.append(scipy.sparse.csr_array)\n CSC_CONTAINERS.append(scipy.sparse.csc_array)\n COO_CONTAINERS.append(scipy.sparse.coo_array)\n LIL_CONTAINERS.append(scipy.sparse.lil_array)\n DOK_CONTAINERS.append(scipy.sparse.dok_array)\n BSR_CONTAINERS.append(scipy.sparse.bsr_array)\n\ntry:\n from scipy.optimize._linesearch import line_search_wolfe1, line_search_wolfe2\nexcept ImportError: # SciPy < 1.8\n from scipy.optimize.linesearch import line_search_wolfe2, line_search_wolfe1 # type: ignore # noqa\n\n\ndef _object_dtype_isnan(X):\n return X != X\n\n\n# Rename the `method` kwarg to `interpolation` for NumPy < 1.22, because\n# `interpolation` kwarg was deprecated in favor of `method` in NumPy >= 1.22.\ndef _percentile(a, q, *, method=\"linear\", **kwargs):\n return np.percentile(a, q, interpolation=method, **kwargs)\n\n\nif np_version < parse_version(\"1.22\"):\n percentile = _percentile\nelse: # >= 1.22\n from numpy import percentile # type: ignore # noqa\n\n\n# compatibility fix for threadpoolctl >= 3.0.0"} {"commit": "c6a2612c1b344204d66fe6f29f6fb6add0f9beac", "message": "FIX acc_find_split_time and acc_compute_hist_time of root nodes in HistGradientBoosting* (#24894)", "old_file": "sklearn/ensemble/_hist_gradient_boosting/grower.py", "new_file": "sklearn/ensemble/_hist_gradient_boosting/grower.py", "status": "M", "old_contents": " sum_hessians = hessians[0] * n_samples\n else:\n sum_hessians = sum_parallel(hessians, self.n_threads)\n self.root = TreeNode(\n depth=depth,\n sample_indices=self.splitter.partition,\n sum_gradients=sum_gradients,\n sum_hessians=sum_hessians,\n value=0,\n )\n\n self.root.partition_start = 0\n self.root.partition_stop = n_samples\n\n if self.root.n_samples < 2 * self.min_samples_leaf:\n # Do not even bother computing any splitting statistics.\n self._finalize_leaf(self.root)\n return\n if sum_hessians < self.splitter.min_hessian_to_split:\n self._finalize_leaf(self.root)\n return\n\n self.root.histograms = self.histogram_builder.compute_histograms_brute(\n self.root.sample_indices\n )\n\n if self.interaction_cst is not None:\n self.root.interaction_cst_indices = range(len(self.interaction_cst))\n allowed_features = set().union(*self.interaction_cst)\n self.root.allowed_features = np.fromiter(\n allowed_features, dtype=np.uint32, count=len(allowed_features)\n )\n\n self._compute_best_split_and_push(self.root)\n\n def _compute_best_split_and_push(self, node):\n \"\"\"Compute the best possible split (SplitInfo) of a given node.\n\n Also push it in the heap of splittable nodes if gain isn't zero.\n The gain of a node is 0 if either all the leaves are pure\n (best gain = 0), or if no split would satisfy the constraints,\n (min_hessians_to_split, min_gain_to_split, min_samples_leaf)\n \"\"\"\n\n node.split_info = self.splitter.find_node_split(\n n_samples=node.n_samples,\n histograms=node.histograms,\n sum_gradients=node.sum_gradients,\n sum_hessians=node.sum_hessians,\n value=node.value,\n lower_bound=node.children_lower_bound,\n upper_bound=node.children_upper_bound,\n allowed_features=node.allowed_features,\n )\n\n if node.split_info.gain <= 0: # no valid split\n self._finalize_leaf(node)\n else:", "new_contents": " sum_hessians = hessians[0] * n_samples\n else:\n sum_hessians = sum_parallel(hessians, self.n_threads)\n self.root = TreeNode(\n depth=depth,\n sample_indices=self.splitter.partition,\n sum_gradients=sum_gradients,\n sum_hessians=sum_hessians,\n value=0,\n )\n\n self.root.partition_start = 0\n self.root.partition_stop = n_samples\n\n if self.root.n_samples < 2 * self.min_samples_leaf:\n # Do not even bother computing any splitting statistics.\n self._finalize_leaf(self.root)\n return\n if sum_hessians < self.splitter.min_hessian_to_split:\n self._finalize_leaf(self.root)\n return\n\n tic = time()\n self.root.histograms = self.histogram_builder.compute_histograms_brute(\n self.root.sample_indices\n )\n self.total_compute_hist_time += time() - tic\n\n if self.interaction_cst is not None:\n self.root.interaction_cst_indices = range(len(self.interaction_cst))\n allowed_features = set().union(*self.interaction_cst)\n self.root.allowed_features = np.fromiter(\n allowed_features, dtype=np.uint32, count=len(allowed_features)\n )\n\n tic = time()\n self._compute_best_split_and_push(self.root)\n self.total_find_split_time += time() - tic\n\n def _compute_best_split_and_push(self, node):\n \"\"\"Compute the best possible split (SplitInfo) of a given node.\n\n Also push it in the heap of splittable nodes if gain isn't zero.\n The gain of a node is 0 if either all the leaves are pure\n (best gain = 0), or if no split would satisfy the constraints,\n (min_hessians_to_split, min_gain_to_split, min_samples_leaf)\n \"\"\"\n\n node.split_info = self.splitter.find_node_split(\n n_samples=node.n_samples,\n histograms=node.histograms,\n sum_gradients=node.sum_gradients,\n sum_hessians=node.sum_hessians,\n value=node.value,\n lower_bound=node.children_lower_bound,\n upper_bound=node.children_upper_bound,\n allowed_features=node.allowed_features,\n )\n\n if node.split_info.gain <= 0: # no valid split\n self._finalize_leaf(node)\n else:", "text": "<|original_code|>\n sum_hessians = hessians[0] * n_samples\n else:\n sum_hessians = sum_parallel(hessians, self.n_threads)\n self.root = TreeNode(\n depth=depth,\n sample_indices=self.splitter.partition,\n sum_gradients=sum_gradients,\n sum_hessians=sum_hessians,\n value=0,\n )\n\n self.root.partition_start = 0\n self.root.partition_stop = n_samples\n\n if self.root.n_samples < 2 * self.min_samples_leaf:\n # Do not even bother computing any splitting statistics.\n self._finalize_leaf(self.root)\n return\n if sum_hessians < self.splitter.min_hessian_to_split:\n self._finalize_leaf(self.root)\n return\n\n self.root.histograms = self.histogram_builder.compute_histograms_brute(\n self.root.sample_indices\n )\n\n if self.interaction_cst is not None:\n self.root.interaction_cst_indices = range(len(self.interaction_cst))\n allowed_features = set().union(*self.interaction_cst)\n self.root.allowed_features = np.fromiter(\n allowed_features, dtype=np.uint32, count=len(allowed_features)\n )\n\n self._compute_best_split_and_push(self.root)\n\n def _compute_best_split_and_push(self, node):\n \"\"\"Compute the best possible split (SplitInfo) of a given node.\n\n Also push it in the heap of splittable nodes if gain isn't zero.\n The gain of a node is 0 if either all the leaves are pure\n (best gain = 0), or if no split would satisfy the constraints,\n (min_hessians_to_split, min_gain_to_split, min_samples_leaf)\n \"\"\"\n\n node.split_info = self.splitter.find_node_split(\n n_samples=node.n_samples,\n histograms=node.histograms,\n sum_gradients=node.sum_gradients,\n sum_hessians=node.sum_hessians,\n value=node.value,\n lower_bound=node.children_lower_bound,\n upper_bound=node.children_upper_bound,\n allowed_features=node.allowed_features,\n )\n\n if node.split_info.gain <= 0: # no valid split\n self._finalize_leaf(node)\n else:\n<|edits_diff|>\n--- sklearn/ensemble/_hist_gradient_boosting/grower.py\n+++ sklearn/ensemble/_hist_gradient_boosting/grower.py\n@@ -20,9 +20,11 @@\n self._finalize_leaf(self.root)\n return\n \n+ tic = time()\n self.root.histograms = self.histogram_builder.compute_histograms_brute(\n self.root.sample_indices\n )\n+ self.total_compute_hist_time += time() - tic\n \n if self.interaction_cst is not None:\n self.root.interaction_cst_indices = range(len(self.interaction_cst))\n@@ -31,6 +33,7 @@\n allowed_features, dtype=np.uint32, count=len(allowed_features)\n )\n \n+ tic = time()\n self._compute_best_split_and_push(self.root)\n \n def _compute_best_split_and_push(self, node):\n<|current_version|>\n sum_hessians = hessians[0] * n_samples\n else:\n sum_hessians = sum_parallel(hessians, self.n_threads)\n self.root = TreeNode(\n depth=depth,\n sample_indices=self.splitter.partition,\n sum_gradients=sum_gradients,\n sum_hessians=sum_hessians,\n value=0,\n )\n\n self.root.partition_start = 0\n self.root.partition_stop = n_samples\n\n if self.root.n_samples < 2 * self.min_samples_leaf:\n # Do not even bother computing any splitting statistics.\n self._finalize_leaf(self.root)\n return\n if sum_hessians < self.splitter.min_hessian_to_split:\n self._finalize_leaf(self.root)\n return\n\n tic = time()\n self.root.histograms = self.histogram_builder.compute_histograms_brute(\n self.root.sample_indices\n )\n self.total_compute_hist_time += time() - tic\n\n if self.interaction_cst is not None:\n self.root.interaction_cst_indices = range(len(self.interaction_cst))\n allowed_features = set().union(*self.interaction_cst)\n self.root.allowed_features = np.fromiter(\n allowed_features, dtype=np.uint32, count=len(allowed_features)\n )\n\n tic = time()\n self._compute_best_split_and_push(self.root)\n\n def _compute_best_split_and_push(self, node):\n \"\"\"Compute the best possible split (SplitInfo) of a given node.\n\n Also push it in the heap of splittable nodes if gain isn't zero.\n The gain of a node is 0 if either all the leaves are pure\n (best gain = 0), or if no split would satisfy the constraints,\n (min_hessians_to_split, min_gain_to_split, min_samples_leaf)\n \"\"\"\n\n node.split_info = self.splitter.find_node_split(\n n_samples=node.n_samples,\n histograms=node.histograms,\n sum_gradients=node.sum_gradients,\n sum_hessians=node.sum_hessians,\n value=node.value,\n lower_bound=node.children_lower_bound,\n upper_bound=node.children_upper_bound,\n allowed_features=node.allowed_features,\n )\n\n if node.split_info.gain <= 0: # no valid split\n self._finalize_leaf(node)\n else:\n<|next_version|>\n sum_hessians = hessians[0] * n_samples\n else:\n sum_hessians = sum_parallel(hessians, self.n_threads)\n self.root = TreeNode(\n depth=depth,\n sample_indices=self.splitter.partition,\n sum_gradients=sum_gradients,\n sum_hessians=sum_hessians,\n value=0,\n )\n\n self.root.partition_start = 0\n self.root.partition_stop = n_samples\n\n if self.root.n_samples < 2 * self.min_samples_leaf:\n # Do not even bother computing any splitting statistics.\n self._finalize_leaf(self.root)\n return\n if sum_hessians < self.splitter.min_hessian_to_split:\n self._finalize_leaf(self.root)\n return\n\n tic = time()\n self.root.histograms = self.histogram_builder.compute_histograms_brute(\n self.root.sample_indices\n )\n self.total_compute_hist_time += time() - tic\n\n if self.interaction_cst is not None:\n self.root.interaction_cst_indices = range(len(self.interaction_cst))\n allowed_features = set().union(*self.interaction_cst)\n self.root.allowed_features = np.fromiter(\n allowed_features, dtype=np.uint32, count=len(allowed_features)\n )\n\n tic = time()\n self._compute_best_split_and_push(self.root)\n self.total_find_split_time += time() - tic\n\n def _compute_best_split_and_push(self, node):\n \"\"\"Compute the best possible split (SplitInfo) of a given node.\n\n Also push it in the heap of splittable nodes if gain isn't zero.\n The gain of a node is 0 if either all the leaves are pure\n (best gain = 0), or if no split would satisfy the constraints,\n (min_hessians_to_split, min_gain_to_split, min_samples_leaf)\n \"\"\"\n\n node.split_info = self.splitter.find_node_split(\n n_samples=node.n_samples,\n histograms=node.histograms,\n sum_gradients=node.sum_gradients,\n sum_hessians=node.sum_hessians,\n value=node.value,\n lower_bound=node.children_lower_bound,\n upper_bound=node.children_upper_bound,\n allowed_features=node.allowed_features,\n )\n\n if node.split_info.gain <= 0: # no valid split\n self._finalize_leaf(node)\n else:\n", "current_contents": " sum_hessians = hessians[0] * n_samples\n else:\n sum_hessians = sum_parallel(hessians, self.n_threads)\n self.root = TreeNode(\n depth=depth,\n sample_indices=self.splitter.partition,\n sum_gradients=sum_gradients,\n sum_hessians=sum_hessians,\n value=0,\n )\n\n self.root.partition_start = 0\n self.root.partition_stop = n_samples\n\n if self.root.n_samples < 2 * self.min_samples_leaf:\n # Do not even bother computing any splitting statistics.\n self._finalize_leaf(self.root)\n return\n if sum_hessians < self.splitter.min_hessian_to_split:\n self._finalize_leaf(self.root)\n return\n\n tic = time()\n self.root.histograms = self.histogram_builder.compute_histograms_brute(\n self.root.sample_indices\n )\n self.total_compute_hist_time += time() - tic\n\n if self.interaction_cst is not None:\n self.root.interaction_cst_indices = range(len(self.interaction_cst))\n allowed_features = set().union(*self.interaction_cst)\n self.root.allowed_features = np.fromiter(\n allowed_features, dtype=np.uint32, count=len(allowed_features)\n )\n\n tic = time()\n self._compute_best_split_and_push(self.root)\n\n def _compute_best_split_and_push(self, node):\n \"\"\"Compute the best possible split (SplitInfo) of a given node.\n\n Also push it in the heap of splittable nodes if gain isn't zero.\n The gain of a node is 0 if either all the leaves are pure\n (best gain = 0), or if no split would satisfy the constraints,\n (min_hessians_to_split, min_gain_to_split, min_samples_leaf)\n \"\"\"\n\n node.split_info = self.splitter.find_node_split(\n n_samples=node.n_samples,\n histograms=node.histograms,\n sum_gradients=node.sum_gradients,\n sum_hessians=node.sum_hessians,\n value=node.value,\n lower_bound=node.children_lower_bound,\n upper_bound=node.children_upper_bound,\n allowed_features=node.allowed_features,\n )\n\n if node.split_info.gain <= 0: # no valid split\n self._finalize_leaf(node)\n else:"} {"commit": "f8fde49bc21d558f2894051749f3fa31a4f42c41", "message": "DOC changed marker colors for calibration comparison (#24766)", "old_file": "examples/calibration/plot_compare_calibration.py", "new_file": "examples/calibration/plot_compare_calibration.py", "status": "M", "old_contents": "gnb = GaussianNB()\nsvc = NaivelyCalibratedLinearSVC(C=1.0)\nrfc = RandomForestClassifier()\n\nclf_list = [\n (lr, \"Logistic\"),\n (gnb, \"Naive Bayes\"),\n (svc, \"SVC\"),\n (rfc, \"Random forest\"),\n]\n\n# %%\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\nfig = plt.figure(figsize=(10, 10))\ngs = GridSpec(4, 2)\ncolors = plt.cm.get_cmap(\"Dark2\")\n\nax_calibration_curve = fig.add_subplot(gs[:2, :2])\ncalibration_displays = {}\nfor i, (clf, name) in enumerate(clf_list):\n clf.fit(X_train, y_train)\n display = CalibrationDisplay.from_estimator(\n clf,\n X_test,\n y_test,\n n_bins=10,\n name=name,\n ax=ax_calibration_curve,\n color=colors(i),\n )\n calibration_displays[name] = display\n\nax_calibration_curve.grid()\nax_calibration_curve.set_title(\"Calibration plots\")\n\n# Add histogram\ngrid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)]\nfor i, (_, name) in enumerate(clf_list):\n row, col = grid_positions[i]\n ax = fig.add_subplot(gs[row, col])\n\n ax.hist(\n calibration_displays[name].y_prob,\n range=(0, 1),\n bins=10,\n label=name,\n color=colors(i),\n )\n ax.set(title=name, xlabel=\"Mean predicted probability\", ylabel=\"Count\")\n\nplt.tight_layout()\nplt.show()\n", "new_contents": "gnb = GaussianNB()\nsvc = NaivelyCalibratedLinearSVC(C=1.0)\nrfc = RandomForestClassifier()\n\nclf_list = [\n (lr, \"Logistic\"),\n (gnb, \"Naive Bayes\"),\n (svc, \"SVC\"),\n (rfc, \"Random forest\"),\n]\n\n# %%\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\nfig = plt.figure(figsize=(10, 10))\ngs = GridSpec(4, 2)\ncolors = plt.cm.get_cmap(\"Dark2\")\n\nax_calibration_curve = fig.add_subplot(gs[:2, :2])\ncalibration_displays = {}\nmarkers = [\"^\", \"v\", \"s\", \"o\"]\nfor i, (clf, name) in enumerate(clf_list):\n clf.fit(X_train, y_train)\n display = CalibrationDisplay.from_estimator(\n clf,\n X_test,\n y_test,\n n_bins=10,\n name=name,\n ax=ax_calibration_curve,\n color=colors(i),\n marker=markers[i],\n )\n calibration_displays[name] = display\n\nax_calibration_curve.grid()\nax_calibration_curve.set_title(\"Calibration plots\")\n\n# Add histogram\ngrid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)]\nfor i, (_, name) in enumerate(clf_list):\n row, col = grid_positions[i]\n ax = fig.add_subplot(gs[row, col])\n\n ax.hist(\n calibration_displays[name].y_prob,\n range=(0, 1),\n bins=10,\n label=name,\n color=colors(i),\n )\n ax.set(title=name, xlabel=\"Mean predicted probability\", ylabel=\"Count\")\n\nplt.tight_layout()\nplt.show()\n", "text": "<|original_code|>\ngnb = GaussianNB()\nsvc = NaivelyCalibratedLinearSVC(C=1.0)\nrfc = RandomForestClassifier()\n\nclf_list = [\n (lr, \"Logistic\"),\n (gnb, \"Naive Bayes\"),\n (svc, \"SVC\"),\n (rfc, \"Random forest\"),\n]\n\n# %%\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\nfig = plt.figure(figsize=(10, 10))\ngs = GridSpec(4, 2)\ncolors = plt.cm.get_cmap(\"Dark2\")\n\nax_calibration_curve = fig.add_subplot(gs[:2, :2])\ncalibration_displays = {}\nfor i, (clf, name) in enumerate(clf_list):\n clf.fit(X_train, y_train)\n display = CalibrationDisplay.from_estimator(\n clf,\n X_test,\n y_test,\n n_bins=10,\n name=name,\n ax=ax_calibration_curve,\n color=colors(i),\n )\n calibration_displays[name] = display\n\nax_calibration_curve.grid()\nax_calibration_curve.set_title(\"Calibration plots\")\n\n# Add histogram\ngrid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)]\nfor i, (_, name) in enumerate(clf_list):\n row, col = grid_positions[i]\n ax = fig.add_subplot(gs[row, col])\n\n ax.hist(\n calibration_displays[name].y_prob,\n range=(0, 1),\n bins=10,\n label=name,\n color=colors(i),\n )\n ax.set(title=name, xlabel=\"Mean predicted probability\", ylabel=\"Count\")\n\nplt.tight_layout()\nplt.show()\n\n<|edits_diff|>\n--- examples/calibration/plot_compare_calibration.py\n+++ examples/calibration/plot_compare_calibration.py\n@@ -20,6 +20,7 @@\n \n ax_calibration_curve = fig.add_subplot(gs[:2, :2])\n calibration_displays = {}\n+markers = [\"^\", \"v\", \"s\", \"o\"]\n for i, (clf, name) in enumerate(clf_list):\n clf.fit(X_train, y_train)\n display = CalibrationDisplay.from_estimator(\n<|current_version|>\ngnb = GaussianNB()\nsvc = NaivelyCalibratedLinearSVC(C=1.0)\nrfc = RandomForestClassifier()\n\nclf_list = [\n (lr, \"Logistic\"),\n (gnb, \"Naive Bayes\"),\n (svc, \"SVC\"),\n (rfc, \"Random forest\"),\n]\n\n# %%\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\nfig = plt.figure(figsize=(10, 10))\ngs = GridSpec(4, 2)\ncolors = plt.cm.get_cmap(\"Dark2\")\n\nax_calibration_curve = fig.add_subplot(gs[:2, :2])\ncalibration_displays = {}\nmarkers = [\"^\", \"v\", \"s\", \"o\"]\nfor i, (clf, name) in enumerate(clf_list):\n clf.fit(X_train, y_train)\n display = CalibrationDisplay.from_estimator(\n clf,\n X_test,\n y_test,\n n_bins=10,\n name=name,\n ax=ax_calibration_curve,\n color=colors(i),\n )\n calibration_displays[name] = display\n\nax_calibration_curve.grid()\nax_calibration_curve.set_title(\"Calibration plots\")\n\n# Add histogram\ngrid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)]\nfor i, (_, name) in enumerate(clf_list):\n row, col = grid_positions[i]\n ax = fig.add_subplot(gs[row, col])\n\n ax.hist(\n calibration_displays[name].y_prob,\n range=(0, 1),\n bins=10,\n label=name,\n color=colors(i),\n )\n ax.set(title=name, xlabel=\"Mean predicted probability\", ylabel=\"Count\")\n\nplt.tight_layout()\nplt.show()\n\n<|next_version|>\ngnb = GaussianNB()\nsvc = NaivelyCalibratedLinearSVC(C=1.0)\nrfc = RandomForestClassifier()\n\nclf_list = [\n (lr, \"Logistic\"),\n (gnb, \"Naive Bayes\"),\n (svc, \"SVC\"),\n (rfc, \"Random forest\"),\n]\n\n# %%\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\nfig = plt.figure(figsize=(10, 10))\ngs = GridSpec(4, 2)\ncolors = plt.cm.get_cmap(\"Dark2\")\n\nax_calibration_curve = fig.add_subplot(gs[:2, :2])\ncalibration_displays = {}\nmarkers = [\"^\", \"v\", \"s\", \"o\"]\nfor i, (clf, name) in enumerate(clf_list):\n clf.fit(X_train, y_train)\n display = CalibrationDisplay.from_estimator(\n clf,\n X_test,\n y_test,\n n_bins=10,\n name=name,\n ax=ax_calibration_curve,\n color=colors(i),\n marker=markers[i],\n )\n calibration_displays[name] = display\n\nax_calibration_curve.grid()\nax_calibration_curve.set_title(\"Calibration plots\")\n\n# Add histogram\ngrid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)]\nfor i, (_, name) in enumerate(clf_list):\n row, col = grid_positions[i]\n ax = fig.add_subplot(gs[row, col])\n\n ax.hist(\n calibration_displays[name].y_prob,\n range=(0, 1),\n bins=10,\n label=name,\n color=colors(i),\n )\n ax.set(title=name, xlabel=\"Mean predicted probability\", ylabel=\"Count\")\n\nplt.tight_layout()\nplt.show()\n\n", "current_contents": "gnb = GaussianNB()\nsvc = NaivelyCalibratedLinearSVC(C=1.0)\nrfc = RandomForestClassifier()\n\nclf_list = [\n (lr, \"Logistic\"),\n (gnb, \"Naive Bayes\"),\n (svc, \"SVC\"),\n (rfc, \"Random forest\"),\n]\n\n# %%\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.gridspec import GridSpec\n\nfig = plt.figure(figsize=(10, 10))\ngs = GridSpec(4, 2)\ncolors = plt.cm.get_cmap(\"Dark2\")\n\nax_calibration_curve = fig.add_subplot(gs[:2, :2])\ncalibration_displays = {}\nmarkers = [\"^\", \"v\", \"s\", \"o\"]\nfor i, (clf, name) in enumerate(clf_list):\n clf.fit(X_train, y_train)\n display = CalibrationDisplay.from_estimator(\n clf,\n X_test,\n y_test,\n n_bins=10,\n name=name,\n ax=ax_calibration_curve,\n color=colors(i),\n )\n calibration_displays[name] = display\n\nax_calibration_curve.grid()\nax_calibration_curve.set_title(\"Calibration plots\")\n\n# Add histogram\ngrid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)]\nfor i, (_, name) in enumerate(clf_list):\n row, col = grid_positions[i]\n ax = fig.add_subplot(gs[row, col])\n\n ax.hist(\n calibration_displays[name].y_prob,\n range=(0, 1),\n bins=10,\n label=name,\n color=colors(i),\n )\n ax.set(title=name, xlabel=\"Mean predicted probability\", ylabel=\"Count\")\n\nplt.tight_layout()\nplt.show()\n"} {"commit": "60cc5b596f38d0d236dab34e02c05d98b5a72bad", "message": "FEA Fused sparse-dense support for `PairwiseDistancesReduction` (#23585)", "old_file": "sklearn/metrics/tests/test_pairwise.py", "new_file": "sklearn/metrics/tests/test_pairwise.py", "status": "M", "old_contents": "\n@pytest.mark.parametrize(\"dtype\", (np.float32, np.float64))\ndef test_pairwise_distances_argmin_min(dtype):\n # Check pairwise minimum distances computation for any metric\n X = np.asarray([[0], [1]], dtype=dtype)\n Y = np.asarray([[-2], [3]], dtype=dtype)\n\n Xsp = dok_matrix(X)\n Ysp = csr_matrix(Y, dtype=np.float32)\n\n expected_idx = [0, 1]\n expected_vals = [2, 2]\n expected_vals_sq = [4, 4]\n\n # euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"euclidean\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"euclidean\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"euclidean\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n # We don't want np.matrix here\n assert type(idxsp) == np.ndarray\n assert type(valssp) == np.ndarray\n\n # Squared Euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"sqeuclidean\")\n idx2, vals2 = pairwise_distances_argmin_min(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n idx3 = pairwise_distances_argmin(X, Y, metric=\"sqeuclidean\")\n idx4 = pairwise_distances_argmin(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n\n assert_array_almost_equal(vals, expected_vals_sq)\n assert_array_almost_equal(vals2, expected_vals_sq)\n\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(idx3, expected_idx)\n assert_array_almost_equal(idx4, expected_idx)\n\n # Non-euclidean scikit-learn metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"manhattan\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"manhattan\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"manhattan\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n\n # Non-euclidean Scipy distance (callable)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=minkowski, metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Non-euclidean Scipy distance (string)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=\"minkowski\", metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Compare with naive implementation\n rng = np.random.RandomState(0)\n X = rng.randn(97, 149)\n Y = rng.randn(111, 149)\n\n dist = pairwise_distances(X, Y, metric=\"manhattan\")\n dist_orig_ind = dist.argmin(axis=0)\n dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))]", "new_contents": "\n@pytest.mark.parametrize(\"dtype\", (np.float32, np.float64))\ndef test_pairwise_distances_argmin_min(dtype):\n # Check pairwise minimum distances computation for any metric\n X = np.asarray([[0], [1]], dtype=dtype)\n Y = np.asarray([[-2], [3]], dtype=dtype)\n\n Xsp = dok_matrix(X)\n Ysp = csr_matrix(Y, dtype=np.float32)\n\n expected_idx = [0, 1]\n expected_vals = [2, 2]\n expected_vals_sq = [4, 4]\n\n # euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"euclidean\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"euclidean\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"euclidean\")\n idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"euclidean\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(idxsp2, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n # We don't want np.matrix here\n assert type(idxsp) == np.ndarray\n assert type(valssp) == np.ndarray\n\n # Squared Euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"sqeuclidean\")\n idx2, vals2 = pairwise_distances_argmin_min(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n idx3 = pairwise_distances_argmin(X, Y, metric=\"sqeuclidean\")\n idx4 = pairwise_distances_argmin(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n\n assert_array_almost_equal(vals, expected_vals_sq)\n assert_array_almost_equal(vals2, expected_vals_sq)\n\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(idx3, expected_idx)\n assert_array_almost_equal(idx4, expected_idx)\n\n # Non-euclidean scikit-learn metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"manhattan\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"manhattan\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"manhattan\")\n idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"manhattan\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(idxsp2, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n\n # Non-euclidean Scipy distance (callable)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=minkowski, metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Non-euclidean Scipy distance (string)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=\"minkowski\", metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Compare with naive implementation\n rng = np.random.RandomState(0)\n X = rng.randn(97, 149)\n Y = rng.randn(111, 149)\n\n dist = pairwise_distances(X, Y, metric=\"manhattan\")\n dist_orig_ind = dist.argmin(axis=0)\n dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))]", "text": "<|original_code|>\n\n@pytest.mark.parametrize(\"dtype\", (np.float32, np.float64))\ndef test_pairwise_distances_argmin_min(dtype):\n # Check pairwise minimum distances computation for any metric\n X = np.asarray([[0], [1]], dtype=dtype)\n Y = np.asarray([[-2], [3]], dtype=dtype)\n\n Xsp = dok_matrix(X)\n Ysp = csr_matrix(Y, dtype=np.float32)\n\n expected_idx = [0, 1]\n expected_vals = [2, 2]\n expected_vals_sq = [4, 4]\n\n # euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"euclidean\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"euclidean\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"euclidean\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n # We don't want np.matrix here\n assert type(idxsp) == np.ndarray\n assert type(valssp) == np.ndarray\n\n # Squared Euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"sqeuclidean\")\n idx2, vals2 = pairwise_distances_argmin_min(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n idx3 = pairwise_distances_argmin(X, Y, metric=\"sqeuclidean\")\n idx4 = pairwise_distances_argmin(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n\n assert_array_almost_equal(vals, expected_vals_sq)\n assert_array_almost_equal(vals2, expected_vals_sq)\n\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(idx3, expected_idx)\n assert_array_almost_equal(idx4, expected_idx)\n\n # Non-euclidean scikit-learn metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"manhattan\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"manhattan\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"manhattan\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n\n # Non-euclidean Scipy distance (callable)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=minkowski, metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Non-euclidean Scipy distance (string)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=\"minkowski\", metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Compare with naive implementation\n rng = np.random.RandomState(0)\n X = rng.randn(97, 149)\n Y = rng.randn(111, 149)\n\n dist = pairwise_distances(X, Y, metric=\"manhattan\")\n dist_orig_ind = dist.argmin(axis=0)\n dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))]\n<|edits_diff|>\n--- sklearn/metrics/tests/test_pairwise.py\n+++ sklearn/metrics/tests/test_pairwise.py\n@@ -20,7 +20,9 @@\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"euclidean\")\n+ idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"euclidean\")\n assert_array_almost_equal(idxsp, expected_idx)\n+ assert_array_almost_equal(idxsp2, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n # We don't want np.matrix here\n assert type(idxsp) == np.ndarray\n@@ -52,6 +54,7 @@\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"manhattan\")\n+ idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"manhattan\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n \n<|current_version|>\n\n@pytest.mark.parametrize(\"dtype\", (np.float32, np.float64))\ndef test_pairwise_distances_argmin_min(dtype):\n # Check pairwise minimum distances computation for any metric\n X = np.asarray([[0], [1]], dtype=dtype)\n Y = np.asarray([[-2], [3]], dtype=dtype)\n\n Xsp = dok_matrix(X)\n Ysp = csr_matrix(Y, dtype=np.float32)\n\n expected_idx = [0, 1]\n expected_vals = [2, 2]\n expected_vals_sq = [4, 4]\n\n # euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"euclidean\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"euclidean\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"euclidean\")\n idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"euclidean\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(idxsp2, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n # We don't want np.matrix here\n assert type(idxsp) == np.ndarray\n assert type(valssp) == np.ndarray\n\n # Squared Euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"sqeuclidean\")\n idx2, vals2 = pairwise_distances_argmin_min(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n idx3 = pairwise_distances_argmin(X, Y, metric=\"sqeuclidean\")\n idx4 = pairwise_distances_argmin(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n\n assert_array_almost_equal(vals, expected_vals_sq)\n assert_array_almost_equal(vals2, expected_vals_sq)\n\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(idx3, expected_idx)\n assert_array_almost_equal(idx4, expected_idx)\n\n # Non-euclidean scikit-learn metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"manhattan\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"manhattan\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"manhattan\")\n idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"manhattan\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n\n # Non-euclidean Scipy distance (callable)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=minkowski, metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Non-euclidean Scipy distance (string)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=\"minkowski\", metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Compare with naive implementation\n rng = np.random.RandomState(0)\n X = rng.randn(97, 149)\n Y = rng.randn(111, 149)\n\n dist = pairwise_distances(X, Y, metric=\"manhattan\")\n dist_orig_ind = dist.argmin(axis=0)\n dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))]\n<|next_version|>\n\n@pytest.mark.parametrize(\"dtype\", (np.float32, np.float64))\ndef test_pairwise_distances_argmin_min(dtype):\n # Check pairwise minimum distances computation for any metric\n X = np.asarray([[0], [1]], dtype=dtype)\n Y = np.asarray([[-2], [3]], dtype=dtype)\n\n Xsp = dok_matrix(X)\n Ysp = csr_matrix(Y, dtype=np.float32)\n\n expected_idx = [0, 1]\n expected_vals = [2, 2]\n expected_vals_sq = [4, 4]\n\n # euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"euclidean\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"euclidean\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"euclidean\")\n idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"euclidean\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(idxsp2, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n # We don't want np.matrix here\n assert type(idxsp) == np.ndarray\n assert type(valssp) == np.ndarray\n\n # Squared Euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"sqeuclidean\")\n idx2, vals2 = pairwise_distances_argmin_min(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n idx3 = pairwise_distances_argmin(X, Y, metric=\"sqeuclidean\")\n idx4 = pairwise_distances_argmin(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n\n assert_array_almost_equal(vals, expected_vals_sq)\n assert_array_almost_equal(vals2, expected_vals_sq)\n\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(idx3, expected_idx)\n assert_array_almost_equal(idx4, expected_idx)\n\n # Non-euclidean scikit-learn metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"manhattan\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"manhattan\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"manhattan\")\n idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"manhattan\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(idxsp2, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n\n # Non-euclidean Scipy distance (callable)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=minkowski, metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Non-euclidean Scipy distance (string)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=\"minkowski\", metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Compare with naive implementation\n rng = np.random.RandomState(0)\n X = rng.randn(97, 149)\n Y = rng.randn(111, 149)\n\n dist = pairwise_distances(X, Y, metric=\"manhattan\")\n dist_orig_ind = dist.argmin(axis=0)\n dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))]\n", "current_contents": "\n@pytest.mark.parametrize(\"dtype\", (np.float32, np.float64))\ndef test_pairwise_distances_argmin_min(dtype):\n # Check pairwise minimum distances computation for any metric\n X = np.asarray([[0], [1]], dtype=dtype)\n Y = np.asarray([[-2], [3]], dtype=dtype)\n\n Xsp = dok_matrix(X)\n Ysp = csr_matrix(Y, dtype=np.float32)\n\n expected_idx = [0, 1]\n expected_vals = [2, 2]\n expected_vals_sq = [4, 4]\n\n # euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"euclidean\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"euclidean\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"euclidean\")\n idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"euclidean\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(idxsp2, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n # We don't want np.matrix here\n assert type(idxsp) == np.ndarray\n assert type(valssp) == np.ndarray\n\n # Squared Euclidean metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"sqeuclidean\")\n idx2, vals2 = pairwise_distances_argmin_min(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n idx3 = pairwise_distances_argmin(X, Y, metric=\"sqeuclidean\")\n idx4 = pairwise_distances_argmin(\n X, Y, metric=\"euclidean\", metric_kwargs={\"squared\": True}\n )\n\n assert_array_almost_equal(vals, expected_vals_sq)\n assert_array_almost_equal(vals2, expected_vals_sq)\n\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(idx3, expected_idx)\n assert_array_almost_equal(idx4, expected_idx)\n\n # Non-euclidean scikit-learn metric\n idx, vals = pairwise_distances_argmin_min(X, Y, metric=\"manhattan\")\n idx2 = pairwise_distances_argmin(X, Y, metric=\"manhattan\")\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(idx2, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n # sparse matrix case\n idxsp, valssp = pairwise_distances_argmin_min(Xsp, Ysp, metric=\"manhattan\")\n idxsp2 = pairwise_distances_argmin(Xsp, Ysp, metric=\"manhattan\")\n assert_array_almost_equal(idxsp, expected_idx)\n assert_array_almost_equal(valssp, expected_vals)\n\n # Non-euclidean Scipy distance (callable)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=minkowski, metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Non-euclidean Scipy distance (string)\n idx, vals = pairwise_distances_argmin_min(\n X, Y, metric=\"minkowski\", metric_kwargs={\"p\": 2}\n )\n assert_array_almost_equal(idx, expected_idx)\n assert_array_almost_equal(vals, expected_vals)\n\n # Compare with naive implementation\n rng = np.random.RandomState(0)\n X = rng.randn(97, 149)\n Y = rng.randn(111, 149)\n\n dist = pairwise_distances(X, Y, metric=\"manhattan\")\n dist_orig_ind = dist.argmin(axis=0)\n dist_orig_val = dist[dist_orig_ind, range(len(dist_orig_ind))]"} {"commit": "8ea2997dfcd72126cdd6793a2c5293406407b1dc", "message": "FIX SimpleImputer uses dtype seen in fit for transform (#22063)", "old_file": "sklearn/impute/_base.py", "new_file": "sklearn/impute/_base.py", "status": "M", "old_contents": " allowed_strategies = [\"mean\", \"median\", \"most_frequent\", \"constant\"]\n if self.strategy not in allowed_strategies:\n raise ValueError(\n \"Can only use these strategies: {0} got strategy={1}\".format(\n allowed_strategies, self.strategy\n )\n )\n\n if self.strategy in (\"most_frequent\", \"constant\"):\n # If input is a list of strings, dtype = object.\n # Otherwise ValueError is raised in SimpleImputer\n # with strategy='most_frequent' or 'constant'\n # because the list is converted to Unicode numpy array\n if isinstance(X, list) and any(\n isinstance(elem, str) for row in X for elem in row\n ):\n dtype = object\n else:\n dtype = None\n else:\n dtype = FLOAT_DTYPES\n\n if _is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values):\n force_all_finite = \"allow-nan\"\n else:\n force_all_finite = True\n\n try:\n X = self._validate_data(\n X,\n reset=in_fit,\n accept_sparse=\"csc\",\n dtype=dtype,\n force_all_finite=force_all_finite,\n copy=self.copy,\n )\n except ValueError as ve:\n if \"could not convert\" in str(ve):\n new_ve = ValueError(\n \"Cannot use {} strategy with non-numeric data:\\n{}\".format(\n self.strategy, ve\n )\n )\n raise new_ve from None\n else:\n raise ve\n\n _check_inputs_dtype(X, self.missing_values)\n if X.dtype.kind not in (\"i\", \"u\", \"f\", \"O\"):\n raise ValueError(\n \"SimpleImputer does not support data with dtype \"\n \"{0}. Please provide either a numeric array (with\"\n \" a floating point or integer dtype) or \"\n \"categorical data represented either as an array \"\n \"with integer dtype or an array of string values \"\n \"with an object dtype.\".format(X.dtype)\n )\n\n return X\n\n def fit(self, X, y=None):\n \"\"\"Fit the imputer on `X`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Input data, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : Ignored", "new_contents": " allowed_strategies = [\"mean\", \"median\", \"most_frequent\", \"constant\"]\n if self.strategy not in allowed_strategies:\n raise ValueError(\n \"Can only use these strategies: {0} got strategy={1}\".format(\n allowed_strategies, self.strategy\n )\n )\n\n if self.strategy in (\"most_frequent\", \"constant\"):\n # If input is a list of strings, dtype = object.\n # Otherwise ValueError is raised in SimpleImputer\n # with strategy='most_frequent' or 'constant'\n # because the list is converted to Unicode numpy array\n if isinstance(X, list) and any(\n isinstance(elem, str) for row in X for elem in row\n ):\n dtype = object\n else:\n dtype = None\n else:\n dtype = FLOAT_DTYPES\n\n if not in_fit and self._fit_dtype.kind == \"O\":\n # Use object dtype if fitted on object dtypes\n dtype = self._fit_dtype\n\n if _is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values):\n force_all_finite = \"allow-nan\"\n else:\n force_all_finite = True\n\n try:\n X = self._validate_data(\n X,\n reset=in_fit,\n accept_sparse=\"csc\",\n dtype=dtype,\n force_all_finite=force_all_finite,\n copy=self.copy,\n )\n except ValueError as ve:\n if \"could not convert\" in str(ve):\n new_ve = ValueError(\n \"Cannot use {} strategy with non-numeric data:\\n{}\".format(\n self.strategy, ve\n )\n )\n raise new_ve from None\n else:\n raise ve\n\n if in_fit:\n # Use the dtype seen in `fit` for non-`fit` conversion\n self._fit_dtype = X.dtype\n\n _check_inputs_dtype(X, self.missing_values)\n if X.dtype.kind not in (\"i\", \"u\", \"f\", \"O\"):\n raise ValueError(\n \"SimpleImputer does not support data with dtype \"\n \"{0}. Please provide either a numeric array (with\"\n \" a floating point or integer dtype) or \"\n \"categorical data represented either as an array \"\n \"with integer dtype or an array of string values \"\n \"with an object dtype.\".format(X.dtype)\n )\n\n return X\n\n def fit(self, X, y=None):\n \"\"\"Fit the imputer on `X`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Input data, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : Ignored", "text": "<|original_code|>\n allowed_strategies = [\"mean\", \"median\", \"most_frequent\", \"constant\"]\n if self.strategy not in allowed_strategies:\n raise ValueError(\n \"Can only use these strategies: {0} got strategy={1}\".format(\n allowed_strategies, self.strategy\n )\n )\n\n if self.strategy in (\"most_frequent\", \"constant\"):\n # If input is a list of strings, dtype = object.\n # Otherwise ValueError is raised in SimpleImputer\n # with strategy='most_frequent' or 'constant'\n # because the list is converted to Unicode numpy array\n if isinstance(X, list) and any(\n isinstance(elem, str) for row in X for elem in row\n ):\n dtype = object\n else:\n dtype = None\n else:\n dtype = FLOAT_DTYPES\n\n if _is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values):\n force_all_finite = \"allow-nan\"\n else:\n force_all_finite = True\n\n try:\n X = self._validate_data(\n X,\n reset=in_fit,\n accept_sparse=\"csc\",\n dtype=dtype,\n force_all_finite=force_all_finite,\n copy=self.copy,\n )\n except ValueError as ve:\n if \"could not convert\" in str(ve):\n new_ve = ValueError(\n \"Cannot use {} strategy with non-numeric data:\\n{}\".format(\n self.strategy, ve\n )\n )\n raise new_ve from None\n else:\n raise ve\n\n _check_inputs_dtype(X, self.missing_values)\n if X.dtype.kind not in (\"i\", \"u\", \"f\", \"O\"):\n raise ValueError(\n \"SimpleImputer does not support data with dtype \"\n \"{0}. Please provide either a numeric array (with\"\n \" a floating point or integer dtype) or \"\n \"categorical data represented either as an array \"\n \"with integer dtype or an array of string values \"\n \"with an object dtype.\".format(X.dtype)\n )\n\n return X\n\n def fit(self, X, y=None):\n \"\"\"Fit the imputer on `X`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Input data, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : Ignored\n<|edits_diff|>\n--- sklearn/impute/_base.py\n+++ sklearn/impute/_base.py\n@@ -19,6 +19,10 @@\n dtype = None\n else:\n dtype = FLOAT_DTYPES\n+\n+ if not in_fit and self._fit_dtype.kind == \"O\":\n+ # Use object dtype if fitted on object dtypes\n+ dtype = self._fit_dtype\n \n if _is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values):\n force_all_finite = \"allow-nan\"\n<|current_version|>\n allowed_strategies = [\"mean\", \"median\", \"most_frequent\", \"constant\"]\n if self.strategy not in allowed_strategies:\n raise ValueError(\n \"Can only use these strategies: {0} got strategy={1}\".format(\n allowed_strategies, self.strategy\n )\n )\n\n if self.strategy in (\"most_frequent\", \"constant\"):\n # If input is a list of strings, dtype = object.\n # Otherwise ValueError is raised in SimpleImputer\n # with strategy='most_frequent' or 'constant'\n # because the list is converted to Unicode numpy array\n if isinstance(X, list) and any(\n isinstance(elem, str) for row in X for elem in row\n ):\n dtype = object\n else:\n dtype = None\n else:\n dtype = FLOAT_DTYPES\n\n if not in_fit and self._fit_dtype.kind == \"O\":\n # Use object dtype if fitted on object dtypes\n dtype = self._fit_dtype\n\n if _is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values):\n force_all_finite = \"allow-nan\"\n else:\n force_all_finite = True\n\n try:\n X = self._validate_data(\n X,\n reset=in_fit,\n accept_sparse=\"csc\",\n dtype=dtype,\n force_all_finite=force_all_finite,\n copy=self.copy,\n )\n except ValueError as ve:\n if \"could not convert\" in str(ve):\n new_ve = ValueError(\n \"Cannot use {} strategy with non-numeric data:\\n{}\".format(\n self.strategy, ve\n )\n )\n raise new_ve from None\n else:\n raise ve\n\n _check_inputs_dtype(X, self.missing_values)\n if X.dtype.kind not in (\"i\", \"u\", \"f\", \"O\"):\n raise ValueError(\n \"SimpleImputer does not support data with dtype \"\n \"{0}. Please provide either a numeric array (with\"\n \" a floating point or integer dtype) or \"\n \"categorical data represented either as an array \"\n \"with integer dtype or an array of string values \"\n \"with an object dtype.\".format(X.dtype)\n )\n\n return X\n\n def fit(self, X, y=None):\n \"\"\"Fit the imputer on `X`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Input data, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : Ignored\n<|next_version|>\n allowed_strategies = [\"mean\", \"median\", \"most_frequent\", \"constant\"]\n if self.strategy not in allowed_strategies:\n raise ValueError(\n \"Can only use these strategies: {0} got strategy={1}\".format(\n allowed_strategies, self.strategy\n )\n )\n\n if self.strategy in (\"most_frequent\", \"constant\"):\n # If input is a list of strings, dtype = object.\n # Otherwise ValueError is raised in SimpleImputer\n # with strategy='most_frequent' or 'constant'\n # because the list is converted to Unicode numpy array\n if isinstance(X, list) and any(\n isinstance(elem, str) for row in X for elem in row\n ):\n dtype = object\n else:\n dtype = None\n else:\n dtype = FLOAT_DTYPES\n\n if not in_fit and self._fit_dtype.kind == \"O\":\n # Use object dtype if fitted on object dtypes\n dtype = self._fit_dtype\n\n if _is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values):\n force_all_finite = \"allow-nan\"\n else:\n force_all_finite = True\n\n try:\n X = self._validate_data(\n X,\n reset=in_fit,\n accept_sparse=\"csc\",\n dtype=dtype,\n force_all_finite=force_all_finite,\n copy=self.copy,\n )\n except ValueError as ve:\n if \"could not convert\" in str(ve):\n new_ve = ValueError(\n \"Cannot use {} strategy with non-numeric data:\\n{}\".format(\n self.strategy, ve\n )\n )\n raise new_ve from None\n else:\n raise ve\n\n if in_fit:\n # Use the dtype seen in `fit` for non-`fit` conversion\n self._fit_dtype = X.dtype\n\n _check_inputs_dtype(X, self.missing_values)\n if X.dtype.kind not in (\"i\", \"u\", \"f\", \"O\"):\n raise ValueError(\n \"SimpleImputer does not support data with dtype \"\n \"{0}. Please provide either a numeric array (with\"\n \" a floating point or integer dtype) or \"\n \"categorical data represented either as an array \"\n \"with integer dtype or an array of string values \"\n \"with an object dtype.\".format(X.dtype)\n )\n\n return X\n\n def fit(self, X, y=None):\n \"\"\"Fit the imputer on `X`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Input data, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : Ignored\n", "current_contents": " allowed_strategies = [\"mean\", \"median\", \"most_frequent\", \"constant\"]\n if self.strategy not in allowed_strategies:\n raise ValueError(\n \"Can only use these strategies: {0} got strategy={1}\".format(\n allowed_strategies, self.strategy\n )\n )\n\n if self.strategy in (\"most_frequent\", \"constant\"):\n # If input is a list of strings, dtype = object.\n # Otherwise ValueError is raised in SimpleImputer\n # with strategy='most_frequent' or 'constant'\n # because the list is converted to Unicode numpy array\n if isinstance(X, list) and any(\n isinstance(elem, str) for row in X for elem in row\n ):\n dtype = object\n else:\n dtype = None\n else:\n dtype = FLOAT_DTYPES\n\n if not in_fit and self._fit_dtype.kind == \"O\":\n # Use object dtype if fitted on object dtypes\n dtype = self._fit_dtype\n\n if _is_pandas_na(self.missing_values) or is_scalar_nan(self.missing_values):\n force_all_finite = \"allow-nan\"\n else:\n force_all_finite = True\n\n try:\n X = self._validate_data(\n X,\n reset=in_fit,\n accept_sparse=\"csc\",\n dtype=dtype,\n force_all_finite=force_all_finite,\n copy=self.copy,\n )\n except ValueError as ve:\n if \"could not convert\" in str(ve):\n new_ve = ValueError(\n \"Cannot use {} strategy with non-numeric data:\\n{}\".format(\n self.strategy, ve\n )\n )\n raise new_ve from None\n else:\n raise ve\n\n _check_inputs_dtype(X, self.missing_values)\n if X.dtype.kind not in (\"i\", \"u\", \"f\", \"O\"):\n raise ValueError(\n \"SimpleImputer does not support data with dtype \"\n \"{0}. Please provide either a numeric array (with\"\n \" a floating point or integer dtype) or \"\n \"categorical data represented either as an array \"\n \"with integer dtype or an array of string values \"\n \"with an object dtype.\".format(X.dtype)\n )\n\n return X\n\n def fit(self, X, y=None):\n \"\"\"Fit the imputer on `X`.\n\n Parameters\n ----------\n X : {array-like, sparse matrix}, shape (n_samples, n_features)\n Input data, where `n_samples` is the number of samples and\n `n_features` is the number of features.\n\n y : Ignored"} {"commit": "bd71f8eefa14182e517115767a4e0bb8e4a28c2b", "message": "BUG Fixes division by zero in PCA `get_precision` (#22300)", "old_file": "sklearn/decomposition/tests/test_pca.py", "new_file": "sklearn/decomposition/tests/test_pca.py", "status": "M", "old_contents": "def test_pca_score_consistency_solvers(svd_solver):\n # Check the consistency of score between solvers\n X, _ = datasets.load_digits(return_X_y=True)\n pca_full = PCA(n_components=30, svd_solver=\"full\", random_state=0)\n pca_other = PCA(n_components=30, svd_solver=svd_solver, random_state=0)\n pca_full.fit(X)\n pca_other.fit(X)\n assert_allclose(pca_full.score(X), pca_other.score(X), rtol=5e-6)\n\n\n# arpack raises ValueError for n_components == min(n_samples, n_features)\n@pytest.mark.parametrize(\"svd_solver\", [\"full\", \"randomized\"])\ndef test_pca_zero_noise_variance_edge_cases(svd_solver):\n # ensure that noise_variance_ is 0 in edge cases\n # when n_components == min(n_samples, n_features)\n n, p = 100, 3\n rng = np.random.RandomState(0)\n X = rng.randn(n, p) * 0.1 + np.array([3, 4, 5])\n\n pca = PCA(n_components=p, svd_solver=svd_solver)\n pca.fit(X)\n assert pca.noise_variance_ == 0\n\n pca.fit(X.T)\n assert pca.noise_variance_ == 0\n\n\n@pytest.mark.parametrize(\n \"data, n_components, expected_solver\",\n [ # case: n_components in (0,1) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 0.5, \"full\"),\n # case: max(X.shape) <= 500 => 'full'\n (np.random.RandomState(0).uniform(size=(10, 50)), 5, \"full\"),\n # case: n_components >= .8 * min(X.shape) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 50, \"full\"),\n # n_components >= 1 and n_components < .8*min(X.shape) => 'randomized'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 10, \"randomized\"),\n ],\n)\ndef test_pca_svd_solver_auto(data, n_components, expected_solver):\n pca_auto = PCA(n_components=n_components, random_state=0)\n pca_test = PCA(\n n_components=n_components, svd_solver=expected_solver, random_state=0\n )\n pca_auto.fit(data)\n pca_test.fit(data)\n assert_allclose(pca_auto.components_, pca_test.components_)\n\n", "new_contents": "def test_pca_score_consistency_solvers(svd_solver):\n # Check the consistency of score between solvers\n X, _ = datasets.load_digits(return_X_y=True)\n pca_full = PCA(n_components=30, svd_solver=\"full\", random_state=0)\n pca_other = PCA(n_components=30, svd_solver=svd_solver, random_state=0)\n pca_full.fit(X)\n pca_other.fit(X)\n assert_allclose(pca_full.score(X), pca_other.score(X), rtol=5e-6)\n\n\n# arpack raises ValueError for n_components == min(n_samples, n_features)\n@pytest.mark.parametrize(\"svd_solver\", [\"full\", \"randomized\"])\ndef test_pca_zero_noise_variance_edge_cases(svd_solver):\n # ensure that noise_variance_ is 0 in edge cases\n # when n_components == min(n_samples, n_features)\n n, p = 100, 3\n rng = np.random.RandomState(0)\n X = rng.randn(n, p) * 0.1 + np.array([3, 4, 5])\n\n pca = PCA(n_components=p, svd_solver=svd_solver)\n pca.fit(X)\n assert pca.noise_variance_ == 0\n # Non-regression test for gh-12489\n # ensure no divide-by-zero error for n_components == n_features < n_samples\n pca.score(X)\n\n pca.fit(X.T)\n assert pca.noise_variance_ == 0\n # Non-regression test for gh-12489\n # ensure no divide-by-zero error for n_components == n_samples < n_features\n pca.score(X.T)\n\n\n@pytest.mark.parametrize(\n \"data, n_components, expected_solver\",\n [ # case: n_components in (0,1) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 0.5, \"full\"),\n # case: max(X.shape) <= 500 => 'full'\n (np.random.RandomState(0).uniform(size=(10, 50)), 5, \"full\"),\n # case: n_components >= .8 * min(X.shape) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 50, \"full\"),\n # n_components >= 1 and n_components < .8*min(X.shape) => 'randomized'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 10, \"randomized\"),\n ],\n)\ndef test_pca_svd_solver_auto(data, n_components, expected_solver):\n pca_auto = PCA(n_components=n_components, random_state=0)\n pca_test = PCA(\n n_components=n_components, svd_solver=expected_solver, random_state=0\n )\n pca_auto.fit(data)\n pca_test.fit(data)\n assert_allclose(pca_auto.components_, pca_test.components_)\n\n", "text": "<|original_code|>\ndef test_pca_score_consistency_solvers(svd_solver):\n # Check the consistency of score between solvers\n X, _ = datasets.load_digits(return_X_y=True)\n pca_full = PCA(n_components=30, svd_solver=\"full\", random_state=0)\n pca_other = PCA(n_components=30, svd_solver=svd_solver, random_state=0)\n pca_full.fit(X)\n pca_other.fit(X)\n assert_allclose(pca_full.score(X), pca_other.score(X), rtol=5e-6)\n\n\n# arpack raises ValueError for n_components == min(n_samples, n_features)\n@pytest.mark.parametrize(\"svd_solver\", [\"full\", \"randomized\"])\ndef test_pca_zero_noise_variance_edge_cases(svd_solver):\n # ensure that noise_variance_ is 0 in edge cases\n # when n_components == min(n_samples, n_features)\n n, p = 100, 3\n rng = np.random.RandomState(0)\n X = rng.randn(n, p) * 0.1 + np.array([3, 4, 5])\n\n pca = PCA(n_components=p, svd_solver=svd_solver)\n pca.fit(X)\n assert pca.noise_variance_ == 0\n\n pca.fit(X.T)\n assert pca.noise_variance_ == 0\n\n\n@pytest.mark.parametrize(\n \"data, n_components, expected_solver\",\n [ # case: n_components in (0,1) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 0.5, \"full\"),\n # case: max(X.shape) <= 500 => 'full'\n (np.random.RandomState(0).uniform(size=(10, 50)), 5, \"full\"),\n # case: n_components >= .8 * min(X.shape) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 50, \"full\"),\n # n_components >= 1 and n_components < .8*min(X.shape) => 'randomized'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 10, \"randomized\"),\n ],\n)\ndef test_pca_svd_solver_auto(data, n_components, expected_solver):\n pca_auto = PCA(n_components=n_components, random_state=0)\n pca_test = PCA(\n n_components=n_components, svd_solver=expected_solver, random_state=0\n )\n pca_auto.fit(data)\n pca_test.fit(data)\n assert_allclose(pca_auto.components_, pca_test.components_)\n\n\n<|edits_diff|>\n--- sklearn/decomposition/tests/test_pca.py\n+++ sklearn/decomposition/tests/test_pca.py\n@@ -20,6 +20,9 @@\n pca = PCA(n_components=p, svd_solver=svd_solver)\n pca.fit(X)\n assert pca.noise_variance_ == 0\n+ # Non-regression test for gh-12489\n+ # ensure no divide-by-zero error for n_components == n_features < n_samples\n+ pca.score(X)\n \n pca.fit(X.T)\n assert pca.noise_variance_ == 0\n<|current_version|>\ndef test_pca_score_consistency_solvers(svd_solver):\n # Check the consistency of score between solvers\n X, _ = datasets.load_digits(return_X_y=True)\n pca_full = PCA(n_components=30, svd_solver=\"full\", random_state=0)\n pca_other = PCA(n_components=30, svd_solver=svd_solver, random_state=0)\n pca_full.fit(X)\n pca_other.fit(X)\n assert_allclose(pca_full.score(X), pca_other.score(X), rtol=5e-6)\n\n\n# arpack raises ValueError for n_components == min(n_samples, n_features)\n@pytest.mark.parametrize(\"svd_solver\", [\"full\", \"randomized\"])\ndef test_pca_zero_noise_variance_edge_cases(svd_solver):\n # ensure that noise_variance_ is 0 in edge cases\n # when n_components == min(n_samples, n_features)\n n, p = 100, 3\n rng = np.random.RandomState(0)\n X = rng.randn(n, p) * 0.1 + np.array([3, 4, 5])\n\n pca = PCA(n_components=p, svd_solver=svd_solver)\n pca.fit(X)\n assert pca.noise_variance_ == 0\n # Non-regression test for gh-12489\n # ensure no divide-by-zero error for n_components == n_features < n_samples\n pca.score(X)\n\n pca.fit(X.T)\n assert pca.noise_variance_ == 0\n\n\n@pytest.mark.parametrize(\n \"data, n_components, expected_solver\",\n [ # case: n_components in (0,1) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 0.5, \"full\"),\n # case: max(X.shape) <= 500 => 'full'\n (np.random.RandomState(0).uniform(size=(10, 50)), 5, \"full\"),\n # case: n_components >= .8 * min(X.shape) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 50, \"full\"),\n # n_components >= 1 and n_components < .8*min(X.shape) => 'randomized'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 10, \"randomized\"),\n ],\n)\ndef test_pca_svd_solver_auto(data, n_components, expected_solver):\n pca_auto = PCA(n_components=n_components, random_state=0)\n pca_test = PCA(\n n_components=n_components, svd_solver=expected_solver, random_state=0\n )\n pca_auto.fit(data)\n pca_test.fit(data)\n assert_allclose(pca_auto.components_, pca_test.components_)\n\n\n<|next_version|>\ndef test_pca_score_consistency_solvers(svd_solver):\n # Check the consistency of score between solvers\n X, _ = datasets.load_digits(return_X_y=True)\n pca_full = PCA(n_components=30, svd_solver=\"full\", random_state=0)\n pca_other = PCA(n_components=30, svd_solver=svd_solver, random_state=0)\n pca_full.fit(X)\n pca_other.fit(X)\n assert_allclose(pca_full.score(X), pca_other.score(X), rtol=5e-6)\n\n\n# arpack raises ValueError for n_components == min(n_samples, n_features)\n@pytest.mark.parametrize(\"svd_solver\", [\"full\", \"randomized\"])\ndef test_pca_zero_noise_variance_edge_cases(svd_solver):\n # ensure that noise_variance_ is 0 in edge cases\n # when n_components == min(n_samples, n_features)\n n, p = 100, 3\n rng = np.random.RandomState(0)\n X = rng.randn(n, p) * 0.1 + np.array([3, 4, 5])\n\n pca = PCA(n_components=p, svd_solver=svd_solver)\n pca.fit(X)\n assert pca.noise_variance_ == 0\n # Non-regression test for gh-12489\n # ensure no divide-by-zero error for n_components == n_features < n_samples\n pca.score(X)\n\n pca.fit(X.T)\n assert pca.noise_variance_ == 0\n # Non-regression test for gh-12489\n # ensure no divide-by-zero error for n_components == n_samples < n_features\n pca.score(X.T)\n\n\n@pytest.mark.parametrize(\n \"data, n_components, expected_solver\",\n [ # case: n_components in (0,1) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 0.5, \"full\"),\n # case: max(X.shape) <= 500 => 'full'\n (np.random.RandomState(0).uniform(size=(10, 50)), 5, \"full\"),\n # case: n_components >= .8 * min(X.shape) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 50, \"full\"),\n # n_components >= 1 and n_components < .8*min(X.shape) => 'randomized'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 10, \"randomized\"),\n ],\n)\ndef test_pca_svd_solver_auto(data, n_components, expected_solver):\n pca_auto = PCA(n_components=n_components, random_state=0)\n pca_test = PCA(\n n_components=n_components, svd_solver=expected_solver, random_state=0\n )\n pca_auto.fit(data)\n pca_test.fit(data)\n assert_allclose(pca_auto.components_, pca_test.components_)\n\n\n", "current_contents": "def test_pca_score_consistency_solvers(svd_solver):\n # Check the consistency of score between solvers\n X, _ = datasets.load_digits(return_X_y=True)\n pca_full = PCA(n_components=30, svd_solver=\"full\", random_state=0)\n pca_other = PCA(n_components=30, svd_solver=svd_solver, random_state=0)\n pca_full.fit(X)\n pca_other.fit(X)\n assert_allclose(pca_full.score(X), pca_other.score(X), rtol=5e-6)\n\n\n# arpack raises ValueError for n_components == min(n_samples, n_features)\n@pytest.mark.parametrize(\"svd_solver\", [\"full\", \"randomized\"])\ndef test_pca_zero_noise_variance_edge_cases(svd_solver):\n # ensure that noise_variance_ is 0 in edge cases\n # when n_components == min(n_samples, n_features)\n n, p = 100, 3\n rng = np.random.RandomState(0)\n X = rng.randn(n, p) * 0.1 + np.array([3, 4, 5])\n\n pca = PCA(n_components=p, svd_solver=svd_solver)\n pca.fit(X)\n assert pca.noise_variance_ == 0\n # Non-regression test for gh-12489\n # ensure no divide-by-zero error for n_components == n_features < n_samples\n pca.score(X)\n\n pca.fit(X.T)\n assert pca.noise_variance_ == 0\n\n\n@pytest.mark.parametrize(\n \"data, n_components, expected_solver\",\n [ # case: n_components in (0,1) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 0.5, \"full\"),\n # case: max(X.shape) <= 500 => 'full'\n (np.random.RandomState(0).uniform(size=(10, 50)), 5, \"full\"),\n # case: n_components >= .8 * min(X.shape) => 'full'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 50, \"full\"),\n # n_components >= 1 and n_components < .8*min(X.shape) => 'randomized'\n (np.random.RandomState(0).uniform(size=(1000, 50)), 10, \"randomized\"),\n ],\n)\ndef test_pca_svd_solver_auto(data, n_components, expected_solver):\n pca_auto = PCA(n_components=n_components, random_state=0)\n pca_test = PCA(\n n_components=n_components, svd_solver=expected_solver, random_state=0\n )\n pca_auto.fit(data)\n pca_test.fit(data)\n assert_allclose(pca_auto.components_, pca_test.components_)\n\n"} {"commit": "7c2f928cbc8d5261e5b85b5e63d549a794116c3b", "message": "FIX Fixes test_compare_to_elki failure (#19221)", "old_file": "sklearn/cluster/_optics.py", "new_file": "sklearn/cluster/_optics.py", "status": "M", "old_contents": " reachability_ = np.empty(n_samples)\n reachability_.fill(np.inf)\n predecessor_ = np.empty(n_samples, dtype=int)\n predecessor_.fill(-1)\n\n nbrs = NearestNeighbors(n_neighbors=min_samples,\n algorithm=algorithm,\n leaf_size=leaf_size,\n metric=metric,\n metric_params=metric_params,\n p=p,\n n_jobs=n_jobs)\n\n nbrs.fit(X)\n # Here we first do a kNN query for each point, this differs from\n # the original OPTICS that only used epsilon range queries.\n # TODO: handle working_memory somehow?\n core_distances_ = _compute_core_distances_(X=X, neighbors=nbrs,\n min_samples=min_samples,\n working_memory=None)\n # OPTICS puts an upper limit on these, use inf for undefined.\n core_distances_[core_distances_ > max_eps] = np.inf\n\n # Main OPTICS loop. Not parallelizable. The order that entries are\n # written to the 'ordering_' list is important!\n # Note that this implementation is O(n^2) theoretically, but\n # supposedly with very low constant factors.\n processed = np.zeros(X.shape[0], dtype=bool)\n ordering = np.zeros(X.shape[0], dtype=int)\n for ordering_idx in range(X.shape[0]):\n # Choose next based on smallest reachability distance\n # (And prefer smaller ids on ties, possibly np.inf!)\n index = np.where(processed == 0)[0]\n point = index[np.argmin(reachability_[index])]\n\n processed[point] = True\n ordering[ordering_idx] = point\n if core_distances_[point] != np.inf:\n _set_reach_dist(core_distances_=core_distances_,\n reachability_=reachability_,\n predecessor_=predecessor_,\n point_index=point,\n processed=processed, X=X, nbrs=nbrs,\n metric=metric, metric_params=metric_params,\n p=p, max_eps=max_eps)\n if np.all(np.isinf(reachability_)):\n warnings.warn(\"All reachability values are inf. Set a larger\"\n \" max_eps or all data will be considered outliers.\",\n UserWarning)\n return ordering, core_distances_, reachability_, predecessor_\n\n\ndef _set_reach_dist(core_distances_, reachability_, predecessor_,\n point_index, processed, X, nbrs, metric, metric_params,\n p, max_eps):\n P = X[point_index:point_index + 1]\n # Assume that radius_neighbors is faster without distances\n # and we don't need all distances, nevertheless, this means\n # we may be doing some work twice.\n indices = nbrs.radius_neighbors(P, radius=max_eps,\n return_distance=False)[0]\n\n # Getting indices of neighbors that have not been processed\n unproc = np.compress(~np.take(processed, indices), indices)\n # Neighbors of current point are already processed.\n if not unproc.size:\n return\n\n # Only compute distances to unprocessed neighbors:\n if metric == 'precomputed':\n dists = X[point_index, unproc]\n else:\n _params = dict() if metric_params is None else metric_params.copy()\n if metric == 'minkowski' and 'p' not in _params:\n # the same logic as neighbors, p is ignored if explicitly set\n # in the dict params\n _params['p'] = p\n dists = pairwise_distances(P, np.take(X, unproc, axis=0),\n metric=metric, n_jobs=None,\n **_params).ravel()\n\n rdists = np.maximum(dists, core_distances_[point_index])\n improved = np.where(rdists < np.take(reachability_, unproc))\n reachability_[unproc[improved]] = rdists[improved]\n predecessor_[unproc[improved]] = point_index\n\n\n@_deprecate_positional_args\ndef cluster_optics_dbscan(*, reachability, core_distances, ordering, eps):\n \"\"\"Performs DBSCAN extraction for an arbitrary epsilon.\n\n Extracting the clusters runs in linear time. Note that this results in\n ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with\n similar settings and ``eps``, only if ``eps`` is close to ``max_eps``.\n\n Parameters\n ----------\n reachability : array of shape (n_samples,)\n Reachability distances calculated by OPTICS (``reachability_``)\n\n core_distances : array of shape (n_samples,)\n Distances at which points become core (``core_distances_``)\n\n ordering : array of shape (n_samples,)\n OPTICS ordered point indices (``ordering_``)\n", "new_contents": " reachability_ = np.empty(n_samples)\n reachability_.fill(np.inf)\n predecessor_ = np.empty(n_samples, dtype=int)\n predecessor_.fill(-1)\n\n nbrs = NearestNeighbors(n_neighbors=min_samples,\n algorithm=algorithm,\n leaf_size=leaf_size,\n metric=metric,\n metric_params=metric_params,\n p=p,\n n_jobs=n_jobs)\n\n nbrs.fit(X)\n # Here we first do a kNN query for each point, this differs from\n # the original OPTICS that only used epsilon range queries.\n # TODO: handle working_memory somehow?\n core_distances_ = _compute_core_distances_(X=X, neighbors=nbrs,\n min_samples=min_samples,\n working_memory=None)\n # OPTICS puts an upper limit on these, use inf for undefined.\n core_distances_[core_distances_ > max_eps] = np.inf\n np.around(core_distances_,\n decimals=np.finfo(core_distances_.dtype).precision,\n out=core_distances_)\n\n # Main OPTICS loop. Not parallelizable. The order that entries are\n # written to the 'ordering_' list is important!\n # Note that this implementation is O(n^2) theoretically, but\n # supposedly with very low constant factors.\n processed = np.zeros(X.shape[0], dtype=bool)\n ordering = np.zeros(X.shape[0], dtype=int)\n for ordering_idx in range(X.shape[0]):\n # Choose next based on smallest reachability distance\n # (And prefer smaller ids on ties, possibly np.inf!)\n index = np.where(processed == 0)[0]\n point = index[np.argmin(reachability_[index])]\n\n processed[point] = True\n ordering[ordering_idx] = point\n if core_distances_[point] != np.inf:\n _set_reach_dist(core_distances_=core_distances_,\n reachability_=reachability_,\n predecessor_=predecessor_,\n point_index=point,\n processed=processed, X=X, nbrs=nbrs,\n metric=metric, metric_params=metric_params,\n p=p, max_eps=max_eps)\n if np.all(np.isinf(reachability_)):\n warnings.warn(\"All reachability values are inf. Set a larger\"\n \" max_eps or all data will be considered outliers.\",\n UserWarning)\n return ordering, core_distances_, reachability_, predecessor_\n\n\ndef _set_reach_dist(core_distances_, reachability_, predecessor_,\n point_index, processed, X, nbrs, metric, metric_params,\n p, max_eps):\n P = X[point_index:point_index + 1]\n # Assume that radius_neighbors is faster without distances\n # and we don't need all distances, nevertheless, this means\n # we may be doing some work twice.\n indices = nbrs.radius_neighbors(P, radius=max_eps,\n return_distance=False)[0]\n\n # Getting indices of neighbors that have not been processed\n unproc = np.compress(~np.take(processed, indices), indices)\n # Neighbors of current point are already processed.\n if not unproc.size:\n return\n\n # Only compute distances to unprocessed neighbors:\n if metric == 'precomputed':\n dists = X[point_index, unproc]\n else:\n _params = dict() if metric_params is None else metric_params.copy()\n if metric == 'minkowski' and 'p' not in _params:\n # the same logic as neighbors, p is ignored if explicitly set\n # in the dict params\n _params['p'] = p\n dists = pairwise_distances(P, np.take(X, unproc, axis=0),\n metric=metric, n_jobs=None,\n **_params).ravel()\n\n rdists = np.maximum(dists, core_distances_[point_index])\n np.around(rdists, decimals=np.finfo(rdists.dtype).precision, out=rdists)\n improved = np.where(rdists < np.take(reachability_, unproc))\n reachability_[unproc[improved]] = rdists[improved]\n predecessor_[unproc[improved]] = point_index\n\n\n@_deprecate_positional_args\ndef cluster_optics_dbscan(*, reachability, core_distances, ordering, eps):\n \"\"\"Performs DBSCAN extraction for an arbitrary epsilon.\n\n Extracting the clusters runs in linear time. Note that this results in\n ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with\n similar settings and ``eps``, only if ``eps`` is close to ``max_eps``.\n\n Parameters\n ----------\n reachability : array of shape (n_samples,)\n Reachability distances calculated by OPTICS (``reachability_``)\n\n core_distances : array of shape (n_samples,)\n Distances at which points become core (``core_distances_``)\n\n ordering : array of shape (n_samples,)\n OPTICS ordered point indices (``ordering_``)\n", "text": "<|original_code|>\n reachability_ = np.empty(n_samples)\n reachability_.fill(np.inf)\n predecessor_ = np.empty(n_samples, dtype=int)\n predecessor_.fill(-1)\n\n nbrs = NearestNeighbors(n_neighbors=min_samples,\n algorithm=algorithm,\n leaf_size=leaf_size,\n metric=metric,\n metric_params=metric_params,\n p=p,\n n_jobs=n_jobs)\n\n nbrs.fit(X)\n # Here we first do a kNN query for each point, this differs from\n # the original OPTICS that only used epsilon range queries.\n # TODO: handle working_memory somehow?\n core_distances_ = _compute_core_distances_(X=X, neighbors=nbrs,\n min_samples=min_samples,\n working_memory=None)\n # OPTICS puts an upper limit on these, use inf for undefined.\n core_distances_[core_distances_ > max_eps] = np.inf\n\n # Main OPTICS loop. Not parallelizable. The order that entries are\n # written to the 'ordering_' list is important!\n # Note that this implementation is O(n^2) theoretically, but\n # supposedly with very low constant factors.\n processed = np.zeros(X.shape[0], dtype=bool)\n ordering = np.zeros(X.shape[0], dtype=int)\n for ordering_idx in range(X.shape[0]):\n # Choose next based on smallest reachability distance\n # (And prefer smaller ids on ties, possibly np.inf!)\n index = np.where(processed == 0)[0]\n point = index[np.argmin(reachability_[index])]\n\n processed[point] = True\n ordering[ordering_idx] = point\n if core_distances_[point] != np.inf:\n _set_reach_dist(core_distances_=core_distances_,\n reachability_=reachability_,\n predecessor_=predecessor_,\n point_index=point,\n processed=processed, X=X, nbrs=nbrs,\n metric=metric, metric_params=metric_params,\n p=p, max_eps=max_eps)\n if np.all(np.isinf(reachability_)):\n warnings.warn(\"All reachability values are inf. Set a larger\"\n \" max_eps or all data will be considered outliers.\",\n UserWarning)\n return ordering, core_distances_, reachability_, predecessor_\n\n\ndef _set_reach_dist(core_distances_, reachability_, predecessor_,\n point_index, processed, X, nbrs, metric, metric_params,\n p, max_eps):\n P = X[point_index:point_index + 1]\n # Assume that radius_neighbors is faster without distances\n # and we don't need all distances, nevertheless, this means\n # we may be doing some work twice.\n indices = nbrs.radius_neighbors(P, radius=max_eps,\n return_distance=False)[0]\n\n # Getting indices of neighbors that have not been processed\n unproc = np.compress(~np.take(processed, indices), indices)\n # Neighbors of current point are already processed.\n if not unproc.size:\n return\n\n # Only compute distances to unprocessed neighbors:\n if metric == 'precomputed':\n dists = X[point_index, unproc]\n else:\n _params = dict() if metric_params is None else metric_params.copy()\n if metric == 'minkowski' and 'p' not in _params:\n # the same logic as neighbors, p is ignored if explicitly set\n # in the dict params\n _params['p'] = p\n dists = pairwise_distances(P, np.take(X, unproc, axis=0),\n metric=metric, n_jobs=None,\n **_params).ravel()\n\n rdists = np.maximum(dists, core_distances_[point_index])\n improved = np.where(rdists < np.take(reachability_, unproc))\n reachability_[unproc[improved]] = rdists[improved]\n predecessor_[unproc[improved]] = point_index\n\n\n@_deprecate_positional_args\ndef cluster_optics_dbscan(*, reachability, core_distances, ordering, eps):\n \"\"\"Performs DBSCAN extraction for an arbitrary epsilon.\n\n Extracting the clusters runs in linear time. Note that this results in\n ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with\n similar settings and ``eps``, only if ``eps`` is close to ``max_eps``.\n\n Parameters\n ----------\n reachability : array of shape (n_samples,)\n Reachability distances calculated by OPTICS (``reachability_``)\n\n core_distances : array of shape (n_samples,)\n Distances at which points become core (``core_distances_``)\n\n ordering : array of shape (n_samples,)\n OPTICS ordered point indices (``ordering_``)\n\n<|edits_diff|>\n--- sklearn/cluster/_optics.py\n+++ sklearn/cluster/_optics.py\n@@ -20,6 +20,9 @@\n working_memory=None)\n # OPTICS puts an upper limit on these, use inf for undefined.\n core_distances_[core_distances_ > max_eps] = np.inf\n+ np.around(core_distances_,\n+ decimals=np.finfo(core_distances_.dtype).precision,\n+ out=core_distances_)\n \n # Main OPTICS loop. Not parallelizable. The order that entries are\n # written to the 'ordering_' list is important!\n<|current_version|>\n reachability_ = np.empty(n_samples)\n reachability_.fill(np.inf)\n predecessor_ = np.empty(n_samples, dtype=int)\n predecessor_.fill(-1)\n\n nbrs = NearestNeighbors(n_neighbors=min_samples,\n algorithm=algorithm,\n leaf_size=leaf_size,\n metric=metric,\n metric_params=metric_params,\n p=p,\n n_jobs=n_jobs)\n\n nbrs.fit(X)\n # Here we first do a kNN query for each point, this differs from\n # the original OPTICS that only used epsilon range queries.\n # TODO: handle working_memory somehow?\n core_distances_ = _compute_core_distances_(X=X, neighbors=nbrs,\n min_samples=min_samples,\n working_memory=None)\n # OPTICS puts an upper limit on these, use inf for undefined.\n core_distances_[core_distances_ > max_eps] = np.inf\n np.around(core_distances_,\n decimals=np.finfo(core_distances_.dtype).precision,\n out=core_distances_)\n\n # Main OPTICS loop. Not parallelizable. The order that entries are\n # written to the 'ordering_' list is important!\n # Note that this implementation is O(n^2) theoretically, but\n # supposedly with very low constant factors.\n processed = np.zeros(X.shape[0], dtype=bool)\n ordering = np.zeros(X.shape[0], dtype=int)\n for ordering_idx in range(X.shape[0]):\n # Choose next based on smallest reachability distance\n # (And prefer smaller ids on ties, possibly np.inf!)\n index = np.where(processed == 0)[0]\n point = index[np.argmin(reachability_[index])]\n\n processed[point] = True\n ordering[ordering_idx] = point\n if core_distances_[point] != np.inf:\n _set_reach_dist(core_distances_=core_distances_,\n reachability_=reachability_,\n predecessor_=predecessor_,\n point_index=point,\n processed=processed, X=X, nbrs=nbrs,\n metric=metric, metric_params=metric_params,\n p=p, max_eps=max_eps)\n if np.all(np.isinf(reachability_)):\n warnings.warn(\"All reachability values are inf. Set a larger\"\n \" max_eps or all data will be considered outliers.\",\n UserWarning)\n return ordering, core_distances_, reachability_, predecessor_\n\n\ndef _set_reach_dist(core_distances_, reachability_, predecessor_,\n point_index, processed, X, nbrs, metric, metric_params,\n p, max_eps):\n P = X[point_index:point_index + 1]\n # Assume that radius_neighbors is faster without distances\n # and we don't need all distances, nevertheless, this means\n # we may be doing some work twice.\n indices = nbrs.radius_neighbors(P, radius=max_eps,\n return_distance=False)[0]\n\n # Getting indices of neighbors that have not been processed\n unproc = np.compress(~np.take(processed, indices), indices)\n # Neighbors of current point are already processed.\n if not unproc.size:\n return\n\n # Only compute distances to unprocessed neighbors:\n if metric == 'precomputed':\n dists = X[point_index, unproc]\n else:\n _params = dict() if metric_params is None else metric_params.copy()\n if metric == 'minkowski' and 'p' not in _params:\n # the same logic as neighbors, p is ignored if explicitly set\n # in the dict params\n _params['p'] = p\n dists = pairwise_distances(P, np.take(X, unproc, axis=0),\n metric=metric, n_jobs=None,\n **_params).ravel()\n\n rdists = np.maximum(dists, core_distances_[point_index])\n improved = np.where(rdists < np.take(reachability_, unproc))\n reachability_[unproc[improved]] = rdists[improved]\n predecessor_[unproc[improved]] = point_index\n\n\n@_deprecate_positional_args\ndef cluster_optics_dbscan(*, reachability, core_distances, ordering, eps):\n \"\"\"Performs DBSCAN extraction for an arbitrary epsilon.\n\n Extracting the clusters runs in linear time. Note that this results in\n ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with\n similar settings and ``eps``, only if ``eps`` is close to ``max_eps``.\n\n Parameters\n ----------\n reachability : array of shape (n_samples,)\n Reachability distances calculated by OPTICS (``reachability_``)\n\n core_distances : array of shape (n_samples,)\n Distances at which points become core (``core_distances_``)\n\n ordering : array of shape (n_samples,)\n OPTICS ordered point indices (``ordering_``)\n\n<|next_version|>\n reachability_ = np.empty(n_samples)\n reachability_.fill(np.inf)\n predecessor_ = np.empty(n_samples, dtype=int)\n predecessor_.fill(-1)\n\n nbrs = NearestNeighbors(n_neighbors=min_samples,\n algorithm=algorithm,\n leaf_size=leaf_size,\n metric=metric,\n metric_params=metric_params,\n p=p,\n n_jobs=n_jobs)\n\n nbrs.fit(X)\n # Here we first do a kNN query for each point, this differs from\n # the original OPTICS that only used epsilon range queries.\n # TODO: handle working_memory somehow?\n core_distances_ = _compute_core_distances_(X=X, neighbors=nbrs,\n min_samples=min_samples,\n working_memory=None)\n # OPTICS puts an upper limit on these, use inf for undefined.\n core_distances_[core_distances_ > max_eps] = np.inf\n np.around(core_distances_,\n decimals=np.finfo(core_distances_.dtype).precision,\n out=core_distances_)\n\n # Main OPTICS loop. Not parallelizable. The order that entries are\n # written to the 'ordering_' list is important!\n # Note that this implementation is O(n^2) theoretically, but\n # supposedly with very low constant factors.\n processed = np.zeros(X.shape[0], dtype=bool)\n ordering = np.zeros(X.shape[0], dtype=int)\n for ordering_idx in range(X.shape[0]):\n # Choose next based on smallest reachability distance\n # (And prefer smaller ids on ties, possibly np.inf!)\n index = np.where(processed == 0)[0]\n point = index[np.argmin(reachability_[index])]\n\n processed[point] = True\n ordering[ordering_idx] = point\n if core_distances_[point] != np.inf:\n _set_reach_dist(core_distances_=core_distances_,\n reachability_=reachability_,\n predecessor_=predecessor_,\n point_index=point,\n processed=processed, X=X, nbrs=nbrs,\n metric=metric, metric_params=metric_params,\n p=p, max_eps=max_eps)\n if np.all(np.isinf(reachability_)):\n warnings.warn(\"All reachability values are inf. Set a larger\"\n \" max_eps or all data will be considered outliers.\",\n UserWarning)\n return ordering, core_distances_, reachability_, predecessor_\n\n\ndef _set_reach_dist(core_distances_, reachability_, predecessor_,\n point_index, processed, X, nbrs, metric, metric_params,\n p, max_eps):\n P = X[point_index:point_index + 1]\n # Assume that radius_neighbors is faster without distances\n # and we don't need all distances, nevertheless, this means\n # we may be doing some work twice.\n indices = nbrs.radius_neighbors(P, radius=max_eps,\n return_distance=False)[0]\n\n # Getting indices of neighbors that have not been processed\n unproc = np.compress(~np.take(processed, indices), indices)\n # Neighbors of current point are already processed.\n if not unproc.size:\n return\n\n # Only compute distances to unprocessed neighbors:\n if metric == 'precomputed':\n dists = X[point_index, unproc]\n else:\n _params = dict() if metric_params is None else metric_params.copy()\n if metric == 'minkowski' and 'p' not in _params:\n # the same logic as neighbors, p is ignored if explicitly set\n # in the dict params\n _params['p'] = p\n dists = pairwise_distances(P, np.take(X, unproc, axis=0),\n metric=metric, n_jobs=None,\n **_params).ravel()\n\n rdists = np.maximum(dists, core_distances_[point_index])\n np.around(rdists, decimals=np.finfo(rdists.dtype).precision, out=rdists)\n improved = np.where(rdists < np.take(reachability_, unproc))\n reachability_[unproc[improved]] = rdists[improved]\n predecessor_[unproc[improved]] = point_index\n\n\n@_deprecate_positional_args\ndef cluster_optics_dbscan(*, reachability, core_distances, ordering, eps):\n \"\"\"Performs DBSCAN extraction for an arbitrary epsilon.\n\n Extracting the clusters runs in linear time. Note that this results in\n ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with\n similar settings and ``eps``, only if ``eps`` is close to ``max_eps``.\n\n Parameters\n ----------\n reachability : array of shape (n_samples,)\n Reachability distances calculated by OPTICS (``reachability_``)\n\n core_distances : array of shape (n_samples,)\n Distances at which points become core (``core_distances_``)\n\n ordering : array of shape (n_samples,)\n OPTICS ordered point indices (``ordering_``)\n\n", "current_contents": " reachability_ = np.empty(n_samples)\n reachability_.fill(np.inf)\n predecessor_ = np.empty(n_samples, dtype=int)\n predecessor_.fill(-1)\n\n nbrs = NearestNeighbors(n_neighbors=min_samples,\n algorithm=algorithm,\n leaf_size=leaf_size,\n metric=metric,\n metric_params=metric_params,\n p=p,\n n_jobs=n_jobs)\n\n nbrs.fit(X)\n # Here we first do a kNN query for each point, this differs from\n # the original OPTICS that only used epsilon range queries.\n # TODO: handle working_memory somehow?\n core_distances_ = _compute_core_distances_(X=X, neighbors=nbrs,\n min_samples=min_samples,\n working_memory=None)\n # OPTICS puts an upper limit on these, use inf for undefined.\n core_distances_[core_distances_ > max_eps] = np.inf\n np.around(core_distances_,\n decimals=np.finfo(core_distances_.dtype).precision,\n out=core_distances_)\n\n # Main OPTICS loop. Not parallelizable. The order that entries are\n # written to the 'ordering_' list is important!\n # Note that this implementation is O(n^2) theoretically, but\n # supposedly with very low constant factors.\n processed = np.zeros(X.shape[0], dtype=bool)\n ordering = np.zeros(X.shape[0], dtype=int)\n for ordering_idx in range(X.shape[0]):\n # Choose next based on smallest reachability distance\n # (And prefer smaller ids on ties, possibly np.inf!)\n index = np.where(processed == 0)[0]\n point = index[np.argmin(reachability_[index])]\n\n processed[point] = True\n ordering[ordering_idx] = point\n if core_distances_[point] != np.inf:\n _set_reach_dist(core_distances_=core_distances_,\n reachability_=reachability_,\n predecessor_=predecessor_,\n point_index=point,\n processed=processed, X=X, nbrs=nbrs,\n metric=metric, metric_params=metric_params,\n p=p, max_eps=max_eps)\n if np.all(np.isinf(reachability_)):\n warnings.warn(\"All reachability values are inf. Set a larger\"\n \" max_eps or all data will be considered outliers.\",\n UserWarning)\n return ordering, core_distances_, reachability_, predecessor_\n\n\ndef _set_reach_dist(core_distances_, reachability_, predecessor_,\n point_index, processed, X, nbrs, metric, metric_params,\n p, max_eps):\n P = X[point_index:point_index + 1]\n # Assume that radius_neighbors is faster without distances\n # and we don't need all distances, nevertheless, this means\n # we may be doing some work twice.\n indices = nbrs.radius_neighbors(P, radius=max_eps,\n return_distance=False)[0]\n\n # Getting indices of neighbors that have not been processed\n unproc = np.compress(~np.take(processed, indices), indices)\n # Neighbors of current point are already processed.\n if not unproc.size:\n return\n\n # Only compute distances to unprocessed neighbors:\n if metric == 'precomputed':\n dists = X[point_index, unproc]\n else:\n _params = dict() if metric_params is None else metric_params.copy()\n if metric == 'minkowski' and 'p' not in _params:\n # the same logic as neighbors, p is ignored if explicitly set\n # in the dict params\n _params['p'] = p\n dists = pairwise_distances(P, np.take(X, unproc, axis=0),\n metric=metric, n_jobs=None,\n **_params).ravel()\n\n rdists = np.maximum(dists, core_distances_[point_index])\n improved = np.where(rdists < np.take(reachability_, unproc))\n reachability_[unproc[improved]] = rdists[improved]\n predecessor_[unproc[improved]] = point_index\n\n\n@_deprecate_positional_args\ndef cluster_optics_dbscan(*, reachability, core_distances, ordering, eps):\n \"\"\"Performs DBSCAN extraction for an arbitrary epsilon.\n\n Extracting the clusters runs in linear time. Note that this results in\n ``labels_`` which are close to a :class:`~sklearn.cluster.DBSCAN` with\n similar settings and ``eps``, only if ``eps`` is close to ``max_eps``.\n\n Parameters\n ----------\n reachability : array of shape (n_samples,)\n Reachability distances calculated by OPTICS (``reachability_``)\n\n core_distances : array of shape (n_samples,)\n Distances at which points become core (``core_distances_``)\n\n ordering : array of shape (n_samples,)\n OPTICS ordered point indices (``ordering_``)\n"} {"commit": "cffd98dfb4df175b8dd8459001db98b3188900f6", "message": "TST Makes sure name is correct (#18503)", "old_file": "sklearn/datasets/tests/conftest.py", "new_file": "sklearn/datasets/tests/conftest.py", "status": "M", "old_contents": "\"\"\" Network tests are only run, if data is already locally available,\nor if download is specifically requested by environment variable.\"\"\"\nimport builtins\nfrom os import environ\nimport pytest\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.datasets import fetch_covtype\nfrom sklearn.datasets import fetch_kddcup99\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.datasets import fetch_rcv1\n\n\ndef _wrapped_fetch(f, dataset_name):\n \"\"\" Fetch dataset (download if missing and requested by environment) \"\"\"\n download_if_missing = environ.get('SKLEARN_SKIP_NETWORK_TESTS', '1') == '0'\n\n def wrapped(*args, **kwargs):\n kwargs['download_if_missing'] = download_if_missing\n try:\n return f(*args, **kwargs)\n except IOError:\n pytest.skip(\"Download {} to run this test\".format(dataset_name))\n return wrapped\n\n\n@pytest.fixture\ndef fetch_20newsgroups_fxt():\n return _wrapped_fetch(fetch_20newsgroups, dataset_name='20newsgroups')\n\n\n@pytest.fixture\ndef fetch_20newsgroups_vectorized_fxt():\n return _wrapped_fetch(fetch_20newsgroups_vectorized,\n dataset_name='20newsgroups_vectorized')\n\n\n@pytest.fixture\ndef fetch_california_housing_fxt():\n return _wrapped_fetch(fetch_california_housing,\n dataset_name='california_housing')", "new_contents": "\"\"\" Network tests are only run, if data is already locally available,\nor if download is specifically requested by environment variable.\"\"\"\nimport builtins\nfrom functools import wraps\nfrom os import environ\nimport pytest\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.datasets import fetch_covtype\nfrom sklearn.datasets import fetch_kddcup99\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.datasets import fetch_rcv1\n\n\ndef _wrapped_fetch(f, dataset_name):\n \"\"\" Fetch dataset (download if missing and requested by environment) \"\"\"\n download_if_missing = environ.get('SKLEARN_SKIP_NETWORK_TESTS', '1') == '0'\n\n @wraps(f)\n def wrapped(*args, **kwargs):\n kwargs['download_if_missing'] = download_if_missing\n try:\n return f(*args, **kwargs)\n except IOError:\n pytest.skip(\"Download {} to run this test\".format(dataset_name))\n return wrapped\n\n\n@pytest.fixture\ndef fetch_20newsgroups_fxt():\n return _wrapped_fetch(fetch_20newsgroups, dataset_name='20newsgroups')\n\n\n@pytest.fixture\ndef fetch_20newsgroups_vectorized_fxt():\n return _wrapped_fetch(fetch_20newsgroups_vectorized,\n dataset_name='20newsgroups_vectorized')\n\n\n@pytest.fixture\ndef fetch_california_housing_fxt():\n return _wrapped_fetch(fetch_california_housing,\n dataset_name='california_housing')", "text": "<|original_code|>\n\"\"\" Network tests are only run, if data is already locally available,\nor if download is specifically requested by environment variable.\"\"\"\nimport builtins\nfrom os import environ\nimport pytest\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.datasets import fetch_covtype\nfrom sklearn.datasets import fetch_kddcup99\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.datasets import fetch_rcv1\n\n\ndef _wrapped_fetch(f, dataset_name):\n \"\"\" Fetch dataset (download if missing and requested by environment) \"\"\"\n download_if_missing = environ.get('SKLEARN_SKIP_NETWORK_TESTS', '1') == '0'\n\n def wrapped(*args, **kwargs):\n kwargs['download_if_missing'] = download_if_missing\n try:\n return f(*args, **kwargs)\n except IOError:\n pytest.skip(\"Download {} to run this test\".format(dataset_name))\n return wrapped\n\n\n@pytest.fixture\ndef fetch_20newsgroups_fxt():\n return _wrapped_fetch(fetch_20newsgroups, dataset_name='20newsgroups')\n\n\n@pytest.fixture\ndef fetch_20newsgroups_vectorized_fxt():\n return _wrapped_fetch(fetch_20newsgroups_vectorized,\n dataset_name='20newsgroups_vectorized')\n\n\n@pytest.fixture\ndef fetch_california_housing_fxt():\n return _wrapped_fetch(fetch_california_housing,\n dataset_name='california_housing')\n<|edits_diff|>\n--- sklearn/datasets/tests/conftest.py\n+++ sklearn/datasets/tests/conftest.py\n@@ -1,6 +1,7 @@\n \"\"\" Network tests are only run, if data is already locally available,\n or if download is specifically requested by environment variable.\"\"\"\n import builtins\n+from functools import wraps\n from os import environ\n import pytest\n from sklearn.datasets import fetch_20newsgroups\n<|current_version|>\n\"\"\" Network tests are only run, if data is already locally available,\nor if download is specifically requested by environment variable.\"\"\"\nimport builtins\nfrom functools import wraps\nfrom os import environ\nimport pytest\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.datasets import fetch_covtype\nfrom sklearn.datasets import fetch_kddcup99\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.datasets import fetch_rcv1\n\n\ndef _wrapped_fetch(f, dataset_name):\n \"\"\" Fetch dataset (download if missing and requested by environment) \"\"\"\n download_if_missing = environ.get('SKLEARN_SKIP_NETWORK_TESTS', '1') == '0'\n\n def wrapped(*args, **kwargs):\n kwargs['download_if_missing'] = download_if_missing\n try:\n return f(*args, **kwargs)\n except IOError:\n pytest.skip(\"Download {} to run this test\".format(dataset_name))\n return wrapped\n\n\n@pytest.fixture\ndef fetch_20newsgroups_fxt():\n return _wrapped_fetch(fetch_20newsgroups, dataset_name='20newsgroups')\n\n\n@pytest.fixture\ndef fetch_20newsgroups_vectorized_fxt():\n return _wrapped_fetch(fetch_20newsgroups_vectorized,\n dataset_name='20newsgroups_vectorized')\n\n\n@pytest.fixture\ndef fetch_california_housing_fxt():\n return _wrapped_fetch(fetch_california_housing,\n dataset_name='california_housing')\n<|next_version|>\n\"\"\" Network tests are only run, if data is already locally available,\nor if download is specifically requested by environment variable.\"\"\"\nimport builtins\nfrom functools import wraps\nfrom os import environ\nimport pytest\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.datasets import fetch_covtype\nfrom sklearn.datasets import fetch_kddcup99\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.datasets import fetch_rcv1\n\n\ndef _wrapped_fetch(f, dataset_name):\n \"\"\" Fetch dataset (download if missing and requested by environment) \"\"\"\n download_if_missing = environ.get('SKLEARN_SKIP_NETWORK_TESTS', '1') == '0'\n\n @wraps(f)\n def wrapped(*args, **kwargs):\n kwargs['download_if_missing'] = download_if_missing\n try:\n return f(*args, **kwargs)\n except IOError:\n pytest.skip(\"Download {} to run this test\".format(dataset_name))\n return wrapped\n\n\n@pytest.fixture\ndef fetch_20newsgroups_fxt():\n return _wrapped_fetch(fetch_20newsgroups, dataset_name='20newsgroups')\n\n\n@pytest.fixture\ndef fetch_20newsgroups_vectorized_fxt():\n return _wrapped_fetch(fetch_20newsgroups_vectorized,\n dataset_name='20newsgroups_vectorized')\n\n\n@pytest.fixture\ndef fetch_california_housing_fxt():\n return _wrapped_fetch(fetch_california_housing,\n dataset_name='california_housing')\n", "current_contents": "\"\"\" Network tests are only run, if data is already locally available,\nor if download is specifically requested by environment variable.\"\"\"\nimport builtins\nfrom functools import wraps\nfrom os import environ\nimport pytest\nfrom sklearn.datasets import fetch_20newsgroups\nfrom sklearn.datasets import fetch_20newsgroups_vectorized\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.datasets import fetch_covtype\nfrom sklearn.datasets import fetch_kddcup99\nfrom sklearn.datasets import fetch_olivetti_faces\nfrom sklearn.datasets import fetch_rcv1\n\n\ndef _wrapped_fetch(f, dataset_name):\n \"\"\" Fetch dataset (download if missing and requested by environment) \"\"\"\n download_if_missing = environ.get('SKLEARN_SKIP_NETWORK_TESTS', '1') == '0'\n\n def wrapped(*args, **kwargs):\n kwargs['download_if_missing'] = download_if_missing\n try:\n return f(*args, **kwargs)\n except IOError:\n pytest.skip(\"Download {} to run this test\".format(dataset_name))\n return wrapped\n\n\n@pytest.fixture\ndef fetch_20newsgroups_fxt():\n return _wrapped_fetch(fetch_20newsgroups, dataset_name='20newsgroups')\n\n\n@pytest.fixture\ndef fetch_20newsgroups_vectorized_fxt():\n return _wrapped_fetch(fetch_20newsgroups_vectorized,\n dataset_name='20newsgroups_vectorized')\n\n\n@pytest.fixture\ndef fetch_california_housing_fxt():\n return _wrapped_fetch(fetch_california_housing,\n dataset_name='california_housing')"} {"commit": "e1f7b631ced4e8fdf535ca7d4e1d03256292ef3f", "message": "ENH Allow usage of nu=inf in Matern kernel (#15972)", "old_file": "sklearn/gaussian_process/kernels.py", "new_file": "sklearn/gaussian_process/kernels.py", "status": "M", "old_contents": " hyperparameter of the kernel. Only returned when eval_gradient\n is True.\n \"\"\"\n X = np.atleast_2d(X)\n length_scale = _check_length_scale(X, self.length_scale)\n if Y is None:\n dists = pdist(X / length_scale, metric='euclidean')\n else:\n if eval_gradient:\n raise ValueError(\n \"Gradient can only be evaluated when Y is None.\")\n dists = cdist(X / length_scale, Y / length_scale,\n metric='euclidean')\n\n if self.nu == 0.5:\n K = np.exp(-dists)\n elif self.nu == 1.5:\n K = dists * math.sqrt(3)\n K = (1. + K) * np.exp(-K)\n elif self.nu == 2.5:\n K = dists * math.sqrt(5)\n K = (1. + K + K ** 2 / 3.0) * np.exp(-K)\n else: # general case; expensive to evaluate\n K = dists\n K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan\n tmp = (math.sqrt(2 * self.nu) * K)\n K.fill((2 ** (1. - self.nu)) / gamma(self.nu))\n K *= tmp ** self.nu\n K *= kv(self.nu, tmp)\n\n if Y is None:\n # convert from upper-triangular matrix to square matrix\n K = squareform(K)\n np.fill_diagonal(K, 1)\n\n if eval_gradient:\n if self.hyperparameter_length_scale.fixed:\n # Hyperparameter l kept fixed\n K_gradient = np.empty((X.shape[0], X.shape[0], 0))\n return K, K_gradient\n\n # We need to recompute the pairwise dimension-wise distances\n if self.anisotropic:\n D = (X[:, np.newaxis, :] - X[np.newaxis, :, :])**2 \\\n / (length_scale ** 2)\n else:\n D = squareform(dists**2)[:, :, np.newaxis]\n\n if self.nu == 0.5:\n K_gradient = K[..., np.newaxis] * D \\\n / np.sqrt(D.sum(2))[:, :, np.newaxis]\n K_gradient[~np.isfinite(K_gradient)] = 0\n elif self.nu == 1.5:\n K_gradient = \\\n 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis]\n elif self.nu == 2.5:\n tmp = np.sqrt(5 * D.sum(-1))[..., np.newaxis]\n K_gradient = 5.0 / 3.0 * D * (tmp + 1) * np.exp(-tmp)\n else:\n # approximate gradient numerically\n def f(theta): # helper function\n return self.clone_with_theta(theta)(X, Y)\n return K, _approx_fprime(self.theta, f, 1e-10)\n\n if not self.anisotropic:\n return K, K_gradient[:, :].sum(-1)[:, :, np.newaxis]\n else:\n return K, K_gradient\n else:\n return K\n\n def __repr__(self):\n if self.anisotropic:\n return \"{0}(length_scale=[{1}], nu={2:.3g})\".format(\n self.__class__.__name__,\n \", \".join(map(\"{0:.3g}\".format, self.length_scale)),\n self.nu)\n else:\n return \"{0}(length_scale={1:.3g}, nu={2:.3g})\".format(\n self.__class__.__name__, np.ravel(self.length_scale)[0],\n self.nu)\n", "new_contents": " hyperparameter of the kernel. Only returned when eval_gradient\n is True.\n \"\"\"\n X = np.atleast_2d(X)\n length_scale = _check_length_scale(X, self.length_scale)\n if Y is None:\n dists = pdist(X / length_scale, metric='euclidean')\n else:\n if eval_gradient:\n raise ValueError(\n \"Gradient can only be evaluated when Y is None.\")\n dists = cdist(X / length_scale, Y / length_scale,\n metric='euclidean')\n\n if self.nu == 0.5:\n K = np.exp(-dists)\n elif self.nu == 1.5:\n K = dists * math.sqrt(3)\n K = (1. + K) * np.exp(-K)\n elif self.nu == 2.5:\n K = dists * math.sqrt(5)\n K = (1. + K + K ** 2 / 3.0) * np.exp(-K)\n elif self.nu == np.inf:\n K = np.exp(-dists ** 2 / 2.0)\n else: # general case; expensive to evaluate\n K = dists\n K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan\n tmp = (math.sqrt(2 * self.nu) * K)\n K.fill((2 ** (1. - self.nu)) / gamma(self.nu))\n K *= tmp ** self.nu\n K *= kv(self.nu, tmp)\n\n if Y is None:\n # convert from upper-triangular matrix to square matrix\n K = squareform(K)\n np.fill_diagonal(K, 1)\n\n if eval_gradient:\n if self.hyperparameter_length_scale.fixed:\n # Hyperparameter l kept fixed\n K_gradient = np.empty((X.shape[0], X.shape[0], 0))\n return K, K_gradient\n\n # We need to recompute the pairwise dimension-wise distances\n if self.anisotropic:\n D = (X[:, np.newaxis, :] - X[np.newaxis, :, :])**2 \\\n / (length_scale ** 2)\n else:\n D = squareform(dists**2)[:, :, np.newaxis]\n\n if self.nu == 0.5:\n K_gradient = K[..., np.newaxis] * D \\\n / np.sqrt(D.sum(2))[:, :, np.newaxis]\n K_gradient[~np.isfinite(K_gradient)] = 0\n elif self.nu == 1.5:\n K_gradient = \\\n 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis]\n elif self.nu == 2.5:\n tmp = np.sqrt(5 * D.sum(-1))[..., np.newaxis]\n K_gradient = 5.0 / 3.0 * D * (tmp + 1) * np.exp(-tmp)\n elif self.nu == np.inf:\n K_gradient = D * K[..., np.newaxis]\n else:\n # approximate gradient numerically\n def f(theta): # helper function\n return self.clone_with_theta(theta)(X, Y)\n return K, _approx_fprime(self.theta, f, 1e-10)\n\n if not self.anisotropic:\n return K, K_gradient[:, :].sum(-1)[:, :, np.newaxis]\n else:\n return K, K_gradient\n else:\n return K\n\n def __repr__(self):\n if self.anisotropic:\n return \"{0}(length_scale=[{1}], nu={2:.3g})\".format(\n self.__class__.__name__,\n \", \".join(map(\"{0:.3g}\".format, self.length_scale)),\n self.nu)\n else:\n return \"{0}(length_scale={1:.3g}, nu={2:.3g})\".format(\n self.__class__.__name__, np.ravel(self.length_scale)[0],\n self.nu)\n", "text": "<|original_code|>\n hyperparameter of the kernel. Only returned when eval_gradient\n is True.\n \"\"\"\n X = np.atleast_2d(X)\n length_scale = _check_length_scale(X, self.length_scale)\n if Y is None:\n dists = pdist(X / length_scale, metric='euclidean')\n else:\n if eval_gradient:\n raise ValueError(\n \"Gradient can only be evaluated when Y is None.\")\n dists = cdist(X / length_scale, Y / length_scale,\n metric='euclidean')\n\n if self.nu == 0.5:\n K = np.exp(-dists)\n elif self.nu == 1.5:\n K = dists * math.sqrt(3)\n K = (1. + K) * np.exp(-K)\n elif self.nu == 2.5:\n K = dists * math.sqrt(5)\n K = (1. + K + K ** 2 / 3.0) * np.exp(-K)\n else: # general case; expensive to evaluate\n K = dists\n K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan\n tmp = (math.sqrt(2 * self.nu) * K)\n K.fill((2 ** (1. - self.nu)) / gamma(self.nu))\n K *= tmp ** self.nu\n K *= kv(self.nu, tmp)\n\n if Y is None:\n # convert from upper-triangular matrix to square matrix\n K = squareform(K)\n np.fill_diagonal(K, 1)\n\n if eval_gradient:\n if self.hyperparameter_length_scale.fixed:\n # Hyperparameter l kept fixed\n K_gradient = np.empty((X.shape[0], X.shape[0], 0))\n return K, K_gradient\n\n # We need to recompute the pairwise dimension-wise distances\n if self.anisotropic:\n D = (X[:, np.newaxis, :] - X[np.newaxis, :, :])**2 \\\n / (length_scale ** 2)\n else:\n D = squareform(dists**2)[:, :, np.newaxis]\n\n if self.nu == 0.5:\n K_gradient = K[..., np.newaxis] * D \\\n / np.sqrt(D.sum(2))[:, :, np.newaxis]\n K_gradient[~np.isfinite(K_gradient)] = 0\n elif self.nu == 1.5:\n K_gradient = \\\n 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis]\n elif self.nu == 2.5:\n tmp = np.sqrt(5 * D.sum(-1))[..., np.newaxis]\n K_gradient = 5.0 / 3.0 * D * (tmp + 1) * np.exp(-tmp)\n else:\n # approximate gradient numerically\n def f(theta): # helper function\n return self.clone_with_theta(theta)(X, Y)\n return K, _approx_fprime(self.theta, f, 1e-10)\n\n if not self.anisotropic:\n return K, K_gradient[:, :].sum(-1)[:, :, np.newaxis]\n else:\n return K, K_gradient\n else:\n return K\n\n def __repr__(self):\n if self.anisotropic:\n return \"{0}(length_scale=[{1}], nu={2:.3g})\".format(\n self.__class__.__name__,\n \", \".join(map(\"{0:.3g}\".format, self.length_scale)),\n self.nu)\n else:\n return \"{0}(length_scale={1:.3g}, nu={2:.3g})\".format(\n self.__class__.__name__, np.ravel(self.length_scale)[0],\n self.nu)\n\n<|edits_diff|>\n--- sklearn/gaussian_process/kernels.py\n+++ sklearn/gaussian_process/kernels.py\n@@ -20,6 +20,8 @@\n elif self.nu == 2.5:\n K = dists * math.sqrt(5)\n K = (1. + K + K ** 2 / 3.0) * np.exp(-K)\n+ elif self.nu == np.inf:\n+ K = np.exp(-dists ** 2 / 2.0)\n else: # general case; expensive to evaluate\n K = dists\n K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan\n<|current_version|>\n hyperparameter of the kernel. Only returned when eval_gradient\n is True.\n \"\"\"\n X = np.atleast_2d(X)\n length_scale = _check_length_scale(X, self.length_scale)\n if Y is None:\n dists = pdist(X / length_scale, metric='euclidean')\n else:\n if eval_gradient:\n raise ValueError(\n \"Gradient can only be evaluated when Y is None.\")\n dists = cdist(X / length_scale, Y / length_scale,\n metric='euclidean')\n\n if self.nu == 0.5:\n K = np.exp(-dists)\n elif self.nu == 1.5:\n K = dists * math.sqrt(3)\n K = (1. + K) * np.exp(-K)\n elif self.nu == 2.5:\n K = dists * math.sqrt(5)\n K = (1. + K + K ** 2 / 3.0) * np.exp(-K)\n elif self.nu == np.inf:\n K = np.exp(-dists ** 2 / 2.0)\n else: # general case; expensive to evaluate\n K = dists\n K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan\n tmp = (math.sqrt(2 * self.nu) * K)\n K.fill((2 ** (1. - self.nu)) / gamma(self.nu))\n K *= tmp ** self.nu\n K *= kv(self.nu, tmp)\n\n if Y is None:\n # convert from upper-triangular matrix to square matrix\n K = squareform(K)\n np.fill_diagonal(K, 1)\n\n if eval_gradient:\n if self.hyperparameter_length_scale.fixed:\n # Hyperparameter l kept fixed\n K_gradient = np.empty((X.shape[0], X.shape[0], 0))\n return K, K_gradient\n\n # We need to recompute the pairwise dimension-wise distances\n if self.anisotropic:\n D = (X[:, np.newaxis, :] - X[np.newaxis, :, :])**2 \\\n / (length_scale ** 2)\n else:\n D = squareform(dists**2)[:, :, np.newaxis]\n\n if self.nu == 0.5:\n K_gradient = K[..., np.newaxis] * D \\\n / np.sqrt(D.sum(2))[:, :, np.newaxis]\n K_gradient[~np.isfinite(K_gradient)] = 0\n elif self.nu == 1.5:\n K_gradient = \\\n 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis]\n elif self.nu == 2.5:\n tmp = np.sqrt(5 * D.sum(-1))[..., np.newaxis]\n K_gradient = 5.0 / 3.0 * D * (tmp + 1) * np.exp(-tmp)\n else:\n # approximate gradient numerically\n def f(theta): # helper function\n return self.clone_with_theta(theta)(X, Y)\n return K, _approx_fprime(self.theta, f, 1e-10)\n\n if not self.anisotropic:\n return K, K_gradient[:, :].sum(-1)[:, :, np.newaxis]\n else:\n return K, K_gradient\n else:\n return K\n\n def __repr__(self):\n if self.anisotropic:\n return \"{0}(length_scale=[{1}], nu={2:.3g})\".format(\n self.__class__.__name__,\n \", \".join(map(\"{0:.3g}\".format, self.length_scale)),\n self.nu)\n else:\n return \"{0}(length_scale={1:.3g}, nu={2:.3g})\".format(\n self.__class__.__name__, np.ravel(self.length_scale)[0],\n self.nu)\n\n<|next_version|>\n hyperparameter of the kernel. Only returned when eval_gradient\n is True.\n \"\"\"\n X = np.atleast_2d(X)\n length_scale = _check_length_scale(X, self.length_scale)\n if Y is None:\n dists = pdist(X / length_scale, metric='euclidean')\n else:\n if eval_gradient:\n raise ValueError(\n \"Gradient can only be evaluated when Y is None.\")\n dists = cdist(X / length_scale, Y / length_scale,\n metric='euclidean')\n\n if self.nu == 0.5:\n K = np.exp(-dists)\n elif self.nu == 1.5:\n K = dists * math.sqrt(3)\n K = (1. + K) * np.exp(-K)\n elif self.nu == 2.5:\n K = dists * math.sqrt(5)\n K = (1. + K + K ** 2 / 3.0) * np.exp(-K)\n elif self.nu == np.inf:\n K = np.exp(-dists ** 2 / 2.0)\n else: # general case; expensive to evaluate\n K = dists\n K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan\n tmp = (math.sqrt(2 * self.nu) * K)\n K.fill((2 ** (1. - self.nu)) / gamma(self.nu))\n K *= tmp ** self.nu\n K *= kv(self.nu, tmp)\n\n if Y is None:\n # convert from upper-triangular matrix to square matrix\n K = squareform(K)\n np.fill_diagonal(K, 1)\n\n if eval_gradient:\n if self.hyperparameter_length_scale.fixed:\n # Hyperparameter l kept fixed\n K_gradient = np.empty((X.shape[0], X.shape[0], 0))\n return K, K_gradient\n\n # We need to recompute the pairwise dimension-wise distances\n if self.anisotropic:\n D = (X[:, np.newaxis, :] - X[np.newaxis, :, :])**2 \\\n / (length_scale ** 2)\n else:\n D = squareform(dists**2)[:, :, np.newaxis]\n\n if self.nu == 0.5:\n K_gradient = K[..., np.newaxis] * D \\\n / np.sqrt(D.sum(2))[:, :, np.newaxis]\n K_gradient[~np.isfinite(K_gradient)] = 0\n elif self.nu == 1.5:\n K_gradient = \\\n 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis]\n elif self.nu == 2.5:\n tmp = np.sqrt(5 * D.sum(-1))[..., np.newaxis]\n K_gradient = 5.0 / 3.0 * D * (tmp + 1) * np.exp(-tmp)\n elif self.nu == np.inf:\n K_gradient = D * K[..., np.newaxis]\n else:\n # approximate gradient numerically\n def f(theta): # helper function\n return self.clone_with_theta(theta)(X, Y)\n return K, _approx_fprime(self.theta, f, 1e-10)\n\n if not self.anisotropic:\n return K, K_gradient[:, :].sum(-1)[:, :, np.newaxis]\n else:\n return K, K_gradient\n else:\n return K\n\n def __repr__(self):\n if self.anisotropic:\n return \"{0}(length_scale=[{1}], nu={2:.3g})\".format(\n self.__class__.__name__,\n \", \".join(map(\"{0:.3g}\".format, self.length_scale)),\n self.nu)\n else:\n return \"{0}(length_scale={1:.3g}, nu={2:.3g})\".format(\n self.__class__.__name__, np.ravel(self.length_scale)[0],\n self.nu)\n\n", "current_contents": " hyperparameter of the kernel. Only returned when eval_gradient\n is True.\n \"\"\"\n X = np.atleast_2d(X)\n length_scale = _check_length_scale(X, self.length_scale)\n if Y is None:\n dists = pdist(X / length_scale, metric='euclidean')\n else:\n if eval_gradient:\n raise ValueError(\n \"Gradient can only be evaluated when Y is None.\")\n dists = cdist(X / length_scale, Y / length_scale,\n metric='euclidean')\n\n if self.nu == 0.5:\n K = np.exp(-dists)\n elif self.nu == 1.5:\n K = dists * math.sqrt(3)\n K = (1. + K) * np.exp(-K)\n elif self.nu == 2.5:\n K = dists * math.sqrt(5)\n K = (1. + K + K ** 2 / 3.0) * np.exp(-K)\n elif self.nu == np.inf:\n K = np.exp(-dists ** 2 / 2.0)\n else: # general case; expensive to evaluate\n K = dists\n K[K == 0.0] += np.finfo(float).eps # strict zeros result in nan\n tmp = (math.sqrt(2 * self.nu) * K)\n K.fill((2 ** (1. - self.nu)) / gamma(self.nu))\n K *= tmp ** self.nu\n K *= kv(self.nu, tmp)\n\n if Y is None:\n # convert from upper-triangular matrix to square matrix\n K = squareform(K)\n np.fill_diagonal(K, 1)\n\n if eval_gradient:\n if self.hyperparameter_length_scale.fixed:\n # Hyperparameter l kept fixed\n K_gradient = np.empty((X.shape[0], X.shape[0], 0))\n return K, K_gradient\n\n # We need to recompute the pairwise dimension-wise distances\n if self.anisotropic:\n D = (X[:, np.newaxis, :] - X[np.newaxis, :, :])**2 \\\n / (length_scale ** 2)\n else:\n D = squareform(dists**2)[:, :, np.newaxis]\n\n if self.nu == 0.5:\n K_gradient = K[..., np.newaxis] * D \\\n / np.sqrt(D.sum(2))[:, :, np.newaxis]\n K_gradient[~np.isfinite(K_gradient)] = 0\n elif self.nu == 1.5:\n K_gradient = \\\n 3 * D * np.exp(-np.sqrt(3 * D.sum(-1)))[..., np.newaxis]\n elif self.nu == 2.5:\n tmp = np.sqrt(5 * D.sum(-1))[..., np.newaxis]\n K_gradient = 5.0 / 3.0 * D * (tmp + 1) * np.exp(-tmp)\n else:\n # approximate gradient numerically\n def f(theta): # helper function\n return self.clone_with_theta(theta)(X, Y)\n return K, _approx_fprime(self.theta, f, 1e-10)\n\n if not self.anisotropic:\n return K, K_gradient[:, :].sum(-1)[:, :, np.newaxis]\n else:\n return K, K_gradient\n else:\n return K\n\n def __repr__(self):\n if self.anisotropic:\n return \"{0}(length_scale=[{1}], nu={2:.3g})\".format(\n self.__class__.__name__,\n \", \".join(map(\"{0:.3g}\".format, self.length_scale)),\n self.nu)\n else:\n return \"{0}(length_scale={1:.3g}, nu={2:.3g})\".format(\n self.__class__.__name__, np.ravel(self.length_scale)[0],\n self.nu)\n"} {"commit": "968252dfb4c252e252614ae8736cc6b1ebdde9ee", "message": "FEA Adds plot_precision_recall_curve (#14936)", "old_file": "sklearn/metrics/__init__.py", "new_file": "sklearn/metrics/__init__.py", "status": "M", "old_contents": "from .pairwise import pairwise_kernels\nfrom .pairwise import pairwise_distances_chunked\n\nfrom ._regression import explained_variance_score\nfrom ._regression import max_error\nfrom ._regression import mean_absolute_error\nfrom ._regression import mean_squared_error\nfrom ._regression import mean_squared_log_error\nfrom ._regression import median_absolute_error\nfrom ._regression import r2_score\nfrom ._regression import mean_tweedie_deviance\nfrom ._regression import mean_poisson_deviance\nfrom ._regression import mean_gamma_deviance\n\n\nfrom ._scorer import check_scoring\nfrom ._scorer import make_scorer\nfrom ._scorer import SCORERS\nfrom ._scorer import get_scorer\n\nfrom ._plot.roc_curve import plot_roc_curve\nfrom ._plot.roc_curve import RocCurveDisplay\n\n\n__all__ = [\n 'accuracy_score',\n 'adjusted_mutual_info_score',\n 'adjusted_rand_score',\n 'auc',\n 'average_precision_score',\n 'balanced_accuracy_score',\n 'calinski_harabaz_score',\n 'calinski_harabasz_score',\n 'check_scoring',\n 'classification_report',\n 'cluster',\n 'cohen_kappa_score',\n 'completeness_score',\n 'confusion_matrix',\n 'consensus_score',\n 'coverage_error',\n 'dcg_score',\n 'davies_bouldin_score',\n 'euclidean_distances',\n 'explained_variance_score',\n 'f1_score',\n 'fbeta_score',\n 'fowlkes_mallows_score',\n 'get_scorer',\n 'hamming_loss',\n 'hinge_loss',\n 'homogeneity_completeness_v_measure',\n 'homogeneity_score',\n 'jaccard_score',\n 'jaccard_similarity_score',\n 'label_ranking_average_precision_score',\n 'label_ranking_loss',\n 'log_loss',\n 'make_scorer',\n 'nan_euclidean_distances',\n 'matthews_corrcoef',\n 'max_error',\n 'mean_absolute_error',\n 'mean_squared_error',\n 'mean_squared_log_error',\n 'mean_poisson_deviance',\n 'mean_gamma_deviance',\n 'mean_tweedie_deviance',\n 'median_absolute_error',\n 'multilabel_confusion_matrix',\n 'mutual_info_score',\n 'ndcg_score',\n 'normalized_mutual_info_score',\n 'pairwise_distances',\n 'pairwise_distances_argmin',\n 'pairwise_distances_argmin_min',\n 'pairwise_distances_chunked',\n 'pairwise_kernels',\n 'plot_roc_curve',\n 'precision_recall_curve',\n 'precision_recall_fscore_support',\n 'precision_score',\n 'r2_score',\n 'recall_score',\n 'RocCurveDisplay',\n 'roc_auc_score',\n 'roc_curve',\n 'SCORERS',\n 'silhouette_samples',\n 'silhouette_score',\n 'v_measure_score',\n 'zero_one_loss',\n 'brier_score_loss',\n]\n", "new_contents": "from .pairwise import pairwise_kernels\nfrom .pairwise import pairwise_distances_chunked\n\nfrom ._regression import explained_variance_score\nfrom ._regression import max_error\nfrom ._regression import mean_absolute_error\nfrom ._regression import mean_squared_error\nfrom ._regression import mean_squared_log_error\nfrom ._regression import median_absolute_error\nfrom ._regression import r2_score\nfrom ._regression import mean_tweedie_deviance\nfrom ._regression import mean_poisson_deviance\nfrom ._regression import mean_gamma_deviance\n\n\nfrom ._scorer import check_scoring\nfrom ._scorer import make_scorer\nfrom ._scorer import SCORERS\nfrom ._scorer import get_scorer\n\nfrom ._plot.roc_curve import plot_roc_curve\nfrom ._plot.roc_curve import RocCurveDisplay\nfrom ._plot.precision_recall_curve import plot_precision_recall_curve\nfrom ._plot.precision_recall_curve import PrecisionRecallDisplay\n\n\n__all__ = [\n 'accuracy_score',\n 'adjusted_mutual_info_score',\n 'adjusted_rand_score',\n 'auc',\n 'average_precision_score',\n 'balanced_accuracy_score',\n 'calinski_harabaz_score',\n 'calinski_harabasz_score',\n 'check_scoring',\n 'classification_report',\n 'cluster',\n 'cohen_kappa_score',\n 'completeness_score',\n 'confusion_matrix',\n 'consensus_score',\n 'coverage_error',\n 'dcg_score',\n 'davies_bouldin_score',\n 'euclidean_distances',\n 'explained_variance_score',\n 'f1_score',\n 'fbeta_score',\n 'fowlkes_mallows_score',\n 'get_scorer',\n 'hamming_loss',\n 'hinge_loss',\n 'homogeneity_completeness_v_measure',\n 'homogeneity_score',\n 'jaccard_score',\n 'jaccard_similarity_score',\n 'label_ranking_average_precision_score',\n 'label_ranking_loss',\n 'log_loss',\n 'make_scorer',\n 'nan_euclidean_distances',\n 'matthews_corrcoef',\n 'max_error',\n 'mean_absolute_error',\n 'mean_squared_error',\n 'mean_squared_log_error',\n 'mean_poisson_deviance',\n 'mean_gamma_deviance',\n 'mean_tweedie_deviance',\n 'median_absolute_error',\n 'multilabel_confusion_matrix',\n 'mutual_info_score',\n 'ndcg_score',\n 'normalized_mutual_info_score',\n 'pairwise_distances',\n 'pairwise_distances_argmin',\n 'pairwise_distances_argmin_min',\n 'pairwise_distances_chunked',\n 'pairwise_kernels',\n 'plot_precision_recall_curve',\n 'plot_roc_curve',\n 'PrecisionRecallDisplay',\n 'precision_recall_curve',\n 'precision_recall_fscore_support',\n 'precision_score',\n 'r2_score',\n 'recall_score',\n 'RocCurveDisplay',\n 'roc_auc_score',\n 'roc_curve',\n 'SCORERS',\n 'silhouette_samples',\n 'silhouette_score',\n 'v_measure_score',\n 'zero_one_loss',\n 'brier_score_loss',\n]\n", "text": "<|original_code|>\nfrom .pairwise import pairwise_kernels\nfrom .pairwise import pairwise_distances_chunked\n\nfrom ._regression import explained_variance_score\nfrom ._regression import max_error\nfrom ._regression import mean_absolute_error\nfrom ._regression import mean_squared_error\nfrom ._regression import mean_squared_log_error\nfrom ._regression import median_absolute_error\nfrom ._regression import r2_score\nfrom ._regression import mean_tweedie_deviance\nfrom ._regression import mean_poisson_deviance\nfrom ._regression import mean_gamma_deviance\n\n\nfrom ._scorer import check_scoring\nfrom ._scorer import make_scorer\nfrom ._scorer import SCORERS\nfrom ._scorer import get_scorer\n\nfrom ._plot.roc_curve import plot_roc_curve\nfrom ._plot.roc_curve import RocCurveDisplay\n\n\n__all__ = [\n 'accuracy_score',\n 'adjusted_mutual_info_score',\n 'adjusted_rand_score',\n 'auc',\n 'average_precision_score',\n 'balanced_accuracy_score',\n 'calinski_harabaz_score',\n 'calinski_harabasz_score',\n 'check_scoring',\n 'classification_report',\n 'cluster',\n 'cohen_kappa_score',\n 'completeness_score',\n 'confusion_matrix',\n 'consensus_score',\n 'coverage_error',\n 'dcg_score',\n 'davies_bouldin_score',\n 'euclidean_distances',\n 'explained_variance_score',\n 'f1_score',\n 'fbeta_score',\n 'fowlkes_mallows_score',\n 'get_scorer',\n 'hamming_loss',\n 'hinge_loss',\n 'homogeneity_completeness_v_measure',\n 'homogeneity_score',\n 'jaccard_score',\n 'jaccard_similarity_score',\n 'label_ranking_average_precision_score',\n 'label_ranking_loss',\n 'log_loss',\n 'make_scorer',\n 'nan_euclidean_distances',\n 'matthews_corrcoef',\n 'max_error',\n 'mean_absolute_error',\n 'mean_squared_error',\n 'mean_squared_log_error',\n 'mean_poisson_deviance',\n 'mean_gamma_deviance',\n 'mean_tweedie_deviance',\n 'median_absolute_error',\n 'multilabel_confusion_matrix',\n 'mutual_info_score',\n 'ndcg_score',\n 'normalized_mutual_info_score',\n 'pairwise_distances',\n 'pairwise_distances_argmin',\n 'pairwise_distances_argmin_min',\n 'pairwise_distances_chunked',\n 'pairwise_kernels',\n 'plot_roc_curve',\n 'precision_recall_curve',\n 'precision_recall_fscore_support',\n 'precision_score',\n 'r2_score',\n 'recall_score',\n 'RocCurveDisplay',\n 'roc_auc_score',\n 'roc_curve',\n 'SCORERS',\n 'silhouette_samples',\n 'silhouette_score',\n 'v_measure_score',\n 'zero_one_loss',\n 'brier_score_loss',\n]\n\n<|edits_diff|>\n--- sklearn/metrics/__init__.py\n+++ sklearn/metrics/__init__.py\n@@ -20,6 +20,8 @@\n \n from ._plot.roc_curve import plot_roc_curve\n from ._plot.roc_curve import RocCurveDisplay\n+from ._plot.precision_recall_curve import plot_precision_recall_curve\n+from ._plot.precision_recall_curve import PrecisionRecallDisplay\n \n \n __all__ = [\n@@ -76,6 +78,7 @@\n 'pairwise_distances_argmin_min',\n 'pairwise_distances_chunked',\n 'pairwise_kernels',\n+ 'plot_precision_recall_curve',\n 'plot_roc_curve',\n 'precision_recall_curve',\n 'precision_recall_fscore_support',\n<|current_version|>\nfrom .pairwise import pairwise_kernels\nfrom .pairwise import pairwise_distances_chunked\n\nfrom ._regression import explained_variance_score\nfrom ._regression import max_error\nfrom ._regression import mean_absolute_error\nfrom ._regression import mean_squared_error\nfrom ._regression import mean_squared_log_error\nfrom ._regression import median_absolute_error\nfrom ._regression import r2_score\nfrom ._regression import mean_tweedie_deviance\nfrom ._regression import mean_poisson_deviance\nfrom ._regression import mean_gamma_deviance\n\n\nfrom ._scorer import check_scoring\nfrom ._scorer import make_scorer\nfrom ._scorer import SCORERS\nfrom ._scorer import get_scorer\n\nfrom ._plot.roc_curve import plot_roc_curve\nfrom ._plot.roc_curve import RocCurveDisplay\nfrom ._plot.precision_recall_curve import plot_precision_recall_curve\nfrom ._plot.precision_recall_curve import PrecisionRecallDisplay\n\n\n__all__ = [\n 'accuracy_score',\n 'adjusted_mutual_info_score',\n 'adjusted_rand_score',\n 'auc',\n 'average_precision_score',\n 'balanced_accuracy_score',\n 'calinski_harabaz_score',\n 'calinski_harabasz_score',\n 'check_scoring',\n 'classification_report',\n 'cluster',\n 'cohen_kappa_score',\n 'completeness_score',\n 'confusion_matrix',\n 'consensus_score',\n 'coverage_error',\n 'dcg_score',\n 'davies_bouldin_score',\n 'euclidean_distances',\n 'explained_variance_score',\n 'f1_score',\n 'fbeta_score',\n 'fowlkes_mallows_score',\n 'get_scorer',\n 'hamming_loss',\n 'hinge_loss',\n 'homogeneity_completeness_v_measure',\n 'homogeneity_score',\n 'jaccard_score',\n 'jaccard_similarity_score',\n 'label_ranking_average_precision_score',\n 'label_ranking_loss',\n 'log_loss',\n 'make_scorer',\n 'nan_euclidean_distances',\n 'matthews_corrcoef',\n 'max_error',\n 'mean_absolute_error',\n 'mean_squared_error',\n 'mean_squared_log_error',\n 'mean_poisson_deviance',\n 'mean_gamma_deviance',\n 'mean_tweedie_deviance',\n 'median_absolute_error',\n 'multilabel_confusion_matrix',\n 'mutual_info_score',\n 'ndcg_score',\n 'normalized_mutual_info_score',\n 'pairwise_distances',\n 'pairwise_distances_argmin',\n 'pairwise_distances_argmin_min',\n 'pairwise_distances_chunked',\n 'pairwise_kernels',\n 'plot_precision_recall_curve',\n 'plot_roc_curve',\n 'precision_recall_curve',\n 'precision_recall_fscore_support',\n 'precision_score',\n 'r2_score',\n 'recall_score',\n 'RocCurveDisplay',\n 'roc_auc_score',\n 'roc_curve',\n 'SCORERS',\n 'silhouette_samples',\n 'silhouette_score',\n 'v_measure_score',\n 'zero_one_loss',\n 'brier_score_loss',\n]\n\n<|next_version|>\nfrom .pairwise import pairwise_kernels\nfrom .pairwise import pairwise_distances_chunked\n\nfrom ._regression import explained_variance_score\nfrom ._regression import max_error\nfrom ._regression import mean_absolute_error\nfrom ._regression import mean_squared_error\nfrom ._regression import mean_squared_log_error\nfrom ._regression import median_absolute_error\nfrom ._regression import r2_score\nfrom ._regression import mean_tweedie_deviance\nfrom ._regression import mean_poisson_deviance\nfrom ._regression import mean_gamma_deviance\n\n\nfrom ._scorer import check_scoring\nfrom ._scorer import make_scorer\nfrom ._scorer import SCORERS\nfrom ._scorer import get_scorer\n\nfrom ._plot.roc_curve import plot_roc_curve\nfrom ._plot.roc_curve import RocCurveDisplay\nfrom ._plot.precision_recall_curve import plot_precision_recall_curve\nfrom ._plot.precision_recall_curve import PrecisionRecallDisplay\n\n\n__all__ = [\n 'accuracy_score',\n 'adjusted_mutual_info_score',\n 'adjusted_rand_score',\n 'auc',\n 'average_precision_score',\n 'balanced_accuracy_score',\n 'calinski_harabaz_score',\n 'calinski_harabasz_score',\n 'check_scoring',\n 'classification_report',\n 'cluster',\n 'cohen_kappa_score',\n 'completeness_score',\n 'confusion_matrix',\n 'consensus_score',\n 'coverage_error',\n 'dcg_score',\n 'davies_bouldin_score',\n 'euclidean_distances',\n 'explained_variance_score',\n 'f1_score',\n 'fbeta_score',\n 'fowlkes_mallows_score',\n 'get_scorer',\n 'hamming_loss',\n 'hinge_loss',\n 'homogeneity_completeness_v_measure',\n 'homogeneity_score',\n 'jaccard_score',\n 'jaccard_similarity_score',\n 'label_ranking_average_precision_score',\n 'label_ranking_loss',\n 'log_loss',\n 'make_scorer',\n 'nan_euclidean_distances',\n 'matthews_corrcoef',\n 'max_error',\n 'mean_absolute_error',\n 'mean_squared_error',\n 'mean_squared_log_error',\n 'mean_poisson_deviance',\n 'mean_gamma_deviance',\n 'mean_tweedie_deviance',\n 'median_absolute_error',\n 'multilabel_confusion_matrix',\n 'mutual_info_score',\n 'ndcg_score',\n 'normalized_mutual_info_score',\n 'pairwise_distances',\n 'pairwise_distances_argmin',\n 'pairwise_distances_argmin_min',\n 'pairwise_distances_chunked',\n 'pairwise_kernels',\n 'plot_precision_recall_curve',\n 'plot_roc_curve',\n 'PrecisionRecallDisplay',\n 'precision_recall_curve',\n 'precision_recall_fscore_support',\n 'precision_score',\n 'r2_score',\n 'recall_score',\n 'RocCurveDisplay',\n 'roc_auc_score',\n 'roc_curve',\n 'SCORERS',\n 'silhouette_samples',\n 'silhouette_score',\n 'v_measure_score',\n 'zero_one_loss',\n 'brier_score_loss',\n]\n\n", "current_contents": "from .pairwise import pairwise_kernels\nfrom .pairwise import pairwise_distances_chunked\n\nfrom ._regression import explained_variance_score\nfrom ._regression import max_error\nfrom ._regression import mean_absolute_error\nfrom ._regression import mean_squared_error\nfrom ._regression import mean_squared_log_error\nfrom ._regression import median_absolute_error\nfrom ._regression import r2_score\nfrom ._regression import mean_tweedie_deviance\nfrom ._regression import mean_poisson_deviance\nfrom ._regression import mean_gamma_deviance\n\n\nfrom ._scorer import check_scoring\nfrom ._scorer import make_scorer\nfrom ._scorer import SCORERS\nfrom ._scorer import get_scorer\n\nfrom ._plot.roc_curve import plot_roc_curve\nfrom ._plot.roc_curve import RocCurveDisplay\nfrom ._plot.precision_recall_curve import plot_precision_recall_curve\nfrom ._plot.precision_recall_curve import PrecisionRecallDisplay\n\n\n__all__ = [\n 'accuracy_score',\n 'adjusted_mutual_info_score',\n 'adjusted_rand_score',\n 'auc',\n 'average_precision_score',\n 'balanced_accuracy_score',\n 'calinski_harabaz_score',\n 'calinski_harabasz_score',\n 'check_scoring',\n 'classification_report',\n 'cluster',\n 'cohen_kappa_score',\n 'completeness_score',\n 'confusion_matrix',\n 'consensus_score',\n 'coverage_error',\n 'dcg_score',\n 'davies_bouldin_score',\n 'euclidean_distances',\n 'explained_variance_score',\n 'f1_score',\n 'fbeta_score',\n 'fowlkes_mallows_score',\n 'get_scorer',\n 'hamming_loss',\n 'hinge_loss',\n 'homogeneity_completeness_v_measure',\n 'homogeneity_score',\n 'jaccard_score',\n 'jaccard_similarity_score',\n 'label_ranking_average_precision_score',\n 'label_ranking_loss',\n 'log_loss',\n 'make_scorer',\n 'nan_euclidean_distances',\n 'matthews_corrcoef',\n 'max_error',\n 'mean_absolute_error',\n 'mean_squared_error',\n 'mean_squared_log_error',\n 'mean_poisson_deviance',\n 'mean_gamma_deviance',\n 'mean_tweedie_deviance',\n 'median_absolute_error',\n 'multilabel_confusion_matrix',\n 'mutual_info_score',\n 'ndcg_score',\n 'normalized_mutual_info_score',\n 'pairwise_distances',\n 'pairwise_distances_argmin',\n 'pairwise_distances_argmin_min',\n 'pairwise_distances_chunked',\n 'pairwise_kernels',\n 'plot_precision_recall_curve',\n 'plot_roc_curve',\n 'precision_recall_curve',\n 'precision_recall_fscore_support',\n 'precision_score',\n 'r2_score',\n 'recall_score',\n 'RocCurveDisplay',\n 'roc_auc_score',\n 'roc_curve',\n 'SCORERS',\n 'silhouette_samples',\n 'silhouette_score',\n 'v_measure_score',\n 'zero_one_loss',\n 'brier_score_loss',\n]\n"} {"commit": "947dffcc9c07bbb01739ad4d34a2f33b8e1120ed", "message": "FIX encode target for scoring when using early stopping in HistGradientBoostinClassifier (#14710)", "old_file": "sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py", "new_file": "sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py", "status": "M", "old_contents": " with scorers.\n \"\"\"\n subsample_size = 10000\n if X_binned_train.shape[0] > subsample_size:\n indices = np.arange(X_binned_train.shape[0])\n stratify = y_train if is_classifier(self) else None\n indices = resample(indices, n_samples=subsample_size,\n replace=False, random_state=seed,\n stratify=stratify)\n X_binned_small_train = X_binned_train[indices]\n y_small_train = y_train[indices]\n X_binned_small_train = np.ascontiguousarray(X_binned_small_train)\n return X_binned_small_train, y_small_train\n else:\n return X_binned_train, y_train\n\n def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,\n X_binned_val, y_val):\n \"\"\"Check if fitting should be early-stopped based on scorer.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n self.train_score_.append(\n self.scorer_(self, X_binned_small_train, y_small_train)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n self.scorer_(self, X_binned_val, y_val)\n )\n return self._should_stop(self.validation_score_)\n else:\n return self._should_stop(self.train_score_)\n\n def _check_early_stopping_loss(self,\n raw_predictions,\n y_train,\n raw_predictions_val,\n y_val):\n \"\"\"Check if fitting should be early-stopped based on loss.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n\n self.train_score_.append(\n -self.loss_(y_train, raw_predictions)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n -self.loss_(y_val, raw_predictions_val)", "new_contents": " with scorers.\n \"\"\"\n subsample_size = 10000\n if X_binned_train.shape[0] > subsample_size:\n indices = np.arange(X_binned_train.shape[0])\n stratify = y_train if is_classifier(self) else None\n indices = resample(indices, n_samples=subsample_size,\n replace=False, random_state=seed,\n stratify=stratify)\n X_binned_small_train = X_binned_train[indices]\n y_small_train = y_train[indices]\n X_binned_small_train = np.ascontiguousarray(X_binned_small_train)\n return X_binned_small_train, y_small_train\n else:\n return X_binned_train, y_train\n\n def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,\n X_binned_val, y_val):\n \"\"\"Check if fitting should be early-stopped based on scorer.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n if is_classifier(self):\n y_small_train = self.classes_[y_small_train.astype(int)]\n self.train_score_.append(\n self.scorer_(self, X_binned_small_train, y_small_train)\n )\n\n if self._use_validation_data:\n if is_classifier(self):\n y_val = self.classes_[y_val.astype(int)]\n self.validation_score_.append(\n self.scorer_(self, X_binned_val, y_val)\n )\n return self._should_stop(self.validation_score_)\n else:\n return self._should_stop(self.train_score_)\n\n def _check_early_stopping_loss(self,\n raw_predictions,\n y_train,\n raw_predictions_val,\n y_val):\n \"\"\"Check if fitting should be early-stopped based on loss.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n\n self.train_score_.append(\n -self.loss_(y_train, raw_predictions)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n -self.loss_(y_val, raw_predictions_val)", "text": "<|original_code|>\n with scorers.\n \"\"\"\n subsample_size = 10000\n if X_binned_train.shape[0] > subsample_size:\n indices = np.arange(X_binned_train.shape[0])\n stratify = y_train if is_classifier(self) else None\n indices = resample(indices, n_samples=subsample_size,\n replace=False, random_state=seed,\n stratify=stratify)\n X_binned_small_train = X_binned_train[indices]\n y_small_train = y_train[indices]\n X_binned_small_train = np.ascontiguousarray(X_binned_small_train)\n return X_binned_small_train, y_small_train\n else:\n return X_binned_train, y_train\n\n def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,\n X_binned_val, y_val):\n \"\"\"Check if fitting should be early-stopped based on scorer.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n self.train_score_.append(\n self.scorer_(self, X_binned_small_train, y_small_train)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n self.scorer_(self, X_binned_val, y_val)\n )\n return self._should_stop(self.validation_score_)\n else:\n return self._should_stop(self.train_score_)\n\n def _check_early_stopping_loss(self,\n raw_predictions,\n y_train,\n raw_predictions_val,\n y_val):\n \"\"\"Check if fitting should be early-stopped based on loss.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n\n self.train_score_.append(\n -self.loss_(y_train, raw_predictions)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n -self.loss_(y_val, raw_predictions_val)\n<|edits_diff|>\n--- sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py\n+++ sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py\n@@ -20,6 +20,8 @@\n \n Scores are computed on validation data or on training data.\n \"\"\"\n+ if is_classifier(self):\n+ y_small_train = self.classes_[y_small_train.astype(int)]\n self.train_score_.append(\n self.scorer_(self, X_binned_small_train, y_small_train)\n )\n<|current_version|>\n with scorers.\n \"\"\"\n subsample_size = 10000\n if X_binned_train.shape[0] > subsample_size:\n indices = np.arange(X_binned_train.shape[0])\n stratify = y_train if is_classifier(self) else None\n indices = resample(indices, n_samples=subsample_size,\n replace=False, random_state=seed,\n stratify=stratify)\n X_binned_small_train = X_binned_train[indices]\n y_small_train = y_train[indices]\n X_binned_small_train = np.ascontiguousarray(X_binned_small_train)\n return X_binned_small_train, y_small_train\n else:\n return X_binned_train, y_train\n\n def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,\n X_binned_val, y_val):\n \"\"\"Check if fitting should be early-stopped based on scorer.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n if is_classifier(self):\n y_small_train = self.classes_[y_small_train.astype(int)]\n self.train_score_.append(\n self.scorer_(self, X_binned_small_train, y_small_train)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n self.scorer_(self, X_binned_val, y_val)\n )\n return self._should_stop(self.validation_score_)\n else:\n return self._should_stop(self.train_score_)\n\n def _check_early_stopping_loss(self,\n raw_predictions,\n y_train,\n raw_predictions_val,\n y_val):\n \"\"\"Check if fitting should be early-stopped based on loss.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n\n self.train_score_.append(\n -self.loss_(y_train, raw_predictions)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n -self.loss_(y_val, raw_predictions_val)\n<|next_version|>\n with scorers.\n \"\"\"\n subsample_size = 10000\n if X_binned_train.shape[0] > subsample_size:\n indices = np.arange(X_binned_train.shape[0])\n stratify = y_train if is_classifier(self) else None\n indices = resample(indices, n_samples=subsample_size,\n replace=False, random_state=seed,\n stratify=stratify)\n X_binned_small_train = X_binned_train[indices]\n y_small_train = y_train[indices]\n X_binned_small_train = np.ascontiguousarray(X_binned_small_train)\n return X_binned_small_train, y_small_train\n else:\n return X_binned_train, y_train\n\n def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,\n X_binned_val, y_val):\n \"\"\"Check if fitting should be early-stopped based on scorer.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n if is_classifier(self):\n y_small_train = self.classes_[y_small_train.astype(int)]\n self.train_score_.append(\n self.scorer_(self, X_binned_small_train, y_small_train)\n )\n\n if self._use_validation_data:\n if is_classifier(self):\n y_val = self.classes_[y_val.astype(int)]\n self.validation_score_.append(\n self.scorer_(self, X_binned_val, y_val)\n )\n return self._should_stop(self.validation_score_)\n else:\n return self._should_stop(self.train_score_)\n\n def _check_early_stopping_loss(self,\n raw_predictions,\n y_train,\n raw_predictions_val,\n y_val):\n \"\"\"Check if fitting should be early-stopped based on loss.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n\n self.train_score_.append(\n -self.loss_(y_train, raw_predictions)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n -self.loss_(y_val, raw_predictions_val)\n", "current_contents": " with scorers.\n \"\"\"\n subsample_size = 10000\n if X_binned_train.shape[0] > subsample_size:\n indices = np.arange(X_binned_train.shape[0])\n stratify = y_train if is_classifier(self) else None\n indices = resample(indices, n_samples=subsample_size,\n replace=False, random_state=seed,\n stratify=stratify)\n X_binned_small_train = X_binned_train[indices]\n y_small_train = y_train[indices]\n X_binned_small_train = np.ascontiguousarray(X_binned_small_train)\n return X_binned_small_train, y_small_train\n else:\n return X_binned_train, y_train\n\n def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,\n X_binned_val, y_val):\n \"\"\"Check if fitting should be early-stopped based on scorer.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n if is_classifier(self):\n y_small_train = self.classes_[y_small_train.astype(int)]\n self.train_score_.append(\n self.scorer_(self, X_binned_small_train, y_small_train)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n self.scorer_(self, X_binned_val, y_val)\n )\n return self._should_stop(self.validation_score_)\n else:\n return self._should_stop(self.train_score_)\n\n def _check_early_stopping_loss(self,\n raw_predictions,\n y_train,\n raw_predictions_val,\n y_val):\n \"\"\"Check if fitting should be early-stopped based on loss.\n\n Scores are computed on validation data or on training data.\n \"\"\"\n\n self.train_score_.append(\n -self.loss_(y_train, raw_predictions)\n )\n\n if self._use_validation_data:\n self.validation_score_.append(\n -self.loss_(y_val, raw_predictions_val)"} {"commit": "d8268956f697a766b9eb24f98420ba4916bf6a3d", "message": "Address a few more Error Prone warnings.", "old_file": "android/guava/src/com/google/common/eventbus/Dispatcher.java", "new_file": "android/guava/src/com/google/common/eventbus/Dispatcher.java", "status": "M", "old_contents": " static Dispatcher legacyAsync() {\n return new LegacyAsyncDispatcher();\n }\n\n /**\n * Returns a dispatcher that dispatches events to subscribers immediately as they're posted\n * without using an intermediate queue to change the dispatch order. This is effectively a\n * depth-first dispatch order, vs. breadth-first when using a queue.\n */\n static Dispatcher immediate() {\n return ImmediateDispatcher.INSTANCE;\n }\n\n /** Dispatches the given {@code event} to the given {@code subscribers}. */\n abstract void dispatch(Object event, Iterator subscribers);\n\n /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */\n private static final class PerThreadQueuedDispatcher extends Dispatcher {\n\n // This dispatcher matches the original dispatch behavior of EventBus.\n\n /** Per-thread queue of events to dispatch. */\n private final ThreadLocal> queue =\n new ThreadLocal>() {\n @Override\n protected Queue initialValue() {\n return Queues.newArrayDeque();\n }\n };\n\n /** Per-thread dispatch state, used to avoid reentrant event dispatching. */\n private final ThreadLocal dispatching =\n new ThreadLocal() {\n @Override\n protected Boolean initialValue() {\n return false;\n }\n };\n\n @Override\n void dispatch(Object event, Iterator subscribers) {\n checkNotNull(event);\n checkNotNull(subscribers);\n // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get\n Queue queueForThread = requireNonNull(queue.get());\n queueForThread.offer(new Event(event, subscribers));\n\n if (!dispatching.get()) {\n dispatching.set(true);\n try {\n Event nextEvent;\n while ((nextEvent = queueForThread.poll()) != null) {\n while (nextEvent.subscribers.hasNext()) {\n nextEvent.subscribers.next().dispatchEvent(nextEvent.event);\n }", "new_contents": " static Dispatcher legacyAsync() {\n return new LegacyAsyncDispatcher();\n }\n\n /**\n * Returns a dispatcher that dispatches events to subscribers immediately as they're posted\n * without using an intermediate queue to change the dispatch order. This is effectively a\n * depth-first dispatch order, vs. breadth-first when using a queue.\n */\n static Dispatcher immediate() {\n return ImmediateDispatcher.INSTANCE;\n }\n\n /** Dispatches the given {@code event} to the given {@code subscribers}. */\n abstract void dispatch(Object event, Iterator subscribers);\n\n /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */\n private static final class PerThreadQueuedDispatcher extends Dispatcher {\n\n // This dispatcher matches the original dispatch behavior of EventBus.\n\n /** Per-thread queue of events to dispatch. */\n @SuppressWarnings(\"ThreadLocalUsage\") // Each Dispatcher needs its own state.\n private final ThreadLocal> queue =\n new ThreadLocal>() {\n @Override\n protected Queue initialValue() {\n return Queues.newArrayDeque();\n }\n };\n\n /** Per-thread dispatch state, used to avoid reentrant event dispatching. */\n @SuppressWarnings(\"ThreadLocalUsage\") // Each Dispatcher needs its own state.\n private final ThreadLocal dispatching =\n new ThreadLocal() {\n @Override\n protected Boolean initialValue() {\n return false;\n }\n };\n\n @Override\n void dispatch(Object event, Iterator subscribers) {\n checkNotNull(event);\n checkNotNull(subscribers);\n // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get\n Queue queueForThread = requireNonNull(queue.get());\n queueForThread.offer(new Event(event, subscribers));\n\n if (!dispatching.get()) {\n dispatching.set(true);\n try {\n Event nextEvent;\n while ((nextEvent = queueForThread.poll()) != null) {\n while (nextEvent.subscribers.hasNext()) {\n nextEvent.subscribers.next().dispatchEvent(nextEvent.event);\n }", "text": "<|original_code|>\n static Dispatcher legacyAsync() {\n return new LegacyAsyncDispatcher();\n }\n\n /**\n * Returns a dispatcher that dispatches events to subscribers immediately as they're posted\n * without using an intermediate queue to change the dispatch order. This is effectively a\n * depth-first dispatch order, vs. breadth-first when using a queue.\n */\n static Dispatcher immediate() {\n return ImmediateDispatcher.INSTANCE;\n }\n\n /** Dispatches the given {@code event} to the given {@code subscribers}. */\n abstract void dispatch(Object event, Iterator subscribers);\n\n /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */\n private static final class PerThreadQueuedDispatcher extends Dispatcher {\n\n // This dispatcher matches the original dispatch behavior of EventBus.\n\n /** Per-thread queue of events to dispatch. */\n private final ThreadLocal> queue =\n new ThreadLocal>() {\n @Override\n protected Queue initialValue() {\n return Queues.newArrayDeque();\n }\n };\n\n /** Per-thread dispatch state, used to avoid reentrant event dispatching. */\n private final ThreadLocal dispatching =\n new ThreadLocal() {\n @Override\n protected Boolean initialValue() {\n return false;\n }\n };\n\n @Override\n void dispatch(Object event, Iterator subscribers) {\n checkNotNull(event);\n checkNotNull(subscribers);\n // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get\n Queue queueForThread = requireNonNull(queue.get());\n queueForThread.offer(new Event(event, subscribers));\n\n if (!dispatching.get()) {\n dispatching.set(true);\n try {\n Event nextEvent;\n while ((nextEvent = queueForThread.poll()) != null) {\n while (nextEvent.subscribers.hasNext()) {\n nextEvent.subscribers.next().dispatchEvent(nextEvent.event);\n }\n<|edits_diff|>\n--- android/guava/src/com/google/common/eventbus/Dispatcher.java\n+++ android/guava/src/com/google/common/eventbus/Dispatcher.java\n@@ -20,6 +20,7 @@\n // This dispatcher matches the original dispatch behavior of EventBus.\n \n /** Per-thread queue of events to dispatch. */\n+ @SuppressWarnings(\"ThreadLocalUsage\") // Each Dispatcher needs its own state.\n private final ThreadLocal> queue =\n new ThreadLocal>() {\n @Override\n<|current_version|>\n static Dispatcher legacyAsync() {\n return new LegacyAsyncDispatcher();\n }\n\n /**\n * Returns a dispatcher that dispatches events to subscribers immediately as they're posted\n * without using an intermediate queue to change the dispatch order. This is effectively a\n * depth-first dispatch order, vs. breadth-first when using a queue.\n */\n static Dispatcher immediate() {\n return ImmediateDispatcher.INSTANCE;\n }\n\n /** Dispatches the given {@code event} to the given {@code subscribers}. */\n abstract void dispatch(Object event, Iterator subscribers);\n\n /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */\n private static final class PerThreadQueuedDispatcher extends Dispatcher {\n\n // This dispatcher matches the original dispatch behavior of EventBus.\n\n /** Per-thread queue of events to dispatch. */\n @SuppressWarnings(\"ThreadLocalUsage\") // Each Dispatcher needs its own state.\n private final ThreadLocal> queue =\n new ThreadLocal>() {\n @Override\n protected Queue initialValue() {\n return Queues.newArrayDeque();\n }\n };\n\n /** Per-thread dispatch state, used to avoid reentrant event dispatching. */\n private final ThreadLocal dispatching =\n new ThreadLocal() {\n @Override\n protected Boolean initialValue() {\n return false;\n }\n };\n\n @Override\n void dispatch(Object event, Iterator subscribers) {\n checkNotNull(event);\n checkNotNull(subscribers);\n // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get\n Queue queueForThread = requireNonNull(queue.get());\n queueForThread.offer(new Event(event, subscribers));\n\n if (!dispatching.get()) {\n dispatching.set(true);\n try {\n Event nextEvent;\n while ((nextEvent = queueForThread.poll()) != null) {\n while (nextEvent.subscribers.hasNext()) {\n nextEvent.subscribers.next().dispatchEvent(nextEvent.event);\n }\n<|next_version|>\n static Dispatcher legacyAsync() {\n return new LegacyAsyncDispatcher();\n }\n\n /**\n * Returns a dispatcher that dispatches events to subscribers immediately as they're posted\n * without using an intermediate queue to change the dispatch order. This is effectively a\n * depth-first dispatch order, vs. breadth-first when using a queue.\n */\n static Dispatcher immediate() {\n return ImmediateDispatcher.INSTANCE;\n }\n\n /** Dispatches the given {@code event} to the given {@code subscribers}. */\n abstract void dispatch(Object event, Iterator subscribers);\n\n /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */\n private static final class PerThreadQueuedDispatcher extends Dispatcher {\n\n // This dispatcher matches the original dispatch behavior of EventBus.\n\n /** Per-thread queue of events to dispatch. */\n @SuppressWarnings(\"ThreadLocalUsage\") // Each Dispatcher needs its own state.\n private final ThreadLocal> queue =\n new ThreadLocal>() {\n @Override\n protected Queue initialValue() {\n return Queues.newArrayDeque();\n }\n };\n\n /** Per-thread dispatch state, used to avoid reentrant event dispatching. */\n @SuppressWarnings(\"ThreadLocalUsage\") // Each Dispatcher needs its own state.\n private final ThreadLocal dispatching =\n new ThreadLocal() {\n @Override\n protected Boolean initialValue() {\n return false;\n }\n };\n\n @Override\n void dispatch(Object event, Iterator subscribers) {\n checkNotNull(event);\n checkNotNull(subscribers);\n // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get\n Queue queueForThread = requireNonNull(queue.get());\n queueForThread.offer(new Event(event, subscribers));\n\n if (!dispatching.get()) {\n dispatching.set(true);\n try {\n Event nextEvent;\n while ((nextEvent = queueForThread.poll()) != null) {\n while (nextEvent.subscribers.hasNext()) {\n nextEvent.subscribers.next().dispatchEvent(nextEvent.event);\n }\n", "current_contents": " static Dispatcher legacyAsync() {\n return new LegacyAsyncDispatcher();\n }\n\n /**\n * Returns a dispatcher that dispatches events to subscribers immediately as they're posted\n * without using an intermediate queue to change the dispatch order. This is effectively a\n * depth-first dispatch order, vs. breadth-first when using a queue.\n */\n static Dispatcher immediate() {\n return ImmediateDispatcher.INSTANCE;\n }\n\n /** Dispatches the given {@code event} to the given {@code subscribers}. */\n abstract void dispatch(Object event, Iterator subscribers);\n\n /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */\n private static final class PerThreadQueuedDispatcher extends Dispatcher {\n\n // This dispatcher matches the original dispatch behavior of EventBus.\n\n /** Per-thread queue of events to dispatch. */\n @SuppressWarnings(\"ThreadLocalUsage\") // Each Dispatcher needs its own state.\n private final ThreadLocal> queue =\n new ThreadLocal>() {\n @Override\n protected Queue initialValue() {\n return Queues.newArrayDeque();\n }\n };\n\n /** Per-thread dispatch state, used to avoid reentrant event dispatching. */\n private final ThreadLocal dispatching =\n new ThreadLocal() {\n @Override\n protected Boolean initialValue() {\n return false;\n }\n };\n\n @Override\n void dispatch(Object event, Iterator subscribers) {\n checkNotNull(event);\n checkNotNull(subscribers);\n // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get\n Queue queueForThread = requireNonNull(queue.get());\n queueForThread.offer(new Event(event, subscribers));\n\n if (!dispatching.get()) {\n dispatching.set(true);\n try {\n Event nextEvent;\n while ((nextEvent = queueForThread.poll()) != null) {\n while (nextEvent.subscribers.hasNext()) {\n nextEvent.subscribers.next().dispatchEvent(nextEvent.event);\n }"} {"commit": "008e78e799cfe6ef47beab313a99d23fdf334b87", "message": "Override `Predicate.test` wherever we override `Predicate.apply`.", "old_file": "guava-tests/test/com/google/common/hash/BloomFilterTest.java", "new_file": "guava-tests/test/com/google/common/hash/BloomFilterTest.java", "status": "M", "old_contents": " IllegalArgumentException.class,\n () -> {\n BloomFilter unused =\n BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);\n });\n assertThat(expected)\n .hasMessageThat()\n .isEqualTo(\"Could not create BloomFilter of 3327428144502 bits\");\n }\n\n @AndroidIncompatible // OutOfMemoryError\n public void testLargeNumberOfInsertions() {\n // We use horrible FPPs here to keep Java from OOM'ing\n BloomFilter unused =\n BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);\n unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);\n }\n\n @SuppressWarnings({\"deprecation\", \"InlineMeInliner\"}) // test of a deprecated method\n private static void checkSanity(BloomFilter bf) {\n assertFalse(bf.mightContain(new Object()));\n assertFalse(bf.apply(new Object()));\n for (int i = 0; i < 100; i++) {\n Object o = new Object();\n bf.put(o);\n assertTrue(bf.mightContain(o));\n assertTrue(bf.apply(o));\n }\n }\n\n public void testCopy() {\n BloomFilter original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);\n BloomFilter copy = original.copy();\n assertNotSame(original, copy);\n assertEquals(original, copy);\n }\n\n public void testExpectedFpp() {\n BloomFilter bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);\n double fpp = bf.expectedFpp();\n assertThat(fpp).isEqualTo(0.0);\n // usually completed in less than 200 iterations\n while (fpp != 1.0) {\n boolean changed = bf.put(new Object());\n double newFpp = bf.expectedFpp();\n // if changed, the new fpp is strictly higher, otherwise it is the same\n assertTrue(changed ? newFpp > fpp : newFpp == fpp);\n fpp = newFpp;\n }\n }\n", "new_contents": " IllegalArgumentException.class,\n () -> {\n BloomFilter unused =\n BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);\n });\n assertThat(expected)\n .hasMessageThat()\n .isEqualTo(\"Could not create BloomFilter of 3327428144502 bits\");\n }\n\n @AndroidIncompatible // OutOfMemoryError\n public void testLargeNumberOfInsertions() {\n // We use horrible FPPs here to keep Java from OOM'ing\n BloomFilter unused =\n BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);\n unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);\n }\n\n @SuppressWarnings({\"deprecation\", \"InlineMeInliner\"}) // test of a deprecated method\n private static void checkSanity(BloomFilter bf) {\n assertFalse(bf.mightContain(new Object()));\n assertFalse(bf.apply(new Object()));\n assertFalse(bf.test(new Object()));\n for (int i = 0; i < 100; i++) {\n Object o = new Object();\n bf.put(o);\n assertTrue(bf.mightContain(o));\n assertTrue(bf.apply(o));\n assertTrue(bf.test(o));\n }\n }\n\n public void testCopy() {\n BloomFilter original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);\n BloomFilter copy = original.copy();\n assertNotSame(original, copy);\n assertEquals(original, copy);\n }\n\n public void testExpectedFpp() {\n BloomFilter bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);\n double fpp = bf.expectedFpp();\n assertThat(fpp).isEqualTo(0.0);\n // usually completed in less than 200 iterations\n while (fpp != 1.0) {\n boolean changed = bf.put(new Object());\n double newFpp = bf.expectedFpp();\n // if changed, the new fpp is strictly higher, otherwise it is the same\n assertTrue(changed ? newFpp > fpp : newFpp == fpp);\n fpp = newFpp;\n }\n }\n", "text": "<|original_code|>\n IllegalArgumentException.class,\n () -> {\n BloomFilter unused =\n BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);\n });\n assertThat(expected)\n .hasMessageThat()\n .isEqualTo(\"Could not create BloomFilter of 3327428144502 bits\");\n }\n\n @AndroidIncompatible // OutOfMemoryError\n public void testLargeNumberOfInsertions() {\n // We use horrible FPPs here to keep Java from OOM'ing\n BloomFilter unused =\n BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);\n unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);\n }\n\n @SuppressWarnings({\"deprecation\", \"InlineMeInliner\"}) // test of a deprecated method\n private static void checkSanity(BloomFilter bf) {\n assertFalse(bf.mightContain(new Object()));\n assertFalse(bf.apply(new Object()));\n for (int i = 0; i < 100; i++) {\n Object o = new Object();\n bf.put(o);\n assertTrue(bf.mightContain(o));\n assertTrue(bf.apply(o));\n }\n }\n\n public void testCopy() {\n BloomFilter original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);\n BloomFilter copy = original.copy();\n assertNotSame(original, copy);\n assertEquals(original, copy);\n }\n\n public void testExpectedFpp() {\n BloomFilter bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);\n double fpp = bf.expectedFpp();\n assertThat(fpp).isEqualTo(0.0);\n // usually completed in less than 200 iterations\n while (fpp != 1.0) {\n boolean changed = bf.put(new Object());\n double newFpp = bf.expectedFpp();\n // if changed, the new fpp is strictly higher, otherwise it is the same\n assertTrue(changed ? newFpp > fpp : newFpp == fpp);\n fpp = newFpp;\n }\n }\n\n<|edits_diff|>\n--- guava-tests/test/com/google/common/hash/BloomFilterTest.java\n+++ guava-tests/test/com/google/common/hash/BloomFilterTest.java\n@@ -20,6 +20,7 @@\n private static void checkSanity(BloomFilter bf) {\n assertFalse(bf.mightContain(new Object()));\n assertFalse(bf.apply(new Object()));\n+ assertFalse(bf.test(new Object()));\n for (int i = 0; i < 100; i++) {\n Object o = new Object();\n bf.put(o);\n<|current_version|>\n IllegalArgumentException.class,\n () -> {\n BloomFilter unused =\n BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);\n });\n assertThat(expected)\n .hasMessageThat()\n .isEqualTo(\"Could not create BloomFilter of 3327428144502 bits\");\n }\n\n @AndroidIncompatible // OutOfMemoryError\n public void testLargeNumberOfInsertions() {\n // We use horrible FPPs here to keep Java from OOM'ing\n BloomFilter unused =\n BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);\n unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);\n }\n\n @SuppressWarnings({\"deprecation\", \"InlineMeInliner\"}) // test of a deprecated method\n private static void checkSanity(BloomFilter bf) {\n assertFalse(bf.mightContain(new Object()));\n assertFalse(bf.apply(new Object()));\n assertFalse(bf.test(new Object()));\n for (int i = 0; i < 100; i++) {\n Object o = new Object();\n bf.put(o);\n assertTrue(bf.mightContain(o));\n assertTrue(bf.apply(o));\n }\n }\n\n public void testCopy() {\n BloomFilter original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);\n BloomFilter copy = original.copy();\n assertNotSame(original, copy);\n assertEquals(original, copy);\n }\n\n public void testExpectedFpp() {\n BloomFilter bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);\n double fpp = bf.expectedFpp();\n assertThat(fpp).isEqualTo(0.0);\n // usually completed in less than 200 iterations\n while (fpp != 1.0) {\n boolean changed = bf.put(new Object());\n double newFpp = bf.expectedFpp();\n // if changed, the new fpp is strictly higher, otherwise it is the same\n assertTrue(changed ? newFpp > fpp : newFpp == fpp);\n fpp = newFpp;\n }\n }\n\n<|next_version|>\n IllegalArgumentException.class,\n () -> {\n BloomFilter unused =\n BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);\n });\n assertThat(expected)\n .hasMessageThat()\n .isEqualTo(\"Could not create BloomFilter of 3327428144502 bits\");\n }\n\n @AndroidIncompatible // OutOfMemoryError\n public void testLargeNumberOfInsertions() {\n // We use horrible FPPs here to keep Java from OOM'ing\n BloomFilter unused =\n BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);\n unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);\n }\n\n @SuppressWarnings({\"deprecation\", \"InlineMeInliner\"}) // test of a deprecated method\n private static void checkSanity(BloomFilter bf) {\n assertFalse(bf.mightContain(new Object()));\n assertFalse(bf.apply(new Object()));\n assertFalse(bf.test(new Object()));\n for (int i = 0; i < 100; i++) {\n Object o = new Object();\n bf.put(o);\n assertTrue(bf.mightContain(o));\n assertTrue(bf.apply(o));\n assertTrue(bf.test(o));\n }\n }\n\n public void testCopy() {\n BloomFilter original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);\n BloomFilter copy = original.copy();\n assertNotSame(original, copy);\n assertEquals(original, copy);\n }\n\n public void testExpectedFpp() {\n BloomFilter bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);\n double fpp = bf.expectedFpp();\n assertThat(fpp).isEqualTo(0.0);\n // usually completed in less than 200 iterations\n while (fpp != 1.0) {\n boolean changed = bf.put(new Object());\n double newFpp = bf.expectedFpp();\n // if changed, the new fpp is strictly higher, otherwise it is the same\n assertTrue(changed ? newFpp > fpp : newFpp == fpp);\n fpp = newFpp;\n }\n }\n\n", "current_contents": " IllegalArgumentException.class,\n () -> {\n BloomFilter unused =\n BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);\n });\n assertThat(expected)\n .hasMessageThat()\n .isEqualTo(\"Could not create BloomFilter of 3327428144502 bits\");\n }\n\n @AndroidIncompatible // OutOfMemoryError\n public void testLargeNumberOfInsertions() {\n // We use horrible FPPs here to keep Java from OOM'ing\n BloomFilter unused =\n BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);\n unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);\n }\n\n @SuppressWarnings({\"deprecation\", \"InlineMeInliner\"}) // test of a deprecated method\n private static void checkSanity(BloomFilter bf) {\n assertFalse(bf.mightContain(new Object()));\n assertFalse(bf.apply(new Object()));\n assertFalse(bf.test(new Object()));\n for (int i = 0; i < 100; i++) {\n Object o = new Object();\n bf.put(o);\n assertTrue(bf.mightContain(o));\n assertTrue(bf.apply(o));\n }\n }\n\n public void testCopy() {\n BloomFilter original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);\n BloomFilter copy = original.copy();\n assertNotSame(original, copy);\n assertEquals(original, copy);\n }\n\n public void testExpectedFpp() {\n BloomFilter bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);\n double fpp = bf.expectedFpp();\n assertThat(fpp).isEqualTo(0.0);\n // usually completed in less than 200 iterations\n while (fpp != 1.0) {\n boolean changed = bf.put(new Object());\n double newFpp = bf.expectedFpp();\n // if changed, the new fpp is strictly higher, otherwise it is the same\n assertTrue(changed ? newFpp > fpp : newFpp == fpp);\n fpp = newFpp;\n }\n }\n"} {"commit": "16d1e071ae555e67577d5c69aa543ea3cd556cd2", "message": "Standardize annotations on `serialVersionUID` fields.", "old_file": "android/guava/src/com/google/common/hash/LongAdder.java", "new_file": "android/guava/src/com/google/common/hash/LongAdder.java", "status": "M", "old_contents": "/*\n * Written by Doug Lea with assistance from members of JCP JSR-166\n * Expert Group and released to the public domain, as explained at\n * http://creativecommons.org/publicdomain/zero/1.0/\n */\n\n/*\n * Source:\n * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17\n */\n\npackage com.google.common.hash;\n\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * One or more variables that together maintain an initially zero {@code long} sum. When updates\n * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to\n * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current\n * total combined across the variables maintaining the sum.\n *\n *

This class is usually preferable to {@link AtomicLong} when multiple threads update a common\n * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization\n * control. Under low update contention, the two classes have similar characteristics. But under\n * high contention, expected throughput of this class is significantly higher, at the expense of\n * higher space consumption.\n *\n *

This class extends {@link Number}, but does not define methods such as {@code\n * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and\n * so are not useful as collection keys.\n *\n *

jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.\n *\n * @since 1.8\n * @author Doug Lea\n */\nfinal class LongAdder extends Striped64 implements Serializable, LongAddable {\n private static final long serialVersionUID = 7249069246863182397L;\n\n /** Version of plus for use in retryUpdate */\n @Override\n final long fn(long v, long x) {\n return v + x;\n }\n\n /** Creates a new adder with initial sum of zero. */\n public LongAdder() {}\n\n /**\n * Adds the given value.\n *\n * @param x the value to add\n */\n @Override\n public void add(long x) {\n Cell[] as;\n long b, v;\n int[] hc;\n Cell a;\n int n;\n if ((as = cells) != null || !casBase(b = base, b + x)) {", "new_contents": "/*\n * Written by Doug Lea with assistance from members of JCP JSR-166\n * Expert Group and released to the public domain, as explained at\n * http://creativecommons.org/publicdomain/zero/1.0/\n */\n\n/*\n * Source:\n * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17\n */\n\npackage com.google.common.hash;\n\nimport com.google.common.annotations.GwtIncompatible;\nimport com.google.common.annotations.J2ktIncompatible;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * One or more variables that together maintain an initially zero {@code long} sum. When updates\n * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to\n * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current\n * total combined across the variables maintaining the sum.\n *\n *

This class is usually preferable to {@link AtomicLong} when multiple threads update a common\n * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization\n * control. Under low update contention, the two classes have similar characteristics. But under\n * high contention, expected throughput of this class is significantly higher, at the expense of\n * higher space consumption.\n *\n *

This class extends {@link Number}, but does not define methods such as {@code\n * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and\n * so are not useful as collection keys.\n *\n *

jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.\n *\n * @since 1.8\n * @author Doug Lea\n */\nfinal class LongAdder extends Striped64 implements Serializable, LongAddable {\n @GwtIncompatible @J2ktIncompatible\n private static final long serialVersionUID = 7249069246863182397L;\n\n /** Version of plus for use in retryUpdate */\n @Override\n final long fn(long v, long x) {\n return v + x;\n }\n\n /** Creates a new adder with initial sum of zero. */\n public LongAdder() {}\n\n /**\n * Adds the given value.\n *\n * @param x the value to add\n */\n @Override\n public void add(long x) {\n Cell[] as;\n long b, v;\n int[] hc;\n Cell a;\n int n;\n if ((as = cells) != null || !casBase(b = base, b + x)) {", "text": "<|original_code|>\n/*\n * Written by Doug Lea with assistance from members of JCP JSR-166\n * Expert Group and released to the public domain, as explained at\n * http://creativecommons.org/publicdomain/zero/1.0/\n */\n\n/*\n * Source:\n * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17\n */\n\npackage com.google.common.hash;\n\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * One or more variables that together maintain an initially zero {@code long} sum. When updates\n * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to\n * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current\n * total combined across the variables maintaining the sum.\n *\n *

This class is usually preferable to {@link AtomicLong} when multiple threads update a common\n * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization\n * control. Under low update contention, the two classes have similar characteristics. But under\n * high contention, expected throughput of this class is significantly higher, at the expense of\n * higher space consumption.\n *\n *

This class extends {@link Number}, but does not define methods such as {@code\n * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and\n * so are not useful as collection keys.\n *\n *

jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.\n *\n * @since 1.8\n * @author Doug Lea\n */\nfinal class LongAdder extends Striped64 implements Serializable, LongAddable {\n private static final long serialVersionUID = 7249069246863182397L;\n\n /** Version of plus for use in retryUpdate */\n @Override\n final long fn(long v, long x) {\n return v + x;\n }\n\n /** Creates a new adder with initial sum of zero. */\n public LongAdder() {}\n\n /**\n * Adds the given value.\n *\n * @param x the value to add\n */\n @Override\n public void add(long x) {\n Cell[] as;\n long b, v;\n int[] hc;\n Cell a;\n int n;\n if ((as = cells) != null || !casBase(b = base, b + x)) {\n<|edits_diff|>\n--- android/guava/src/com/google/common/hash/LongAdder.java\n+++ android/guava/src/com/google/common/hash/LongAdder.java\n@@ -11,6 +11,8 @@\n \n package com.google.common.hash;\n \n+import com.google.common.annotations.GwtIncompatible;\n+import com.google.common.annotations.J2ktIncompatible;\n import java.io.IOException;\n import java.io.ObjectInputStream;\n import java.io.ObjectOutputStream;\n<|current_version|>\n/*\n * Written by Doug Lea with assistance from members of JCP JSR-166\n * Expert Group and released to the public domain, as explained at\n * http://creativecommons.org/publicdomain/zero/1.0/\n */\n\n/*\n * Source:\n * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17\n */\n\npackage com.google.common.hash;\n\nimport com.google.common.annotations.GwtIncompatible;\nimport com.google.common.annotations.J2ktIncompatible;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * One or more variables that together maintain an initially zero {@code long} sum. When updates\n * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to\n * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current\n * total combined across the variables maintaining the sum.\n *\n *

This class is usually preferable to {@link AtomicLong} when multiple threads update a common\n * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization\n * control. Under low update contention, the two classes have similar characteristics. But under\n * high contention, expected throughput of this class is significantly higher, at the expense of\n * higher space consumption.\n *\n *

This class extends {@link Number}, but does not define methods such as {@code\n * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and\n * so are not useful as collection keys.\n *\n *

jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.\n *\n * @since 1.8\n * @author Doug Lea\n */\nfinal class LongAdder extends Striped64 implements Serializable, LongAddable {\n private static final long serialVersionUID = 7249069246863182397L;\n\n /** Version of plus for use in retryUpdate */\n @Override\n final long fn(long v, long x) {\n return v + x;\n }\n\n /** Creates a new adder with initial sum of zero. */\n public LongAdder() {}\n\n /**\n * Adds the given value.\n *\n * @param x the value to add\n */\n @Override\n public void add(long x) {\n Cell[] as;\n long b, v;\n int[] hc;\n Cell a;\n int n;\n if ((as = cells) != null || !casBase(b = base, b + x)) {\n<|next_version|>\n/*\n * Written by Doug Lea with assistance from members of JCP JSR-166\n * Expert Group and released to the public domain, as explained at\n * http://creativecommons.org/publicdomain/zero/1.0/\n */\n\n/*\n * Source:\n * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17\n */\n\npackage com.google.common.hash;\n\nimport com.google.common.annotations.GwtIncompatible;\nimport com.google.common.annotations.J2ktIncompatible;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * One or more variables that together maintain an initially zero {@code long} sum. When updates\n * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to\n * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current\n * total combined across the variables maintaining the sum.\n *\n *

This class is usually preferable to {@link AtomicLong} when multiple threads update a common\n * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization\n * control. Under low update contention, the two classes have similar characteristics. But under\n * high contention, expected throughput of this class is significantly higher, at the expense of\n * higher space consumption.\n *\n *

This class extends {@link Number}, but does not define methods such as {@code\n * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and\n * so are not useful as collection keys.\n *\n *

jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.\n *\n * @since 1.8\n * @author Doug Lea\n */\nfinal class LongAdder extends Striped64 implements Serializable, LongAddable {\n @GwtIncompatible @J2ktIncompatible\n private static final long serialVersionUID = 7249069246863182397L;\n\n /** Version of plus for use in retryUpdate */\n @Override\n final long fn(long v, long x) {\n return v + x;\n }\n\n /** Creates a new adder with initial sum of zero. */\n public LongAdder() {}\n\n /**\n * Adds the given value.\n *\n * @param x the value to add\n */\n @Override\n public void add(long x) {\n Cell[] as;\n long b, v;\n int[] hc;\n Cell a;\n int n;\n if ((as = cells) != null || !casBase(b = base, b + x)) {\n", "current_contents": "/*\n * Written by Doug Lea with assistance from members of JCP JSR-166\n * Expert Group and released to the public domain, as explained at\n * http://creativecommons.org/publicdomain/zero/1.0/\n */\n\n/*\n * Source:\n * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17\n */\n\npackage com.google.common.hash;\n\nimport com.google.common.annotations.GwtIncompatible;\nimport com.google.common.annotations.J2ktIncompatible;\nimport java.io.IOException;\nimport java.io.ObjectInputStream;\nimport java.io.ObjectOutputStream;\nimport java.io.Serializable;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * One or more variables that together maintain an initially zero {@code long} sum. When updates\n * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to\n * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current\n * total combined across the variables maintaining the sum.\n *\n *

This class is usually preferable to {@link AtomicLong} when multiple threads update a common\n * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization\n * control. Under low update contention, the two classes have similar characteristics. But under\n * high contention, expected throughput of this class is significantly higher, at the expense of\n * higher space consumption.\n *\n *

This class extends {@link Number}, but does not define methods such as {@code\n * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and\n * so are not useful as collection keys.\n *\n *

jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.\n *\n * @since 1.8\n * @author Doug Lea\n */\nfinal class LongAdder extends Striped64 implements Serializable, LongAddable {\n private static final long serialVersionUID = 7249069246863182397L;\n\n /** Version of plus for use in retryUpdate */\n @Override\n final long fn(long v, long x) {\n return v + x;\n }\n\n /** Creates a new adder with initial sum of zero. */\n public LongAdder() {}\n\n /**\n * Adds the given value.\n *\n * @param x the value to add\n */\n @Override\n public void add(long x) {\n Cell[] as;\n long b, v;\n int[] hc;\n Cell a;\n int n;\n if ((as = cells) != null || !casBase(b = base, b + x)) {"} {"commit": "f2bd540e7654360d83d96bd7e283eba53ec74d2e", "message": "Add `@CanIgnoreReturnValue`, or suppress where we shouldn't.", "old_file": "android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java", "new_file": "android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java", "status": "M", "old_contents": "/*\n * Copyright (C) 2011 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.caliper.Benchmark;\nimport org.jspecify.annotations.NullUnmarked;\n\n/**\n * Benchmarking interners.\n *\n * @author Dimitris Andreou\n */\n@NullUnmarked\npublic class InternersBenchmark {\n @Benchmark\n int weakInterner(int reps) {\n Interner interner = Interners.newWeakInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @Benchmark\n int strongInterner(int reps) {\n Interner interner = Interners.newStrongInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @Benchmark\n int stringIntern(int reps) {\n for (int i = 0; i < reps; i++) {\n String unused = Double.toHexString(Math.random()).intern();\n }\n return reps;\n }\n}\n", "new_contents": "/*\n * Copyright (C) 2011 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.caliper.Benchmark;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport org.jspecify.annotations.NullUnmarked;\n\n/**\n * Benchmarking interners.\n *\n * @author Dimitris Andreou\n */\n@NullUnmarked\npublic class InternersBenchmark {\n @CanIgnoreReturnValue\n @Benchmark\n int weakInterner(int reps) {\n Interner interner = Interners.newWeakInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @CanIgnoreReturnValue\n @Benchmark\n int strongInterner(int reps) {\n Interner interner = Interners.newStrongInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @CanIgnoreReturnValue\n @Benchmark\n int stringIntern(int reps) {\n for (int i = 0; i < reps; i++) {\n String unused = Double.toHexString(Math.random()).intern();\n }\n return reps;\n }\n}\n", "text": "<|original_code|>\n/*\n * Copyright (C) 2011 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.caliper.Benchmark;\nimport org.jspecify.annotations.NullUnmarked;\n\n/**\n * Benchmarking interners.\n *\n * @author Dimitris Andreou\n */\n@NullUnmarked\npublic class InternersBenchmark {\n @Benchmark\n int weakInterner(int reps) {\n Interner interner = Interners.newWeakInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @Benchmark\n int strongInterner(int reps) {\n Interner interner = Interners.newStrongInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @Benchmark\n int stringIntern(int reps) {\n for (int i = 0; i < reps; i++) {\n String unused = Double.toHexString(Math.random()).intern();\n }\n return reps;\n }\n}\n\n<|edits_diff|>\n--- android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java\n+++ android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java\n@@ -17,6 +17,7 @@\n package com.google.common.collect;\n \n import com.google.caliper.Benchmark;\n+import com.google.errorprone.annotations.CanIgnoreReturnValue;\n import org.jspecify.annotations.NullUnmarked;\n \n /**\n@@ -26,6 +27,7 @@\n */\n @NullUnmarked\n public class InternersBenchmark {\n+ @CanIgnoreReturnValue\n @Benchmark\n int weakInterner(int reps) {\n Interner interner = Interners.newWeakInterner();\n@@ -35,6 +37,7 @@\n return reps;\n }\n \n+ @CanIgnoreReturnValue\n @Benchmark\n int strongInterner(int reps) {\n Interner interner = Interners.newStrongInterner();\n<|current_version|>\n/*\n * Copyright (C) 2011 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.caliper.Benchmark;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport org.jspecify.annotations.NullUnmarked;\n\n/**\n * Benchmarking interners.\n *\n * @author Dimitris Andreou\n */\n@NullUnmarked\npublic class InternersBenchmark {\n @CanIgnoreReturnValue\n @Benchmark\n int weakInterner(int reps) {\n Interner interner = Interners.newWeakInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @CanIgnoreReturnValue\n @Benchmark\n int strongInterner(int reps) {\n Interner interner = Interners.newStrongInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @Benchmark\n int stringIntern(int reps) {\n for (int i = 0; i < reps; i++) {\n String unused = Double.toHexString(Math.random()).intern();\n }\n return reps;\n }\n}\n\n<|next_version|>\n/*\n * Copyright (C) 2011 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.caliper.Benchmark;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport org.jspecify.annotations.NullUnmarked;\n\n/**\n * Benchmarking interners.\n *\n * @author Dimitris Andreou\n */\n@NullUnmarked\npublic class InternersBenchmark {\n @CanIgnoreReturnValue\n @Benchmark\n int weakInterner(int reps) {\n Interner interner = Interners.newWeakInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @CanIgnoreReturnValue\n @Benchmark\n int strongInterner(int reps) {\n Interner interner = Interners.newStrongInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @CanIgnoreReturnValue\n @Benchmark\n int stringIntern(int reps) {\n for (int i = 0; i < reps; i++) {\n String unused = Double.toHexString(Math.random()).intern();\n }\n return reps;\n }\n}\n\n", "current_contents": "/*\n * Copyright (C) 2011 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.caliper.Benchmark;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport org.jspecify.annotations.NullUnmarked;\n\n/**\n * Benchmarking interners.\n *\n * @author Dimitris Andreou\n */\n@NullUnmarked\npublic class InternersBenchmark {\n @CanIgnoreReturnValue\n @Benchmark\n int weakInterner(int reps) {\n Interner interner = Interners.newWeakInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @CanIgnoreReturnValue\n @Benchmark\n int strongInterner(int reps) {\n Interner interner = Interners.newStrongInterner();\n for (int i = 0; i < reps; i++) {\n String unused = interner.intern(Double.toHexString(Math.random()));\n }\n return reps;\n }\n\n @Benchmark\n int stringIntern(int reps) {\n for (int i = 0; i < reps; i++) {\n String unused = Double.toHexString(Math.random()).intern();\n }\n return reps;\n }\n}\n"} {"commit": "4559277ff03fec79861839039c608820049146e8", "message": "Apply or suppress suggestions to use `@InlineMe`.", "old_file": "guava/src/com/google/common/graph/ImmutableValueGraph.java", "new_file": "guava/src/com/google/common/graph/ImmutableValueGraph.java", "status": "M", "old_contents": " * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.graph;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.Objects.requireNonNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.errorprone.annotations.Immutable;\n\n/**\n * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of\n * this class may be obtained with {@link #copyOf(ValueGraph)}.\n *\n *

See the Guava User's Guide's discussion\n * of the {@code Immutable*} types for more information on the properties and guarantees\n * provided by this class.\n *\n * @author James Sexton\n * @author Jens Nyman\n * @param Node parameter type\n * @param Value parameter type\n * @since 20.0\n */\n@Beta\n@Immutable(containerOf = {\"N\", \"V\"})\n@SuppressWarnings(\"Immutable\") // Extends StandardValueGraph but uses ImmutableMaps.\npublic final class ImmutableValueGraph extends StandardValueGraph {\n\n private ImmutableValueGraph(ValueGraph graph) {\n super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());\n }\n\n /** Returns an immutable copy of {@code graph}. */\n public static ImmutableValueGraph copyOf(ValueGraph graph) {\n return (graph instanceof ImmutableValueGraph)\n ? (ImmutableValueGraph) graph\n : new ImmutableValueGraph(graph);\n }\n\n /**\n * Simply returns its argument.\n *\n * @deprecated no need to use this\n */\n @Deprecated\n public static ImmutableValueGraph copyOf(ImmutableValueGraph graph) {\n return checkNotNull(graph);\n }\n\n @Override\n public ElementOrder incidentEdgeOrder() {\n return ElementOrder.stable();\n }\n\n @Override\n public ImmutableGraph asGraph() {\n return new ImmutableGraph<>(this); // safe because the view is effectively immutable\n }\n\n private static ImmutableMap> getNodeConnections(\n ValueGraph graph) {\n // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have\n // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the\n // input nodes are sorted.\n ImmutableMap.Builder> nodeConnections = ImmutableMap.builder();\n for (N node : graph.nodes()) {\n nodeConnections.put(node, connectionsOf(graph, node));\n }", "new_contents": " * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.graph;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.Objects.requireNonNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.errorprone.annotations.Immutable;\nimport com.google.errorprone.annotations.InlineMe;\n\n/**\n * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of\n * this class may be obtained with {@link #copyOf(ValueGraph)}.\n *\n *

See the Guava User's Guide's discussion\n * of the {@code Immutable*} types for more information on the properties and guarantees\n * provided by this class.\n *\n * @author James Sexton\n * @author Jens Nyman\n * @param Node parameter type\n * @param Value parameter type\n * @since 20.0\n */\n@Beta\n@Immutable(containerOf = {\"N\", \"V\"})\n@SuppressWarnings(\"Immutable\") // Extends StandardValueGraph but uses ImmutableMaps.\npublic final class ImmutableValueGraph extends StandardValueGraph {\n\n private ImmutableValueGraph(ValueGraph graph) {\n super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());\n }\n\n /** Returns an immutable copy of {@code graph}. */\n public static ImmutableValueGraph copyOf(ValueGraph graph) {\n return (graph instanceof ImmutableValueGraph)\n ? (ImmutableValueGraph) graph\n : new ImmutableValueGraph(graph);\n }\n\n /**\n * Simply returns its argument.\n *\n * @deprecated no need to use this\n */\n @InlineMe(\n replacement = \"checkNotNull(graph)\",\n staticImports = \"com.google.common.base.Preconditions.checkNotNull\")\n @Deprecated\n public static ImmutableValueGraph copyOf(ImmutableValueGraph graph) {\n return checkNotNull(graph);\n }\n\n @Override\n public ElementOrder incidentEdgeOrder() {\n return ElementOrder.stable();\n }\n\n @Override\n public ImmutableGraph asGraph() {\n return new ImmutableGraph<>(this); // safe because the view is effectively immutable\n }\n\n private static ImmutableMap> getNodeConnections(\n ValueGraph graph) {\n // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have\n // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the\n // input nodes are sorted.\n ImmutableMap.Builder> nodeConnections = ImmutableMap.builder();\n for (N node : graph.nodes()) {\n nodeConnections.put(node, connectionsOf(graph, node));\n }", "text": "<|original_code|>\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.graph;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.Objects.requireNonNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.errorprone.annotations.Immutable;\n\n/**\n * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of\n * this class may be obtained with {@link #copyOf(ValueGraph)}.\n *\n *

See the Guava User's Guide's discussion\n * of the {@code Immutable*} types for more information on the properties and guarantees\n * provided by this class.\n *\n * @author James Sexton\n * @author Jens Nyman\n * @param Node parameter type\n * @param Value parameter type\n * @since 20.0\n */\n@Beta\n@Immutable(containerOf = {\"N\", \"V\"})\n@SuppressWarnings(\"Immutable\") // Extends StandardValueGraph but uses ImmutableMaps.\npublic final class ImmutableValueGraph extends StandardValueGraph {\n\n private ImmutableValueGraph(ValueGraph graph) {\n super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());\n }\n\n /** Returns an immutable copy of {@code graph}. */\n public static ImmutableValueGraph copyOf(ValueGraph graph) {\n return (graph instanceof ImmutableValueGraph)\n ? (ImmutableValueGraph) graph\n : new ImmutableValueGraph(graph);\n }\n\n /**\n * Simply returns its argument.\n *\n * @deprecated no need to use this\n */\n @Deprecated\n public static ImmutableValueGraph copyOf(ImmutableValueGraph graph) {\n return checkNotNull(graph);\n }\n\n @Override\n public ElementOrder incidentEdgeOrder() {\n return ElementOrder.stable();\n }\n\n @Override\n public ImmutableGraph asGraph() {\n return new ImmutableGraph<>(this); // safe because the view is effectively immutable\n }\n\n private static ImmutableMap> getNodeConnections(\n ValueGraph graph) {\n // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have\n // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the\n // input nodes are sorted.\n ImmutableMap.Builder> nodeConnections = ImmutableMap.builder();\n for (N node : graph.nodes()) {\n nodeConnections.put(node, connectionsOf(graph, node));\n }\n<|edits_diff|>\n--- guava/src/com/google/common/graph/ImmutableValueGraph.java\n+++ guava/src/com/google/common/graph/ImmutableValueGraph.java\n@@ -20,6 +20,7 @@\n import com.google.common.collect.Maps;\n import com.google.errorprone.annotations.CanIgnoreReturnValue;\n import com.google.errorprone.annotations.Immutable;\n+import com.google.errorprone.annotations.InlineMe;\n \n /**\n * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of\n<|current_version|>\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.graph;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.Objects.requireNonNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.errorprone.annotations.Immutable;\nimport com.google.errorprone.annotations.InlineMe;\n\n/**\n * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of\n * this class may be obtained with {@link #copyOf(ValueGraph)}.\n *\n *

See the Guava User's Guide's discussion\n * of the {@code Immutable*} types for more information on the properties and guarantees\n * provided by this class.\n *\n * @author James Sexton\n * @author Jens Nyman\n * @param Node parameter type\n * @param Value parameter type\n * @since 20.0\n */\n@Beta\n@Immutable(containerOf = {\"N\", \"V\"})\n@SuppressWarnings(\"Immutable\") // Extends StandardValueGraph but uses ImmutableMaps.\npublic final class ImmutableValueGraph extends StandardValueGraph {\n\n private ImmutableValueGraph(ValueGraph graph) {\n super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());\n }\n\n /** Returns an immutable copy of {@code graph}. */\n public static ImmutableValueGraph copyOf(ValueGraph graph) {\n return (graph instanceof ImmutableValueGraph)\n ? (ImmutableValueGraph) graph\n : new ImmutableValueGraph(graph);\n }\n\n /**\n * Simply returns its argument.\n *\n * @deprecated no need to use this\n */\n @Deprecated\n public static ImmutableValueGraph copyOf(ImmutableValueGraph graph) {\n return checkNotNull(graph);\n }\n\n @Override\n public ElementOrder incidentEdgeOrder() {\n return ElementOrder.stable();\n }\n\n @Override\n public ImmutableGraph asGraph() {\n return new ImmutableGraph<>(this); // safe because the view is effectively immutable\n }\n\n private static ImmutableMap> getNodeConnections(\n ValueGraph graph) {\n // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have\n // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the\n // input nodes are sorted.\n ImmutableMap.Builder> nodeConnections = ImmutableMap.builder();\n for (N node : graph.nodes()) {\n nodeConnections.put(node, connectionsOf(graph, node));\n }\n<|next_version|>\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.graph;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.Objects.requireNonNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.errorprone.annotations.Immutable;\nimport com.google.errorprone.annotations.InlineMe;\n\n/**\n * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of\n * this class may be obtained with {@link #copyOf(ValueGraph)}.\n *\n *

See the Guava User's Guide's discussion\n * of the {@code Immutable*} types for more information on the properties and guarantees\n * provided by this class.\n *\n * @author James Sexton\n * @author Jens Nyman\n * @param Node parameter type\n * @param Value parameter type\n * @since 20.0\n */\n@Beta\n@Immutable(containerOf = {\"N\", \"V\"})\n@SuppressWarnings(\"Immutable\") // Extends StandardValueGraph but uses ImmutableMaps.\npublic final class ImmutableValueGraph extends StandardValueGraph {\n\n private ImmutableValueGraph(ValueGraph graph) {\n super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());\n }\n\n /** Returns an immutable copy of {@code graph}. */\n public static ImmutableValueGraph copyOf(ValueGraph graph) {\n return (graph instanceof ImmutableValueGraph)\n ? (ImmutableValueGraph) graph\n : new ImmutableValueGraph(graph);\n }\n\n /**\n * Simply returns its argument.\n *\n * @deprecated no need to use this\n */\n @InlineMe(\n replacement = \"checkNotNull(graph)\",\n staticImports = \"com.google.common.base.Preconditions.checkNotNull\")\n @Deprecated\n public static ImmutableValueGraph copyOf(ImmutableValueGraph graph) {\n return checkNotNull(graph);\n }\n\n @Override\n public ElementOrder incidentEdgeOrder() {\n return ElementOrder.stable();\n }\n\n @Override\n public ImmutableGraph asGraph() {\n return new ImmutableGraph<>(this); // safe because the view is effectively immutable\n }\n\n private static ImmutableMap> getNodeConnections(\n ValueGraph graph) {\n // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have\n // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the\n // input nodes are sorted.\n ImmutableMap.Builder> nodeConnections = ImmutableMap.builder();\n for (N node : graph.nodes()) {\n nodeConnections.put(node, connectionsOf(graph, node));\n }\n", "current_contents": " * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.graph;\n\nimport static com.google.common.base.Preconditions.checkNotNull;\nimport static java.util.Objects.requireNonNull;\n\nimport com.google.common.annotations.Beta;\nimport com.google.common.base.Function;\nimport com.google.common.collect.ImmutableMap;\nimport com.google.common.collect.Maps;\nimport com.google.errorprone.annotations.CanIgnoreReturnValue;\nimport com.google.errorprone.annotations.Immutable;\nimport com.google.errorprone.annotations.InlineMe;\n\n/**\n * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of\n * this class may be obtained with {@link #copyOf(ValueGraph)}.\n *\n *

See the Guava User's Guide's discussion\n * of the {@code Immutable*} types for more information on the properties and guarantees\n * provided by this class.\n *\n * @author James Sexton\n * @author Jens Nyman\n * @param Node parameter type\n * @param Value parameter type\n * @since 20.0\n */\n@Beta\n@Immutable(containerOf = {\"N\", \"V\"})\n@SuppressWarnings(\"Immutable\") // Extends StandardValueGraph but uses ImmutableMaps.\npublic final class ImmutableValueGraph extends StandardValueGraph {\n\n private ImmutableValueGraph(ValueGraph graph) {\n super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());\n }\n\n /** Returns an immutable copy of {@code graph}. */\n public static ImmutableValueGraph copyOf(ValueGraph graph) {\n return (graph instanceof ImmutableValueGraph)\n ? (ImmutableValueGraph) graph\n : new ImmutableValueGraph(graph);\n }\n\n /**\n * Simply returns its argument.\n *\n * @deprecated no need to use this\n */\n @Deprecated\n public static ImmutableValueGraph copyOf(ImmutableValueGraph graph) {\n return checkNotNull(graph);\n }\n\n @Override\n public ElementOrder incidentEdgeOrder() {\n return ElementOrder.stable();\n }\n\n @Override\n public ImmutableGraph asGraph() {\n return new ImmutableGraph<>(this); // safe because the view is effectively immutable\n }\n\n private static ImmutableMap> getNodeConnections(\n ValueGraph graph) {\n // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have\n // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the\n // input nodes are sorted.\n ImmutableMap.Builder> nodeConnections = ImmutableMap.builder();\n for (N node : graph.nodes()) {\n nodeConnections.put(node, connectionsOf(graph, node));\n }"} {"commit": "daad0b3fba2bdc317900966a2752bf7d906001f4", "message": "Avoid calling methods whose return type changed in Java 9 -- even from tests.", "old_file": "guava/src/com/google/common/io/Java8Compatibility.java", "new_file": "guava/src/com/google/common/io/Java8Compatibility.java", "status": "M", "old_contents": "import com.google.common.annotations.GwtIncompatible;\nimport java.nio.Buffer;\n\n/**\n * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See\n * https://github.com/google/guava/issues/3990\n */\n@GwtIncompatible\n@ElementTypesAreNonnullByDefault\nfinal class Java8Compatibility {\n static void clear(Buffer b) {\n b.clear();\n }\n\n static void flip(Buffer b) {\n b.flip();\n }\n\n static void limit(Buffer b, int limit) {\n b.limit(limit);\n }\n\n static void position(Buffer b, int position) {\n b.position(position);\n }\n\n private Java8Compatibility() {}\n}\n", "new_contents": "import com.google.common.annotations.GwtIncompatible;\nimport java.nio.Buffer;\n\n/**\n * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See\n * https://github.com/google/guava/issues/3990\n */\n@GwtIncompatible\n@ElementTypesAreNonnullByDefault\nfinal class Java8Compatibility {\n static void clear(Buffer b) {\n b.clear();\n }\n\n static void flip(Buffer b) {\n b.flip();\n }\n\n static void limit(Buffer b, int limit) {\n b.limit(limit);\n }\n\n static void mark(Buffer b) {\n b.mark();\n }\n\n static void position(Buffer b, int position) {\n b.position(position);\n }\n\n static void reset(Buffer b) {\n b.reset();\n }\n\n private Java8Compatibility() {}\n}\n", "text": "<|original_code|>\nimport com.google.common.annotations.GwtIncompatible;\nimport java.nio.Buffer;\n\n/**\n * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See\n * https://github.com/google/guava/issues/3990\n */\n@GwtIncompatible\n@ElementTypesAreNonnullByDefault\nfinal class Java8Compatibility {\n static void clear(Buffer b) {\n b.clear();\n }\n\n static void flip(Buffer b) {\n b.flip();\n }\n\n static void limit(Buffer b, int limit) {\n b.limit(limit);\n }\n\n static void position(Buffer b, int position) {\n b.position(position);\n }\n\n private Java8Compatibility() {}\n}\n\n<|edits_diff|>\n--- guava/src/com/google/common/io/Java8Compatibility.java\n+++ guava/src/com/google/common/io/Java8Compatibility.java\n@@ -20,6 +20,10 @@\n b.limit(limit);\n }\n \n+ static void mark(Buffer b) {\n+ b.mark();\n+ }\n+\n static void position(Buffer b, int position) {\n b.position(position);\n }\n<|current_version|>\nimport com.google.common.annotations.GwtIncompatible;\nimport java.nio.Buffer;\n\n/**\n * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See\n * https://github.com/google/guava/issues/3990\n */\n@GwtIncompatible\n@ElementTypesAreNonnullByDefault\nfinal class Java8Compatibility {\n static void clear(Buffer b) {\n b.clear();\n }\n\n static void flip(Buffer b) {\n b.flip();\n }\n\n static void limit(Buffer b, int limit) {\n b.limit(limit);\n }\n\n static void mark(Buffer b) {\n b.mark();\n }\n\n static void position(Buffer b, int position) {\n b.position(position);\n }\n\n private Java8Compatibility() {}\n}\n\n<|next_version|>\nimport com.google.common.annotations.GwtIncompatible;\nimport java.nio.Buffer;\n\n/**\n * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See\n * https://github.com/google/guava/issues/3990\n */\n@GwtIncompatible\n@ElementTypesAreNonnullByDefault\nfinal class Java8Compatibility {\n static void clear(Buffer b) {\n b.clear();\n }\n\n static void flip(Buffer b) {\n b.flip();\n }\n\n static void limit(Buffer b, int limit) {\n b.limit(limit);\n }\n\n static void mark(Buffer b) {\n b.mark();\n }\n\n static void position(Buffer b, int position) {\n b.position(position);\n }\n\n static void reset(Buffer b) {\n b.reset();\n }\n\n private Java8Compatibility() {}\n}\n\n", "current_contents": "import com.google.common.annotations.GwtIncompatible;\nimport java.nio.Buffer;\n\n/**\n * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See\n * https://github.com/google/guava/issues/3990\n */\n@GwtIncompatible\n@ElementTypesAreNonnullByDefault\nfinal class Java8Compatibility {\n static void clear(Buffer b) {\n b.clear();\n }\n\n static void flip(Buffer b) {\n b.flip();\n }\n\n static void limit(Buffer b, int limit) {\n b.limit(limit);\n }\n\n static void mark(Buffer b) {\n b.mark();\n }\n\n static void position(Buffer b, int position) {\n b.position(position);\n }\n\n private Java8Compatibility() {}\n}\n"} {"commit": "c7d9fef73b9314581bf4acd0d97b12178935eb11", "message": "Copy the `setUp` and `tearDown` from the parent builder to derived test suites.", "old_file": "android/guava-testlib/src/com/google/common/collect/testing/MapTestSuiteBuilder.java", "new_file": "android/guava-testlib/src/com/google/common/collect/testing/MapTestSuiteBuilder.java", "status": "M", "old_contents": " MapSizeTester.class,\n MapToStringTester.class);\n }\n\n @Override\n protected List createDerivedSuites(\n FeatureSpecificTestSuiteBuilder<\n ?, ? extends OneSizeTestContainerGenerator, Entry>>\n parentBuilder) {\n // TODO: Once invariant support is added, supply invariants to each of the\n // derived suites, to check that mutations to the derived collections are\n // reflected in the underlying map.\n\n List derivedSuites = super.createDerivedSuites(parentBuilder);\n\n if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {\n derivedSuites.add(\n MapTestSuiteBuilder.using(\n new ReserializedMapGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" reserialized\")\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n }\n\n derivedSuites.add(\n createDerivedEntrySetSuite(\n new MapEntrySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" entrySet\")\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" keys\")\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedValueCollectionSuite(\n new MapValueCollectionGenerator(parentBuilder.getSubjectGenerator()))\n .named(parentBuilder.getName() + \" values\")\n .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n\n return derivedSuites;\n }\n\n protected SetTestSuiteBuilder> createDerivedEntrySetSuite(\n TestSetGenerator> entrySetGenerator) {\n return SetTestSuiteBuilder.using(entrySetGenerator);\n }\n\n protected SetTestSuiteBuilder createDerivedKeySetSuite(TestSetGenerator keySetGenerator) {\n return SetTestSuiteBuilder.using(keySetGenerator);\n }\n\n protected CollectionTestSuiteBuilder createDerivedValueCollectionSuite(\n TestCollectionGenerator valueCollectionGenerator) {\n return CollectionTestSuiteBuilder.using(valueCollectionGenerator);\n }\n\n private static Set> computeReserializedMapFeatures(Set> mapFeatures) {\n Set> derivedFeatures = Helpers.copyToSet(mapFeatures);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);\n return derivedFeatures;", "new_contents": " MapSizeTester.class,\n MapToStringTester.class);\n }\n\n @Override\n protected List createDerivedSuites(\n FeatureSpecificTestSuiteBuilder<\n ?, ? extends OneSizeTestContainerGenerator, Entry>>\n parentBuilder) {\n // TODO: Once invariant support is added, supply invariants to each of the\n // derived suites, to check that mutations to the derived collections are\n // reflected in the underlying map.\n\n List derivedSuites = super.createDerivedSuites(parentBuilder);\n\n if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {\n derivedSuites.add(\n MapTestSuiteBuilder.using(\n new ReserializedMapGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" reserialized\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n }\n\n derivedSuites.add(\n createDerivedEntrySetSuite(\n new MapEntrySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" entrySet\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" keys\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedValueCollectionSuite(\n new MapValueCollectionGenerator(parentBuilder.getSubjectGenerator()))\n .named(parentBuilder.getName() + \" values\")\n .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n return derivedSuites;\n }\n\n protected SetTestSuiteBuilder> createDerivedEntrySetSuite(\n TestSetGenerator> entrySetGenerator) {\n return SetTestSuiteBuilder.using(entrySetGenerator);\n }\n\n protected SetTestSuiteBuilder createDerivedKeySetSuite(TestSetGenerator keySetGenerator) {\n return SetTestSuiteBuilder.using(keySetGenerator);\n }\n\n protected CollectionTestSuiteBuilder createDerivedValueCollectionSuite(\n TestCollectionGenerator valueCollectionGenerator) {\n return CollectionTestSuiteBuilder.using(valueCollectionGenerator);\n }\n\n private static Set> computeReserializedMapFeatures(Set> mapFeatures) {\n Set> derivedFeatures = Helpers.copyToSet(mapFeatures);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);\n return derivedFeatures;", "text": "<|original_code|>\n MapSizeTester.class,\n MapToStringTester.class);\n }\n\n @Override\n protected List createDerivedSuites(\n FeatureSpecificTestSuiteBuilder<\n ?, ? extends OneSizeTestContainerGenerator, Entry>>\n parentBuilder) {\n // TODO: Once invariant support is added, supply invariants to each of the\n // derived suites, to check that mutations to the derived collections are\n // reflected in the underlying map.\n\n List derivedSuites = super.createDerivedSuites(parentBuilder);\n\n if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {\n derivedSuites.add(\n MapTestSuiteBuilder.using(\n new ReserializedMapGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" reserialized\")\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n }\n\n derivedSuites.add(\n createDerivedEntrySetSuite(\n new MapEntrySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" entrySet\")\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" keys\")\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedValueCollectionSuite(\n new MapValueCollectionGenerator(parentBuilder.getSubjectGenerator()))\n .named(parentBuilder.getName() + \" values\")\n .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n\n return derivedSuites;\n }\n\n protected SetTestSuiteBuilder> createDerivedEntrySetSuite(\n TestSetGenerator> entrySetGenerator) {\n return SetTestSuiteBuilder.using(entrySetGenerator);\n }\n\n protected SetTestSuiteBuilder createDerivedKeySetSuite(TestSetGenerator keySetGenerator) {\n return SetTestSuiteBuilder.using(keySetGenerator);\n }\n\n protected CollectionTestSuiteBuilder createDerivedValueCollectionSuite(\n TestCollectionGenerator valueCollectionGenerator) {\n return CollectionTestSuiteBuilder.using(valueCollectionGenerator);\n }\n\n private static Set> computeReserializedMapFeatures(Set> mapFeatures) {\n Set> derivedFeatures = Helpers.copyToSet(mapFeatures);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);\n return derivedFeatures;\n<|edits_diff|>\n--- android/guava-testlib/src/com/google/common/collect/testing/MapTestSuiteBuilder.java\n+++ android/guava-testlib/src/com/google/common/collect/testing/MapTestSuiteBuilder.java\n@@ -20,6 +20,8 @@\n .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" reserialized\")\n .suppressing(parentBuilder.getSuppressedTests())\n+ .withSetUp(parentBuilder.getSetUp())\n+ .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n }\n \n@@ -29,6 +31,8 @@\n .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" entrySet\")\n .suppressing(parentBuilder.getSuppressedTests())\n+ .withSetUp(parentBuilder.getSetUp())\n+ .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n \n derivedSuites.add(\n@@ -36,6 +40,8 @@\n .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" keys\")\n .suppressing(parentBuilder.getSuppressedTests())\n+ .withSetUp(parentBuilder.getSetUp())\n+ .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n \n derivedSuites.add(\n<|current_version|>\n MapSizeTester.class,\n MapToStringTester.class);\n }\n\n @Override\n protected List createDerivedSuites(\n FeatureSpecificTestSuiteBuilder<\n ?, ? extends OneSizeTestContainerGenerator, Entry>>\n parentBuilder) {\n // TODO: Once invariant support is added, supply invariants to each of the\n // derived suites, to check that mutations to the derived collections are\n // reflected in the underlying map.\n\n List derivedSuites = super.createDerivedSuites(parentBuilder);\n\n if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {\n derivedSuites.add(\n MapTestSuiteBuilder.using(\n new ReserializedMapGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" reserialized\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n }\n\n derivedSuites.add(\n createDerivedEntrySetSuite(\n new MapEntrySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" entrySet\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" keys\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedValueCollectionSuite(\n new MapValueCollectionGenerator(parentBuilder.getSubjectGenerator()))\n .named(parentBuilder.getName() + \" values\")\n .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n\n return derivedSuites;\n }\n\n protected SetTestSuiteBuilder> createDerivedEntrySetSuite(\n TestSetGenerator> entrySetGenerator) {\n return SetTestSuiteBuilder.using(entrySetGenerator);\n }\n\n protected SetTestSuiteBuilder createDerivedKeySetSuite(TestSetGenerator keySetGenerator) {\n return SetTestSuiteBuilder.using(keySetGenerator);\n }\n\n protected CollectionTestSuiteBuilder createDerivedValueCollectionSuite(\n TestCollectionGenerator valueCollectionGenerator) {\n return CollectionTestSuiteBuilder.using(valueCollectionGenerator);\n }\n\n private static Set> computeReserializedMapFeatures(Set> mapFeatures) {\n Set> derivedFeatures = Helpers.copyToSet(mapFeatures);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);\n return derivedFeatures;\n<|next_version|>\n MapSizeTester.class,\n MapToStringTester.class);\n }\n\n @Override\n protected List createDerivedSuites(\n FeatureSpecificTestSuiteBuilder<\n ?, ? extends OneSizeTestContainerGenerator, Entry>>\n parentBuilder) {\n // TODO: Once invariant support is added, supply invariants to each of the\n // derived suites, to check that mutations to the derived collections are\n // reflected in the underlying map.\n\n List derivedSuites = super.createDerivedSuites(parentBuilder);\n\n if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {\n derivedSuites.add(\n MapTestSuiteBuilder.using(\n new ReserializedMapGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" reserialized\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n }\n\n derivedSuites.add(\n createDerivedEntrySetSuite(\n new MapEntrySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" entrySet\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" keys\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedValueCollectionSuite(\n new MapValueCollectionGenerator(parentBuilder.getSubjectGenerator()))\n .named(parentBuilder.getName() + \" values\")\n .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n return derivedSuites;\n }\n\n protected SetTestSuiteBuilder> createDerivedEntrySetSuite(\n TestSetGenerator> entrySetGenerator) {\n return SetTestSuiteBuilder.using(entrySetGenerator);\n }\n\n protected SetTestSuiteBuilder createDerivedKeySetSuite(TestSetGenerator keySetGenerator) {\n return SetTestSuiteBuilder.using(keySetGenerator);\n }\n\n protected CollectionTestSuiteBuilder createDerivedValueCollectionSuite(\n TestCollectionGenerator valueCollectionGenerator) {\n return CollectionTestSuiteBuilder.using(valueCollectionGenerator);\n }\n\n private static Set> computeReserializedMapFeatures(Set> mapFeatures) {\n Set> derivedFeatures = Helpers.copyToSet(mapFeatures);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);\n return derivedFeatures;\n", "current_contents": " MapSizeTester.class,\n MapToStringTester.class);\n }\n\n @Override\n protected List createDerivedSuites(\n FeatureSpecificTestSuiteBuilder<\n ?, ? extends OneSizeTestContainerGenerator, Entry>>\n parentBuilder) {\n // TODO: Once invariant support is added, supply invariants to each of the\n // derived suites, to check that mutations to the derived collections are\n // reflected in the underlying map.\n\n List derivedSuites = super.createDerivedSuites(parentBuilder);\n\n if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {\n derivedSuites.add(\n MapTestSuiteBuilder.using(\n new ReserializedMapGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" reserialized\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n }\n\n derivedSuites.add(\n createDerivedEntrySetSuite(\n new MapEntrySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" entrySet\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))\n .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))\n .named(parentBuilder.getName() + \" keys\")\n .suppressing(parentBuilder.getSuppressedTests())\n .withSetUp(parentBuilder.getSetUp())\n .withTearDown(parentBuilder.getTearDown())\n .createTestSuite());\n\n derivedSuites.add(\n createDerivedValueCollectionSuite(\n new MapValueCollectionGenerator(parentBuilder.getSubjectGenerator()))\n .named(parentBuilder.getName() + \" values\")\n .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))\n .suppressing(parentBuilder.getSuppressedTests())\n .createTestSuite());\n\n return derivedSuites;\n }\n\n protected SetTestSuiteBuilder> createDerivedEntrySetSuite(\n TestSetGenerator> entrySetGenerator) {\n return SetTestSuiteBuilder.using(entrySetGenerator);\n }\n\n protected SetTestSuiteBuilder createDerivedKeySetSuite(TestSetGenerator keySetGenerator) {\n return SetTestSuiteBuilder.using(keySetGenerator);\n }\n\n protected CollectionTestSuiteBuilder createDerivedValueCollectionSuite(\n TestCollectionGenerator valueCollectionGenerator) {\n return CollectionTestSuiteBuilder.using(valueCollectionGenerator);\n }\n\n private static Set> computeReserializedMapFeatures(Set> mapFeatures) {\n Set> derivedFeatures = Helpers.copyToSet(mapFeatures);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE);\n derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);\n return derivedFeatures;"} {"commit": "19c08f9a3e7ffd96749e897fdaa456d0400ffa33", "message": "Use ConcurrentHashMap.newKeySet() in Sets.newConcurrentHashSet()", "old_file": "guava/src/com/google/common/collect/Platform.java", "new_file": "guava/src/com/google/common/collect/Platform.java", "status": "M", "old_contents": " * Copyright (C) 2008 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.common.annotations.GwtCompatible;\nimport java.lang.reflect.Array;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * Methods factored out so that they can be emulated differently in GWT.\n *\n * @author Hayward Chan\n */\n@GwtCompatible(emulated = true)\nfinal class Platform {\n private static final java.util.logging.Logger logger =\n java.util.logging.Logger.getLogger(Platform.class.getName());\n\n /** Returns the platform preferred implementation of a map based on a hash table. */\n static Map newHashMapWithExpectedSize(int expectedSize) {\n return Maps.newHashMapWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered map based on a hash\n * table.\n */\n static Map newLinkedHashMapWithExpectedSize(int expectedSize) {\n return Maps.newLinkedHashMapWithExpectedSize(expectedSize);\n }\n\n /** Returns the platform preferred implementation of a set based on a hash table. */\n static Set newHashSetWithExpectedSize(int expectedSize) {\n return Sets.newHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered set based on a hash\n * table.\n */\n static Set newLinkedHashSetWithExpectedSize(int expectedSize) {\n return Sets.newLinkedHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred map implementation that preserves insertion order when used only\n * for insertions.\n */\n static Map preservesInsertionOrderOnPutsMap() {\n return Maps.newLinkedHashMap();\n }\n\n /**\n * Returns the platform preferred set implementation that preserves insertion order when used only\n * for insertions.\n */\n static Set preservesInsertionOrderOnAddsSet() {\n return Sets.newLinkedHashSet();", "new_contents": " * Copyright (C) 2008 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.common.annotations.GwtCompatible;\nimport java.lang.reflect.Array;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * Methods factored out so that they can be emulated differently in GWT.\n *\n * @author Hayward Chan\n */\n@GwtCompatible(emulated = true)\nfinal class Platform {\n private static final java.util.logging.Logger logger =\n java.util.logging.Logger.getLogger(Platform.class.getName());\n\n /** Returns the platform preferred implementation of a map based on a hash table. */\n static Map newHashMapWithExpectedSize(int expectedSize) {\n return Maps.newHashMapWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered map based on a hash\n * table.\n */\n static Map newLinkedHashMapWithExpectedSize(int expectedSize) {\n return Maps.newLinkedHashMapWithExpectedSize(expectedSize);\n }\n\n /** Returns the platform preferred implementation of a set based on a hash table. */\n static Set newHashSetWithExpectedSize(int expectedSize) {\n return Sets.newHashSetWithExpectedSize(expectedSize);\n }\n\n /** Returns the platform preferred implementation of a thread-safe hash set. */\n static Set newConcurrentHashSet() {\n return ConcurrentHashMap.newKeySet();\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered set based on a hash\n * table.\n */\n static Set newLinkedHashSetWithExpectedSize(int expectedSize) {\n return Sets.newLinkedHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred map implementation that preserves insertion order when used only\n * for insertions.\n */\n static Map preservesInsertionOrderOnPutsMap() {\n return Maps.newLinkedHashMap();\n }\n\n /**\n * Returns the platform preferred set implementation that preserves insertion order when used only\n * for insertions.\n */\n static Set preservesInsertionOrderOnAddsSet() {\n return Sets.newLinkedHashSet();", "text": "<|original_code|>\n * Copyright (C) 2008 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.common.annotations.GwtCompatible;\nimport java.lang.reflect.Array;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\n\n/**\n * Methods factored out so that they can be emulated differently in GWT.\n *\n * @author Hayward Chan\n */\n@GwtCompatible(emulated = true)\nfinal class Platform {\n private static final java.util.logging.Logger logger =\n java.util.logging.Logger.getLogger(Platform.class.getName());\n\n /** Returns the platform preferred implementation of a map based on a hash table. */\n static Map newHashMapWithExpectedSize(int expectedSize) {\n return Maps.newHashMapWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered map based on a hash\n * table.\n */\n static Map newLinkedHashMapWithExpectedSize(int expectedSize) {\n return Maps.newLinkedHashMapWithExpectedSize(expectedSize);\n }\n\n /** Returns the platform preferred implementation of a set based on a hash table. */\n static Set newHashSetWithExpectedSize(int expectedSize) {\n return Sets.newHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered set based on a hash\n * table.\n */\n static Set newLinkedHashSetWithExpectedSize(int expectedSize) {\n return Sets.newLinkedHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred map implementation that preserves insertion order when used only\n * for insertions.\n */\n static Map preservesInsertionOrderOnPutsMap() {\n return Maps.newLinkedHashMap();\n }\n\n /**\n * Returns the platform preferred set implementation that preserves insertion order when used only\n * for insertions.\n */\n static Set preservesInsertionOrderOnAddsSet() {\n return Sets.newLinkedHashSet();\n<|edits_diff|>\n--- guava/src/com/google/common/collect/Platform.java\n+++ guava/src/com/google/common/collect/Platform.java\n@@ -20,6 +20,7 @@\n import java.util.Arrays;\n import java.util.Map;\n import java.util.Set;\n+import java.util.concurrent.ConcurrentHashMap;\n \n /**\n * Methods factored out so that they can be emulated differently in GWT.\n<|current_version|>\n * Copyright (C) 2008 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.common.annotations.GwtCompatible;\nimport java.lang.reflect.Array;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * Methods factored out so that they can be emulated differently in GWT.\n *\n * @author Hayward Chan\n */\n@GwtCompatible(emulated = true)\nfinal class Platform {\n private static final java.util.logging.Logger logger =\n java.util.logging.Logger.getLogger(Platform.class.getName());\n\n /** Returns the platform preferred implementation of a map based on a hash table. */\n static Map newHashMapWithExpectedSize(int expectedSize) {\n return Maps.newHashMapWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered map based on a hash\n * table.\n */\n static Map newLinkedHashMapWithExpectedSize(int expectedSize) {\n return Maps.newLinkedHashMapWithExpectedSize(expectedSize);\n }\n\n /** Returns the platform preferred implementation of a set based on a hash table. */\n static Set newHashSetWithExpectedSize(int expectedSize) {\n return Sets.newHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered set based on a hash\n * table.\n */\n static Set newLinkedHashSetWithExpectedSize(int expectedSize) {\n return Sets.newLinkedHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred map implementation that preserves insertion order when used only\n * for insertions.\n */\n static Map preservesInsertionOrderOnPutsMap() {\n return Maps.newLinkedHashMap();\n }\n\n /**\n * Returns the platform preferred set implementation that preserves insertion order when used only\n * for insertions.\n */\n static Set preservesInsertionOrderOnAddsSet() {\n return Sets.newLinkedHashSet();\n<|next_version|>\n * Copyright (C) 2008 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.common.annotations.GwtCompatible;\nimport java.lang.reflect.Array;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * Methods factored out so that they can be emulated differently in GWT.\n *\n * @author Hayward Chan\n */\n@GwtCompatible(emulated = true)\nfinal class Platform {\n private static final java.util.logging.Logger logger =\n java.util.logging.Logger.getLogger(Platform.class.getName());\n\n /** Returns the platform preferred implementation of a map based on a hash table. */\n static Map newHashMapWithExpectedSize(int expectedSize) {\n return Maps.newHashMapWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered map based on a hash\n * table.\n */\n static Map newLinkedHashMapWithExpectedSize(int expectedSize) {\n return Maps.newLinkedHashMapWithExpectedSize(expectedSize);\n }\n\n /** Returns the platform preferred implementation of a set based on a hash table. */\n static Set newHashSetWithExpectedSize(int expectedSize) {\n return Sets.newHashSetWithExpectedSize(expectedSize);\n }\n\n /** Returns the platform preferred implementation of a thread-safe hash set. */\n static Set newConcurrentHashSet() {\n return ConcurrentHashMap.newKeySet();\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered set based on a hash\n * table.\n */\n static Set newLinkedHashSetWithExpectedSize(int expectedSize) {\n return Sets.newLinkedHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred map implementation that preserves insertion order when used only\n * for insertions.\n */\n static Map preservesInsertionOrderOnPutsMap() {\n return Maps.newLinkedHashMap();\n }\n\n /**\n * Returns the platform preferred set implementation that preserves insertion order when used only\n * for insertions.\n */\n static Set preservesInsertionOrderOnAddsSet() {\n return Sets.newLinkedHashSet();\n", "current_contents": " * Copyright (C) 2008 The Guava Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage com.google.common.collect;\n\nimport com.google.common.annotations.GwtCompatible;\nimport java.lang.reflect.Array;\nimport java.util.Arrays;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.concurrent.ConcurrentHashMap;\n\n/**\n * Methods factored out so that they can be emulated differently in GWT.\n *\n * @author Hayward Chan\n */\n@GwtCompatible(emulated = true)\nfinal class Platform {\n private static final java.util.logging.Logger logger =\n java.util.logging.Logger.getLogger(Platform.class.getName());\n\n /** Returns the platform preferred implementation of a map based on a hash table. */\n static Map newHashMapWithExpectedSize(int expectedSize) {\n return Maps.newHashMapWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered map based on a hash\n * table.\n */\n static Map newLinkedHashMapWithExpectedSize(int expectedSize) {\n return Maps.newLinkedHashMapWithExpectedSize(expectedSize);\n }\n\n /** Returns the platform preferred implementation of a set based on a hash table. */\n static Set newHashSetWithExpectedSize(int expectedSize) {\n return Sets.newHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred implementation of an insertion ordered set based on a hash\n * table.\n */\n static Set newLinkedHashSetWithExpectedSize(int expectedSize) {\n return Sets.newLinkedHashSetWithExpectedSize(expectedSize);\n }\n\n /**\n * Returns the platform preferred map implementation that preserves insertion order when used only\n * for insertions.\n */\n static Map preservesInsertionOrderOnPutsMap() {\n return Maps.newLinkedHashMap();\n }\n\n /**\n * Returns the platform preferred set implementation that preserves insertion order when used only\n * for insertions.\n */\n static Set preservesInsertionOrderOnAddsSet() {\n return Sets.newLinkedHashSet();"} {"commit": "b21d5719e6a0ce6f4e2f71eec09bf55908ede062", "message": "Rename 'ConfigurableX' to 'StandardX' for Network, which better captures what these implementations represent.", "old_file": "android/guava/src/com/google/common/graph/AbstractDirectedNetworkConnections.java", "new_file": "android/guava/src/com/google/common/graph/AbstractDirectedNetworkConnections.java", "status": "M", "old_contents": " // Since the reference node is defined to be 'source' for directed graphs,\n // we can assume this edge lives in the set of outgoing edges.\n return checkNotNull(outEdgeMap.get(edge));\n }\n\n @Override\n public N removeInEdge(E edge, boolean isSelfLoop) {\n if (isSelfLoop) {\n checkNonNegative(--selfLoopCount);\n }\n N previousNode = inEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public N removeOutEdge(E edge) {\n N previousNode = outEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public void addInEdge(E edge, N node, boolean isSelfLoop) {\n if (isSelfLoop) {\n checkPositive(++selfLoopCount);\n }\n N previousNode = inEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n\n @Override\n public void addOutEdge(E edge, N node) {\n N previousNode = outEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n}\n", "new_contents": " // Since the reference node is defined to be 'source' for directed graphs,\n // we can assume this edge lives in the set of outgoing edges.\n return checkNotNull(outEdgeMap.get(edge));\n }\n\n @Override\n public N removeInEdge(E edge, boolean isSelfLoop) {\n if (isSelfLoop) {\n checkNonNegative(--selfLoopCount);\n }\n N previousNode = inEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public N removeOutEdge(E edge) {\n N previousNode = outEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public void addInEdge(E edge, N node, boolean isSelfLoop) {\n checkNotNull(edge);\n checkNotNull(node);\n\n if (isSelfLoop) {\n checkPositive(++selfLoopCount);\n }\n N previousNode = inEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n\n @Override\n public void addOutEdge(E edge, N node) {\n checkNotNull(edge);\n checkNotNull(node);\n\n N previousNode = outEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n}\n", "text": "<|original_code|>\n // Since the reference node is defined to be 'source' for directed graphs,\n // we can assume this edge lives in the set of outgoing edges.\n return checkNotNull(outEdgeMap.get(edge));\n }\n\n @Override\n public N removeInEdge(E edge, boolean isSelfLoop) {\n if (isSelfLoop) {\n checkNonNegative(--selfLoopCount);\n }\n N previousNode = inEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public N removeOutEdge(E edge) {\n N previousNode = outEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public void addInEdge(E edge, N node, boolean isSelfLoop) {\n if (isSelfLoop) {\n checkPositive(++selfLoopCount);\n }\n N previousNode = inEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n\n @Override\n public void addOutEdge(E edge, N node) {\n N previousNode = outEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n}\n\n<|edits_diff|>\n--- android/guava/src/com/google/common/graph/AbstractDirectedNetworkConnections.java\n+++ android/guava/src/com/google/common/graph/AbstractDirectedNetworkConnections.java\n@@ -20,6 +20,9 @@\n \n @Override\n public void addInEdge(E edge, N node, boolean isSelfLoop) {\n+ checkNotNull(edge);\n+ checkNotNull(node);\n+\n if (isSelfLoop) {\n checkPositive(++selfLoopCount);\n }\n<|current_version|>\n // Since the reference node is defined to be 'source' for directed graphs,\n // we can assume this edge lives in the set of outgoing edges.\n return checkNotNull(outEdgeMap.get(edge));\n }\n\n @Override\n public N removeInEdge(E edge, boolean isSelfLoop) {\n if (isSelfLoop) {\n checkNonNegative(--selfLoopCount);\n }\n N previousNode = inEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public N removeOutEdge(E edge) {\n N previousNode = outEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public void addInEdge(E edge, N node, boolean isSelfLoop) {\n checkNotNull(edge);\n checkNotNull(node);\n\n if (isSelfLoop) {\n checkPositive(++selfLoopCount);\n }\n N previousNode = inEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n\n @Override\n public void addOutEdge(E edge, N node) {\n N previousNode = outEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n}\n\n<|next_version|>\n // Since the reference node is defined to be 'source' for directed graphs,\n // we can assume this edge lives in the set of outgoing edges.\n return checkNotNull(outEdgeMap.get(edge));\n }\n\n @Override\n public N removeInEdge(E edge, boolean isSelfLoop) {\n if (isSelfLoop) {\n checkNonNegative(--selfLoopCount);\n }\n N previousNode = inEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public N removeOutEdge(E edge) {\n N previousNode = outEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public void addInEdge(E edge, N node, boolean isSelfLoop) {\n checkNotNull(edge);\n checkNotNull(node);\n\n if (isSelfLoop) {\n checkPositive(++selfLoopCount);\n }\n N previousNode = inEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n\n @Override\n public void addOutEdge(E edge, N node) {\n checkNotNull(edge);\n checkNotNull(node);\n\n N previousNode = outEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n}\n\n", "current_contents": " // Since the reference node is defined to be 'source' for directed graphs,\n // we can assume this edge lives in the set of outgoing edges.\n return checkNotNull(outEdgeMap.get(edge));\n }\n\n @Override\n public N removeInEdge(E edge, boolean isSelfLoop) {\n if (isSelfLoop) {\n checkNonNegative(--selfLoopCount);\n }\n N previousNode = inEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public N removeOutEdge(E edge) {\n N previousNode = outEdgeMap.remove(edge);\n return checkNotNull(previousNode);\n }\n\n @Override\n public void addInEdge(E edge, N node, boolean isSelfLoop) {\n checkNotNull(edge);\n checkNotNull(node);\n\n if (isSelfLoop) {\n checkPositive(++selfLoopCount);\n }\n N previousNode = inEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n\n @Override\n public void addOutEdge(E edge, N node) {\n N previousNode = outEdgeMap.put(edge, node);\n checkState(previousNode == null);\n }\n}\n"} {"commit": "8a7d36a8e5044096919a3512aa6734c95032f38c", "message": "Add support for scope IDs to InetAddresses.isInetAddress().", "old_file": "android/guava/src/com/google/common/net/InetAddresses.java", "new_file": "android/guava/src/com/google/common/net/InetAddresses.java", "status": "M", "old_contents": " /**\n * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.\n *\n * @param bytes byte array representing an IPv4 address (should be of length 4)\n * @return {@link Inet4Address} corresponding to the supplied byte array\n * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created\n */\n private static Inet4Address getInet4Address(byte[] bytes) {\n checkArgument(\n bytes.length == 4,\n \"Byte array has invalid length for an IPv4 address: %s != 4.\",\n bytes.length);\n\n // Given a 4-byte array, this cast should always succeed.\n return (Inet4Address) bytesToInetAddress(bytes);\n }\n\n /**\n * Returns the {@link InetAddress} having the given string representation.\n *\n *

This deliberately avoids all nameservice lookups (e.g. no DNS).\n *\n * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code\n * \"192.168.0.1\"} or {@code \"2001:db8::1\"}\n * @return {@link InetAddress} representing the argument\n * @throws IllegalArgumentException if the argument is not a valid IP string literal\n */\n public static InetAddress forString(String ipString) {\n byte[] addr = ipStringToBytes(ipString);\n\n // The argument was malformed, i.e. not an IP string literal.\n if (addr == null) {\n throw formatIllegalArgumentException(\"'%s' is not an IP string literal.\", ipString);\n }\n\n return bytesToInetAddress(addr);\n }\n\n /**\n * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}\n * otherwise.\n *\n * @param ipString {@code String} to evaluated as an IP string literal\n * @return {@code true} if the argument is a valid IP string literal\n */\n public static boolean isInetAddress(String ipString) {\n return ipStringToBytes(ipString) != null;\n }\n\n @NullableDecl\n private static byte[] ipStringToBytes(String ipString) {\n // Make a first pass to categorize the characters in this string.\n boolean hasColon = false;\n boolean hasDot = false;\n for (int i = 0; i < ipString.length(); i++) {\n char c = ipString.charAt(i);\n if (c == '.') {\n hasDot = true;\n } else if (c == ':') {\n if (hasDot) {\n return null; // Colons must not appear after dots.\n }\n hasColon = true;\n } else if (Character.digit(c, 16) == -1) {\n return null; // Everything else must be a decimal or hex digit.\n }\n }\n\n // Now decide which address family to parse.\n if (hasColon) {\n if (hasDot) {\n ipString = convertDottedQuadToHex(ipString);\n if (ipString == null) {\n return null;\n }\n }\n return textToNumericFormatV6(ipString);\n } else if (hasDot) {\n return textToNumericFormatV4(ipString);\n }\n return null;\n }\n\n @NullableDecl\n private static byte[] textToNumericFormatV4(String ipString) {\n byte[] bytes = new byte[IPV4_PART_COUNT];\n int i = 0;\n try {\n for (String octet : IPV4_SPLITTER.split(ipString)) {\n bytes[i++] = parseOctet(octet);\n }\n } catch (NumberFormatException ex) {\n return null;\n }\n\n return i == IPV4_PART_COUNT ? bytes : null;\n }\n\n @NullableDecl", "new_contents": " /**\n * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.\n *\n * @param bytes byte array representing an IPv4 address (should be of length 4)\n * @return {@link Inet4Address} corresponding to the supplied byte array\n * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created\n */\n private static Inet4Address getInet4Address(byte[] bytes) {\n checkArgument(\n bytes.length == 4,\n \"Byte array has invalid length for an IPv4 address: %s != 4.\",\n bytes.length);\n\n // Given a 4-byte array, this cast should always succeed.\n return (Inet4Address) bytesToInetAddress(bytes);\n }\n\n /**\n * Returns the {@link InetAddress} having the given string representation.\n *\n *

This deliberately avoids all nameservice lookups (e.g. no DNS).\n *\n *

Anything after a {@code %} in an IPv6 address is ignored (assumed to be a Scope ID).\n *\n * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code\n * \"192.168.0.1\"} or {@code \"2001:db8::1\"}\n * @return {@link InetAddress} representing the argument\n * @throws IllegalArgumentException if the argument is not a valid IP string literal\n */\n public static InetAddress forString(String ipString) {\n byte[] addr = ipStringToBytes(ipString);\n\n // The argument was malformed, i.e. not an IP string literal.\n if (addr == null) {\n throw formatIllegalArgumentException(\"'%s' is not an IP string literal.\", ipString);\n }\n\n return bytesToInetAddress(addr);\n }\n\n /**\n * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}\n * otherwise.\n *\n * @param ipString {@code String} to evaluated as an IP string literal\n * @return {@code true} if the argument is a valid IP string literal\n */\n public static boolean isInetAddress(String ipString) {\n return ipStringToBytes(ipString) != null;\n }\n\n /** Returns {@code null} if unable to parse into a {@code byte[]}. */\n @NullableDecl\n private static byte[] ipStringToBytes(String ipString) {\n // Make a first pass to categorize the characters in this string.\n boolean hasColon = false;\n boolean hasDot = false;\n int percentIndex = -1;\n for (int i = 0; i < ipString.length(); i++) {\n char c = ipString.charAt(i);\n if (c == '.') {\n hasDot = true;\n } else if (c == ':') {\n if (hasDot) {\n return null; // Colons must not appear after dots.\n }\n hasColon = true;\n } else if (c == '%') {\n percentIndex = i;\n break; // everything after a '%' is ignored (it's a Scope ID): http://superuser.com/a/99753\n } else if (Character.digit(c, 16) == -1) {\n return null; // Everything else must be a decimal or hex digit.\n }\n }\n\n // Now decide which address family to parse.\n if (hasColon) {\n if (hasDot) {\n ipString = convertDottedQuadToHex(ipString);\n if (ipString == null) {\n return null;\n }\n }\n if (percentIndex != -1) {\n ipString = ipString.substring(0, percentIndex);\n }\n return textToNumericFormatV6(ipString);\n } else if (hasDot) {\n return textToNumericFormatV4(ipString);\n }\n return null;\n }\n\n @NullableDecl\n private static byte[] textToNumericFormatV4(String ipString) {\n byte[] bytes = new byte[IPV4_PART_COUNT];\n int i = 0;\n try {\n for (String octet : IPV4_SPLITTER.split(ipString)) {\n bytes[i++] = parseOctet(octet);\n }\n } catch (NumberFormatException ex) {\n return null;\n }\n\n return i == IPV4_PART_COUNT ? bytes : null;\n }\n\n @NullableDecl", "text": "<|original_code|>\n /**\n * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.\n *\n * @param bytes byte array representing an IPv4 address (should be of length 4)\n * @return {@link Inet4Address} corresponding to the supplied byte array\n * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created\n */\n private static Inet4Address getInet4Address(byte[] bytes) {\n checkArgument(\n bytes.length == 4,\n \"Byte array has invalid length for an IPv4 address: %s != 4.\",\n bytes.length);\n\n // Given a 4-byte array, this cast should always succeed.\n return (Inet4Address) bytesToInetAddress(bytes);\n }\n\n /**\n * Returns the {@link InetAddress} having the given string representation.\n *\n *

This deliberately avoids all nameservice lookups (e.g. no DNS).\n *\n * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code\n * \"192.168.0.1\"} or {@code \"2001:db8::1\"}\n * @return {@link InetAddress} representing the argument\n * @throws IllegalArgumentException if the argument is not a valid IP string literal\n */\n public static InetAddress forString(String ipString) {\n byte[] addr = ipStringToBytes(ipString);\n\n // The argument was malformed, i.e. not an IP string literal.\n if (addr == null) {\n throw formatIllegalArgumentException(\"'%s' is not an IP string literal.\", ipString);\n }\n\n return bytesToInetAddress(addr);\n }\n\n /**\n * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}\n * otherwise.\n *\n * @param ipString {@code String} to evaluated as an IP string literal\n * @return {@code true} if the argument is a valid IP string literal\n */\n public static boolean isInetAddress(String ipString) {\n return ipStringToBytes(ipString) != null;\n }\n\n @NullableDecl\n private static byte[] ipStringToBytes(String ipString) {\n // Make a first pass to categorize the characters in this string.\n boolean hasColon = false;\n boolean hasDot = false;\n for (int i = 0; i < ipString.length(); i++) {\n char c = ipString.charAt(i);\n if (c == '.') {\n hasDot = true;\n } else if (c == ':') {\n if (hasDot) {\n return null; // Colons must not appear after dots.\n }\n hasColon = true;\n } else if (Character.digit(c, 16) == -1) {\n return null; // Everything else must be a decimal or hex digit.\n }\n }\n\n // Now decide which address family to parse.\n if (hasColon) {\n if (hasDot) {\n ipString = convertDottedQuadToHex(ipString);\n if (ipString == null) {\n return null;\n }\n }\n return textToNumericFormatV6(ipString);\n } else if (hasDot) {\n return textToNumericFormatV4(ipString);\n }\n return null;\n }\n\n @NullableDecl\n private static byte[] textToNumericFormatV4(String ipString) {\n byte[] bytes = new byte[IPV4_PART_COUNT];\n int i = 0;\n try {\n for (String octet : IPV4_SPLITTER.split(ipString)) {\n bytes[i++] = parseOctet(octet);\n }\n } catch (NumberFormatException ex) {\n return null;\n }\n\n return i == IPV4_PART_COUNT ? bytes : null;\n }\n\n @NullableDecl\n<|edits_diff|>\n--- android/guava/src/com/google/common/net/InetAddresses.java\n+++ android/guava/src/com/google/common/net/InetAddresses.java\n@@ -19,6 +19,8 @@\n * Returns the {@link InetAddress} having the given string representation.\n *\n *

This deliberately avoids all nameservice lookups (e.g. no DNS).\n+ *\n+ *

Anything after a {@code %} in an IPv6 address is ignored (assumed to be a Scope ID).\n *\n * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code\n * \"192.168.0.1\"} or {@code \"2001:db8::1\"}\n@@ -47,11 +49,13 @@\n return ipStringToBytes(ipString) != null;\n }\n \n+ /** Returns {@code null} if unable to parse into a {@code byte[]}. */\n @NullableDecl\n private static byte[] ipStringToBytes(String ipString) {\n // Make a first pass to categorize the characters in this string.\n boolean hasColon = false;\n boolean hasDot = false;\n+ int percentIndex = -1;\n for (int i = 0; i < ipString.length(); i++) {\n char c = ipString.charAt(i);\n if (c == '.') {\n@@ -61,6 +65,9 @@\n return null; // Colons must not appear after dots.\n }\n hasColon = true;\n+ } else if (c == '%') {\n+ percentIndex = i;\n+ break; // everything after a '%' is ignored (it's a Scope ID): http://superuser.com/a/99753\n } else if (Character.digit(c, 16) == -1) {\n return null; // Everything else must be a decimal or hex digit.\n }\n<|current_version|>\n /**\n * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.\n *\n * @param bytes byte array representing an IPv4 address (should be of length 4)\n * @return {@link Inet4Address} corresponding to the supplied byte array\n * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created\n */\n private static Inet4Address getInet4Address(byte[] bytes) {\n checkArgument(\n bytes.length == 4,\n \"Byte array has invalid length for an IPv4 address: %s != 4.\",\n bytes.length);\n\n // Given a 4-byte array, this cast should always succeed.\n return (Inet4Address) bytesToInetAddress(bytes);\n }\n\n /**\n * Returns the {@link InetAddress} having the given string representation.\n *\n *

This deliberately avoids all nameservice lookups (e.g. no DNS).\n *\n *

Anything after a {@code %} in an IPv6 address is ignored (assumed to be a Scope ID).\n *\n * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code\n * \"192.168.0.1\"} or {@code \"2001:db8::1\"}\n * @return {@link InetAddress} representing the argument\n * @throws IllegalArgumentException if the argument is not a valid IP string literal\n */\n public static InetAddress forString(String ipString) {\n byte[] addr = ipStringToBytes(ipString);\n\n // The argument was malformed, i.e. not an IP string literal.\n if (addr == null) {\n throw formatIllegalArgumentException(\"'%s' is not an IP string literal.\", ipString);\n }\n\n return bytesToInetAddress(addr);\n }\n\n /**\n * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}\n * otherwise.\n *\n * @param ipString {@code String} to evaluated as an IP string literal\n * @return {@code true} if the argument is a valid IP string literal\n */\n public static boolean isInetAddress(String ipString) {\n return ipStringToBytes(ipString) != null;\n }\n\n /** Returns {@code null} if unable to parse into a {@code byte[]}. */\n @NullableDecl\n private static byte[] ipStringToBytes(String ipString) {\n // Make a first pass to categorize the characters in this string.\n boolean hasColon = false;\n boolean hasDot = false;\n int percentIndex = -1;\n for (int i = 0; i < ipString.length(); i++) {\n char c = ipString.charAt(i);\n if (c == '.') {\n hasDot = true;\n } else if (c == ':') {\n if (hasDot) {\n return null; // Colons must not appear after dots.\n }\n hasColon = true;\n } else if (c == '%') {\n percentIndex = i;\n break; // everything after a '%' is ignored (it's a Scope ID): http://superuser.com/a/99753\n } else if (Character.digit(c, 16) == -1) {\n return null; // Everything else must be a decimal or hex digit.\n }\n }\n\n // Now decide which address family to parse.\n if (hasColon) {\n if (hasDot) {\n ipString = convertDottedQuadToHex(ipString);\n if (ipString == null) {\n return null;\n }\n }\n return textToNumericFormatV6(ipString);\n } else if (hasDot) {\n return textToNumericFormatV4(ipString);\n }\n return null;\n }\n\n @NullableDecl\n private static byte[] textToNumericFormatV4(String ipString) {\n byte[] bytes = new byte[IPV4_PART_COUNT];\n int i = 0;\n try {\n for (String octet : IPV4_SPLITTER.split(ipString)) {\n bytes[i++] = parseOctet(octet);\n }\n } catch (NumberFormatException ex) {\n return null;\n }\n\n return i == IPV4_PART_COUNT ? bytes : null;\n }\n\n @NullableDecl\n<|next_version|>\n /**\n * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.\n *\n * @param bytes byte array representing an IPv4 address (should be of length 4)\n * @return {@link Inet4Address} corresponding to the supplied byte array\n * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created\n */\n private static Inet4Address getInet4Address(byte[] bytes) {\n checkArgument(\n bytes.length == 4,\n \"Byte array has invalid length for an IPv4 address: %s != 4.\",\n bytes.length);\n\n // Given a 4-byte array, this cast should always succeed.\n return (Inet4Address) bytesToInetAddress(bytes);\n }\n\n /**\n * Returns the {@link InetAddress} having the given string representation.\n *\n *

This deliberately avoids all nameservice lookups (e.g. no DNS).\n *\n *

Anything after a {@code %} in an IPv6 address is ignored (assumed to be a Scope ID).\n *\n * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code\n * \"192.168.0.1\"} or {@code \"2001:db8::1\"}\n * @return {@link InetAddress} representing the argument\n * @throws IllegalArgumentException if the argument is not a valid IP string literal\n */\n public static InetAddress forString(String ipString) {\n byte[] addr = ipStringToBytes(ipString);\n\n // The argument was malformed, i.e. not an IP string literal.\n if (addr == null) {\n throw formatIllegalArgumentException(\"'%s' is not an IP string literal.\", ipString);\n }\n\n return bytesToInetAddress(addr);\n }\n\n /**\n * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}\n * otherwise.\n *\n * @param ipString {@code String} to evaluated as an IP string literal\n * @return {@code true} if the argument is a valid IP string literal\n */\n public static boolean isInetAddress(String ipString) {\n return ipStringToBytes(ipString) != null;\n }\n\n /** Returns {@code null} if unable to parse into a {@code byte[]}. */\n @NullableDecl\n private static byte[] ipStringToBytes(String ipString) {\n // Make a first pass to categorize the characters in this string.\n boolean hasColon = false;\n boolean hasDot = false;\n int percentIndex = -1;\n for (int i = 0; i < ipString.length(); i++) {\n char c = ipString.charAt(i);\n if (c == '.') {\n hasDot = true;\n } else if (c == ':') {\n if (hasDot) {\n return null; // Colons must not appear after dots.\n }\n hasColon = true;\n } else if (c == '%') {\n percentIndex = i;\n break; // everything after a '%' is ignored (it's a Scope ID): http://superuser.com/a/99753\n } else if (Character.digit(c, 16) == -1) {\n return null; // Everything else must be a decimal or hex digit.\n }\n }\n\n // Now decide which address family to parse.\n if (hasColon) {\n if (hasDot) {\n ipString = convertDottedQuadToHex(ipString);\n if (ipString == null) {\n return null;\n }\n }\n if (percentIndex != -1) {\n ipString = ipString.substring(0, percentIndex);\n }\n return textToNumericFormatV6(ipString);\n } else if (hasDot) {\n return textToNumericFormatV4(ipString);\n }\n return null;\n }\n\n @NullableDecl\n private static byte[] textToNumericFormatV4(String ipString) {\n byte[] bytes = new byte[IPV4_PART_COUNT];\n int i = 0;\n try {\n for (String octet : IPV4_SPLITTER.split(ipString)) {\n bytes[i++] = parseOctet(octet);\n }\n } catch (NumberFormatException ex) {\n return null;\n }\n\n return i == IPV4_PART_COUNT ? bytes : null;\n }\n\n @NullableDecl\n", "current_contents": " /**\n * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.\n *\n * @param bytes byte array representing an IPv4 address (should be of length 4)\n * @return {@link Inet4Address} corresponding to the supplied byte array\n * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created\n */\n private static Inet4Address getInet4Address(byte[] bytes) {\n checkArgument(\n bytes.length == 4,\n \"Byte array has invalid length for an IPv4 address: %s != 4.\",\n bytes.length);\n\n // Given a 4-byte array, this cast should always succeed.\n return (Inet4Address) bytesToInetAddress(bytes);\n }\n\n /**\n * Returns the {@link InetAddress} having the given string representation.\n *\n *

This deliberately avoids all nameservice lookups (e.g. no DNS).\n *\n *

Anything after a {@code %} in an IPv6 address is ignored (assumed to be a Scope ID).\n *\n * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code\n * \"192.168.0.1\"} or {@code \"2001:db8::1\"}\n * @return {@link InetAddress} representing the argument\n * @throws IllegalArgumentException if the argument is not a valid IP string literal\n */\n public static InetAddress forString(String ipString) {\n byte[] addr = ipStringToBytes(ipString);\n\n // The argument was malformed, i.e. not an IP string literal.\n if (addr == null) {\n throw formatIllegalArgumentException(\"'%s' is not an IP string literal.\", ipString);\n }\n\n return bytesToInetAddress(addr);\n }\n\n /**\n * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}\n * otherwise.\n *\n * @param ipString {@code String} to evaluated as an IP string literal\n * @return {@code true} if the argument is a valid IP string literal\n */\n public static boolean isInetAddress(String ipString) {\n return ipStringToBytes(ipString) != null;\n }\n\n /** Returns {@code null} if unable to parse into a {@code byte[]}. */\n @NullableDecl\n private static byte[] ipStringToBytes(String ipString) {\n // Make a first pass to categorize the characters in this string.\n boolean hasColon = false;\n boolean hasDot = false;\n int percentIndex = -1;\n for (int i = 0; i < ipString.length(); i++) {\n char c = ipString.charAt(i);\n if (c == '.') {\n hasDot = true;\n } else if (c == ':') {\n if (hasDot) {\n return null; // Colons must not appear after dots.\n }\n hasColon = true;\n } else if (c == '%') {\n percentIndex = i;\n break; // everything after a '%' is ignored (it's a Scope ID): http://superuser.com/a/99753\n } else if (Character.digit(c, 16) == -1) {\n return null; // Everything else must be a decimal or hex digit.\n }\n }\n\n // Now decide which address family to parse.\n if (hasColon) {\n if (hasDot) {\n ipString = convertDottedQuadToHex(ipString);\n if (ipString == null) {\n return null;\n }\n }\n return textToNumericFormatV6(ipString);\n } else if (hasDot) {\n return textToNumericFormatV4(ipString);\n }\n return null;\n }\n\n @NullableDecl\n private static byte[] textToNumericFormatV4(String ipString) {\n byte[] bytes = new byte[IPV4_PART_COUNT];\n int i = 0;\n try {\n for (String octet : IPV4_SPLITTER.split(ipString)) {\n bytes[i++] = parseOctet(octet);\n }\n } catch (NumberFormatException ex) {\n return null;\n }\n\n return i == IPV4_PART_COUNT ? bytes : null;\n }\n\n @NullableDecl"} {"commit": "ede5cfcb41a6a1c8f955d77d80883d5d08e843d9", "message": "Fix MpscLinkedQueue GC issues (#7799)", "old_file": "src/main/java/io/reactivex/rxjava3/internal/queue/MpscLinkedQueue.java", "new_file": "src/main/java/io/reactivex/rxjava3/internal/queue/MpscLinkedQueue.java", "status": "M", "old_contents": " *

\n * IMPLEMENTATION NOTES:
\n * Poll is allowed from a SINGLE thread.
\n * Poll reads the next node from the consumerNode and:\n *

    \n *
  1. If it is null, the queue is assumed empty (though it might not be).\n *
  2. If it is not null set it as the consumer node and return it's now evacuated value.\n *
\n * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null\n * values are not allowed to be offered this is the only node with it's value set to null at any one time.\n *\n * @see java.util.Queue#poll()\n */\n @Nullable\n @Override\n public T poll() {\n LinkedQueueNode currConsumerNode = lpConsumerNode(); // don't load twice, it's alright\n LinkedQueueNode nextNode = currConsumerNode.lvNext();\n if (nextNode != null) {\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n return nextValue;\n }\n else if (currConsumerNode != lvProducerNode()) {\n // spin, we are no longer wait free\n while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD\n // got the next node...\n\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n return nextValue;\n }\n return null;\n }\n\n @Override\n public boolean offer(T v1, T v2) {\n offer(v1);\n offer(v2);\n return true;\n }\n\n @Override\n public void clear() {\n while (poll() != null && !isEmpty()) { } // NOPMD\n }\n LinkedQueueNode lvProducerNode() {\n return producerNode.get();\n }\n LinkedQueueNode xchgProducerNode(LinkedQueueNode node) {\n return producerNode.getAndSet(node);\n }\n LinkedQueueNode lvConsumerNode() {\n return consumerNode.get();", "new_contents": " *

\n * IMPLEMENTATION NOTES:
\n * Poll is allowed from a SINGLE thread.
\n * Poll reads the next node from the consumerNode and:\n *

    \n *
  1. If it is null, the queue is assumed empty (though it might not be).\n *
  2. If it is not null set it as the consumer node and return it's now evacuated value.\n *
\n * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null\n * values are not allowed to be offered this is the only node with it's value set to null at any one time.\n *\n * @see java.util.Queue#poll()\n */\n @Nullable\n @Override\n public T poll() {\n LinkedQueueNode currConsumerNode = lpConsumerNode(); // don't load twice, it's alright\n LinkedQueueNode nextNode = currConsumerNode.lvNext();\n if (nextNode != null) {\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n // unlink previous consumer to help gc\n currConsumerNode.soNext(null);\n return nextValue;\n }\n else if (currConsumerNode != lvProducerNode()) {\n // spin, we are no longer wait free\n while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD\n // got the next node...\n\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n // unlink previous consumer to help gc\n currConsumerNode.soNext(null);\n return nextValue;\n }\n return null;\n }\n\n @Override\n public boolean offer(T v1, T v2) {\n offer(v1);\n offer(v2);\n return true;\n }\n\n @Override\n public void clear() {\n while (poll() != null && !isEmpty()) { } // NOPMD\n }\n LinkedQueueNode lvProducerNode() {\n return producerNode.get();\n }\n LinkedQueueNode xchgProducerNode(LinkedQueueNode node) {\n return producerNode.getAndSet(node);\n }\n LinkedQueueNode lvConsumerNode() {\n return consumerNode.get();", "text": "<|original_code|>\n *

\n * IMPLEMENTATION NOTES:
\n * Poll is allowed from a SINGLE thread.
\n * Poll reads the next node from the consumerNode and:\n *

    \n *
  1. If it is null, the queue is assumed empty (though it might not be).\n *
  2. If it is not null set it as the consumer node and return it's now evacuated value.\n *
\n * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null\n * values are not allowed to be offered this is the only node with it's value set to null at any one time.\n *\n * @see java.util.Queue#poll()\n */\n @Nullable\n @Override\n public T poll() {\n LinkedQueueNode currConsumerNode = lpConsumerNode(); // don't load twice, it's alright\n LinkedQueueNode nextNode = currConsumerNode.lvNext();\n if (nextNode != null) {\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n return nextValue;\n }\n else if (currConsumerNode != lvProducerNode()) {\n // spin, we are no longer wait free\n while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD\n // got the next node...\n\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n return nextValue;\n }\n return null;\n }\n\n @Override\n public boolean offer(T v1, T v2) {\n offer(v1);\n offer(v2);\n return true;\n }\n\n @Override\n public void clear() {\n while (poll() != null && !isEmpty()) { } // NOPMD\n }\n LinkedQueueNode lvProducerNode() {\n return producerNode.get();\n }\n LinkedQueueNode xchgProducerNode(LinkedQueueNode node) {\n return producerNode.getAndSet(node);\n }\n LinkedQueueNode lvConsumerNode() {\n return consumerNode.get();\n<|edits_diff|>\n--- src/main/java/io/reactivex/rxjava3/internal/queue/MpscLinkedQueue.java\n+++ src/main/java/io/reactivex/rxjava3/internal/queue/MpscLinkedQueue.java\n@@ -20,6 +20,8 @@\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n+ // unlink previous consumer to help gc\n+ currConsumerNode.soNext(null);\n return nextValue;\n }\n else if (currConsumerNode != lvProducerNode()) {\n<|current_version|>\n *

\n * IMPLEMENTATION NOTES:
\n * Poll is allowed from a SINGLE thread.
\n * Poll reads the next node from the consumerNode and:\n *

    \n *
  1. If it is null, the queue is assumed empty (though it might not be).\n *
  2. If it is not null set it as the consumer node and return it's now evacuated value.\n *
\n * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null\n * values are not allowed to be offered this is the only node with it's value set to null at any one time.\n *\n * @see java.util.Queue#poll()\n */\n @Nullable\n @Override\n public T poll() {\n LinkedQueueNode currConsumerNode = lpConsumerNode(); // don't load twice, it's alright\n LinkedQueueNode nextNode = currConsumerNode.lvNext();\n if (nextNode != null) {\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n // unlink previous consumer to help gc\n currConsumerNode.soNext(null);\n return nextValue;\n }\n else if (currConsumerNode != lvProducerNode()) {\n // spin, we are no longer wait free\n while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD\n // got the next node...\n\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n return nextValue;\n }\n return null;\n }\n\n @Override\n public boolean offer(T v1, T v2) {\n offer(v1);\n offer(v2);\n return true;\n }\n\n @Override\n public void clear() {\n while (poll() != null && !isEmpty()) { } // NOPMD\n }\n LinkedQueueNode lvProducerNode() {\n return producerNode.get();\n }\n LinkedQueueNode xchgProducerNode(LinkedQueueNode node) {\n return producerNode.getAndSet(node);\n }\n LinkedQueueNode lvConsumerNode() {\n return consumerNode.get();\n<|next_version|>\n *

\n * IMPLEMENTATION NOTES:
\n * Poll is allowed from a SINGLE thread.
\n * Poll reads the next node from the consumerNode and:\n *

    \n *
  1. If it is null, the queue is assumed empty (though it might not be).\n *
  2. If it is not null set it as the consumer node and return it's now evacuated value.\n *
\n * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null\n * values are not allowed to be offered this is the only node with it's value set to null at any one time.\n *\n * @see java.util.Queue#poll()\n */\n @Nullable\n @Override\n public T poll() {\n LinkedQueueNode currConsumerNode = lpConsumerNode(); // don't load twice, it's alright\n LinkedQueueNode nextNode = currConsumerNode.lvNext();\n if (nextNode != null) {\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n // unlink previous consumer to help gc\n currConsumerNode.soNext(null);\n return nextValue;\n }\n else if (currConsumerNode != lvProducerNode()) {\n // spin, we are no longer wait free\n while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD\n // got the next node...\n\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n // unlink previous consumer to help gc\n currConsumerNode.soNext(null);\n return nextValue;\n }\n return null;\n }\n\n @Override\n public boolean offer(T v1, T v2) {\n offer(v1);\n offer(v2);\n return true;\n }\n\n @Override\n public void clear() {\n while (poll() != null && !isEmpty()) { } // NOPMD\n }\n LinkedQueueNode lvProducerNode() {\n return producerNode.get();\n }\n LinkedQueueNode xchgProducerNode(LinkedQueueNode node) {\n return producerNode.getAndSet(node);\n }\n LinkedQueueNode lvConsumerNode() {\n return consumerNode.get();\n", "current_contents": " *

\n * IMPLEMENTATION NOTES:
\n * Poll is allowed from a SINGLE thread.
\n * Poll reads the next node from the consumerNode and:\n *

    \n *
  1. If it is null, the queue is assumed empty (though it might not be).\n *
  2. If it is not null set it as the consumer node and return it's now evacuated value.\n *
\n * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null\n * values are not allowed to be offered this is the only node with it's value set to null at any one time.\n *\n * @see java.util.Queue#poll()\n */\n @Nullable\n @Override\n public T poll() {\n LinkedQueueNode currConsumerNode = lpConsumerNode(); // don't load twice, it's alright\n LinkedQueueNode nextNode = currConsumerNode.lvNext();\n if (nextNode != null) {\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n // unlink previous consumer to help gc\n currConsumerNode.soNext(null);\n return nextValue;\n }\n else if (currConsumerNode != lvProducerNode()) {\n // spin, we are no longer wait free\n while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD\n // got the next node...\n\n // we have to null out the value because we are going to hang on to the node\n final T nextValue = nextNode.getAndNullValue();\n spConsumerNode(nextNode);\n return nextValue;\n }\n return null;\n }\n\n @Override\n public boolean offer(T v1, T v2) {\n offer(v1);\n offer(v2);\n return true;\n }\n\n @Override\n public void clear() {\n while (poll() != null && !isEmpty()) { } // NOPMD\n }\n LinkedQueueNode lvProducerNode() {\n return producerNode.get();\n }\n LinkedQueueNode xchgProducerNode(LinkedQueueNode node) {\n return producerNode.getAndSet(node);\n }\n LinkedQueueNode lvConsumerNode() {\n return consumerNode.get();"} {"commit": "597d2493f9b807580f46277f8102bd874833fba7", "message": "Suppress UndeliverableException handling in tests (#6987) (#6996)", "old_file": "src/test/java/io/reactivex/rxjava3/core/RxJavaTest.java", "new_file": "src/test/java/io/reactivex/rxjava3/core/RxJavaTest.java", "status": "M", "old_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.reactivex.rxjava3.core;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.junit.*;\nimport org.junit.rules.Timeout;\n\npublic abstract class RxJavaTest {\n @Rule\n public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);\n\n /**\n * Announce creates a log print preventing Travis CI from killing the build.\n */\n @Test\n @Ignore\n public final void announce() {\n }\n}\n", "new_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.reactivex.rxjava3.core;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.junit.*;\nimport org.junit.rules.Timeout;\n\nimport io.reactivex.rxjava3.testsupport.SuppressUndeliverableRule;\n\npublic abstract class RxJavaTest {\n @Rule\n public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);\n @Rule\n public final SuppressUndeliverableRule suppressUndeliverableRule = new SuppressUndeliverableRule();\n\n /**\n * Announce creates a log print preventing Travis CI from killing the build.\n */\n @Test\n @Ignore\n public final void announce() {\n }\n}\n", "text": "<|original_code|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.reactivex.rxjava3.core;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.junit.*;\nimport org.junit.rules.Timeout;\n\npublic abstract class RxJavaTest {\n @Rule\n public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);\n\n /**\n * Announce creates a log print preventing Travis CI from killing the build.\n */\n @Test\n @Ignore\n public final void announce() {\n }\n}\n\n<|edits_diff|>\n--- src/test/java/io/reactivex/rxjava3/core/RxJavaTest.java\n+++ src/test/java/io/reactivex/rxjava3/core/RxJavaTest.java\n@@ -20,6 +20,8 @@\n import org.junit.*;\n import org.junit.rules.Timeout;\n \n+import io.reactivex.rxjava3.testsupport.SuppressUndeliverableRule;\n+\n public abstract class RxJavaTest {\n @Rule\n public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);\n<|current_version|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.reactivex.rxjava3.core;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.junit.*;\nimport org.junit.rules.Timeout;\n\nimport io.reactivex.rxjava3.testsupport.SuppressUndeliverableRule;\n\npublic abstract class RxJavaTest {\n @Rule\n public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);\n\n /**\n * Announce creates a log print preventing Travis CI from killing the build.\n */\n @Test\n @Ignore\n public final void announce() {\n }\n}\n\n<|next_version|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.reactivex.rxjava3.core;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.junit.*;\nimport org.junit.rules.Timeout;\n\nimport io.reactivex.rxjava3.testsupport.SuppressUndeliverableRule;\n\npublic abstract class RxJavaTest {\n @Rule\n public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);\n @Rule\n public final SuppressUndeliverableRule suppressUndeliverableRule = new SuppressUndeliverableRule();\n\n /**\n * Announce creates a log print preventing Travis CI from killing the build.\n */\n @Test\n @Ignore\n public final void announce() {\n }\n}\n\n", "current_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\npackage io.reactivex.rxjava3.core;\n\nimport java.util.concurrent.TimeUnit;\n\nimport org.junit.*;\nimport org.junit.rules.Timeout;\n\nimport io.reactivex.rxjava3.testsupport.SuppressUndeliverableRule;\n\npublic abstract class RxJavaTest {\n @Rule\n public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);\n\n /**\n * Announce creates a log print preventing Travis CI from killing the build.\n */\n @Test\n @Ignore\n public final void announce() {\n }\n}\n"} {"commit": "597d2493f9b807580f46277f8102bd874833fba7", "message": "Suppress UndeliverableException handling in tests (#6987) (#6996)", "old_file": "src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableLiftTest.java", "new_file": "src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableLiftTest.java", "status": "M", "old_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.operators.observable;\n\nimport static org.junit.Assert.*;\n\nimport org.junit.Test;\n\nimport io.reactivex.rxjava3.core.*;\nimport io.reactivex.rxjava3.exceptions.TestException;\n\npublic class ObservableLiftTest extends RxJavaTest {\n\n @Test\n public void callbackCrash() {\n try {\n Observable.just(1)\n .lift(new ObservableOperator() {\n @Override\n public Observer apply(Observer o) throws Exception {\n throw new TestException();\n }\n })\n .test();\n fail(\"Should have thrown\");\n } catch (NullPointerException ex) {\n assertTrue(ex.toString(), ex.getCause() instanceof TestException);\n }\n }\n}\n", "new_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.operators.observable;\n\nimport static org.junit.Assert.*;\n\nimport org.junit.Test;\n\nimport io.reactivex.rxjava3.core.*;\nimport io.reactivex.rxjava3.exceptions.TestException;\nimport io.reactivex.rxjava3.testsupport.SuppressUndeliverable;\n\npublic class ObservableLiftTest extends RxJavaTest {\n\n @Test\n @SuppressUndeliverable\n public void callbackCrash() {\n try {\n Observable.just(1)\n .lift(new ObservableOperator() {\n @Override\n public Observer apply(Observer o) throws Exception {\n throw new TestException();\n }\n })\n .test();\n fail(\"Should have thrown\");\n } catch (NullPointerException ex) {\n assertTrue(ex.toString(), ex.getCause() instanceof TestException);\n }\n }\n}\n", "text": "<|original_code|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.operators.observable;\n\nimport static org.junit.Assert.*;\n\nimport org.junit.Test;\n\nimport io.reactivex.rxjava3.core.*;\nimport io.reactivex.rxjava3.exceptions.TestException;\n\npublic class ObservableLiftTest extends RxJavaTest {\n\n @Test\n public void callbackCrash() {\n try {\n Observable.just(1)\n .lift(new ObservableOperator() {\n @Override\n public Observer apply(Observer o) throws Exception {\n throw new TestException();\n }\n })\n .test();\n fail(\"Should have thrown\");\n } catch (NullPointerException ex) {\n assertTrue(ex.toString(), ex.getCause() instanceof TestException);\n }\n }\n}\n\n<|edits_diff|>\n--- src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableLiftTest.java\n+++ src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableLiftTest.java\n@@ -19,6 +19,7 @@\n \n import io.reactivex.rxjava3.core.*;\n import io.reactivex.rxjava3.exceptions.TestException;\n+import io.reactivex.rxjava3.testsupport.SuppressUndeliverable;\n \n public class ObservableLiftTest extends RxJavaTest {\n \n<|current_version|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.operators.observable;\n\nimport static org.junit.Assert.*;\n\nimport org.junit.Test;\n\nimport io.reactivex.rxjava3.core.*;\nimport io.reactivex.rxjava3.exceptions.TestException;\nimport io.reactivex.rxjava3.testsupport.SuppressUndeliverable;\n\npublic class ObservableLiftTest extends RxJavaTest {\n\n @Test\n public void callbackCrash() {\n try {\n Observable.just(1)\n .lift(new ObservableOperator() {\n @Override\n public Observer apply(Observer o) throws Exception {\n throw new TestException();\n }\n })\n .test();\n fail(\"Should have thrown\");\n } catch (NullPointerException ex) {\n assertTrue(ex.toString(), ex.getCause() instanceof TestException);\n }\n }\n}\n\n<|next_version|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.operators.observable;\n\nimport static org.junit.Assert.*;\n\nimport org.junit.Test;\n\nimport io.reactivex.rxjava3.core.*;\nimport io.reactivex.rxjava3.exceptions.TestException;\nimport io.reactivex.rxjava3.testsupport.SuppressUndeliverable;\n\npublic class ObservableLiftTest extends RxJavaTest {\n\n @Test\n @SuppressUndeliverable\n public void callbackCrash() {\n try {\n Observable.just(1)\n .lift(new ObservableOperator() {\n @Override\n public Observer apply(Observer o) throws Exception {\n throw new TestException();\n }\n })\n .test();\n fail(\"Should have thrown\");\n } catch (NullPointerException ex) {\n assertTrue(ex.toString(), ex.getCause() instanceof TestException);\n }\n }\n}\n\n", "current_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.operators.observable;\n\nimport static org.junit.Assert.*;\n\nimport org.junit.Test;\n\nimport io.reactivex.rxjava3.core.*;\nimport io.reactivex.rxjava3.exceptions.TestException;\nimport io.reactivex.rxjava3.testsupport.SuppressUndeliverable;\n\npublic class ObservableLiftTest extends RxJavaTest {\n\n @Test\n public void callbackCrash() {\n try {\n Observable.just(1)\n .lift(new ObservableOperator() {\n @Override\n public Observer apply(Observer o) throws Exception {\n throw new TestException();\n }\n })\n .test();\n fail(\"Should have thrown\");\n } catch (NullPointerException ex) {\n assertTrue(ex.toString(), ex.getCause() instanceof TestException);\n }\n }\n}\n"} {"commit": "a97d871ee7161fc9f4684d95cae3e94340cd0ccf", "message": "3.x: Add missing throwIfFatal calls (#6801)", "old_file": "src/main/java/io/reactivex/rxjava3/internal/schedulers/InstantPeriodicTask.java", "new_file": "src/main/java/io/reactivex/rxjava3/internal/schedulers/InstantPeriodicTask.java", "status": "M", "old_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.schedulers;\n\nimport java.util.concurrent.*;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.internal.functions.Functions;\nimport io.reactivex.rxjava3.plugins.RxJavaPlugins;\n\n/**\n * Wrapper for a regular task that gets immediately rescheduled when the task completed.\n */\nfinal class InstantPeriodicTask implements Callable, Disposable {\n\n final Runnable task;\n\n final AtomicReference> rest;\n\n final AtomicReference> first;\n\n final ExecutorService executor;\n\n Thread runner;\n\n static final FutureTask CANCELLED = new FutureTask(Functions.EMPTY_RUNNABLE, null);\n\n InstantPeriodicTask(Runnable task, ExecutorService executor) {\n super();\n this.task = task;\n this.first = new AtomicReference>();\n this.rest = new AtomicReference>();\n this.executor = executor;\n }\n\n @Override\n public Void call() throws Exception {\n runner = Thread.currentThread();\n try {\n task.run();\n setRest(executor.submit(this));\n runner = null;\n } catch (Throwable ex) {\n runner = null;\n RxJavaPlugins.onError(ex);\n }\n return null;\n }\n\n @Override\n public void dispose() {\n Future current = first.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n current = rest.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n }\n\n @Override\n public boolean isDisposed() {\n return first.get() == CANCELLED;\n }\n\n void setFirst(Future f) {", "new_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.schedulers;\n\nimport java.util.concurrent.*;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.exceptions.Exceptions;\nimport io.reactivex.rxjava3.internal.functions.Functions;\nimport io.reactivex.rxjava3.plugins.RxJavaPlugins;\n\n/**\n * Wrapper for a regular task that gets immediately rescheduled when the task completed.\n */\nfinal class InstantPeriodicTask implements Callable, Disposable {\n\n final Runnable task;\n\n final AtomicReference> rest;\n\n final AtomicReference> first;\n\n final ExecutorService executor;\n\n Thread runner;\n\n static final FutureTask CANCELLED = new FutureTask(Functions.EMPTY_RUNNABLE, null);\n\n InstantPeriodicTask(Runnable task, ExecutorService executor) {\n super();\n this.task = task;\n this.first = new AtomicReference>();\n this.rest = new AtomicReference>();\n this.executor = executor;\n }\n\n @Override\n public Void call() throws Exception {\n runner = Thread.currentThread();\n try {\n task.run();\n setRest(executor.submit(this));\n runner = null;\n } catch (Throwable ex) {\n Exceptions.throwIfFatal(ex);\n runner = null;\n RxJavaPlugins.onError(ex);\n }\n return null;\n }\n\n @Override\n public void dispose() {\n Future current = first.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n current = rest.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n }\n\n @Override\n public boolean isDisposed() {\n return first.get() == CANCELLED;\n }\n\n void setFirst(Future f) {", "text": "<|original_code|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.schedulers;\n\nimport java.util.concurrent.*;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.internal.functions.Functions;\nimport io.reactivex.rxjava3.plugins.RxJavaPlugins;\n\n/**\n * Wrapper for a regular task that gets immediately rescheduled when the task completed.\n */\nfinal class InstantPeriodicTask implements Callable, Disposable {\n\n final Runnable task;\n\n final AtomicReference> rest;\n\n final AtomicReference> first;\n\n final ExecutorService executor;\n\n Thread runner;\n\n static final FutureTask CANCELLED = new FutureTask(Functions.EMPTY_RUNNABLE, null);\n\n InstantPeriodicTask(Runnable task, ExecutorService executor) {\n super();\n this.task = task;\n this.first = new AtomicReference>();\n this.rest = new AtomicReference>();\n this.executor = executor;\n }\n\n @Override\n public Void call() throws Exception {\n runner = Thread.currentThread();\n try {\n task.run();\n setRest(executor.submit(this));\n runner = null;\n } catch (Throwable ex) {\n runner = null;\n RxJavaPlugins.onError(ex);\n }\n return null;\n }\n\n @Override\n public void dispose() {\n Future current = first.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n current = rest.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n }\n\n @Override\n public boolean isDisposed() {\n return first.get() == CANCELLED;\n }\n\n void setFirst(Future f) {\n<|edits_diff|>\n--- src/main/java/io/reactivex/rxjava3/internal/schedulers/InstantPeriodicTask.java\n+++ src/main/java/io/reactivex/rxjava3/internal/schedulers/InstantPeriodicTask.java\n@@ -20,6 +20,7 @@\n import java.util.concurrent.atomic.AtomicReference;\n \n import io.reactivex.rxjava3.disposables.Disposable;\n+import io.reactivex.rxjava3.exceptions.Exceptions;\n import io.reactivex.rxjava3.internal.functions.Functions;\n import io.reactivex.rxjava3.plugins.RxJavaPlugins;\n \n<|current_version|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.schedulers;\n\nimport java.util.concurrent.*;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.exceptions.Exceptions;\nimport io.reactivex.rxjava3.internal.functions.Functions;\nimport io.reactivex.rxjava3.plugins.RxJavaPlugins;\n\n/**\n * Wrapper for a regular task that gets immediately rescheduled when the task completed.\n */\nfinal class InstantPeriodicTask implements Callable, Disposable {\n\n final Runnable task;\n\n final AtomicReference> rest;\n\n final AtomicReference> first;\n\n final ExecutorService executor;\n\n Thread runner;\n\n static final FutureTask CANCELLED = new FutureTask(Functions.EMPTY_RUNNABLE, null);\n\n InstantPeriodicTask(Runnable task, ExecutorService executor) {\n super();\n this.task = task;\n this.first = new AtomicReference>();\n this.rest = new AtomicReference>();\n this.executor = executor;\n }\n\n @Override\n public Void call() throws Exception {\n runner = Thread.currentThread();\n try {\n task.run();\n setRest(executor.submit(this));\n runner = null;\n } catch (Throwable ex) {\n runner = null;\n RxJavaPlugins.onError(ex);\n }\n return null;\n }\n\n @Override\n public void dispose() {\n Future current = first.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n current = rest.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n }\n\n @Override\n public boolean isDisposed() {\n return first.get() == CANCELLED;\n }\n\n void setFirst(Future f) {\n<|next_version|>\n/**\n * Copyright (c) 2016-present, RxJava Contributors.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.schedulers;\n\nimport java.util.concurrent.*;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.exceptions.Exceptions;\nimport io.reactivex.rxjava3.internal.functions.Functions;\nimport io.reactivex.rxjava3.plugins.RxJavaPlugins;\n\n/**\n * Wrapper for a regular task that gets immediately rescheduled when the task completed.\n */\nfinal class InstantPeriodicTask implements Callable, Disposable {\n\n final Runnable task;\n\n final AtomicReference> rest;\n\n final AtomicReference> first;\n\n final ExecutorService executor;\n\n Thread runner;\n\n static final FutureTask CANCELLED = new FutureTask(Functions.EMPTY_RUNNABLE, null);\n\n InstantPeriodicTask(Runnable task, ExecutorService executor) {\n super();\n this.task = task;\n this.first = new AtomicReference>();\n this.rest = new AtomicReference>();\n this.executor = executor;\n }\n\n @Override\n public Void call() throws Exception {\n runner = Thread.currentThread();\n try {\n task.run();\n setRest(executor.submit(this));\n runner = null;\n } catch (Throwable ex) {\n Exceptions.throwIfFatal(ex);\n runner = null;\n RxJavaPlugins.onError(ex);\n }\n return null;\n }\n\n @Override\n public void dispose() {\n Future current = first.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n current = rest.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n }\n\n @Override\n public boolean isDisposed() {\n return first.get() == CANCELLED;\n }\n\n void setFirst(Future f) {\n", "current_contents": "/**\n * Copyright (c) 2016-present, RxJava Contributors.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage io.reactivex.rxjava3.internal.schedulers;\n\nimport java.util.concurrent.*;\nimport java.util.concurrent.atomic.AtomicReference;\n\nimport io.reactivex.rxjava3.disposables.Disposable;\nimport io.reactivex.rxjava3.exceptions.Exceptions;\nimport io.reactivex.rxjava3.internal.functions.Functions;\nimport io.reactivex.rxjava3.plugins.RxJavaPlugins;\n\n/**\n * Wrapper for a regular task that gets immediately rescheduled when the task completed.\n */\nfinal class InstantPeriodicTask implements Callable, Disposable {\n\n final Runnable task;\n\n final AtomicReference> rest;\n\n final AtomicReference> first;\n\n final ExecutorService executor;\n\n Thread runner;\n\n static final FutureTask CANCELLED = new FutureTask(Functions.EMPTY_RUNNABLE, null);\n\n InstantPeriodicTask(Runnable task, ExecutorService executor) {\n super();\n this.task = task;\n this.first = new AtomicReference>();\n this.rest = new AtomicReference>();\n this.executor = executor;\n }\n\n @Override\n public Void call() throws Exception {\n runner = Thread.currentThread();\n try {\n task.run();\n setRest(executor.submit(this));\n runner = null;\n } catch (Throwable ex) {\n runner = null;\n RxJavaPlugins.onError(ex);\n }\n return null;\n }\n\n @Override\n public void dispose() {\n Future current = first.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n current = rest.getAndSet(CANCELLED);\n if (current != null && current != CANCELLED) {\n current.cancel(runner != Thread.currentThread());\n }\n }\n\n @Override\n public boolean isDisposed() {\n return first.get() == CANCELLED;\n }\n\n void setFirst(Future f) {"} {"commit": "ab6c4b3dfdb700e64ea00ac90dbdf47d3f653b82", "message": "3.x: Fix truncation bugs in replay() and ReplaySubject/Processor (#6582)", "old_file": "src/main/java/io/reactivex/processors/ReplayProcessor.java", "new_file": "src/main/java/io/reactivex/processors/ReplayProcessor.java", "status": "M", "old_contents": "\n SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {\n this.maxSize = ObjectHelper.verifyPositive(maxSize, \"maxSize\");\n this.maxAge = ObjectHelper.verifyPositive(maxAge, \"maxAge\");\n this.unit = ObjectHelper.requireNonNull(unit, \"unit is null\");\n this.scheduler = ObjectHelper.requireNonNull(scheduler, \"scheduler is null\");\n TimedNode h = new TimedNode(null, 0L);\n this.tail = h;\n this.head = h;\n }\n\n void trim() {\n if (size > maxSize) {\n size--;\n TimedNode h = head;\n head = h.get();\n }\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n TimedNode next = h.get();\n if (next == null) {\n head = h;\n break;\n }\n\n if (next.time > limit) {\n head = h;\n break;\n }\n\n h = next;\n }\n\n }\n\n void trimFinal() {\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n TimedNode next = h.get();\n if (next == null) {\n if (h.value != null) {\n head = new TimedNode(null, 0L);\n } else {\n head = h;\n }\n break;\n }\n\n if (next.time > limit) {\n if (h.value != null) {\n TimedNode n = new TimedNode(null, 0L);\n n.lazySet(h.get());", "new_contents": "\n SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {\n this.maxSize = ObjectHelper.verifyPositive(maxSize, \"maxSize\");\n this.maxAge = ObjectHelper.verifyPositive(maxAge, \"maxAge\");\n this.unit = ObjectHelper.requireNonNull(unit, \"unit is null\");\n this.scheduler = ObjectHelper.requireNonNull(scheduler, \"scheduler is null\");\n TimedNode h = new TimedNode(null, 0L);\n this.tail = h;\n this.head = h;\n }\n\n void trim() {\n if (size > maxSize) {\n size--;\n TimedNode h = head;\n head = h.get();\n }\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n if (size <= 1) {\n head = h;\n break;\n }\n TimedNode next = h.get();\n if (next == null) {\n head = h;\n break;\n }\n\n if (next.time > limit) {\n head = h;\n break;\n }\n\n h = next;\n size--;\n }\n\n }\n\n void trimFinal() {\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n TimedNode next = h.get();\n if (next == null) {\n if (h.value != null) {\n head = new TimedNode(null, 0L);\n } else {\n head = h;\n }\n break;\n }\n\n if (next.time > limit) {\n if (h.value != null) {\n TimedNode n = new TimedNode(null, 0L);\n n.lazySet(h.get());", "text": "<|original_code|>\n\n SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {\n this.maxSize = ObjectHelper.verifyPositive(maxSize, \"maxSize\");\n this.maxAge = ObjectHelper.verifyPositive(maxAge, \"maxAge\");\n this.unit = ObjectHelper.requireNonNull(unit, \"unit is null\");\n this.scheduler = ObjectHelper.requireNonNull(scheduler, \"scheduler is null\");\n TimedNode h = new TimedNode(null, 0L);\n this.tail = h;\n this.head = h;\n }\n\n void trim() {\n if (size > maxSize) {\n size--;\n TimedNode h = head;\n head = h.get();\n }\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n TimedNode next = h.get();\n if (next == null) {\n head = h;\n break;\n }\n\n if (next.time > limit) {\n head = h;\n break;\n }\n\n h = next;\n }\n\n }\n\n void trimFinal() {\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n TimedNode next = h.get();\n if (next == null) {\n if (h.value != null) {\n head = new TimedNode(null, 0L);\n } else {\n head = h;\n }\n break;\n }\n\n if (next.time > limit) {\n if (h.value != null) {\n TimedNode n = new TimedNode(null, 0L);\n n.lazySet(h.get());\n<|edits_diff|>\n--- src/main/java/io/reactivex/processors/ReplayProcessor.java\n+++ src/main/java/io/reactivex/processors/ReplayProcessor.java\n@@ -20,6 +20,10 @@\n TimedNode h = head;\n \n for (;;) {\n+ if (size <= 1) {\n+ head = h;\n+ break;\n+ }\n TimedNode next = h.get();\n if (next == null) {\n head = h;\n<|current_version|>\n\n SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {\n this.maxSize = ObjectHelper.verifyPositive(maxSize, \"maxSize\");\n this.maxAge = ObjectHelper.verifyPositive(maxAge, \"maxAge\");\n this.unit = ObjectHelper.requireNonNull(unit, \"unit is null\");\n this.scheduler = ObjectHelper.requireNonNull(scheduler, \"scheduler is null\");\n TimedNode h = new TimedNode(null, 0L);\n this.tail = h;\n this.head = h;\n }\n\n void trim() {\n if (size > maxSize) {\n size--;\n TimedNode h = head;\n head = h.get();\n }\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n if (size <= 1) {\n head = h;\n break;\n }\n TimedNode next = h.get();\n if (next == null) {\n head = h;\n break;\n }\n\n if (next.time > limit) {\n head = h;\n break;\n }\n\n h = next;\n }\n\n }\n\n void trimFinal() {\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n TimedNode next = h.get();\n if (next == null) {\n if (h.value != null) {\n head = new TimedNode(null, 0L);\n } else {\n head = h;\n }\n break;\n }\n\n if (next.time > limit) {\n if (h.value != null) {\n TimedNode n = new TimedNode(null, 0L);\n n.lazySet(h.get());\n<|next_version|>\n\n SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {\n this.maxSize = ObjectHelper.verifyPositive(maxSize, \"maxSize\");\n this.maxAge = ObjectHelper.verifyPositive(maxAge, \"maxAge\");\n this.unit = ObjectHelper.requireNonNull(unit, \"unit is null\");\n this.scheduler = ObjectHelper.requireNonNull(scheduler, \"scheduler is null\");\n TimedNode h = new TimedNode(null, 0L);\n this.tail = h;\n this.head = h;\n }\n\n void trim() {\n if (size > maxSize) {\n size--;\n TimedNode h = head;\n head = h.get();\n }\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n if (size <= 1) {\n head = h;\n break;\n }\n TimedNode next = h.get();\n if (next == null) {\n head = h;\n break;\n }\n\n if (next.time > limit) {\n head = h;\n break;\n }\n\n h = next;\n size--;\n }\n\n }\n\n void trimFinal() {\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n TimedNode next = h.get();\n if (next == null) {\n if (h.value != null) {\n head = new TimedNode(null, 0L);\n } else {\n head = h;\n }\n break;\n }\n\n if (next.time > limit) {\n if (h.value != null) {\n TimedNode n = new TimedNode(null, 0L);\n n.lazySet(h.get());\n", "current_contents": "\n SizeAndTimeBoundReplayBuffer(int maxSize, long maxAge, TimeUnit unit, Scheduler scheduler) {\n this.maxSize = ObjectHelper.verifyPositive(maxSize, \"maxSize\");\n this.maxAge = ObjectHelper.verifyPositive(maxAge, \"maxAge\");\n this.unit = ObjectHelper.requireNonNull(unit, \"unit is null\");\n this.scheduler = ObjectHelper.requireNonNull(scheduler, \"scheduler is null\");\n TimedNode h = new TimedNode(null, 0L);\n this.tail = h;\n this.head = h;\n }\n\n void trim() {\n if (size > maxSize) {\n size--;\n TimedNode h = head;\n head = h.get();\n }\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n if (size <= 1) {\n head = h;\n break;\n }\n TimedNode next = h.get();\n if (next == null) {\n head = h;\n break;\n }\n\n if (next.time > limit) {\n head = h;\n break;\n }\n\n h = next;\n }\n\n }\n\n void trimFinal() {\n long limit = scheduler.now(unit) - maxAge;\n\n TimedNode h = head;\n\n for (;;) {\n TimedNode next = h.get();\n if (next == null) {\n if (h.value != null) {\n head = new TimedNode(null, 0L);\n } else {\n head = h;\n }\n break;\n }\n\n if (next.time > limit) {\n if (h.value != null) {\n TimedNode n = new TimedNode(null, 0L);\n n.lazySet(h.get());"} {"commit": "2abeadbdd4b1ac904f2eb289f7d03b8608bad618", "message": "2.x: fix Flowable.flatMapMaybe/Single maxConcurrency not requesting more (#5287)", "old_file": "src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybe.java", "new_file": "src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybe.java", "status": "M", "old_contents": " drainLoop();\n }\n\n SpscLinkedArrayQueue getOrCreateQueue() {\n for (;;) {\n SpscLinkedArrayQueue current = queue.get();\n if (current != null) {\n return current;\n }\n current = new SpscLinkedArrayQueue(Flowable.bufferSize());\n if (queue.compareAndSet(null, current)) {\n return current;\n }\n }\n }\n\n void innerError(InnerObserver inner, Throwable e) {\n set.delete(inner);\n if (errors.addThrowable(e)) {\n if (!delayErrors) {\n s.cancel();\n set.dispose();\n }\n active.decrementAndGet();\n drain();\n } else {\n RxJavaPlugins.onError(e);\n }\n }\n\n void innerComplete(InnerObserver inner) {\n set.delete(inner);\n\n if (get() == 0 && compareAndSet(0, 1)) {\n boolean d = active.decrementAndGet() == 0;\n SpscLinkedArrayQueue q = queue.get();\n\n if (d && (q == null || q.isEmpty())) {\n Throwable ex = errors.terminate();\n if (ex != null) {\n actual.onError(ex);\n } else {\n actual.onComplete();\n }\n return;\n }\n if (decrementAndGet() == 0) {\n return;\n }\n drainLoop();\n } else {\n active.decrementAndGet();\n drain();\n }\n }\n\n void drain() {\n if (getAndIncrement() == 0) {\n drainLoop();\n }\n }\n\n void clear() {\n SpscLinkedArrayQueue q = queue.get();\n if (q != null) {\n q.clear();\n }\n }\n\n void drainLoop() {\n int missed = 1;\n Subscriber a = actual;\n AtomicInteger n = active;\n AtomicReference> qr = queue;\n\n for (;;) {", "new_contents": " drainLoop();\n }\n\n SpscLinkedArrayQueue getOrCreateQueue() {\n for (;;) {\n SpscLinkedArrayQueue current = queue.get();\n if (current != null) {\n return current;\n }\n current = new SpscLinkedArrayQueue(Flowable.bufferSize());\n if (queue.compareAndSet(null, current)) {\n return current;\n }\n }\n }\n\n void innerError(InnerObserver inner, Throwable e) {\n set.delete(inner);\n if (errors.addThrowable(e)) {\n if (!delayErrors) {\n s.cancel();\n set.dispose();\n } else {\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n }\n active.decrementAndGet();\n drain();\n } else {\n RxJavaPlugins.onError(e);\n }\n }\n\n void innerComplete(InnerObserver inner) {\n set.delete(inner);\n\n if (get() == 0 && compareAndSet(0, 1)) {\n boolean d = active.decrementAndGet() == 0;\n SpscLinkedArrayQueue q = queue.get();\n\n if (d && (q == null || q.isEmpty())) {\n Throwable ex = errors.terminate();\n if (ex != null) {\n actual.onError(ex);\n } else {\n actual.onComplete();\n }\n return;\n }\n\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n if (decrementAndGet() == 0) {\n return;\n }\n drainLoop();\n } else {\n active.decrementAndGet();\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n drain();\n }\n }\n\n void drain() {\n if (getAndIncrement() == 0) {\n drainLoop();\n }\n }\n\n void clear() {\n SpscLinkedArrayQueue q = queue.get();\n if (q != null) {\n q.clear();\n }\n }\n\n void drainLoop() {\n int missed = 1;\n Subscriber a = actual;\n AtomicInteger n = active;\n AtomicReference> qr = queue;\n\n for (;;) {", "text": "<|original_code|>\n drainLoop();\n }\n\n SpscLinkedArrayQueue getOrCreateQueue() {\n for (;;) {\n SpscLinkedArrayQueue current = queue.get();\n if (current != null) {\n return current;\n }\n current = new SpscLinkedArrayQueue(Flowable.bufferSize());\n if (queue.compareAndSet(null, current)) {\n return current;\n }\n }\n }\n\n void innerError(InnerObserver inner, Throwable e) {\n set.delete(inner);\n if (errors.addThrowable(e)) {\n if (!delayErrors) {\n s.cancel();\n set.dispose();\n }\n active.decrementAndGet();\n drain();\n } else {\n RxJavaPlugins.onError(e);\n }\n }\n\n void innerComplete(InnerObserver inner) {\n set.delete(inner);\n\n if (get() == 0 && compareAndSet(0, 1)) {\n boolean d = active.decrementAndGet() == 0;\n SpscLinkedArrayQueue q = queue.get();\n\n if (d && (q == null || q.isEmpty())) {\n Throwable ex = errors.terminate();\n if (ex != null) {\n actual.onError(ex);\n } else {\n actual.onComplete();\n }\n return;\n }\n if (decrementAndGet() == 0) {\n return;\n }\n drainLoop();\n } else {\n active.decrementAndGet();\n drain();\n }\n }\n\n void drain() {\n if (getAndIncrement() == 0) {\n drainLoop();\n }\n }\n\n void clear() {\n SpscLinkedArrayQueue q = queue.get();\n if (q != null) {\n q.clear();\n }\n }\n\n void drainLoop() {\n int missed = 1;\n Subscriber a = actual;\n AtomicInteger n = active;\n AtomicReference> qr = queue;\n\n for (;;) {\n<|edits_diff|>\n--- src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybe.java\n+++ src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMapMaybe.java\n@@ -20,6 +20,10 @@\n if (!delayErrors) {\n s.cancel();\n set.dispose();\n+ } else {\n+ if (maxConcurrency != Integer.MAX_VALUE) {\n+ s.request(1);\n+ }\n }\n active.decrementAndGet();\n drain();\n@@ -43,6 +47,10 @@\n actual.onComplete();\n }\n return;\n+ }\n+\n+ if (maxConcurrency != Integer.MAX_VALUE) {\n+ s.request(1);\n }\n if (decrementAndGet() == 0) {\n return;\n<|current_version|>\n drainLoop();\n }\n\n SpscLinkedArrayQueue getOrCreateQueue() {\n for (;;) {\n SpscLinkedArrayQueue current = queue.get();\n if (current != null) {\n return current;\n }\n current = new SpscLinkedArrayQueue(Flowable.bufferSize());\n if (queue.compareAndSet(null, current)) {\n return current;\n }\n }\n }\n\n void innerError(InnerObserver inner, Throwable e) {\n set.delete(inner);\n if (errors.addThrowable(e)) {\n if (!delayErrors) {\n s.cancel();\n set.dispose();\n } else {\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n }\n active.decrementAndGet();\n drain();\n } else {\n RxJavaPlugins.onError(e);\n }\n }\n\n void innerComplete(InnerObserver inner) {\n set.delete(inner);\n\n if (get() == 0 && compareAndSet(0, 1)) {\n boolean d = active.decrementAndGet() == 0;\n SpscLinkedArrayQueue q = queue.get();\n\n if (d && (q == null || q.isEmpty())) {\n Throwable ex = errors.terminate();\n if (ex != null) {\n actual.onError(ex);\n } else {\n actual.onComplete();\n }\n return;\n }\n\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n if (decrementAndGet() == 0) {\n return;\n }\n drainLoop();\n } else {\n active.decrementAndGet();\n drain();\n }\n }\n\n void drain() {\n if (getAndIncrement() == 0) {\n drainLoop();\n }\n }\n\n void clear() {\n SpscLinkedArrayQueue q = queue.get();\n if (q != null) {\n q.clear();\n }\n }\n\n void drainLoop() {\n int missed = 1;\n Subscriber a = actual;\n AtomicInteger n = active;\n AtomicReference> qr = queue;\n\n for (;;) {\n<|next_version|>\n drainLoop();\n }\n\n SpscLinkedArrayQueue getOrCreateQueue() {\n for (;;) {\n SpscLinkedArrayQueue current = queue.get();\n if (current != null) {\n return current;\n }\n current = new SpscLinkedArrayQueue(Flowable.bufferSize());\n if (queue.compareAndSet(null, current)) {\n return current;\n }\n }\n }\n\n void innerError(InnerObserver inner, Throwable e) {\n set.delete(inner);\n if (errors.addThrowable(e)) {\n if (!delayErrors) {\n s.cancel();\n set.dispose();\n } else {\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n }\n active.decrementAndGet();\n drain();\n } else {\n RxJavaPlugins.onError(e);\n }\n }\n\n void innerComplete(InnerObserver inner) {\n set.delete(inner);\n\n if (get() == 0 && compareAndSet(0, 1)) {\n boolean d = active.decrementAndGet() == 0;\n SpscLinkedArrayQueue q = queue.get();\n\n if (d && (q == null || q.isEmpty())) {\n Throwable ex = errors.terminate();\n if (ex != null) {\n actual.onError(ex);\n } else {\n actual.onComplete();\n }\n return;\n }\n\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n if (decrementAndGet() == 0) {\n return;\n }\n drainLoop();\n } else {\n active.decrementAndGet();\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n drain();\n }\n }\n\n void drain() {\n if (getAndIncrement() == 0) {\n drainLoop();\n }\n }\n\n void clear() {\n SpscLinkedArrayQueue q = queue.get();\n if (q != null) {\n q.clear();\n }\n }\n\n void drainLoop() {\n int missed = 1;\n Subscriber a = actual;\n AtomicInteger n = active;\n AtomicReference> qr = queue;\n\n for (;;) {\n", "current_contents": " drainLoop();\n }\n\n SpscLinkedArrayQueue getOrCreateQueue() {\n for (;;) {\n SpscLinkedArrayQueue current = queue.get();\n if (current != null) {\n return current;\n }\n current = new SpscLinkedArrayQueue(Flowable.bufferSize());\n if (queue.compareAndSet(null, current)) {\n return current;\n }\n }\n }\n\n void innerError(InnerObserver inner, Throwable e) {\n set.delete(inner);\n if (errors.addThrowable(e)) {\n if (!delayErrors) {\n s.cancel();\n set.dispose();\n } else {\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n }\n active.decrementAndGet();\n drain();\n } else {\n RxJavaPlugins.onError(e);\n }\n }\n\n void innerComplete(InnerObserver inner) {\n set.delete(inner);\n\n if (get() == 0 && compareAndSet(0, 1)) {\n boolean d = active.decrementAndGet() == 0;\n SpscLinkedArrayQueue q = queue.get();\n\n if (d && (q == null || q.isEmpty())) {\n Throwable ex = errors.terminate();\n if (ex != null) {\n actual.onError(ex);\n } else {\n actual.onComplete();\n }\n return;\n }\n\n if (maxConcurrency != Integer.MAX_VALUE) {\n s.request(1);\n }\n if (decrementAndGet() == 0) {\n return;\n }\n drainLoop();\n } else {\n active.decrementAndGet();\n drain();\n }\n }\n\n void drain() {\n if (getAndIncrement() == 0) {\n drainLoop();\n }\n }\n\n void clear() {\n SpscLinkedArrayQueue q = queue.get();\n if (q != null) {\n q.clear();\n }\n }\n\n void drainLoop() {\n int missed = 1;\n Subscriber a = actual;\n AtomicInteger n = active;\n AtomicReference> qr = queue;\n\n for (;;) {"} {"commit": "75e9bfa3bd1e0c084d20ed671d33d05d5ff0f8ab", "message": "FlowableScanSeed - prevent post-terminal events (#4899)", "old_file": "src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java", "new_file": "src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java", "status": "M", "old_contents": " this.seedSupplier = seedSupplier;\n }\n\n @Override\n protected void subscribeActual(Subscriber s) {\n R r;\n\n try {\n r = ObjectHelper.requireNonNull(seedSupplier.call(), \"The seed supplied is null\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n EmptySubscription.error(e, s);\n return;\n }\n\n source.subscribe(new ScanSeedSubscriber(s, accumulator, r));\n }\n\n static final class ScanSeedSubscriber extends SinglePostCompleteSubscriber {\n private static final long serialVersionUID = -1776795561228106469L;\n\n final BiFunction accumulator;\n\n ScanSeedSubscriber(Subscriber actual, BiFunction accumulator, R value) {\n super(actual);\n this.accumulator = accumulator;\n this.value = value;\n }\n\n @Override\n public void onNext(T t) {\n R v = value;\n\n R u;\n\n try {\n u = ObjectHelper.requireNonNull(accumulator.apply(v, t), \"The accumulator returned a null value\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n s.cancel();\n onError(e);\n return;\n }\n\n value = u;\n produced++;\n actual.onNext(v);\n }\n\n @Override\n public void onError(Throwable t) {\n value = null;\n actual.onError(t);\n }\n\n @Override\n public void onComplete() {\n complete(value);\n }\n }\n}\n", "new_contents": " this.seedSupplier = seedSupplier;\n }\n\n @Override\n protected void subscribeActual(Subscriber s) {\n R r;\n\n try {\n r = ObjectHelper.requireNonNull(seedSupplier.call(), \"The seed supplied is null\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n EmptySubscription.error(e, s);\n return;\n }\n\n source.subscribe(new ScanSeedSubscriber(s, accumulator, r));\n }\n\n static final class ScanSeedSubscriber extends SinglePostCompleteSubscriber {\n private static final long serialVersionUID = -1776795561228106469L;\n\n final BiFunction accumulator;\n \n boolean done;\n\n ScanSeedSubscriber(Subscriber actual, BiFunction accumulator, R value) {\n super(actual);\n this.accumulator = accumulator;\n this.value = value;\n }\n\n @Override\n public void onNext(T t) {\n if (done) {\n return;\n }\n \n R v = value;\n\n R u;\n\n try {\n u = ObjectHelper.requireNonNull(accumulator.apply(v, t), \"The accumulator returned a null value\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n s.cancel();\n onError(e);\n return;\n }\n\n value = u;\n produced++;\n actual.onNext(v);\n }\n\n @Override\n public void onError(Throwable t) {\n if (done) {\n return;\n }\n done = true;\n value = null;\n actual.onError(t);\n }\n\n @Override\n public void onComplete() {\n if (done) {\n return;\n }\n done = true;\n complete(value);\n }\n }\n}\n", "text": "<|original_code|>\n this.seedSupplier = seedSupplier;\n }\n\n @Override\n protected void subscribeActual(Subscriber s) {\n R r;\n\n try {\n r = ObjectHelper.requireNonNull(seedSupplier.call(), \"The seed supplied is null\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n EmptySubscription.error(e, s);\n return;\n }\n\n source.subscribe(new ScanSeedSubscriber(s, accumulator, r));\n }\n\n static final class ScanSeedSubscriber extends SinglePostCompleteSubscriber {\n private static final long serialVersionUID = -1776795561228106469L;\n\n final BiFunction accumulator;\n\n ScanSeedSubscriber(Subscriber actual, BiFunction accumulator, R value) {\n super(actual);\n this.accumulator = accumulator;\n this.value = value;\n }\n\n @Override\n public void onNext(T t) {\n R v = value;\n\n R u;\n\n try {\n u = ObjectHelper.requireNonNull(accumulator.apply(v, t), \"The accumulator returned a null value\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n s.cancel();\n onError(e);\n return;\n }\n\n value = u;\n produced++;\n actual.onNext(v);\n }\n\n @Override\n public void onError(Throwable t) {\n value = null;\n actual.onError(t);\n }\n\n @Override\n public void onComplete() {\n complete(value);\n }\n }\n}\n\n<|edits_diff|>\n--- src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java\n+++ src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java\n@@ -20,6 +20,8 @@\n private static final long serialVersionUID = -1776795561228106469L;\n \n final BiFunction accumulator;\n+ \n+ boolean done;\n \n ScanSeedSubscriber(Subscriber actual, BiFunction accumulator, R value) {\n super(actual);\n@@ -29,6 +31,10 @@\n \n @Override\n public void onNext(T t) {\n+ if (done) {\n+ return;\n+ }\n+ \n R v = value;\n \n R u;\n@@ -49,6 +55,10 @@\n \n @Override\n public void onError(Throwable t) {\n+ if (done) {\n+ return;\n+ }\n+ done = true;\n value = null;\n actual.onError(t);\n }\n<|current_version|>\n this.seedSupplier = seedSupplier;\n }\n\n @Override\n protected void subscribeActual(Subscriber s) {\n R r;\n\n try {\n r = ObjectHelper.requireNonNull(seedSupplier.call(), \"The seed supplied is null\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n EmptySubscription.error(e, s);\n return;\n }\n\n source.subscribe(new ScanSeedSubscriber(s, accumulator, r));\n }\n\n static final class ScanSeedSubscriber extends SinglePostCompleteSubscriber {\n private static final long serialVersionUID = -1776795561228106469L;\n\n final BiFunction accumulator;\n \n boolean done;\n\n ScanSeedSubscriber(Subscriber actual, BiFunction accumulator, R value) {\n super(actual);\n this.accumulator = accumulator;\n this.value = value;\n }\n\n @Override\n public void onNext(T t) {\n if (done) {\n return;\n }\n \n R v = value;\n\n R u;\n\n try {\n u = ObjectHelper.requireNonNull(accumulator.apply(v, t), \"The accumulator returned a null value\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n s.cancel();\n onError(e);\n return;\n }\n\n value = u;\n produced++;\n actual.onNext(v);\n }\n\n @Override\n public void onError(Throwable t) {\n if (done) {\n return;\n }\n done = true;\n value = null;\n actual.onError(t);\n }\n\n @Override\n public void onComplete() {\n complete(value);\n }\n }\n}\n\n<|next_version|>\n this.seedSupplier = seedSupplier;\n }\n\n @Override\n protected void subscribeActual(Subscriber s) {\n R r;\n\n try {\n r = ObjectHelper.requireNonNull(seedSupplier.call(), \"The seed supplied is null\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n EmptySubscription.error(e, s);\n return;\n }\n\n source.subscribe(new ScanSeedSubscriber(s, accumulator, r));\n }\n\n static final class ScanSeedSubscriber extends SinglePostCompleteSubscriber {\n private static final long serialVersionUID = -1776795561228106469L;\n\n final BiFunction accumulator;\n \n boolean done;\n\n ScanSeedSubscriber(Subscriber actual, BiFunction accumulator, R value) {\n super(actual);\n this.accumulator = accumulator;\n this.value = value;\n }\n\n @Override\n public void onNext(T t) {\n if (done) {\n return;\n }\n \n R v = value;\n\n R u;\n\n try {\n u = ObjectHelper.requireNonNull(accumulator.apply(v, t), \"The accumulator returned a null value\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n s.cancel();\n onError(e);\n return;\n }\n\n value = u;\n produced++;\n actual.onNext(v);\n }\n\n @Override\n public void onError(Throwable t) {\n if (done) {\n return;\n }\n done = true;\n value = null;\n actual.onError(t);\n }\n\n @Override\n public void onComplete() {\n if (done) {\n return;\n }\n done = true;\n complete(value);\n }\n }\n}\n\n", "current_contents": " this.seedSupplier = seedSupplier;\n }\n\n @Override\n protected void subscribeActual(Subscriber s) {\n R r;\n\n try {\n r = ObjectHelper.requireNonNull(seedSupplier.call(), \"The seed supplied is null\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n EmptySubscription.error(e, s);\n return;\n }\n\n source.subscribe(new ScanSeedSubscriber(s, accumulator, r));\n }\n\n static final class ScanSeedSubscriber extends SinglePostCompleteSubscriber {\n private static final long serialVersionUID = -1776795561228106469L;\n\n final BiFunction accumulator;\n \n boolean done;\n\n ScanSeedSubscriber(Subscriber actual, BiFunction accumulator, R value) {\n super(actual);\n this.accumulator = accumulator;\n this.value = value;\n }\n\n @Override\n public void onNext(T t) {\n if (done) {\n return;\n }\n \n R v = value;\n\n R u;\n\n try {\n u = ObjectHelper.requireNonNull(accumulator.apply(v, t), \"The accumulator returned a null value\");\n } catch (Throwable e) {\n Exceptions.throwIfFatal(e);\n s.cancel();\n onError(e);\n return;\n }\n\n value = u;\n produced++;\n actual.onNext(v);\n }\n\n @Override\n public void onError(Throwable t) {\n if (done) {\n return;\n }\n done = true;\n value = null;\n actual.onError(t);\n }\n\n @Override\n public void onComplete() {\n complete(value);\n }\n }\n}\n"} {"commit": "e49c8ff713609d3d8bf6ef30e6a5e2f9dcbdd11e", "message": "2.x: add system properties to adjust thread priorities of Schedulers (#4503)", "old_file": "src/main/java/io/reactivex/internal/schedulers/RxThreadFactory.java", "new_file": "src/main/java/io/reactivex/internal/schedulers/RxThreadFactory.java", "status": "M", "old_contents": "/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.internal.schedulers;\n\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.atomic.AtomicLong;\n\npublic final class RxThreadFactory extends AtomicLong implements ThreadFactory {\n /** */\n private static final long serialVersionUID = -7789753024099756196L;\n\n final String prefix;\n\n static volatile boolean CREATE_TRACE;\n\n public RxThreadFactory(String prefix) {\n this.prefix = prefix;\n }\n\n @Override\n public Thread newThread(Runnable r) {\n StringBuilder nameBuilder = new StringBuilder(prefix).append('-').append(incrementAndGet());\n\n if (CREATE_TRACE) {\n nameBuilder.append(\"\\r\\n\");\n for (StackTraceElement se :Thread.currentThread().getStackTrace()) {\n String s = se.toString();\n if (s.contains(\"sun.reflect.\")) {\n continue;\n }\n if (s.contains(\"junit.runners.\")) {\n continue;\n }\n if (s.contains(\"org.gradle.internal.\")) {\n continue;\n }\n if (s.contains(\"java.util.concurrent.ThreadPoolExecutor\")) {\n continue;\n }\n nameBuilder.append(s).append(\"\\r\\n\");\n }\n }\n Thread t = new Thread(r, nameBuilder.toString());\n t.setDaemon(true);\n return t;\n }\n\n @Override\n public String toString() {\n return \"RxThreadFactory[\" + prefix + \"]\";\n }\n}\n", "new_contents": "/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.internal.schedulers;\n\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * A ThreadFactory that counts how many threads have been created and given a prefix,\n * sets the created Thread's name to {@code prefix-count}.\n */\npublic final class RxThreadFactory extends AtomicLong implements ThreadFactory {\n /** */\n private static final long serialVersionUID = -7789753024099756196L;\n\n final String prefix;\n\n final int priority;\n\n static volatile boolean CREATE_TRACE;\n\n public RxThreadFactory(String prefix) {\n this(prefix, Thread.NORM_PRIORITY);\n }\n\n public RxThreadFactory(String prefix, int priority) {\n this.prefix = prefix;\n this.priority = priority;\n }\n\n @Override\n public Thread newThread(Runnable r) {\n StringBuilder nameBuilder = new StringBuilder(prefix).append('-').append(incrementAndGet());\n\n if (CREATE_TRACE) {\n nameBuilder.append(\"\\r\\n\");\n for (StackTraceElement se :Thread.currentThread().getStackTrace()) {\n String s = se.toString();\n if (s.contains(\"sun.reflect.\")) {\n continue;\n }\n if (s.contains(\"junit.runners.\")) {\n continue;\n }\n if (s.contains(\"org.gradle.internal.\")) {\n continue;\n }\n if (s.contains(\"java.util.concurrent.ThreadPoolExecutor\")) {\n continue;\n }\n nameBuilder.append(s).append(\"\\r\\n\");\n }\n }\n Thread t = new Thread(r, nameBuilder.toString());\n t.setPriority(priority);\n t.setDaemon(true);\n return t;\n }\n\n @Override\n public String toString() {\n return \"RxThreadFactory[\" + prefix + \"]\";\n }\n}\n", "text": "<|original_code|>\n/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.internal.schedulers;\n\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.atomic.AtomicLong;\n\npublic final class RxThreadFactory extends AtomicLong implements ThreadFactory {\n /** */\n private static final long serialVersionUID = -7789753024099756196L;\n\n final String prefix;\n\n static volatile boolean CREATE_TRACE;\n\n public RxThreadFactory(String prefix) {\n this.prefix = prefix;\n }\n\n @Override\n public Thread newThread(Runnable r) {\n StringBuilder nameBuilder = new StringBuilder(prefix).append('-').append(incrementAndGet());\n\n if (CREATE_TRACE) {\n nameBuilder.append(\"\\r\\n\");\n for (StackTraceElement se :Thread.currentThread().getStackTrace()) {\n String s = se.toString();\n if (s.contains(\"sun.reflect.\")) {\n continue;\n }\n if (s.contains(\"junit.runners.\")) {\n continue;\n }\n if (s.contains(\"org.gradle.internal.\")) {\n continue;\n }\n if (s.contains(\"java.util.concurrent.ThreadPoolExecutor\")) {\n continue;\n }\n nameBuilder.append(s).append(\"\\r\\n\");\n }\n }\n Thread t = new Thread(r, nameBuilder.toString());\n t.setDaemon(true);\n return t;\n }\n\n @Override\n public String toString() {\n return \"RxThreadFactory[\" + prefix + \"]\";\n }\n}\n\n<|edits_diff|>\n--- src/main/java/io/reactivex/internal/schedulers/RxThreadFactory.java\n+++ src/main/java/io/reactivex/internal/schedulers/RxThreadFactory.java\n@@ -16,16 +16,27 @@\n import java.util.concurrent.ThreadFactory;\n import java.util.concurrent.atomic.AtomicLong;\n \n+/**\n+ * A ThreadFactory that counts how many threads have been created and given a prefix,\n+ * sets the created Thread's name to {@code prefix-count}.\n+ */\n public final class RxThreadFactory extends AtomicLong implements ThreadFactory {\n /** */\n private static final long serialVersionUID = -7789753024099756196L;\n \n final String prefix;\n \n+ final int priority;\n+\n static volatile boolean CREATE_TRACE;\n \n public RxThreadFactory(String prefix) {\n+ this(prefix, Thread.NORM_PRIORITY);\n+ }\n+\n+ public RxThreadFactory(String prefix, int priority) {\n this.prefix = prefix;\n+ this.priority = priority;\n }\n \n @Override\n<|current_version|>\n/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.internal.schedulers;\n\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * A ThreadFactory that counts how many threads have been created and given a prefix,\n * sets the created Thread's name to {@code prefix-count}.\n */\npublic final class RxThreadFactory extends AtomicLong implements ThreadFactory {\n /** */\n private static final long serialVersionUID = -7789753024099756196L;\n\n final String prefix;\n\n final int priority;\n\n static volatile boolean CREATE_TRACE;\n\n public RxThreadFactory(String prefix) {\n this(prefix, Thread.NORM_PRIORITY);\n }\n\n public RxThreadFactory(String prefix, int priority) {\n this.prefix = prefix;\n this.priority = priority;\n }\n\n @Override\n public Thread newThread(Runnable r) {\n StringBuilder nameBuilder = new StringBuilder(prefix).append('-').append(incrementAndGet());\n\n if (CREATE_TRACE) {\n nameBuilder.append(\"\\r\\n\");\n for (StackTraceElement se :Thread.currentThread().getStackTrace()) {\n String s = se.toString();\n if (s.contains(\"sun.reflect.\")) {\n continue;\n }\n if (s.contains(\"junit.runners.\")) {\n continue;\n }\n if (s.contains(\"org.gradle.internal.\")) {\n continue;\n }\n if (s.contains(\"java.util.concurrent.ThreadPoolExecutor\")) {\n continue;\n }\n nameBuilder.append(s).append(\"\\r\\n\");\n }\n }\n Thread t = new Thread(r, nameBuilder.toString());\n t.setDaemon(true);\n return t;\n }\n\n @Override\n public String toString() {\n return \"RxThreadFactory[\" + prefix + \"]\";\n }\n}\n\n<|next_version|>\n/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.internal.schedulers;\n\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * A ThreadFactory that counts how many threads have been created and given a prefix,\n * sets the created Thread's name to {@code prefix-count}.\n */\npublic final class RxThreadFactory extends AtomicLong implements ThreadFactory {\n /** */\n private static final long serialVersionUID = -7789753024099756196L;\n\n final String prefix;\n\n final int priority;\n\n static volatile boolean CREATE_TRACE;\n\n public RxThreadFactory(String prefix) {\n this(prefix, Thread.NORM_PRIORITY);\n }\n\n public RxThreadFactory(String prefix, int priority) {\n this.prefix = prefix;\n this.priority = priority;\n }\n\n @Override\n public Thread newThread(Runnable r) {\n StringBuilder nameBuilder = new StringBuilder(prefix).append('-').append(incrementAndGet());\n\n if (CREATE_TRACE) {\n nameBuilder.append(\"\\r\\n\");\n for (StackTraceElement se :Thread.currentThread().getStackTrace()) {\n String s = se.toString();\n if (s.contains(\"sun.reflect.\")) {\n continue;\n }\n if (s.contains(\"junit.runners.\")) {\n continue;\n }\n if (s.contains(\"org.gradle.internal.\")) {\n continue;\n }\n if (s.contains(\"java.util.concurrent.ThreadPoolExecutor\")) {\n continue;\n }\n nameBuilder.append(s).append(\"\\r\\n\");\n }\n }\n Thread t = new Thread(r, nameBuilder.toString());\n t.setPriority(priority);\n t.setDaemon(true);\n return t;\n }\n\n @Override\n public String toString() {\n return \"RxThreadFactory[\" + prefix + \"]\";\n }\n}\n\n", "current_contents": "/**\n * Copyright 2016 Netflix, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.internal.schedulers;\n\nimport java.util.concurrent.ThreadFactory;\nimport java.util.concurrent.atomic.AtomicLong;\n\n/**\n * A ThreadFactory that counts how many threads have been created and given a prefix,\n * sets the created Thread's name to {@code prefix-count}.\n */\npublic final class RxThreadFactory extends AtomicLong implements ThreadFactory {\n /** */\n private static final long serialVersionUID = -7789753024099756196L;\n\n final String prefix;\n\n final int priority;\n\n static volatile boolean CREATE_TRACE;\n\n public RxThreadFactory(String prefix) {\n this(prefix, Thread.NORM_PRIORITY);\n }\n\n public RxThreadFactory(String prefix, int priority) {\n this.prefix = prefix;\n this.priority = priority;\n }\n\n @Override\n public Thread newThread(Runnable r) {\n StringBuilder nameBuilder = new StringBuilder(prefix).append('-').append(incrementAndGet());\n\n if (CREATE_TRACE) {\n nameBuilder.append(\"\\r\\n\");\n for (StackTraceElement se :Thread.currentThread().getStackTrace()) {\n String s = se.toString();\n if (s.contains(\"sun.reflect.\")) {\n continue;\n }\n if (s.contains(\"junit.runners.\")) {\n continue;\n }\n if (s.contains(\"org.gradle.internal.\")) {\n continue;\n }\n if (s.contains(\"java.util.concurrent.ThreadPoolExecutor\")) {\n continue;\n }\n nameBuilder.append(s).append(\"\\r\\n\");\n }\n }\n Thread t = new Thread(r, nameBuilder.toString());\n t.setDaemon(true);\n return t;\n }\n\n @Override\n public String toString() {\n return \"RxThreadFactory[\" + prefix + \"]\";\n }\n}\n"} {"commit": "5688cc8ad6fb20dde449ba71138de278baba86ea", "message": "2.x: switch to throwing Action, switchMapDelayError (#4357)", "old_file": "src/main/java/io/reactivex/disposables/Disposables.java", "new_file": "src/main/java/io/reactivex/disposables/Disposables.java", "status": "M", "old_contents": "/**\n * Copyright 2016 Netflix, Inc.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.disposables;\n\nimport java.util.concurrent.Future;\n\nimport org.reactivestreams.Subscription;\n\nimport io.reactivex.internal.disposables.EmptyDisposable;\nimport io.reactivex.internal.functions.Functions;\n\n/**\n * Utility class to help create disposables by wrapping\n * other types.\n */\npublic final class Disposables {\n /** Utility class. */\n private Disposables() {\n throw new IllegalStateException(\"No instances!\");\n }\n \n public static Disposable from(Runnable run) {\n return new RunnableDisposable(run);\n }\n\n public static Disposable from(Future future) {\n return from(future, true);\n }\n\n public static Disposable from(Future future, boolean allowInterrupt) {\n return new FutureDisposable(future, allowInterrupt);\n }\n\n public static Disposable from(Subscription subscription) {\n return new SubscriptionDisposable(subscription);\n }\n\n public static Disposable empty() {\n return from(Functions.EMPTY_RUNNABLE);\n }\n\n public static Disposable disposed() {\n return EmptyDisposable.INSTANCE;\n }\n}\n", "new_contents": "/**\n * Copyright 2016 Netflix, Inc.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.disposables;\n\nimport java.util.concurrent.Future;\n\nimport org.reactivestreams.Subscription;\n\nimport io.reactivex.functions.Action;\nimport io.reactivex.internal.disposables.EmptyDisposable;\nimport io.reactivex.internal.functions.Functions;\n\n/**\n * Utility class to help create disposables by wrapping\n * other types.\n */\npublic final class Disposables {\n /** Utility class. */\n private Disposables() {\n throw new IllegalStateException(\"No instances!\");\n }\n \n public static Disposable from(Runnable run) {\n return new RunnableDisposable(run);\n }\n\n public static Disposable from(Action run) {\n return new ActionDisposable(run);\n }\n\n public static Disposable from(Future future) {\n return from(future, true);\n }\n\n public static Disposable from(Future future, boolean allowInterrupt) {\n return new FutureDisposable(future, allowInterrupt);\n }\n\n public static Disposable from(Subscription subscription) {\n return new SubscriptionDisposable(subscription);\n }\n\n public static Disposable empty() {\n return from(Functions.EMPTY_RUNNABLE);\n }\n\n public static Disposable disposed() {\n return EmptyDisposable.INSTANCE;\n }\n}\n", "text": "<|original_code|>\n/**\n * Copyright 2016 Netflix, Inc.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.disposables;\n\nimport java.util.concurrent.Future;\n\nimport org.reactivestreams.Subscription;\n\nimport io.reactivex.internal.disposables.EmptyDisposable;\nimport io.reactivex.internal.functions.Functions;\n\n/**\n * Utility class to help create disposables by wrapping\n * other types.\n */\npublic final class Disposables {\n /** Utility class. */\n private Disposables() {\n throw new IllegalStateException(\"No instances!\");\n }\n \n public static Disposable from(Runnable run) {\n return new RunnableDisposable(run);\n }\n\n public static Disposable from(Future future) {\n return from(future, true);\n }\n\n public static Disposable from(Future future, boolean allowInterrupt) {\n return new FutureDisposable(future, allowInterrupt);\n }\n\n public static Disposable from(Subscription subscription) {\n return new SubscriptionDisposable(subscription);\n }\n\n public static Disposable empty() {\n return from(Functions.EMPTY_RUNNABLE);\n }\n\n public static Disposable disposed() {\n return EmptyDisposable.INSTANCE;\n }\n}\n\n<|edits_diff|>\n--- src/main/java/io/reactivex/disposables/Disposables.java\n+++ src/main/java/io/reactivex/disposables/Disposables.java\n@@ -17,6 +17,7 @@\n \n import org.reactivestreams.Subscription;\n \n+import io.reactivex.functions.Action;\n import io.reactivex.internal.disposables.EmptyDisposable;\n import io.reactivex.internal.functions.Functions;\n \n<|current_version|>\n/**\n * Copyright 2016 Netflix, Inc.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.disposables;\n\nimport java.util.concurrent.Future;\n\nimport org.reactivestreams.Subscription;\n\nimport io.reactivex.functions.Action;\nimport io.reactivex.internal.disposables.EmptyDisposable;\nimport io.reactivex.internal.functions.Functions;\n\n/**\n * Utility class to help create disposables by wrapping\n * other types.\n */\npublic final class Disposables {\n /** Utility class. */\n private Disposables() {\n throw new IllegalStateException(\"No instances!\");\n }\n \n public static Disposable from(Runnable run) {\n return new RunnableDisposable(run);\n }\n\n public static Disposable from(Future future) {\n return from(future, true);\n }\n\n public static Disposable from(Future future, boolean allowInterrupt) {\n return new FutureDisposable(future, allowInterrupt);\n }\n\n public static Disposable from(Subscription subscription) {\n return new SubscriptionDisposable(subscription);\n }\n\n public static Disposable empty() {\n return from(Functions.EMPTY_RUNNABLE);\n }\n\n public static Disposable disposed() {\n return EmptyDisposable.INSTANCE;\n }\n}\n\n<|next_version|>\n/**\n * Copyright 2016 Netflix, Inc.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.disposables;\n\nimport java.util.concurrent.Future;\n\nimport org.reactivestreams.Subscription;\n\nimport io.reactivex.functions.Action;\nimport io.reactivex.internal.disposables.EmptyDisposable;\nimport io.reactivex.internal.functions.Functions;\n\n/**\n * Utility class to help create disposables by wrapping\n * other types.\n */\npublic final class Disposables {\n /** Utility class. */\n private Disposables() {\n throw new IllegalStateException(\"No instances!\");\n }\n \n public static Disposable from(Runnable run) {\n return new RunnableDisposable(run);\n }\n\n public static Disposable from(Action run) {\n return new ActionDisposable(run);\n }\n\n public static Disposable from(Future future) {\n return from(future, true);\n }\n\n public static Disposable from(Future future, boolean allowInterrupt) {\n return new FutureDisposable(future, allowInterrupt);\n }\n\n public static Disposable from(Subscription subscription) {\n return new SubscriptionDisposable(subscription);\n }\n\n public static Disposable empty() {\n return from(Functions.EMPTY_RUNNABLE);\n }\n\n public static Disposable disposed() {\n return EmptyDisposable.INSTANCE;\n }\n}\n\n", "current_contents": "/**\n * Copyright 2016 Netflix, Inc.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in\n * compliance with the License. You may obtain a copy of the License at\n * \n * http://www.apache.org/licenses/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\n\npackage io.reactivex.disposables;\n\nimport java.util.concurrent.Future;\n\nimport org.reactivestreams.Subscription;\n\nimport io.reactivex.functions.Action;\nimport io.reactivex.internal.disposables.EmptyDisposable;\nimport io.reactivex.internal.functions.Functions;\n\n/**\n * Utility class to help create disposables by wrapping\n * other types.\n */\npublic final class Disposables {\n /** Utility class. */\n private Disposables() {\n throw new IllegalStateException(\"No instances!\");\n }\n \n public static Disposable from(Runnable run) {\n return new RunnableDisposable(run);\n }\n\n public static Disposable from(Future future) {\n return from(future, true);\n }\n\n public static Disposable from(Future future, boolean allowInterrupt) {\n return new FutureDisposable(future, allowInterrupt);\n }\n\n public static Disposable from(Subscription subscription) {\n return new SubscriptionDisposable(subscription);\n }\n\n public static Disposable empty() {\n return from(Functions.EMPTY_RUNNABLE);\n }\n\n public static Disposable disposed() {\n return EmptyDisposable.INSTANCE;\n }\n}\n"} {"commit": "967e083d0dfe504637d42c20ad18ea05384393a2", "message": "Fixes to MpscLinkedQueue, some minor refactorings.", "old_file": "src/main/java/io/reactivex/internal/util/NotificationLite.java", "new_file": "src/main/java/io/reactivex/internal/util/NotificationLite.java", "status": "M", "old_contents": " * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\npackage io.reactivex.internal.util;\n\nimport java.io.Serializable;\n\nimport org.reactivestreams.*;\n\n/**\n * Lightweight notification handling utility class.\n */\npublic enum NotificationLite {\n // No instances\n ;\n \n /**\n * Indicates a completion notification.\n */\n private enum Complete {\n INSTANCE;\n }\n \n /**\n * Wraps a Throwable.\n */\n private static final class ErrorNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -8759979445933046293L;\n final Throwable e;\n ErrorNotification(Throwable e) {\n this.e = e;\n }\n }\n \n /**\n * Wraps a Subscription.\n */\n private static final class SubscriptionNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -1322257508628817540L;\n final Subscription s;\n SubscriptionNotification(Subscription s) {\n this.s = s;\n }\n }\n \n /**\n * Converts a value into a notification value.\n * @param value the value to convert\n * @return the notification representing the value\n */\n public static Object next(T value) {\n return value;\n }\n \n /**\n * Returns a complete notification.\n * @return a complete notification\n */\n public static Object complete() {\n return Complete.INSTANCE;\n }\n \n /**\n * Converts a Throwable into a notification value.\n * @param e the Throwable to convert\n * @return the notification representing the Throwable\n */", "new_contents": " * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\npackage io.reactivex.internal.util;\n\nimport java.io.Serializable;\n\nimport org.reactivestreams.*;\n\n/**\n * Lightweight notification handling utility class.\n */\npublic enum NotificationLite {\n // No instances\n ;\n \n /**\n * Indicates a completion notification.\n */\n private enum Complete {\n INSTANCE;\n @Override\n public String toString() {\n return \"NotificationLite.Complete\";\n };\n }\n \n /**\n * Wraps a Throwable.\n */\n private static final class ErrorNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -8759979445933046293L;\n final Throwable e;\n ErrorNotification(Throwable e) {\n this.e = e;\n }\n \n @Override\n public String toString() {\n return \"NotificationLite.Error[\" + e + \"]\";\n }\n }\n \n /**\n * Wraps a Subscription.\n */\n private static final class SubscriptionNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -1322257508628817540L;\n final Subscription s;\n SubscriptionNotification(Subscription s) {\n this.s = s;\n }\n \n @Override\n public String toString() {\n return \"NotificationLite.Subscription[\" + s + \"]\";\n }\n }\n \n /**\n * Converts a value into a notification value.\n * @param value the value to convert\n * @return the notification representing the value\n */\n public static Object next(T value) {\n return value;\n }\n \n /**\n * Returns a complete notification.\n * @return a complete notification\n */\n public static Object complete() {\n return Complete.INSTANCE;\n }\n \n /**\n * Converts a Throwable into a notification value.\n * @param e the Throwable to convert\n * @return the notification representing the Throwable\n */", "text": "<|original_code|>\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\npackage io.reactivex.internal.util;\n\nimport java.io.Serializable;\n\nimport org.reactivestreams.*;\n\n/**\n * Lightweight notification handling utility class.\n */\npublic enum NotificationLite {\n // No instances\n ;\n \n /**\n * Indicates a completion notification.\n */\n private enum Complete {\n INSTANCE;\n }\n \n /**\n * Wraps a Throwable.\n */\n private static final class ErrorNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -8759979445933046293L;\n final Throwable e;\n ErrorNotification(Throwable e) {\n this.e = e;\n }\n }\n \n /**\n * Wraps a Subscription.\n */\n private static final class SubscriptionNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -1322257508628817540L;\n final Subscription s;\n SubscriptionNotification(Subscription s) {\n this.s = s;\n }\n }\n \n /**\n * Converts a value into a notification value.\n * @param value the value to convert\n * @return the notification representing the value\n */\n public static Object next(T value) {\n return value;\n }\n \n /**\n * Returns a complete notification.\n * @return a complete notification\n */\n public static Object complete() {\n return Complete.INSTANCE;\n }\n \n /**\n * Converts a Throwable into a notification value.\n * @param e the Throwable to convert\n * @return the notification representing the Throwable\n */\n<|edits_diff|>\n--- src/main/java/io/reactivex/internal/util/NotificationLite.java\n+++ src/main/java/io/reactivex/internal/util/NotificationLite.java\n@@ -20,6 +20,10 @@\n */\n private enum Complete {\n INSTANCE;\n+ @Override\n+ public String toString() {\n+ return \"NotificationLite.Complete\";\n+ };\n }\n \n /**\n@@ -31,6 +35,11 @@\n final Throwable e;\n ErrorNotification(Throwable e) {\n this.e = e;\n+ }\n+ \n+ @Override\n+ public String toString() {\n+ return \"NotificationLite.Error[\" + e + \"]\";\n }\n }\n \n<|current_version|>\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\npackage io.reactivex.internal.util;\n\nimport java.io.Serializable;\n\nimport org.reactivestreams.*;\n\n/**\n * Lightweight notification handling utility class.\n */\npublic enum NotificationLite {\n // No instances\n ;\n \n /**\n * Indicates a completion notification.\n */\n private enum Complete {\n INSTANCE;\n @Override\n public String toString() {\n return \"NotificationLite.Complete\";\n };\n }\n \n /**\n * Wraps a Throwable.\n */\n private static final class ErrorNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -8759979445933046293L;\n final Throwable e;\n ErrorNotification(Throwable e) {\n this.e = e;\n }\n \n @Override\n public String toString() {\n return \"NotificationLite.Error[\" + e + \"]\";\n }\n }\n \n /**\n * Wraps a Subscription.\n */\n private static final class SubscriptionNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -1322257508628817540L;\n final Subscription s;\n SubscriptionNotification(Subscription s) {\n this.s = s;\n }\n }\n \n /**\n * Converts a value into a notification value.\n * @param value the value to convert\n * @return the notification representing the value\n */\n public static Object next(T value) {\n return value;\n }\n \n /**\n * Returns a complete notification.\n * @return a complete notification\n */\n public static Object complete() {\n return Complete.INSTANCE;\n }\n \n /**\n * Converts a Throwable into a notification value.\n * @param e the Throwable to convert\n * @return the notification representing the Throwable\n */\n<|next_version|>\n * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\npackage io.reactivex.internal.util;\n\nimport java.io.Serializable;\n\nimport org.reactivestreams.*;\n\n/**\n * Lightweight notification handling utility class.\n */\npublic enum NotificationLite {\n // No instances\n ;\n \n /**\n * Indicates a completion notification.\n */\n private enum Complete {\n INSTANCE;\n @Override\n public String toString() {\n return \"NotificationLite.Complete\";\n };\n }\n \n /**\n * Wraps a Throwable.\n */\n private static final class ErrorNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -8759979445933046293L;\n final Throwable e;\n ErrorNotification(Throwable e) {\n this.e = e;\n }\n \n @Override\n public String toString() {\n return \"NotificationLite.Error[\" + e + \"]\";\n }\n }\n \n /**\n * Wraps a Subscription.\n */\n private static final class SubscriptionNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -1322257508628817540L;\n final Subscription s;\n SubscriptionNotification(Subscription s) {\n this.s = s;\n }\n \n @Override\n public String toString() {\n return \"NotificationLite.Subscription[\" + s + \"]\";\n }\n }\n \n /**\n * Converts a value into a notification value.\n * @param value the value to convert\n * @return the notification representing the value\n */\n public static Object next(T value) {\n return value;\n }\n \n /**\n * Returns a complete notification.\n * @return a complete notification\n */\n public static Object complete() {\n return Complete.INSTANCE;\n }\n \n /**\n * Converts a Throwable into a notification value.\n * @param e the Throwable to convert\n * @return the notification representing the Throwable\n */\n", "current_contents": " * Unless required by applicable law or agreed to in writing, software distributed under the License is\n * distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See\n * the License for the specific language governing permissions and limitations under the License.\n */\npackage io.reactivex.internal.util;\n\nimport java.io.Serializable;\n\nimport org.reactivestreams.*;\n\n/**\n * Lightweight notification handling utility class.\n */\npublic enum NotificationLite {\n // No instances\n ;\n \n /**\n * Indicates a completion notification.\n */\n private enum Complete {\n INSTANCE;\n @Override\n public String toString() {\n return \"NotificationLite.Complete\";\n };\n }\n \n /**\n * Wraps a Throwable.\n */\n private static final class ErrorNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -8759979445933046293L;\n final Throwable e;\n ErrorNotification(Throwable e) {\n this.e = e;\n }\n \n @Override\n public String toString() {\n return \"NotificationLite.Error[\" + e + \"]\";\n }\n }\n \n /**\n * Wraps a Subscription.\n */\n private static final class SubscriptionNotification implements Serializable {\n /** */\n private static final long serialVersionUID = -1322257508628817540L;\n final Subscription s;\n SubscriptionNotification(Subscription s) {\n this.s = s;\n }\n }\n \n /**\n * Converts a value into a notification value.\n * @param value the value to convert\n * @return the notification representing the value\n */\n public static Object next(T value) {\n return value;\n }\n \n /**\n * Returns a complete notification.\n * @return a complete notification\n */\n public static Object complete() {\n return Complete.INSTANCE;\n }\n \n /**\n * Converts a Throwable into a notification value.\n * @param e the Throwable to convert\n * @return the notification representing the Throwable\n */"} {"commit": "14b3bf5445ef2e347389fc6a20693a047fdc31b1", "message": "Configure alpha as false explicitly on jpeg encode tests", "old_file": "library/test/src/test/java/com/bumptech/glide/load/resource/bitmap/BitmapEncoderTest.java", "new_file": "library/test/src/test/java/com/bumptech/glide/load/resource/bitmap/BitmapEncoderTest.java", "status": "M", "old_contents": "import org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.annotation.Config;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18)\npublic class BitmapEncoderTest {\n private EncoderHarness harness;\n\n @Before\n public void setUp() {\n harness = new EncoderHarness();\n }\n\n @After\n public void tearDown() {\n harness.tearDown();\n }\n\n @Test\n public void testBitmapIsEncoded() throws IOException {\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testBitmapIsEncodedWithGivenQuality() throws IOException {\n int quality = 7;\n harness.setQuality(quality);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, quality));\n }\n\n @Test\n public void testEncoderObeysNonNullCompressFormat() throws IOException {\n Bitmap.CompressFormat format = Bitmap.CompressFormat.WEBP;\n harness.setFormat(format);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.WEBP, 90));\n }\n\n @Test\n public void testEncoderEncodesJpegWithNullFormatAndBitmapWithoutAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testEncoderEncodesPngWithNullFormatAndBitmapWithAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(true);", "new_contents": "import org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.annotation.Config;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18)\npublic class BitmapEncoderTest {\n private EncoderHarness harness;\n\n @Before\n public void setUp() {\n harness = new EncoderHarness();\n }\n\n @After\n public void tearDown() {\n harness.tearDown();\n }\n\n @Test\n public void testBitmapIsEncoded() throws IOException {\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testBitmapIsEncodedWithGivenQuality() throws IOException {\n int quality = 7;\n harness.setQuality(quality);\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, quality));\n }\n\n @Test\n public void testEncoderObeysNonNullCompressFormat() throws IOException {\n Bitmap.CompressFormat format = Bitmap.CompressFormat.WEBP;\n harness.setFormat(format);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.WEBP, 90));\n }\n\n @Test\n public void testEncoderEncodesJpegWithNullFormatAndBitmapWithoutAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testEncoderEncodesPngWithNullFormatAndBitmapWithAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(true);", "text": "<|original_code|>\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.annotation.Config;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18)\npublic class BitmapEncoderTest {\n private EncoderHarness harness;\n\n @Before\n public void setUp() {\n harness = new EncoderHarness();\n }\n\n @After\n public void tearDown() {\n harness.tearDown();\n }\n\n @Test\n public void testBitmapIsEncoded() throws IOException {\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testBitmapIsEncodedWithGivenQuality() throws IOException {\n int quality = 7;\n harness.setQuality(quality);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, quality));\n }\n\n @Test\n public void testEncoderObeysNonNullCompressFormat() throws IOException {\n Bitmap.CompressFormat format = Bitmap.CompressFormat.WEBP;\n harness.setFormat(format);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.WEBP, 90));\n }\n\n @Test\n public void testEncoderEncodesJpegWithNullFormatAndBitmapWithoutAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testEncoderEncodesPngWithNullFormatAndBitmapWithAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(true);\n<|edits_diff|>\n--- library/test/src/test/java/com/bumptech/glide/load/resource/bitmap/BitmapEncoderTest.java\n+++ library/test/src/test/java/com/bumptech/glide/load/resource/bitmap/BitmapEncoderTest.java\n@@ -20,6 +20,8 @@\n \n @Test\n public void testBitmapIsEncoded() throws IOException {\n+ harness.bitmap.setHasAlpha(false);\n+\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n \n<|current_version|>\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.annotation.Config;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18)\npublic class BitmapEncoderTest {\n private EncoderHarness harness;\n\n @Before\n public void setUp() {\n harness = new EncoderHarness();\n }\n\n @After\n public void tearDown() {\n harness.tearDown();\n }\n\n @Test\n public void testBitmapIsEncoded() throws IOException {\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testBitmapIsEncodedWithGivenQuality() throws IOException {\n int quality = 7;\n harness.setQuality(quality);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, quality));\n }\n\n @Test\n public void testEncoderObeysNonNullCompressFormat() throws IOException {\n Bitmap.CompressFormat format = Bitmap.CompressFormat.WEBP;\n harness.setFormat(format);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.WEBP, 90));\n }\n\n @Test\n public void testEncoderEncodesJpegWithNullFormatAndBitmapWithoutAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testEncoderEncodesPngWithNullFormatAndBitmapWithAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(true);\n<|next_version|>\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.annotation.Config;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18)\npublic class BitmapEncoderTest {\n private EncoderHarness harness;\n\n @Before\n public void setUp() {\n harness = new EncoderHarness();\n }\n\n @After\n public void tearDown() {\n harness.tearDown();\n }\n\n @Test\n public void testBitmapIsEncoded() throws IOException {\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testBitmapIsEncodedWithGivenQuality() throws IOException {\n int quality = 7;\n harness.setQuality(quality);\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, quality));\n }\n\n @Test\n public void testEncoderObeysNonNullCompressFormat() throws IOException {\n Bitmap.CompressFormat format = Bitmap.CompressFormat.WEBP;\n harness.setFormat(format);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.WEBP, 90));\n }\n\n @Test\n public void testEncoderEncodesJpegWithNullFormatAndBitmapWithoutAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testEncoderEncodesPngWithNullFormatAndBitmapWithAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(true);\n", "current_contents": "import org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.annotation.Config;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18)\npublic class BitmapEncoderTest {\n private EncoderHarness harness;\n\n @Before\n public void setUp() {\n harness = new EncoderHarness();\n }\n\n @After\n public void tearDown() {\n harness.tearDown();\n }\n\n @Test\n public void testBitmapIsEncoded() throws IOException {\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testBitmapIsEncodedWithGivenQuality() throws IOException {\n int quality = 7;\n harness.setQuality(quality);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, quality));\n }\n\n @Test\n public void testEncoderObeysNonNullCompressFormat() throws IOException {\n Bitmap.CompressFormat format = Bitmap.CompressFormat.WEBP;\n harness.setFormat(format);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.WEBP, 90));\n }\n\n @Test\n public void testEncoderEncodesJpegWithNullFormatAndBitmapWithoutAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(false);\n\n assertThat(harness.encode()).isEqualTo(harness.expectedData(CompressFormat.JPEG, 90));\n }\n\n @Test\n public void testEncoderEncodesPngWithNullFormatAndBitmapWithAlpha() throws IOException {\n harness.setFormat(null);\n harness.bitmap.setHasAlpha(true);"} {"commit": "a77ed9003d578bf2520b188cff2f701097813f31", "message": "Add an experimental option to Glide to avoid hardware Bitmaps until after the first frame.", "old_file": "library/src/main/java/com/bumptech/glide/load/resource/bitmap/HardwareConfigState.java", "new_file": "library/src/main/java/com/bumptech/glide/load/resource/bitmap/HardwareConfigState.java", "status": "M", "old_contents": " private static final File FD_SIZE_LIST = new File(\"/proc/self/fd\");\n\n /**\n * Each FD check takes 1-2ms, so to avoid overhead, only check every N decodes. 50 is more or less\n * arbitrary.\n */\n private static final int MINIMUM_DECODES_BETWEEN_FD_CHECKS = 50;\n\n /**\n * 700 with an error of 50 Bitmaps in between at two FDs each lets us use up to 800 FDs for\n * hardware Bitmaps.\n *\n *

Prior to P, the limit per process was 1024 FDs. In P, the limit was updated to 32k FDs per\n * process.\n *\n *

Access to this variable will be removed in a future version without deprecation.\n */\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O = 700;\n // 20k.\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P = 20000;\n\n private static volatile HardwareConfigState instance;\n\n private final boolean isHardwareConfigAllowedByDeviceModel;\n private final int fdCountLimit;\n private final int minHardwareDimension;\n\n @GuardedBy(\"this\")\n private int decodesSinceLastFdCheck;\n\n @GuardedBy(\"this\")\n private boolean isFdSizeBelowHardwareLimit = true;\n\n public static HardwareConfigState getInstance() {\n if (instance == null) {\n synchronized (HardwareConfigState.class) {\n if (instance == null) {\n instance = new HardwareConfigState();\n }\n }\n }\n return instance;\n }\n\n @VisibleForTesting\n HardwareConfigState() {\n isHardwareConfigAllowedByDeviceModel = isHardwareConfigAllowedByDeviceModel();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_P;\n } else {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_O;\n }\n }\n\n public boolean isHardwareConfigAllowed(\n int targetWidth,\n int targetHeight,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n if (!isHardwareConfigAllowed\n || !isHardwareConfigAllowedByDeviceModel\n || Build.VERSION.SDK_INT < Build.VERSION_CODES.O\n || isExifOrientationRequired) {\n return false;\n }\n\n return targetWidth >= minHardwareDimension\n && targetHeight >= minHardwareDimension\n // Make sure to call isFdSizeBelowHardwareLimit last because it has side affects.\n && isFdSizeBelowHardwareLimit();\n }\n\n @TargetApi(Build.VERSION_CODES.O)\n boolean setHardwareConfigIfAllowed(\n int targetWidth,\n int targetHeight,\n BitmapFactory.Options optionsWithScaling,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n boolean result =\n isHardwareConfigAllowed(\n targetWidth, targetHeight, isHardwareConfigAllowed, isExifOrientationRequired);\n if (result) {\n optionsWithScaling.inPreferredConfig = Bitmap.Config.HARDWARE;\n optionsWithScaling.inMutable = false;\n }", "new_contents": " private static final File FD_SIZE_LIST = new File(\"/proc/self/fd\");\n\n /**\n * Each FD check takes 1-2ms, so to avoid overhead, only check every N decodes. 50 is more or less\n * arbitrary.\n */\n private static final int MINIMUM_DECODES_BETWEEN_FD_CHECKS = 50;\n\n /**\n * 700 with an error of 50 Bitmaps in between at two FDs each lets us use up to 800 FDs for\n * hardware Bitmaps.\n *\n *

Prior to P, the limit per process was 1024 FDs. In P, the limit was updated to 32k FDs per\n * process.\n *\n *

Access to this variable will be removed in a future version without deprecation.\n */\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O = 700;\n // 20k.\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P = 20000;\n\n private static volatile HardwareConfigState instance;\n private static volatile boolean waitForFirstFrame;\n\n private final boolean isHardwareConfigAllowedByDeviceModel;\n private final int fdCountLimit;\n private final int minHardwareDimension;\n\n @GuardedBy(\"this\")\n private int decodesSinceLastFdCheck;\n\n @GuardedBy(\"this\")\n private boolean isFdSizeBelowHardwareLimit = true;\n\n private volatile boolean isFirstFrameDrawn;\n\n public static HardwareConfigState getInstance() {\n if (instance == null) {\n synchronized (HardwareConfigState.class) {\n if (instance == null) {\n instance = new HardwareConfigState();\n }\n }\n }\n return instance;\n }\n\n @VisibleForTesting\n HardwareConfigState() {\n isHardwareConfigAllowedByDeviceModel = isHardwareConfigAllowedByDeviceModel();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_P;\n } else {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_O;\n }\n }\n\n public boolean isHardwareConfigAllowed(\n int targetWidth,\n int targetHeight,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n if (!isHardwareConfigAllowed\n || !isHardwareConfigAllowedByDeviceModel\n || Build.VERSION.SDK_INT < Build.VERSION_CODES.O\n || (waitForFirstFrame && !isFirstFrameDrawn)\n || isExifOrientationRequired) {\n return false;\n }\n\n return targetWidth >= minHardwareDimension\n && targetHeight >= minHardwareDimension\n // Make sure to call isFdSizeBelowHardwareLimit last because it has side affects.\n && isFdSizeBelowHardwareLimit();\n }\n\n @TargetApi(Build.VERSION_CODES.O)\n boolean setHardwareConfigIfAllowed(\n int targetWidth,\n int targetHeight,\n BitmapFactory.Options optionsWithScaling,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n boolean result =\n isHardwareConfigAllowed(\n targetWidth, targetHeight, isHardwareConfigAllowed, isExifOrientationRequired);\n if (result) {\n optionsWithScaling.inPreferredConfig = Bitmap.Config.HARDWARE;\n optionsWithScaling.inMutable = false;\n }", "text": "<|original_code|>\n private static final File FD_SIZE_LIST = new File(\"/proc/self/fd\");\n\n /**\n * Each FD check takes 1-2ms, so to avoid overhead, only check every N decodes. 50 is more or less\n * arbitrary.\n */\n private static final int MINIMUM_DECODES_BETWEEN_FD_CHECKS = 50;\n\n /**\n * 700 with an error of 50 Bitmaps in between at two FDs each lets us use up to 800 FDs for\n * hardware Bitmaps.\n *\n *

Prior to P, the limit per process was 1024 FDs. In P, the limit was updated to 32k FDs per\n * process.\n *\n *

Access to this variable will be removed in a future version without deprecation.\n */\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O = 700;\n // 20k.\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P = 20000;\n\n private static volatile HardwareConfigState instance;\n\n private final boolean isHardwareConfigAllowedByDeviceModel;\n private final int fdCountLimit;\n private final int minHardwareDimension;\n\n @GuardedBy(\"this\")\n private int decodesSinceLastFdCheck;\n\n @GuardedBy(\"this\")\n private boolean isFdSizeBelowHardwareLimit = true;\n\n public static HardwareConfigState getInstance() {\n if (instance == null) {\n synchronized (HardwareConfigState.class) {\n if (instance == null) {\n instance = new HardwareConfigState();\n }\n }\n }\n return instance;\n }\n\n @VisibleForTesting\n HardwareConfigState() {\n isHardwareConfigAllowedByDeviceModel = isHardwareConfigAllowedByDeviceModel();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_P;\n } else {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_O;\n }\n }\n\n public boolean isHardwareConfigAllowed(\n int targetWidth,\n int targetHeight,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n if (!isHardwareConfigAllowed\n || !isHardwareConfigAllowedByDeviceModel\n || Build.VERSION.SDK_INT < Build.VERSION_CODES.O\n || isExifOrientationRequired) {\n return false;\n }\n\n return targetWidth >= minHardwareDimension\n && targetHeight >= minHardwareDimension\n // Make sure to call isFdSizeBelowHardwareLimit last because it has side affects.\n && isFdSizeBelowHardwareLimit();\n }\n\n @TargetApi(Build.VERSION_CODES.O)\n boolean setHardwareConfigIfAllowed(\n int targetWidth,\n int targetHeight,\n BitmapFactory.Options optionsWithScaling,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n boolean result =\n isHardwareConfigAllowed(\n targetWidth, targetHeight, isHardwareConfigAllowed, isExifOrientationRequired);\n if (result) {\n optionsWithScaling.inPreferredConfig = Bitmap.Config.HARDWARE;\n optionsWithScaling.inMutable = false;\n }\n<|edits_diff|>\n--- library/src/main/java/com/bumptech/glide/load/resource/bitmap/HardwareConfigState.java\n+++ library/src/main/java/com/bumptech/glide/load/resource/bitmap/HardwareConfigState.java\n@@ -20,6 +20,7 @@\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P = 20000;\n \n private static volatile HardwareConfigState instance;\n+ private static volatile boolean waitForFirstFrame;\n \n private final boolean isHardwareConfigAllowedByDeviceModel;\n private final int fdCountLimit;\n@@ -30,6 +31,8 @@\n \n @GuardedBy(\"this\")\n private boolean isFdSizeBelowHardwareLimit = true;\n+\n+ private volatile boolean isFirstFrameDrawn;\n \n public static HardwareConfigState getInstance() {\n if (instance == null) {\n<|current_version|>\n private static final File FD_SIZE_LIST = new File(\"/proc/self/fd\");\n\n /**\n * Each FD check takes 1-2ms, so to avoid overhead, only check every N decodes. 50 is more or less\n * arbitrary.\n */\n private static final int MINIMUM_DECODES_BETWEEN_FD_CHECKS = 50;\n\n /**\n * 700 with an error of 50 Bitmaps in between at two FDs each lets us use up to 800 FDs for\n * hardware Bitmaps.\n *\n *

Prior to P, the limit per process was 1024 FDs. In P, the limit was updated to 32k FDs per\n * process.\n *\n *

Access to this variable will be removed in a future version without deprecation.\n */\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O = 700;\n // 20k.\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P = 20000;\n\n private static volatile HardwareConfigState instance;\n private static volatile boolean waitForFirstFrame;\n\n private final boolean isHardwareConfigAllowedByDeviceModel;\n private final int fdCountLimit;\n private final int minHardwareDimension;\n\n @GuardedBy(\"this\")\n private int decodesSinceLastFdCheck;\n\n @GuardedBy(\"this\")\n private boolean isFdSizeBelowHardwareLimit = true;\n\n private volatile boolean isFirstFrameDrawn;\n\n public static HardwareConfigState getInstance() {\n if (instance == null) {\n synchronized (HardwareConfigState.class) {\n if (instance == null) {\n instance = new HardwareConfigState();\n }\n }\n }\n return instance;\n }\n\n @VisibleForTesting\n HardwareConfigState() {\n isHardwareConfigAllowedByDeviceModel = isHardwareConfigAllowedByDeviceModel();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_P;\n } else {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_O;\n }\n }\n\n public boolean isHardwareConfigAllowed(\n int targetWidth,\n int targetHeight,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n if (!isHardwareConfigAllowed\n || !isHardwareConfigAllowedByDeviceModel\n || Build.VERSION.SDK_INT < Build.VERSION_CODES.O\n || isExifOrientationRequired) {\n return false;\n }\n\n return targetWidth >= minHardwareDimension\n && targetHeight >= minHardwareDimension\n // Make sure to call isFdSizeBelowHardwareLimit last because it has side affects.\n && isFdSizeBelowHardwareLimit();\n }\n\n @TargetApi(Build.VERSION_CODES.O)\n boolean setHardwareConfigIfAllowed(\n int targetWidth,\n int targetHeight,\n BitmapFactory.Options optionsWithScaling,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n boolean result =\n isHardwareConfigAllowed(\n targetWidth, targetHeight, isHardwareConfigAllowed, isExifOrientationRequired);\n if (result) {\n optionsWithScaling.inPreferredConfig = Bitmap.Config.HARDWARE;\n optionsWithScaling.inMutable = false;\n }\n<|next_version|>\n private static final File FD_SIZE_LIST = new File(\"/proc/self/fd\");\n\n /**\n * Each FD check takes 1-2ms, so to avoid overhead, only check every N decodes. 50 is more or less\n * arbitrary.\n */\n private static final int MINIMUM_DECODES_BETWEEN_FD_CHECKS = 50;\n\n /**\n * 700 with an error of 50 Bitmaps in between at two FDs each lets us use up to 800 FDs for\n * hardware Bitmaps.\n *\n *

Prior to P, the limit per process was 1024 FDs. In P, the limit was updated to 32k FDs per\n * process.\n *\n *

Access to this variable will be removed in a future version without deprecation.\n */\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O = 700;\n // 20k.\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P = 20000;\n\n private static volatile HardwareConfigState instance;\n private static volatile boolean waitForFirstFrame;\n\n private final boolean isHardwareConfigAllowedByDeviceModel;\n private final int fdCountLimit;\n private final int minHardwareDimension;\n\n @GuardedBy(\"this\")\n private int decodesSinceLastFdCheck;\n\n @GuardedBy(\"this\")\n private boolean isFdSizeBelowHardwareLimit = true;\n\n private volatile boolean isFirstFrameDrawn;\n\n public static HardwareConfigState getInstance() {\n if (instance == null) {\n synchronized (HardwareConfigState.class) {\n if (instance == null) {\n instance = new HardwareConfigState();\n }\n }\n }\n return instance;\n }\n\n @VisibleForTesting\n HardwareConfigState() {\n isHardwareConfigAllowedByDeviceModel = isHardwareConfigAllowedByDeviceModel();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_P;\n } else {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_O;\n }\n }\n\n public boolean isHardwareConfigAllowed(\n int targetWidth,\n int targetHeight,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n if (!isHardwareConfigAllowed\n || !isHardwareConfigAllowedByDeviceModel\n || Build.VERSION.SDK_INT < Build.VERSION_CODES.O\n || (waitForFirstFrame && !isFirstFrameDrawn)\n || isExifOrientationRequired) {\n return false;\n }\n\n return targetWidth >= minHardwareDimension\n && targetHeight >= minHardwareDimension\n // Make sure to call isFdSizeBelowHardwareLimit last because it has side affects.\n && isFdSizeBelowHardwareLimit();\n }\n\n @TargetApi(Build.VERSION_CODES.O)\n boolean setHardwareConfigIfAllowed(\n int targetWidth,\n int targetHeight,\n BitmapFactory.Options optionsWithScaling,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n boolean result =\n isHardwareConfigAllowed(\n targetWidth, targetHeight, isHardwareConfigAllowed, isExifOrientationRequired);\n if (result) {\n optionsWithScaling.inPreferredConfig = Bitmap.Config.HARDWARE;\n optionsWithScaling.inMutable = false;\n }\n", "current_contents": " private static final File FD_SIZE_LIST = new File(\"/proc/self/fd\");\n\n /**\n * Each FD check takes 1-2ms, so to avoid overhead, only check every N decodes. 50 is more or less\n * arbitrary.\n */\n private static final int MINIMUM_DECODES_BETWEEN_FD_CHECKS = 50;\n\n /**\n * 700 with an error of 50 Bitmaps in between at two FDs each lets us use up to 800 FDs for\n * hardware Bitmaps.\n *\n *

Prior to P, the limit per process was 1024 FDs. In P, the limit was updated to 32k FDs per\n * process.\n *\n *

Access to this variable will be removed in a future version without deprecation.\n */\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O = 700;\n // 20k.\n private static final int MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P = 20000;\n\n private static volatile HardwareConfigState instance;\n private static volatile boolean waitForFirstFrame;\n\n private final boolean isHardwareConfigAllowedByDeviceModel;\n private final int fdCountLimit;\n private final int minHardwareDimension;\n\n @GuardedBy(\"this\")\n private int decodesSinceLastFdCheck;\n\n @GuardedBy(\"this\")\n private boolean isFdSizeBelowHardwareLimit = true;\n\n private volatile boolean isFirstFrameDrawn;\n\n public static HardwareConfigState getInstance() {\n if (instance == null) {\n synchronized (HardwareConfigState.class) {\n if (instance == null) {\n instance = new HardwareConfigState();\n }\n }\n }\n return instance;\n }\n\n @VisibleForTesting\n HardwareConfigState() {\n isHardwareConfigAllowedByDeviceModel = isHardwareConfigAllowedByDeviceModel();\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_P;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_P;\n } else {\n fdCountLimit = MAXIMUM_FDS_FOR_HARDWARE_CONFIGS_O;\n minHardwareDimension = MIN_HARDWARE_DIMENSION_O;\n }\n }\n\n public boolean isHardwareConfigAllowed(\n int targetWidth,\n int targetHeight,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n if (!isHardwareConfigAllowed\n || !isHardwareConfigAllowedByDeviceModel\n || Build.VERSION.SDK_INT < Build.VERSION_CODES.O\n || isExifOrientationRequired) {\n return false;\n }\n\n return targetWidth >= minHardwareDimension\n && targetHeight >= minHardwareDimension\n // Make sure to call isFdSizeBelowHardwareLimit last because it has side affects.\n && isFdSizeBelowHardwareLimit();\n }\n\n @TargetApi(Build.VERSION_CODES.O)\n boolean setHardwareConfigIfAllowed(\n int targetWidth,\n int targetHeight,\n BitmapFactory.Options optionsWithScaling,\n boolean isHardwareConfigAllowed,\n boolean isExifOrientationRequired) {\n boolean result =\n isHardwareConfigAllowed(\n targetWidth, targetHeight, isHardwareConfigAllowed, isExifOrientationRequired);\n if (result) {\n optionsWithScaling.inPreferredConfig = Bitmap.Config.HARDWARE;\n optionsWithScaling.inMutable = false;\n }"} {"commit": "fb672a54e11739454f34430f856a9eeb2ea0244f", "message": "Annotate tests to use Robolectric's LEGACY LooperMode.", "old_file": "library/test/src/test/java/com/bumptech/glide/load/resource/gif/ByteBufferGifDecoderTest.java", "new_file": "library/test/src/test/java/com/bumptech/glide/load/resource/gif/ByteBufferGifDecoderTest.java", "status": "M", "old_contents": "package com.bumptech.glide.load.resource.gif;\n\nimport static com.google.common.truth.Truth.assertThat;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.gifdecoder.GifHeader;\nimport com.bumptech.glide.gifdecoder.GifHeaderParser;\nimport com.bumptech.glide.load.ImageHeaderParser;\nimport com.bumptech.glide.load.Options;\nimport com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;\nimport com.bumptech.glide.load.engine.bitmap_recycle.LruArrayPool;\nimport com.bumptech.glide.load.resource.bitmap.DefaultImageHeaderParser;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18, shadows = GlideShadowLooper.class)\npublic class ByteBufferGifDecoderTest {\n private static final byte[] GIF_HEADER = new byte[] {0x47, 0x49, 0x46};\n private static final int ARRAY_POOL_SIZE_BYTES = 4 * 1024 * 1024;\n\n private ByteBufferGifDecoder decoder;\n private GifHeader gifHeader;\n private Options options;\n\n @Mock private BitmapPool bitmapPool;\n @Mock private GifHeaderParser parser;\n @Mock private GifDecoder gifDecoder;\n @Mock private ByteBufferGifDecoder.GifHeaderParserPool parserPool;\n @Mock private ByteBufferGifDecoder.GifDecoderFactory decoderFactory;\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n\n gifHeader = Mockito.spy(new GifHeader());\n when(parser.parseHeader()).thenReturn(gifHeader);\n when(parserPool.obtain(isA(ByteBuffer.class))).thenReturn(parser);\n", "new_contents": "package com.bumptech.glide.load.resource.gif;\n\nimport static com.google.common.truth.Truth.assertThat;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\nimport static org.robolectric.annotation.LooperMode.Mode.LEGACY;\n\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.gifdecoder.GifHeader;\nimport com.bumptech.glide.gifdecoder.GifHeaderParser;\nimport com.bumptech.glide.load.ImageHeaderParser;\nimport com.bumptech.glide.load.Options;\nimport com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;\nimport com.bumptech.glide.load.engine.bitmap_recycle.LruArrayPool;\nimport com.bumptech.glide.load.resource.bitmap.DefaultImageHeaderParser;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.LooperMode;\n\n@LooperMode(LEGACY)\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18, shadows = GlideShadowLooper.class)\npublic class ByteBufferGifDecoderTest {\n private static final byte[] GIF_HEADER = new byte[] {0x47, 0x49, 0x46};\n private static final int ARRAY_POOL_SIZE_BYTES = 4 * 1024 * 1024;\n\n private ByteBufferGifDecoder decoder;\n private GifHeader gifHeader;\n private Options options;\n\n @Mock private BitmapPool bitmapPool;\n @Mock private GifHeaderParser parser;\n @Mock private GifDecoder gifDecoder;\n @Mock private ByteBufferGifDecoder.GifHeaderParserPool parserPool;\n @Mock private ByteBufferGifDecoder.GifDecoderFactory decoderFactory;\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n\n gifHeader = Mockito.spy(new GifHeader());\n when(parser.parseHeader()).thenReturn(gifHeader);\n when(parserPool.obtain(isA(ByteBuffer.class))).thenReturn(parser);\n", "text": "<|original_code|>\npackage com.bumptech.glide.load.resource.gif;\n\nimport static com.google.common.truth.Truth.assertThat;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.gifdecoder.GifHeader;\nimport com.bumptech.glide.gifdecoder.GifHeaderParser;\nimport com.bumptech.glide.load.ImageHeaderParser;\nimport com.bumptech.glide.load.Options;\nimport com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;\nimport com.bumptech.glide.load.engine.bitmap_recycle.LruArrayPool;\nimport com.bumptech.glide.load.resource.bitmap.DefaultImageHeaderParser;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18, shadows = GlideShadowLooper.class)\npublic class ByteBufferGifDecoderTest {\n private static final byte[] GIF_HEADER = new byte[] {0x47, 0x49, 0x46};\n private static final int ARRAY_POOL_SIZE_BYTES = 4 * 1024 * 1024;\n\n private ByteBufferGifDecoder decoder;\n private GifHeader gifHeader;\n private Options options;\n\n @Mock private BitmapPool bitmapPool;\n @Mock private GifHeaderParser parser;\n @Mock private GifDecoder gifDecoder;\n @Mock private ByteBufferGifDecoder.GifHeaderParserPool parserPool;\n @Mock private ByteBufferGifDecoder.GifDecoderFactory decoderFactory;\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n\n gifHeader = Mockito.spy(new GifHeader());\n when(parser.parseHeader()).thenReturn(gifHeader);\n when(parserPool.obtain(isA(ByteBuffer.class))).thenReturn(parser);\n\n<|edits_diff|>\n--- library/test/src/test/java/com/bumptech/glide/load/resource/gif/ByteBufferGifDecoderTest.java\n+++ library/test/src/test/java/com/bumptech/glide/load/resource/gif/ByteBufferGifDecoderTest.java\n@@ -8,6 +8,7 @@\n import static org.mockito.ArgumentMatchers.isA;\n import static org.mockito.Mockito.verify;\n import static org.mockito.Mockito.when;\n+import static org.robolectric.annotation.LooperMode.Mode.LEGACY;\n \n import com.bumptech.glide.gifdecoder.GifDecoder;\n import com.bumptech.glide.gifdecoder.GifHeader;\n@@ -31,6 +32,7 @@\n import org.robolectric.RobolectricTestRunner;\n import org.robolectric.RuntimeEnvironment;\n import org.robolectric.annotation.Config;\n+import org.robolectric.annotation.LooperMode;\n \n @RunWith(RobolectricTestRunner.class)\n @Config(sdk = 18, shadows = GlideShadowLooper.class)\n<|current_version|>\npackage com.bumptech.glide.load.resource.gif;\n\nimport static com.google.common.truth.Truth.assertThat;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\nimport static org.robolectric.annotation.LooperMode.Mode.LEGACY;\n\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.gifdecoder.GifHeader;\nimport com.bumptech.glide.gifdecoder.GifHeaderParser;\nimport com.bumptech.glide.load.ImageHeaderParser;\nimport com.bumptech.glide.load.Options;\nimport com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;\nimport com.bumptech.glide.load.engine.bitmap_recycle.LruArrayPool;\nimport com.bumptech.glide.load.resource.bitmap.DefaultImageHeaderParser;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.LooperMode;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18, shadows = GlideShadowLooper.class)\npublic class ByteBufferGifDecoderTest {\n private static final byte[] GIF_HEADER = new byte[] {0x47, 0x49, 0x46};\n private static final int ARRAY_POOL_SIZE_BYTES = 4 * 1024 * 1024;\n\n private ByteBufferGifDecoder decoder;\n private GifHeader gifHeader;\n private Options options;\n\n @Mock private BitmapPool bitmapPool;\n @Mock private GifHeaderParser parser;\n @Mock private GifDecoder gifDecoder;\n @Mock private ByteBufferGifDecoder.GifHeaderParserPool parserPool;\n @Mock private ByteBufferGifDecoder.GifDecoderFactory decoderFactory;\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n\n gifHeader = Mockito.spy(new GifHeader());\n when(parser.parseHeader()).thenReturn(gifHeader);\n when(parserPool.obtain(isA(ByteBuffer.class))).thenReturn(parser);\n\n<|next_version|>\npackage com.bumptech.glide.load.resource.gif;\n\nimport static com.google.common.truth.Truth.assertThat;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\nimport static org.robolectric.annotation.LooperMode.Mode.LEGACY;\n\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.gifdecoder.GifHeader;\nimport com.bumptech.glide.gifdecoder.GifHeaderParser;\nimport com.bumptech.glide.load.ImageHeaderParser;\nimport com.bumptech.glide.load.Options;\nimport com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;\nimport com.bumptech.glide.load.engine.bitmap_recycle.LruArrayPool;\nimport com.bumptech.glide.load.resource.bitmap.DefaultImageHeaderParser;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.LooperMode;\n\n@LooperMode(LEGACY)\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18, shadows = GlideShadowLooper.class)\npublic class ByteBufferGifDecoderTest {\n private static final byte[] GIF_HEADER = new byte[] {0x47, 0x49, 0x46};\n private static final int ARRAY_POOL_SIZE_BYTES = 4 * 1024 * 1024;\n\n private ByteBufferGifDecoder decoder;\n private GifHeader gifHeader;\n private Options options;\n\n @Mock private BitmapPool bitmapPool;\n @Mock private GifHeaderParser parser;\n @Mock private GifDecoder gifDecoder;\n @Mock private ByteBufferGifDecoder.GifHeaderParserPool parserPool;\n @Mock private ByteBufferGifDecoder.GifDecoderFactory decoderFactory;\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n\n gifHeader = Mockito.spy(new GifHeader());\n when(parser.parseHeader()).thenReturn(gifHeader);\n when(parserPool.obtain(isA(ByteBuffer.class))).thenReturn(parser);\n\n", "current_contents": "package com.bumptech.glide.load.resource.gif;\n\nimport static com.google.common.truth.Truth.assertThat;\nimport static org.junit.Assert.assertNull;\nimport static org.junit.Assert.fail;\nimport static org.mockito.ArgumentMatchers.anyInt;\nimport static org.mockito.ArgumentMatchers.eq;\nimport static org.mockito.ArgumentMatchers.isA;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\nimport static org.robolectric.annotation.LooperMode.Mode.LEGACY;\n\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.gifdecoder.GifHeader;\nimport com.bumptech.glide.gifdecoder.GifHeaderParser;\nimport com.bumptech.glide.load.ImageHeaderParser;\nimport com.bumptech.glide.load.Options;\nimport com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;\nimport com.bumptech.glide.load.engine.bitmap_recycle.LruArrayPool;\nimport com.bumptech.glide.load.resource.bitmap.DefaultImageHeaderParser;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport java.io.IOException;\nimport java.nio.ByteBuffer;\nimport java.util.ArrayList;\nimport java.util.List;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.Mockito;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.LooperMode;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(sdk = 18, shadows = GlideShadowLooper.class)\npublic class ByteBufferGifDecoderTest {\n private static final byte[] GIF_HEADER = new byte[] {0x47, 0x49, 0x46};\n private static final int ARRAY_POOL_SIZE_BYTES = 4 * 1024 * 1024;\n\n private ByteBufferGifDecoder decoder;\n private GifHeader gifHeader;\n private Options options;\n\n @Mock private BitmapPool bitmapPool;\n @Mock private GifHeaderParser parser;\n @Mock private GifDecoder gifDecoder;\n @Mock private ByteBufferGifDecoder.GifHeaderParserPool parserPool;\n @Mock private ByteBufferGifDecoder.GifDecoderFactory decoderFactory;\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n\n gifHeader = Mockito.spy(new GifHeader());\n when(parser.parseHeader()).thenReturn(gifHeader);\n when(parserPool.obtain(isA(ByteBuffer.class))).thenReturn(parser);\n"} {"commit": "37127f0f817d4a11dfdcc447946397b5288de593", "message": "Add global/activity/fragment scoped RequestListener API to Glide.", "old_file": "library/src/main/java/com/bumptech/glide/GlideContext.java", "new_file": "library/src/main/java/com/bumptech/glide/GlideContext.java", "status": "M", "old_contents": "package com.bumptech.glide;\n\nimport android.content.Context;\nimport android.content.ContextWrapper;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.VisibleForTesting;\nimport android.widget.ImageView;\nimport com.bumptech.glide.load.engine.Engine;\nimport com.bumptech.glide.load.engine.bitmap_recycle.ArrayPool;\nimport com.bumptech.glide.request.RequestOptions;\nimport com.bumptech.glide.request.target.ImageViewTargetFactory;\nimport com.bumptech.glide.request.target.ViewTarget;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * Global context for all loads in Glide containing and exposing the various registries and classes\n * required to load resources.\n */\npublic class GlideContext extends ContextWrapper {\n @VisibleForTesting\n static final TransitionOptions DEFAULT_TRANSITION_OPTIONS =\n new GenericTransitionOptions<>();\n private final Handler mainHandler;\n private final ArrayPool arrayPool;\n private final Registry registry;\n private final ImageViewTargetFactory imageViewTargetFactory;\n private final RequestOptions defaultRequestOptions;\n private final Map, TransitionOptions> defaultTransitionOptions;\n private final Engine engine;\n private final int logLevel;\n\n public GlideContext(\n @NonNull Context context,\n @NonNull ArrayPool arrayPool,\n @NonNull Registry registry,\n @NonNull ImageViewTargetFactory imageViewTargetFactory,\n @NonNull RequestOptions defaultRequestOptions,\n @NonNull Map, TransitionOptions> defaultTransitionOptions,\n @NonNull Engine engine,\n int logLevel) {\n super(context.getApplicationContext());\n this.arrayPool = arrayPool;\n this.registry = registry;\n this.imageViewTargetFactory = imageViewTargetFactory;\n this.defaultRequestOptions = defaultRequestOptions;\n this.defaultTransitionOptions = defaultTransitionOptions;\n this.engine = engine;\n this.logLevel = logLevel;\n\n mainHandler = new Handler(Looper.getMainLooper());\n }\n\n public RequestOptions getDefaultRequestOptions() {\n return defaultRequestOptions;\n }\n\n @SuppressWarnings(\"unchecked\")\n @NonNull\n public TransitionOptions getDefaultTransitionOptions(@NonNull Class transcodeClass) {\n TransitionOptions result = defaultTransitionOptions.get(transcodeClass);\n if (result == null) {\n for (Entry, TransitionOptions> value : defaultTransitionOptions.entrySet()) {\n if (value.getKey().isAssignableFrom(transcodeClass)) {\n result = value.getValue();\n }\n }\n }\n if (result == null) {\n result = DEFAULT_TRANSITION_OPTIONS;\n }\n return (TransitionOptions) result;\n }\n\n @NonNull", "new_contents": "package com.bumptech.glide;\n\nimport android.content.Context;\nimport android.content.ContextWrapper;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.VisibleForTesting;\nimport android.widget.ImageView;\nimport com.bumptech.glide.load.engine.Engine;\nimport com.bumptech.glide.load.engine.bitmap_recycle.ArrayPool;\nimport com.bumptech.glide.request.RequestListener;\nimport com.bumptech.glide.request.RequestOptions;\nimport com.bumptech.glide.request.target.ImageViewTargetFactory;\nimport com.bumptech.glide.request.target.ViewTarget;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * Global context for all loads in Glide containing and exposing the various registries and classes\n * required to load resources.\n */\npublic class GlideContext extends ContextWrapper {\n @VisibleForTesting\n static final TransitionOptions DEFAULT_TRANSITION_OPTIONS =\n new GenericTransitionOptions<>();\n private final Handler mainHandler;\n private final ArrayPool arrayPool;\n private final Registry registry;\n private final ImageViewTargetFactory imageViewTargetFactory;\n private final RequestOptions defaultRequestOptions;\n private final List> defaultRequestListeners;\n private final Map, TransitionOptions> defaultTransitionOptions;\n private final Engine engine;\n private final int logLevel;\n\n public GlideContext(\n @NonNull Context context,\n @NonNull ArrayPool arrayPool,\n @NonNull Registry registry,\n @NonNull ImageViewTargetFactory imageViewTargetFactory,\n @NonNull RequestOptions defaultRequestOptions,\n @NonNull Map, TransitionOptions> defaultTransitionOptions,\n @NonNull List> defaultRequestListeners,\n @NonNull Engine engine,\n int logLevel) {\n super(context.getApplicationContext());\n this.arrayPool = arrayPool;\n this.registry = registry;\n this.imageViewTargetFactory = imageViewTargetFactory;\n this.defaultRequestOptions = defaultRequestOptions;\n this.defaultRequestListeners = defaultRequestListeners;\n this.defaultTransitionOptions = defaultTransitionOptions;\n this.engine = engine;\n this.logLevel = logLevel;\n\n mainHandler = new Handler(Looper.getMainLooper());\n }\n\n public List> getDefaultRequestListeners() {\n return defaultRequestListeners;\n }\n\n public RequestOptions getDefaultRequestOptions() {\n return defaultRequestOptions;\n }\n\n @SuppressWarnings(\"unchecked\")\n @NonNull\n public TransitionOptions getDefaultTransitionOptions(@NonNull Class transcodeClass) {\n TransitionOptions result = defaultTransitionOptions.get(transcodeClass);\n if (result == null) {\n for (Entry, TransitionOptions> value : defaultTransitionOptions.entrySet()) {\n if (value.getKey().isAssignableFrom(transcodeClass)) {\n result = value.getValue();\n }\n }\n }\n if (result == null) {\n result = DEFAULT_TRANSITION_OPTIONS;\n }\n return (TransitionOptions) result;\n }\n\n @NonNull", "text": "<|original_code|>\npackage com.bumptech.glide;\n\nimport android.content.Context;\nimport android.content.ContextWrapper;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.VisibleForTesting;\nimport android.widget.ImageView;\nimport com.bumptech.glide.load.engine.Engine;\nimport com.bumptech.glide.load.engine.bitmap_recycle.ArrayPool;\nimport com.bumptech.glide.request.RequestOptions;\nimport com.bumptech.glide.request.target.ImageViewTargetFactory;\nimport com.bumptech.glide.request.target.ViewTarget;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * Global context for all loads in Glide containing and exposing the various registries and classes\n * required to load resources.\n */\npublic class GlideContext extends ContextWrapper {\n @VisibleForTesting\n static final TransitionOptions DEFAULT_TRANSITION_OPTIONS =\n new GenericTransitionOptions<>();\n private final Handler mainHandler;\n private final ArrayPool arrayPool;\n private final Registry registry;\n private final ImageViewTargetFactory imageViewTargetFactory;\n private final RequestOptions defaultRequestOptions;\n private final Map, TransitionOptions> defaultTransitionOptions;\n private final Engine engine;\n private final int logLevel;\n\n public GlideContext(\n @NonNull Context context,\n @NonNull ArrayPool arrayPool,\n @NonNull Registry registry,\n @NonNull ImageViewTargetFactory imageViewTargetFactory,\n @NonNull RequestOptions defaultRequestOptions,\n @NonNull Map, TransitionOptions> defaultTransitionOptions,\n @NonNull Engine engine,\n int logLevel) {\n super(context.getApplicationContext());\n this.arrayPool = arrayPool;\n this.registry = registry;\n this.imageViewTargetFactory = imageViewTargetFactory;\n this.defaultRequestOptions = defaultRequestOptions;\n this.defaultTransitionOptions = defaultTransitionOptions;\n this.engine = engine;\n this.logLevel = logLevel;\n\n mainHandler = new Handler(Looper.getMainLooper());\n }\n\n public RequestOptions getDefaultRequestOptions() {\n return defaultRequestOptions;\n }\n\n @SuppressWarnings(\"unchecked\")\n @NonNull\n public TransitionOptions getDefaultTransitionOptions(@NonNull Class transcodeClass) {\n TransitionOptions result = defaultTransitionOptions.get(transcodeClass);\n if (result == null) {\n for (Entry, TransitionOptions> value : defaultTransitionOptions.entrySet()) {\n if (value.getKey().isAssignableFrom(transcodeClass)) {\n result = value.getValue();\n }\n }\n }\n if (result == null) {\n result = DEFAULT_TRANSITION_OPTIONS;\n }\n return (TransitionOptions) result;\n }\n\n @NonNull\n<|edits_diff|>\n--- library/src/main/java/com/bumptech/glide/GlideContext.java\n+++ library/src/main/java/com/bumptech/glide/GlideContext.java\n@@ -9,9 +9,11 @@\n import android.widget.ImageView;\n import com.bumptech.glide.load.engine.Engine;\n import com.bumptech.glide.load.engine.bitmap_recycle.ArrayPool;\n+import com.bumptech.glide.request.RequestListener;\n import com.bumptech.glide.request.RequestOptions;\n import com.bumptech.glide.request.target.ImageViewTargetFactory;\n import com.bumptech.glide.request.target.ViewTarget;\n+import java.util.List;\n import java.util.Map;\n import java.util.Map.Entry;\n \n@@ -28,6 +30,7 @@\n private final Registry registry;\n private final ImageViewTargetFactory imageViewTargetFactory;\n private final RequestOptions defaultRequestOptions;\n+ private final List> defaultRequestListeners;\n private final Map, TransitionOptions> defaultTransitionOptions;\n private final Engine engine;\n private final int logLevel;\n@@ -39,6 +42,7 @@\n @NonNull ImageViewTargetFactory imageViewTargetFactory,\n @NonNull RequestOptions defaultRequestOptions,\n @NonNull Map, TransitionOptions> defaultTransitionOptions,\n+ @NonNull List> defaultRequestListeners,\n @NonNull Engine engine,\n int logLevel) {\n super(context.getApplicationContext());\n@@ -46,6 +50,7 @@\n this.registry = registry;\n this.imageViewTargetFactory = imageViewTargetFactory;\n this.defaultRequestOptions = defaultRequestOptions;\n+ this.defaultRequestListeners = defaultRequestListeners;\n this.defaultTransitionOptions = defaultTransitionOptions;\n this.engine = engine;\n this.logLevel = logLevel;\n<|current_version|>\npackage com.bumptech.glide;\n\nimport android.content.Context;\nimport android.content.ContextWrapper;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.VisibleForTesting;\nimport android.widget.ImageView;\nimport com.bumptech.glide.load.engine.Engine;\nimport com.bumptech.glide.load.engine.bitmap_recycle.ArrayPool;\nimport com.bumptech.glide.request.RequestListener;\nimport com.bumptech.glide.request.RequestOptions;\nimport com.bumptech.glide.request.target.ImageViewTargetFactory;\nimport com.bumptech.glide.request.target.ViewTarget;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * Global context for all loads in Glide containing and exposing the various registries and classes\n * required to load resources.\n */\npublic class GlideContext extends ContextWrapper {\n @VisibleForTesting\n static final TransitionOptions DEFAULT_TRANSITION_OPTIONS =\n new GenericTransitionOptions<>();\n private final Handler mainHandler;\n private final ArrayPool arrayPool;\n private final Registry registry;\n private final ImageViewTargetFactory imageViewTargetFactory;\n private final RequestOptions defaultRequestOptions;\n private final List> defaultRequestListeners;\n private final Map, TransitionOptions> defaultTransitionOptions;\n private final Engine engine;\n private final int logLevel;\n\n public GlideContext(\n @NonNull Context context,\n @NonNull ArrayPool arrayPool,\n @NonNull Registry registry,\n @NonNull ImageViewTargetFactory imageViewTargetFactory,\n @NonNull RequestOptions defaultRequestOptions,\n @NonNull Map, TransitionOptions> defaultTransitionOptions,\n @NonNull List> defaultRequestListeners,\n @NonNull Engine engine,\n int logLevel) {\n super(context.getApplicationContext());\n this.arrayPool = arrayPool;\n this.registry = registry;\n this.imageViewTargetFactory = imageViewTargetFactory;\n this.defaultRequestOptions = defaultRequestOptions;\n this.defaultRequestListeners = defaultRequestListeners;\n this.defaultTransitionOptions = defaultTransitionOptions;\n this.engine = engine;\n this.logLevel = logLevel;\n\n mainHandler = new Handler(Looper.getMainLooper());\n }\n\n public RequestOptions getDefaultRequestOptions() {\n return defaultRequestOptions;\n }\n\n @SuppressWarnings(\"unchecked\")\n @NonNull\n public TransitionOptions getDefaultTransitionOptions(@NonNull Class transcodeClass) {\n TransitionOptions result = defaultTransitionOptions.get(transcodeClass);\n if (result == null) {\n for (Entry, TransitionOptions> value : defaultTransitionOptions.entrySet()) {\n if (value.getKey().isAssignableFrom(transcodeClass)) {\n result = value.getValue();\n }\n }\n }\n if (result == null) {\n result = DEFAULT_TRANSITION_OPTIONS;\n }\n return (TransitionOptions) result;\n }\n\n @NonNull\n<|next_version|>\npackage com.bumptech.glide;\n\nimport android.content.Context;\nimport android.content.ContextWrapper;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.VisibleForTesting;\nimport android.widget.ImageView;\nimport com.bumptech.glide.load.engine.Engine;\nimport com.bumptech.glide.load.engine.bitmap_recycle.ArrayPool;\nimport com.bumptech.glide.request.RequestListener;\nimport com.bumptech.glide.request.RequestOptions;\nimport com.bumptech.glide.request.target.ImageViewTargetFactory;\nimport com.bumptech.glide.request.target.ViewTarget;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * Global context for all loads in Glide containing and exposing the various registries and classes\n * required to load resources.\n */\npublic class GlideContext extends ContextWrapper {\n @VisibleForTesting\n static final TransitionOptions DEFAULT_TRANSITION_OPTIONS =\n new GenericTransitionOptions<>();\n private final Handler mainHandler;\n private final ArrayPool arrayPool;\n private final Registry registry;\n private final ImageViewTargetFactory imageViewTargetFactory;\n private final RequestOptions defaultRequestOptions;\n private final List> defaultRequestListeners;\n private final Map, TransitionOptions> defaultTransitionOptions;\n private final Engine engine;\n private final int logLevel;\n\n public GlideContext(\n @NonNull Context context,\n @NonNull ArrayPool arrayPool,\n @NonNull Registry registry,\n @NonNull ImageViewTargetFactory imageViewTargetFactory,\n @NonNull RequestOptions defaultRequestOptions,\n @NonNull Map, TransitionOptions> defaultTransitionOptions,\n @NonNull List> defaultRequestListeners,\n @NonNull Engine engine,\n int logLevel) {\n super(context.getApplicationContext());\n this.arrayPool = arrayPool;\n this.registry = registry;\n this.imageViewTargetFactory = imageViewTargetFactory;\n this.defaultRequestOptions = defaultRequestOptions;\n this.defaultRequestListeners = defaultRequestListeners;\n this.defaultTransitionOptions = defaultTransitionOptions;\n this.engine = engine;\n this.logLevel = logLevel;\n\n mainHandler = new Handler(Looper.getMainLooper());\n }\n\n public List> getDefaultRequestListeners() {\n return defaultRequestListeners;\n }\n\n public RequestOptions getDefaultRequestOptions() {\n return defaultRequestOptions;\n }\n\n @SuppressWarnings(\"unchecked\")\n @NonNull\n public TransitionOptions getDefaultTransitionOptions(@NonNull Class transcodeClass) {\n TransitionOptions result = defaultTransitionOptions.get(transcodeClass);\n if (result == null) {\n for (Entry, TransitionOptions> value : defaultTransitionOptions.entrySet()) {\n if (value.getKey().isAssignableFrom(transcodeClass)) {\n result = value.getValue();\n }\n }\n }\n if (result == null) {\n result = DEFAULT_TRANSITION_OPTIONS;\n }\n return (TransitionOptions) result;\n }\n\n @NonNull\n", "current_contents": "package com.bumptech.glide;\n\nimport android.content.Context;\nimport android.content.ContextWrapper;\nimport android.os.Handler;\nimport android.os.Looper;\nimport android.support.annotation.NonNull;\nimport android.support.annotation.VisibleForTesting;\nimport android.widget.ImageView;\nimport com.bumptech.glide.load.engine.Engine;\nimport com.bumptech.glide.load.engine.bitmap_recycle.ArrayPool;\nimport com.bumptech.glide.request.RequestListener;\nimport com.bumptech.glide.request.RequestOptions;\nimport com.bumptech.glide.request.target.ImageViewTargetFactory;\nimport com.bumptech.glide.request.target.ViewTarget;\nimport java.util.List;\nimport java.util.Map;\nimport java.util.Map.Entry;\n\n/**\n * Global context for all loads in Glide containing and exposing the various registries and classes\n * required to load resources.\n */\npublic class GlideContext extends ContextWrapper {\n @VisibleForTesting\n static final TransitionOptions DEFAULT_TRANSITION_OPTIONS =\n new GenericTransitionOptions<>();\n private final Handler mainHandler;\n private final ArrayPool arrayPool;\n private final Registry registry;\n private final ImageViewTargetFactory imageViewTargetFactory;\n private final RequestOptions defaultRequestOptions;\n private final List> defaultRequestListeners;\n private final Map, TransitionOptions> defaultTransitionOptions;\n private final Engine engine;\n private final int logLevel;\n\n public GlideContext(\n @NonNull Context context,\n @NonNull ArrayPool arrayPool,\n @NonNull Registry registry,\n @NonNull ImageViewTargetFactory imageViewTargetFactory,\n @NonNull RequestOptions defaultRequestOptions,\n @NonNull Map, TransitionOptions> defaultTransitionOptions,\n @NonNull List> defaultRequestListeners,\n @NonNull Engine engine,\n int logLevel) {\n super(context.getApplicationContext());\n this.arrayPool = arrayPool;\n this.registry = registry;\n this.imageViewTargetFactory = imageViewTargetFactory;\n this.defaultRequestOptions = defaultRequestOptions;\n this.defaultRequestListeners = defaultRequestListeners;\n this.defaultTransitionOptions = defaultTransitionOptions;\n this.engine = engine;\n this.logLevel = logLevel;\n\n mainHandler = new Handler(Looper.getMainLooper());\n }\n\n public RequestOptions getDefaultRequestOptions() {\n return defaultRequestOptions;\n }\n\n @SuppressWarnings(\"unchecked\")\n @NonNull\n public TransitionOptions getDefaultTransitionOptions(@NonNull Class transcodeClass) {\n TransitionOptions result = defaultTransitionOptions.get(transcodeClass);\n if (result == null) {\n for (Entry, TransitionOptions> value : defaultTransitionOptions.entrySet()) {\n if (value.getKey().isAssignableFrom(transcodeClass)) {\n result = value.getValue();\n }\n }\n }\n if (result == null) {\n result = DEFAULT_TRANSITION_OPTIONS;\n }\n return (TransitionOptions) result;\n }\n\n @NonNull"} {"commit": "d45956144f72f080675c119a7d21dc1bf6057380", "message": "TearDownGlide in the GifDrawable unit test.", "old_file": "library/test/src/test/java/com/bumptech/glide/load/resource/gif/GifDrawableTest.java", "new_file": "library/test/src/test/java/com/bumptech/glide/load/resource/gif/GifDrawableTest.java", "status": "M", "old_contents": "import static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport android.app.Application;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.ColorFilter;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.PorterDuff.Mode;\nimport android.graphics.PorterDuffColorFilter;\nimport android.graphics.Rect;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.TransitionDrawable;\nimport android.os.Build;\nimport android.view.View;\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.load.Transformation;\nimport com.bumptech.glide.load.resource.gif.GifDrawableTest.BitmapTrackingShadowCanvas;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport com.bumptech.glide.tests.Util;\nimport com.bumptech.glide.util.Preconditions;\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.Implementation;\nimport org.robolectric.annotation.Implements;\nimport org.robolectric.shadow.api.Shadow;\nimport org.robolectric.shadows.ShadowCanvas;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(manifest = Config.NONE, sdk = 18,\n shadows = { GlideShadowLooper.class, BitmapTrackingShadowCanvas.class })\npublic class GifDrawableTest {\n private GifDrawable drawable;\n private int frameHeight;\n private int frameWidth;\n private Bitmap firstFrame;\n private int initialSdkVersion;\n\n @Mock private Drawable.Callback cb;\n @Mock private GifFrameLoader frameLoader;\n @Mock private Paint paint;\n @Mock private Transformation transformation;\n private Application context;\n\n private static Paint isAPaint() {\n return isA(Paint.class);\n }\n\n private static Rect isARect() {\n return isA(Rect.class);\n }\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n context = RuntimeEnvironment.application;", "new_contents": "import static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport android.app.Application;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.ColorFilter;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.PorterDuff.Mode;\nimport android.graphics.PorterDuffColorFilter;\nimport android.graphics.Rect;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.TransitionDrawable;\nimport android.os.Build;\nimport android.view.View;\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.load.Transformation;\nimport com.bumptech.glide.load.resource.gif.GifDrawableTest.BitmapTrackingShadowCanvas;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport com.bumptech.glide.tests.TearDownGlide;\nimport com.bumptech.glide.tests.Util;\nimport com.bumptech.glide.util.Preconditions;\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.Implementation;\nimport org.robolectric.annotation.Implements;\nimport org.robolectric.shadow.api.Shadow;\nimport org.robolectric.shadows.ShadowCanvas;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(manifest = Config.NONE, sdk = 18,\n shadows = { GlideShadowLooper.class, BitmapTrackingShadowCanvas.class })\npublic class GifDrawableTest {\n @Rule public final TearDownGlide tearDownGlide = new TearDownGlide();\n\n private GifDrawable drawable;\n private int frameHeight;\n private int frameWidth;\n private Bitmap firstFrame;\n private int initialSdkVersion;\n\n @Mock private Drawable.Callback cb;\n @Mock private GifFrameLoader frameLoader;\n @Mock private Paint paint;\n @Mock private Transformation transformation;\n private Application context;\n\n private static Paint isAPaint() {\n return isA(Paint.class);\n }\n\n private static Rect isARect() {\n return isA(Rect.class);\n }\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n context = RuntimeEnvironment.application;", "text": "<|original_code|>\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport android.app.Application;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.ColorFilter;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.PorterDuff.Mode;\nimport android.graphics.PorterDuffColorFilter;\nimport android.graphics.Rect;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.TransitionDrawable;\nimport android.os.Build;\nimport android.view.View;\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.load.Transformation;\nimport com.bumptech.glide.load.resource.gif.GifDrawableTest.BitmapTrackingShadowCanvas;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport com.bumptech.glide.tests.Util;\nimport com.bumptech.glide.util.Preconditions;\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.Implementation;\nimport org.robolectric.annotation.Implements;\nimport org.robolectric.shadow.api.Shadow;\nimport org.robolectric.shadows.ShadowCanvas;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(manifest = Config.NONE, sdk = 18,\n shadows = { GlideShadowLooper.class, BitmapTrackingShadowCanvas.class })\npublic class GifDrawableTest {\n private GifDrawable drawable;\n private int frameHeight;\n private int frameWidth;\n private Bitmap firstFrame;\n private int initialSdkVersion;\n\n @Mock private Drawable.Callback cb;\n @Mock private GifFrameLoader frameLoader;\n @Mock private Paint paint;\n @Mock private Transformation transformation;\n private Application context;\n\n private static Paint isAPaint() {\n return isA(Paint.class);\n }\n\n private static Rect isARect() {\n return isA(Rect.class);\n }\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n context = RuntimeEnvironment.application;\n<|edits_diff|>\n--- library/test/src/test/java/com/bumptech/glide/load/resource/gif/GifDrawableTest.java\n+++ library/test/src/test/java/com/bumptech/glide/load/resource/gif/GifDrawableTest.java\n@@ -20,12 +20,14 @@\n import com.bumptech.glide.load.Transformation;\n import com.bumptech.glide.load.resource.gif.GifDrawableTest.BitmapTrackingShadowCanvas;\n import com.bumptech.glide.tests.GlideShadowLooper;\n+import com.bumptech.glide.tests.TearDownGlide;\n import com.bumptech.glide.tests.Util;\n import com.bumptech.glide.util.Preconditions;\n import java.util.HashSet;\n import java.util.Set;\n import org.junit.After;\n import org.junit.Before;\n+import org.junit.Rule;\n import org.junit.Test;\n import org.junit.runner.RunWith;\n import org.mockito.Mock;\n<|current_version|>\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport android.app.Application;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.ColorFilter;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.PorterDuff.Mode;\nimport android.graphics.PorterDuffColorFilter;\nimport android.graphics.Rect;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.TransitionDrawable;\nimport android.os.Build;\nimport android.view.View;\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.load.Transformation;\nimport com.bumptech.glide.load.resource.gif.GifDrawableTest.BitmapTrackingShadowCanvas;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport com.bumptech.glide.tests.TearDownGlide;\nimport com.bumptech.glide.tests.Util;\nimport com.bumptech.glide.util.Preconditions;\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.Implementation;\nimport org.robolectric.annotation.Implements;\nimport org.robolectric.shadow.api.Shadow;\nimport org.robolectric.shadows.ShadowCanvas;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(manifest = Config.NONE, sdk = 18,\n shadows = { GlideShadowLooper.class, BitmapTrackingShadowCanvas.class })\npublic class GifDrawableTest {\n private GifDrawable drawable;\n private int frameHeight;\n private int frameWidth;\n private Bitmap firstFrame;\n private int initialSdkVersion;\n\n @Mock private Drawable.Callback cb;\n @Mock private GifFrameLoader frameLoader;\n @Mock private Paint paint;\n @Mock private Transformation transformation;\n private Application context;\n\n private static Paint isAPaint() {\n return isA(Paint.class);\n }\n\n private static Rect isARect() {\n return isA(Rect.class);\n }\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n context = RuntimeEnvironment.application;\n<|next_version|>\nimport static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport android.app.Application;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.ColorFilter;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.PorterDuff.Mode;\nimport android.graphics.PorterDuffColorFilter;\nimport android.graphics.Rect;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.TransitionDrawable;\nimport android.os.Build;\nimport android.view.View;\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.load.Transformation;\nimport com.bumptech.glide.load.resource.gif.GifDrawableTest.BitmapTrackingShadowCanvas;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport com.bumptech.glide.tests.TearDownGlide;\nimport com.bumptech.glide.tests.Util;\nimport com.bumptech.glide.util.Preconditions;\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.Implementation;\nimport org.robolectric.annotation.Implements;\nimport org.robolectric.shadow.api.Shadow;\nimport org.robolectric.shadows.ShadowCanvas;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(manifest = Config.NONE, sdk = 18,\n shadows = { GlideShadowLooper.class, BitmapTrackingShadowCanvas.class })\npublic class GifDrawableTest {\n @Rule public final TearDownGlide tearDownGlide = new TearDownGlide();\n\n private GifDrawable drawable;\n private int frameHeight;\n private int frameWidth;\n private Bitmap firstFrame;\n private int initialSdkVersion;\n\n @Mock private Drawable.Callback cb;\n @Mock private GifFrameLoader frameLoader;\n @Mock private Paint paint;\n @Mock private Transformation transformation;\n private Application context;\n\n private static Paint isAPaint() {\n return isA(Paint.class);\n }\n\n private static Rect isARect() {\n return isA(Rect.class);\n }\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n context = RuntimeEnvironment.application;\n", "current_contents": "import static org.mockito.Mockito.times;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\nimport android.app.Application;\nimport android.graphics.Bitmap;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.ColorFilter;\nimport android.graphics.Paint;\nimport android.graphics.PixelFormat;\nimport android.graphics.PorterDuff.Mode;\nimport android.graphics.PorterDuffColorFilter;\nimport android.graphics.Rect;\nimport android.graphics.drawable.Drawable;\nimport android.graphics.drawable.TransitionDrawable;\nimport android.os.Build;\nimport android.view.View;\nimport com.bumptech.glide.gifdecoder.GifDecoder;\nimport com.bumptech.glide.load.Transformation;\nimport com.bumptech.glide.load.resource.gif.GifDrawableTest.BitmapTrackingShadowCanvas;\nimport com.bumptech.glide.tests.GlideShadowLooper;\nimport com.bumptech.glide.tests.TearDownGlide;\nimport com.bumptech.glide.tests.Util;\nimport com.bumptech.glide.util.Preconditions;\nimport java.util.HashSet;\nimport java.util.Set;\nimport org.junit.After;\nimport org.junit.Before;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.mockito.Mock;\nimport org.mockito.MockitoAnnotations;\nimport org.robolectric.RobolectricTestRunner;\nimport org.robolectric.RuntimeEnvironment;\nimport org.robolectric.annotation.Config;\nimport org.robolectric.annotation.Implementation;\nimport org.robolectric.annotation.Implements;\nimport org.robolectric.shadow.api.Shadow;\nimport org.robolectric.shadows.ShadowCanvas;\n\n@RunWith(RobolectricTestRunner.class)\n@Config(manifest = Config.NONE, sdk = 18,\n shadows = { GlideShadowLooper.class, BitmapTrackingShadowCanvas.class })\npublic class GifDrawableTest {\n private GifDrawable drawable;\n private int frameHeight;\n private int frameWidth;\n private Bitmap firstFrame;\n private int initialSdkVersion;\n\n @Mock private Drawable.Callback cb;\n @Mock private GifFrameLoader frameLoader;\n @Mock private Paint paint;\n @Mock private Transformation transformation;\n private Application context;\n\n private static Paint isAPaint() {\n return isA(Paint.class);\n }\n\n private static Rect isARect() {\n return isA(Rect.class);\n }\n\n @Before\n public void setUp() {\n MockitoAnnotations.initMocks(this);\n context = RuntimeEnvironment.application;"} {"commit": "1ac38b5f88ddf462e46f7cbc3139b4f58cdabf06", "message": "Check isLaidOut/isLayoutRequested in ViewTarget.", "old_file": "library/src/test/java/com/bumptech/glide/util/ViewPreloadSizeProviderTest.java", "new_file": "library/src/test/java/com/bumptech/glide/util/ViewPreloadSizeProviderTest.java", "status": "M", "old_contents": "\n @Test\n public void testReturnsNullFromGetPreloadSizeBeforeHasSize() {\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testReturnsValidSizeFromGetPreloadSizeAfterHasSize() {\n int width = 4123;\n int height = 342;\n provider.onSizeReady(width, height);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testDoesNotObtainSizeFromViewOnceSizeIsSet() {\n int width = 123;\n int height = 456;\n provider.onSizeReady(width, height);\n view.setLayoutParams(new ViewGroup.LayoutParams(1, 1));\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testCanObtainFixedSizeFromView() {\n int width = 123;\n int height = 456;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testIgnoresNewViewIfAlreadyWaitingOnSizeOfAnotherView() {\n provider.setView(view);\n\n View newView = new View(RuntimeEnvironment.application);\n newView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));\n provider.setView(newView);\n\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testCanObtainSizeFromViewWhenGivenViewInConstructor() {\n int width = 100;\n int height = 200;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n\n provider = new ViewPreloadSizeProvider<>(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n}\n", "new_contents": "\n @Test\n public void testReturnsNullFromGetPreloadSizeBeforeHasSize() {\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testReturnsValidSizeFromGetPreloadSizeAfterHasSize() {\n int width = 4123;\n int height = 342;\n provider.onSizeReady(width, height);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testDoesNotObtainSizeFromViewOnceSizeIsSet() {\n int width = 123;\n int height = 456;\n provider.onSizeReady(width, height);\n view.setLayoutParams(new ViewGroup.LayoutParams(1, 1));\n view.layout(0, 0, 1, 1);\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testCanObtainFixedSizeFromView() {\n int width = 123;\n int height = 456;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n view.layout(0, 0, width, height);\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testIgnoresNewViewIfAlreadyWaitingOnSizeOfAnotherView() {\n provider.setView(view);\n\n View newView = new View(RuntimeEnvironment.application);\n newView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));\n provider.setView(newView);\n\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testCanObtainSizeFromViewWhenGivenViewInConstructor() {\n int width = 100;\n int height = 200;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n view.layout(0, 0, width, height);\n\n provider = new ViewPreloadSizeProvider<>(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n}\n", "text": "<|original_code|>\n\n @Test\n public void testReturnsNullFromGetPreloadSizeBeforeHasSize() {\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testReturnsValidSizeFromGetPreloadSizeAfterHasSize() {\n int width = 4123;\n int height = 342;\n provider.onSizeReady(width, height);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testDoesNotObtainSizeFromViewOnceSizeIsSet() {\n int width = 123;\n int height = 456;\n provider.onSizeReady(width, height);\n view.setLayoutParams(new ViewGroup.LayoutParams(1, 1));\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testCanObtainFixedSizeFromView() {\n int width = 123;\n int height = 456;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testIgnoresNewViewIfAlreadyWaitingOnSizeOfAnotherView() {\n provider.setView(view);\n\n View newView = new View(RuntimeEnvironment.application);\n newView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));\n provider.setView(newView);\n\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testCanObtainSizeFromViewWhenGivenViewInConstructor() {\n int width = 100;\n int height = 200;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n\n provider = new ViewPreloadSizeProvider<>(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n}\n\n<|edits_diff|>\n--- library/src/test/java/com/bumptech/glide/util/ViewPreloadSizeProviderTest.java\n+++ library/src/test/java/com/bumptech/glide/util/ViewPreloadSizeProviderTest.java\n@@ -20,6 +20,7 @@\n int height = 456;\n provider.onSizeReady(width, height);\n view.setLayoutParams(new ViewGroup.LayoutParams(1, 1));\n+ view.layout(0, 0, 1, 1);\n \n provider.setView(view);\n \n@@ -32,6 +33,7 @@\n int width = 123;\n int height = 456;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n+ view.layout(0, 0, width, height);\n \n provider.setView(view);\n \n<|current_version|>\n\n @Test\n public void testReturnsNullFromGetPreloadSizeBeforeHasSize() {\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testReturnsValidSizeFromGetPreloadSizeAfterHasSize() {\n int width = 4123;\n int height = 342;\n provider.onSizeReady(width, height);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testDoesNotObtainSizeFromViewOnceSizeIsSet() {\n int width = 123;\n int height = 456;\n provider.onSizeReady(width, height);\n view.setLayoutParams(new ViewGroup.LayoutParams(1, 1));\n view.layout(0, 0, 1, 1);\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testCanObtainFixedSizeFromView() {\n int width = 123;\n int height = 456;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n view.layout(0, 0, width, height);\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testIgnoresNewViewIfAlreadyWaitingOnSizeOfAnotherView() {\n provider.setView(view);\n\n View newView = new View(RuntimeEnvironment.application);\n newView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));\n provider.setView(newView);\n\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testCanObtainSizeFromViewWhenGivenViewInConstructor() {\n int width = 100;\n int height = 200;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n\n provider = new ViewPreloadSizeProvider<>(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n}\n\n<|next_version|>\n\n @Test\n public void testReturnsNullFromGetPreloadSizeBeforeHasSize() {\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testReturnsValidSizeFromGetPreloadSizeAfterHasSize() {\n int width = 4123;\n int height = 342;\n provider.onSizeReady(width, height);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testDoesNotObtainSizeFromViewOnceSizeIsSet() {\n int width = 123;\n int height = 456;\n provider.onSizeReady(width, height);\n view.setLayoutParams(new ViewGroup.LayoutParams(1, 1));\n view.layout(0, 0, 1, 1);\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testCanObtainFixedSizeFromView() {\n int width = 123;\n int height = 456;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n view.layout(0, 0, width, height);\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testIgnoresNewViewIfAlreadyWaitingOnSizeOfAnotherView() {\n provider.setView(view);\n\n View newView = new View(RuntimeEnvironment.application);\n newView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));\n provider.setView(newView);\n\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testCanObtainSizeFromViewWhenGivenViewInConstructor() {\n int width = 100;\n int height = 200;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n view.layout(0, 0, width, height);\n\n provider = new ViewPreloadSizeProvider<>(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n}\n\n", "current_contents": "\n @Test\n public void testReturnsNullFromGetPreloadSizeBeforeHasSize() {\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testReturnsValidSizeFromGetPreloadSizeAfterHasSize() {\n int width = 4123;\n int height = 342;\n provider.onSizeReady(width, height);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testDoesNotObtainSizeFromViewOnceSizeIsSet() {\n int width = 123;\n int height = 456;\n provider.onSizeReady(width, height);\n view.setLayoutParams(new ViewGroup.LayoutParams(1, 1));\n view.layout(0, 0, 1, 1);\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testCanObtainFixedSizeFromView() {\n int width = 123;\n int height = 456;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n view.layout(0, 0, width, height);\n\n provider.setView(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n\n @Test\n public void testIgnoresNewViewIfAlreadyWaitingOnSizeOfAnotherView() {\n provider.setView(view);\n\n View newView = new View(RuntimeEnvironment.application);\n newView.setLayoutParams(new ViewGroup.LayoutParams(100, 100));\n provider.setView(newView);\n\n assertNull(provider.getPreloadSize(new Object(), 0, 0));\n }\n\n @Test\n public void testCanObtainSizeFromViewWhenGivenViewInConstructor() {\n int width = 100;\n int height = 200;\n view.setLayoutParams(new ViewGroup.LayoutParams(width, height));\n\n provider = new ViewPreloadSizeProvider<>(view);\n\n int[] size = provider.getPreloadSize(new Object(), 0, 0);\n assertThat(size).asList().containsExactly(width, height);\n }\n}\n"} {"commit": "c15f453757836e736a8155437da98860168058d4", "message": "Add onlyRetrieveFromCache option to Glide RequestOptions", "old_file": "library/src/test/java/com/bumptech/glide/load/engine/EngineTest.java", "new_file": "library/src/test/java/com/bumptech/glide/load/engine/EngineTest.java", "status": "M", "old_contents": " ResourceCallback cb = mock(ResourceCallback.class);\n @SuppressWarnings(\"rawtypes\")\n EngineResource resource = mock(EngineResource.class);\n Map> jobs = new HashMap<>();\n Map>> activeResources = new HashMap<>();\n\n int width = 100;\n int height = 100;\n\n Object model = new Object();\n MemoryCache cache = mock(MemoryCache.class);\n EngineJob job;\n Engine engine;\n Engine.EngineJobFactory engineJobFactory = mock(Engine.EngineJobFactory.class);\n Engine.DecodeJobFactory decodeJobFactory = mock(Engine.DecodeJobFactory.class);\n ResourceRecycler resourceRecycler = mock(ResourceRecycler.class);\n Key signature = mock(Key.class);\n Map, Transformation> transformations = new HashMap<>();\n Options options = new Options();\n GlideContext glideContext = mock(GlideContext.class);\n boolean isMemoryCacheable = true;\n boolean useUnlimitedSourceGeneratorPool = false;\n\n public EngineTestHarness() {\n when(keyFactory.buildKey(eq(model), eq(signature), anyInt(), anyInt(), eq(transformations),\n eq(Object.class), eq(Object.class), eq(options))).thenReturn(cacheKey);\n\n job = mock(EngineJob.class);\n\n engine = new Engine(cache, mock(DiskCache.Factory.class),\n GlideExecutor.newDiskCacheExecutor(),\n MockGlideExecutor.newMainThreadExecutor(),\n MockGlideExecutor.newMainThreadUnlimitedExecutor(),\n jobs, keyFactory, activeResources,\n engineJobFactory, decodeJobFactory, resourceRecycler);\n }\n\n public Engine.LoadStatus doLoad() {\n when(engineJobFactory.build(eq(cacheKey), anyBoolean(), anyBoolean()))\n .thenReturn((EngineJob) job);\n return engine.load(glideContext,\n model,\n signature,\n width,\n height,\n Object.class /*resourceClass*/,\n Object.class /*transcodeClass*/,\n Priority.HIGH,\n DiskCacheStrategy.ALL,\n transformations,\n false /*isTransformationRequired*/,\n options,\n isMemoryCacheable,\n useUnlimitedSourceGeneratorPool,\n cb);\n }\n }\n}\n", "new_contents": " ResourceCallback cb = mock(ResourceCallback.class);\n @SuppressWarnings(\"rawtypes\")\n EngineResource resource = mock(EngineResource.class);\n Map> jobs = new HashMap<>();\n Map>> activeResources = new HashMap<>();\n\n int width = 100;\n int height = 100;\n\n Object model = new Object();\n MemoryCache cache = mock(MemoryCache.class);\n EngineJob job;\n Engine engine;\n Engine.EngineJobFactory engineJobFactory = mock(Engine.EngineJobFactory.class);\n Engine.DecodeJobFactory decodeJobFactory = mock(Engine.DecodeJobFactory.class);\n ResourceRecycler resourceRecycler = mock(ResourceRecycler.class);\n Key signature = mock(Key.class);\n Map, Transformation> transformations = new HashMap<>();\n Options options = new Options();\n GlideContext glideContext = mock(GlideContext.class);\n boolean isMemoryCacheable = true;\n boolean useUnlimitedSourceGeneratorPool = false;\n boolean onlyRetrieveFromCache = false;\n\n public EngineTestHarness() {\n when(keyFactory.buildKey(eq(model), eq(signature), anyInt(), anyInt(), eq(transformations),\n eq(Object.class), eq(Object.class), eq(options))).thenReturn(cacheKey);\n\n job = mock(EngineJob.class);\n\n engine = new Engine(cache, mock(DiskCache.Factory.class),\n GlideExecutor.newDiskCacheExecutor(),\n MockGlideExecutor.newMainThreadExecutor(),\n MockGlideExecutor.newMainThreadUnlimitedExecutor(),\n jobs, keyFactory, activeResources,\n engineJobFactory, decodeJobFactory, resourceRecycler);\n }\n\n public Engine.LoadStatus doLoad() {\n when(engineJobFactory.build(eq(cacheKey), anyBoolean(), anyBoolean()))\n .thenReturn((EngineJob) job);\n return engine.load(glideContext,\n model,\n signature,\n width,\n height,\n Object.class /*resourceClass*/,\n Object.class /*transcodeClass*/,\n Priority.HIGH,\n DiskCacheStrategy.ALL,\n transformations,\n false /*isTransformationRequired*/,\n options,\n isMemoryCacheable,\n useUnlimitedSourceGeneratorPool,\n onlyRetrieveFromCache,\n cb);\n }\n }\n}\n", "text": "<|original_code|>\n ResourceCallback cb = mock(ResourceCallback.class);\n @SuppressWarnings(\"rawtypes\")\n EngineResource resource = mock(EngineResource.class);\n Map> jobs = new HashMap<>();\n Map>> activeResources = new HashMap<>();\n\n int width = 100;\n int height = 100;\n\n Object model = new Object();\n MemoryCache cache = mock(MemoryCache.class);\n EngineJob job;\n Engine engine;\n Engine.EngineJobFactory engineJobFactory = mock(Engine.EngineJobFactory.class);\n Engine.DecodeJobFactory decodeJobFactory = mock(Engine.DecodeJobFactory.class);\n ResourceRecycler resourceRecycler = mock(ResourceRecycler.class);\n Key signature = mock(Key.class);\n Map, Transformation> transformations = new HashMap<>();\n Options options = new Options();\n GlideContext glideContext = mock(GlideContext.class);\n boolean isMemoryCacheable = true;\n boolean useUnlimitedSourceGeneratorPool = false;\n\n public EngineTestHarness() {\n when(keyFactory.buildKey(eq(model), eq(signature), anyInt(), anyInt(), eq(transformations),\n eq(Object.class), eq(Object.class), eq(options))).thenReturn(cacheKey);\n\n job = mock(EngineJob.class);\n\n engine = new Engine(cache, mock(DiskCache.Factory.class),\n GlideExecutor.newDiskCacheExecutor(),\n MockGlideExecutor.newMainThreadExecutor(),\n MockGlideExecutor.newMainThreadUnlimitedExecutor(),\n jobs, keyFactory, activeResources,\n engineJobFactory, decodeJobFactory, resourceRecycler);\n }\n\n public Engine.LoadStatus doLoad() {\n when(engineJobFactory.build(eq(cacheKey), anyBoolean(), anyBoolean()))\n .thenReturn((EngineJob) job);\n return engine.load(glideContext,\n model,\n signature,\n width,\n height,\n Object.class /*resourceClass*/,\n Object.class /*transcodeClass*/,\n Priority.HIGH,\n DiskCacheStrategy.ALL,\n transformations,\n false /*isTransformationRequired*/,\n options,\n isMemoryCacheable,\n useUnlimitedSourceGeneratorPool,\n cb);\n }\n }\n}\n\n<|edits_diff|>\n--- library/src/test/java/com/bumptech/glide/load/engine/EngineTest.java\n+++ library/src/test/java/com/bumptech/glide/load/engine/EngineTest.java\n@@ -20,6 +20,7 @@\n GlideContext glideContext = mock(GlideContext.class);\n boolean isMemoryCacheable = true;\n boolean useUnlimitedSourceGeneratorPool = false;\n+ boolean onlyRetrieveFromCache = false;\n \n public EngineTestHarness() {\n when(keyFactory.buildKey(eq(model), eq(signature), anyInt(), anyInt(), eq(transformations),\n<|current_version|>\n ResourceCallback cb = mock(ResourceCallback.class);\n @SuppressWarnings(\"rawtypes\")\n EngineResource resource = mock(EngineResource.class);\n Map> jobs = new HashMap<>();\n Map>> activeResources = new HashMap<>();\n\n int width = 100;\n int height = 100;\n\n Object model = new Object();\n MemoryCache cache = mock(MemoryCache.class);\n EngineJob job;\n Engine engine;\n Engine.EngineJobFactory engineJobFactory = mock(Engine.EngineJobFactory.class);\n Engine.DecodeJobFactory decodeJobFactory = mock(Engine.DecodeJobFactory.class);\n ResourceRecycler resourceRecycler = mock(ResourceRecycler.class);\n Key signature = mock(Key.class);\n Map, Transformation> transformations = new HashMap<>();\n Options options = new Options();\n GlideContext glideContext = mock(GlideContext.class);\n boolean isMemoryCacheable = true;\n boolean useUnlimitedSourceGeneratorPool = false;\n boolean onlyRetrieveFromCache = false;\n\n public EngineTestHarness() {\n when(keyFactory.buildKey(eq(model), eq(signature), anyInt(), anyInt(), eq(transformations),\n eq(Object.class), eq(Object.class), eq(options))).thenReturn(cacheKey);\n\n job = mock(EngineJob.class);\n\n engine = new Engine(cache, mock(DiskCache.Factory.class),\n GlideExecutor.newDiskCacheExecutor(),\n MockGlideExecutor.newMainThreadExecutor(),\n MockGlideExecutor.newMainThreadUnlimitedExecutor(),\n jobs, keyFactory, activeResources,\n engineJobFactory, decodeJobFactory, resourceRecycler);\n }\n\n public Engine.LoadStatus doLoad() {\n when(engineJobFactory.build(eq(cacheKey), anyBoolean(), anyBoolean()))\n .thenReturn((EngineJob) job);\n return engine.load(glideContext,\n model,\n signature,\n width,\n height,\n Object.class /*resourceClass*/,\n Object.class /*transcodeClass*/,\n Priority.HIGH,\n DiskCacheStrategy.ALL,\n transformations,\n false /*isTransformationRequired*/,\n options,\n isMemoryCacheable,\n useUnlimitedSourceGeneratorPool,\n cb);\n }\n }\n}\n\n<|next_version|>\n ResourceCallback cb = mock(ResourceCallback.class);\n @SuppressWarnings(\"rawtypes\")\n EngineResource resource = mock(EngineResource.class);\n Map> jobs = new HashMap<>();\n Map>> activeResources = new HashMap<>();\n\n int width = 100;\n int height = 100;\n\n Object model = new Object();\n MemoryCache cache = mock(MemoryCache.class);\n EngineJob job;\n Engine engine;\n Engine.EngineJobFactory engineJobFactory = mock(Engine.EngineJobFactory.class);\n Engine.DecodeJobFactory decodeJobFactory = mock(Engine.DecodeJobFactory.class);\n ResourceRecycler resourceRecycler = mock(ResourceRecycler.class);\n Key signature = mock(Key.class);\n Map, Transformation> transformations = new HashMap<>();\n Options options = new Options();\n GlideContext glideContext = mock(GlideContext.class);\n boolean isMemoryCacheable = true;\n boolean useUnlimitedSourceGeneratorPool = false;\n boolean onlyRetrieveFromCache = false;\n\n public EngineTestHarness() {\n when(keyFactory.buildKey(eq(model), eq(signature), anyInt(), anyInt(), eq(transformations),\n eq(Object.class), eq(Object.class), eq(options))).thenReturn(cacheKey);\n\n job = mock(EngineJob.class);\n\n engine = new Engine(cache, mock(DiskCache.Factory.class),\n GlideExecutor.newDiskCacheExecutor(),\n MockGlideExecutor.newMainThreadExecutor(),\n MockGlideExecutor.newMainThreadUnlimitedExecutor(),\n jobs, keyFactory, activeResources,\n engineJobFactory, decodeJobFactory, resourceRecycler);\n }\n\n public Engine.LoadStatus doLoad() {\n when(engineJobFactory.build(eq(cacheKey), anyBoolean(), anyBoolean()))\n .thenReturn((EngineJob) job);\n return engine.load(glideContext,\n model,\n signature,\n width,\n height,\n Object.class /*resourceClass*/,\n Object.class /*transcodeClass*/,\n Priority.HIGH,\n DiskCacheStrategy.ALL,\n transformations,\n false /*isTransformationRequired*/,\n options,\n isMemoryCacheable,\n useUnlimitedSourceGeneratorPool,\n onlyRetrieveFromCache,\n cb);\n }\n }\n}\n\n", "current_contents": " ResourceCallback cb = mock(ResourceCallback.class);\n @SuppressWarnings(\"rawtypes\")\n EngineResource resource = mock(EngineResource.class);\n Map> jobs = new HashMap<>();\n Map>> activeResources = new HashMap<>();\n\n int width = 100;\n int height = 100;\n\n Object model = new Object();\n MemoryCache cache = mock(MemoryCache.class);\n EngineJob job;\n Engine engine;\n Engine.EngineJobFactory engineJobFactory = mock(Engine.EngineJobFactory.class);\n Engine.DecodeJobFactory decodeJobFactory = mock(Engine.DecodeJobFactory.class);\n ResourceRecycler resourceRecycler = mock(ResourceRecycler.class);\n Key signature = mock(Key.class);\n Map, Transformation> transformations = new HashMap<>();\n Options options = new Options();\n GlideContext glideContext = mock(GlideContext.class);\n boolean isMemoryCacheable = true;\n boolean useUnlimitedSourceGeneratorPool = false;\n boolean onlyRetrieveFromCache = false;\n\n public EngineTestHarness() {\n when(keyFactory.buildKey(eq(model), eq(signature), anyInt(), anyInt(), eq(transformations),\n eq(Object.class), eq(Object.class), eq(options))).thenReturn(cacheKey);\n\n job = mock(EngineJob.class);\n\n engine = new Engine(cache, mock(DiskCache.Factory.class),\n GlideExecutor.newDiskCacheExecutor(),\n MockGlideExecutor.newMainThreadExecutor(),\n MockGlideExecutor.newMainThreadUnlimitedExecutor(),\n jobs, keyFactory, activeResources,\n engineJobFactory, decodeJobFactory, resourceRecycler);\n }\n\n public Engine.LoadStatus doLoad() {\n when(engineJobFactory.build(eq(cacheKey), anyBoolean(), anyBoolean()))\n .thenReturn((EngineJob) job);\n return engine.load(glideContext,\n model,\n signature,\n width,\n height,\n Object.class /*resourceClass*/,\n Object.class /*transcodeClass*/,\n Priority.HIGH,\n DiskCacheStrategy.ALL,\n transformations,\n false /*isTransformationRequired*/,\n options,\n isMemoryCacheable,\n useUnlimitedSourceGeneratorPool,\n cb);\n }\n }\n}\n"} {"commit": "4eb3545b8e4615418391437a60f8d07057d11c10", "message": "Add Load/Decode paths.", "old_file": "library/src/main/java/com/bumptech/glide/load/data/DataRewinderRegistry.java", "new_file": "library/src/main/java/com/bumptech/glide/load/data/DataRewinderRegistry.java", "status": "M", "old_contents": "package com.bumptech.glide.load.data;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class DataRewinderRegistry {\n private final Map rewinders = new HashMap();\n private static final DataRewinder.Factory DEFAULT_FACTORY = new DataRewinder.Factory() {\n @Override\n public DataRewinder build(Object data) {\n return new DefaultRewinder(data);\n }\n\n @Override\n public Class getDataClass() {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n };\n\n public synchronized void register(DataRewinder.Factory factory) {\n rewinders.put(factory.getDataClass(), factory);\n }\n\n @SuppressWarnings(\"unchecked\")\n public synchronized DataRewinder build(T data) {\n DataRewinder.Factory result = rewinders.get(data.getClass());\n if (result == null) {\n for (DataRewinder.Factory registeredFactory : rewinders.values()) {\n if (registeredFactory.getDataClass().isAssignableFrom(data.getClass())) {\n result = registeredFactory;\n break;\n }\n }\n }\n\n if (result == null) {\n result = DEFAULT_FACTORY;\n }\n return result.build(data);\n }\n\n private static class DefaultRewinder implements DataRewinder {\n private Object data;\n\n public DefaultRewinder(Object data) {\n this.data = data;\n }\n\n @Override", "new_contents": "package com.bumptech.glide.load.data;\n\nimport com.bumptech.glide.util.Preconditions;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class DataRewinderRegistry {\n private final Map rewinders = new HashMap();\n private static final DataRewinder.Factory DEFAULT_FACTORY = new DataRewinder.Factory() {\n @Override\n public DataRewinder build(Object data) {\n return new DefaultRewinder(data);\n }\n\n @Override\n public Class getDataClass() {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n };\n\n public synchronized void register(DataRewinder.Factory factory) {\n rewinders.put(factory.getDataClass(), factory);\n }\n\n @SuppressWarnings(\"unchecked\")\n public synchronized DataRewinder build(T data) {\n Preconditions.checkNotNull(data);\n DataRewinder.Factory result = rewinders.get(data.getClass());\n if (result == null) {\n for (DataRewinder.Factory registeredFactory : rewinders.values()) {\n if (registeredFactory.getDataClass().isAssignableFrom(data.getClass())) {\n result = registeredFactory;\n break;\n }\n }\n }\n\n if (result == null) {\n result = DEFAULT_FACTORY;\n }\n return result.build(data);\n }\n\n private static class DefaultRewinder implements DataRewinder {\n private Object data;\n\n public DefaultRewinder(Object data) {\n this.data = data;\n }\n\n @Override", "text": "<|original_code|>\npackage com.bumptech.glide.load.data;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class DataRewinderRegistry {\n private final Map rewinders = new HashMap();\n private static final DataRewinder.Factory DEFAULT_FACTORY = new DataRewinder.Factory() {\n @Override\n public DataRewinder build(Object data) {\n return new DefaultRewinder(data);\n }\n\n @Override\n public Class getDataClass() {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n };\n\n public synchronized void register(DataRewinder.Factory factory) {\n rewinders.put(factory.getDataClass(), factory);\n }\n\n @SuppressWarnings(\"unchecked\")\n public synchronized DataRewinder build(T data) {\n DataRewinder.Factory result = rewinders.get(data.getClass());\n if (result == null) {\n for (DataRewinder.Factory registeredFactory : rewinders.values()) {\n if (registeredFactory.getDataClass().isAssignableFrom(data.getClass())) {\n result = registeredFactory;\n break;\n }\n }\n }\n\n if (result == null) {\n result = DEFAULT_FACTORY;\n }\n return result.build(data);\n }\n\n private static class DefaultRewinder implements DataRewinder {\n private Object data;\n\n public DefaultRewinder(Object data) {\n this.data = data;\n }\n\n @Override\n<|edits_diff|>\n--- library/src/main/java/com/bumptech/glide/load/data/DataRewinderRegistry.java\n+++ library/src/main/java/com/bumptech/glide/load/data/DataRewinderRegistry.java\n@@ -1,4 +1,6 @@\n package com.bumptech.glide.load.data;\n+\n+import com.bumptech.glide.util.Preconditions;\n \n import java.util.HashMap;\n import java.util.Map;\n<|current_version|>\npackage com.bumptech.glide.load.data;\n\nimport com.bumptech.glide.util.Preconditions;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class DataRewinderRegistry {\n private final Map rewinders = new HashMap();\n private static final DataRewinder.Factory DEFAULT_FACTORY = new DataRewinder.Factory() {\n @Override\n public DataRewinder build(Object data) {\n return new DefaultRewinder(data);\n }\n\n @Override\n public Class getDataClass() {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n };\n\n public synchronized void register(DataRewinder.Factory factory) {\n rewinders.put(factory.getDataClass(), factory);\n }\n\n @SuppressWarnings(\"unchecked\")\n public synchronized DataRewinder build(T data) {\n DataRewinder.Factory result = rewinders.get(data.getClass());\n if (result == null) {\n for (DataRewinder.Factory registeredFactory : rewinders.values()) {\n if (registeredFactory.getDataClass().isAssignableFrom(data.getClass())) {\n result = registeredFactory;\n break;\n }\n }\n }\n\n if (result == null) {\n result = DEFAULT_FACTORY;\n }\n return result.build(data);\n }\n\n private static class DefaultRewinder implements DataRewinder {\n private Object data;\n\n public DefaultRewinder(Object data) {\n this.data = data;\n }\n\n @Override\n<|next_version|>\npackage com.bumptech.glide.load.data;\n\nimport com.bumptech.glide.util.Preconditions;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class DataRewinderRegistry {\n private final Map rewinders = new HashMap();\n private static final DataRewinder.Factory DEFAULT_FACTORY = new DataRewinder.Factory() {\n @Override\n public DataRewinder build(Object data) {\n return new DefaultRewinder(data);\n }\n\n @Override\n public Class getDataClass() {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n };\n\n public synchronized void register(DataRewinder.Factory factory) {\n rewinders.put(factory.getDataClass(), factory);\n }\n\n @SuppressWarnings(\"unchecked\")\n public synchronized DataRewinder build(T data) {\n Preconditions.checkNotNull(data);\n DataRewinder.Factory result = rewinders.get(data.getClass());\n if (result == null) {\n for (DataRewinder.Factory registeredFactory : rewinders.values()) {\n if (registeredFactory.getDataClass().isAssignableFrom(data.getClass())) {\n result = registeredFactory;\n break;\n }\n }\n }\n\n if (result == null) {\n result = DEFAULT_FACTORY;\n }\n return result.build(data);\n }\n\n private static class DefaultRewinder implements DataRewinder {\n private Object data;\n\n public DefaultRewinder(Object data) {\n this.data = data;\n }\n\n @Override\n", "current_contents": "package com.bumptech.glide.load.data;\n\nimport com.bumptech.glide.util.Preconditions;\n\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class DataRewinderRegistry {\n private final Map rewinders = new HashMap();\n private static final DataRewinder.Factory DEFAULT_FACTORY = new DataRewinder.Factory() {\n @Override\n public DataRewinder build(Object data) {\n return new DefaultRewinder(data);\n }\n\n @Override\n public Class getDataClass() {\n throw new UnsupportedOperationException(\"Not implemented\");\n }\n };\n\n public synchronized void register(DataRewinder.Factory factory) {\n rewinders.put(factory.getDataClass(), factory);\n }\n\n @SuppressWarnings(\"unchecked\")\n public synchronized DataRewinder build(T data) {\n DataRewinder.Factory result = rewinders.get(data.getClass());\n if (result == null) {\n for (DataRewinder.Factory registeredFactory : rewinders.values()) {\n if (registeredFactory.getDataClass().isAssignableFrom(data.getClass())) {\n result = registeredFactory;\n break;\n }\n }\n }\n\n if (result == null) {\n result = DEFAULT_FACTORY;\n }\n return result.build(data);\n }\n\n private static class DefaultRewinder implements DataRewinder {\n private Object data;\n\n public DefaultRewinder(Object data) {\n this.data = data;\n }\n\n @Override"} {"commit": "2293cb271dce5355f4e6e19de6ec4b7816fad0d2", "message": "Explicitly set JUnit4 runner for junit tests.", "old_file": "library/src/androidTest/java/com/bumptech/glide/load/MultiTransformationTest.java", "new_file": "library/src/androidTest/java/com/bumptech/glide/load/MultiTransformationTest.java", "status": "M", "old_contents": "package com.bumptech.glide.load;\n\nimport com.bumptech.glide.load.engine.Resource;\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Matchers.anyInt;\nimport static org.mockito.Matchers.eq;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\npublic class MultiTransformationTest {\n @Test\n public void testReturnsConcatenatedTransformationIds() {\n String firstId = \"firstId\";\n Transformation first = mock(Transformation.class);\n when(first.getId()).thenReturn(firstId);\n String secondId = \"secondId\";\n Transformation second = mock(Transformation.class);\n when(second.getId()).thenReturn(secondId);\n String thirdId = \"thirdId\";\n Transformation third = mock(Transformation.class);\n when(third.getId()).thenReturn(thirdId);\n\n MultiTransformation transformation = new MultiTransformation(first, second, third);\n\n final String expected = firstId + secondId + thirdId;\n assertEquals(expected, transformation.getId());\n\n ArrayList transformations = new ArrayList();\n transformations.add(first);\n transformations.add(second);\n transformations.add(third);\n\n transformation = new MultiTransformation(transformations);", "new_contents": "package com.bumptech.glide.load;\n\nimport com.bumptech.glide.load.engine.Resource;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Matchers.anyInt;\nimport static org.mockito.Matchers.eq;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\n@RunWith(JUnit4.class)\npublic class MultiTransformationTest {\n @Test\n public void testReturnsConcatenatedTransformationIds() {\n String firstId = \"firstId\";\n Transformation first = mock(Transformation.class);\n when(first.getId()).thenReturn(firstId);\n String secondId = \"secondId\";\n Transformation second = mock(Transformation.class);\n when(second.getId()).thenReturn(secondId);\n String thirdId = \"thirdId\";\n Transformation third = mock(Transformation.class);\n when(third.getId()).thenReturn(thirdId);\n\n MultiTransformation transformation = new MultiTransformation(first, second, third);\n\n final String expected = firstId + secondId + thirdId;\n assertEquals(expected, transformation.getId());\n\n ArrayList transformations = new ArrayList();\n transformations.add(first);\n transformations.add(second);\n transformations.add(third);\n\n transformation = new MultiTransformation(transformations);", "text": "<|original_code|>\npackage com.bumptech.glide.load;\n\nimport com.bumptech.glide.load.engine.Resource;\nimport org.junit.Test;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Matchers.anyInt;\nimport static org.mockito.Matchers.eq;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\npublic class MultiTransformationTest {\n @Test\n public void testReturnsConcatenatedTransformationIds() {\n String firstId = \"firstId\";\n Transformation first = mock(Transformation.class);\n when(first.getId()).thenReturn(firstId);\n String secondId = \"secondId\";\n Transformation second = mock(Transformation.class);\n when(second.getId()).thenReturn(secondId);\n String thirdId = \"thirdId\";\n Transformation third = mock(Transformation.class);\n when(third.getId()).thenReturn(thirdId);\n\n MultiTransformation transformation = new MultiTransformation(first, second, third);\n\n final String expected = firstId + secondId + thirdId;\n assertEquals(expected, transformation.getId());\n\n ArrayList transformations = new ArrayList();\n transformations.add(first);\n transformations.add(second);\n transformations.add(third);\n\n transformation = new MultiTransformation(transformations);\n<|edits_diff|>\n--- library/src/androidTest/java/com/bumptech/glide/load/MultiTransformationTest.java\n+++ library/src/androidTest/java/com/bumptech/glide/load/MultiTransformationTest.java\n@@ -2,6 +2,8 @@\n \n import com.bumptech.glide.load.engine.Resource;\n import org.junit.Test;\n+import org.junit.runner.RunWith;\n+import org.junit.runners.JUnit4;\n \n import java.util.ArrayList;\n \n<|current_version|>\npackage com.bumptech.glide.load;\n\nimport com.bumptech.glide.load.engine.Resource;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Matchers.anyInt;\nimport static org.mockito.Matchers.eq;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\npublic class MultiTransformationTest {\n @Test\n public void testReturnsConcatenatedTransformationIds() {\n String firstId = \"firstId\";\n Transformation first = mock(Transformation.class);\n when(first.getId()).thenReturn(firstId);\n String secondId = \"secondId\";\n Transformation second = mock(Transformation.class);\n when(second.getId()).thenReturn(secondId);\n String thirdId = \"thirdId\";\n Transformation third = mock(Transformation.class);\n when(third.getId()).thenReturn(thirdId);\n\n MultiTransformation transformation = new MultiTransformation(first, second, third);\n\n final String expected = firstId + secondId + thirdId;\n assertEquals(expected, transformation.getId());\n\n ArrayList transformations = new ArrayList();\n transformations.add(first);\n transformations.add(second);\n transformations.add(third);\n\n transformation = new MultiTransformation(transformations);\n<|next_version|>\npackage com.bumptech.glide.load;\n\nimport com.bumptech.glide.load.engine.Resource;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Matchers.anyInt;\nimport static org.mockito.Matchers.eq;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\n@RunWith(JUnit4.class)\npublic class MultiTransformationTest {\n @Test\n public void testReturnsConcatenatedTransformationIds() {\n String firstId = \"firstId\";\n Transformation first = mock(Transformation.class);\n when(first.getId()).thenReturn(firstId);\n String secondId = \"secondId\";\n Transformation second = mock(Transformation.class);\n when(second.getId()).thenReturn(secondId);\n String thirdId = \"thirdId\";\n Transformation third = mock(Transformation.class);\n when(third.getId()).thenReturn(thirdId);\n\n MultiTransformation transformation = new MultiTransformation(first, second, third);\n\n final String expected = firstId + secondId + thirdId;\n assertEquals(expected, transformation.getId());\n\n ArrayList transformations = new ArrayList();\n transformations.add(first);\n transformations.add(second);\n transformations.add(third);\n\n transformation = new MultiTransformation(transformations);\n", "current_contents": "package com.bumptech.glide.load;\n\nimport com.bumptech.glide.load.engine.Resource;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.JUnit4;\n\nimport java.util.ArrayList;\n\nimport static org.junit.Assert.assertEquals;\nimport static org.mockito.Matchers.any;\nimport static org.mockito.Matchers.anyInt;\nimport static org.mockito.Matchers.eq;\nimport static org.mockito.Mockito.mock;\nimport static org.mockito.Mockito.never;\nimport static org.mockito.Mockito.verify;\nimport static org.mockito.Mockito.when;\n\npublic class MultiTransformationTest {\n @Test\n public void testReturnsConcatenatedTransformationIds() {\n String firstId = \"firstId\";\n Transformation first = mock(Transformation.class);\n when(first.getId()).thenReturn(firstId);\n String secondId = \"secondId\";\n Transformation second = mock(Transformation.class);\n when(second.getId()).thenReturn(secondId);\n String thirdId = \"thirdId\";\n Transformation third = mock(Transformation.class);\n when(third.getId()).thenReturn(thirdId);\n\n MultiTransformation transformation = new MultiTransformation(first, second, third);\n\n final String expected = firstId + secondId + thirdId;\n assertEquals(expected, transformation.getId());\n\n ArrayList transformations = new ArrayList();\n transformations.add(first);\n transformations.add(second);\n transformations.add(third);\n\n transformation = new MultiTransformation(transformations);"} {"commit": "c95999a11b7c380a6711395482e16362039e5b31", "message": "Avoid NPE loading null or empty urls.", "old_file": "library/src/main/java/com/bumptech/glide/load/model/GlideUrl.java", "new_file": "library/src/main/java/com/bumptech/glide/load/model/GlideUrl.java", "status": "M", "old_contents": "package com.bumptech.glide.load.model;\n\nimport android.text.TextUtils;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\n/**\n * This is a simple wrapper for strings representing http/https URLs. new URL() is an excessively expensive operation\n * that may be unnecessary if the class loading the image from the URL doesn't actually require a URL object.\n *\n * Users wishing to replace the class for handling URLs must register a factory using GlideUrl.\n */\npublic class GlideUrl {\n private String stringUrl;\n private URL url;\n\n public GlideUrl(URL url) {\n this.url = url;\n stringUrl = null;\n }\n\n public GlideUrl(String url) {\n this.stringUrl = url;\n this.url = null;\n }\n\n public URL toURL() throws MalformedURLException {\n if (url == null) {\n url = new URL(stringUrl);\n }\n return url;\n }\n\n @Override\n public String toString() {\n if (TextUtils.isEmpty(stringUrl)) {\n stringUrl = url.toString();\n }\n return stringUrl;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }", "new_contents": "package com.bumptech.glide.load.model;\n\nimport android.text.TextUtils;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\n/**\n * This is a simple wrapper for strings representing http/https URLs. new URL() is an excessively expensive operation\n * that may be unnecessary if the class loading the image from the URL doesn't actually require a URL object.\n *\n * Users wishing to replace the class for handling URLs must register a factory using GlideUrl.\n */\npublic class GlideUrl {\n private String stringUrl;\n private URL url;\n\n public GlideUrl(URL url) {\n if (url == null) {\n throw new IllegalArgumentException(\"URL must not be null!\");\n }\n this.url = url;\n stringUrl = null;\n }\n\n public GlideUrl(String url) {\n if (TextUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"String url must not be empty or null: \" + url);\n }\n this.stringUrl = url;\n this.url = null;\n }\n\n public URL toURL() throws MalformedURLException {\n if (url == null) {\n url = new URL(stringUrl);\n }\n return url;\n }\n\n @Override\n public String toString() {\n if (TextUtils.isEmpty(stringUrl)) {\n stringUrl = url.toString();\n }\n return stringUrl;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }", "text": "<|original_code|>\npackage com.bumptech.glide.load.model;\n\nimport android.text.TextUtils;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\n/**\n * This is a simple wrapper for strings representing http/https URLs. new URL() is an excessively expensive operation\n * that may be unnecessary if the class loading the image from the URL doesn't actually require a URL object.\n *\n * Users wishing to replace the class for handling URLs must register a factory using GlideUrl.\n */\npublic class GlideUrl {\n private String stringUrl;\n private URL url;\n\n public GlideUrl(URL url) {\n this.url = url;\n stringUrl = null;\n }\n\n public GlideUrl(String url) {\n this.stringUrl = url;\n this.url = null;\n }\n\n public URL toURL() throws MalformedURLException {\n if (url == null) {\n url = new URL(stringUrl);\n }\n return url;\n }\n\n @Override\n public String toString() {\n if (TextUtils.isEmpty(stringUrl)) {\n stringUrl = url.toString();\n }\n return stringUrl;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n<|edits_diff|>\n--- library/src/main/java/com/bumptech/glide/load/model/GlideUrl.java\n+++ library/src/main/java/com/bumptech/glide/load/model/GlideUrl.java\n@@ -16,6 +16,9 @@\n private URL url;\n \n public GlideUrl(URL url) {\n+ if (url == null) {\n+ throw new IllegalArgumentException(\"URL must not be null!\");\n+ }\n this.url = url;\n stringUrl = null;\n }\n<|current_version|>\npackage com.bumptech.glide.load.model;\n\nimport android.text.TextUtils;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\n/**\n * This is a simple wrapper for strings representing http/https URLs. new URL() is an excessively expensive operation\n * that may be unnecessary if the class loading the image from the URL doesn't actually require a URL object.\n *\n * Users wishing to replace the class for handling URLs must register a factory using GlideUrl.\n */\npublic class GlideUrl {\n private String stringUrl;\n private URL url;\n\n public GlideUrl(URL url) {\n if (url == null) {\n throw new IllegalArgumentException(\"URL must not be null!\");\n }\n this.url = url;\n stringUrl = null;\n }\n\n public GlideUrl(String url) {\n this.stringUrl = url;\n this.url = null;\n }\n\n public URL toURL() throws MalformedURLException {\n if (url == null) {\n url = new URL(stringUrl);\n }\n return url;\n }\n\n @Override\n public String toString() {\n if (TextUtils.isEmpty(stringUrl)) {\n stringUrl = url.toString();\n }\n return stringUrl;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n<|next_version|>\npackage com.bumptech.glide.load.model;\n\nimport android.text.TextUtils;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\n/**\n * This is a simple wrapper for strings representing http/https URLs. new URL() is an excessively expensive operation\n * that may be unnecessary if the class loading the image from the URL doesn't actually require a URL object.\n *\n * Users wishing to replace the class for handling URLs must register a factory using GlideUrl.\n */\npublic class GlideUrl {\n private String stringUrl;\n private URL url;\n\n public GlideUrl(URL url) {\n if (url == null) {\n throw new IllegalArgumentException(\"URL must not be null!\");\n }\n this.url = url;\n stringUrl = null;\n }\n\n public GlideUrl(String url) {\n if (TextUtils.isEmpty(url)) {\n throw new IllegalArgumentException(\"String url must not be empty or null: \" + url);\n }\n this.stringUrl = url;\n this.url = null;\n }\n\n public URL toURL() throws MalformedURLException {\n if (url == null) {\n url = new URL(stringUrl);\n }\n return url;\n }\n\n @Override\n public String toString() {\n if (TextUtils.isEmpty(stringUrl)) {\n stringUrl = url.toString();\n }\n return stringUrl;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n", "current_contents": "package com.bumptech.glide.load.model;\n\nimport android.text.TextUtils;\n\nimport java.net.MalformedURLException;\nimport java.net.URL;\n\n/**\n * This is a simple wrapper for strings representing http/https URLs. new URL() is an excessively expensive operation\n * that may be unnecessary if the class loading the image from the URL doesn't actually require a URL object.\n *\n * Users wishing to replace the class for handling URLs must register a factory using GlideUrl.\n */\npublic class GlideUrl {\n private String stringUrl;\n private URL url;\n\n public GlideUrl(URL url) {\n if (url == null) {\n throw new IllegalArgumentException(\"URL must not be null!\");\n }\n this.url = url;\n stringUrl = null;\n }\n\n public GlideUrl(String url) {\n this.stringUrl = url;\n this.url = null;\n }\n\n public URL toURL() throws MalformedURLException {\n if (url == null) {\n url = new URL(stringUrl);\n }\n return url;\n }\n\n @Override\n public String toString() {\n if (TextUtils.isEmpty(stringUrl)) {\n stringUrl = url.toString();\n }\n return stringUrl;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }"} {"commit": "424f648632c925ce14a75018c4dcab395e035993", "message": "increase default context length to 4096 (#10364)", "old_file": "server/routes_generate_test.go", "new_file": "server/routes_generate_test.go", "status": "M", "old_contents": "\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test\", \"Hi!\")\n\t})\n\n\tw = createRequest(t, s.CreateHandler, api.CreateRequest{\n\t\tModel: \"test-system\",\n\t\tFrom: \"test\",\n\t\tSystem: \"You are a helpful assistant.\",\n\t})\n\n\tif w.Code != http.StatusOK {\n\t\tt.Fatalf(\"expected status 200, got %d\", w.Code)\n\t}\n\n\tt.Run(\"messages with model system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Hi!\")\n\t})\n\n\tmock.CompletionResponse.Content = \"Abra kadabra!\"\n\tt.Run(\"messages with system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You can perform magic tricks.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with interleaved system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t\t{Role: \"assistant\", Content: \"I can help you with that.\"},\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Help me write tests.\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\nassistant: I can help you with that.\\nsystem: You can perform magic tricks.\\nuser: Help me write tests.\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with tools (non-streaming)\", func(t *testing.T) {\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Fatalf(\"failed to create test-system model: %d\", w.Code)\n\t\t}\n\n\t\ttools := []api.Tool{\n\t\t\t{\n\t\t\t\tType: \"function\",\n\t\t\t\tFunction: api.ToolFunction{\n\t\t\t\t\tName: \"get_weather\",\n\t\t\t\t\tDescription: \"Get the current weather\",", "new_contents": "\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test\", \"Hi!\")\n\t})\n\n\tw = createRequest(t, s.CreateHandler, api.CreateRequest{\n\t\tModel: \"test-system\",\n\t\tFrom: \"test\",\n\t\tSystem: \"You are a helpful assistant.\",\n\t})\n\n\tif w.Code != http.StatusOK {\n\t\tt.Fatalf(\"expected status 200, got %d\", w.Code)\n\t}\n\n\tt.Run(\"messages with model system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Hi!\")\n\t})\n\n\tmock.CompletionResponse.Content = \"Abra kadabra!\"\n\tt.Run(\"messages with system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You can perform magic tricks.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with interleaved system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t\t{Role: \"assistant\", Content: \"I can help you with that.\"},\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Help me write tests.\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\nassistant: I can help you with that.\\nsystem: You can perform magic tricks.\\nuser: Help me write tests.\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with tools (non-streaming)\", func(t *testing.T) {\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Fatalf(\"failed to create test-system model: %d\", w.Code)\n\t\t}\n\n\t\ttools := []api.Tool{\n\t\t\t{\n\t\t\t\tType: \"function\",\n\t\t\t\tFunction: api.ToolFunction{\n\t\t\t\t\tName: \"get_weather\",\n\t\t\t\t\tDescription: \"Get the current weather\",", "text": "<|original_code|>\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test\", \"Hi!\")\n\t})\n\n\tw = createRequest(t, s.CreateHandler, api.CreateRequest{\n\t\tModel: \"test-system\",\n\t\tFrom: \"test\",\n\t\tSystem: \"You are a helpful assistant.\",\n\t})\n\n\tif w.Code != http.StatusOK {\n\t\tt.Fatalf(\"expected status 200, got %d\", w.Code)\n\t}\n\n\tt.Run(\"messages with model system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Hi!\")\n\t})\n\n\tmock.CompletionResponse.Content = \"Abra kadabra!\"\n\tt.Run(\"messages with system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You can perform magic tricks.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with interleaved system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t\t{Role: \"assistant\", Content: \"I can help you with that.\"},\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Help me write tests.\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\nassistant: I can help you with that.\\nsystem: You can perform magic tricks.\\nuser: Help me write tests.\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with tools (non-streaming)\", func(t *testing.T) {\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Fatalf(\"failed to create test-system model: %d\", w.Code)\n\t\t}\n\n\t\ttools := []api.Tool{\n\t\t\t{\n\t\t\t\tType: \"function\",\n\t\t\t\tFunction: api.ToolFunction{\n\t\t\t\t\tName: \"get_weather\",\n\t\t\t\t\tDescription: \"Get the current weather\",\n<|edits_diff|>\n--- server/routes_generate_test.go\n+++ server/routes_generate_test.go\n@@ -20,6 +20,9 @@\n \t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n \t\t\t},\n \t\t\tStream: &stream,\n+\t\t\tOptions: map[string]any{\n+\t\t\t\t\"num_ctx\": 1024,\n+\t\t\t},\n \t\t})\n \n \t\tif w.Code != http.StatusOK {\n@@ -42,6 +45,9 @@\n \t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n \t\t\t},\n \t\t\tStream: &stream,\n+\t\t\tOptions: map[string]any{\n+\t\t\t\t\"num_ctx\": 1024,\n+\t\t\t},\n \t\t})\n \n \t\tif w.Code != http.StatusOK {\n<|current_version|>\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test\", \"Hi!\")\n\t})\n\n\tw = createRequest(t, s.CreateHandler, api.CreateRequest{\n\t\tModel: \"test-system\",\n\t\tFrom: \"test\",\n\t\tSystem: \"You are a helpful assistant.\",\n\t})\n\n\tif w.Code != http.StatusOK {\n\t\tt.Fatalf(\"expected status 200, got %d\", w.Code)\n\t}\n\n\tt.Run(\"messages with model system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Hi!\")\n\t})\n\n\tmock.CompletionResponse.Content = \"Abra kadabra!\"\n\tt.Run(\"messages with system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You can perform magic tricks.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with interleaved system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t\t{Role: \"assistant\", Content: \"I can help you with that.\"},\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Help me write tests.\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\nassistant: I can help you with that.\\nsystem: You can perform magic tricks.\\nuser: Help me write tests.\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with tools (non-streaming)\", func(t *testing.T) {\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Fatalf(\"failed to create test-system model: %d\", w.Code)\n\t\t}\n\n\t\ttools := []api.Tool{\n\t\t\t{\n\t\t\t\tType: \"function\",\n\t\t\t\tFunction: api.ToolFunction{\n\t\t\t\t\tName: \"get_weather\",\n\t\t\t\t\tDescription: \"Get the current weather\",\n<|next_version|>\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test\", \"Hi!\")\n\t})\n\n\tw = createRequest(t, s.CreateHandler, api.CreateRequest{\n\t\tModel: \"test-system\",\n\t\tFrom: \"test\",\n\t\tSystem: \"You are a helpful assistant.\",\n\t})\n\n\tif w.Code != http.StatusOK {\n\t\tt.Fatalf(\"expected status 200, got %d\", w.Code)\n\t}\n\n\tt.Run(\"messages with model system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Hi!\")\n\t})\n\n\tmock.CompletionResponse.Content = \"Abra kadabra!\"\n\tt.Run(\"messages with system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You can perform magic tricks.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with interleaved system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t\t{Role: \"assistant\", Content: \"I can help you with that.\"},\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Help me write tests.\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\nassistant: I can help you with that.\\nsystem: You can perform magic tricks.\\nuser: Help me write tests.\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with tools (non-streaming)\", func(t *testing.T) {\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Fatalf(\"failed to create test-system model: %d\", w.Code)\n\t\t}\n\n\t\ttools := []api.Tool{\n\t\t\t{\n\t\t\t\tType: \"function\",\n\t\t\t\tFunction: api.ToolFunction{\n\t\t\t\t\tName: \"get_weather\",\n\t\t\t\t\tDescription: \"Get the current weather\",\n", "current_contents": "\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test\", \"Hi!\")\n\t})\n\n\tw = createRequest(t, s.CreateHandler, api.CreateRequest{\n\t\tModel: \"test-system\",\n\t\tFrom: \"test\",\n\t\tSystem: \"You are a helpful assistant.\",\n\t})\n\n\tif w.Code != http.StatusOK {\n\t\tt.Fatalf(\"expected status 200, got %d\", w.Code)\n\t}\n\n\tt.Run(\"messages with model system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Hi!\")\n\t})\n\n\tmock.CompletionResponse.Content = \"Abra kadabra!\"\n\tt.Run(\"messages with system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t\tOptions: map[string]any{\n\t\t\t\t\"num_ctx\": 1024,\n\t\t\t},\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You can perform magic tricks.\\nuser: Hello!\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with interleaved system\", func(t *testing.T) {\n\t\tw := createRequest(t, s.ChatHandler, api.ChatRequest{\n\t\t\tModel: \"test-system\",\n\t\t\tMessages: []api.Message{\n\t\t\t\t{Role: \"user\", Content: \"Hello!\"},\n\t\t\t\t{Role: \"assistant\", Content: \"I can help you with that.\"},\n\t\t\t\t{Role: \"system\", Content: \"You can perform magic tricks.\"},\n\t\t\t\t{Role: \"user\", Content: \"Help me write tests.\"},\n\t\t\t},\n\t\t\tStream: &stream,\n\t\t})\n\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Errorf(\"expected status 200, got %d\", w.Code)\n\t\t}\n\n\t\tif diff := cmp.Diff(mock.CompletionRequest.Prompt, \"system: You are a helpful assistant.\\nuser: Hello!\\nassistant: I can help you with that.\\nsystem: You can perform magic tricks.\\nuser: Help me write tests.\\n\"); diff != \"\" {\n\t\t\tt.Errorf(\"mismatch (-got +want):\\n%s\", diff)\n\t\t}\n\n\t\tcheckChatResponse(t, w.Body, \"test-system\", \"Abra kadabra!\")\n\t})\n\n\tt.Run(\"messages with tools (non-streaming)\", func(t *testing.T) {\n\t\tif w.Code != http.StatusOK {\n\t\t\tt.Fatalf(\"failed to create test-system model: %d\", w.Code)\n\t\t}\n\n\t\ttools := []api.Tool{\n\t\t\t{\n\t\t\t\tType: \"function\",\n\t\t\t\tFunction: api.ToolFunction{\n\t\t\t\t\tName: \"get_weather\",\n\t\t\t\t\tDescription: \"Get the current weather\","} {"commit": "bc108b9ad61da81a5d170e0f487b7603fbeb768f", "message": "ggml: Log filesystem errors", "old_file": "ml/backend/ggml/ggml.go", "new_file": "ml/backend/ggml/ggml.go", "status": "M", "old_contents": "\tg.SetLimit(runtime.GOMAXPROCS(0))\n\tfor _, t := range meta.Tensors().Items() {\n\t\tg.Go(func() error {\n\t\t\ttts := make([]*C.struct_ggml_tensor, max(1, len(targets[t.Name])))\n\t\t\tfor i := range tts {\n\t\t\t\ttarget := targets[t.Name][i]\n\t\t\t\tif target == \"\" {\n\t\t\t\t\ttarget = t.Name\n\t\t\t\t}\n\n\t\t\t\ttt, ok := tensors[target]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"unassigned tensor: %s\", t.Name)\n\t\t\t\t}\n\n\t\t\t\ttts[i] = tt\n\t\t\t}\n\n\t\t\t// Create a new FD for each goroutine so that each FD is read sequentially, rather than\n\t\t\t// seeking around within an FD shared between all goroutines.\n\t\t\tfile, err := os.Open(r.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\tsr := io.NewSectionReader(file, int64(meta.Tensors().Offset+t.Offset), int64(t.Size()))\n\t\t\tbts := make([]byte, 128*format.KibiByte)\n\n\t\t\tvar s uint64\n\t\t\tfor s < t.Size() {\n\t\t\t\tn, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Size()-s))])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfor _, tt := range tts {\n\t\t\t\t\tC.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), C.size_t(s), C.size_t(n))\n\t\t\t\t}\n\n\t\t\t\ts += uint64(n)\n\n\t\t\t\tif params.Progress != nil {\n\t\t\t\t\tdone := doneBytes.Add(uint64(n))\n\t\t\t\t\tparams.Progress(float32(done) / float32(totalBytes))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t// start a goroutine to cancel the errgroup if the parent context is done\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tg.Go(func() error {\n\t\t\treturn ctx.Err()", "new_contents": "\tg.SetLimit(runtime.GOMAXPROCS(0))\n\tfor _, t := range meta.Tensors().Items() {\n\t\tg.Go(func() error {\n\t\t\ttts := make([]*C.struct_ggml_tensor, max(1, len(targets[t.Name])))\n\t\t\tfor i := range tts {\n\t\t\t\ttarget := targets[t.Name][i]\n\t\t\t\tif target == \"\" {\n\t\t\t\t\ttarget = t.Name\n\t\t\t\t}\n\n\t\t\t\ttt, ok := tensors[target]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"unassigned tensor: %s\", t.Name)\n\t\t\t\t}\n\n\t\t\t\ttts[i] = tt\n\t\t\t}\n\n\t\t\t// Create a new FD for each goroutine so that each FD is read sequentially, rather than\n\t\t\t// seeking around within an FD shared between all goroutines.\n\t\t\tfile, err := os.Open(r.Name())\n\t\t\tif err != nil {\n\t\t\t\tslog.Warn(\"file open error\", \"file\", r.Name(), \"error\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\tsr := io.NewSectionReader(file, int64(meta.Tensors().Offset+t.Offset), int64(t.Size()))\n\t\t\tbts := make([]byte, 128*format.KibiByte)\n\n\t\t\tvar s uint64\n\t\t\tfor s < t.Size() {\n\t\t\t\tn, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Size()-s))])\n\t\t\t\tif err != nil {\n\t\t\t\t\tslog.Warn(\"file read error\", \"file\", r.Name(), \"error\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfor _, tt := range tts {\n\t\t\t\t\tC.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), C.size_t(s), C.size_t(n))\n\t\t\t\t}\n\n\t\t\t\ts += uint64(n)\n\n\t\t\t\tif params.Progress != nil {\n\t\t\t\t\tdone := doneBytes.Add(uint64(n))\n\t\t\t\t\tparams.Progress(float32(done) / float32(totalBytes))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t// start a goroutine to cancel the errgroup if the parent context is done\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tg.Go(func() error {\n\t\t\treturn ctx.Err()", "text": "<|original_code|>\n\tg.SetLimit(runtime.GOMAXPROCS(0))\n\tfor _, t := range meta.Tensors().Items() {\n\t\tg.Go(func() error {\n\t\t\ttts := make([]*C.struct_ggml_tensor, max(1, len(targets[t.Name])))\n\t\t\tfor i := range tts {\n\t\t\t\ttarget := targets[t.Name][i]\n\t\t\t\tif target == \"\" {\n\t\t\t\t\ttarget = t.Name\n\t\t\t\t}\n\n\t\t\t\ttt, ok := tensors[target]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"unassigned tensor: %s\", t.Name)\n\t\t\t\t}\n\n\t\t\t\ttts[i] = tt\n\t\t\t}\n\n\t\t\t// Create a new FD for each goroutine so that each FD is read sequentially, rather than\n\t\t\t// seeking around within an FD shared between all goroutines.\n\t\t\tfile, err := os.Open(r.Name())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\tsr := io.NewSectionReader(file, int64(meta.Tensors().Offset+t.Offset), int64(t.Size()))\n\t\t\tbts := make([]byte, 128*format.KibiByte)\n\n\t\t\tvar s uint64\n\t\t\tfor s < t.Size() {\n\t\t\t\tn, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Size()-s))])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfor _, tt := range tts {\n\t\t\t\t\tC.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), C.size_t(s), C.size_t(n))\n\t\t\t\t}\n\n\t\t\t\ts += uint64(n)\n\n\t\t\t\tif params.Progress != nil {\n\t\t\t\t\tdone := doneBytes.Add(uint64(n))\n\t\t\t\t\tparams.Progress(float32(done) / float32(totalBytes))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t// start a goroutine to cancel the errgroup if the parent context is done\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tg.Go(func() error {\n\t\t\treturn ctx.Err()\n<|edits_diff|>\n--- ml/backend/ggml/ggml.go\n+++ ml/backend/ggml/ggml.go\n@@ -20,6 +20,7 @@\n \t\t\t// seeking around within an FD shared between all goroutines.\n \t\t\tfile, err := os.Open(r.Name())\n \t\t\tif err != nil {\n+\t\t\t\tslog.Warn(\"file open error\", \"file\", r.Name(), \"error\", err)\n \t\t\t\treturn err\n \t\t\t}\n \t\t\tdefer file.Close()\n<|current_version|>\n\tg.SetLimit(runtime.GOMAXPROCS(0))\n\tfor _, t := range meta.Tensors().Items() {\n\t\tg.Go(func() error {\n\t\t\ttts := make([]*C.struct_ggml_tensor, max(1, len(targets[t.Name])))\n\t\t\tfor i := range tts {\n\t\t\t\ttarget := targets[t.Name][i]\n\t\t\t\tif target == \"\" {\n\t\t\t\t\ttarget = t.Name\n\t\t\t\t}\n\n\t\t\t\ttt, ok := tensors[target]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"unassigned tensor: %s\", t.Name)\n\t\t\t\t}\n\n\t\t\t\ttts[i] = tt\n\t\t\t}\n\n\t\t\t// Create a new FD for each goroutine so that each FD is read sequentially, rather than\n\t\t\t// seeking around within an FD shared between all goroutines.\n\t\t\tfile, err := os.Open(r.Name())\n\t\t\tif err != nil {\n\t\t\t\tslog.Warn(\"file open error\", \"file\", r.Name(), \"error\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\tsr := io.NewSectionReader(file, int64(meta.Tensors().Offset+t.Offset), int64(t.Size()))\n\t\t\tbts := make([]byte, 128*format.KibiByte)\n\n\t\t\tvar s uint64\n\t\t\tfor s < t.Size() {\n\t\t\t\tn, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Size()-s))])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfor _, tt := range tts {\n\t\t\t\t\tC.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), C.size_t(s), C.size_t(n))\n\t\t\t\t}\n\n\t\t\t\ts += uint64(n)\n\n\t\t\t\tif params.Progress != nil {\n\t\t\t\t\tdone := doneBytes.Add(uint64(n))\n\t\t\t\t\tparams.Progress(float32(done) / float32(totalBytes))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t// start a goroutine to cancel the errgroup if the parent context is done\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tg.Go(func() error {\n\t\t\treturn ctx.Err()\n<|next_version|>\n\tg.SetLimit(runtime.GOMAXPROCS(0))\n\tfor _, t := range meta.Tensors().Items() {\n\t\tg.Go(func() error {\n\t\t\ttts := make([]*C.struct_ggml_tensor, max(1, len(targets[t.Name])))\n\t\t\tfor i := range tts {\n\t\t\t\ttarget := targets[t.Name][i]\n\t\t\t\tif target == \"\" {\n\t\t\t\t\ttarget = t.Name\n\t\t\t\t}\n\n\t\t\t\ttt, ok := tensors[target]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"unassigned tensor: %s\", t.Name)\n\t\t\t\t}\n\n\t\t\t\ttts[i] = tt\n\t\t\t}\n\n\t\t\t// Create a new FD for each goroutine so that each FD is read sequentially, rather than\n\t\t\t// seeking around within an FD shared between all goroutines.\n\t\t\tfile, err := os.Open(r.Name())\n\t\t\tif err != nil {\n\t\t\t\tslog.Warn(\"file open error\", \"file\", r.Name(), \"error\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\tsr := io.NewSectionReader(file, int64(meta.Tensors().Offset+t.Offset), int64(t.Size()))\n\t\t\tbts := make([]byte, 128*format.KibiByte)\n\n\t\t\tvar s uint64\n\t\t\tfor s < t.Size() {\n\t\t\t\tn, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Size()-s))])\n\t\t\t\tif err != nil {\n\t\t\t\t\tslog.Warn(\"file read error\", \"file\", r.Name(), \"error\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfor _, tt := range tts {\n\t\t\t\t\tC.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), C.size_t(s), C.size_t(n))\n\t\t\t\t}\n\n\t\t\t\ts += uint64(n)\n\n\t\t\t\tif params.Progress != nil {\n\t\t\t\t\tdone := doneBytes.Add(uint64(n))\n\t\t\t\t\tparams.Progress(float32(done) / float32(totalBytes))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t// start a goroutine to cancel the errgroup if the parent context is done\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tg.Go(func() error {\n\t\t\treturn ctx.Err()\n", "current_contents": "\tg.SetLimit(runtime.GOMAXPROCS(0))\n\tfor _, t := range meta.Tensors().Items() {\n\t\tg.Go(func() error {\n\t\t\ttts := make([]*C.struct_ggml_tensor, max(1, len(targets[t.Name])))\n\t\t\tfor i := range tts {\n\t\t\t\ttarget := targets[t.Name][i]\n\t\t\t\tif target == \"\" {\n\t\t\t\t\ttarget = t.Name\n\t\t\t\t}\n\n\t\t\t\ttt, ok := tensors[target]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn fmt.Errorf(\"unassigned tensor: %s\", t.Name)\n\t\t\t\t}\n\n\t\t\t\ttts[i] = tt\n\t\t\t}\n\n\t\t\t// Create a new FD for each goroutine so that each FD is read sequentially, rather than\n\t\t\t// seeking around within an FD shared between all goroutines.\n\t\t\tfile, err := os.Open(r.Name())\n\t\t\tif err != nil {\n\t\t\t\tslog.Warn(\"file open error\", \"file\", r.Name(), \"error\", err)\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer file.Close()\n\t\t\tsr := io.NewSectionReader(file, int64(meta.Tensors().Offset+t.Offset), int64(t.Size()))\n\t\t\tbts := make([]byte, 128*format.KibiByte)\n\n\t\t\tvar s uint64\n\t\t\tfor s < t.Size() {\n\t\t\t\tn, err := io.ReadFull(sr, bts[:min(len(bts), int(t.Size()-s))])\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tfor _, tt := range tts {\n\t\t\t\t\tC.ggml_backend_tensor_set(tt, unsafe.Pointer(&bts[0]), C.size_t(s), C.size_t(n))\n\t\t\t\t}\n\n\t\t\t\ts += uint64(n)\n\n\t\t\t\tif params.Progress != nil {\n\t\t\t\t\tdone := doneBytes.Add(uint64(n))\n\t\t\t\t\tparams.Progress(float32(done) / float32(totalBytes))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t// start a goroutine to cancel the errgroup if the parent context is done\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tg.Go(func() error {\n\t\t\treturn ctx.Err()"} {"commit": "6d1103048eac63f27148d6d8fe47c98cbb6f184f", "message": "fix: show correct bool value for kv in verbose show information (#9928)", "old_file": "cmd/cmd_test.go", "new_file": "cmd/cmd_test.go", "status": "M", "old_contents": " embedding length 0 \n quantization FP16 \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"verbose model\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"8B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop up`,\n\t\t\tModelInfo: map[string]any{\n\t\t\t\t\"general.architecture\": \"test\",\n\t\t\t\t\"general.parameter_count\": float64(8_000_000_000),\n\t\t\t\t\"test.context_length\": float64(1000),\n\t\t\t\t\"test.embedding_length\": float64(11434),\n\t\t\t},\n\t\t\tTensors: []api.Tensor{\n\t\t\t\t{Name: \"blk.0.attn_k.weight\", Type: \"BF16\", Shape: []uint64{42, 3117}},\n\t\t\t\t{Name: \"blk.0.attn_q.weight\", Type: \"FP16\", Shape: []uint64{3117, 42}},\n\t\t\t},\n\t\t}, true, &b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpect := ` Model\n architecture test \n parameters 8B \n context length 1000 \n embedding length 11434 \n quantization FP16 \n\n Parameters\n stop up \n\n Metadata\n general.architecture test \n general.parameter_count 8e+09 \n test.context_length 1000 \n test.embedding_length 11434 \n\n Tensors\n blk.0.attn_k.weight BF16 [42 3117] \n blk.0.attn_q.weight FP16 [3117 42] \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"parameters\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"7B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop never\n\t\t\tstop gonna", "new_contents": " embedding length 0 \n quantization FP16 \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"verbose model\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"8B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop up`,\n\t\t\tModelInfo: map[string]any{\n\t\t\t\t\"general.architecture\": \"test\",\n\t\t\t\t\"general.parameter_count\": float64(8_000_000_000),\n\t\t\t\t\"some.true_bool\": true,\n\t\t\t\t\"some.false_bool\": false,\n\t\t\t\t\"test.context_length\": float64(1000),\n\t\t\t\t\"test.embedding_length\": float64(11434),\n\t\t\t},\n\t\t\tTensors: []api.Tensor{\n\t\t\t\t{Name: \"blk.0.attn_k.weight\", Type: \"BF16\", Shape: []uint64{42, 3117}},\n\t\t\t\t{Name: \"blk.0.attn_q.weight\", Type: \"FP16\", Shape: []uint64{3117, 42}},\n\t\t\t},\n\t\t}, true, &b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpect := ` Model\n architecture test \n parameters 8B \n context length 1000 \n embedding length 11434 \n quantization FP16 \n\n Parameters\n stop up \n\n Metadata\n general.architecture test \n general.parameter_count 8e+09 \n some.false_bool false \n some.true_bool true \n test.context_length 1000 \n test.embedding_length 11434 \n\n Tensors\n blk.0.attn_k.weight BF16 [42 3117] \n blk.0.attn_q.weight FP16 [3117 42] \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"parameters\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"7B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop never\n\t\t\tstop gonna", "text": "<|original_code|>\n embedding length 0 \n quantization FP16 \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"verbose model\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"8B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop up`,\n\t\t\tModelInfo: map[string]any{\n\t\t\t\t\"general.architecture\": \"test\",\n\t\t\t\t\"general.parameter_count\": float64(8_000_000_000),\n\t\t\t\t\"test.context_length\": float64(1000),\n\t\t\t\t\"test.embedding_length\": float64(11434),\n\t\t\t},\n\t\t\tTensors: []api.Tensor{\n\t\t\t\t{Name: \"blk.0.attn_k.weight\", Type: \"BF16\", Shape: []uint64{42, 3117}},\n\t\t\t\t{Name: \"blk.0.attn_q.weight\", Type: \"FP16\", Shape: []uint64{3117, 42}},\n\t\t\t},\n\t\t}, true, &b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpect := ` Model\n architecture test \n parameters 8B \n context length 1000 \n embedding length 11434 \n quantization FP16 \n\n Parameters\n stop up \n\n Metadata\n general.architecture test \n general.parameter_count 8e+09 \n test.context_length 1000 \n test.embedding_length 11434 \n\n Tensors\n blk.0.attn_k.weight BF16 [42 3117] \n blk.0.attn_q.weight FP16 [3117 42] \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"parameters\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"7B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop never\n\t\t\tstop gonna\n<|edits_diff|>\n--- cmd/cmd_test.go\n+++ cmd/cmd_test.go\n@@ -20,6 +20,8 @@\n \t\t\tModelInfo: map[string]any{\n \t\t\t\t\"general.architecture\": \"test\",\n \t\t\t\t\"general.parameter_count\": float64(8_000_000_000),\n+\t\t\t\t\"some.true_bool\": true,\n+\t\t\t\t\"some.false_bool\": false,\n \t\t\t\t\"test.context_length\": float64(1000),\n \t\t\t\t\"test.embedding_length\": float64(11434),\n \t\t\t},\n<|current_version|>\n embedding length 0 \n quantization FP16 \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"verbose model\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"8B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop up`,\n\t\t\tModelInfo: map[string]any{\n\t\t\t\t\"general.architecture\": \"test\",\n\t\t\t\t\"general.parameter_count\": float64(8_000_000_000),\n\t\t\t\t\"some.true_bool\": true,\n\t\t\t\t\"some.false_bool\": false,\n\t\t\t\t\"test.context_length\": float64(1000),\n\t\t\t\t\"test.embedding_length\": float64(11434),\n\t\t\t},\n\t\t\tTensors: []api.Tensor{\n\t\t\t\t{Name: \"blk.0.attn_k.weight\", Type: \"BF16\", Shape: []uint64{42, 3117}},\n\t\t\t\t{Name: \"blk.0.attn_q.weight\", Type: \"FP16\", Shape: []uint64{3117, 42}},\n\t\t\t},\n\t\t}, true, &b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpect := ` Model\n architecture test \n parameters 8B \n context length 1000 \n embedding length 11434 \n quantization FP16 \n\n Parameters\n stop up \n\n Metadata\n general.architecture test \n general.parameter_count 8e+09 \n test.context_length 1000 \n test.embedding_length 11434 \n\n Tensors\n blk.0.attn_k.weight BF16 [42 3117] \n blk.0.attn_q.weight FP16 [3117 42] \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"parameters\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"7B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop never\n\t\t\tstop gonna\n<|next_version|>\n embedding length 0 \n quantization FP16 \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"verbose model\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"8B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop up`,\n\t\t\tModelInfo: map[string]any{\n\t\t\t\t\"general.architecture\": \"test\",\n\t\t\t\t\"general.parameter_count\": float64(8_000_000_000),\n\t\t\t\t\"some.true_bool\": true,\n\t\t\t\t\"some.false_bool\": false,\n\t\t\t\t\"test.context_length\": float64(1000),\n\t\t\t\t\"test.embedding_length\": float64(11434),\n\t\t\t},\n\t\t\tTensors: []api.Tensor{\n\t\t\t\t{Name: \"blk.0.attn_k.weight\", Type: \"BF16\", Shape: []uint64{42, 3117}},\n\t\t\t\t{Name: \"blk.0.attn_q.weight\", Type: \"FP16\", Shape: []uint64{3117, 42}},\n\t\t\t},\n\t\t}, true, &b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpect := ` Model\n architecture test \n parameters 8B \n context length 1000 \n embedding length 11434 \n quantization FP16 \n\n Parameters\n stop up \n\n Metadata\n general.architecture test \n general.parameter_count 8e+09 \n some.false_bool false \n some.true_bool true \n test.context_length 1000 \n test.embedding_length 11434 \n\n Tensors\n blk.0.attn_k.weight BF16 [42 3117] \n blk.0.attn_q.weight FP16 [3117 42] \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"parameters\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"7B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop never\n\t\t\tstop gonna\n", "current_contents": " embedding length 0 \n quantization FP16 \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"verbose model\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"8B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop up`,\n\t\t\tModelInfo: map[string]any{\n\t\t\t\t\"general.architecture\": \"test\",\n\t\t\t\t\"general.parameter_count\": float64(8_000_000_000),\n\t\t\t\t\"some.true_bool\": true,\n\t\t\t\t\"some.false_bool\": false,\n\t\t\t\t\"test.context_length\": float64(1000),\n\t\t\t\t\"test.embedding_length\": float64(11434),\n\t\t\t},\n\t\t\tTensors: []api.Tensor{\n\t\t\t\t{Name: \"blk.0.attn_k.weight\", Type: \"BF16\", Shape: []uint64{42, 3117}},\n\t\t\t\t{Name: \"blk.0.attn_q.weight\", Type: \"FP16\", Shape: []uint64{3117, 42}},\n\t\t\t},\n\t\t}, true, &b); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\texpect := ` Model\n architecture test \n parameters 8B \n context length 1000 \n embedding length 11434 \n quantization FP16 \n\n Parameters\n stop up \n\n Metadata\n general.architecture test \n general.parameter_count 8e+09 \n test.context_length 1000 \n test.embedding_length 11434 \n\n Tensors\n blk.0.attn_k.weight BF16 [42 3117] \n blk.0.attn_q.weight FP16 [3117 42] \n\n`\n\t\tif diff := cmp.Diff(expect, b.String()); diff != \"\" {\n\t\t\tt.Errorf(\"unexpected output (-want +got):\\n%s\", diff)\n\t\t}\n\t})\n\n\tt.Run(\"parameters\", func(t *testing.T) {\n\t\tvar b bytes.Buffer\n\t\tif err := showInfo(&api.ShowResponse{\n\t\t\tDetails: api.ModelDetails{\n\t\t\t\tFamily: \"test\",\n\t\t\t\tParameterSize: \"7B\",\n\t\t\t\tQuantizationLevel: \"FP16\",\n\t\t\t},\n\t\t\tParameters: `\n\t\t\tstop never\n\t\t\tstop gonna"} {"commit": "5f8051180e3b9aeafc153f6b5056e7358a939c88", "message": "Enable index tracking for tools - openai api support (#7888)", "old_file": "openai/openai.go", "new_file": "openai/openai.go", "status": "M", "old_contents": "\ntype Completion struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tUsage Usage `json:\"usage,omitempty\"`\n}\n\ntype CompletionChunk struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tType string `json:\"type\"`\n\tFunction struct {\n\t\tName string `json:\"name\"`\n\t\tArguments string `json:\"arguments\"`\n\t} `json:\"function\"`\n}\n\ntype Model struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tOwnedBy string `json:\"owned_by\"`\n}\n\ntype Embedding struct {\n\tObject string `json:\"object\"`\n\tEmbedding []float32 `json:\"embedding\"`\n\tIndex int `json:\"index\"`\n}\n\ntype ListCompletion struct {\n\tObject string `json:\"object\"`\n\tData []Model `json:\"data\"`\n}\n\ntype EmbeddingList struct {\n\tObject string `json:\"object\"`\n\tData []Embedding `json:\"data\"`\n\tModel string `json:\"model\"`\n\tUsage EmbeddingUsage `json:\"usage,omitempty\"`\n}\n\ntype EmbeddingUsage struct {\n\tPromptTokens int `json:\"prompt_tokens\"`\n\tTotalTokens int `json:\"total_tokens\"`\n}\n\nfunc NewError(code int, message string) ErrorResponse {\n\tvar etype string\n\tswitch code {\n\tcase http.StatusBadRequest:\n\t\tetype = \"invalid_request_error\"\n\tcase http.StatusNotFound:\n\t\tetype = \"not_found_error\"\n\tdefault:\n\t\tetype = \"api_error\"\n\t}\n\n\treturn ErrorResponse{Error{Type: etype, Message: message}}\n}\n\nfunc toolCallId() string {\n\tconst letterBytes = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\tb := make([]byte, 8)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Intn(len(letterBytes))]\n\t}\n\treturn \"call_\" + strings.ToLower(string(b))\n}\n\nfunc toToolCalls(tc []api.ToolCall) []ToolCall {\n\ttoolCalls := make([]ToolCall, len(tc))\n\tfor i, tc := range tc {\n\t\ttoolCalls[i].ID = toolCallId()\n\t\ttoolCalls[i].Type = \"function\"\n\t\ttoolCalls[i].Function.Name = tc.Function.Name\n\n\t\targs, err := json.Marshal(tc.Function.Arguments)\n\t\tif err != nil {\n\t\t\tslog.Error(\"could not marshall function arguments to json\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\ttoolCalls[i].Function.Arguments = string(args)\n\t}\n\treturn toolCalls\n}\n\nfunc toChatCompletion(id string, r api.ChatResponse) ChatCompletion {\n\ttoolCalls := toToolCalls(r.Message.ToolCalls)\n\treturn ChatCompletion{\n\t\tId: id,\n\t\tObject: \"chat.completion\",\n\t\tCreated: r.CreatedAt.Unix(),\n\t\tModel: r.Model,\n\t\tSystemFingerprint: \"fp_ollama\",\n\t\tChoices: []Choice{{\n\t\t\tIndex: 0,\n\t\t\tMessage: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls},\n\t\t\tFinishReason: func(reason string) *string {", "new_contents": "\ntype Completion struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tUsage Usage `json:\"usage,omitempty\"`\n}\n\ntype CompletionChunk struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tIndex int `json:\"index\"`\n\tType string `json:\"type\"`\n\tFunction struct {\n\t\tName string `json:\"name\"`\n\t\tArguments string `json:\"arguments\"`\n\t} `json:\"function\"`\n}\n\ntype Model struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tOwnedBy string `json:\"owned_by\"`\n}\n\ntype Embedding struct {\n\tObject string `json:\"object\"`\n\tEmbedding []float32 `json:\"embedding\"`\n\tIndex int `json:\"index\"`\n}\n\ntype ListCompletion struct {\n\tObject string `json:\"object\"`\n\tData []Model `json:\"data\"`\n}\n\ntype EmbeddingList struct {\n\tObject string `json:\"object\"`\n\tData []Embedding `json:\"data\"`\n\tModel string `json:\"model\"`\n\tUsage EmbeddingUsage `json:\"usage,omitempty\"`\n}\n\ntype EmbeddingUsage struct {\n\tPromptTokens int `json:\"prompt_tokens\"`\n\tTotalTokens int `json:\"total_tokens\"`\n}\n\nfunc NewError(code int, message string) ErrorResponse {\n\tvar etype string\n\tswitch code {\n\tcase http.StatusBadRequest:\n\t\tetype = \"invalid_request_error\"\n\tcase http.StatusNotFound:\n\t\tetype = \"not_found_error\"\n\tdefault:\n\t\tetype = \"api_error\"\n\t}\n\n\treturn ErrorResponse{Error{Type: etype, Message: message}}\n}\n\nfunc toolCallId() string {\n\tconst letterBytes = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\tb := make([]byte, 8)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Intn(len(letterBytes))]\n\t}\n\treturn \"call_\" + strings.ToLower(string(b))\n}\n\nfunc toToolCalls(tc []api.ToolCall) []ToolCall {\n\ttoolCalls := make([]ToolCall, len(tc))\n\tfor i, tc := range tc {\n\t\ttoolCalls[i].ID = toolCallId()\n\t\ttoolCalls[i].Type = \"function\"\n\t\ttoolCalls[i].Function.Name = tc.Function.Name\n\t\ttoolCalls[i].Index = tc.Function.Index\n\n\t\targs, err := json.Marshal(tc.Function.Arguments)\n\t\tif err != nil {\n\t\t\tslog.Error(\"could not marshall function arguments to json\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\ttoolCalls[i].Function.Arguments = string(args)\n\t}\n\treturn toolCalls\n}\n\nfunc toChatCompletion(id string, r api.ChatResponse) ChatCompletion {\n\ttoolCalls := toToolCalls(r.Message.ToolCalls)\n\treturn ChatCompletion{\n\t\tId: id,\n\t\tObject: \"chat.completion\",\n\t\tCreated: r.CreatedAt.Unix(),\n\t\tModel: r.Model,\n\t\tSystemFingerprint: \"fp_ollama\",\n\t\tChoices: []Choice{{\n\t\t\tIndex: 0,\n\t\t\tMessage: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls},\n\t\t\tFinishReason: func(reason string) *string {", "text": "<|original_code|>\n\ntype Completion struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tUsage Usage `json:\"usage,omitempty\"`\n}\n\ntype CompletionChunk struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tType string `json:\"type\"`\n\tFunction struct {\n\t\tName string `json:\"name\"`\n\t\tArguments string `json:\"arguments\"`\n\t} `json:\"function\"`\n}\n\ntype Model struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tOwnedBy string `json:\"owned_by\"`\n}\n\ntype Embedding struct {\n\tObject string `json:\"object\"`\n\tEmbedding []float32 `json:\"embedding\"`\n\tIndex int `json:\"index\"`\n}\n\ntype ListCompletion struct {\n\tObject string `json:\"object\"`\n\tData []Model `json:\"data\"`\n}\n\ntype EmbeddingList struct {\n\tObject string `json:\"object\"`\n\tData []Embedding `json:\"data\"`\n\tModel string `json:\"model\"`\n\tUsage EmbeddingUsage `json:\"usage,omitempty\"`\n}\n\ntype EmbeddingUsage struct {\n\tPromptTokens int `json:\"prompt_tokens\"`\n\tTotalTokens int `json:\"total_tokens\"`\n}\n\nfunc NewError(code int, message string) ErrorResponse {\n\tvar etype string\n\tswitch code {\n\tcase http.StatusBadRequest:\n\t\tetype = \"invalid_request_error\"\n\tcase http.StatusNotFound:\n\t\tetype = \"not_found_error\"\n\tdefault:\n\t\tetype = \"api_error\"\n\t}\n\n\treturn ErrorResponse{Error{Type: etype, Message: message}}\n}\n\nfunc toolCallId() string {\n\tconst letterBytes = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\tb := make([]byte, 8)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Intn(len(letterBytes))]\n\t}\n\treturn \"call_\" + strings.ToLower(string(b))\n}\n\nfunc toToolCalls(tc []api.ToolCall) []ToolCall {\n\ttoolCalls := make([]ToolCall, len(tc))\n\tfor i, tc := range tc {\n\t\ttoolCalls[i].ID = toolCallId()\n\t\ttoolCalls[i].Type = \"function\"\n\t\ttoolCalls[i].Function.Name = tc.Function.Name\n\n\t\targs, err := json.Marshal(tc.Function.Arguments)\n\t\tif err != nil {\n\t\t\tslog.Error(\"could not marshall function arguments to json\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\ttoolCalls[i].Function.Arguments = string(args)\n\t}\n\treturn toolCalls\n}\n\nfunc toChatCompletion(id string, r api.ChatResponse) ChatCompletion {\n\ttoolCalls := toToolCalls(r.Message.ToolCalls)\n\treturn ChatCompletion{\n\t\tId: id,\n\t\tObject: \"chat.completion\",\n\t\tCreated: r.CreatedAt.Unix(),\n\t\tModel: r.Model,\n\t\tSystemFingerprint: \"fp_ollama\",\n\t\tChoices: []Choice{{\n\t\t\tIndex: 0,\n\t\t\tMessage: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls},\n\t\t\tFinishReason: func(reason string) *string {\n<|edits_diff|>\n--- openai/openai.go\n+++ openai/openai.go\n@@ -20,6 +20,7 @@\n \n type ToolCall struct {\n \tID string `json:\"id\"`\n+\tIndex int `json:\"index\"`\n \tType string `json:\"type\"`\n \tFunction struct {\n \t\tName string `json:\"name\"`\n<|current_version|>\n\ntype Completion struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tUsage Usage `json:\"usage,omitempty\"`\n}\n\ntype CompletionChunk struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tIndex int `json:\"index\"`\n\tType string `json:\"type\"`\n\tFunction struct {\n\t\tName string `json:\"name\"`\n\t\tArguments string `json:\"arguments\"`\n\t} `json:\"function\"`\n}\n\ntype Model struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tOwnedBy string `json:\"owned_by\"`\n}\n\ntype Embedding struct {\n\tObject string `json:\"object\"`\n\tEmbedding []float32 `json:\"embedding\"`\n\tIndex int `json:\"index\"`\n}\n\ntype ListCompletion struct {\n\tObject string `json:\"object\"`\n\tData []Model `json:\"data\"`\n}\n\ntype EmbeddingList struct {\n\tObject string `json:\"object\"`\n\tData []Embedding `json:\"data\"`\n\tModel string `json:\"model\"`\n\tUsage EmbeddingUsage `json:\"usage,omitempty\"`\n}\n\ntype EmbeddingUsage struct {\n\tPromptTokens int `json:\"prompt_tokens\"`\n\tTotalTokens int `json:\"total_tokens\"`\n}\n\nfunc NewError(code int, message string) ErrorResponse {\n\tvar etype string\n\tswitch code {\n\tcase http.StatusBadRequest:\n\t\tetype = \"invalid_request_error\"\n\tcase http.StatusNotFound:\n\t\tetype = \"not_found_error\"\n\tdefault:\n\t\tetype = \"api_error\"\n\t}\n\n\treturn ErrorResponse{Error{Type: etype, Message: message}}\n}\n\nfunc toolCallId() string {\n\tconst letterBytes = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\tb := make([]byte, 8)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Intn(len(letterBytes))]\n\t}\n\treturn \"call_\" + strings.ToLower(string(b))\n}\n\nfunc toToolCalls(tc []api.ToolCall) []ToolCall {\n\ttoolCalls := make([]ToolCall, len(tc))\n\tfor i, tc := range tc {\n\t\ttoolCalls[i].ID = toolCallId()\n\t\ttoolCalls[i].Type = \"function\"\n\t\ttoolCalls[i].Function.Name = tc.Function.Name\n\n\t\targs, err := json.Marshal(tc.Function.Arguments)\n\t\tif err != nil {\n\t\t\tslog.Error(\"could not marshall function arguments to json\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\ttoolCalls[i].Function.Arguments = string(args)\n\t}\n\treturn toolCalls\n}\n\nfunc toChatCompletion(id string, r api.ChatResponse) ChatCompletion {\n\ttoolCalls := toToolCalls(r.Message.ToolCalls)\n\treturn ChatCompletion{\n\t\tId: id,\n\t\tObject: \"chat.completion\",\n\t\tCreated: r.CreatedAt.Unix(),\n\t\tModel: r.Model,\n\t\tSystemFingerprint: \"fp_ollama\",\n\t\tChoices: []Choice{{\n\t\t\tIndex: 0,\n\t\t\tMessage: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls},\n\t\t\tFinishReason: func(reason string) *string {\n<|next_version|>\n\ntype Completion struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tUsage Usage `json:\"usage,omitempty\"`\n}\n\ntype CompletionChunk struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tIndex int `json:\"index\"`\n\tType string `json:\"type\"`\n\tFunction struct {\n\t\tName string `json:\"name\"`\n\t\tArguments string `json:\"arguments\"`\n\t} `json:\"function\"`\n}\n\ntype Model struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tOwnedBy string `json:\"owned_by\"`\n}\n\ntype Embedding struct {\n\tObject string `json:\"object\"`\n\tEmbedding []float32 `json:\"embedding\"`\n\tIndex int `json:\"index\"`\n}\n\ntype ListCompletion struct {\n\tObject string `json:\"object\"`\n\tData []Model `json:\"data\"`\n}\n\ntype EmbeddingList struct {\n\tObject string `json:\"object\"`\n\tData []Embedding `json:\"data\"`\n\tModel string `json:\"model\"`\n\tUsage EmbeddingUsage `json:\"usage,omitempty\"`\n}\n\ntype EmbeddingUsage struct {\n\tPromptTokens int `json:\"prompt_tokens\"`\n\tTotalTokens int `json:\"total_tokens\"`\n}\n\nfunc NewError(code int, message string) ErrorResponse {\n\tvar etype string\n\tswitch code {\n\tcase http.StatusBadRequest:\n\t\tetype = \"invalid_request_error\"\n\tcase http.StatusNotFound:\n\t\tetype = \"not_found_error\"\n\tdefault:\n\t\tetype = \"api_error\"\n\t}\n\n\treturn ErrorResponse{Error{Type: etype, Message: message}}\n}\n\nfunc toolCallId() string {\n\tconst letterBytes = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\tb := make([]byte, 8)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Intn(len(letterBytes))]\n\t}\n\treturn \"call_\" + strings.ToLower(string(b))\n}\n\nfunc toToolCalls(tc []api.ToolCall) []ToolCall {\n\ttoolCalls := make([]ToolCall, len(tc))\n\tfor i, tc := range tc {\n\t\ttoolCalls[i].ID = toolCallId()\n\t\ttoolCalls[i].Type = \"function\"\n\t\ttoolCalls[i].Function.Name = tc.Function.Name\n\t\ttoolCalls[i].Index = tc.Function.Index\n\n\t\targs, err := json.Marshal(tc.Function.Arguments)\n\t\tif err != nil {\n\t\t\tslog.Error(\"could not marshall function arguments to json\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\ttoolCalls[i].Function.Arguments = string(args)\n\t}\n\treturn toolCalls\n}\n\nfunc toChatCompletion(id string, r api.ChatResponse) ChatCompletion {\n\ttoolCalls := toToolCalls(r.Message.ToolCalls)\n\treturn ChatCompletion{\n\t\tId: id,\n\t\tObject: \"chat.completion\",\n\t\tCreated: r.CreatedAt.Unix(),\n\t\tModel: r.Model,\n\t\tSystemFingerprint: \"fp_ollama\",\n\t\tChoices: []Choice{{\n\t\t\tIndex: 0,\n\t\t\tMessage: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls},\n\t\t\tFinishReason: func(reason string) *string {\n", "current_contents": "\ntype Completion struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tUsage Usage `json:\"usage,omitempty\"`\n}\n\ntype CompletionChunk struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tChoices []CompleteChunkChoice `json:\"choices\"`\n\tModel string `json:\"model\"`\n\tSystemFingerprint string `json:\"system_fingerprint\"`\n}\n\ntype ToolCall struct {\n\tID string `json:\"id\"`\n\tIndex int `json:\"index\"`\n\tType string `json:\"type\"`\n\tFunction struct {\n\t\tName string `json:\"name\"`\n\t\tArguments string `json:\"arguments\"`\n\t} `json:\"function\"`\n}\n\ntype Model struct {\n\tId string `json:\"id\"`\n\tObject string `json:\"object\"`\n\tCreated int64 `json:\"created\"`\n\tOwnedBy string `json:\"owned_by\"`\n}\n\ntype Embedding struct {\n\tObject string `json:\"object\"`\n\tEmbedding []float32 `json:\"embedding\"`\n\tIndex int `json:\"index\"`\n}\n\ntype ListCompletion struct {\n\tObject string `json:\"object\"`\n\tData []Model `json:\"data\"`\n}\n\ntype EmbeddingList struct {\n\tObject string `json:\"object\"`\n\tData []Embedding `json:\"data\"`\n\tModel string `json:\"model\"`\n\tUsage EmbeddingUsage `json:\"usage,omitempty\"`\n}\n\ntype EmbeddingUsage struct {\n\tPromptTokens int `json:\"prompt_tokens\"`\n\tTotalTokens int `json:\"total_tokens\"`\n}\n\nfunc NewError(code int, message string) ErrorResponse {\n\tvar etype string\n\tswitch code {\n\tcase http.StatusBadRequest:\n\t\tetype = \"invalid_request_error\"\n\tcase http.StatusNotFound:\n\t\tetype = \"not_found_error\"\n\tdefault:\n\t\tetype = \"api_error\"\n\t}\n\n\treturn ErrorResponse{Error{Type: etype, Message: message}}\n}\n\nfunc toolCallId() string {\n\tconst letterBytes = \"abcdefghijklmnopqrstuvwxyz0123456789\"\n\tb := make([]byte, 8)\n\tfor i := range b {\n\t\tb[i] = letterBytes[rand.Intn(len(letterBytes))]\n\t}\n\treturn \"call_\" + strings.ToLower(string(b))\n}\n\nfunc toToolCalls(tc []api.ToolCall) []ToolCall {\n\ttoolCalls := make([]ToolCall, len(tc))\n\tfor i, tc := range tc {\n\t\ttoolCalls[i].ID = toolCallId()\n\t\ttoolCalls[i].Type = \"function\"\n\t\ttoolCalls[i].Function.Name = tc.Function.Name\n\n\t\targs, err := json.Marshal(tc.Function.Arguments)\n\t\tif err != nil {\n\t\t\tslog.Error(\"could not marshall function arguments to json\", \"error\", err)\n\t\t\tcontinue\n\t\t}\n\n\t\ttoolCalls[i].Function.Arguments = string(args)\n\t}\n\treturn toolCalls\n}\n\nfunc toChatCompletion(id string, r api.ChatResponse) ChatCompletion {\n\ttoolCalls := toToolCalls(r.Message.ToolCalls)\n\treturn ChatCompletion{\n\t\tId: id,\n\t\tObject: \"chat.completion\",\n\t\tCreated: r.CreatedAt.Unix(),\n\t\tModel: r.Model,\n\t\tSystemFingerprint: \"fp_ollama\",\n\t\tChoices: []Choice{{\n\t\t\tIndex: 0,\n\t\t\tMessage: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls},\n\t\t\tFinishReason: func(reason string) *string {"} {"commit": "91dfbb1bba3318c1604e75ecc95e23b2991001db", "message": "windows: Support alt install paths, fit and finish (#6967)", "old_file": "app/lifecycle/server.go", "new_file": "app/lifecycle/server.go", "status": "M", "old_contents": "package lifecycle\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/ollama/ollama/api\"\n)\n\nfunc getCLIFullPath(command string) string {\n\tvar cmdPath string\n\tappExe, err := os.Executable()\n\tif err == nil {\n\t\tcmdPath = filepath.Join(filepath.Dir(appExe), command)\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tcmdPath, err = exec.LookPath(command)\n\tif err == nil {\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tpwd, err := os.Getwd()\n\tif err == nil {\n\t\tcmdPath = filepath.Join(pwd, command)\n\t\t_, err = os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\n\treturn command\n}\n\nfunc start(ctx context.Context, command string) (*exec.Cmd, error) {", "new_contents": "package lifecycle\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/ollama/ollama/api\"\n)\n\nfunc getCLIFullPath(command string) string {\n\tvar cmdPath string\n\tappExe, err := os.Executable()\n\tif err == nil {\n\t\t// Check both the same location as the tray app, as well as ./bin\n\t\tcmdPath = filepath.Join(filepath.Dir(appExe), command)\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t\tcmdPath = filepath.Join(filepath.Dir(appExe), \"bin\", command)\n\t\t_, err = os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tcmdPath, err = exec.LookPath(command)\n\tif err == nil {\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tpwd, err := os.Getwd()\n\tif err == nil {\n\t\tcmdPath = filepath.Join(pwd, command)\n\t\t_, err = os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\n\treturn command\n}\n\nfunc start(ctx context.Context, command string) (*exec.Cmd, error) {", "text": "<|original_code|>\npackage lifecycle\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/ollama/ollama/api\"\n)\n\nfunc getCLIFullPath(command string) string {\n\tvar cmdPath string\n\tappExe, err := os.Executable()\n\tif err == nil {\n\t\tcmdPath = filepath.Join(filepath.Dir(appExe), command)\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tcmdPath, err = exec.LookPath(command)\n\tif err == nil {\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tpwd, err := os.Getwd()\n\tif err == nil {\n\t\tcmdPath = filepath.Join(pwd, command)\n\t\t_, err = os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\n\treturn command\n}\n\nfunc start(ctx context.Context, command string) (*exec.Cmd, error) {\n<|edits_diff|>\n--- app/lifecycle/server.go\n+++ app/lifecycle/server.go\n@@ -18,6 +18,7 @@\n \tvar cmdPath string\n \tappExe, err := os.Executable()\n \tif err == nil {\n+\t\t// Check both the same location as the tray app, as well as ./bin\n \t\tcmdPath = filepath.Join(filepath.Dir(appExe), command)\n \t\t_, err := os.Stat(cmdPath)\n \t\tif err == nil {\n<|current_version|>\npackage lifecycle\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/ollama/ollama/api\"\n)\n\nfunc getCLIFullPath(command string) string {\n\tvar cmdPath string\n\tappExe, err := os.Executable()\n\tif err == nil {\n\t\t// Check both the same location as the tray app, as well as ./bin\n\t\tcmdPath = filepath.Join(filepath.Dir(appExe), command)\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tcmdPath, err = exec.LookPath(command)\n\tif err == nil {\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tpwd, err := os.Getwd()\n\tif err == nil {\n\t\tcmdPath = filepath.Join(pwd, command)\n\t\t_, err = os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\n\treturn command\n}\n\nfunc start(ctx context.Context, command string) (*exec.Cmd, error) {\n<|next_version|>\npackage lifecycle\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/ollama/ollama/api\"\n)\n\nfunc getCLIFullPath(command string) string {\n\tvar cmdPath string\n\tappExe, err := os.Executable()\n\tif err == nil {\n\t\t// Check both the same location as the tray app, as well as ./bin\n\t\tcmdPath = filepath.Join(filepath.Dir(appExe), command)\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t\tcmdPath = filepath.Join(filepath.Dir(appExe), \"bin\", command)\n\t\t_, err = os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tcmdPath, err = exec.LookPath(command)\n\tif err == nil {\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tpwd, err := os.Getwd()\n\tif err == nil {\n\t\tcmdPath = filepath.Join(pwd, command)\n\t\t_, err = os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\n\treturn command\n}\n\nfunc start(ctx context.Context, command string) (*exec.Cmd, error) {\n", "current_contents": "package lifecycle\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"time\"\n\n\t\"github.com/ollama/ollama/api\"\n)\n\nfunc getCLIFullPath(command string) string {\n\tvar cmdPath string\n\tappExe, err := os.Executable()\n\tif err == nil {\n\t\t// Check both the same location as the tray app, as well as ./bin\n\t\tcmdPath = filepath.Join(filepath.Dir(appExe), command)\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tcmdPath, err = exec.LookPath(command)\n\tif err == nil {\n\t\t_, err := os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\tpwd, err := os.Getwd()\n\tif err == nil {\n\t\tcmdPath = filepath.Join(pwd, command)\n\t\t_, err = os.Stat(cmdPath)\n\t\tif err == nil {\n\t\t\treturn cmdPath\n\t\t}\n\t}\n\n\treturn command\n}\n\nfunc start(ctx context.Context, command string) (*exec.Cmd, error) {"} {"commit": "0d41623b52b77725624a9f4dbc4c0f9a356a9021", "message": "OpenAI: Add Suffix to `v1/completions` (#5611)", "old_file": "openai/openai_test.go", "new_file": "openai/openai_test.go", "status": "M", "old_contents": "\n\t\t\t\tif chatReq.Messages[0].Role != \"user\" {\n\t\t\t\t\tt.Fatalf(\"expected 'user', got %s\", chatReq.Messages[0].Role)\n\t\t\t\t}\n\n\t\t\t\tif chatReq.Messages[0].Content != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", chatReq.Messages[0].Content)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"completions handler\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/generate\",\n\t\t\tHandler: CompletionsMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\ttemp := float32(0.8)\n\t\t\t\tbody := CompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tPrompt: \"Hello\",\n\t\t\t\t\tTemperature: &temp,\n\t\t\t\t\tStop: []string{\"\\n\", \"stop\"},\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t},\n\t\t\tExpected: func(t *testing.T, req *http.Request) {\n\t\t\t\tvar genReq api.GenerateRequest\n\t\t\t\tif err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Prompt != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", genReq.Prompt)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Options[\"temperature\"] != 1.6 {\n\t\t\t\t\tt.Fatalf(\"expected 1.6, got %f\", genReq.Options[\"temperature\"])\n\t\t\t\t}\n\n\t\t\t\tstopTokens, ok := genReq.Options[\"stop\"].([]any)\n\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"expected stop tokens to be a list\")\n\t\t\t\t}\n\n\t\t\t\tif stopTokens[0] != \"\\n\" || stopTokens[1] != \"stop\" {\n\t\t\t\t\tt.Fatalf(\"expected ['\\\\n', 'stop'], got %v\", stopTokens)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"chat handler with image content\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/chat\",\n\t\t\tHandler: ChatMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\tbody := ChatCompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tMessages: []Message{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRole: \"user\", Content: []map[string]any{\n\t\t\t\t\t\t\t\t{\"type\": \"text\", \"text\": \"Hello\"},\n\t\t\t\t\t\t\t\t{\"type\": \"image_url\", \"image_url\": map[string]string{\"url\": imageURL}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))", "new_contents": "\n\t\t\t\tif chatReq.Messages[0].Role != \"user\" {\n\t\t\t\t\tt.Fatalf(\"expected 'user', got %s\", chatReq.Messages[0].Role)\n\t\t\t\t}\n\n\t\t\t\tif chatReq.Messages[0].Content != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", chatReq.Messages[0].Content)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"completions handler\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/generate\",\n\t\t\tHandler: CompletionsMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\ttemp := float32(0.8)\n\t\t\t\tbody := CompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tPrompt: \"Hello\",\n\t\t\t\t\tTemperature: &temp,\n\t\t\t\t\tStop: []string{\"\\n\", \"stop\"},\n\t\t\t\t\tSuffix: \"suffix\",\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t},\n\t\t\tExpected: func(t *testing.T, req *http.Request) {\n\t\t\t\tvar genReq api.GenerateRequest\n\t\t\t\tif err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Prompt != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", genReq.Prompt)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Options[\"temperature\"] != 1.6 {\n\t\t\t\t\tt.Fatalf(\"expected 1.6, got %f\", genReq.Options[\"temperature\"])\n\t\t\t\t}\n\n\t\t\t\tstopTokens, ok := genReq.Options[\"stop\"].([]any)\n\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"expected stop tokens to be a list\")\n\t\t\t\t}\n\n\t\t\t\tif stopTokens[0] != \"\\n\" || stopTokens[1] != \"stop\" {\n\t\t\t\t\tt.Fatalf(\"expected ['\\\\n', 'stop'], got %v\", stopTokens)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Suffix != \"suffix\" {\n\t\t\t\t\tt.Fatalf(\"expected 'suffix', got %s\", genReq.Suffix)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"chat handler with image content\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/chat\",\n\t\t\tHandler: ChatMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\tbody := ChatCompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tMessages: []Message{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRole: \"user\", Content: []map[string]any{\n\t\t\t\t\t\t\t\t{\"type\": \"text\", \"text\": \"Hello\"},\n\t\t\t\t\t\t\t\t{\"type\": \"image_url\", \"image_url\": map[string]string{\"url\": imageURL}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))", "text": "<|original_code|>\n\n\t\t\t\tif chatReq.Messages[0].Role != \"user\" {\n\t\t\t\t\tt.Fatalf(\"expected 'user', got %s\", chatReq.Messages[0].Role)\n\t\t\t\t}\n\n\t\t\t\tif chatReq.Messages[0].Content != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", chatReq.Messages[0].Content)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"completions handler\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/generate\",\n\t\t\tHandler: CompletionsMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\ttemp := float32(0.8)\n\t\t\t\tbody := CompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tPrompt: \"Hello\",\n\t\t\t\t\tTemperature: &temp,\n\t\t\t\t\tStop: []string{\"\\n\", \"stop\"},\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t},\n\t\t\tExpected: func(t *testing.T, req *http.Request) {\n\t\t\t\tvar genReq api.GenerateRequest\n\t\t\t\tif err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Prompt != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", genReq.Prompt)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Options[\"temperature\"] != 1.6 {\n\t\t\t\t\tt.Fatalf(\"expected 1.6, got %f\", genReq.Options[\"temperature\"])\n\t\t\t\t}\n\n\t\t\t\tstopTokens, ok := genReq.Options[\"stop\"].([]any)\n\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"expected stop tokens to be a list\")\n\t\t\t\t}\n\n\t\t\t\tif stopTokens[0] != \"\\n\" || stopTokens[1] != \"stop\" {\n\t\t\t\t\tt.Fatalf(\"expected ['\\\\n', 'stop'], got %v\", stopTokens)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"chat handler with image content\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/chat\",\n\t\t\tHandler: ChatMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\tbody := ChatCompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tMessages: []Message{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRole: \"user\", Content: []map[string]any{\n\t\t\t\t\t\t\t\t{\"type\": \"text\", \"text\": \"Hello\"},\n\t\t\t\t\t\t\t\t{\"type\": \"image_url\", \"image_url\": map[string]string{\"url\": imageURL}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n<|edits_diff|>\n--- openai/openai_test.go\n+++ openai/openai_test.go\n@@ -20,6 +20,7 @@\n \t\t\t\t\tPrompt: \"Hello\",\n \t\t\t\t\tTemperature: &temp,\n \t\t\t\t\tStop: []string{\"\\n\", \"stop\"},\n+\t\t\t\t\tSuffix: \"suffix\",\n \t\t\t\t}\n \n \t\t\t\tbodyBytes, _ := json.Marshal(body)\n<|current_version|>\n\n\t\t\t\tif chatReq.Messages[0].Role != \"user\" {\n\t\t\t\t\tt.Fatalf(\"expected 'user', got %s\", chatReq.Messages[0].Role)\n\t\t\t\t}\n\n\t\t\t\tif chatReq.Messages[0].Content != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", chatReq.Messages[0].Content)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"completions handler\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/generate\",\n\t\t\tHandler: CompletionsMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\ttemp := float32(0.8)\n\t\t\t\tbody := CompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tPrompt: \"Hello\",\n\t\t\t\t\tTemperature: &temp,\n\t\t\t\t\tStop: []string{\"\\n\", \"stop\"},\n\t\t\t\t\tSuffix: \"suffix\",\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t},\n\t\t\tExpected: func(t *testing.T, req *http.Request) {\n\t\t\t\tvar genReq api.GenerateRequest\n\t\t\t\tif err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Prompt != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", genReq.Prompt)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Options[\"temperature\"] != 1.6 {\n\t\t\t\t\tt.Fatalf(\"expected 1.6, got %f\", genReq.Options[\"temperature\"])\n\t\t\t\t}\n\n\t\t\t\tstopTokens, ok := genReq.Options[\"stop\"].([]any)\n\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"expected stop tokens to be a list\")\n\t\t\t\t}\n\n\t\t\t\tif stopTokens[0] != \"\\n\" || stopTokens[1] != \"stop\" {\n\t\t\t\t\tt.Fatalf(\"expected ['\\\\n', 'stop'], got %v\", stopTokens)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"chat handler with image content\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/chat\",\n\t\t\tHandler: ChatMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\tbody := ChatCompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tMessages: []Message{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRole: \"user\", Content: []map[string]any{\n\t\t\t\t\t\t\t\t{\"type\": \"text\", \"text\": \"Hello\"},\n\t\t\t\t\t\t\t\t{\"type\": \"image_url\", \"image_url\": map[string]string{\"url\": imageURL}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n<|next_version|>\n\n\t\t\t\tif chatReq.Messages[0].Role != \"user\" {\n\t\t\t\t\tt.Fatalf(\"expected 'user', got %s\", chatReq.Messages[0].Role)\n\t\t\t\t}\n\n\t\t\t\tif chatReq.Messages[0].Content != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", chatReq.Messages[0].Content)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"completions handler\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/generate\",\n\t\t\tHandler: CompletionsMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\ttemp := float32(0.8)\n\t\t\t\tbody := CompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tPrompt: \"Hello\",\n\t\t\t\t\tTemperature: &temp,\n\t\t\t\t\tStop: []string{\"\\n\", \"stop\"},\n\t\t\t\t\tSuffix: \"suffix\",\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t},\n\t\t\tExpected: func(t *testing.T, req *http.Request) {\n\t\t\t\tvar genReq api.GenerateRequest\n\t\t\t\tif err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Prompt != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", genReq.Prompt)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Options[\"temperature\"] != 1.6 {\n\t\t\t\t\tt.Fatalf(\"expected 1.6, got %f\", genReq.Options[\"temperature\"])\n\t\t\t\t}\n\n\t\t\t\tstopTokens, ok := genReq.Options[\"stop\"].([]any)\n\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"expected stop tokens to be a list\")\n\t\t\t\t}\n\n\t\t\t\tif stopTokens[0] != \"\\n\" || stopTokens[1] != \"stop\" {\n\t\t\t\t\tt.Fatalf(\"expected ['\\\\n', 'stop'], got %v\", stopTokens)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Suffix != \"suffix\" {\n\t\t\t\t\tt.Fatalf(\"expected 'suffix', got %s\", genReq.Suffix)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"chat handler with image content\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/chat\",\n\t\t\tHandler: ChatMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\tbody := ChatCompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tMessages: []Message{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRole: \"user\", Content: []map[string]any{\n\t\t\t\t\t\t\t\t{\"type\": \"text\", \"text\": \"Hello\"},\n\t\t\t\t\t\t\t\t{\"type\": \"image_url\", \"image_url\": map[string]string{\"url\": imageURL}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n", "current_contents": "\n\t\t\t\tif chatReq.Messages[0].Role != \"user\" {\n\t\t\t\t\tt.Fatalf(\"expected 'user', got %s\", chatReq.Messages[0].Role)\n\t\t\t\t}\n\n\t\t\t\tif chatReq.Messages[0].Content != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", chatReq.Messages[0].Content)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"completions handler\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/generate\",\n\t\t\tHandler: CompletionsMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\ttemp := float32(0.8)\n\t\t\t\tbody := CompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tPrompt: \"Hello\",\n\t\t\t\t\tTemperature: &temp,\n\t\t\t\t\tStop: []string{\"\\n\", \"stop\"},\n\t\t\t\t\tSuffix: \"suffix\",\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t},\n\t\t\tExpected: func(t *testing.T, req *http.Request) {\n\t\t\t\tvar genReq api.GenerateRequest\n\t\t\t\tif err := json.NewDecoder(req.Body).Decode(&genReq); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Prompt != \"Hello\" {\n\t\t\t\t\tt.Fatalf(\"expected 'Hello', got %s\", genReq.Prompt)\n\t\t\t\t}\n\n\t\t\t\tif genReq.Options[\"temperature\"] != 1.6 {\n\t\t\t\t\tt.Fatalf(\"expected 1.6, got %f\", genReq.Options[\"temperature\"])\n\t\t\t\t}\n\n\t\t\t\tstopTokens, ok := genReq.Options[\"stop\"].([]any)\n\n\t\t\t\tif !ok {\n\t\t\t\t\tt.Fatalf(\"expected stop tokens to be a list\")\n\t\t\t\t}\n\n\t\t\t\tif stopTokens[0] != \"\\n\" || stopTokens[1] != \"stop\" {\n\t\t\t\t\tt.Fatalf(\"expected ['\\\\n', 'stop'], got %v\", stopTokens)\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"chat handler with image content\",\n\t\t\tMethod: http.MethodPost,\n\t\t\tPath: \"/api/chat\",\n\t\t\tHandler: ChatMiddleware,\n\t\t\tSetup: func(t *testing.T, req *http.Request) {\n\t\t\t\tbody := ChatCompletionRequest{\n\t\t\t\t\tModel: \"test-model\",\n\t\t\t\t\tMessages: []Message{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRole: \"user\", Content: []map[string]any{\n\t\t\t\t\t\t\t\t{\"type\": \"text\", \"text\": \"Hello\"},\n\t\t\t\t\t\t\t\t{\"type\": \"image_url\", \"image_url\": map[string]string{\"url\": imageURL}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}\n\n\t\t\t\tbodyBytes, _ := json.Marshal(body)\n\n\t\t\t\treq.Body = io.NopCloser(bytes.NewReader(bodyBytes))"} {"commit": "c4cf8ad55966cc61c73f119ab9cbfaf57264fc81", "message": "llm: avoid loading model if system memory is too small (#5637)", "old_file": "gpu/gpu.go", "new_file": "gpu/gpu.go", "status": "M", "old_contents": "\t\t}\n\n\t\trocmGPUs = AMDGetGPUInfo()\n\t\tbootstrapped = true\n\t\tif len(cudaGPUs) == 0 && len(rocmGPUs) == 0 && len(oneapiGPUs) == 0 {\n\t\t\tslog.Info(\"no compatible GPUs were discovered\")\n\t\t}\n\t}\n\n\t// For detected GPUs, load library if not loaded\n\n\t// Refresh free memory usage\n\tif needRefresh {\n\t\tmem, err := GetCPUMem()\n\t\tif err != nil {\n\t\t\tslog.Warn(\"error looking up system memory\", \"error\", err)\n\t\t} else {\n\t\t\tslog.Debug(\"updating system memory data\",\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"before\",\n\t\t\t\t\t\"total\", format.HumanBytes2(cpus[0].TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(cpus[0].FreeMemory),\n\t\t\t\t),\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"now\",\n\t\t\t\t\t\"total\", format.HumanBytes2(mem.TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(mem.FreeMemory),\n\t\t\t\t),\n\t\t\t)\n\t\t\tcpus[0].FreeMemory = mem.FreeMemory\n\t\t}\n\n\t\tvar memInfo C.mem_info_t\n\t\tif cHandles == nil && len(cudaGPUs) > 0 {\n\t\t\tcHandles = initCudaHandles()\n\t\t}\n\t\tfor i, gpu := range cudaGPUs {\n\t\t\tif cHandles.nvml != nil {\n\t\t\t\tC.nvml_get_free(*cHandles.nvml, C.int(gpu.index), &memInfo.free, &memInfo.total, &memInfo.used)\n\t\t\t} else if cHandles.cudart != nil {\n\t\t\t\tC.cudart_bootstrap(*cHandles.cudart, C.int(gpu.index), &memInfo)\n\t\t\t} else if cHandles.nvcuda != nil {\n\t\t\t\tC.nvcuda_get_free(*cHandles.nvcuda, C.int(gpu.index), &memInfo.free, &memInfo.total)\n\t\t\t\tmemInfo.used = memInfo.total - memInfo.free\n\t\t\t} else {\n\t\t\t\t// shouldn't happen\n\t\t\t\tslog.Warn(\"no valid cuda library loaded to refresh vram usage\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif memInfo.err != nil {\n\t\t\t\tslog.Warn(\"error looking up nvidia GPU memory\", \"error\", C.GoString(memInfo.err))\n\t\t\t\tC.free(unsafe.Pointer(memInfo.err))\n\t\t\t\tcontinue\n\t\t\t}", "new_contents": "\t\t}\n\n\t\trocmGPUs = AMDGetGPUInfo()\n\t\tbootstrapped = true\n\t\tif len(cudaGPUs) == 0 && len(rocmGPUs) == 0 && len(oneapiGPUs) == 0 {\n\t\t\tslog.Info(\"no compatible GPUs were discovered\")\n\t\t}\n\t}\n\n\t// For detected GPUs, load library if not loaded\n\n\t// Refresh free memory usage\n\tif needRefresh {\n\t\tmem, err := GetCPUMem()\n\t\tif err != nil {\n\t\t\tslog.Warn(\"error looking up system memory\", \"error\", err)\n\t\t} else {\n\t\t\tslog.Debug(\"updating system memory data\",\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"before\",\n\t\t\t\t\t\"total\", format.HumanBytes2(cpus[0].TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(cpus[0].FreeMemory),\n\t\t\t\t\t\"free_swap\", format.HumanBytes2(cpus[0].FreeSwap),\n\t\t\t\t),\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"now\",\n\t\t\t\t\t\"total\", format.HumanBytes2(mem.TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(mem.FreeMemory),\n\t\t\t\t\t\"free_swap\", format.HumanBytes2(mem.FreeSwap),\n\t\t\t\t),\n\t\t\t)\n\t\t\tcpus[0].FreeMemory = mem.FreeMemory\n\t\t\tcpus[0].FreeSwap = mem.FreeSwap\n\t\t}\n\n\t\tvar memInfo C.mem_info_t\n\t\tif cHandles == nil && len(cudaGPUs) > 0 {\n\t\t\tcHandles = initCudaHandles()\n\t\t}\n\t\tfor i, gpu := range cudaGPUs {\n\t\t\tif cHandles.nvml != nil {\n\t\t\t\tC.nvml_get_free(*cHandles.nvml, C.int(gpu.index), &memInfo.free, &memInfo.total, &memInfo.used)\n\t\t\t} else if cHandles.cudart != nil {\n\t\t\t\tC.cudart_bootstrap(*cHandles.cudart, C.int(gpu.index), &memInfo)\n\t\t\t} else if cHandles.nvcuda != nil {\n\t\t\t\tC.nvcuda_get_free(*cHandles.nvcuda, C.int(gpu.index), &memInfo.free, &memInfo.total)\n\t\t\t\tmemInfo.used = memInfo.total - memInfo.free\n\t\t\t} else {\n\t\t\t\t// shouldn't happen\n\t\t\t\tslog.Warn(\"no valid cuda library loaded to refresh vram usage\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif memInfo.err != nil {\n\t\t\t\tslog.Warn(\"error looking up nvidia GPU memory\", \"error\", C.GoString(memInfo.err))\n\t\t\t\tC.free(unsafe.Pointer(memInfo.err))\n\t\t\t\tcontinue\n\t\t\t}", "text": "<|original_code|>\n\t\t}\n\n\t\trocmGPUs = AMDGetGPUInfo()\n\t\tbootstrapped = true\n\t\tif len(cudaGPUs) == 0 && len(rocmGPUs) == 0 && len(oneapiGPUs) == 0 {\n\t\t\tslog.Info(\"no compatible GPUs were discovered\")\n\t\t}\n\t}\n\n\t// For detected GPUs, load library if not loaded\n\n\t// Refresh free memory usage\n\tif needRefresh {\n\t\tmem, err := GetCPUMem()\n\t\tif err != nil {\n\t\t\tslog.Warn(\"error looking up system memory\", \"error\", err)\n\t\t} else {\n\t\t\tslog.Debug(\"updating system memory data\",\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"before\",\n\t\t\t\t\t\"total\", format.HumanBytes2(cpus[0].TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(cpus[0].FreeMemory),\n\t\t\t\t),\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"now\",\n\t\t\t\t\t\"total\", format.HumanBytes2(mem.TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(mem.FreeMemory),\n\t\t\t\t),\n\t\t\t)\n\t\t\tcpus[0].FreeMemory = mem.FreeMemory\n\t\t}\n\n\t\tvar memInfo C.mem_info_t\n\t\tif cHandles == nil && len(cudaGPUs) > 0 {\n\t\t\tcHandles = initCudaHandles()\n\t\t}\n\t\tfor i, gpu := range cudaGPUs {\n\t\t\tif cHandles.nvml != nil {\n\t\t\t\tC.nvml_get_free(*cHandles.nvml, C.int(gpu.index), &memInfo.free, &memInfo.total, &memInfo.used)\n\t\t\t} else if cHandles.cudart != nil {\n\t\t\t\tC.cudart_bootstrap(*cHandles.cudart, C.int(gpu.index), &memInfo)\n\t\t\t} else if cHandles.nvcuda != nil {\n\t\t\t\tC.nvcuda_get_free(*cHandles.nvcuda, C.int(gpu.index), &memInfo.free, &memInfo.total)\n\t\t\t\tmemInfo.used = memInfo.total - memInfo.free\n\t\t\t} else {\n\t\t\t\t// shouldn't happen\n\t\t\t\tslog.Warn(\"no valid cuda library loaded to refresh vram usage\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif memInfo.err != nil {\n\t\t\t\tslog.Warn(\"error looking up nvidia GPU memory\", \"error\", C.GoString(memInfo.err))\n\t\t\t\tC.free(unsafe.Pointer(memInfo.err))\n\t\t\t\tcontinue\n\t\t\t}\n<|edits_diff|>\n--- gpu/gpu.go\n+++ gpu/gpu.go\n@@ -20,11 +20,13 @@\n \t\t\t\t\t\"before\",\n \t\t\t\t\t\"total\", format.HumanBytes2(cpus[0].TotalMemory),\n \t\t\t\t\t\"free\", format.HumanBytes2(cpus[0].FreeMemory),\n+\t\t\t\t\t\"free_swap\", format.HumanBytes2(cpus[0].FreeSwap),\n \t\t\t\t),\n \t\t\t\tslog.Group(\n \t\t\t\t\t\"now\",\n \t\t\t\t\t\"total\", format.HumanBytes2(mem.TotalMemory),\n \t\t\t\t\t\"free\", format.HumanBytes2(mem.FreeMemory),\n+\t\t\t\t\t\"free_swap\", format.HumanBytes2(mem.FreeSwap),\n \t\t\t\t),\n \t\t\t)\n \t\t\tcpus[0].FreeMemory = mem.FreeMemory\n<|current_version|>\n\t\t}\n\n\t\trocmGPUs = AMDGetGPUInfo()\n\t\tbootstrapped = true\n\t\tif len(cudaGPUs) == 0 && len(rocmGPUs) == 0 && len(oneapiGPUs) == 0 {\n\t\t\tslog.Info(\"no compatible GPUs were discovered\")\n\t\t}\n\t}\n\n\t// For detected GPUs, load library if not loaded\n\n\t// Refresh free memory usage\n\tif needRefresh {\n\t\tmem, err := GetCPUMem()\n\t\tif err != nil {\n\t\t\tslog.Warn(\"error looking up system memory\", \"error\", err)\n\t\t} else {\n\t\t\tslog.Debug(\"updating system memory data\",\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"before\",\n\t\t\t\t\t\"total\", format.HumanBytes2(cpus[0].TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(cpus[0].FreeMemory),\n\t\t\t\t\t\"free_swap\", format.HumanBytes2(cpus[0].FreeSwap),\n\t\t\t\t),\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"now\",\n\t\t\t\t\t\"total\", format.HumanBytes2(mem.TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(mem.FreeMemory),\n\t\t\t\t\t\"free_swap\", format.HumanBytes2(mem.FreeSwap),\n\t\t\t\t),\n\t\t\t)\n\t\t\tcpus[0].FreeMemory = mem.FreeMemory\n\t\t}\n\n\t\tvar memInfo C.mem_info_t\n\t\tif cHandles == nil && len(cudaGPUs) > 0 {\n\t\t\tcHandles = initCudaHandles()\n\t\t}\n\t\tfor i, gpu := range cudaGPUs {\n\t\t\tif cHandles.nvml != nil {\n\t\t\t\tC.nvml_get_free(*cHandles.nvml, C.int(gpu.index), &memInfo.free, &memInfo.total, &memInfo.used)\n\t\t\t} else if cHandles.cudart != nil {\n\t\t\t\tC.cudart_bootstrap(*cHandles.cudart, C.int(gpu.index), &memInfo)\n\t\t\t} else if cHandles.nvcuda != nil {\n\t\t\t\tC.nvcuda_get_free(*cHandles.nvcuda, C.int(gpu.index), &memInfo.free, &memInfo.total)\n\t\t\t\tmemInfo.used = memInfo.total - memInfo.free\n\t\t\t} else {\n\t\t\t\t// shouldn't happen\n\t\t\t\tslog.Warn(\"no valid cuda library loaded to refresh vram usage\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif memInfo.err != nil {\n\t\t\t\tslog.Warn(\"error looking up nvidia GPU memory\", \"error\", C.GoString(memInfo.err))\n\t\t\t\tC.free(unsafe.Pointer(memInfo.err))\n\t\t\t\tcontinue\n\t\t\t}\n<|next_version|>\n\t\t}\n\n\t\trocmGPUs = AMDGetGPUInfo()\n\t\tbootstrapped = true\n\t\tif len(cudaGPUs) == 0 && len(rocmGPUs) == 0 && len(oneapiGPUs) == 0 {\n\t\t\tslog.Info(\"no compatible GPUs were discovered\")\n\t\t}\n\t}\n\n\t// For detected GPUs, load library if not loaded\n\n\t// Refresh free memory usage\n\tif needRefresh {\n\t\tmem, err := GetCPUMem()\n\t\tif err != nil {\n\t\t\tslog.Warn(\"error looking up system memory\", \"error\", err)\n\t\t} else {\n\t\t\tslog.Debug(\"updating system memory data\",\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"before\",\n\t\t\t\t\t\"total\", format.HumanBytes2(cpus[0].TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(cpus[0].FreeMemory),\n\t\t\t\t\t\"free_swap\", format.HumanBytes2(cpus[0].FreeSwap),\n\t\t\t\t),\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"now\",\n\t\t\t\t\t\"total\", format.HumanBytes2(mem.TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(mem.FreeMemory),\n\t\t\t\t\t\"free_swap\", format.HumanBytes2(mem.FreeSwap),\n\t\t\t\t),\n\t\t\t)\n\t\t\tcpus[0].FreeMemory = mem.FreeMemory\n\t\t\tcpus[0].FreeSwap = mem.FreeSwap\n\t\t}\n\n\t\tvar memInfo C.mem_info_t\n\t\tif cHandles == nil && len(cudaGPUs) > 0 {\n\t\t\tcHandles = initCudaHandles()\n\t\t}\n\t\tfor i, gpu := range cudaGPUs {\n\t\t\tif cHandles.nvml != nil {\n\t\t\t\tC.nvml_get_free(*cHandles.nvml, C.int(gpu.index), &memInfo.free, &memInfo.total, &memInfo.used)\n\t\t\t} else if cHandles.cudart != nil {\n\t\t\t\tC.cudart_bootstrap(*cHandles.cudart, C.int(gpu.index), &memInfo)\n\t\t\t} else if cHandles.nvcuda != nil {\n\t\t\t\tC.nvcuda_get_free(*cHandles.nvcuda, C.int(gpu.index), &memInfo.free, &memInfo.total)\n\t\t\t\tmemInfo.used = memInfo.total - memInfo.free\n\t\t\t} else {\n\t\t\t\t// shouldn't happen\n\t\t\t\tslog.Warn(\"no valid cuda library loaded to refresh vram usage\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif memInfo.err != nil {\n\t\t\t\tslog.Warn(\"error looking up nvidia GPU memory\", \"error\", C.GoString(memInfo.err))\n\t\t\t\tC.free(unsafe.Pointer(memInfo.err))\n\t\t\t\tcontinue\n\t\t\t}\n", "current_contents": "\t\t}\n\n\t\trocmGPUs = AMDGetGPUInfo()\n\t\tbootstrapped = true\n\t\tif len(cudaGPUs) == 0 && len(rocmGPUs) == 0 && len(oneapiGPUs) == 0 {\n\t\t\tslog.Info(\"no compatible GPUs were discovered\")\n\t\t}\n\t}\n\n\t// For detected GPUs, load library if not loaded\n\n\t// Refresh free memory usage\n\tif needRefresh {\n\t\tmem, err := GetCPUMem()\n\t\tif err != nil {\n\t\t\tslog.Warn(\"error looking up system memory\", \"error\", err)\n\t\t} else {\n\t\t\tslog.Debug(\"updating system memory data\",\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"before\",\n\t\t\t\t\t\"total\", format.HumanBytes2(cpus[0].TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(cpus[0].FreeMemory),\n\t\t\t\t\t\"free_swap\", format.HumanBytes2(cpus[0].FreeSwap),\n\t\t\t\t),\n\t\t\t\tslog.Group(\n\t\t\t\t\t\"now\",\n\t\t\t\t\t\"total\", format.HumanBytes2(mem.TotalMemory),\n\t\t\t\t\t\"free\", format.HumanBytes2(mem.FreeMemory),\n\t\t\t\t\t\"free_swap\", format.HumanBytes2(mem.FreeSwap),\n\t\t\t\t),\n\t\t\t)\n\t\t\tcpus[0].FreeMemory = mem.FreeMemory\n\t\t}\n\n\t\tvar memInfo C.mem_info_t\n\t\tif cHandles == nil && len(cudaGPUs) > 0 {\n\t\t\tcHandles = initCudaHandles()\n\t\t}\n\t\tfor i, gpu := range cudaGPUs {\n\t\t\tif cHandles.nvml != nil {\n\t\t\t\tC.nvml_get_free(*cHandles.nvml, C.int(gpu.index), &memInfo.free, &memInfo.total, &memInfo.used)\n\t\t\t} else if cHandles.cudart != nil {\n\t\t\t\tC.cudart_bootstrap(*cHandles.cudart, C.int(gpu.index), &memInfo)\n\t\t\t} else if cHandles.nvcuda != nil {\n\t\t\t\tC.nvcuda_get_free(*cHandles.nvcuda, C.int(gpu.index), &memInfo.free, &memInfo.total)\n\t\t\t\tmemInfo.used = memInfo.total - memInfo.free\n\t\t\t} else {\n\t\t\t\t// shouldn't happen\n\t\t\t\tslog.Warn(\"no valid cuda library loaded to refresh vram usage\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif memInfo.err != nil {\n\t\t\t\tslog.Warn(\"error looking up nvidia GPU memory\", \"error\", C.GoString(memInfo.err))\n\t\t\t\tC.free(unsafe.Pointer(memInfo.err))\n\t\t\t\tcontinue\n\t\t\t}"} {"commit": "b2f00aa9771d44a1423a2e2f23c5218f1bbc834d", "message": "close zip files", "old_file": "server/model.go", "new_file": "server/model.go", "status": "M", "old_contents": "\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr, err := zip.NewReader(file, stat.Size())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempdir, err := os.MkdirTemp(filepath.Dir(file.Name()), \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.RemoveAll(tempdir)\n\n\tfn(api.ProgressResponse{Status: \"unpacking model metadata\"})\n\tfor _, f := range r.File {\n\t\t// TODO(mxyng): this should not write out all files to disk\n\t\toutfile, err := os.Create(filepath.Join(tempdir, f.Name))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tinfile, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif _, err = io.Copy(outfile, infile); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := outfile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := infile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmf, err := convert.GetModelFormat(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := mf.GetParams(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n", "new_contents": "\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr, err := zip.NewReader(file, stat.Size())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempdir, err := os.MkdirTemp(filepath.Dir(file.Name()), \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.RemoveAll(tempdir)\n\n\tfn(api.ProgressResponse{Status: \"unpacking model metadata\"})\n\tfor _, f := range r.File {\n\t\t// TODO(mxyng): this should not write out all files to disk\n\t\toutfile, err := os.Create(filepath.Join(tempdir, f.Name))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer outfile.Close()\n\n\t\tinfile, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer infile.Close()\n\n\t\tif _, err = io.Copy(outfile, infile); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := outfile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := infile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmf, err := convert.GetModelFormat(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := mf.GetParams(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n", "text": "<|original_code|>\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr, err := zip.NewReader(file, stat.Size())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempdir, err := os.MkdirTemp(filepath.Dir(file.Name()), \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.RemoveAll(tempdir)\n\n\tfn(api.ProgressResponse{Status: \"unpacking model metadata\"})\n\tfor _, f := range r.File {\n\t\t// TODO(mxyng): this should not write out all files to disk\n\t\toutfile, err := os.Create(filepath.Join(tempdir, f.Name))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tinfile, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif _, err = io.Copy(outfile, infile); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := outfile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := infile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmf, err := convert.GetModelFormat(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := mf.GetParams(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n<|edits_diff|>\n--- server/model.go\n+++ server/model.go\n@@ -20,6 +20,7 @@\n \t\tif err != nil {\n \t\t\treturn nil, err\n \t\t}\n+\t\tdefer outfile.Close()\n \n \t\tinfile, err := f.Open()\n \t\tif err != nil {\n<|current_version|>\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr, err := zip.NewReader(file, stat.Size())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempdir, err := os.MkdirTemp(filepath.Dir(file.Name()), \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.RemoveAll(tempdir)\n\n\tfn(api.ProgressResponse{Status: \"unpacking model metadata\"})\n\tfor _, f := range r.File {\n\t\t// TODO(mxyng): this should not write out all files to disk\n\t\toutfile, err := os.Create(filepath.Join(tempdir, f.Name))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer outfile.Close()\n\n\t\tinfile, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif _, err = io.Copy(outfile, infile); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := outfile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := infile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmf, err := convert.GetModelFormat(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := mf.GetParams(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n<|next_version|>\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr, err := zip.NewReader(file, stat.Size())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempdir, err := os.MkdirTemp(filepath.Dir(file.Name()), \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.RemoveAll(tempdir)\n\n\tfn(api.ProgressResponse{Status: \"unpacking model metadata\"})\n\tfor _, f := range r.File {\n\t\t// TODO(mxyng): this should not write out all files to disk\n\t\toutfile, err := os.Create(filepath.Join(tempdir, f.Name))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer outfile.Close()\n\n\t\tinfile, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer infile.Close()\n\n\t\tif _, err = io.Copy(outfile, infile); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := outfile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := infile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmf, err := convert.GetModelFormat(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := mf.GetParams(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n", "current_contents": "\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr, err := zip.NewReader(file, stat.Size())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttempdir, err := os.MkdirTemp(filepath.Dir(file.Name()), \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer os.RemoveAll(tempdir)\n\n\tfn(api.ProgressResponse{Status: \"unpacking model metadata\"})\n\tfor _, f := range r.File {\n\t\t// TODO(mxyng): this should not write out all files to disk\n\t\toutfile, err := os.Create(filepath.Join(tempdir, f.Name))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer outfile.Close()\n\n\t\tinfile, err := f.Open()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif _, err = io.Copy(outfile, infile); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := outfile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := infile.Close(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmf, err := convert.GetModelFormat(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams, err := mf.GetParams(tempdir)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n"} {"commit": "9f04e5a8eaf24b0391766fc4904f7f1f08d2d1e8", "message": "format bytes", "old_file": "format/bytes.go", "new_file": "format/bytes.go", "status": "M", "old_contents": "package format\n\nimport \"fmt\"\n\nconst (\n\tByte = 1\n\tKiloByte = Byte * 1000\n\tMegaByte = KiloByte * 1000\n\tGigaByte = MegaByte * 1000\n)\n\nfunc HumanBytes(b int64) string {\n\tswitch {\n\tcase b > GigaByte:\n\t\treturn fmt.Sprintf(\"%.1f GB\", float64(b)/GigaByte)\n\tcase b > MegaByte:\n\t\treturn fmt.Sprintf(\"%.1f MB\", float64(b)/MegaByte)\n\tcase b > KiloByte:\n\t\treturn fmt.Sprintf(\"%.1f KB\", float64(b)/KiloByte)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n}\n", "new_contents": "package format\n\nimport \"fmt\"\n\nconst (\n\tByte = 1\n\tKiloByte = Byte * 1000\n\tMegaByte = KiloByte * 1000\n\tGigaByte = MegaByte * 1000\n\tTeraByte = GigaByte * 1000\n)\n\nfunc HumanBytes(b int64) string {\n\tswitch {\n\tcase b > TeraByte:\n\t\treturn fmt.Sprintf(\"%.1f TB\", float64(b)/TeraByte)\n\tcase b > GigaByte:\n\t\treturn fmt.Sprintf(\"%.1f GB\", float64(b)/GigaByte)\n\tcase b > MegaByte:\n\t\treturn fmt.Sprintf(\"%.1f MB\", float64(b)/MegaByte)\n\tcase b > KiloByte:\n\t\treturn fmt.Sprintf(\"%.1f KB\", float64(b)/KiloByte)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n}\n", "text": "<|original_code|>\npackage format\n\nimport \"fmt\"\n\nconst (\n\tByte = 1\n\tKiloByte = Byte * 1000\n\tMegaByte = KiloByte * 1000\n\tGigaByte = MegaByte * 1000\n)\n\nfunc HumanBytes(b int64) string {\n\tswitch {\n\tcase b > GigaByte:\n\t\treturn fmt.Sprintf(\"%.1f GB\", float64(b)/GigaByte)\n\tcase b > MegaByte:\n\t\treturn fmt.Sprintf(\"%.1f MB\", float64(b)/MegaByte)\n\tcase b > KiloByte:\n\t\treturn fmt.Sprintf(\"%.1f KB\", float64(b)/KiloByte)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n}\n\n<|edits_diff|>\n--- format/bytes.go\n+++ format/bytes.go\n@@ -7,6 +7,7 @@\n \tKiloByte = Byte * 1000\n \tMegaByte = KiloByte * 1000\n \tGigaByte = MegaByte * 1000\n+\tTeraByte = GigaByte * 1000\n )\n \n func HumanBytes(b int64) string {\n<|current_version|>\npackage format\n\nimport \"fmt\"\n\nconst (\n\tByte = 1\n\tKiloByte = Byte * 1000\n\tMegaByte = KiloByte * 1000\n\tGigaByte = MegaByte * 1000\n\tTeraByte = GigaByte * 1000\n)\n\nfunc HumanBytes(b int64) string {\n\tswitch {\n\tcase b > GigaByte:\n\t\treturn fmt.Sprintf(\"%.1f GB\", float64(b)/GigaByte)\n\tcase b > MegaByte:\n\t\treturn fmt.Sprintf(\"%.1f MB\", float64(b)/MegaByte)\n\tcase b > KiloByte:\n\t\treturn fmt.Sprintf(\"%.1f KB\", float64(b)/KiloByte)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n}\n\n<|next_version|>\npackage format\n\nimport \"fmt\"\n\nconst (\n\tByte = 1\n\tKiloByte = Byte * 1000\n\tMegaByte = KiloByte * 1000\n\tGigaByte = MegaByte * 1000\n\tTeraByte = GigaByte * 1000\n)\n\nfunc HumanBytes(b int64) string {\n\tswitch {\n\tcase b > TeraByte:\n\t\treturn fmt.Sprintf(\"%.1f TB\", float64(b)/TeraByte)\n\tcase b > GigaByte:\n\t\treturn fmt.Sprintf(\"%.1f GB\", float64(b)/GigaByte)\n\tcase b > MegaByte:\n\t\treturn fmt.Sprintf(\"%.1f MB\", float64(b)/MegaByte)\n\tcase b > KiloByte:\n\t\treturn fmt.Sprintf(\"%.1f KB\", float64(b)/KiloByte)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n}\n\n", "current_contents": "package format\n\nimport \"fmt\"\n\nconst (\n\tByte = 1\n\tKiloByte = Byte * 1000\n\tMegaByte = KiloByte * 1000\n\tGigaByte = MegaByte * 1000\n\tTeraByte = GigaByte * 1000\n)\n\nfunc HumanBytes(b int64) string {\n\tswitch {\n\tcase b > GigaByte:\n\t\treturn fmt.Sprintf(\"%.1f GB\", float64(b)/GigaByte)\n\tcase b > MegaByte:\n\t\treturn fmt.Sprintf(\"%.1f MB\", float64(b)/MegaByte)\n\tcase b > KiloByte:\n\t\treturn fmt.Sprintf(\"%.1f KB\", float64(b)/KiloByte)\n\tdefault:\n\t\treturn fmt.Sprintf(\"%d B\", b)\n\t}\n}\n"} {"commit": "c5f7eadd8767aa0c394af26aedf2118c07ae0694", "message": "error checking new model", "old_file": "llama/llama.go", "new_file": "llama/llama.go", "status": "M", "old_contents": "\n\tC.llama_backend_init(C.bool(llm.UseNUMA))\n\n\tparams := C.llama_context_default_params()\n\tparams.seed = C.uint(llm.Seed)\n\tparams.n_ctx = C.int(llm.NumCtx)\n\tparams.n_batch = C.int(llm.NumBatch)\n\tparams.n_gpu_layers = C.int(llm.NumGPU)\n\tparams.main_gpu = C.int(llm.MainGPU)\n\tparams.low_vram = C.bool(llm.LowVRAM)\n\tparams.f16_kv = C.bool(llm.F16KV)\n\tparams.logits_all = C.bool(llm.LogitsAll)\n\tparams.vocab_only = C.bool(llm.VocabOnly)\n\tparams.use_mmap = C.bool(llm.UseMMap)\n\tparams.use_mlock = C.bool(llm.UseMLock)\n\tparams.embedding = C.bool(llm.EmbeddingOnly)\n\tllm.params = ¶ms\n\n\tcModel := C.CString(model)\n\tdefer C.free(unsafe.Pointer(cModel))\n\n\tllm.model = C.llama_load_model_from_file(cModel, params)\n\tllm.ctx = C.llama_new_context_with_model(llm.model, params)\n\n\t// warm up the model\n\tbos := []C.llama_token{C.llama_token_bos()}\n\tC.llama_eval(llm.ctx, unsafe.SliceData(bos), C.int(len(bos)), 0, C.int(opts.NumThread))\n\tC.llama_reset_timings(llm.ctx)\n\n\treturn &llm, nil\n}\n\nfunc (llm *llama) Close() {\n\tdefer C.llama_free_model(llm.model)\n\tdefer C.llama_free(llm.ctx)\n\n\tC.llama_print_timings(llm.ctx)\n}\n\nfunc (llm *llama) Predict(prompt string, fn func(string)) error {\n\tif tokens := llm.tokenize(prompt); tokens != nil {\n\t\treturn llm.generate(tokens, fn)\n\t}\n\n\treturn errors.New(\"llama: tokenize\")\n}\n", "new_contents": "\n\tC.llama_backend_init(C.bool(llm.UseNUMA))\n\n\tparams := C.llama_context_default_params()\n\tparams.seed = C.uint(llm.Seed)\n\tparams.n_ctx = C.int(llm.NumCtx)\n\tparams.n_batch = C.int(llm.NumBatch)\n\tparams.n_gpu_layers = C.int(llm.NumGPU)\n\tparams.main_gpu = C.int(llm.MainGPU)\n\tparams.low_vram = C.bool(llm.LowVRAM)\n\tparams.f16_kv = C.bool(llm.F16KV)\n\tparams.logits_all = C.bool(llm.LogitsAll)\n\tparams.vocab_only = C.bool(llm.VocabOnly)\n\tparams.use_mmap = C.bool(llm.UseMMap)\n\tparams.use_mlock = C.bool(llm.UseMLock)\n\tparams.embedding = C.bool(llm.EmbeddingOnly)\n\tllm.params = ¶ms\n\n\tcModel := C.CString(model)\n\tdefer C.free(unsafe.Pointer(cModel))\n\n\tllm.model = C.llama_load_model_from_file(cModel, params)\n\tif llm.model == nil {\n\t\treturn nil, errors.New(\"failed to load model\")\n\t}\n\n\tllm.ctx = C.llama_new_context_with_model(llm.model, params)\n\tif llm.ctx == nil {\n\t\treturn nil, errors.New(\"failed to create context\")\n\t}\n\n\t// warm up the model\n\tbos := []C.llama_token{C.llama_token_bos()}\n\tC.llama_eval(llm.ctx, unsafe.SliceData(bos), C.int(len(bos)), 0, C.int(opts.NumThread))\n\tC.llama_reset_timings(llm.ctx)\n\n\treturn &llm, nil\n}\n\nfunc (llm *llama) Close() {\n\tdefer C.llama_free_model(llm.model)\n\tdefer C.llama_free(llm.ctx)\n\n\tC.llama_print_timings(llm.ctx)\n}\n\nfunc (llm *llama) Predict(prompt string, fn func(string)) error {\n\tif tokens := llm.tokenize(prompt); tokens != nil {\n\t\treturn llm.generate(tokens, fn)\n\t}\n\n\treturn errors.New(\"llama: tokenize\")\n}\n", "text": "<|original_code|>\n\n\tC.llama_backend_init(C.bool(llm.UseNUMA))\n\n\tparams := C.llama_context_default_params()\n\tparams.seed = C.uint(llm.Seed)\n\tparams.n_ctx = C.int(llm.NumCtx)\n\tparams.n_batch = C.int(llm.NumBatch)\n\tparams.n_gpu_layers = C.int(llm.NumGPU)\n\tparams.main_gpu = C.int(llm.MainGPU)\n\tparams.low_vram = C.bool(llm.LowVRAM)\n\tparams.f16_kv = C.bool(llm.F16KV)\n\tparams.logits_all = C.bool(llm.LogitsAll)\n\tparams.vocab_only = C.bool(llm.VocabOnly)\n\tparams.use_mmap = C.bool(llm.UseMMap)\n\tparams.use_mlock = C.bool(llm.UseMLock)\n\tparams.embedding = C.bool(llm.EmbeddingOnly)\n\tllm.params = ¶ms\n\n\tcModel := C.CString(model)\n\tdefer C.free(unsafe.Pointer(cModel))\n\n\tllm.model = C.llama_load_model_from_file(cModel, params)\n\tllm.ctx = C.llama_new_context_with_model(llm.model, params)\n\n\t// warm up the model\n\tbos := []C.llama_token{C.llama_token_bos()}\n\tC.llama_eval(llm.ctx, unsafe.SliceData(bos), C.int(len(bos)), 0, C.int(opts.NumThread))\n\tC.llama_reset_timings(llm.ctx)\n\n\treturn &llm, nil\n}\n\nfunc (llm *llama) Close() {\n\tdefer C.llama_free_model(llm.model)\n\tdefer C.llama_free(llm.ctx)\n\n\tC.llama_print_timings(llm.ctx)\n}\n\nfunc (llm *llama) Predict(prompt string, fn func(string)) error {\n\tif tokens := llm.tokenize(prompt); tokens != nil {\n\t\treturn llm.generate(tokens, fn)\n\t}\n\n\treturn errors.New(\"llama: tokenize\")\n}\n\n<|edits_diff|>\n--- llama/llama.go\n+++ llama/llama.go\n@@ -20,6 +20,10 @@\n \tdefer C.free(unsafe.Pointer(cModel))\n \n \tllm.model = C.llama_load_model_from_file(cModel, params)\n+\tif llm.model == nil {\n+\t\treturn nil, errors.New(\"failed to load model\")\n+\t}\n+\n \tllm.ctx = C.llama_new_context_with_model(llm.model, params)\n \n \t// warm up the model\n<|current_version|>\n\n\tC.llama_backend_init(C.bool(llm.UseNUMA))\n\n\tparams := C.llama_context_default_params()\n\tparams.seed = C.uint(llm.Seed)\n\tparams.n_ctx = C.int(llm.NumCtx)\n\tparams.n_batch = C.int(llm.NumBatch)\n\tparams.n_gpu_layers = C.int(llm.NumGPU)\n\tparams.main_gpu = C.int(llm.MainGPU)\n\tparams.low_vram = C.bool(llm.LowVRAM)\n\tparams.f16_kv = C.bool(llm.F16KV)\n\tparams.logits_all = C.bool(llm.LogitsAll)\n\tparams.vocab_only = C.bool(llm.VocabOnly)\n\tparams.use_mmap = C.bool(llm.UseMMap)\n\tparams.use_mlock = C.bool(llm.UseMLock)\n\tparams.embedding = C.bool(llm.EmbeddingOnly)\n\tllm.params = ¶ms\n\n\tcModel := C.CString(model)\n\tdefer C.free(unsafe.Pointer(cModel))\n\n\tllm.model = C.llama_load_model_from_file(cModel, params)\n\tif llm.model == nil {\n\t\treturn nil, errors.New(\"failed to load model\")\n\t}\n\n\tllm.ctx = C.llama_new_context_with_model(llm.model, params)\n\n\t// warm up the model\n\tbos := []C.llama_token{C.llama_token_bos()}\n\tC.llama_eval(llm.ctx, unsafe.SliceData(bos), C.int(len(bos)), 0, C.int(opts.NumThread))\n\tC.llama_reset_timings(llm.ctx)\n\n\treturn &llm, nil\n}\n\nfunc (llm *llama) Close() {\n\tdefer C.llama_free_model(llm.model)\n\tdefer C.llama_free(llm.ctx)\n\n\tC.llama_print_timings(llm.ctx)\n}\n\nfunc (llm *llama) Predict(prompt string, fn func(string)) error {\n\tif tokens := llm.tokenize(prompt); tokens != nil {\n\t\treturn llm.generate(tokens, fn)\n\t}\n\n\treturn errors.New(\"llama: tokenize\")\n}\n\n<|next_version|>\n\n\tC.llama_backend_init(C.bool(llm.UseNUMA))\n\n\tparams := C.llama_context_default_params()\n\tparams.seed = C.uint(llm.Seed)\n\tparams.n_ctx = C.int(llm.NumCtx)\n\tparams.n_batch = C.int(llm.NumBatch)\n\tparams.n_gpu_layers = C.int(llm.NumGPU)\n\tparams.main_gpu = C.int(llm.MainGPU)\n\tparams.low_vram = C.bool(llm.LowVRAM)\n\tparams.f16_kv = C.bool(llm.F16KV)\n\tparams.logits_all = C.bool(llm.LogitsAll)\n\tparams.vocab_only = C.bool(llm.VocabOnly)\n\tparams.use_mmap = C.bool(llm.UseMMap)\n\tparams.use_mlock = C.bool(llm.UseMLock)\n\tparams.embedding = C.bool(llm.EmbeddingOnly)\n\tllm.params = ¶ms\n\n\tcModel := C.CString(model)\n\tdefer C.free(unsafe.Pointer(cModel))\n\n\tllm.model = C.llama_load_model_from_file(cModel, params)\n\tif llm.model == nil {\n\t\treturn nil, errors.New(\"failed to load model\")\n\t}\n\n\tllm.ctx = C.llama_new_context_with_model(llm.model, params)\n\tif llm.ctx == nil {\n\t\treturn nil, errors.New(\"failed to create context\")\n\t}\n\n\t// warm up the model\n\tbos := []C.llama_token{C.llama_token_bos()}\n\tC.llama_eval(llm.ctx, unsafe.SliceData(bos), C.int(len(bos)), 0, C.int(opts.NumThread))\n\tC.llama_reset_timings(llm.ctx)\n\n\treturn &llm, nil\n}\n\nfunc (llm *llama) Close() {\n\tdefer C.llama_free_model(llm.model)\n\tdefer C.llama_free(llm.ctx)\n\n\tC.llama_print_timings(llm.ctx)\n}\n\nfunc (llm *llama) Predict(prompt string, fn func(string)) error {\n\tif tokens := llm.tokenize(prompt); tokens != nil {\n\t\treturn llm.generate(tokens, fn)\n\t}\n\n\treturn errors.New(\"llama: tokenize\")\n}\n\n", "current_contents": "\n\tC.llama_backend_init(C.bool(llm.UseNUMA))\n\n\tparams := C.llama_context_default_params()\n\tparams.seed = C.uint(llm.Seed)\n\tparams.n_ctx = C.int(llm.NumCtx)\n\tparams.n_batch = C.int(llm.NumBatch)\n\tparams.n_gpu_layers = C.int(llm.NumGPU)\n\tparams.main_gpu = C.int(llm.MainGPU)\n\tparams.low_vram = C.bool(llm.LowVRAM)\n\tparams.f16_kv = C.bool(llm.F16KV)\n\tparams.logits_all = C.bool(llm.LogitsAll)\n\tparams.vocab_only = C.bool(llm.VocabOnly)\n\tparams.use_mmap = C.bool(llm.UseMMap)\n\tparams.use_mlock = C.bool(llm.UseMLock)\n\tparams.embedding = C.bool(llm.EmbeddingOnly)\n\tllm.params = ¶ms\n\n\tcModel := C.CString(model)\n\tdefer C.free(unsafe.Pointer(cModel))\n\n\tllm.model = C.llama_load_model_from_file(cModel, params)\n\tif llm.model == nil {\n\t\treturn nil, errors.New(\"failed to load model\")\n\t}\n\n\tllm.ctx = C.llama_new_context_with_model(llm.model, params)\n\n\t// warm up the model\n\tbos := []C.llama_token{C.llama_token_bos()}\n\tC.llama_eval(llm.ctx, unsafe.SliceData(bos), C.int(len(bos)), 0, C.int(opts.NumThread))\n\tC.llama_reset_timings(llm.ctx)\n\n\treturn &llm, nil\n}\n\nfunc (llm *llama) Close() {\n\tdefer C.llama_free_model(llm.model)\n\tdefer C.llama_free(llm.ctx)\n\n\tC.llama_print_timings(llm.ctx)\n}\n\nfunc (llm *llama) Predict(prompt string, fn func(string)) error {\n\tif tokens := llm.tokenize(prompt); tokens != nil {\n\t\treturn llm.generate(tokens, fn)\n\t}\n\n\treturn errors.New(\"llama: tokenize\")\n}\n"} {"commit": "8763f33c65f7df8be5b9fe7504ab7fcf20abb41d", "message": "fix: prevent middleware re-entry issue in HandleContext (#3987)", "old_file": "gin.go", "new_file": "gin.go", "status": "M", "old_contents": "\n\terr = http.Serve(listener, engine.Handler())\n\treturn\n}\n\n// ServeHTTP conforms to the http.Handler interface.\nfunc (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tc := engine.pool.Get().(*Context)\n\tc.writermem.reset(w)\n\tc.Request = req\n\tc.reset()\n\n\tengine.handleHTTPRequest(c)\n\n\tengine.pool.Put(c)\n}\n\n// HandleContext re-enters a context that has been rewritten.\n// This can be done by setting c.Request.URL.Path to your new target.\n// Disclaimer: You can loop yourself to deal with this, use wisely.\nfunc (engine *Engine) HandleContext(c *Context) {\n\toldIndexValue := c.index\n\tc.reset()\n\tengine.handleHTTPRequest(c)\n\n\tc.index = oldIndexValue\n}\n\nfunc (engine *Engine) handleHTTPRequest(c *Context) {\n\thttpMethod := c.Request.Method\n\trPath := c.Request.URL.Path\n\tunescape := false\n\tif engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {\n\t\trPath = c.Request.URL.RawPath\n\t\tunescape = engine.UnescapePathValues\n\t}\n\n\tif engine.RemoveExtraSlash {\n\t\trPath = cleanPath(rPath)\n\t}\n\n\t// Find root of the tree for the given HTTP method\n\tt := engine.trees\n\tfor i, tl := 0, len(t); i < tl; i++ {\n\t\tif t[i].method != httpMethod {\n\t\t\tcontinue\n\t\t}\n\t\troot := t[i].root\n\t\t// Find route in tree\n\t\tvalue := root.getValue(rPath, c.params, c.skippedNodes, unescape)", "new_contents": "\n\terr = http.Serve(listener, engine.Handler())\n\treturn\n}\n\n// ServeHTTP conforms to the http.Handler interface.\nfunc (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tc := engine.pool.Get().(*Context)\n\tc.writermem.reset(w)\n\tc.Request = req\n\tc.reset()\n\n\tengine.handleHTTPRequest(c)\n\n\tengine.pool.Put(c)\n}\n\n// HandleContext re-enters a context that has been rewritten.\n// This can be done by setting c.Request.URL.Path to your new target.\n// Disclaimer: You can loop yourself to deal with this, use wisely.\nfunc (engine *Engine) HandleContext(c *Context) {\n\toldIndexValue := c.index\n\toldHandlers := c.handlers\n\tc.reset()\n\tengine.handleHTTPRequest(c)\n\n\tc.index = oldIndexValue\n\tc.handlers = oldHandlers\n}\n\nfunc (engine *Engine) handleHTTPRequest(c *Context) {\n\thttpMethod := c.Request.Method\n\trPath := c.Request.URL.Path\n\tunescape := false\n\tif engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {\n\t\trPath = c.Request.URL.RawPath\n\t\tunescape = engine.UnescapePathValues\n\t}\n\n\tif engine.RemoveExtraSlash {\n\t\trPath = cleanPath(rPath)\n\t}\n\n\t// Find root of the tree for the given HTTP method\n\tt := engine.trees\n\tfor i, tl := 0, len(t); i < tl; i++ {\n\t\tif t[i].method != httpMethod {\n\t\t\tcontinue\n\t\t}\n\t\troot := t[i].root\n\t\t// Find route in tree\n\t\tvalue := root.getValue(rPath, c.params, c.skippedNodes, unescape)", "text": "<|original_code|>\n\n\terr = http.Serve(listener, engine.Handler())\n\treturn\n}\n\n// ServeHTTP conforms to the http.Handler interface.\nfunc (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tc := engine.pool.Get().(*Context)\n\tc.writermem.reset(w)\n\tc.Request = req\n\tc.reset()\n\n\tengine.handleHTTPRequest(c)\n\n\tengine.pool.Put(c)\n}\n\n// HandleContext re-enters a context that has been rewritten.\n// This can be done by setting c.Request.URL.Path to your new target.\n// Disclaimer: You can loop yourself to deal with this, use wisely.\nfunc (engine *Engine) HandleContext(c *Context) {\n\toldIndexValue := c.index\n\tc.reset()\n\tengine.handleHTTPRequest(c)\n\n\tc.index = oldIndexValue\n}\n\nfunc (engine *Engine) handleHTTPRequest(c *Context) {\n\thttpMethod := c.Request.Method\n\trPath := c.Request.URL.Path\n\tunescape := false\n\tif engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {\n\t\trPath = c.Request.URL.RawPath\n\t\tunescape = engine.UnescapePathValues\n\t}\n\n\tif engine.RemoveExtraSlash {\n\t\trPath = cleanPath(rPath)\n\t}\n\n\t// Find root of the tree for the given HTTP method\n\tt := engine.trees\n\tfor i, tl := 0, len(t); i < tl; i++ {\n\t\tif t[i].method != httpMethod {\n\t\t\tcontinue\n\t\t}\n\t\troot := t[i].root\n\t\t// Find route in tree\n\t\tvalue := root.getValue(rPath, c.params, c.skippedNodes, unescape)\n<|edits_diff|>\n--- gin.go\n+++ gin.go\n@@ -20,6 +20,7 @@\n // Disclaimer: You can loop yourself to deal with this, use wisely.\n func (engine *Engine) HandleContext(c *Context) {\n \toldIndexValue := c.index\n+\toldHandlers := c.handlers\n \tc.reset()\n \tengine.handleHTTPRequest(c)\n \n<|current_version|>\n\n\terr = http.Serve(listener, engine.Handler())\n\treturn\n}\n\n// ServeHTTP conforms to the http.Handler interface.\nfunc (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tc := engine.pool.Get().(*Context)\n\tc.writermem.reset(w)\n\tc.Request = req\n\tc.reset()\n\n\tengine.handleHTTPRequest(c)\n\n\tengine.pool.Put(c)\n}\n\n// HandleContext re-enters a context that has been rewritten.\n// This can be done by setting c.Request.URL.Path to your new target.\n// Disclaimer: You can loop yourself to deal with this, use wisely.\nfunc (engine *Engine) HandleContext(c *Context) {\n\toldIndexValue := c.index\n\toldHandlers := c.handlers\n\tc.reset()\n\tengine.handleHTTPRequest(c)\n\n\tc.index = oldIndexValue\n}\n\nfunc (engine *Engine) handleHTTPRequest(c *Context) {\n\thttpMethod := c.Request.Method\n\trPath := c.Request.URL.Path\n\tunescape := false\n\tif engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {\n\t\trPath = c.Request.URL.RawPath\n\t\tunescape = engine.UnescapePathValues\n\t}\n\n\tif engine.RemoveExtraSlash {\n\t\trPath = cleanPath(rPath)\n\t}\n\n\t// Find root of the tree for the given HTTP method\n\tt := engine.trees\n\tfor i, tl := 0, len(t); i < tl; i++ {\n\t\tif t[i].method != httpMethod {\n\t\t\tcontinue\n\t\t}\n\t\troot := t[i].root\n\t\t// Find route in tree\n\t\tvalue := root.getValue(rPath, c.params, c.skippedNodes, unescape)\n<|next_version|>\n\n\terr = http.Serve(listener, engine.Handler())\n\treturn\n}\n\n// ServeHTTP conforms to the http.Handler interface.\nfunc (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tc := engine.pool.Get().(*Context)\n\tc.writermem.reset(w)\n\tc.Request = req\n\tc.reset()\n\n\tengine.handleHTTPRequest(c)\n\n\tengine.pool.Put(c)\n}\n\n// HandleContext re-enters a context that has been rewritten.\n// This can be done by setting c.Request.URL.Path to your new target.\n// Disclaimer: You can loop yourself to deal with this, use wisely.\nfunc (engine *Engine) HandleContext(c *Context) {\n\toldIndexValue := c.index\n\toldHandlers := c.handlers\n\tc.reset()\n\tengine.handleHTTPRequest(c)\n\n\tc.index = oldIndexValue\n\tc.handlers = oldHandlers\n}\n\nfunc (engine *Engine) handleHTTPRequest(c *Context) {\n\thttpMethod := c.Request.Method\n\trPath := c.Request.URL.Path\n\tunescape := false\n\tif engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {\n\t\trPath = c.Request.URL.RawPath\n\t\tunescape = engine.UnescapePathValues\n\t}\n\n\tif engine.RemoveExtraSlash {\n\t\trPath = cleanPath(rPath)\n\t}\n\n\t// Find root of the tree for the given HTTP method\n\tt := engine.trees\n\tfor i, tl := 0, len(t); i < tl; i++ {\n\t\tif t[i].method != httpMethod {\n\t\t\tcontinue\n\t\t}\n\t\troot := t[i].root\n\t\t// Find route in tree\n\t\tvalue := root.getValue(rPath, c.params, c.skippedNodes, unescape)\n", "current_contents": "\n\terr = http.Serve(listener, engine.Handler())\n\treturn\n}\n\n// ServeHTTP conforms to the http.Handler interface.\nfunc (engine *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tc := engine.pool.Get().(*Context)\n\tc.writermem.reset(w)\n\tc.Request = req\n\tc.reset()\n\n\tengine.handleHTTPRequest(c)\n\n\tengine.pool.Put(c)\n}\n\n// HandleContext re-enters a context that has been rewritten.\n// This can be done by setting c.Request.URL.Path to your new target.\n// Disclaimer: You can loop yourself to deal with this, use wisely.\nfunc (engine *Engine) HandleContext(c *Context) {\n\toldIndexValue := c.index\n\toldHandlers := c.handlers\n\tc.reset()\n\tengine.handleHTTPRequest(c)\n\n\tc.index = oldIndexValue\n}\n\nfunc (engine *Engine) handleHTTPRequest(c *Context) {\n\thttpMethod := c.Request.Method\n\trPath := c.Request.URL.Path\n\tunescape := false\n\tif engine.UseRawPath && len(c.Request.URL.RawPath) > 0 {\n\t\trPath = c.Request.URL.RawPath\n\t\tunescape = engine.UnescapePathValues\n\t}\n\n\tif engine.RemoveExtraSlash {\n\t\trPath = cleanPath(rPath)\n\t}\n\n\t// Find root of the tree for the given HTTP method\n\tt := engine.trees\n\tfor i, tl := 0, len(t); i < tl; i++ {\n\t\tif t[i].method != httpMethod {\n\t\t\tcontinue\n\t\t}\n\t\troot := t[i].root\n\t\t// Find route in tree\n\t\tvalue := root.getValue(rPath, c.params, c.skippedNodes, unescape)"} {"commit": "646312aef6a34095476ac846b0920db5fb24b2ea", "message": "fix: protect Context.Keys map when call Copy method (#3873)", "old_file": "context.go", "new_file": "context.go", "status": "M", "old_contents": "\tc.sameSite = 0\n\t*c.params = (*c.params)[:0]\n\t*c.skippedNodes = (*c.skippedNodes)[:0]\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tengine: c.engine,\n\t}\n\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.fullPath = c.fullPath\n\n\tcKeys := c.Keys\n\tcp.Keys = make(map[string]any, len(cKeys))\n\tfor k, v := range cKeys {\n\t\tcp.Keys[k] = v\n\t}\n\n\tcParams := c.Params\n\tcp.Params = make([]Param, len(cParams))\n\tcopy(cp.Params, cParams)\n\n\treturn &cp\n}\n\n// HandlerName returns the main handler's name. For example if the handler is \"handleGetUsers()\",\n// this function will return \"main.handleGetUsers\".\nfunc (c *Context) HandlerName() string {\n\treturn nameOfFunction(c.handlers.Last())\n}\n\n// HandlerNames returns a list of all registered handlers for this context in descending order,\n// following the semantics of HandlerName()\nfunc (c *Context) HandlerNames() []string {\n\thn := make([]string, 0, len(c.handlers))\n\tfor _, val := range c.handlers {\n\t\thn = append(hn, nameOfFunction(val))\n\t}\n\treturn hn\n}\n", "new_contents": "\tc.sameSite = 0\n\t*c.params = (*c.params)[:0]\n\t*c.skippedNodes = (*c.skippedNodes)[:0]\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tengine: c.engine,\n\t}\n\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.fullPath = c.fullPath\n\n\tcKeys := c.Keys\n\tcp.Keys = make(map[string]any, len(cKeys))\n\tc.mu.RLock()\n\tfor k, v := range cKeys {\n\t\tcp.Keys[k] = v\n\t}\n\tc.mu.RUnlock()\n\n\tcParams := c.Params\n\tcp.Params = make([]Param, len(cParams))\n\tcopy(cp.Params, cParams)\n\n\treturn &cp\n}\n\n// HandlerName returns the main handler's name. For example if the handler is \"handleGetUsers()\",\n// this function will return \"main.handleGetUsers\".\nfunc (c *Context) HandlerName() string {\n\treturn nameOfFunction(c.handlers.Last())\n}\n\n// HandlerNames returns a list of all registered handlers for this context in descending order,\n// following the semantics of HandlerName()\nfunc (c *Context) HandlerNames() []string {\n\thn := make([]string, 0, len(c.handlers))\n\tfor _, val := range c.handlers {\n\t\thn = append(hn, nameOfFunction(val))\n\t}\n\treturn hn\n}\n", "text": "<|original_code|>\n\tc.sameSite = 0\n\t*c.params = (*c.params)[:0]\n\t*c.skippedNodes = (*c.skippedNodes)[:0]\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tengine: c.engine,\n\t}\n\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.fullPath = c.fullPath\n\n\tcKeys := c.Keys\n\tcp.Keys = make(map[string]any, len(cKeys))\n\tfor k, v := range cKeys {\n\t\tcp.Keys[k] = v\n\t}\n\n\tcParams := c.Params\n\tcp.Params = make([]Param, len(cParams))\n\tcopy(cp.Params, cParams)\n\n\treturn &cp\n}\n\n// HandlerName returns the main handler's name. For example if the handler is \"handleGetUsers()\",\n// this function will return \"main.handleGetUsers\".\nfunc (c *Context) HandlerName() string {\n\treturn nameOfFunction(c.handlers.Last())\n}\n\n// HandlerNames returns a list of all registered handlers for this context in descending order,\n// following the semantics of HandlerName()\nfunc (c *Context) HandlerNames() []string {\n\thn := make([]string, 0, len(c.handlers))\n\tfor _, val := range c.handlers {\n\t\thn = append(hn, nameOfFunction(val))\n\t}\n\treturn hn\n}\n\n<|edits_diff|>\n--- context.go\n+++ context.go\n@@ -20,6 +20,7 @@\n \n \tcKeys := c.Keys\n \tcp.Keys = make(map[string]any, len(cKeys))\n+\tc.mu.RLock()\n \tfor k, v := range cKeys {\n \t\tcp.Keys[k] = v\n \t}\n<|current_version|>\n\tc.sameSite = 0\n\t*c.params = (*c.params)[:0]\n\t*c.skippedNodes = (*c.skippedNodes)[:0]\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tengine: c.engine,\n\t}\n\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.fullPath = c.fullPath\n\n\tcKeys := c.Keys\n\tcp.Keys = make(map[string]any, len(cKeys))\n\tc.mu.RLock()\n\tfor k, v := range cKeys {\n\t\tcp.Keys[k] = v\n\t}\n\n\tcParams := c.Params\n\tcp.Params = make([]Param, len(cParams))\n\tcopy(cp.Params, cParams)\n\n\treturn &cp\n}\n\n// HandlerName returns the main handler's name. For example if the handler is \"handleGetUsers()\",\n// this function will return \"main.handleGetUsers\".\nfunc (c *Context) HandlerName() string {\n\treturn nameOfFunction(c.handlers.Last())\n}\n\n// HandlerNames returns a list of all registered handlers for this context in descending order,\n// following the semantics of HandlerName()\nfunc (c *Context) HandlerNames() []string {\n\thn := make([]string, 0, len(c.handlers))\n\tfor _, val := range c.handlers {\n\t\thn = append(hn, nameOfFunction(val))\n\t}\n\treturn hn\n}\n\n<|next_version|>\n\tc.sameSite = 0\n\t*c.params = (*c.params)[:0]\n\t*c.skippedNodes = (*c.skippedNodes)[:0]\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tengine: c.engine,\n\t}\n\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.fullPath = c.fullPath\n\n\tcKeys := c.Keys\n\tcp.Keys = make(map[string]any, len(cKeys))\n\tc.mu.RLock()\n\tfor k, v := range cKeys {\n\t\tcp.Keys[k] = v\n\t}\n\tc.mu.RUnlock()\n\n\tcParams := c.Params\n\tcp.Params = make([]Param, len(cParams))\n\tcopy(cp.Params, cParams)\n\n\treturn &cp\n}\n\n// HandlerName returns the main handler's name. For example if the handler is \"handleGetUsers()\",\n// this function will return \"main.handleGetUsers\".\nfunc (c *Context) HandlerName() string {\n\treturn nameOfFunction(c.handlers.Last())\n}\n\n// HandlerNames returns a list of all registered handlers for this context in descending order,\n// following the semantics of HandlerName()\nfunc (c *Context) HandlerNames() []string {\n\thn := make([]string, 0, len(c.handlers))\n\tfor _, val := range c.handlers {\n\t\thn = append(hn, nameOfFunction(val))\n\t}\n\treturn hn\n}\n\n", "current_contents": "\tc.sameSite = 0\n\t*c.params = (*c.params)[:0]\n\t*c.skippedNodes = (*c.skippedNodes)[:0]\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tengine: c.engine,\n\t}\n\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.fullPath = c.fullPath\n\n\tcKeys := c.Keys\n\tcp.Keys = make(map[string]any, len(cKeys))\n\tc.mu.RLock()\n\tfor k, v := range cKeys {\n\t\tcp.Keys[k] = v\n\t}\n\n\tcParams := c.Params\n\tcp.Params = make([]Param, len(cParams))\n\tcopy(cp.Params, cParams)\n\n\treturn &cp\n}\n\n// HandlerName returns the main handler's name. For example if the handler is \"handleGetUsers()\",\n// this function will return \"main.handleGetUsers\".\nfunc (c *Context) HandlerName() string {\n\treturn nameOfFunction(c.handlers.Last())\n}\n\n// HandlerNames returns a list of all registered handlers for this context in descending order,\n// following the semantics of HandlerName()\nfunc (c *Context) HandlerNames() []string {\n\thn := make([]string, 0, len(c.handlers))\n\tfor _, val := range c.handlers {\n\t\thn = append(hn, nameOfFunction(val))\n\t}\n\treturn hn\n}\n"} {"commit": "09f8224593e31edf3c58ab3f13bc31ef53473733", "message": "fix(route): Add fullPath in context copy (#3784)", "old_file": "context_test.go", "new_file": "context_test.go", "status": "M", "old_contents": "\n\tassert.Equal(t, m, c.GetStringMapString(\"map\"))\n\tassert.Equal(t, \"bar\", c.GetStringMapString(\"map\")[\"foo\"])\n}\n\nfunc TestContextGetStringMapStringSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string][]string)\n\tm[\"foo\"] = []string{\"foo\"}\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMapStringSlice(\"map\"))\n\tassert.Equal(t, []string{\"foo\"}, c.GetStringMapStringSlice(\"map\")[\"foo\"])\n}\n\nfunc TestContextCopy(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.index = 2\n\tc.Request, _ = http.NewRequest(\"POST\", \"/hola\", nil)\n\tc.handlers = HandlersChain{func(c *Context) {}}\n\tc.Params = Params{Param{Key: \"foo\", Value: \"bar\"}}\n\tc.Set(\"foo\", \"bar\")\n\n\tcp := c.Copy()\n\tassert.Nil(t, cp.handlers)\n\tassert.Nil(t, cp.writermem.ResponseWriter)\n\tassert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))\n\tassert.Equal(t, cp.Request, c.Request)\n\tassert.Equal(t, cp.index, abortIndex)\n\tassert.Equal(t, cp.Keys, c.Keys)\n\tassert.Equal(t, cp.engine, c.engine)\n\tassert.Equal(t, cp.Params, c.Params)\n\tcp.Set(\"foo\", \"notBar\")\n\tassert.False(t, cp.Keys[\"foo\"] == c.Keys[\"foo\"])\n}\n\nfunc TestContextHandlerName(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}\n\n\tassert.Regexp(t, \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$\", c.HandlerName())\n}\n\nfunc TestContextHandlerNames(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest, func(c *Context) {}, handlerNameTest2}\n\n\tnames := c.HandlerNames()\n\n\tassert.True(t, len(names) == 4)\n\tfor _, name := range names {\n\t\tassert.Regexp(t, `^(.*/vendor/)?(github\\.com/gin-gonic/gin\\.){1}(TestContextHandlerNames\\.func.*){0,1}(handlerNameTest.*){0,1}`, name)\n\t}\n}\n\nfunc handlerNameTest(c *Context) {\n}\n", "new_contents": "\n\tassert.Equal(t, m, c.GetStringMapString(\"map\"))\n\tassert.Equal(t, \"bar\", c.GetStringMapString(\"map\")[\"foo\"])\n}\n\nfunc TestContextGetStringMapStringSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string][]string)\n\tm[\"foo\"] = []string{\"foo\"}\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMapStringSlice(\"map\"))\n\tassert.Equal(t, []string{\"foo\"}, c.GetStringMapStringSlice(\"map\")[\"foo\"])\n}\n\nfunc TestContextCopy(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.index = 2\n\tc.Request, _ = http.NewRequest(\"POST\", \"/hola\", nil)\n\tc.handlers = HandlersChain{func(c *Context) {}}\n\tc.Params = Params{Param{Key: \"foo\", Value: \"bar\"}}\n\tc.Set(\"foo\", \"bar\")\n\tc.fullPath = \"/hola\"\n\n\tcp := c.Copy()\n\tassert.Nil(t, cp.handlers)\n\tassert.Nil(t, cp.writermem.ResponseWriter)\n\tassert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))\n\tassert.Equal(t, cp.Request, c.Request)\n\tassert.Equal(t, cp.index, abortIndex)\n\tassert.Equal(t, cp.Keys, c.Keys)\n\tassert.Equal(t, cp.engine, c.engine)\n\tassert.Equal(t, cp.Params, c.Params)\n\tcp.Set(\"foo\", \"notBar\")\n\tassert.False(t, cp.Keys[\"foo\"] == c.Keys[\"foo\"])\n\tassert.Equal(t, cp.fullPath, c.fullPath)\n}\n\nfunc TestContextHandlerName(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}\n\n\tassert.Regexp(t, \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$\", c.HandlerName())\n}\n\nfunc TestContextHandlerNames(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest, func(c *Context) {}, handlerNameTest2}\n\n\tnames := c.HandlerNames()\n\n\tassert.True(t, len(names) == 4)\n\tfor _, name := range names {\n\t\tassert.Regexp(t, `^(.*/vendor/)?(github\\.com/gin-gonic/gin\\.){1}(TestContextHandlerNames\\.func.*){0,1}(handlerNameTest.*){0,1}`, name)\n\t}\n}\n\nfunc handlerNameTest(c *Context) {\n}\n", "text": "<|original_code|>\n\n\tassert.Equal(t, m, c.GetStringMapString(\"map\"))\n\tassert.Equal(t, \"bar\", c.GetStringMapString(\"map\")[\"foo\"])\n}\n\nfunc TestContextGetStringMapStringSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string][]string)\n\tm[\"foo\"] = []string{\"foo\"}\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMapStringSlice(\"map\"))\n\tassert.Equal(t, []string{\"foo\"}, c.GetStringMapStringSlice(\"map\")[\"foo\"])\n}\n\nfunc TestContextCopy(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.index = 2\n\tc.Request, _ = http.NewRequest(\"POST\", \"/hola\", nil)\n\tc.handlers = HandlersChain{func(c *Context) {}}\n\tc.Params = Params{Param{Key: \"foo\", Value: \"bar\"}}\n\tc.Set(\"foo\", \"bar\")\n\n\tcp := c.Copy()\n\tassert.Nil(t, cp.handlers)\n\tassert.Nil(t, cp.writermem.ResponseWriter)\n\tassert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))\n\tassert.Equal(t, cp.Request, c.Request)\n\tassert.Equal(t, cp.index, abortIndex)\n\tassert.Equal(t, cp.Keys, c.Keys)\n\tassert.Equal(t, cp.engine, c.engine)\n\tassert.Equal(t, cp.Params, c.Params)\n\tcp.Set(\"foo\", \"notBar\")\n\tassert.False(t, cp.Keys[\"foo\"] == c.Keys[\"foo\"])\n}\n\nfunc TestContextHandlerName(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}\n\n\tassert.Regexp(t, \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$\", c.HandlerName())\n}\n\nfunc TestContextHandlerNames(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest, func(c *Context) {}, handlerNameTest2}\n\n\tnames := c.HandlerNames()\n\n\tassert.True(t, len(names) == 4)\n\tfor _, name := range names {\n\t\tassert.Regexp(t, `^(.*/vendor/)?(github\\.com/gin-gonic/gin\\.){1}(TestContextHandlerNames\\.func.*){0,1}(handlerNameTest.*){0,1}`, name)\n\t}\n}\n\nfunc handlerNameTest(c *Context) {\n}\n\n<|edits_diff|>\n--- context_test.go\n+++ context_test.go\n@@ -20,6 +20,7 @@\n \tc.handlers = HandlersChain{func(c *Context) {}}\n \tc.Params = Params{Param{Key: \"foo\", Value: \"bar\"}}\n \tc.Set(\"foo\", \"bar\")\n+\tc.fullPath = \"/hola\"\n \n \tcp := c.Copy()\n \tassert.Nil(t, cp.handlers)\n<|current_version|>\n\n\tassert.Equal(t, m, c.GetStringMapString(\"map\"))\n\tassert.Equal(t, \"bar\", c.GetStringMapString(\"map\")[\"foo\"])\n}\n\nfunc TestContextGetStringMapStringSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string][]string)\n\tm[\"foo\"] = []string{\"foo\"}\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMapStringSlice(\"map\"))\n\tassert.Equal(t, []string{\"foo\"}, c.GetStringMapStringSlice(\"map\")[\"foo\"])\n}\n\nfunc TestContextCopy(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.index = 2\n\tc.Request, _ = http.NewRequest(\"POST\", \"/hola\", nil)\n\tc.handlers = HandlersChain{func(c *Context) {}}\n\tc.Params = Params{Param{Key: \"foo\", Value: \"bar\"}}\n\tc.Set(\"foo\", \"bar\")\n\tc.fullPath = \"/hola\"\n\n\tcp := c.Copy()\n\tassert.Nil(t, cp.handlers)\n\tassert.Nil(t, cp.writermem.ResponseWriter)\n\tassert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))\n\tassert.Equal(t, cp.Request, c.Request)\n\tassert.Equal(t, cp.index, abortIndex)\n\tassert.Equal(t, cp.Keys, c.Keys)\n\tassert.Equal(t, cp.engine, c.engine)\n\tassert.Equal(t, cp.Params, c.Params)\n\tcp.Set(\"foo\", \"notBar\")\n\tassert.False(t, cp.Keys[\"foo\"] == c.Keys[\"foo\"])\n}\n\nfunc TestContextHandlerName(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}\n\n\tassert.Regexp(t, \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$\", c.HandlerName())\n}\n\nfunc TestContextHandlerNames(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest, func(c *Context) {}, handlerNameTest2}\n\n\tnames := c.HandlerNames()\n\n\tassert.True(t, len(names) == 4)\n\tfor _, name := range names {\n\t\tassert.Regexp(t, `^(.*/vendor/)?(github\\.com/gin-gonic/gin\\.){1}(TestContextHandlerNames\\.func.*){0,1}(handlerNameTest.*){0,1}`, name)\n\t}\n}\n\nfunc handlerNameTest(c *Context) {\n}\n\n<|next_version|>\n\n\tassert.Equal(t, m, c.GetStringMapString(\"map\"))\n\tassert.Equal(t, \"bar\", c.GetStringMapString(\"map\")[\"foo\"])\n}\n\nfunc TestContextGetStringMapStringSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string][]string)\n\tm[\"foo\"] = []string{\"foo\"}\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMapStringSlice(\"map\"))\n\tassert.Equal(t, []string{\"foo\"}, c.GetStringMapStringSlice(\"map\")[\"foo\"])\n}\n\nfunc TestContextCopy(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.index = 2\n\tc.Request, _ = http.NewRequest(\"POST\", \"/hola\", nil)\n\tc.handlers = HandlersChain{func(c *Context) {}}\n\tc.Params = Params{Param{Key: \"foo\", Value: \"bar\"}}\n\tc.Set(\"foo\", \"bar\")\n\tc.fullPath = \"/hola\"\n\n\tcp := c.Copy()\n\tassert.Nil(t, cp.handlers)\n\tassert.Nil(t, cp.writermem.ResponseWriter)\n\tassert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))\n\tassert.Equal(t, cp.Request, c.Request)\n\tassert.Equal(t, cp.index, abortIndex)\n\tassert.Equal(t, cp.Keys, c.Keys)\n\tassert.Equal(t, cp.engine, c.engine)\n\tassert.Equal(t, cp.Params, c.Params)\n\tcp.Set(\"foo\", \"notBar\")\n\tassert.False(t, cp.Keys[\"foo\"] == c.Keys[\"foo\"])\n\tassert.Equal(t, cp.fullPath, c.fullPath)\n}\n\nfunc TestContextHandlerName(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}\n\n\tassert.Regexp(t, \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$\", c.HandlerName())\n}\n\nfunc TestContextHandlerNames(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest, func(c *Context) {}, handlerNameTest2}\n\n\tnames := c.HandlerNames()\n\n\tassert.True(t, len(names) == 4)\n\tfor _, name := range names {\n\t\tassert.Regexp(t, `^(.*/vendor/)?(github\\.com/gin-gonic/gin\\.){1}(TestContextHandlerNames\\.func.*){0,1}(handlerNameTest.*){0,1}`, name)\n\t}\n}\n\nfunc handlerNameTest(c *Context) {\n}\n\n", "current_contents": "\n\tassert.Equal(t, m, c.GetStringMapString(\"map\"))\n\tassert.Equal(t, \"bar\", c.GetStringMapString(\"map\")[\"foo\"])\n}\n\nfunc TestContextGetStringMapStringSlice(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tm := make(map[string][]string)\n\tm[\"foo\"] = []string{\"foo\"}\n\tc.Set(\"map\", m)\n\n\tassert.Equal(t, m, c.GetStringMapStringSlice(\"map\"))\n\tassert.Equal(t, []string{\"foo\"}, c.GetStringMapStringSlice(\"map\")[\"foo\"])\n}\n\nfunc TestContextCopy(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.index = 2\n\tc.Request, _ = http.NewRequest(\"POST\", \"/hola\", nil)\n\tc.handlers = HandlersChain{func(c *Context) {}}\n\tc.Params = Params{Param{Key: \"foo\", Value: \"bar\"}}\n\tc.Set(\"foo\", \"bar\")\n\tc.fullPath = \"/hola\"\n\n\tcp := c.Copy()\n\tassert.Nil(t, cp.handlers)\n\tassert.Nil(t, cp.writermem.ResponseWriter)\n\tassert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))\n\tassert.Equal(t, cp.Request, c.Request)\n\tassert.Equal(t, cp.index, abortIndex)\n\tassert.Equal(t, cp.Keys, c.Keys)\n\tassert.Equal(t, cp.engine, c.engine)\n\tassert.Equal(t, cp.Params, c.Params)\n\tcp.Set(\"foo\", \"notBar\")\n\tassert.False(t, cp.Keys[\"foo\"] == c.Keys[\"foo\"])\n}\n\nfunc TestContextHandlerName(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}\n\n\tassert.Regexp(t, \"^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$\", c.HandlerName())\n}\n\nfunc TestContextHandlerNames(t *testing.T) {\n\tc, _ := CreateTestContext(httptest.NewRecorder())\n\tc.handlers = HandlersChain{func(c *Context) {}, handlerNameTest, func(c *Context) {}, handlerNameTest2}\n\n\tnames := c.HandlerNames()\n\n\tassert.True(t, len(names) == 4)\n\tfor _, name := range names {\n\t\tassert.Regexp(t, `^(.*/vendor/)?(github\\.com/gin-gonic/gin\\.){1}(TestContextHandlerNames\\.func.*){0,1}(handlerNameTest.*){0,1}`, name)\n\t}\n}\n\nfunc handlerNameTest(c *Context) {\n}\n"} {"commit": "d17270dd90c488308de3102d6951946ca0a5911f", "message": "Sync route tree to httprouter latest code (#2368)", "old_file": "context.go", "new_file": "context.go", "status": "M", "old_contents": "\tMIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm\n\tMIMEYAML = binding.MIMEYAML\n)\n\n// BodyBytesKey indicates a default body bytes key.\nconst BodyBytesKey = \"_gin-gonic/gin/bodybyteskey\"\n\nconst abortIndex int8 = math.MaxInt8 / 2\n\n// Context is the most important part of gin. It allows us to pass variables between middleware,\n// manage the flow, validate the JSON of a request and render a JSON response for example.\ntype Context struct {\n\twritermem responseWriter\n\tRequest *http.Request\n\tWriter ResponseWriter\n\n\tParams Params\n\thandlers HandlersChain\n\tindex int8\n\tfullPath string\n\n\tengine *Engine\n\n\t// This mutex protect Keys map\n\tmu sync.RWMutex\n\n\t// Keys is a key/value pair exclusively for the context of each request.\n\tKeys map[string]interface{}\n\n\t// Errors is a list of errors attached to all the handlers/middlewares who used this context.\n\tErrors errorMsgs\n\n\t// Accepted defines a list of manually accepted formats for content negotiation.\n\tAccepted []string\n\n\t// queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()\n\tqueryCache url.Values\n\n\t// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,\n\t// or PUT body parameters.\n\tformCache url.Values\n\n\t// SameSite allows a server to define a cookie attribute making it impossible for\n\t// the browser to send this cookie along with cross-site requests.\n\tsameSite http.SameSite\n}\n\n/************************************/\n/********** CONTEXT CREATION ********/\n/************************************/\n\nfunc (c *Context) reset() {\n\tc.Writer = &c.writermem\n\tc.Params = c.Params[0:0]\n\tc.handlers = nil\n\tc.index = -1\n\n\tc.fullPath = \"\"\n\tc.Keys = nil\n\tc.Errors = c.Errors[0:0]\n\tc.Accepted = nil\n\tc.queryCache = nil\n\tc.formCache = nil\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tParams: c.Params,\n\t\tengine: c.engine,\n\t}\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.Keys = map[string]interface{}{}\n\tfor k, v := range c.Keys {\n\t\tcp.Keys[k] = v\n\t}\n\tparamCopy := make([]Param, len(cp.Params))\n\tcopy(paramCopy, cp.Params)\n\tcp.Params = paramCopy\n\treturn &cp\n}", "new_contents": "\tMIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm\n\tMIMEYAML = binding.MIMEYAML\n)\n\n// BodyBytesKey indicates a default body bytes key.\nconst BodyBytesKey = \"_gin-gonic/gin/bodybyteskey\"\n\nconst abortIndex int8 = math.MaxInt8 / 2\n\n// Context is the most important part of gin. It allows us to pass variables between middleware,\n// manage the flow, validate the JSON of a request and render a JSON response for example.\ntype Context struct {\n\twritermem responseWriter\n\tRequest *http.Request\n\tWriter ResponseWriter\n\n\tParams Params\n\thandlers HandlersChain\n\tindex int8\n\tfullPath string\n\n\tengine *Engine\n\tparams *Params\n\n\t// This mutex protect Keys map\n\tmu sync.RWMutex\n\n\t// Keys is a key/value pair exclusively for the context of each request.\n\tKeys map[string]interface{}\n\n\t// Errors is a list of errors attached to all the handlers/middlewares who used this context.\n\tErrors errorMsgs\n\n\t// Accepted defines a list of manually accepted formats for content negotiation.\n\tAccepted []string\n\n\t// queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()\n\tqueryCache url.Values\n\n\t// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,\n\t// or PUT body parameters.\n\tformCache url.Values\n\n\t// SameSite allows a server to define a cookie attribute making it impossible for\n\t// the browser to send this cookie along with cross-site requests.\n\tsameSite http.SameSite\n}\n\n/************************************/\n/********** CONTEXT CREATION ********/\n/************************************/\n\nfunc (c *Context) reset() {\n\tc.Writer = &c.writermem\n\tc.Params = c.Params[0:0]\n\tc.handlers = nil\n\tc.index = -1\n\n\tc.fullPath = \"\"\n\tc.Keys = nil\n\tc.Errors = c.Errors[0:0]\n\tc.Accepted = nil\n\tc.queryCache = nil\n\tc.formCache = nil\n\t*c.params = (*c.params)[0:0]\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tParams: c.Params,\n\t\tengine: c.engine,\n\t}\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.Keys = map[string]interface{}{}\n\tfor k, v := range c.Keys {\n\t\tcp.Keys[k] = v\n\t}\n\tparamCopy := make([]Param, len(cp.Params))\n\tcopy(paramCopy, cp.Params)\n\tcp.Params = paramCopy\n\treturn &cp\n}", "text": "<|original_code|>\n\tMIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm\n\tMIMEYAML = binding.MIMEYAML\n)\n\n// BodyBytesKey indicates a default body bytes key.\nconst BodyBytesKey = \"_gin-gonic/gin/bodybyteskey\"\n\nconst abortIndex int8 = math.MaxInt8 / 2\n\n// Context is the most important part of gin. It allows us to pass variables between middleware,\n// manage the flow, validate the JSON of a request and render a JSON response for example.\ntype Context struct {\n\twritermem responseWriter\n\tRequest *http.Request\n\tWriter ResponseWriter\n\n\tParams Params\n\thandlers HandlersChain\n\tindex int8\n\tfullPath string\n\n\tengine *Engine\n\n\t// This mutex protect Keys map\n\tmu sync.RWMutex\n\n\t// Keys is a key/value pair exclusively for the context of each request.\n\tKeys map[string]interface{}\n\n\t// Errors is a list of errors attached to all the handlers/middlewares who used this context.\n\tErrors errorMsgs\n\n\t// Accepted defines a list of manually accepted formats for content negotiation.\n\tAccepted []string\n\n\t// queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()\n\tqueryCache url.Values\n\n\t// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,\n\t// or PUT body parameters.\n\tformCache url.Values\n\n\t// SameSite allows a server to define a cookie attribute making it impossible for\n\t// the browser to send this cookie along with cross-site requests.\n\tsameSite http.SameSite\n}\n\n/************************************/\n/********** CONTEXT CREATION ********/\n/************************************/\n\nfunc (c *Context) reset() {\n\tc.Writer = &c.writermem\n\tc.Params = c.Params[0:0]\n\tc.handlers = nil\n\tc.index = -1\n\n\tc.fullPath = \"\"\n\tc.Keys = nil\n\tc.Errors = c.Errors[0:0]\n\tc.Accepted = nil\n\tc.queryCache = nil\n\tc.formCache = nil\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tParams: c.Params,\n\t\tengine: c.engine,\n\t}\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.Keys = map[string]interface{}{}\n\tfor k, v := range c.Keys {\n\t\tcp.Keys[k] = v\n\t}\n\tparamCopy := make([]Param, len(cp.Params))\n\tcopy(paramCopy, cp.Params)\n\tcp.Params = paramCopy\n\treturn &cp\n}\n<|edits_diff|>\n--- context.go\n+++ context.go\n@@ -20,6 +20,7 @@\n \tfullPath string\n \n \tengine *Engine\n+\tparams *Params\n \n \t// This mutex protect Keys map\n \tmu sync.RWMutex\n<|current_version|>\n\tMIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm\n\tMIMEYAML = binding.MIMEYAML\n)\n\n// BodyBytesKey indicates a default body bytes key.\nconst BodyBytesKey = \"_gin-gonic/gin/bodybyteskey\"\n\nconst abortIndex int8 = math.MaxInt8 / 2\n\n// Context is the most important part of gin. It allows us to pass variables between middleware,\n// manage the flow, validate the JSON of a request and render a JSON response for example.\ntype Context struct {\n\twritermem responseWriter\n\tRequest *http.Request\n\tWriter ResponseWriter\n\n\tParams Params\n\thandlers HandlersChain\n\tindex int8\n\tfullPath string\n\n\tengine *Engine\n\tparams *Params\n\n\t// This mutex protect Keys map\n\tmu sync.RWMutex\n\n\t// Keys is a key/value pair exclusively for the context of each request.\n\tKeys map[string]interface{}\n\n\t// Errors is a list of errors attached to all the handlers/middlewares who used this context.\n\tErrors errorMsgs\n\n\t// Accepted defines a list of manually accepted formats for content negotiation.\n\tAccepted []string\n\n\t// queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()\n\tqueryCache url.Values\n\n\t// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,\n\t// or PUT body parameters.\n\tformCache url.Values\n\n\t// SameSite allows a server to define a cookie attribute making it impossible for\n\t// the browser to send this cookie along with cross-site requests.\n\tsameSite http.SameSite\n}\n\n/************************************/\n/********** CONTEXT CREATION ********/\n/************************************/\n\nfunc (c *Context) reset() {\n\tc.Writer = &c.writermem\n\tc.Params = c.Params[0:0]\n\tc.handlers = nil\n\tc.index = -1\n\n\tc.fullPath = \"\"\n\tc.Keys = nil\n\tc.Errors = c.Errors[0:0]\n\tc.Accepted = nil\n\tc.queryCache = nil\n\tc.formCache = nil\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tParams: c.Params,\n\t\tengine: c.engine,\n\t}\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.Keys = map[string]interface{}{}\n\tfor k, v := range c.Keys {\n\t\tcp.Keys[k] = v\n\t}\n\tparamCopy := make([]Param, len(cp.Params))\n\tcopy(paramCopy, cp.Params)\n\tcp.Params = paramCopy\n\treturn &cp\n}\n<|next_version|>\n\tMIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm\n\tMIMEYAML = binding.MIMEYAML\n)\n\n// BodyBytesKey indicates a default body bytes key.\nconst BodyBytesKey = \"_gin-gonic/gin/bodybyteskey\"\n\nconst abortIndex int8 = math.MaxInt8 / 2\n\n// Context is the most important part of gin. It allows us to pass variables between middleware,\n// manage the flow, validate the JSON of a request and render a JSON response for example.\ntype Context struct {\n\twritermem responseWriter\n\tRequest *http.Request\n\tWriter ResponseWriter\n\n\tParams Params\n\thandlers HandlersChain\n\tindex int8\n\tfullPath string\n\n\tengine *Engine\n\tparams *Params\n\n\t// This mutex protect Keys map\n\tmu sync.RWMutex\n\n\t// Keys is a key/value pair exclusively for the context of each request.\n\tKeys map[string]interface{}\n\n\t// Errors is a list of errors attached to all the handlers/middlewares who used this context.\n\tErrors errorMsgs\n\n\t// Accepted defines a list of manually accepted formats for content negotiation.\n\tAccepted []string\n\n\t// queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()\n\tqueryCache url.Values\n\n\t// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,\n\t// or PUT body parameters.\n\tformCache url.Values\n\n\t// SameSite allows a server to define a cookie attribute making it impossible for\n\t// the browser to send this cookie along with cross-site requests.\n\tsameSite http.SameSite\n}\n\n/************************************/\n/********** CONTEXT CREATION ********/\n/************************************/\n\nfunc (c *Context) reset() {\n\tc.Writer = &c.writermem\n\tc.Params = c.Params[0:0]\n\tc.handlers = nil\n\tc.index = -1\n\n\tc.fullPath = \"\"\n\tc.Keys = nil\n\tc.Errors = c.Errors[0:0]\n\tc.Accepted = nil\n\tc.queryCache = nil\n\tc.formCache = nil\n\t*c.params = (*c.params)[0:0]\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tParams: c.Params,\n\t\tengine: c.engine,\n\t}\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.Keys = map[string]interface{}{}\n\tfor k, v := range c.Keys {\n\t\tcp.Keys[k] = v\n\t}\n\tparamCopy := make([]Param, len(cp.Params))\n\tcopy(paramCopy, cp.Params)\n\tcp.Params = paramCopy\n\treturn &cp\n}\n", "current_contents": "\tMIMEMultipartPOSTForm = binding.MIMEMultipartPOSTForm\n\tMIMEYAML = binding.MIMEYAML\n)\n\n// BodyBytesKey indicates a default body bytes key.\nconst BodyBytesKey = \"_gin-gonic/gin/bodybyteskey\"\n\nconst abortIndex int8 = math.MaxInt8 / 2\n\n// Context is the most important part of gin. It allows us to pass variables between middleware,\n// manage the flow, validate the JSON of a request and render a JSON response for example.\ntype Context struct {\n\twritermem responseWriter\n\tRequest *http.Request\n\tWriter ResponseWriter\n\n\tParams Params\n\thandlers HandlersChain\n\tindex int8\n\tfullPath string\n\n\tengine *Engine\n\tparams *Params\n\n\t// This mutex protect Keys map\n\tmu sync.RWMutex\n\n\t// Keys is a key/value pair exclusively for the context of each request.\n\tKeys map[string]interface{}\n\n\t// Errors is a list of errors attached to all the handlers/middlewares who used this context.\n\tErrors errorMsgs\n\n\t// Accepted defines a list of manually accepted formats for content negotiation.\n\tAccepted []string\n\n\t// queryCache use url.ParseQuery cached the param query result from c.Request.URL.Query()\n\tqueryCache url.Values\n\n\t// formCache use url.ParseQuery cached PostForm contains the parsed form data from POST, PATCH,\n\t// or PUT body parameters.\n\tformCache url.Values\n\n\t// SameSite allows a server to define a cookie attribute making it impossible for\n\t// the browser to send this cookie along with cross-site requests.\n\tsameSite http.SameSite\n}\n\n/************************************/\n/********** CONTEXT CREATION ********/\n/************************************/\n\nfunc (c *Context) reset() {\n\tc.Writer = &c.writermem\n\tc.Params = c.Params[0:0]\n\tc.handlers = nil\n\tc.index = -1\n\n\tc.fullPath = \"\"\n\tc.Keys = nil\n\tc.Errors = c.Errors[0:0]\n\tc.Accepted = nil\n\tc.queryCache = nil\n\tc.formCache = nil\n}\n\n// Copy returns a copy of the current context that can be safely used outside the request's scope.\n// This has to be used when the context has to be passed to a goroutine.\nfunc (c *Context) Copy() *Context {\n\tcp := Context{\n\t\twritermem: c.writermem,\n\t\tRequest: c.Request,\n\t\tParams: c.Params,\n\t\tengine: c.engine,\n\t}\n\tcp.writermem.ResponseWriter = nil\n\tcp.Writer = &cp.writermem\n\tcp.index = abortIndex\n\tcp.handlers = nil\n\tcp.Keys = map[string]interface{}{}\n\tfor k, v := range c.Keys {\n\t\tcp.Keys[k] = v\n\t}\n\tparamCopy := make([]Param, len(cp.Params))\n\tcopy(paramCopy, cp.Params)\n\tcp.Params = paramCopy\n\treturn &cp\n}"} {"commit": "731c827892f5b1eac9f58fc65cef32fa1908972c", "message": "add yaml negotitation (#2220)", "old_file": "context.go", "new_file": "context.go", "status": "M", "old_contents": "\t\t\treturn true\n\t\tdefault:\n\t\t\tkeepOpen := step(w)\n\t\t\tw.Flush()\n\t\t\tif !keepOpen {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n}\n\n/************************************/\n/******** CONTENT NEGOTIATION *******/\n/************************************/\n\n// Negotiate contains all negotiations data.\ntype Negotiate struct {\n\tOffered []string\n\tHTMLName string\n\tHTMLData interface{}\n\tJSONData interface{}\n\tXMLData interface{}\n\tData interface{}\n}\n\n// Negotiate calls different Render according acceptable Accept format.\nfunc (c *Context) Negotiate(code int, config Negotiate) {\n\tswitch c.NegotiateFormat(config.Offered...) {\n\tcase binding.MIMEJSON:\n\t\tdata := chooseData(config.JSONData, config.Data)\n\t\tc.JSON(code, data)\n\n\tcase binding.MIMEHTML:\n\t\tdata := chooseData(config.HTMLData, config.Data)\n\t\tc.HTML(code, config.HTMLName, data)\n\n\tcase binding.MIMEXML:\n\t\tdata := chooseData(config.XMLData, config.Data)\n\t\tc.XML(code, data)\n\n\tdefault:\n\t\tc.AbortWithError(http.StatusNotAcceptable, errors.New(\"the accepted formats are not offered by the server\")) // nolint: errcheck\n\t}\n}\n\n// NegotiateFormat returns an acceptable Accept format.\nfunc (c *Context) NegotiateFormat(offered ...string) string {\n\tassert1(len(offered) > 0, \"you must provide at least one offer\")\n\n\tif c.Accepted == nil {\n\t\tc.Accepted = parseAccept(c.requestHeader(\"Accept\"))\n\t}\n\tif len(c.Accepted) == 0 {\n\t\treturn offered[0]\n\t}\n\tfor _, accepted := range c.Accepted {\n\t\tfor _, offer := range offered {\n\t\t\t// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,\n\t\t\t// therefore we can just iterate over the string without casting it into []rune\n\t\t\ti := 0\n\t\t\tfor ; i < len(accepted); i++ {\n\t\t\t\tif accepted[i] == '*' || offer[i] == '*' {\n\t\t\t\t\treturn offer", "new_contents": "\t\t\treturn true\n\t\tdefault:\n\t\t\tkeepOpen := step(w)\n\t\t\tw.Flush()\n\t\t\tif !keepOpen {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n}\n\n/************************************/\n/******** CONTENT NEGOTIATION *******/\n/************************************/\n\n// Negotiate contains all negotiations data.\ntype Negotiate struct {\n\tOffered []string\n\tHTMLName string\n\tHTMLData interface{}\n\tJSONData interface{}\n\tXMLData interface{}\n\tYAMLData interface{}\n\tData interface{}\n}\n\n// Negotiate calls different Render according acceptable Accept format.\nfunc (c *Context) Negotiate(code int, config Negotiate) {\n\tswitch c.NegotiateFormat(config.Offered...) {\n\tcase binding.MIMEJSON:\n\t\tdata := chooseData(config.JSONData, config.Data)\n\t\tc.JSON(code, data)\n\n\tcase binding.MIMEHTML:\n\t\tdata := chooseData(config.HTMLData, config.Data)\n\t\tc.HTML(code, config.HTMLName, data)\n\n\tcase binding.MIMEXML:\n\t\tdata := chooseData(config.XMLData, config.Data)\n\t\tc.XML(code, data)\n\n\tcase binding.MIMEYAML:\n\t\tdata := chooseData(config.YAMLData, config.Data)\n\t\tc.YAML(code, data)\n\n\tdefault:\n\t\tc.AbortWithError(http.StatusNotAcceptable, errors.New(\"the accepted formats are not offered by the server\")) // nolint: errcheck\n\t}\n}\n\n// NegotiateFormat returns an acceptable Accept format.\nfunc (c *Context) NegotiateFormat(offered ...string) string {\n\tassert1(len(offered) > 0, \"you must provide at least one offer\")\n\n\tif c.Accepted == nil {\n\t\tc.Accepted = parseAccept(c.requestHeader(\"Accept\"))\n\t}\n\tif len(c.Accepted) == 0 {\n\t\treturn offered[0]\n\t}\n\tfor _, accepted := range c.Accepted {\n\t\tfor _, offer := range offered {\n\t\t\t// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,\n\t\t\t// therefore we can just iterate over the string without casting it into []rune\n\t\t\ti := 0\n\t\t\tfor ; i < len(accepted); i++ {\n\t\t\t\tif accepted[i] == '*' || offer[i] == '*' {\n\t\t\t\t\treturn offer", "text": "<|original_code|>\n\t\t\treturn true\n\t\tdefault:\n\t\t\tkeepOpen := step(w)\n\t\t\tw.Flush()\n\t\t\tif !keepOpen {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n}\n\n/************************************/\n/******** CONTENT NEGOTIATION *******/\n/************************************/\n\n// Negotiate contains all negotiations data.\ntype Negotiate struct {\n\tOffered []string\n\tHTMLName string\n\tHTMLData interface{}\n\tJSONData interface{}\n\tXMLData interface{}\n\tData interface{}\n}\n\n// Negotiate calls different Render according acceptable Accept format.\nfunc (c *Context) Negotiate(code int, config Negotiate) {\n\tswitch c.NegotiateFormat(config.Offered...) {\n\tcase binding.MIMEJSON:\n\t\tdata := chooseData(config.JSONData, config.Data)\n\t\tc.JSON(code, data)\n\n\tcase binding.MIMEHTML:\n\t\tdata := chooseData(config.HTMLData, config.Data)\n\t\tc.HTML(code, config.HTMLName, data)\n\n\tcase binding.MIMEXML:\n\t\tdata := chooseData(config.XMLData, config.Data)\n\t\tc.XML(code, data)\n\n\tdefault:\n\t\tc.AbortWithError(http.StatusNotAcceptable, errors.New(\"the accepted formats are not offered by the server\")) // nolint: errcheck\n\t}\n}\n\n// NegotiateFormat returns an acceptable Accept format.\nfunc (c *Context) NegotiateFormat(offered ...string) string {\n\tassert1(len(offered) > 0, \"you must provide at least one offer\")\n\n\tif c.Accepted == nil {\n\t\tc.Accepted = parseAccept(c.requestHeader(\"Accept\"))\n\t}\n\tif len(c.Accepted) == 0 {\n\t\treturn offered[0]\n\t}\n\tfor _, accepted := range c.Accepted {\n\t\tfor _, offer := range offered {\n\t\t\t// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,\n\t\t\t// therefore we can just iterate over the string without casting it into []rune\n\t\t\ti := 0\n\t\t\tfor ; i < len(accepted); i++ {\n\t\t\t\tif accepted[i] == '*' || offer[i] == '*' {\n\t\t\t\t\treturn offer\n<|edits_diff|>\n--- context.go\n+++ context.go\n@@ -20,6 +20,7 @@\n \tHTMLData interface{}\n \tJSONData interface{}\n \tXMLData interface{}\n+\tYAMLData interface{}\n \tData interface{}\n }\n \n<|current_version|>\n\t\t\treturn true\n\t\tdefault:\n\t\t\tkeepOpen := step(w)\n\t\t\tw.Flush()\n\t\t\tif !keepOpen {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n}\n\n/************************************/\n/******** CONTENT NEGOTIATION *******/\n/************************************/\n\n// Negotiate contains all negotiations data.\ntype Negotiate struct {\n\tOffered []string\n\tHTMLName string\n\tHTMLData interface{}\n\tJSONData interface{}\n\tXMLData interface{}\n\tYAMLData interface{}\n\tData interface{}\n}\n\n// Negotiate calls different Render according acceptable Accept format.\nfunc (c *Context) Negotiate(code int, config Negotiate) {\n\tswitch c.NegotiateFormat(config.Offered...) {\n\tcase binding.MIMEJSON:\n\t\tdata := chooseData(config.JSONData, config.Data)\n\t\tc.JSON(code, data)\n\n\tcase binding.MIMEHTML:\n\t\tdata := chooseData(config.HTMLData, config.Data)\n\t\tc.HTML(code, config.HTMLName, data)\n\n\tcase binding.MIMEXML:\n\t\tdata := chooseData(config.XMLData, config.Data)\n\t\tc.XML(code, data)\n\n\tdefault:\n\t\tc.AbortWithError(http.StatusNotAcceptable, errors.New(\"the accepted formats are not offered by the server\")) // nolint: errcheck\n\t}\n}\n\n// NegotiateFormat returns an acceptable Accept format.\nfunc (c *Context) NegotiateFormat(offered ...string) string {\n\tassert1(len(offered) > 0, \"you must provide at least one offer\")\n\n\tif c.Accepted == nil {\n\t\tc.Accepted = parseAccept(c.requestHeader(\"Accept\"))\n\t}\n\tif len(c.Accepted) == 0 {\n\t\treturn offered[0]\n\t}\n\tfor _, accepted := range c.Accepted {\n\t\tfor _, offer := range offered {\n\t\t\t// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,\n\t\t\t// therefore we can just iterate over the string without casting it into []rune\n\t\t\ti := 0\n\t\t\tfor ; i < len(accepted); i++ {\n\t\t\t\tif accepted[i] == '*' || offer[i] == '*' {\n\t\t\t\t\treturn offer\n<|next_version|>\n\t\t\treturn true\n\t\tdefault:\n\t\t\tkeepOpen := step(w)\n\t\t\tw.Flush()\n\t\t\tif !keepOpen {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n}\n\n/************************************/\n/******** CONTENT NEGOTIATION *******/\n/************************************/\n\n// Negotiate contains all negotiations data.\ntype Negotiate struct {\n\tOffered []string\n\tHTMLName string\n\tHTMLData interface{}\n\tJSONData interface{}\n\tXMLData interface{}\n\tYAMLData interface{}\n\tData interface{}\n}\n\n// Negotiate calls different Render according acceptable Accept format.\nfunc (c *Context) Negotiate(code int, config Negotiate) {\n\tswitch c.NegotiateFormat(config.Offered...) {\n\tcase binding.MIMEJSON:\n\t\tdata := chooseData(config.JSONData, config.Data)\n\t\tc.JSON(code, data)\n\n\tcase binding.MIMEHTML:\n\t\tdata := chooseData(config.HTMLData, config.Data)\n\t\tc.HTML(code, config.HTMLName, data)\n\n\tcase binding.MIMEXML:\n\t\tdata := chooseData(config.XMLData, config.Data)\n\t\tc.XML(code, data)\n\n\tcase binding.MIMEYAML:\n\t\tdata := chooseData(config.YAMLData, config.Data)\n\t\tc.YAML(code, data)\n\n\tdefault:\n\t\tc.AbortWithError(http.StatusNotAcceptable, errors.New(\"the accepted formats are not offered by the server\")) // nolint: errcheck\n\t}\n}\n\n// NegotiateFormat returns an acceptable Accept format.\nfunc (c *Context) NegotiateFormat(offered ...string) string {\n\tassert1(len(offered) > 0, \"you must provide at least one offer\")\n\n\tif c.Accepted == nil {\n\t\tc.Accepted = parseAccept(c.requestHeader(\"Accept\"))\n\t}\n\tif len(c.Accepted) == 0 {\n\t\treturn offered[0]\n\t}\n\tfor _, accepted := range c.Accepted {\n\t\tfor _, offer := range offered {\n\t\t\t// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,\n\t\t\t// therefore we can just iterate over the string without casting it into []rune\n\t\t\ti := 0\n\t\t\tfor ; i < len(accepted); i++ {\n\t\t\t\tif accepted[i] == '*' || offer[i] == '*' {\n\t\t\t\t\treturn offer\n", "current_contents": "\t\t\treturn true\n\t\tdefault:\n\t\t\tkeepOpen := step(w)\n\t\t\tw.Flush()\n\t\t\tif !keepOpen {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n}\n\n/************************************/\n/******** CONTENT NEGOTIATION *******/\n/************************************/\n\n// Negotiate contains all negotiations data.\ntype Negotiate struct {\n\tOffered []string\n\tHTMLName string\n\tHTMLData interface{}\n\tJSONData interface{}\n\tXMLData interface{}\n\tYAMLData interface{}\n\tData interface{}\n}\n\n// Negotiate calls different Render according acceptable Accept format.\nfunc (c *Context) Negotiate(code int, config Negotiate) {\n\tswitch c.NegotiateFormat(config.Offered...) {\n\tcase binding.MIMEJSON:\n\t\tdata := chooseData(config.JSONData, config.Data)\n\t\tc.JSON(code, data)\n\n\tcase binding.MIMEHTML:\n\t\tdata := chooseData(config.HTMLData, config.Data)\n\t\tc.HTML(code, config.HTMLName, data)\n\n\tcase binding.MIMEXML:\n\t\tdata := chooseData(config.XMLData, config.Data)\n\t\tc.XML(code, data)\n\n\tdefault:\n\t\tc.AbortWithError(http.StatusNotAcceptable, errors.New(\"the accepted formats are not offered by the server\")) // nolint: errcheck\n\t}\n}\n\n// NegotiateFormat returns an acceptable Accept format.\nfunc (c *Context) NegotiateFormat(offered ...string) string {\n\tassert1(len(offered) > 0, \"you must provide at least one offer\")\n\n\tif c.Accepted == nil {\n\t\tc.Accepted = parseAccept(c.requestHeader(\"Accept\"))\n\t}\n\tif len(c.Accepted) == 0 {\n\t\treturn offered[0]\n\t}\n\tfor _, accepted := range c.Accepted {\n\t\tfor _, offer := range offered {\n\t\t\t// According to RFC 2616 and RFC 2396, non-ASCII characters are not allowed in headers,\n\t\t\t// therefore we can just iterate over the string without casting it into []rune\n\t\t\ti := 0\n\t\t\tfor ; i < len(accepted); i++ {\n\t\t\t\tif accepted[i] == '*' || offer[i] == '*' {\n\t\t\t\t\treturn offer"} {"commit": "8cb390f8fe847854adf21aca97561db9602d4ad8", "message": "Yaml binding (#1618)", "old_file": "binding/binding.go", "new_file": "binding/binding.go", "status": "M", "old_contents": "// Copyright 2014 Manu Martinez-Almeida. All rights reserved.\n// Use of this source code is governed by a MIT style\n// license that can be found in the LICENSE file.\n\npackage binding\n\nimport \"net/http\"\n\n// Content-Type MIME of the most common data formats.\nconst (\n\tMIMEJSON = \"application/json\"\n\tMIMEHTML = \"text/html\"\n\tMIMEXML = \"application/xml\"\n\tMIMEXML2 = \"text/xml\"\n\tMIMEPlain = \"text/plain\"\n\tMIMEPOSTForm = \"application/x-www-form-urlencoded\"\n\tMIMEMultipartPOSTForm = \"multipart/form-data\"\n\tMIMEPROTOBUF = \"application/x-protobuf\"\n\tMIMEMSGPACK = \"application/x-msgpack\"\n\tMIMEMSGPACK2 = \"application/msgpack\"\n)\n\n// Binding describes the interface which needs to be implemented for binding the\n// data present in the request such as JSON request body, query parameters or\n// the form POST.\ntype Binding interface {\n\tName() string\n\tBind(*http.Request, interface{}) error\n}\n\n// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,\n// but it reads the body from supplied bytes instead of req.Body.\ntype BindingBody interface {\n\tBinding\n\tBindBody([]byte, interface{}) error\n}\n\n// StructValidator is the minimal interface which needs to be implemented in\n// order for it to be used as the validator engine for ensuring the correctness\n// of the request. Gin provides a default implementation for this using\n// https://github.com/go-playground/validator/tree/v8.18.2.\ntype StructValidator interface {\n\t// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.\n\t// If the received type is not a struct, any validation should be skipped and nil must be returned.\n\t// If the received type is a struct or pointer to a struct, the validation should be performed.\n\t// If the struct is not valid or the validation itself fails, a descriptive error should be returned.\n\t// Otherwise nil must be returned.\n\tValidateStruct(interface{}) error\n\n\t// Engine returns the underlying validator engine which powers the\n\t// StructValidator implementation.\n\tEngine() interface{}\n}\n\n// Validator is the default validator which implements the StructValidator\n// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2\n// under the hood.\nvar Validator StructValidator = &defaultValidator{}\n\n// These implement the Binding interface and can be used to bind the data\n// present in the request to struct instances.\nvar (\n\tJSON = jsonBinding{}\n\tXML = xmlBinding{}\n\tForm = formBinding{}\n\tQuery = queryBinding{}\n\tFormPost = formPostBinding{}\n\tFormMultipart = formMultipartBinding{}\n\tProtoBuf = protobufBinding{}\n\tMsgPack = msgpackBinding{}\n)\n\n// Default returns the appropriate Binding instance based on the HTTP method\n// and the content type.\nfunc Default(method, contentType string) Binding {\n\tif method == \"GET\" {\n\t\treturn Form\n\t}\n\n\tswitch contentType {\n\tcase MIMEJSON:\n\t\treturn JSON\n\tcase MIMEXML, MIMEXML2:\n\t\treturn XML\n\tcase MIMEPROTOBUF:\n\t\treturn ProtoBuf\n\tcase MIMEMSGPACK, MIMEMSGPACK2:\n\t\treturn MsgPack\n\tdefault: //case MIMEPOSTForm, MIMEMultipartPOSTForm:\n\t\treturn Form\n\t}\n}\n\nfunc validate(obj interface{}) error {\n\tif Validator == nil {\n\t\treturn nil\n\t}\n\treturn Validator.ValidateStruct(obj)\n}\n", "new_contents": "// Copyright 2014 Manu Martinez-Almeida. All rights reserved.\n// Use of this source code is governed by a MIT style\n// license that can be found in the LICENSE file.\n\npackage binding\n\nimport \"net/http\"\n\n// Content-Type MIME of the most common data formats.\nconst (\n\tMIMEJSON = \"application/json\"\n\tMIMEHTML = \"text/html\"\n\tMIMEXML = \"application/xml\"\n\tMIMEXML2 = \"text/xml\"\n\tMIMEPlain = \"text/plain\"\n\tMIMEPOSTForm = \"application/x-www-form-urlencoded\"\n\tMIMEMultipartPOSTForm = \"multipart/form-data\"\n\tMIMEPROTOBUF = \"application/x-protobuf\"\n\tMIMEMSGPACK = \"application/x-msgpack\"\n\tMIMEMSGPACK2 = \"application/msgpack\"\n\tMIMEYAML = \"application/x-yaml\"\n)\n\n// Binding describes the interface which needs to be implemented for binding the\n// data present in the request such as JSON request body, query parameters or\n// the form POST.\ntype Binding interface {\n\tName() string\n\tBind(*http.Request, interface{}) error\n}\n\n// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,\n// but it reads the body from supplied bytes instead of req.Body.\ntype BindingBody interface {\n\tBinding\n\tBindBody([]byte, interface{}) error\n}\n\n// StructValidator is the minimal interface which needs to be implemented in\n// order for it to be used as the validator engine for ensuring the correctness\n// of the request. Gin provides a default implementation for this using\n// https://github.com/go-playground/validator/tree/v8.18.2.\ntype StructValidator interface {\n\t// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.\n\t// If the received type is not a struct, any validation should be skipped and nil must be returned.\n\t// If the received type is a struct or pointer to a struct, the validation should be performed.\n\t// If the struct is not valid or the validation itself fails, a descriptive error should be returned.\n\t// Otherwise nil must be returned.\n\tValidateStruct(interface{}) error\n\n\t// Engine returns the underlying validator engine which powers the\n\t// StructValidator implementation.\n\tEngine() interface{}\n}\n\n// Validator is the default validator which implements the StructValidator\n// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2\n// under the hood.\nvar Validator StructValidator = &defaultValidator{}\n\n// These implement the Binding interface and can be used to bind the data\n// present in the request to struct instances.\nvar (\n\tJSON = jsonBinding{}\n\tXML = xmlBinding{}\n\tForm = formBinding{}\n\tQuery = queryBinding{}\n\tFormPost = formPostBinding{}\n\tFormMultipart = formMultipartBinding{}\n\tProtoBuf = protobufBinding{}\n\tMsgPack = msgpackBinding{}\n\tYAML = yamlBinding{}\n)\n\n// Default returns the appropriate Binding instance based on the HTTP method\n// and the content type.\nfunc Default(method, contentType string) Binding {\n\tif method == \"GET\" {\n\t\treturn Form\n\t}\n\n\tswitch contentType {\n\tcase MIMEJSON:\n\t\treturn JSON\n\tcase MIMEXML, MIMEXML2:\n\t\treturn XML\n\tcase MIMEPROTOBUF:\n\t\treturn ProtoBuf\n\tcase MIMEMSGPACK, MIMEMSGPACK2:\n\t\treturn MsgPack\n\tcase MIMEYAML:\n\t\treturn YAML\n\tdefault: //case MIMEPOSTForm, MIMEMultipartPOSTForm:\n\t\treturn Form\n\t}\n}\n\nfunc validate(obj interface{}) error {\n\tif Validator == nil {\n\t\treturn nil\n\t}\n\treturn Validator.ValidateStruct(obj)\n}\n", "text": "<|original_code|>\n// Copyright 2014 Manu Martinez-Almeida. All rights reserved.\n// Use of this source code is governed by a MIT style\n// license that can be found in the LICENSE file.\n\npackage binding\n\nimport \"net/http\"\n\n// Content-Type MIME of the most common data formats.\nconst (\n\tMIMEJSON = \"application/json\"\n\tMIMEHTML = \"text/html\"\n\tMIMEXML = \"application/xml\"\n\tMIMEXML2 = \"text/xml\"\n\tMIMEPlain = \"text/plain\"\n\tMIMEPOSTForm = \"application/x-www-form-urlencoded\"\n\tMIMEMultipartPOSTForm = \"multipart/form-data\"\n\tMIMEPROTOBUF = \"application/x-protobuf\"\n\tMIMEMSGPACK = \"application/x-msgpack\"\n\tMIMEMSGPACK2 = \"application/msgpack\"\n)\n\n// Binding describes the interface which needs to be implemented for binding the\n// data present in the request such as JSON request body, query parameters or\n// the form POST.\ntype Binding interface {\n\tName() string\n\tBind(*http.Request, interface{}) error\n}\n\n// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,\n// but it reads the body from supplied bytes instead of req.Body.\ntype BindingBody interface {\n\tBinding\n\tBindBody([]byte, interface{}) error\n}\n\n// StructValidator is the minimal interface which needs to be implemented in\n// order for it to be used as the validator engine for ensuring the correctness\n// of the request. Gin provides a default implementation for this using\n// https://github.com/go-playground/validator/tree/v8.18.2.\ntype StructValidator interface {\n\t// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.\n\t// If the received type is not a struct, any validation should be skipped and nil must be returned.\n\t// If the received type is a struct or pointer to a struct, the validation should be performed.\n\t// If the struct is not valid or the validation itself fails, a descriptive error should be returned.\n\t// Otherwise nil must be returned.\n\tValidateStruct(interface{}) error\n\n\t// Engine returns the underlying validator engine which powers the\n\t// StructValidator implementation.\n\tEngine() interface{}\n}\n\n// Validator is the default validator which implements the StructValidator\n// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2\n// under the hood.\nvar Validator StructValidator = &defaultValidator{}\n\n// These implement the Binding interface and can be used to bind the data\n// present in the request to struct instances.\nvar (\n\tJSON = jsonBinding{}\n\tXML = xmlBinding{}\n\tForm = formBinding{}\n\tQuery = queryBinding{}\n\tFormPost = formPostBinding{}\n\tFormMultipart = formMultipartBinding{}\n\tProtoBuf = protobufBinding{}\n\tMsgPack = msgpackBinding{}\n)\n\n// Default returns the appropriate Binding instance based on the HTTP method\n// and the content type.\nfunc Default(method, contentType string) Binding {\n\tif method == \"GET\" {\n\t\treturn Form\n\t}\n\n\tswitch contentType {\n\tcase MIMEJSON:\n\t\treturn JSON\n\tcase MIMEXML, MIMEXML2:\n\t\treturn XML\n\tcase MIMEPROTOBUF:\n\t\treturn ProtoBuf\n\tcase MIMEMSGPACK, MIMEMSGPACK2:\n\t\treturn MsgPack\n\tdefault: //case MIMEPOSTForm, MIMEMultipartPOSTForm:\n\t\treturn Form\n\t}\n}\n\nfunc validate(obj interface{}) error {\n\tif Validator == nil {\n\t\treturn nil\n\t}\n\treturn Validator.ValidateStruct(obj)\n}\n\n<|edits_diff|>\n--- binding/binding.go\n+++ binding/binding.go\n@@ -18,6 +18,7 @@\n \tMIMEPROTOBUF = \"application/x-protobuf\"\n \tMIMEMSGPACK = \"application/x-msgpack\"\n \tMIMEMSGPACK2 = \"application/msgpack\"\n+\tMIMEYAML = \"application/x-yaml\"\n )\n \n // Binding describes the interface which needs to be implemented for binding the\n@@ -68,6 +69,7 @@\n \tFormMultipart = formMultipartBinding{}\n \tProtoBuf = protobufBinding{}\n \tMsgPack = msgpackBinding{}\n+\tYAML = yamlBinding{}\n )\n \n // Default returns the appropriate Binding instance based on the HTTP method\n<|current_version|>\n// Copyright 2014 Manu Martinez-Almeida. All rights reserved.\n// Use of this source code is governed by a MIT style\n// license that can be found in the LICENSE file.\n\npackage binding\n\nimport \"net/http\"\n\n// Content-Type MIME of the most common data formats.\nconst (\n\tMIMEJSON = \"application/json\"\n\tMIMEHTML = \"text/html\"\n\tMIMEXML = \"application/xml\"\n\tMIMEXML2 = \"text/xml\"\n\tMIMEPlain = \"text/plain\"\n\tMIMEPOSTForm = \"application/x-www-form-urlencoded\"\n\tMIMEMultipartPOSTForm = \"multipart/form-data\"\n\tMIMEPROTOBUF = \"application/x-protobuf\"\n\tMIMEMSGPACK = \"application/x-msgpack\"\n\tMIMEMSGPACK2 = \"application/msgpack\"\n\tMIMEYAML = \"application/x-yaml\"\n)\n\n// Binding describes the interface which needs to be implemented for binding the\n// data present in the request such as JSON request body, query parameters or\n// the form POST.\ntype Binding interface {\n\tName() string\n\tBind(*http.Request, interface{}) error\n}\n\n// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,\n// but it reads the body from supplied bytes instead of req.Body.\ntype BindingBody interface {\n\tBinding\n\tBindBody([]byte, interface{}) error\n}\n\n// StructValidator is the minimal interface which needs to be implemented in\n// order for it to be used as the validator engine for ensuring the correctness\n// of the request. Gin provides a default implementation for this using\n// https://github.com/go-playground/validator/tree/v8.18.2.\ntype StructValidator interface {\n\t// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.\n\t// If the received type is not a struct, any validation should be skipped and nil must be returned.\n\t// If the received type is a struct or pointer to a struct, the validation should be performed.\n\t// If the struct is not valid or the validation itself fails, a descriptive error should be returned.\n\t// Otherwise nil must be returned.\n\tValidateStruct(interface{}) error\n\n\t// Engine returns the underlying validator engine which powers the\n\t// StructValidator implementation.\n\tEngine() interface{}\n}\n\n// Validator is the default validator which implements the StructValidator\n// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2\n// under the hood.\nvar Validator StructValidator = &defaultValidator{}\n\n// These implement the Binding interface and can be used to bind the data\n// present in the request to struct instances.\nvar (\n\tJSON = jsonBinding{}\n\tXML = xmlBinding{}\n\tForm = formBinding{}\n\tQuery = queryBinding{}\n\tFormPost = formPostBinding{}\n\tFormMultipart = formMultipartBinding{}\n\tProtoBuf = protobufBinding{}\n\tMsgPack = msgpackBinding{}\n\tYAML = yamlBinding{}\n)\n\n// Default returns the appropriate Binding instance based on the HTTP method\n// and the content type.\nfunc Default(method, contentType string) Binding {\n\tif method == \"GET\" {\n\t\treturn Form\n\t}\n\n\tswitch contentType {\n\tcase MIMEJSON:\n\t\treturn JSON\n\tcase MIMEXML, MIMEXML2:\n\t\treturn XML\n\tcase MIMEPROTOBUF:\n\t\treturn ProtoBuf\n\tcase MIMEMSGPACK, MIMEMSGPACK2:\n\t\treturn MsgPack\n\tdefault: //case MIMEPOSTForm, MIMEMultipartPOSTForm:\n\t\treturn Form\n\t}\n}\n\nfunc validate(obj interface{}) error {\n\tif Validator == nil {\n\t\treturn nil\n\t}\n\treturn Validator.ValidateStruct(obj)\n}\n\n<|next_version|>\n// Copyright 2014 Manu Martinez-Almeida. All rights reserved.\n// Use of this source code is governed by a MIT style\n// license that can be found in the LICENSE file.\n\npackage binding\n\nimport \"net/http\"\n\n// Content-Type MIME of the most common data formats.\nconst (\n\tMIMEJSON = \"application/json\"\n\tMIMEHTML = \"text/html\"\n\tMIMEXML = \"application/xml\"\n\tMIMEXML2 = \"text/xml\"\n\tMIMEPlain = \"text/plain\"\n\tMIMEPOSTForm = \"application/x-www-form-urlencoded\"\n\tMIMEMultipartPOSTForm = \"multipart/form-data\"\n\tMIMEPROTOBUF = \"application/x-protobuf\"\n\tMIMEMSGPACK = \"application/x-msgpack\"\n\tMIMEMSGPACK2 = \"application/msgpack\"\n\tMIMEYAML = \"application/x-yaml\"\n)\n\n// Binding describes the interface which needs to be implemented for binding the\n// data present in the request such as JSON request body, query parameters or\n// the form POST.\ntype Binding interface {\n\tName() string\n\tBind(*http.Request, interface{}) error\n}\n\n// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,\n// but it reads the body from supplied bytes instead of req.Body.\ntype BindingBody interface {\n\tBinding\n\tBindBody([]byte, interface{}) error\n}\n\n// StructValidator is the minimal interface which needs to be implemented in\n// order for it to be used as the validator engine for ensuring the correctness\n// of the request. Gin provides a default implementation for this using\n// https://github.com/go-playground/validator/tree/v8.18.2.\ntype StructValidator interface {\n\t// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.\n\t// If the received type is not a struct, any validation should be skipped and nil must be returned.\n\t// If the received type is a struct or pointer to a struct, the validation should be performed.\n\t// If the struct is not valid or the validation itself fails, a descriptive error should be returned.\n\t// Otherwise nil must be returned.\n\tValidateStruct(interface{}) error\n\n\t// Engine returns the underlying validator engine which powers the\n\t// StructValidator implementation.\n\tEngine() interface{}\n}\n\n// Validator is the default validator which implements the StructValidator\n// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2\n// under the hood.\nvar Validator StructValidator = &defaultValidator{}\n\n// These implement the Binding interface and can be used to bind the data\n// present in the request to struct instances.\nvar (\n\tJSON = jsonBinding{}\n\tXML = xmlBinding{}\n\tForm = formBinding{}\n\tQuery = queryBinding{}\n\tFormPost = formPostBinding{}\n\tFormMultipart = formMultipartBinding{}\n\tProtoBuf = protobufBinding{}\n\tMsgPack = msgpackBinding{}\n\tYAML = yamlBinding{}\n)\n\n// Default returns the appropriate Binding instance based on the HTTP method\n// and the content type.\nfunc Default(method, contentType string) Binding {\n\tif method == \"GET\" {\n\t\treturn Form\n\t}\n\n\tswitch contentType {\n\tcase MIMEJSON:\n\t\treturn JSON\n\tcase MIMEXML, MIMEXML2:\n\t\treturn XML\n\tcase MIMEPROTOBUF:\n\t\treturn ProtoBuf\n\tcase MIMEMSGPACK, MIMEMSGPACK2:\n\t\treturn MsgPack\n\tcase MIMEYAML:\n\t\treturn YAML\n\tdefault: //case MIMEPOSTForm, MIMEMultipartPOSTForm:\n\t\treturn Form\n\t}\n}\n\nfunc validate(obj interface{}) error {\n\tif Validator == nil {\n\t\treturn nil\n\t}\n\treturn Validator.ValidateStruct(obj)\n}\n\n", "current_contents": "// Copyright 2014 Manu Martinez-Almeida. All rights reserved.\n// Use of this source code is governed by a MIT style\n// license that can be found in the LICENSE file.\n\npackage binding\n\nimport \"net/http\"\n\n// Content-Type MIME of the most common data formats.\nconst (\n\tMIMEJSON = \"application/json\"\n\tMIMEHTML = \"text/html\"\n\tMIMEXML = \"application/xml\"\n\tMIMEXML2 = \"text/xml\"\n\tMIMEPlain = \"text/plain\"\n\tMIMEPOSTForm = \"application/x-www-form-urlencoded\"\n\tMIMEMultipartPOSTForm = \"multipart/form-data\"\n\tMIMEPROTOBUF = \"application/x-protobuf\"\n\tMIMEMSGPACK = \"application/x-msgpack\"\n\tMIMEMSGPACK2 = \"application/msgpack\"\n\tMIMEYAML = \"application/x-yaml\"\n)\n\n// Binding describes the interface which needs to be implemented for binding the\n// data present in the request such as JSON request body, query parameters or\n// the form POST.\ntype Binding interface {\n\tName() string\n\tBind(*http.Request, interface{}) error\n}\n\n// BindingBody adds BindBody method to Binding. BindBody is similar with Bind,\n// but it reads the body from supplied bytes instead of req.Body.\ntype BindingBody interface {\n\tBinding\n\tBindBody([]byte, interface{}) error\n}\n\n// StructValidator is the minimal interface which needs to be implemented in\n// order for it to be used as the validator engine for ensuring the correctness\n// of the request. Gin provides a default implementation for this using\n// https://github.com/go-playground/validator/tree/v8.18.2.\ntype StructValidator interface {\n\t// ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.\n\t// If the received type is not a struct, any validation should be skipped and nil must be returned.\n\t// If the received type is a struct or pointer to a struct, the validation should be performed.\n\t// If the struct is not valid or the validation itself fails, a descriptive error should be returned.\n\t// Otherwise nil must be returned.\n\tValidateStruct(interface{}) error\n\n\t// Engine returns the underlying validator engine which powers the\n\t// StructValidator implementation.\n\tEngine() interface{}\n}\n\n// Validator is the default validator which implements the StructValidator\n// interface. It uses https://github.com/go-playground/validator/tree/v8.18.2\n// under the hood.\nvar Validator StructValidator = &defaultValidator{}\n\n// These implement the Binding interface and can be used to bind the data\n// present in the request to struct instances.\nvar (\n\tJSON = jsonBinding{}\n\tXML = xmlBinding{}\n\tForm = formBinding{}\n\tQuery = queryBinding{}\n\tFormPost = formPostBinding{}\n\tFormMultipart = formMultipartBinding{}\n\tProtoBuf = protobufBinding{}\n\tMsgPack = msgpackBinding{}\n\tYAML = yamlBinding{}\n)\n\n// Default returns the appropriate Binding instance based on the HTTP method\n// and the content type.\nfunc Default(method, contentType string) Binding {\n\tif method == \"GET\" {\n\t\treturn Form\n\t}\n\n\tswitch contentType {\n\tcase MIMEJSON:\n\t\treturn JSON\n\tcase MIMEXML, MIMEXML2:\n\t\treturn XML\n\tcase MIMEPROTOBUF:\n\t\treturn ProtoBuf\n\tcase MIMEMSGPACK, MIMEMSGPACK2:\n\t\treturn MsgPack\n\tdefault: //case MIMEPOSTForm, MIMEMultipartPOSTForm:\n\t\treturn Form\n\t}\n}\n\nfunc validate(obj interface{}) error {\n\tif Validator == nil {\n\t\treturn nil\n\t}\n\treturn Validator.ValidateStruct(obj)\n}\n"} {"commit": "286d775de665a5c39bf00205b09a57c68a540ccd", "message": "Updates realtime-advanced", "old_file": "examples/realtime-advanced/routes.go", "new_file": "examples/realtime-advanced/routes.go", "status": "M", "old_contents": "package main\n\nimport (\n\t\"html\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc index(c *gin.Context) {\n\tc.Redirect(301, \"/room/hn\")\n}\n\nfunc roomGET(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tif len(nick) < 2 {\n\t\tnick = \"\"\n\t}\n\tif len(nick) > 13 {\n\t\tnick = nick[0:12] + \"...\"\n\t}\n\tc.HTML(200, \"room_login.templ.html\", gin.H{\n\t\t\"roomid\": roomid,\n\t\t\"nick\": nick,\n\t\t\"timestamp\": time.Now().Unix(),\n\t})\n\n}\n\nfunc roomPOST(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tmessage := c.PostFormValue(\"message\")\n\n\tvalidMessage := len(message) > 1 && len(message) < 200\n\tvalidNick := len(nick) > 1 && len(nick) < 14\n\tif !validMessage || !validNick {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"status\": \"failed\",\n\t\t\t\"error\": \"the message or nickname is too long\",\n\t\t})\n\t\treturn\n\t}\n\n\tpost := gin.H{\n\t\t\"nick\": html.EscapeString(nick),\n\t\t\"message\": html.EscapeString(message),\n\t}\n\tmessages.Add(\"inbound\", 1)\n\troom(roomid).Submit(post)\n\tc.JSON(200, post)\n}\n\nfunc streamRoom(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tlistener := openListener(roomid)\n\tticker := time.NewTicker(1 * time.Second)", "new_contents": "package main\n\nimport (\n\t\"html\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc index(c *gin.Context) {\n\tc.Redirect(301, \"/room/hn\")\n}\n\nfunc roomGET(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tif len(nick) < 2 {\n\t\tnick = \"\"\n\t}\n\tif len(nick) > 13 {\n\t\tnick = nick[0:12] + \"...\"\n\t}\n\tc.HTML(200, \"room_login.templ.html\", gin.H{\n\t\t\"roomid\": roomid,\n\t\t\"nick\": nick,\n\t\t\"timestamp\": time.Now().Unix(),\n\t})\n\n}\n\nfunc roomPOST(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tmessage := c.PostFormValue(\"message\")\n\tmessage = strings.TrimSpace(message)\n\n\tvalidMessage := len(message) > 1 && len(message) < 200\n\tvalidNick := len(nick) > 1 && len(nick) < 14\n\tif !validMessage || !validNick {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"status\": \"failed\",\n\t\t\t\"error\": \"the message or nickname is too long\",\n\t\t})\n\t\treturn\n\t}\n\n\tpost := gin.H{\n\t\t\"nick\": html.EscapeString(nick),\n\t\t\"message\": html.EscapeString(message),\n\t}\n\tmessages.Add(\"inbound\", 1)\n\troom(roomid).Submit(post)\n\tc.JSON(200, post)\n}\n\nfunc streamRoom(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tlistener := openListener(roomid)\n\tticker := time.NewTicker(1 * time.Second)", "text": "<|original_code|>\npackage main\n\nimport (\n\t\"html\"\n\t\"io\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc index(c *gin.Context) {\n\tc.Redirect(301, \"/room/hn\")\n}\n\nfunc roomGET(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tif len(nick) < 2 {\n\t\tnick = \"\"\n\t}\n\tif len(nick) > 13 {\n\t\tnick = nick[0:12] + \"...\"\n\t}\n\tc.HTML(200, \"room_login.templ.html\", gin.H{\n\t\t\"roomid\": roomid,\n\t\t\"nick\": nick,\n\t\t\"timestamp\": time.Now().Unix(),\n\t})\n\n}\n\nfunc roomPOST(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tmessage := c.PostFormValue(\"message\")\n\n\tvalidMessage := len(message) > 1 && len(message) < 200\n\tvalidNick := len(nick) > 1 && len(nick) < 14\n\tif !validMessage || !validNick {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"status\": \"failed\",\n\t\t\t\"error\": \"the message or nickname is too long\",\n\t\t})\n\t\treturn\n\t}\n\n\tpost := gin.H{\n\t\t\"nick\": html.EscapeString(nick),\n\t\t\"message\": html.EscapeString(message),\n\t}\n\tmessages.Add(\"inbound\", 1)\n\troom(roomid).Submit(post)\n\tc.JSON(200, post)\n}\n\nfunc streamRoom(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tlistener := openListener(roomid)\n\tticker := time.NewTicker(1 * time.Second)\n<|edits_diff|>\n--- examples/realtime-advanced/routes.go\n+++ examples/realtime-advanced/routes.go\n@@ -3,6 +3,7 @@\n import (\n \t\"html\"\n \t\"io\"\n+\t\"strings\"\n \t\"time\"\n \n \t\"github.com/gin-gonic/gin\"\n<|current_version|>\npackage main\n\nimport (\n\t\"html\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc index(c *gin.Context) {\n\tc.Redirect(301, \"/room/hn\")\n}\n\nfunc roomGET(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tif len(nick) < 2 {\n\t\tnick = \"\"\n\t}\n\tif len(nick) > 13 {\n\t\tnick = nick[0:12] + \"...\"\n\t}\n\tc.HTML(200, \"room_login.templ.html\", gin.H{\n\t\t\"roomid\": roomid,\n\t\t\"nick\": nick,\n\t\t\"timestamp\": time.Now().Unix(),\n\t})\n\n}\n\nfunc roomPOST(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tmessage := c.PostFormValue(\"message\")\n\n\tvalidMessage := len(message) > 1 && len(message) < 200\n\tvalidNick := len(nick) > 1 && len(nick) < 14\n\tif !validMessage || !validNick {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"status\": \"failed\",\n\t\t\t\"error\": \"the message or nickname is too long\",\n\t\t})\n\t\treturn\n\t}\n\n\tpost := gin.H{\n\t\t\"nick\": html.EscapeString(nick),\n\t\t\"message\": html.EscapeString(message),\n\t}\n\tmessages.Add(\"inbound\", 1)\n\troom(roomid).Submit(post)\n\tc.JSON(200, post)\n}\n\nfunc streamRoom(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tlistener := openListener(roomid)\n\tticker := time.NewTicker(1 * time.Second)\n<|next_version|>\npackage main\n\nimport (\n\t\"html\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc index(c *gin.Context) {\n\tc.Redirect(301, \"/room/hn\")\n}\n\nfunc roomGET(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tif len(nick) < 2 {\n\t\tnick = \"\"\n\t}\n\tif len(nick) > 13 {\n\t\tnick = nick[0:12] + \"...\"\n\t}\n\tc.HTML(200, \"room_login.templ.html\", gin.H{\n\t\t\"roomid\": roomid,\n\t\t\"nick\": nick,\n\t\t\"timestamp\": time.Now().Unix(),\n\t})\n\n}\n\nfunc roomPOST(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tmessage := c.PostFormValue(\"message\")\n\tmessage = strings.TrimSpace(message)\n\n\tvalidMessage := len(message) > 1 && len(message) < 200\n\tvalidNick := len(nick) > 1 && len(nick) < 14\n\tif !validMessage || !validNick {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"status\": \"failed\",\n\t\t\t\"error\": \"the message or nickname is too long\",\n\t\t})\n\t\treturn\n\t}\n\n\tpost := gin.H{\n\t\t\"nick\": html.EscapeString(nick),\n\t\t\"message\": html.EscapeString(message),\n\t}\n\tmessages.Add(\"inbound\", 1)\n\troom(roomid).Submit(post)\n\tc.JSON(200, post)\n}\n\nfunc streamRoom(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tlistener := openListener(roomid)\n\tticker := time.NewTicker(1 * time.Second)\n", "current_contents": "package main\n\nimport (\n\t\"html\"\n\t\"io\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc index(c *gin.Context) {\n\tc.Redirect(301, \"/room/hn\")\n}\n\nfunc roomGET(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tif len(nick) < 2 {\n\t\tnick = \"\"\n\t}\n\tif len(nick) > 13 {\n\t\tnick = nick[0:12] + \"...\"\n\t}\n\tc.HTML(200, \"room_login.templ.html\", gin.H{\n\t\t\"roomid\": roomid,\n\t\t\"nick\": nick,\n\t\t\"timestamp\": time.Now().Unix(),\n\t})\n\n}\n\nfunc roomPOST(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tnick := c.FormValue(\"nick\")\n\tmessage := c.PostFormValue(\"message\")\n\n\tvalidMessage := len(message) > 1 && len(message) < 200\n\tvalidNick := len(nick) > 1 && len(nick) < 14\n\tif !validMessage || !validNick {\n\t\tc.JSON(400, gin.H{\n\t\t\t\"status\": \"failed\",\n\t\t\t\"error\": \"the message or nickname is too long\",\n\t\t})\n\t\treturn\n\t}\n\n\tpost := gin.H{\n\t\t\"nick\": html.EscapeString(nick),\n\t\t\"message\": html.EscapeString(message),\n\t}\n\tmessages.Add(\"inbound\", 1)\n\troom(roomid).Submit(post)\n\tc.JSON(200, post)\n}\n\nfunc streamRoom(c *gin.Context) {\n\troomid := c.ParamValue(\"roomid\")\n\tlistener := openListener(roomid)\n\tticker := time.NewTicker(1 * time.Second)"} {"commit": "f212ae77289674a64f725bf650841e14b8f98613", "message": "Updates tree.go + fixes + unit tests", "old_file": "gin.go", "new_file": "gin.go", "status": "M", "old_contents": "\t\t}\n\t}\n\tcontext.handlers = engine.allNoRoute\n\tserveError(context, 404, default404Body)\n}\n\nfunc (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {\n\treq := c.Request\n\tpath := req.URL.Path\n\tcode := 301 // Permanent redirect, request with GET method\n\tif req.Method != \"GET\" {\n\t\tcode = 307\n\t}\n\n\tif tsr && engine.RedirectTrailingSlash {\n\t\tif len(path) > 1 && path[len(path)-1] == '/' {\n\t\t\treq.URL.Path = path[:len(path)-1]\n\t\t} else {\n\t\t\treq.URL.Path = path + \"/\"\n\t\t}\n\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\treturn true\n\t}\n\n\t// Try to fix the request path\n\tif engine.RedirectFixedPath {\n\t\tfixedPath, found := root.findCaseInsensitivePath(\n\t\t\tCleanPath(path),\n\t\t\tengine.RedirectTrailingSlash,\n\t\t)\n\t\tif found {\n\t\t\treq.URL.Path = string(fixedPath)\n\t\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc serveError(c *Context, code int, defaultMessage []byte) {\n\tc.writermem.status = code\n\tc.Next()\n\tif !c.Writer.Written() {\n\t\tif c.Writer.Status() == code {\n\t\t\tc.Data(-1, binding.MIMEPlain, defaultMessage)\n\t\t} else {\n\t\t\tc.Writer.WriteHeaderNow()\n\t\t}\n\t}\n}\n", "new_contents": "\t\t}\n\t}\n\tcontext.handlers = engine.allNoRoute\n\tserveError(context, 404, default404Body)\n}\n\nfunc (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {\n\treq := c.Request\n\tpath := req.URL.Path\n\tcode := 301 // Permanent redirect, request with GET method\n\tif req.Method != \"GET\" {\n\t\tcode = 307\n\t}\n\n\tif tsr && engine.RedirectTrailingSlash {\n\t\tif len(path) > 1 && path[len(path)-1] == '/' {\n\t\t\treq.URL.Path = path[:len(path)-1]\n\t\t} else {\n\t\t\treq.URL.Path = path + \"/\"\n\t\t}\n\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\tc.writermem.WriteHeaderNow()\n\t\treturn true\n\t}\n\n\t// Try to fix the request path\n\tif engine.RedirectFixedPath {\n\t\tfixedPath, found := root.findCaseInsensitivePath(\n\t\t\tCleanPath(path),\n\t\t\tengine.RedirectTrailingSlash,\n\t\t)\n\t\tif found {\n\t\t\treq.URL.Path = string(fixedPath)\n\t\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\t\tc.writermem.WriteHeaderNow()\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc serveError(c *Context, code int, defaultMessage []byte) {\n\tc.writermem.status = code\n\tc.Next()\n\tif !c.Writer.Written() {\n\t\tif c.Writer.Status() == code {\n\t\t\tc.Data(-1, binding.MIMEPlain, defaultMessage)\n\t\t} else {\n\t\t\tc.Writer.WriteHeaderNow()\n\t\t}\n\t}\n}\n", "text": "<|original_code|>\n\t\t}\n\t}\n\tcontext.handlers = engine.allNoRoute\n\tserveError(context, 404, default404Body)\n}\n\nfunc (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {\n\treq := c.Request\n\tpath := req.URL.Path\n\tcode := 301 // Permanent redirect, request with GET method\n\tif req.Method != \"GET\" {\n\t\tcode = 307\n\t}\n\n\tif tsr && engine.RedirectTrailingSlash {\n\t\tif len(path) > 1 && path[len(path)-1] == '/' {\n\t\t\treq.URL.Path = path[:len(path)-1]\n\t\t} else {\n\t\t\treq.URL.Path = path + \"/\"\n\t\t}\n\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\treturn true\n\t}\n\n\t// Try to fix the request path\n\tif engine.RedirectFixedPath {\n\t\tfixedPath, found := root.findCaseInsensitivePath(\n\t\t\tCleanPath(path),\n\t\t\tengine.RedirectTrailingSlash,\n\t\t)\n\t\tif found {\n\t\t\treq.URL.Path = string(fixedPath)\n\t\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc serveError(c *Context, code int, defaultMessage []byte) {\n\tc.writermem.status = code\n\tc.Next()\n\tif !c.Writer.Written() {\n\t\tif c.Writer.Status() == code {\n\t\t\tc.Data(-1, binding.MIMEPlain, defaultMessage)\n\t\t} else {\n\t\t\tc.Writer.WriteHeaderNow()\n\t\t}\n\t}\n}\n\n<|edits_diff|>\n--- gin.go\n+++ gin.go\n@@ -20,6 +20,7 @@\n \t\t}\n \t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n \t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n+\t\tc.writermem.WriteHeaderNow()\n \t\treturn true\n \t}\n \n<|current_version|>\n\t\t}\n\t}\n\tcontext.handlers = engine.allNoRoute\n\tserveError(context, 404, default404Body)\n}\n\nfunc (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {\n\treq := c.Request\n\tpath := req.URL.Path\n\tcode := 301 // Permanent redirect, request with GET method\n\tif req.Method != \"GET\" {\n\t\tcode = 307\n\t}\n\n\tif tsr && engine.RedirectTrailingSlash {\n\t\tif len(path) > 1 && path[len(path)-1] == '/' {\n\t\t\treq.URL.Path = path[:len(path)-1]\n\t\t} else {\n\t\t\treq.URL.Path = path + \"/\"\n\t\t}\n\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\tc.writermem.WriteHeaderNow()\n\t\treturn true\n\t}\n\n\t// Try to fix the request path\n\tif engine.RedirectFixedPath {\n\t\tfixedPath, found := root.findCaseInsensitivePath(\n\t\t\tCleanPath(path),\n\t\t\tengine.RedirectTrailingSlash,\n\t\t)\n\t\tif found {\n\t\t\treq.URL.Path = string(fixedPath)\n\t\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc serveError(c *Context, code int, defaultMessage []byte) {\n\tc.writermem.status = code\n\tc.Next()\n\tif !c.Writer.Written() {\n\t\tif c.Writer.Status() == code {\n\t\t\tc.Data(-1, binding.MIMEPlain, defaultMessage)\n\t\t} else {\n\t\t\tc.Writer.WriteHeaderNow()\n\t\t}\n\t}\n}\n\n<|next_version|>\n\t\t}\n\t}\n\tcontext.handlers = engine.allNoRoute\n\tserveError(context, 404, default404Body)\n}\n\nfunc (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {\n\treq := c.Request\n\tpath := req.URL.Path\n\tcode := 301 // Permanent redirect, request with GET method\n\tif req.Method != \"GET\" {\n\t\tcode = 307\n\t}\n\n\tif tsr && engine.RedirectTrailingSlash {\n\t\tif len(path) > 1 && path[len(path)-1] == '/' {\n\t\t\treq.URL.Path = path[:len(path)-1]\n\t\t} else {\n\t\t\treq.URL.Path = path + \"/\"\n\t\t}\n\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\tc.writermem.WriteHeaderNow()\n\t\treturn true\n\t}\n\n\t// Try to fix the request path\n\tif engine.RedirectFixedPath {\n\t\tfixedPath, found := root.findCaseInsensitivePath(\n\t\t\tCleanPath(path),\n\t\t\tengine.RedirectTrailingSlash,\n\t\t)\n\t\tif found {\n\t\t\treq.URL.Path = string(fixedPath)\n\t\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\t\tc.writermem.WriteHeaderNow()\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc serveError(c *Context, code int, defaultMessage []byte) {\n\tc.writermem.status = code\n\tc.Next()\n\tif !c.Writer.Written() {\n\t\tif c.Writer.Status() == code {\n\t\t\tc.Data(-1, binding.MIMEPlain, defaultMessage)\n\t\t} else {\n\t\t\tc.Writer.WriteHeaderNow()\n\t\t}\n\t}\n}\n\n", "current_contents": "\t\t}\n\t}\n\tcontext.handlers = engine.allNoRoute\n\tserveError(context, 404, default404Body)\n}\n\nfunc (engine *Engine) serveAutoRedirect(c *Context, root *node, tsr bool) bool {\n\treq := c.Request\n\tpath := req.URL.Path\n\tcode := 301 // Permanent redirect, request with GET method\n\tif req.Method != \"GET\" {\n\t\tcode = 307\n\t}\n\n\tif tsr && engine.RedirectTrailingSlash {\n\t\tif len(path) > 1 && path[len(path)-1] == '/' {\n\t\t\treq.URL.Path = path[:len(path)-1]\n\t\t} else {\n\t\t\treq.URL.Path = path + \"/\"\n\t\t}\n\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\tc.writermem.WriteHeaderNow()\n\t\treturn true\n\t}\n\n\t// Try to fix the request path\n\tif engine.RedirectFixedPath {\n\t\tfixedPath, found := root.findCaseInsensitivePath(\n\t\t\tCleanPath(path),\n\t\t\tengine.RedirectTrailingSlash,\n\t\t)\n\t\tif found {\n\t\t\treq.URL.Path = string(fixedPath)\n\t\t\tdebugPrint(\"redirecting request %d: %s --> %s\", code, path, req.URL.String())\n\t\t\thttp.Redirect(c.Writer, req, req.URL.String(), code)\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc serveError(c *Context, code int, defaultMessage []byte) {\n\tc.writermem.status = code\n\tc.Next()\n\tif !c.Writer.Written() {\n\t\tif c.Writer.Status() == code {\n\t\t\tc.Data(-1, binding.MIMEPlain, defaultMessage)\n\t\t} else {\n\t\t\tc.Writer.WriteHeaderNow()\n\t\t}\n\t}\n}\n"} {"commit": "97ae4a6b654f7ce2a2b77b3905ffe16f0b6b2652", "message": "Fix for #119. gin.LoadHTML* incorrectly works in debug mode.", "old_file": "gin.go", "new_file": "gin.go", "status": "M", "old_contents": "func New() *Engine {\n\tengine := &Engine{}\n\tengine.RouterGroup = &RouterGroup{nil, \"/\", nil, engine}\n\tengine.router = httprouter.New()\n\tengine.router.NotFound = engine.handle404\n\tengine.cache.New = func() interface{} {\n\t\tc := &Context{Engine: engine}\n\t\tc.Writer = &c.writermem\n\t\treturn c\n\t}\n\treturn engine\n}\n\n// Returns a Engine instance with the Logger and Recovery already attached.\nfunc Default() *Engine {\n\tengine := New()\n\tengine.Use(Recovery(), Logger())\n\treturn engine\n}\n\nfunc (engine *Engine) LoadHTMLGlob(pattern string) {\n\tif gin_mode == debugCode {\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseGlob(pattern))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) LoadHTMLFiles(files ...string) {\n\tif gin_mode == debugCode {\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseFiles(files...))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) SetHTMLTemplate(templ *template.Template) {\n\tengine.HTMLRender = render.HTMLRender{\n\t\tTemplate: templ,\n\t}\n}\n\n// Adds handlers for NoRoute. It return a 404 code by default.\nfunc (engine *Engine) NoRoute(handlers ...HandlerFunc) {\n\tengine.noRoute = handlers\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\nfunc (engine *Engine) Use(middlewares ...HandlerFunc) {\n\tengine.RouterGroup.Use(middlewares...)\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n", "new_contents": "func New() *Engine {\n\tengine := &Engine{}\n\tengine.RouterGroup = &RouterGroup{nil, \"/\", nil, engine}\n\tengine.router = httprouter.New()\n\tengine.router.NotFound = engine.handle404\n\tengine.cache.New = func() interface{} {\n\t\tc := &Context{Engine: engine}\n\t\tc.Writer = &c.writermem\n\t\treturn c\n\t}\n\treturn engine\n}\n\n// Returns a Engine instance with the Logger and Recovery already attached.\nfunc Default() *Engine {\n\tengine := New()\n\tengine.Use(Recovery(), Logger())\n\treturn engine\n}\n\nfunc (engine *Engine) LoadHTMLGlob(pattern string) {\n\tif gin_mode == debugCode {\n\t\trender.HTMLDebug.AddGlob(pattern)\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseGlob(pattern))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) LoadHTMLFiles(files ...string) {\n\tif gin_mode == debugCode {\n\t\trender.HTMLDebug.AddFiles(files...)\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseFiles(files...))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) SetHTMLTemplate(templ *template.Template) {\n\tengine.HTMLRender = render.HTMLRender{\n\t\tTemplate: templ,\n\t}\n}\n\n// Adds handlers for NoRoute. It return a 404 code by default.\nfunc (engine *Engine) NoRoute(handlers ...HandlerFunc) {\n\tengine.noRoute = handlers\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\nfunc (engine *Engine) Use(middlewares ...HandlerFunc) {\n\tengine.RouterGroup.Use(middlewares...)\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n", "text": "<|original_code|>\nfunc New() *Engine {\n\tengine := &Engine{}\n\tengine.RouterGroup = &RouterGroup{nil, \"/\", nil, engine}\n\tengine.router = httprouter.New()\n\tengine.router.NotFound = engine.handle404\n\tengine.cache.New = func() interface{} {\n\t\tc := &Context{Engine: engine}\n\t\tc.Writer = &c.writermem\n\t\treturn c\n\t}\n\treturn engine\n}\n\n// Returns a Engine instance with the Logger and Recovery already attached.\nfunc Default() *Engine {\n\tengine := New()\n\tengine.Use(Recovery(), Logger())\n\treturn engine\n}\n\nfunc (engine *Engine) LoadHTMLGlob(pattern string) {\n\tif gin_mode == debugCode {\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseGlob(pattern))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) LoadHTMLFiles(files ...string) {\n\tif gin_mode == debugCode {\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseFiles(files...))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) SetHTMLTemplate(templ *template.Template) {\n\tengine.HTMLRender = render.HTMLRender{\n\t\tTemplate: templ,\n\t}\n}\n\n// Adds handlers for NoRoute. It return a 404 code by default.\nfunc (engine *Engine) NoRoute(handlers ...HandlerFunc) {\n\tengine.noRoute = handlers\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\nfunc (engine *Engine) Use(middlewares ...HandlerFunc) {\n\tengine.RouterGroup.Use(middlewares...)\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\n<|edits_diff|>\n--- gin.go\n+++ gin.go\n@@ -20,6 +20,7 @@\n \n func (engine *Engine) LoadHTMLGlob(pattern string) {\n \tif gin_mode == debugCode {\n+\t\trender.HTMLDebug.AddGlob(pattern)\n \t\tengine.HTMLRender = render.HTMLDebug\n \t} else {\n \t\ttempl := template.Must(template.ParseGlob(pattern))\n<|current_version|>\nfunc New() *Engine {\n\tengine := &Engine{}\n\tengine.RouterGroup = &RouterGroup{nil, \"/\", nil, engine}\n\tengine.router = httprouter.New()\n\tengine.router.NotFound = engine.handle404\n\tengine.cache.New = func() interface{} {\n\t\tc := &Context{Engine: engine}\n\t\tc.Writer = &c.writermem\n\t\treturn c\n\t}\n\treturn engine\n}\n\n// Returns a Engine instance with the Logger and Recovery already attached.\nfunc Default() *Engine {\n\tengine := New()\n\tengine.Use(Recovery(), Logger())\n\treturn engine\n}\n\nfunc (engine *Engine) LoadHTMLGlob(pattern string) {\n\tif gin_mode == debugCode {\n\t\trender.HTMLDebug.AddGlob(pattern)\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseGlob(pattern))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) LoadHTMLFiles(files ...string) {\n\tif gin_mode == debugCode {\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseFiles(files...))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) SetHTMLTemplate(templ *template.Template) {\n\tengine.HTMLRender = render.HTMLRender{\n\t\tTemplate: templ,\n\t}\n}\n\n// Adds handlers for NoRoute. It return a 404 code by default.\nfunc (engine *Engine) NoRoute(handlers ...HandlerFunc) {\n\tengine.noRoute = handlers\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\nfunc (engine *Engine) Use(middlewares ...HandlerFunc) {\n\tengine.RouterGroup.Use(middlewares...)\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\n<|next_version|>\nfunc New() *Engine {\n\tengine := &Engine{}\n\tengine.RouterGroup = &RouterGroup{nil, \"/\", nil, engine}\n\tengine.router = httprouter.New()\n\tengine.router.NotFound = engine.handle404\n\tengine.cache.New = func() interface{} {\n\t\tc := &Context{Engine: engine}\n\t\tc.Writer = &c.writermem\n\t\treturn c\n\t}\n\treturn engine\n}\n\n// Returns a Engine instance with the Logger and Recovery already attached.\nfunc Default() *Engine {\n\tengine := New()\n\tengine.Use(Recovery(), Logger())\n\treturn engine\n}\n\nfunc (engine *Engine) LoadHTMLGlob(pattern string) {\n\tif gin_mode == debugCode {\n\t\trender.HTMLDebug.AddGlob(pattern)\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseGlob(pattern))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) LoadHTMLFiles(files ...string) {\n\tif gin_mode == debugCode {\n\t\trender.HTMLDebug.AddFiles(files...)\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseFiles(files...))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) SetHTMLTemplate(templ *template.Template) {\n\tengine.HTMLRender = render.HTMLRender{\n\t\tTemplate: templ,\n\t}\n}\n\n// Adds handlers for NoRoute. It return a 404 code by default.\nfunc (engine *Engine) NoRoute(handlers ...HandlerFunc) {\n\tengine.noRoute = handlers\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\nfunc (engine *Engine) Use(middlewares ...HandlerFunc) {\n\tengine.RouterGroup.Use(middlewares...)\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\n", "current_contents": "func New() *Engine {\n\tengine := &Engine{}\n\tengine.RouterGroup = &RouterGroup{nil, \"/\", nil, engine}\n\tengine.router = httprouter.New()\n\tengine.router.NotFound = engine.handle404\n\tengine.cache.New = func() interface{} {\n\t\tc := &Context{Engine: engine}\n\t\tc.Writer = &c.writermem\n\t\treturn c\n\t}\n\treturn engine\n}\n\n// Returns a Engine instance with the Logger and Recovery already attached.\nfunc Default() *Engine {\n\tengine := New()\n\tengine.Use(Recovery(), Logger())\n\treturn engine\n}\n\nfunc (engine *Engine) LoadHTMLGlob(pattern string) {\n\tif gin_mode == debugCode {\n\t\trender.HTMLDebug.AddGlob(pattern)\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseGlob(pattern))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) LoadHTMLFiles(files ...string) {\n\tif gin_mode == debugCode {\n\t\tengine.HTMLRender = render.HTMLDebug\n\t} else {\n\t\ttempl := template.Must(template.ParseFiles(files...))\n\t\tengine.SetHTMLTemplate(templ)\n\t}\n}\n\nfunc (engine *Engine) SetHTMLTemplate(templ *template.Template) {\n\tengine.HTMLRender = render.HTMLRender{\n\t\tTemplate: templ,\n\t}\n}\n\n// Adds handlers for NoRoute. It return a 404 code by default.\nfunc (engine *Engine) NoRoute(handlers ...HandlerFunc) {\n\tengine.noRoute = handlers\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n\nfunc (engine *Engine) Use(middlewares ...HandlerFunc) {\n\tengine.RouterGroup.Use(middlewares...)\n\tengine.finalNoRoute = engine.combineHandlers(engine.noRoute)\n}\n"} {"commit": "0ed259ca34d5af4e91a9820dd1923b89f6bb58d5", "message": "Adds TestMode", "old_file": "mode.go", "new_file": "mode.go", "status": "M", "old_contents": "package gin\n\nimport (\n\t\"os\"\n)\n\nconst GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode string = \"debug\"\n\tReleaseMode string = \"release\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode = iota\n)\n\nvar gin_mode int = debugCode\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tgin_mode = debugCode\n\tcase ReleaseMode:\n\t\tgin_mode = releaseCode\n\tdefault:\n\t\tpanic(\"gin mode unknown, the allowed modes are: \" + DebugMode + \" and \" + ReleaseMode)\n\t}\n}\n\nfunc init() {\n\tvalue := os.Getenv(GIN_MODE)\n\tif len(value) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(value)\n\t}\n}\n", "new_contents": "package gin\n\nimport (\n\t\"os\"\n)\n\nconst GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode string = \"debug\"\n\tReleaseMode string = \"release\"\n\tTestMode string = \"test\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode = iota\n\ttestCode = iota\n)\n\nvar gin_mode int = debugCode\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tgin_mode = debugCode\n\tcase ReleaseMode:\n\t\tgin_mode = releaseCode\n\tcase TestMode:\n\t\tgin_mode = testCode\n\tdefault:\n\t\tpanic(\"gin mode unknown, the allowed modes are: \" + DebugMode + \" and \" + ReleaseMode)\n\t}\n}\n\nfunc init() {\n\tvalue := os.Getenv(GIN_MODE)\n\tif len(value) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(value)\n\t}\n}\n", "text": "<|original_code|>\npackage gin\n\nimport (\n\t\"os\"\n)\n\nconst GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode string = \"debug\"\n\tReleaseMode string = \"release\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode = iota\n)\n\nvar gin_mode int = debugCode\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tgin_mode = debugCode\n\tcase ReleaseMode:\n\t\tgin_mode = releaseCode\n\tdefault:\n\t\tpanic(\"gin mode unknown, the allowed modes are: \" + DebugMode + \" and \" + ReleaseMode)\n\t}\n}\n\nfunc init() {\n\tvalue := os.Getenv(GIN_MODE)\n\tif len(value) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(value)\n\t}\n}\n\n<|edits_diff|>\n--- mode.go\n+++ mode.go\n@@ -9,10 +9,12 @@\n const (\n \tDebugMode string = \"debug\"\n \tReleaseMode string = \"release\"\n+\tTestMode string = \"test\"\n )\n const (\n \tdebugCode = iota\n \treleaseCode = iota\n+\ttestCode = iota\n )\n \n var gin_mode int = debugCode\n<|current_version|>\npackage gin\n\nimport (\n\t\"os\"\n)\n\nconst GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode string = \"debug\"\n\tReleaseMode string = \"release\"\n\tTestMode string = \"test\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode = iota\n\ttestCode = iota\n)\n\nvar gin_mode int = debugCode\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tgin_mode = debugCode\n\tcase ReleaseMode:\n\t\tgin_mode = releaseCode\n\tdefault:\n\t\tpanic(\"gin mode unknown, the allowed modes are: \" + DebugMode + \" and \" + ReleaseMode)\n\t}\n}\n\nfunc init() {\n\tvalue := os.Getenv(GIN_MODE)\n\tif len(value) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(value)\n\t}\n}\n\n<|next_version|>\npackage gin\n\nimport (\n\t\"os\"\n)\n\nconst GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode string = \"debug\"\n\tReleaseMode string = \"release\"\n\tTestMode string = \"test\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode = iota\n\ttestCode = iota\n)\n\nvar gin_mode int = debugCode\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tgin_mode = debugCode\n\tcase ReleaseMode:\n\t\tgin_mode = releaseCode\n\tcase TestMode:\n\t\tgin_mode = testCode\n\tdefault:\n\t\tpanic(\"gin mode unknown, the allowed modes are: \" + DebugMode + \" and \" + ReleaseMode)\n\t}\n}\n\nfunc init() {\n\tvalue := os.Getenv(GIN_MODE)\n\tif len(value) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(value)\n\t}\n}\n\n", "current_contents": "package gin\n\nimport (\n\t\"os\"\n)\n\nconst GIN_MODE = \"GIN_MODE\"\n\nconst (\n\tDebugMode string = \"debug\"\n\tReleaseMode string = \"release\"\n\tTestMode string = \"test\"\n)\nconst (\n\tdebugCode = iota\n\treleaseCode = iota\n\ttestCode = iota\n)\n\nvar gin_mode int = debugCode\n\nfunc SetMode(value string) {\n\tswitch value {\n\tcase DebugMode:\n\t\tgin_mode = debugCode\n\tcase ReleaseMode:\n\t\tgin_mode = releaseCode\n\tdefault:\n\t\tpanic(\"gin mode unknown, the allowed modes are: \" + DebugMode + \" and \" + ReleaseMode)\n\t}\n}\n\nfunc init() {\n\tvalue := os.Getenv(GIN_MODE)\n\tif len(value) == 0 {\n\t\tSetMode(DebugMode)\n\t} else {\n\t\tSetMode(value)\n\t}\n}\n"} {"commit": "cba163a1fdf2c2ad24b27683ed44b90d945ba764", "message": "chore: enable TLS client cache for HTTPS where appropriate (#9721)", "old_file": "lib/discover/global.go", "new_file": "lib/discover/global.go", "status": "M", "old_contents": "\t\t}\n\t}\n\n\t// The http.Client used for announcements. It needs to have our\n\t// certificate to prove our identity, and may or may not verify the server\n\t// certificate depending on the insecure setting.\n\tvar dialContext func(ctx context.Context, network, addr string) (net.Conn, error)\n\tif registry != nil {\n\t\tdialContext = dialer.DialContextReusePortFunc(registry)\n\t} else {\n\t\tdialContext = dialer.DialContext\n\t}\n\tvar announceClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDisableKeepAlives: true, // announcements are few and far between, so don't keep the connection open\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tCertificates: []tls.Certificate{cert},\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tannounceClient = newIDCheckingHTTPClient(announceClient, devID)\n\t}\n\n\t// The http.Client used for queries. We don't need to present our\n\t// certificate here, so lets not include it. May be insecure if requested.\n\tvar queryClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialer.DialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tIdleConnTimeout: time.Second,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tqueryClient = newIDCheckingHTTPClient(queryClient, devID)\n\t}\n\n\tcl := &globalClient{\n\t\tserver: server,\n\t\taddrList: addrList,\n\t\tannounceClient: announceClient,\n\t\tqueryClient: queryClient,\n\t\tnoAnnounce: opts.noAnnounce,\n\t\tnoLookup: opts.noLookup,\n\t\tevLogger: evLogger,\n\t}\n\tif !opts.noAnnounce {\n\t\t// If we are supposed to announce, it's an error until we've done so.\n\t\tcl.setError(errors.New(\"not announced\"))\n\t}\n\n\treturn cl, nil\n}\n", "new_contents": "\t\t}\n\t}\n\n\t// The http.Client used for announcements. It needs to have our\n\t// certificate to prove our identity, and may or may not verify the server\n\t// certificate depending on the insecure setting.\n\tvar dialContext func(ctx context.Context, network, addr string) (net.Conn, error)\n\tif registry != nil {\n\t\tdialContext = dialer.DialContextReusePortFunc(registry)\n\t} else {\n\t\tdialContext = dialer.DialContext\n\t}\n\tvar announceClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDisableKeepAlives: true, // announcements are few and far between, so don't keep the connection open\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tCertificates: []tls.Certificate{cert},\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t\tClientSessionCache: tls.NewLRUClientSessionCache(0),\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tannounceClient = newIDCheckingHTTPClient(announceClient, devID)\n\t}\n\n\t// The http.Client used for queries. We don't need to present our\n\t// certificate here, so lets not include it. May be insecure if requested.\n\tvar queryClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialer.DialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tIdleConnTimeout: time.Second,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t\tClientSessionCache: tls.NewLRUClientSessionCache(0),\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tqueryClient = newIDCheckingHTTPClient(queryClient, devID)\n\t}\n\n\tcl := &globalClient{\n\t\tserver: server,\n\t\taddrList: addrList,\n\t\tannounceClient: announceClient,\n\t\tqueryClient: queryClient,\n\t\tnoAnnounce: opts.noAnnounce,\n\t\tnoLookup: opts.noLookup,\n\t\tevLogger: evLogger,\n\t}\n\tif !opts.noAnnounce {\n\t\t// If we are supposed to announce, it's an error until we've done so.\n\t\tcl.setError(errors.New(\"not announced\"))\n\t}\n\n\treturn cl, nil\n}\n", "text": "<|original_code|>\n\t\t}\n\t}\n\n\t// The http.Client used for announcements. It needs to have our\n\t// certificate to prove our identity, and may or may not verify the server\n\t// certificate depending on the insecure setting.\n\tvar dialContext func(ctx context.Context, network, addr string) (net.Conn, error)\n\tif registry != nil {\n\t\tdialContext = dialer.DialContextReusePortFunc(registry)\n\t} else {\n\t\tdialContext = dialer.DialContext\n\t}\n\tvar announceClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDisableKeepAlives: true, // announcements are few and far between, so don't keep the connection open\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tCertificates: []tls.Certificate{cert},\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tannounceClient = newIDCheckingHTTPClient(announceClient, devID)\n\t}\n\n\t// The http.Client used for queries. We don't need to present our\n\t// certificate here, so lets not include it. May be insecure if requested.\n\tvar queryClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialer.DialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tIdleConnTimeout: time.Second,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tqueryClient = newIDCheckingHTTPClient(queryClient, devID)\n\t}\n\n\tcl := &globalClient{\n\t\tserver: server,\n\t\taddrList: addrList,\n\t\tannounceClient: announceClient,\n\t\tqueryClient: queryClient,\n\t\tnoAnnounce: opts.noAnnounce,\n\t\tnoLookup: opts.noLookup,\n\t\tevLogger: evLogger,\n\t}\n\tif !opts.noAnnounce {\n\t\t// If we are supposed to announce, it's an error until we've done so.\n\t\tcl.setError(errors.New(\"not announced\"))\n\t}\n\n\treturn cl, nil\n}\n\n<|edits_diff|>\n--- lib/discover/global.go\n+++ lib/discover/global.go\n@@ -20,6 +20,7 @@\n \t\t\t\tInsecureSkipVerify: opts.insecure,\n \t\t\t\tCertificates: []tls.Certificate{cert},\n \t\t\t\tMinVersion: tls.VersionTLS12,\n+\t\t\t\tClientSessionCache: tls.NewLRUClientSessionCache(0),\n \t\t\t},\n \t\t}),\n \t}}\n<|current_version|>\n\t\t}\n\t}\n\n\t// The http.Client used for announcements. It needs to have our\n\t// certificate to prove our identity, and may or may not verify the server\n\t// certificate depending on the insecure setting.\n\tvar dialContext func(ctx context.Context, network, addr string) (net.Conn, error)\n\tif registry != nil {\n\t\tdialContext = dialer.DialContextReusePortFunc(registry)\n\t} else {\n\t\tdialContext = dialer.DialContext\n\t}\n\tvar announceClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDisableKeepAlives: true, // announcements are few and far between, so don't keep the connection open\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tCertificates: []tls.Certificate{cert},\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t\tClientSessionCache: tls.NewLRUClientSessionCache(0),\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tannounceClient = newIDCheckingHTTPClient(announceClient, devID)\n\t}\n\n\t// The http.Client used for queries. We don't need to present our\n\t// certificate here, so lets not include it. May be insecure if requested.\n\tvar queryClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialer.DialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tIdleConnTimeout: time.Second,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tqueryClient = newIDCheckingHTTPClient(queryClient, devID)\n\t}\n\n\tcl := &globalClient{\n\t\tserver: server,\n\t\taddrList: addrList,\n\t\tannounceClient: announceClient,\n\t\tqueryClient: queryClient,\n\t\tnoAnnounce: opts.noAnnounce,\n\t\tnoLookup: opts.noLookup,\n\t\tevLogger: evLogger,\n\t}\n\tif !opts.noAnnounce {\n\t\t// If we are supposed to announce, it's an error until we've done so.\n\t\tcl.setError(errors.New(\"not announced\"))\n\t}\n\n\treturn cl, nil\n}\n\n<|next_version|>\n\t\t}\n\t}\n\n\t// The http.Client used for announcements. It needs to have our\n\t// certificate to prove our identity, and may or may not verify the server\n\t// certificate depending on the insecure setting.\n\tvar dialContext func(ctx context.Context, network, addr string) (net.Conn, error)\n\tif registry != nil {\n\t\tdialContext = dialer.DialContextReusePortFunc(registry)\n\t} else {\n\t\tdialContext = dialer.DialContext\n\t}\n\tvar announceClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDisableKeepAlives: true, // announcements are few and far between, so don't keep the connection open\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tCertificates: []tls.Certificate{cert},\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t\tClientSessionCache: tls.NewLRUClientSessionCache(0),\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tannounceClient = newIDCheckingHTTPClient(announceClient, devID)\n\t}\n\n\t// The http.Client used for queries. We don't need to present our\n\t// certificate here, so lets not include it. May be insecure if requested.\n\tvar queryClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialer.DialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tIdleConnTimeout: time.Second,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t\tClientSessionCache: tls.NewLRUClientSessionCache(0),\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tqueryClient = newIDCheckingHTTPClient(queryClient, devID)\n\t}\n\n\tcl := &globalClient{\n\t\tserver: server,\n\t\taddrList: addrList,\n\t\tannounceClient: announceClient,\n\t\tqueryClient: queryClient,\n\t\tnoAnnounce: opts.noAnnounce,\n\t\tnoLookup: opts.noLookup,\n\t\tevLogger: evLogger,\n\t}\n\tif !opts.noAnnounce {\n\t\t// If we are supposed to announce, it's an error until we've done so.\n\t\tcl.setError(errors.New(\"not announced\"))\n\t}\n\n\treturn cl, nil\n}\n\n", "current_contents": "\t\t}\n\t}\n\n\t// The http.Client used for announcements. It needs to have our\n\t// certificate to prove our identity, and may or may not verify the server\n\t// certificate depending on the insecure setting.\n\tvar dialContext func(ctx context.Context, network, addr string) (net.Conn, error)\n\tif registry != nil {\n\t\tdialContext = dialer.DialContextReusePortFunc(registry)\n\t} else {\n\t\tdialContext = dialer.DialContext\n\t}\n\tvar announceClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDisableKeepAlives: true, // announcements are few and far between, so don't keep the connection open\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tCertificates: []tls.Certificate{cert},\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t\tClientSessionCache: tls.NewLRUClientSessionCache(0),\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tannounceClient = newIDCheckingHTTPClient(announceClient, devID)\n\t}\n\n\t// The http.Client used for queries. We don't need to present our\n\t// certificate here, so lets not include it. May be insecure if requested.\n\tvar queryClient httpClient = &contextClient{&http.Client{\n\t\tTimeout: requestTimeout,\n\t\tTransport: http2EnabledTransport(&http.Transport{\n\t\t\tDialContext: dialer.DialContext,\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tIdleConnTimeout: time.Second,\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: opts.insecure,\n\t\t\t\tMinVersion: tls.VersionTLS12,\n\t\t\t},\n\t\t}),\n\t}}\n\tif opts.id != \"\" {\n\t\tqueryClient = newIDCheckingHTTPClient(queryClient, devID)\n\t}\n\n\tcl := &globalClient{\n\t\tserver: server,\n\t\taddrList: addrList,\n\t\tannounceClient: announceClient,\n\t\tqueryClient: queryClient,\n\t\tnoAnnounce: opts.noAnnounce,\n\t\tnoLookup: opts.noLookup,\n\t\tevLogger: evLogger,\n\t}\n\tif !opts.noAnnounce {\n\t\t// If we are supposed to announce, it's an error until we've done so.\n\t\tcl.setError(errors.New(\"not announced\"))\n\t}\n\n\treturn cl, nil\n}\n"} {"commit": "0fe6d97d3d11a28851310c951ed5dec0629b7918", "message": "lib/fs: Add missing locks to fakeFile methods (fixes #9499) (#9603)", "old_file": "lib/fs/fakefs.go", "new_file": "lib/fs/fakefs.go", "status": "M", "old_contents": "\n\tif f.content != nil {\n\t\tif len(f.content) < int(off)+len(p) {\n\t\t\tnewc := make([]byte, int(off)+len(p))\n\t\t\tcopy(newc, f.content)\n\t\t\tf.content = newc\n\t\t}\n\t\tcopy(f.content[int(off):], p)\n\t}\n\n\tf.rng = nil\n\tf.offset = off + int64(len(p))\n\tif f.offset > f.size {\n\t\tf.size = f.offset\n\t}\n\treturn len(p), nil\n}\n\nfunc (f *fakeFile) Name() string {\n\tif f.presentedName != \"\" {\n\t\treturn f.presentedName\n\t}\n\treturn f.name\n}\n\nfunc (f *fakeFile) Truncate(size int64) error {\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\n\tif f.content != nil {\n\t\tif int64(cap(f.content)) < size {\n\t\t\tc := make([]byte, size)\n\t\t\tcopy(c[:len(f.content)], f.content)\n\t\t\tf.content = c\n\t\t} else {\n\t\t\tf.content = f.content[:int(size)]\n\t\t}\n\t}\n\tf.rng = nil\n\tf.size = size\n\tif f.offset > size {\n\t\tf.offset = size\n\t}\n\treturn nil\n}\n\nfunc (f *fakeFile) Stat() (FileInfo, error) {\n\tinfo := &fakeFileInfo{*f.fakeEntry}\n\tif f.presentedName != \"\" {\n\t\tinfo.name = f.presentedName\n\t}\n\n\treturn info, nil\n}\n\nfunc (*fakeFile) Sync() error {\n\treturn nil\n}\n\n// fakeFileInfo is the stat result.\ntype fakeFileInfo struct {\n\tfakeEntry // intentionally a copy of the struct\n}\n\nfunc (f *fakeFileInfo) Name() string {\n\treturn f.name\n}\n\nfunc (f *fakeFileInfo) Mode() FileMode {\n\treturn f.mode\n}\n", "new_contents": "\n\tif f.content != nil {\n\t\tif len(f.content) < int(off)+len(p) {\n\t\t\tnewc := make([]byte, int(off)+len(p))\n\t\t\tcopy(newc, f.content)\n\t\t\tf.content = newc\n\t\t}\n\t\tcopy(f.content[int(off):], p)\n\t}\n\n\tf.rng = nil\n\tf.offset = off + int64(len(p))\n\tif f.offset > f.size {\n\t\tf.size = f.offset\n\t}\n\treturn len(p), nil\n}\n\nfunc (f *fakeFile) Name() string {\n\tif f.presentedName != \"\" {\n\t\treturn f.presentedName\n\t}\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\treturn f.name\n}\n\nfunc (f *fakeFile) Truncate(size int64) error {\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\n\tif f.content != nil {\n\t\tif int64(cap(f.content)) < size {\n\t\t\tc := make([]byte, size)\n\t\t\tcopy(c[:len(f.content)], f.content)\n\t\t\tf.content = c\n\t\t} else {\n\t\t\tf.content = f.content[:int(size)]\n\t\t}\n\t}\n\tf.rng = nil\n\tf.size = size\n\tif f.offset > size {\n\t\tf.offset = size\n\t}\n\treturn nil\n}\n\nfunc (f *fakeFile) Stat() (FileInfo, error) {\n\tf.mut.Lock()\n\tinfo := &fakeFileInfo{*f.fakeEntry}\n\tf.mut.Unlock()\n\tif f.presentedName != \"\" {\n\t\tinfo.name = f.presentedName\n\t}\n\n\treturn info, nil\n}\n\nfunc (*fakeFile) Sync() error {\n\treturn nil\n}\n\n// fakeFileInfo is the stat result.\ntype fakeFileInfo struct {\n\tfakeEntry // intentionally a copy of the struct\n}\n\nfunc (f *fakeFileInfo) Name() string {\n\treturn f.name\n}\n\nfunc (f *fakeFileInfo) Mode() FileMode {\n\treturn f.mode\n}\n", "text": "<|original_code|>\n\n\tif f.content != nil {\n\t\tif len(f.content) < int(off)+len(p) {\n\t\t\tnewc := make([]byte, int(off)+len(p))\n\t\t\tcopy(newc, f.content)\n\t\t\tf.content = newc\n\t\t}\n\t\tcopy(f.content[int(off):], p)\n\t}\n\n\tf.rng = nil\n\tf.offset = off + int64(len(p))\n\tif f.offset > f.size {\n\t\tf.size = f.offset\n\t}\n\treturn len(p), nil\n}\n\nfunc (f *fakeFile) Name() string {\n\tif f.presentedName != \"\" {\n\t\treturn f.presentedName\n\t}\n\treturn f.name\n}\n\nfunc (f *fakeFile) Truncate(size int64) error {\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\n\tif f.content != nil {\n\t\tif int64(cap(f.content)) < size {\n\t\t\tc := make([]byte, size)\n\t\t\tcopy(c[:len(f.content)], f.content)\n\t\t\tf.content = c\n\t\t} else {\n\t\t\tf.content = f.content[:int(size)]\n\t\t}\n\t}\n\tf.rng = nil\n\tf.size = size\n\tif f.offset > size {\n\t\tf.offset = size\n\t}\n\treturn nil\n}\n\nfunc (f *fakeFile) Stat() (FileInfo, error) {\n\tinfo := &fakeFileInfo{*f.fakeEntry}\n\tif f.presentedName != \"\" {\n\t\tinfo.name = f.presentedName\n\t}\n\n\treturn info, nil\n}\n\nfunc (*fakeFile) Sync() error {\n\treturn nil\n}\n\n// fakeFileInfo is the stat result.\ntype fakeFileInfo struct {\n\tfakeEntry // intentionally a copy of the struct\n}\n\nfunc (f *fakeFileInfo) Name() string {\n\treturn f.name\n}\n\nfunc (f *fakeFileInfo) Mode() FileMode {\n\treturn f.mode\n}\n\n<|edits_diff|>\n--- lib/fs/fakefs.go\n+++ lib/fs/fakefs.go\n@@ -20,6 +20,8 @@\n \tif f.presentedName != \"\" {\n \t\treturn f.presentedName\n \t}\n+\tf.mut.Lock()\n+\tdefer f.mut.Unlock()\n \treturn f.name\n }\n \n@@ -45,6 +47,7 @@\n }\n \n func (f *fakeFile) Stat() (FileInfo, error) {\n+\tf.mut.Lock()\n \tinfo := &fakeFileInfo{*f.fakeEntry}\n \tif f.presentedName != \"\" {\n \t\tinfo.name = f.presentedName\n<|current_version|>\n\n\tif f.content != nil {\n\t\tif len(f.content) < int(off)+len(p) {\n\t\t\tnewc := make([]byte, int(off)+len(p))\n\t\t\tcopy(newc, f.content)\n\t\t\tf.content = newc\n\t\t}\n\t\tcopy(f.content[int(off):], p)\n\t}\n\n\tf.rng = nil\n\tf.offset = off + int64(len(p))\n\tif f.offset > f.size {\n\t\tf.size = f.offset\n\t}\n\treturn len(p), nil\n}\n\nfunc (f *fakeFile) Name() string {\n\tif f.presentedName != \"\" {\n\t\treturn f.presentedName\n\t}\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\treturn f.name\n}\n\nfunc (f *fakeFile) Truncate(size int64) error {\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\n\tif f.content != nil {\n\t\tif int64(cap(f.content)) < size {\n\t\t\tc := make([]byte, size)\n\t\t\tcopy(c[:len(f.content)], f.content)\n\t\t\tf.content = c\n\t\t} else {\n\t\t\tf.content = f.content[:int(size)]\n\t\t}\n\t}\n\tf.rng = nil\n\tf.size = size\n\tif f.offset > size {\n\t\tf.offset = size\n\t}\n\treturn nil\n}\n\nfunc (f *fakeFile) Stat() (FileInfo, error) {\n\tf.mut.Lock()\n\tinfo := &fakeFileInfo{*f.fakeEntry}\n\tif f.presentedName != \"\" {\n\t\tinfo.name = f.presentedName\n\t}\n\n\treturn info, nil\n}\n\nfunc (*fakeFile) Sync() error {\n\treturn nil\n}\n\n// fakeFileInfo is the stat result.\ntype fakeFileInfo struct {\n\tfakeEntry // intentionally a copy of the struct\n}\n\nfunc (f *fakeFileInfo) Name() string {\n\treturn f.name\n}\n\nfunc (f *fakeFileInfo) Mode() FileMode {\n\treturn f.mode\n}\n\n<|next_version|>\n\n\tif f.content != nil {\n\t\tif len(f.content) < int(off)+len(p) {\n\t\t\tnewc := make([]byte, int(off)+len(p))\n\t\t\tcopy(newc, f.content)\n\t\t\tf.content = newc\n\t\t}\n\t\tcopy(f.content[int(off):], p)\n\t}\n\n\tf.rng = nil\n\tf.offset = off + int64(len(p))\n\tif f.offset > f.size {\n\t\tf.size = f.offset\n\t}\n\treturn len(p), nil\n}\n\nfunc (f *fakeFile) Name() string {\n\tif f.presentedName != \"\" {\n\t\treturn f.presentedName\n\t}\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\treturn f.name\n}\n\nfunc (f *fakeFile) Truncate(size int64) error {\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\n\tif f.content != nil {\n\t\tif int64(cap(f.content)) < size {\n\t\t\tc := make([]byte, size)\n\t\t\tcopy(c[:len(f.content)], f.content)\n\t\t\tf.content = c\n\t\t} else {\n\t\t\tf.content = f.content[:int(size)]\n\t\t}\n\t}\n\tf.rng = nil\n\tf.size = size\n\tif f.offset > size {\n\t\tf.offset = size\n\t}\n\treturn nil\n}\n\nfunc (f *fakeFile) Stat() (FileInfo, error) {\n\tf.mut.Lock()\n\tinfo := &fakeFileInfo{*f.fakeEntry}\n\tf.mut.Unlock()\n\tif f.presentedName != \"\" {\n\t\tinfo.name = f.presentedName\n\t}\n\n\treturn info, nil\n}\n\nfunc (*fakeFile) Sync() error {\n\treturn nil\n}\n\n// fakeFileInfo is the stat result.\ntype fakeFileInfo struct {\n\tfakeEntry // intentionally a copy of the struct\n}\n\nfunc (f *fakeFileInfo) Name() string {\n\treturn f.name\n}\n\nfunc (f *fakeFileInfo) Mode() FileMode {\n\treturn f.mode\n}\n\n", "current_contents": "\n\tif f.content != nil {\n\t\tif len(f.content) < int(off)+len(p) {\n\t\t\tnewc := make([]byte, int(off)+len(p))\n\t\t\tcopy(newc, f.content)\n\t\t\tf.content = newc\n\t\t}\n\t\tcopy(f.content[int(off):], p)\n\t}\n\n\tf.rng = nil\n\tf.offset = off + int64(len(p))\n\tif f.offset > f.size {\n\t\tf.size = f.offset\n\t}\n\treturn len(p), nil\n}\n\nfunc (f *fakeFile) Name() string {\n\tif f.presentedName != \"\" {\n\t\treturn f.presentedName\n\t}\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\treturn f.name\n}\n\nfunc (f *fakeFile) Truncate(size int64) error {\n\tf.mut.Lock()\n\tdefer f.mut.Unlock()\n\n\tif f.content != nil {\n\t\tif int64(cap(f.content)) < size {\n\t\t\tc := make([]byte, size)\n\t\t\tcopy(c[:len(f.content)], f.content)\n\t\t\tf.content = c\n\t\t} else {\n\t\t\tf.content = f.content[:int(size)]\n\t\t}\n\t}\n\tf.rng = nil\n\tf.size = size\n\tif f.offset > size {\n\t\tf.offset = size\n\t}\n\treturn nil\n}\n\nfunc (f *fakeFile) Stat() (FileInfo, error) {\n\tf.mut.Lock()\n\tinfo := &fakeFileInfo{*f.fakeEntry}\n\tif f.presentedName != \"\" {\n\t\tinfo.name = f.presentedName\n\t}\n\n\treturn info, nil\n}\n\nfunc (*fakeFile) Sync() error {\n\treturn nil\n}\n\n// fakeFileInfo is the stat result.\ntype fakeFileInfo struct {\n\tfakeEntry // intentionally a copy of the struct\n}\n\nfunc (f *fakeFileInfo) Name() string {\n\treturn f.name\n}\n\nfunc (f *fakeFileInfo) Mode() FileMode {\n\treturn f.mode\n}\n"} {"commit": "dc6a10dff4bddab178118cc0e32a56925118293b", "message": "cmd/stcrashreceiver: Aggregate slice out of bounds errors", "old_file": "cmd/stcrashreceiver/sentry.go", "new_file": "cmd/stcrashreceiver/sentry.go", "status": "M", "old_contents": "\t\t}\n\t}\n\n\tpkt := packet(version, \"crash\")\n\tpkt.Message = string(subjectLine)\n\tpkt.Extra = raven.Extra{\n\t\t\"url\": reportServer + path,\n\t}\n\tpkt.Interfaces = []raven.Interface{&trace}\n\tpkt.Fingerprint = crashReportFingerprint(pkt.Message)\n\n\treturn pkt, nil\n}\n\nvar (\n\tindexRe = regexp.MustCompile(`\\[[-:0-9]+\\]`)\n\tsizeRe = regexp.MustCompile(`(length|capacity) [0-9]+`)\n\tldbPosRe = regexp.MustCompile(`(\\(pos=)([0-9]+)\\)`)\n\tldbChecksumRe = regexp.MustCompile(`(want=0x)([a-z0-9]+)( got=0x)([a-z0-9]+)`)\n\tldbFileRe = regexp.MustCompile(`(\\[file=)([0-9]+)(\\.ldb\\])`)\n\tldbInternalKeyRe = regexp.MustCompile(`(internal key \")[^\"]+(\", len=)[0-9]+`)\n\tldbPathRe = regexp.MustCompile(`(open|write|read) .+[\\\\/].+[\\\\/]index[^\\\\/]+[\\\\/][^\\\\/]+: `)\n)\n\nfunc sanitizeMessageLDB(message string) string {\n\tmessage = ldbPosRe.ReplaceAllString(message, \"${1}x)\")\n\tmessage = ldbFileRe.ReplaceAllString(message, \"${1}x${3}\")\n\tmessage = ldbChecksumRe.ReplaceAllString(message, \"${1}X${3}X\")\n\tmessage = ldbInternalKeyRe.ReplaceAllString(message, \"${1}x${2}x\")\n\tmessage = ldbPathRe.ReplaceAllString(message, \"$1 x: \")\n\treturn message\n}\n\nfunc crashReportFingerprint(message string) []string {\n\t// Do not fingerprint on the stack in case of db corruption or fatal\n\t// db io error - where it occurs doesn't matter.\n\torig := message\n\tmessage = sanitizeMessageLDB(message)\n\tif message != orig {\n\t\treturn []string{message}\n\t}\n\n\tmessage = indexRe.ReplaceAllString(message, \"[x]\")\n\tmessage = sizeRe.ReplaceAllString(message, \"$1 x\")\n\n\t// {{ default }} is what sentry uses as a fingerprint by default. While\n\t// never specified, the docs point at this being some hash derived from the\n\t// stack trace. Here we include the filtered panic message on top of that.\n\t// https://docs.sentry.io/platforms/go/data-management/event-grouping/sdk-fingerprinting/#basic-example\n\treturn []string{\"{{ default }}\", message}\n}\n\n// syncthing v1.1.4-rc.1+30-g6aaae618-dirty-crashrep \"Erbium Earthworm\" (go1.12.5 darwin-amd64) jb@kvin.kastelo.net 2019-05-23 16:08:14 UTC [foo, bar]\n// or, somewhere along the way the \"+\" in the version tag disappeared:", "new_contents": "\t\t}\n\t}\n\n\tpkt := packet(version, \"crash\")\n\tpkt.Message = string(subjectLine)\n\tpkt.Extra = raven.Extra{\n\t\t\"url\": reportServer + path,\n\t}\n\tpkt.Interfaces = []raven.Interface{&trace}\n\tpkt.Fingerprint = crashReportFingerprint(pkt.Message)\n\n\treturn pkt, nil\n}\n\nvar (\n\tindexRe = regexp.MustCompile(`\\[[-:0-9]+\\]`)\n\tsizeRe = regexp.MustCompile(`(length|capacity) [0-9]+`)\n\tldbPosRe = regexp.MustCompile(`(\\(pos=)([0-9]+)\\)`)\n\tldbChecksumRe = regexp.MustCompile(`(want=0x)([a-z0-9]+)( got=0x)([a-z0-9]+)`)\n\tldbFileRe = regexp.MustCompile(`(\\[file=)([0-9]+)(\\.ldb\\])`)\n\tldbInternalKeyRe = regexp.MustCompile(`(internal key \")[^\"]+(\", len=)[0-9]+`)\n\tldbPathRe = regexp.MustCompile(`(open|write|read) .+[\\\\/].+[\\\\/]index[^\\\\/]+[\\\\/][^\\\\/]+: `)\n\tsliceBoundsRe = regexp.MustCompile(`(slice bounds out of range) \\[.+`)\n)\n\nfunc sanitizeMessageLDB(message string) string {\n\tmessage = ldbPosRe.ReplaceAllString(message, \"${1}x)\")\n\tmessage = ldbFileRe.ReplaceAllString(message, \"${1}x${3}\")\n\tmessage = ldbChecksumRe.ReplaceAllString(message, \"${1}X${3}X\")\n\tmessage = ldbInternalKeyRe.ReplaceAllString(message, \"${1}x${2}x\")\n\tmessage = ldbPathRe.ReplaceAllString(message, \"$1 x: \")\n\tmessage = sliceBoundsRe.ReplaceAllString(message, \"$1\")\n\treturn message\n}\n\nfunc crashReportFingerprint(message string) []string {\n\t// Do not fingerprint on the stack in case of db corruption or fatal\n\t// db io error - where it occurs doesn't matter.\n\torig := message\n\tmessage = sanitizeMessageLDB(message)\n\tif message != orig {\n\t\treturn []string{message}\n\t}\n\n\tmessage = indexRe.ReplaceAllString(message, \"[x]\")\n\tmessage = sizeRe.ReplaceAllString(message, \"$1 x\")\n\n\t// {{ default }} is what sentry uses as a fingerprint by default. While\n\t// never specified, the docs point at this being some hash derived from the\n\t// stack trace. Here we include the filtered panic message on top of that.\n\t// https://docs.sentry.io/platforms/go/data-management/event-grouping/sdk-fingerprinting/#basic-example\n\treturn []string{\"{{ default }}\", message}\n}\n\n// syncthing v1.1.4-rc.1+30-g6aaae618-dirty-crashrep \"Erbium Earthworm\" (go1.12.5 darwin-amd64) jb@kvin.kastelo.net 2019-05-23 16:08:14 UTC [foo, bar]\n// or, somewhere along the way the \"+\" in the version tag disappeared:", "text": "<|original_code|>\n\t\t}\n\t}\n\n\tpkt := packet(version, \"crash\")\n\tpkt.Message = string(subjectLine)\n\tpkt.Extra = raven.Extra{\n\t\t\"url\": reportServer + path,\n\t}\n\tpkt.Interfaces = []raven.Interface{&trace}\n\tpkt.Fingerprint = crashReportFingerprint(pkt.Message)\n\n\treturn pkt, nil\n}\n\nvar (\n\tindexRe = regexp.MustCompile(`\\[[-:0-9]+\\]`)\n\tsizeRe = regexp.MustCompile(`(length|capacity) [0-9]+`)\n\tldbPosRe = regexp.MustCompile(`(\\(pos=)([0-9]+)\\)`)\n\tldbChecksumRe = regexp.MustCompile(`(want=0x)([a-z0-9]+)( got=0x)([a-z0-9]+)`)\n\tldbFileRe = regexp.MustCompile(`(\\[file=)([0-9]+)(\\.ldb\\])`)\n\tldbInternalKeyRe = regexp.MustCompile(`(internal key \")[^\"]+(\", len=)[0-9]+`)\n\tldbPathRe = regexp.MustCompile(`(open|write|read) .+[\\\\/].+[\\\\/]index[^\\\\/]+[\\\\/][^\\\\/]+: `)\n)\n\nfunc sanitizeMessageLDB(message string) string {\n\tmessage = ldbPosRe.ReplaceAllString(message, \"${1}x)\")\n\tmessage = ldbFileRe.ReplaceAllString(message, \"${1}x${3}\")\n\tmessage = ldbChecksumRe.ReplaceAllString(message, \"${1}X${3}X\")\n\tmessage = ldbInternalKeyRe.ReplaceAllString(message, \"${1}x${2}x\")\n\tmessage = ldbPathRe.ReplaceAllString(message, \"$1 x: \")\n\treturn message\n}\n\nfunc crashReportFingerprint(message string) []string {\n\t// Do not fingerprint on the stack in case of db corruption or fatal\n\t// db io error - where it occurs doesn't matter.\n\torig := message\n\tmessage = sanitizeMessageLDB(message)\n\tif message != orig {\n\t\treturn []string{message}\n\t}\n\n\tmessage = indexRe.ReplaceAllString(message, \"[x]\")\n\tmessage = sizeRe.ReplaceAllString(message, \"$1 x\")\n\n\t// {{ default }} is what sentry uses as a fingerprint by default. While\n\t// never specified, the docs point at this being some hash derived from the\n\t// stack trace. Here we include the filtered panic message on top of that.\n\t// https://docs.sentry.io/platforms/go/data-management/event-grouping/sdk-fingerprinting/#basic-example\n\treturn []string{\"{{ default }}\", message}\n}\n\n// syncthing v1.1.4-rc.1+30-g6aaae618-dirty-crashrep \"Erbium Earthworm\" (go1.12.5 darwin-amd64) jb@kvin.kastelo.net 2019-05-23 16:08:14 UTC [foo, bar]\n// or, somewhere along the way the \"+\" in the version tag disappeared:\n<|edits_diff|>\n--- cmd/stcrashreceiver/sentry.go\n+++ cmd/stcrashreceiver/sentry.go\n@@ -20,6 +20,7 @@\n \tldbFileRe = regexp.MustCompile(`(\\[file=)([0-9]+)(\\.ldb\\])`)\n \tldbInternalKeyRe = regexp.MustCompile(`(internal key \")[^\"]+(\", len=)[0-9]+`)\n \tldbPathRe = regexp.MustCompile(`(open|write|read) .+[\\\\/].+[\\\\/]index[^\\\\/]+[\\\\/][^\\\\/]+: `)\n+\tsliceBoundsRe = regexp.MustCompile(`(slice bounds out of range) \\[.+`)\n )\n \n func sanitizeMessageLDB(message string) string {\n<|current_version|>\n\t\t}\n\t}\n\n\tpkt := packet(version, \"crash\")\n\tpkt.Message = string(subjectLine)\n\tpkt.Extra = raven.Extra{\n\t\t\"url\": reportServer + path,\n\t}\n\tpkt.Interfaces = []raven.Interface{&trace}\n\tpkt.Fingerprint = crashReportFingerprint(pkt.Message)\n\n\treturn pkt, nil\n}\n\nvar (\n\tindexRe = regexp.MustCompile(`\\[[-:0-9]+\\]`)\n\tsizeRe = regexp.MustCompile(`(length|capacity) [0-9]+`)\n\tldbPosRe = regexp.MustCompile(`(\\(pos=)([0-9]+)\\)`)\n\tldbChecksumRe = regexp.MustCompile(`(want=0x)([a-z0-9]+)( got=0x)([a-z0-9]+)`)\n\tldbFileRe = regexp.MustCompile(`(\\[file=)([0-9]+)(\\.ldb\\])`)\n\tldbInternalKeyRe = regexp.MustCompile(`(internal key \")[^\"]+(\", len=)[0-9]+`)\n\tldbPathRe = regexp.MustCompile(`(open|write|read) .+[\\\\/].+[\\\\/]index[^\\\\/]+[\\\\/][^\\\\/]+: `)\n\tsliceBoundsRe = regexp.MustCompile(`(slice bounds out of range) \\[.+`)\n)\n\nfunc sanitizeMessageLDB(message string) string {\n\tmessage = ldbPosRe.ReplaceAllString(message, \"${1}x)\")\n\tmessage = ldbFileRe.ReplaceAllString(message, \"${1}x${3}\")\n\tmessage = ldbChecksumRe.ReplaceAllString(message, \"${1}X${3}X\")\n\tmessage = ldbInternalKeyRe.ReplaceAllString(message, \"${1}x${2}x\")\n\tmessage = ldbPathRe.ReplaceAllString(message, \"$1 x: \")\n\treturn message\n}\n\nfunc crashReportFingerprint(message string) []string {\n\t// Do not fingerprint on the stack in case of db corruption or fatal\n\t// db io error - where it occurs doesn't matter.\n\torig := message\n\tmessage = sanitizeMessageLDB(message)\n\tif message != orig {\n\t\treturn []string{message}\n\t}\n\n\tmessage = indexRe.ReplaceAllString(message, \"[x]\")\n\tmessage = sizeRe.ReplaceAllString(message, \"$1 x\")\n\n\t// {{ default }} is what sentry uses as a fingerprint by default. While\n\t// never specified, the docs point at this being some hash derived from the\n\t// stack trace. Here we include the filtered panic message on top of that.\n\t// https://docs.sentry.io/platforms/go/data-management/event-grouping/sdk-fingerprinting/#basic-example\n\treturn []string{\"{{ default }}\", message}\n}\n\n// syncthing v1.1.4-rc.1+30-g6aaae618-dirty-crashrep \"Erbium Earthworm\" (go1.12.5 darwin-amd64) jb@kvin.kastelo.net 2019-05-23 16:08:14 UTC [foo, bar]\n// or, somewhere along the way the \"+\" in the version tag disappeared:\n<|next_version|>\n\t\t}\n\t}\n\n\tpkt := packet(version, \"crash\")\n\tpkt.Message = string(subjectLine)\n\tpkt.Extra = raven.Extra{\n\t\t\"url\": reportServer + path,\n\t}\n\tpkt.Interfaces = []raven.Interface{&trace}\n\tpkt.Fingerprint = crashReportFingerprint(pkt.Message)\n\n\treturn pkt, nil\n}\n\nvar (\n\tindexRe = regexp.MustCompile(`\\[[-:0-9]+\\]`)\n\tsizeRe = regexp.MustCompile(`(length|capacity) [0-9]+`)\n\tldbPosRe = regexp.MustCompile(`(\\(pos=)([0-9]+)\\)`)\n\tldbChecksumRe = regexp.MustCompile(`(want=0x)([a-z0-9]+)( got=0x)([a-z0-9]+)`)\n\tldbFileRe = regexp.MustCompile(`(\\[file=)([0-9]+)(\\.ldb\\])`)\n\tldbInternalKeyRe = regexp.MustCompile(`(internal key \")[^\"]+(\", len=)[0-9]+`)\n\tldbPathRe = regexp.MustCompile(`(open|write|read) .+[\\\\/].+[\\\\/]index[^\\\\/]+[\\\\/][^\\\\/]+: `)\n\tsliceBoundsRe = regexp.MustCompile(`(slice bounds out of range) \\[.+`)\n)\n\nfunc sanitizeMessageLDB(message string) string {\n\tmessage = ldbPosRe.ReplaceAllString(message, \"${1}x)\")\n\tmessage = ldbFileRe.ReplaceAllString(message, \"${1}x${3}\")\n\tmessage = ldbChecksumRe.ReplaceAllString(message, \"${1}X${3}X\")\n\tmessage = ldbInternalKeyRe.ReplaceAllString(message, \"${1}x${2}x\")\n\tmessage = ldbPathRe.ReplaceAllString(message, \"$1 x: \")\n\tmessage = sliceBoundsRe.ReplaceAllString(message, \"$1\")\n\treturn message\n}\n\nfunc crashReportFingerprint(message string) []string {\n\t// Do not fingerprint on the stack in case of db corruption or fatal\n\t// db io error - where it occurs doesn't matter.\n\torig := message\n\tmessage = sanitizeMessageLDB(message)\n\tif message != orig {\n\t\treturn []string{message}\n\t}\n\n\tmessage = indexRe.ReplaceAllString(message, \"[x]\")\n\tmessage = sizeRe.ReplaceAllString(message, \"$1 x\")\n\n\t// {{ default }} is what sentry uses as a fingerprint by default. While\n\t// never specified, the docs point at this being some hash derived from the\n\t// stack trace. Here we include the filtered panic message on top of that.\n\t// https://docs.sentry.io/platforms/go/data-management/event-grouping/sdk-fingerprinting/#basic-example\n\treturn []string{\"{{ default }}\", message}\n}\n\n// syncthing v1.1.4-rc.1+30-g6aaae618-dirty-crashrep \"Erbium Earthworm\" (go1.12.5 darwin-amd64) jb@kvin.kastelo.net 2019-05-23 16:08:14 UTC [foo, bar]\n// or, somewhere along the way the \"+\" in the version tag disappeared:\n", "current_contents": "\t\t}\n\t}\n\n\tpkt := packet(version, \"crash\")\n\tpkt.Message = string(subjectLine)\n\tpkt.Extra = raven.Extra{\n\t\t\"url\": reportServer + path,\n\t}\n\tpkt.Interfaces = []raven.Interface{&trace}\n\tpkt.Fingerprint = crashReportFingerprint(pkt.Message)\n\n\treturn pkt, nil\n}\n\nvar (\n\tindexRe = regexp.MustCompile(`\\[[-:0-9]+\\]`)\n\tsizeRe = regexp.MustCompile(`(length|capacity) [0-9]+`)\n\tldbPosRe = regexp.MustCompile(`(\\(pos=)([0-9]+)\\)`)\n\tldbChecksumRe = regexp.MustCompile(`(want=0x)([a-z0-9]+)( got=0x)([a-z0-9]+)`)\n\tldbFileRe = regexp.MustCompile(`(\\[file=)([0-9]+)(\\.ldb\\])`)\n\tldbInternalKeyRe = regexp.MustCompile(`(internal key \")[^\"]+(\", len=)[0-9]+`)\n\tldbPathRe = regexp.MustCompile(`(open|write|read) .+[\\\\/].+[\\\\/]index[^\\\\/]+[\\\\/][^\\\\/]+: `)\n\tsliceBoundsRe = regexp.MustCompile(`(slice bounds out of range) \\[.+`)\n)\n\nfunc sanitizeMessageLDB(message string) string {\n\tmessage = ldbPosRe.ReplaceAllString(message, \"${1}x)\")\n\tmessage = ldbFileRe.ReplaceAllString(message, \"${1}x${3}\")\n\tmessage = ldbChecksumRe.ReplaceAllString(message, \"${1}X${3}X\")\n\tmessage = ldbInternalKeyRe.ReplaceAllString(message, \"${1}x${2}x\")\n\tmessage = ldbPathRe.ReplaceAllString(message, \"$1 x: \")\n\treturn message\n}\n\nfunc crashReportFingerprint(message string) []string {\n\t// Do not fingerprint on the stack in case of db corruption or fatal\n\t// db io error - where it occurs doesn't matter.\n\torig := message\n\tmessage = sanitizeMessageLDB(message)\n\tif message != orig {\n\t\treturn []string{message}\n\t}\n\n\tmessage = indexRe.ReplaceAllString(message, \"[x]\")\n\tmessage = sizeRe.ReplaceAllString(message, \"$1 x\")\n\n\t// {{ default }} is what sentry uses as a fingerprint by default. While\n\t// never specified, the docs point at this being some hash derived from the\n\t// stack trace. Here we include the filtered panic message on top of that.\n\t// https://docs.sentry.io/platforms/go/data-management/event-grouping/sdk-fingerprinting/#basic-example\n\treturn []string{\"{{ default }}\", message}\n}\n\n// syncthing v1.1.4-rc.1+30-g6aaae618-dirty-crashrep \"Erbium Earthworm\" (go1.12.5 darwin-amd64) jb@kvin.kastelo.net 2019-05-23 16:08:14 UTC [foo, bar]\n// or, somewhere along the way the \"+\" in the version tag disappeared:"} {"commit": "b9c08d3814685bc8c4a322756e042b9852e321b4", "message": "all: Add Prometheus-style metrics to expose some internal performance counters (fixes #5175) (#9003)", "old_file": "lib/events/events.go", "new_file": "lib/events/events.go", "status": "M", "old_contents": "func NewLogger() Logger {\n\tl := &logger{\n\t\ttimeout: time.NewTimer(time.Second),\n\t\tevents: make(chan Event, BufferSize),\n\t\tfuncs: make(chan func(context.Context)),\n\t\ttoUnsubscribe: make(chan *subscription),\n\t}\n\t// Make sure the timer is in the stopped state and hasn't fired anything\n\t// into the channel.\n\tif !l.timeout.Stop() {\n\t\t<-l.timeout.C\n\t}\n\treturn l\n}\n\nfunc (l *logger) Serve(ctx context.Context) error {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase e := <-l.events:\n\t\t\t// Incoming events get sent\n\t\t\tl.sendEvent(e)\n\n\t\tcase fn := <-l.funcs:\n\t\t\t// Subscriptions are handled here.\n\t\t\tfn(ctx)\n\n\t\tcase s := <-l.toUnsubscribe:\n\t\t\tl.unsubscribe(s)\n\n\t\tcase <-ctx.Done():\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\t// Closing the event channels corresponds to what happens when a\n\t// subscription is unsubscribed; this stops any BufferedSubscription,\n\t// makes Poll() return ErrClosed, etc.\n\tfor _, s := range l.subs {\n\t\tclose(s.events)\n\t}\n\n\treturn nil\n}\n\nfunc (l *logger) Log(t EventType, data interface{}) {\n\tl.events <- Event{\n\t\tTime: time.Now(), // intentionally high precision\n\t\tType: t,\n\t\tData: data,\n\t\t// SubscriptionID and GlobalID are set in sendEvent\n\t}\n}\n\nfunc (l *logger) sendEvent(e Event) {\n\tl.nextGlobalID++\n\tdl.Debugln(\"log\", l.nextGlobalID, e.Type, e.Data)\n\n\te.GlobalID = l.nextGlobalID\n\n\tfor i, s := range l.subs {\n\t\tif s.mask&e.Type != 0 {\n\t\t\te.SubscriptionID = l.nextSubscriptionIDs[i]\n\t\t\tl.nextSubscriptionIDs[i]++\n\n\t\t\tl.timeout.Reset(eventLogTimeout)\n\t\t\ttimedOut := false\n\n\t\t\tselect {\n\t\t\tcase s.events <- e:\n\t\t\tcase <-l.timeout.C:\n\t\t\t\t// if s.events is not ready, drop the event\n\t\t\t\ttimedOut = true\n\t\t\t}\n\n\t\t\t// If stop returns false it already sent something to the\n\t\t\t// channel. If we didn't already read it above we must do so now\n\t\t\t// or we get a spurious timeout on the next loop.\n\t\t\tif !l.timeout.Stop() && !timedOut {\n\t\t\t\t<-l.timeout.C\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *logger) Subscribe(mask EventType) Subscription {\n\tres := make(chan Subscription)\n\tl.funcs <- func(ctx context.Context) {\n\t\tdl.Debugln(\"subscribe\", mask)\n\n\t\ts := &subscription{\n\t\t\tmask: mask,\n\t\t\tevents: make(chan Event, BufferSize),\n\t\t\ttoUnsubscribe: l.toUnsubscribe,\n\t\t\ttimeout: time.NewTimer(0),\n\t\t\tctx: ctx,\n\t\t}", "new_contents": "func NewLogger() Logger {\n\tl := &logger{\n\t\ttimeout: time.NewTimer(time.Second),\n\t\tevents: make(chan Event, BufferSize),\n\t\tfuncs: make(chan func(context.Context)),\n\t\ttoUnsubscribe: make(chan *subscription),\n\t}\n\t// Make sure the timer is in the stopped state and hasn't fired anything\n\t// into the channel.\n\tif !l.timeout.Stop() {\n\t\t<-l.timeout.C\n\t}\n\treturn l\n}\n\nfunc (l *logger) Serve(ctx context.Context) error {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase e := <-l.events:\n\t\t\t// Incoming events get sent\n\t\t\tl.sendEvent(e)\n\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateCreated).Inc()\n\n\t\tcase fn := <-l.funcs:\n\t\t\t// Subscriptions are handled here.\n\t\t\tfn(ctx)\n\n\t\tcase s := <-l.toUnsubscribe:\n\t\t\tl.unsubscribe(s)\n\n\t\tcase <-ctx.Done():\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\t// Closing the event channels corresponds to what happens when a\n\t// subscription is unsubscribed; this stops any BufferedSubscription,\n\t// makes Poll() return ErrClosed, etc.\n\tfor _, s := range l.subs {\n\t\tclose(s.events)\n\t}\n\n\treturn nil\n}\n\nfunc (l *logger) Log(t EventType, data interface{}) {\n\tl.events <- Event{\n\t\tTime: time.Now(), // intentionally high precision\n\t\tType: t,\n\t\tData: data,\n\t\t// SubscriptionID and GlobalID are set in sendEvent\n\t}\n}\n\nfunc (l *logger) sendEvent(e Event) {\n\tl.nextGlobalID++\n\tdl.Debugln(\"log\", l.nextGlobalID, e.Type, e.Data)\n\n\te.GlobalID = l.nextGlobalID\n\n\tfor i, s := range l.subs {\n\t\tif s.mask&e.Type != 0 {\n\t\t\te.SubscriptionID = l.nextSubscriptionIDs[i]\n\t\t\tl.nextSubscriptionIDs[i]++\n\n\t\t\tl.timeout.Reset(eventLogTimeout)\n\t\t\ttimedOut := false\n\n\t\t\tselect {\n\t\t\tcase s.events <- e:\n\t\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateDelivered).Inc()\n\t\t\tcase <-l.timeout.C:\n\t\t\t\t// if s.events is not ready, drop the event\n\t\t\t\ttimedOut = true\n\t\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateDropped).Inc()\n\t\t\t}\n\n\t\t\t// If stop returns false it already sent something to the\n\t\t\t// channel. If we didn't already read it above we must do so now\n\t\t\t// or we get a spurious timeout on the next loop.\n\t\t\tif !l.timeout.Stop() && !timedOut {\n\t\t\t\t<-l.timeout.C\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *logger) Subscribe(mask EventType) Subscription {\n\tres := make(chan Subscription)\n\tl.funcs <- func(ctx context.Context) {\n\t\tdl.Debugln(\"subscribe\", mask)\n\n\t\ts := &subscription{\n\t\t\tmask: mask,\n\t\t\tevents: make(chan Event, BufferSize),\n\t\t\ttoUnsubscribe: l.toUnsubscribe,\n\t\t\ttimeout: time.NewTimer(0),\n\t\t\tctx: ctx,\n\t\t}", "text": "<|original_code|>\nfunc NewLogger() Logger {\n\tl := &logger{\n\t\ttimeout: time.NewTimer(time.Second),\n\t\tevents: make(chan Event, BufferSize),\n\t\tfuncs: make(chan func(context.Context)),\n\t\ttoUnsubscribe: make(chan *subscription),\n\t}\n\t// Make sure the timer is in the stopped state and hasn't fired anything\n\t// into the channel.\n\tif !l.timeout.Stop() {\n\t\t<-l.timeout.C\n\t}\n\treturn l\n}\n\nfunc (l *logger) Serve(ctx context.Context) error {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase e := <-l.events:\n\t\t\t// Incoming events get sent\n\t\t\tl.sendEvent(e)\n\n\t\tcase fn := <-l.funcs:\n\t\t\t// Subscriptions are handled here.\n\t\t\tfn(ctx)\n\n\t\tcase s := <-l.toUnsubscribe:\n\t\t\tl.unsubscribe(s)\n\n\t\tcase <-ctx.Done():\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\t// Closing the event channels corresponds to what happens when a\n\t// subscription is unsubscribed; this stops any BufferedSubscription,\n\t// makes Poll() return ErrClosed, etc.\n\tfor _, s := range l.subs {\n\t\tclose(s.events)\n\t}\n\n\treturn nil\n}\n\nfunc (l *logger) Log(t EventType, data interface{}) {\n\tl.events <- Event{\n\t\tTime: time.Now(), // intentionally high precision\n\t\tType: t,\n\t\tData: data,\n\t\t// SubscriptionID and GlobalID are set in sendEvent\n\t}\n}\n\nfunc (l *logger) sendEvent(e Event) {\n\tl.nextGlobalID++\n\tdl.Debugln(\"log\", l.nextGlobalID, e.Type, e.Data)\n\n\te.GlobalID = l.nextGlobalID\n\n\tfor i, s := range l.subs {\n\t\tif s.mask&e.Type != 0 {\n\t\t\te.SubscriptionID = l.nextSubscriptionIDs[i]\n\t\t\tl.nextSubscriptionIDs[i]++\n\n\t\t\tl.timeout.Reset(eventLogTimeout)\n\t\t\ttimedOut := false\n\n\t\t\tselect {\n\t\t\tcase s.events <- e:\n\t\t\tcase <-l.timeout.C:\n\t\t\t\t// if s.events is not ready, drop the event\n\t\t\t\ttimedOut = true\n\t\t\t}\n\n\t\t\t// If stop returns false it already sent something to the\n\t\t\t// channel. If we didn't already read it above we must do so now\n\t\t\t// or we get a spurious timeout on the next loop.\n\t\t\tif !l.timeout.Stop() && !timedOut {\n\t\t\t\t<-l.timeout.C\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *logger) Subscribe(mask EventType) Subscription {\n\tres := make(chan Subscription)\n\tl.funcs <- func(ctx context.Context) {\n\t\tdl.Debugln(\"subscribe\", mask)\n\n\t\ts := &subscription{\n\t\t\tmask: mask,\n\t\t\tevents: make(chan Event, BufferSize),\n\t\t\ttoUnsubscribe: l.toUnsubscribe,\n\t\t\ttimeout: time.NewTimer(0),\n\t\t\tctx: ctx,\n\t\t}\n<|edits_diff|>\n--- lib/events/events.go\n+++ lib/events/events.go\n@@ -20,6 +20,7 @@\n \t\tcase e := <-l.events:\n \t\t\t// Incoming events get sent\n \t\t\tl.sendEvent(e)\n+\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateCreated).Inc()\n \n \t\tcase fn := <-l.funcs:\n \t\t\t// Subscriptions are handled here.\n@@ -68,6 +69,7 @@\n \n \t\t\tselect {\n \t\t\tcase s.events <- e:\n+\t\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateDelivered).Inc()\n \t\t\tcase <-l.timeout.C:\n \t\t\t\t// if s.events is not ready, drop the event\n \t\t\t\ttimedOut = true\n<|current_version|>\nfunc NewLogger() Logger {\n\tl := &logger{\n\t\ttimeout: time.NewTimer(time.Second),\n\t\tevents: make(chan Event, BufferSize),\n\t\tfuncs: make(chan func(context.Context)),\n\t\ttoUnsubscribe: make(chan *subscription),\n\t}\n\t// Make sure the timer is in the stopped state and hasn't fired anything\n\t// into the channel.\n\tif !l.timeout.Stop() {\n\t\t<-l.timeout.C\n\t}\n\treturn l\n}\n\nfunc (l *logger) Serve(ctx context.Context) error {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase e := <-l.events:\n\t\t\t// Incoming events get sent\n\t\t\tl.sendEvent(e)\n\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateCreated).Inc()\n\n\t\tcase fn := <-l.funcs:\n\t\t\t// Subscriptions are handled here.\n\t\t\tfn(ctx)\n\n\t\tcase s := <-l.toUnsubscribe:\n\t\t\tl.unsubscribe(s)\n\n\t\tcase <-ctx.Done():\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\t// Closing the event channels corresponds to what happens when a\n\t// subscription is unsubscribed; this stops any BufferedSubscription,\n\t// makes Poll() return ErrClosed, etc.\n\tfor _, s := range l.subs {\n\t\tclose(s.events)\n\t}\n\n\treturn nil\n}\n\nfunc (l *logger) Log(t EventType, data interface{}) {\n\tl.events <- Event{\n\t\tTime: time.Now(), // intentionally high precision\n\t\tType: t,\n\t\tData: data,\n\t\t// SubscriptionID and GlobalID are set in sendEvent\n\t}\n}\n\nfunc (l *logger) sendEvent(e Event) {\n\tl.nextGlobalID++\n\tdl.Debugln(\"log\", l.nextGlobalID, e.Type, e.Data)\n\n\te.GlobalID = l.nextGlobalID\n\n\tfor i, s := range l.subs {\n\t\tif s.mask&e.Type != 0 {\n\t\t\te.SubscriptionID = l.nextSubscriptionIDs[i]\n\t\t\tl.nextSubscriptionIDs[i]++\n\n\t\t\tl.timeout.Reset(eventLogTimeout)\n\t\t\ttimedOut := false\n\n\t\t\tselect {\n\t\t\tcase s.events <- e:\n\t\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateDelivered).Inc()\n\t\t\tcase <-l.timeout.C:\n\t\t\t\t// if s.events is not ready, drop the event\n\t\t\t\ttimedOut = true\n\t\t\t}\n\n\t\t\t// If stop returns false it already sent something to the\n\t\t\t// channel. If we didn't already read it above we must do so now\n\t\t\t// or we get a spurious timeout on the next loop.\n\t\t\tif !l.timeout.Stop() && !timedOut {\n\t\t\t\t<-l.timeout.C\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *logger) Subscribe(mask EventType) Subscription {\n\tres := make(chan Subscription)\n\tl.funcs <- func(ctx context.Context) {\n\t\tdl.Debugln(\"subscribe\", mask)\n\n\t\ts := &subscription{\n\t\t\tmask: mask,\n\t\t\tevents: make(chan Event, BufferSize),\n\t\t\ttoUnsubscribe: l.toUnsubscribe,\n\t\t\ttimeout: time.NewTimer(0),\n\t\t\tctx: ctx,\n\t\t}\n<|next_version|>\nfunc NewLogger() Logger {\n\tl := &logger{\n\t\ttimeout: time.NewTimer(time.Second),\n\t\tevents: make(chan Event, BufferSize),\n\t\tfuncs: make(chan func(context.Context)),\n\t\ttoUnsubscribe: make(chan *subscription),\n\t}\n\t// Make sure the timer is in the stopped state and hasn't fired anything\n\t// into the channel.\n\tif !l.timeout.Stop() {\n\t\t<-l.timeout.C\n\t}\n\treturn l\n}\n\nfunc (l *logger) Serve(ctx context.Context) error {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase e := <-l.events:\n\t\t\t// Incoming events get sent\n\t\t\tl.sendEvent(e)\n\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateCreated).Inc()\n\n\t\tcase fn := <-l.funcs:\n\t\t\t// Subscriptions are handled here.\n\t\t\tfn(ctx)\n\n\t\tcase s := <-l.toUnsubscribe:\n\t\t\tl.unsubscribe(s)\n\n\t\tcase <-ctx.Done():\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\t// Closing the event channels corresponds to what happens when a\n\t// subscription is unsubscribed; this stops any BufferedSubscription,\n\t// makes Poll() return ErrClosed, etc.\n\tfor _, s := range l.subs {\n\t\tclose(s.events)\n\t}\n\n\treturn nil\n}\n\nfunc (l *logger) Log(t EventType, data interface{}) {\n\tl.events <- Event{\n\t\tTime: time.Now(), // intentionally high precision\n\t\tType: t,\n\t\tData: data,\n\t\t// SubscriptionID and GlobalID are set in sendEvent\n\t}\n}\n\nfunc (l *logger) sendEvent(e Event) {\n\tl.nextGlobalID++\n\tdl.Debugln(\"log\", l.nextGlobalID, e.Type, e.Data)\n\n\te.GlobalID = l.nextGlobalID\n\n\tfor i, s := range l.subs {\n\t\tif s.mask&e.Type != 0 {\n\t\t\te.SubscriptionID = l.nextSubscriptionIDs[i]\n\t\t\tl.nextSubscriptionIDs[i]++\n\n\t\t\tl.timeout.Reset(eventLogTimeout)\n\t\t\ttimedOut := false\n\n\t\t\tselect {\n\t\t\tcase s.events <- e:\n\t\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateDelivered).Inc()\n\t\t\tcase <-l.timeout.C:\n\t\t\t\t// if s.events is not ready, drop the event\n\t\t\t\ttimedOut = true\n\t\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateDropped).Inc()\n\t\t\t}\n\n\t\t\t// If stop returns false it already sent something to the\n\t\t\t// channel. If we didn't already read it above we must do so now\n\t\t\t// or we get a spurious timeout on the next loop.\n\t\t\tif !l.timeout.Stop() && !timedOut {\n\t\t\t\t<-l.timeout.C\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *logger) Subscribe(mask EventType) Subscription {\n\tres := make(chan Subscription)\n\tl.funcs <- func(ctx context.Context) {\n\t\tdl.Debugln(\"subscribe\", mask)\n\n\t\ts := &subscription{\n\t\t\tmask: mask,\n\t\t\tevents: make(chan Event, BufferSize),\n\t\t\ttoUnsubscribe: l.toUnsubscribe,\n\t\t\ttimeout: time.NewTimer(0),\n\t\t\tctx: ctx,\n\t\t}\n", "current_contents": "func NewLogger() Logger {\n\tl := &logger{\n\t\ttimeout: time.NewTimer(time.Second),\n\t\tevents: make(chan Event, BufferSize),\n\t\tfuncs: make(chan func(context.Context)),\n\t\ttoUnsubscribe: make(chan *subscription),\n\t}\n\t// Make sure the timer is in the stopped state and hasn't fired anything\n\t// into the channel.\n\tif !l.timeout.Stop() {\n\t\t<-l.timeout.C\n\t}\n\treturn l\n}\n\nfunc (l *logger) Serve(ctx context.Context) error {\nloop:\n\tfor {\n\t\tselect {\n\t\tcase e := <-l.events:\n\t\t\t// Incoming events get sent\n\t\t\tl.sendEvent(e)\n\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateCreated).Inc()\n\n\t\tcase fn := <-l.funcs:\n\t\t\t// Subscriptions are handled here.\n\t\t\tfn(ctx)\n\n\t\tcase s := <-l.toUnsubscribe:\n\t\t\tl.unsubscribe(s)\n\n\t\tcase <-ctx.Done():\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\t// Closing the event channels corresponds to what happens when a\n\t// subscription is unsubscribed; this stops any BufferedSubscription,\n\t// makes Poll() return ErrClosed, etc.\n\tfor _, s := range l.subs {\n\t\tclose(s.events)\n\t}\n\n\treturn nil\n}\n\nfunc (l *logger) Log(t EventType, data interface{}) {\n\tl.events <- Event{\n\t\tTime: time.Now(), // intentionally high precision\n\t\tType: t,\n\t\tData: data,\n\t\t// SubscriptionID and GlobalID are set in sendEvent\n\t}\n}\n\nfunc (l *logger) sendEvent(e Event) {\n\tl.nextGlobalID++\n\tdl.Debugln(\"log\", l.nextGlobalID, e.Type, e.Data)\n\n\te.GlobalID = l.nextGlobalID\n\n\tfor i, s := range l.subs {\n\t\tif s.mask&e.Type != 0 {\n\t\t\te.SubscriptionID = l.nextSubscriptionIDs[i]\n\t\t\tl.nextSubscriptionIDs[i]++\n\n\t\t\tl.timeout.Reset(eventLogTimeout)\n\t\t\ttimedOut := false\n\n\t\t\tselect {\n\t\t\tcase s.events <- e:\n\t\t\t\tmetricEvents.WithLabelValues(e.Type.String(), metricEventStateDelivered).Inc()\n\t\t\tcase <-l.timeout.C:\n\t\t\t\t// if s.events is not ready, drop the event\n\t\t\t\ttimedOut = true\n\t\t\t}\n\n\t\t\t// If stop returns false it already sent something to the\n\t\t\t// channel. If we didn't already read it above we must do so now\n\t\t\t// or we get a spurious timeout on the next loop.\n\t\t\tif !l.timeout.Stop() && !timedOut {\n\t\t\t\t<-l.timeout.C\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (l *logger) Subscribe(mask EventType) Subscription {\n\tres := make(chan Subscription)\n\tl.funcs <- func(ctx context.Context) {\n\t\tdl.Debugln(\"subscribe\", mask)\n\n\t\ts := &subscription{\n\t\t\tmask: mask,\n\t\t\tevents: make(chan Event, BufferSize),\n\t\t\ttoUnsubscribe: l.toUnsubscribe,\n\t\t\ttimeout: time.NewTimer(0),\n\t\t\tctx: ctx,\n\t\t}"} {"commit": "ab0eb909a2b3edafdc551737cc79f0088bd35571", "message": "gui, lib/connections: Let the backend decide whether connection is local (fixes #8686) (#8694)", "old_file": "lib/connections/structs.go", "new_file": "lib/connections/structs.go", "status": "M", "old_contents": "\t\"github.com/syncthing/syncthing/lib/nat\"\n\t\"github.com/syncthing/syncthing/lib/osutil\"\n\t\"github.com/syncthing/syncthing/lib/protocol\"\n\t\"github.com/syncthing/syncthing/lib/stats\"\n\n\t\"github.com/thejerf/suture/v4\"\n)\n\ntype tlsConn interface {\n\tio.ReadWriteCloser\n\tConnectionState() tls.ConnectionState\n\tRemoteAddr() net.Addr\n\tSetDeadline(time.Time) error\n\tSetWriteDeadline(time.Time) error\n\tLocalAddr() net.Addr\n}\n\n// internalConn is the raw TLS connection plus some metadata on where it\n// came from (type, priority).\ntype internalConn struct {\n\ttlsConn\n\tconnType connType\n\tpriority int\n\testablishedAt time.Time\n}\n\ntype connType int\n\nconst (\n\tconnTypeRelayClient connType = iota\n\tconnTypeRelayServer\n\tconnTypeTCPClient\n\tconnTypeTCPServer\n\tconnTypeQUICClient\n\tconnTypeQUICServer\n)\n\nfunc (t connType) String() string {\n\tswitch t {\n\tcase connTypeRelayClient:\n\t\treturn \"relay-client\"\n\tcase connTypeRelayServer:\n\t\treturn \"relay-server\"\n\tcase connTypeTCPClient:\n\t\treturn \"tcp-client\"\n\tcase connTypeTCPServer:\n\t\treturn \"tcp-server\"\n\tcase connTypeQUICClient:\n\t\treturn \"quic-client\"\n\tcase connTypeQUICServer:\n\t\treturn \"quic-server\"\n\tdefault:\n\t\treturn \"unknown-type\"\n\t}\n}\n\nfunc (t connType) Transport() string {\n\tswitch t {\n\tcase connTypeRelayClient, connTypeRelayServer:\n\t\treturn \"relay\"\n\tcase connTypeTCPClient, connTypeTCPServer:\n\t\treturn \"tcp\"\n\tcase connTypeQUICClient, connTypeQUICServer:\n\t\treturn \"quic\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc newInternalConn(tc tlsConn, connType connType, priority int) internalConn {\n\treturn internalConn{\n\t\ttlsConn: tc,\n\t\tconnType: connType,\n\t\tpriority: priority,\n\t\testablishedAt: time.Now().Truncate(time.Second),\n\t}\n}\n\nfunc (c internalConn) Close() error {\n\t// *tls.Conn.Close() does more than it says on the tin. Specifically, it\n\t// sends a TLS alert message, which might block forever if the\n\t// connection is dead and we don't have a deadline set.\n\t_ = c.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))\n\treturn c.tlsConn.Close()\n}\n\nfunc (c internalConn) Type() string {\n\treturn c.connType.String()\n}\n\nfunc (c internalConn) Priority() int {\n\treturn c.priority\n}\n\nfunc (c internalConn) Crypto() string {\n\tcs := c.ConnectionState()\n\treturn fmt.Sprintf(\"%s-%s\", tlsVersionNames[cs.Version], tlsCipherSuiteNames[cs.CipherSuite])\n}\n\nfunc (c internalConn) Transport() string {\n\ttransport := c.connType.Transport()\n\tip, err := osutil.IPFromAddr(c.LocalAddr())\n\tif err != nil {\n\t\treturn transport\n\t}\n\tif ip.To4() != nil {\n\t\treturn transport + \"4\"\n\t}\n\treturn transport + \"6\"\n}\n\nfunc (c internalConn) EstablishedAt() time.Time {", "new_contents": "\t\"github.com/syncthing/syncthing/lib/nat\"\n\t\"github.com/syncthing/syncthing/lib/osutil\"\n\t\"github.com/syncthing/syncthing/lib/protocol\"\n\t\"github.com/syncthing/syncthing/lib/stats\"\n\n\t\"github.com/thejerf/suture/v4\"\n)\n\ntype tlsConn interface {\n\tio.ReadWriteCloser\n\tConnectionState() tls.ConnectionState\n\tRemoteAddr() net.Addr\n\tSetDeadline(time.Time) error\n\tSetWriteDeadline(time.Time) error\n\tLocalAddr() net.Addr\n}\n\n// internalConn is the raw TLS connection plus some metadata on where it\n// came from (type, priority).\ntype internalConn struct {\n\ttlsConn\n\tconnType connType\n\tisLocal bool\n\tpriority int\n\testablishedAt time.Time\n}\n\ntype connType int\n\nconst (\n\tconnTypeRelayClient connType = iota\n\tconnTypeRelayServer\n\tconnTypeTCPClient\n\tconnTypeTCPServer\n\tconnTypeQUICClient\n\tconnTypeQUICServer\n)\n\nfunc (t connType) String() string {\n\tswitch t {\n\tcase connTypeRelayClient:\n\t\treturn \"relay-client\"\n\tcase connTypeRelayServer:\n\t\treturn \"relay-server\"\n\tcase connTypeTCPClient:\n\t\treturn \"tcp-client\"\n\tcase connTypeTCPServer:\n\t\treturn \"tcp-server\"\n\tcase connTypeQUICClient:\n\t\treturn \"quic-client\"\n\tcase connTypeQUICServer:\n\t\treturn \"quic-server\"\n\tdefault:\n\t\treturn \"unknown-type\"\n\t}\n}\n\nfunc (t connType) Transport() string {\n\tswitch t {\n\tcase connTypeRelayClient, connTypeRelayServer:\n\t\treturn \"relay\"\n\tcase connTypeTCPClient, connTypeTCPServer:\n\t\treturn \"tcp\"\n\tcase connTypeQUICClient, connTypeQUICServer:\n\t\treturn \"quic\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc newInternalConn(tc tlsConn, connType connType, priority int) internalConn {\n\treturn internalConn{\n\t\ttlsConn: tc,\n\t\tconnType: connType,\n\t\tpriority: priority,\n\t\testablishedAt: time.Now().Truncate(time.Second),\n\t}\n}\n\nfunc (c internalConn) Close() error {\n\t// *tls.Conn.Close() does more than it says on the tin. Specifically, it\n\t// sends a TLS alert message, which might block forever if the\n\t// connection is dead and we don't have a deadline set.\n\t_ = c.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))\n\treturn c.tlsConn.Close()\n}\n\nfunc (c internalConn) Type() string {\n\treturn c.connType.String()\n}\n\nfunc (c internalConn) IsLocal() bool {\n\treturn c.isLocal\n}\n\nfunc (c internalConn) Priority() int {\n\treturn c.priority\n}\n\nfunc (c internalConn) Crypto() string {\n\tcs := c.ConnectionState()\n\treturn fmt.Sprintf(\"%s-%s\", tlsVersionNames[cs.Version], tlsCipherSuiteNames[cs.CipherSuite])\n}\n\nfunc (c internalConn) Transport() string {\n\ttransport := c.connType.Transport()\n\tip, err := osutil.IPFromAddr(c.LocalAddr())\n\tif err != nil {\n\t\treturn transport\n\t}\n\tif ip.To4() != nil {\n\t\treturn transport + \"4\"\n\t}\n\treturn transport + \"6\"\n}\n\nfunc (c internalConn) EstablishedAt() time.Time {", "text": "<|original_code|>\n\t\"github.com/syncthing/syncthing/lib/nat\"\n\t\"github.com/syncthing/syncthing/lib/osutil\"\n\t\"github.com/syncthing/syncthing/lib/protocol\"\n\t\"github.com/syncthing/syncthing/lib/stats\"\n\n\t\"github.com/thejerf/suture/v4\"\n)\n\ntype tlsConn interface {\n\tio.ReadWriteCloser\n\tConnectionState() tls.ConnectionState\n\tRemoteAddr() net.Addr\n\tSetDeadline(time.Time) error\n\tSetWriteDeadline(time.Time) error\n\tLocalAddr() net.Addr\n}\n\n// internalConn is the raw TLS connection plus some metadata on where it\n// came from (type, priority).\ntype internalConn struct {\n\ttlsConn\n\tconnType connType\n\tpriority int\n\testablishedAt time.Time\n}\n\ntype connType int\n\nconst (\n\tconnTypeRelayClient connType = iota\n\tconnTypeRelayServer\n\tconnTypeTCPClient\n\tconnTypeTCPServer\n\tconnTypeQUICClient\n\tconnTypeQUICServer\n)\n\nfunc (t connType) String() string {\n\tswitch t {\n\tcase connTypeRelayClient:\n\t\treturn \"relay-client\"\n\tcase connTypeRelayServer:\n\t\treturn \"relay-server\"\n\tcase connTypeTCPClient:\n\t\treturn \"tcp-client\"\n\tcase connTypeTCPServer:\n\t\treturn \"tcp-server\"\n\tcase connTypeQUICClient:\n\t\treturn \"quic-client\"\n\tcase connTypeQUICServer:\n\t\treturn \"quic-server\"\n\tdefault:\n\t\treturn \"unknown-type\"\n\t}\n}\n\nfunc (t connType) Transport() string {\n\tswitch t {\n\tcase connTypeRelayClient, connTypeRelayServer:\n\t\treturn \"relay\"\n\tcase connTypeTCPClient, connTypeTCPServer:\n\t\treturn \"tcp\"\n\tcase connTypeQUICClient, connTypeQUICServer:\n\t\treturn \"quic\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc newInternalConn(tc tlsConn, connType connType, priority int) internalConn {\n\treturn internalConn{\n\t\ttlsConn: tc,\n\t\tconnType: connType,\n\t\tpriority: priority,\n\t\testablishedAt: time.Now().Truncate(time.Second),\n\t}\n}\n\nfunc (c internalConn) Close() error {\n\t// *tls.Conn.Close() does more than it says on the tin. Specifically, it\n\t// sends a TLS alert message, which might block forever if the\n\t// connection is dead and we don't have a deadline set.\n\t_ = c.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))\n\treturn c.tlsConn.Close()\n}\n\nfunc (c internalConn) Type() string {\n\treturn c.connType.String()\n}\n\nfunc (c internalConn) Priority() int {\n\treturn c.priority\n}\n\nfunc (c internalConn) Crypto() string {\n\tcs := c.ConnectionState()\n\treturn fmt.Sprintf(\"%s-%s\", tlsVersionNames[cs.Version], tlsCipherSuiteNames[cs.CipherSuite])\n}\n\nfunc (c internalConn) Transport() string {\n\ttransport := c.connType.Transport()\n\tip, err := osutil.IPFromAddr(c.LocalAddr())\n\tif err != nil {\n\t\treturn transport\n\t}\n\tif ip.To4() != nil {\n\t\treturn transport + \"4\"\n\t}\n\treturn transport + \"6\"\n}\n\nfunc (c internalConn) EstablishedAt() time.Time {\n<|edits_diff|>\n--- lib/connections/structs.go\n+++ lib/connections/structs.go\n@@ -20,6 +20,7 @@\n type internalConn struct {\n \ttlsConn\n \tconnType connType\n+\tisLocal bool\n \tpriority int\n \testablishedAt time.Time\n }\n<|current_version|>\n\t\"github.com/syncthing/syncthing/lib/nat\"\n\t\"github.com/syncthing/syncthing/lib/osutil\"\n\t\"github.com/syncthing/syncthing/lib/protocol\"\n\t\"github.com/syncthing/syncthing/lib/stats\"\n\n\t\"github.com/thejerf/suture/v4\"\n)\n\ntype tlsConn interface {\n\tio.ReadWriteCloser\n\tConnectionState() tls.ConnectionState\n\tRemoteAddr() net.Addr\n\tSetDeadline(time.Time) error\n\tSetWriteDeadline(time.Time) error\n\tLocalAddr() net.Addr\n}\n\n// internalConn is the raw TLS connection plus some metadata on where it\n// came from (type, priority).\ntype internalConn struct {\n\ttlsConn\n\tconnType connType\n\tisLocal bool\n\tpriority int\n\testablishedAt time.Time\n}\n\ntype connType int\n\nconst (\n\tconnTypeRelayClient connType = iota\n\tconnTypeRelayServer\n\tconnTypeTCPClient\n\tconnTypeTCPServer\n\tconnTypeQUICClient\n\tconnTypeQUICServer\n)\n\nfunc (t connType) String() string {\n\tswitch t {\n\tcase connTypeRelayClient:\n\t\treturn \"relay-client\"\n\tcase connTypeRelayServer:\n\t\treturn \"relay-server\"\n\tcase connTypeTCPClient:\n\t\treturn \"tcp-client\"\n\tcase connTypeTCPServer:\n\t\treturn \"tcp-server\"\n\tcase connTypeQUICClient:\n\t\treturn \"quic-client\"\n\tcase connTypeQUICServer:\n\t\treturn \"quic-server\"\n\tdefault:\n\t\treturn \"unknown-type\"\n\t}\n}\n\nfunc (t connType) Transport() string {\n\tswitch t {\n\tcase connTypeRelayClient, connTypeRelayServer:\n\t\treturn \"relay\"\n\tcase connTypeTCPClient, connTypeTCPServer:\n\t\treturn \"tcp\"\n\tcase connTypeQUICClient, connTypeQUICServer:\n\t\treturn \"quic\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc newInternalConn(tc tlsConn, connType connType, priority int) internalConn {\n\treturn internalConn{\n\t\ttlsConn: tc,\n\t\tconnType: connType,\n\t\tpriority: priority,\n\t\testablishedAt: time.Now().Truncate(time.Second),\n\t}\n}\n\nfunc (c internalConn) Close() error {\n\t// *tls.Conn.Close() does more than it says on the tin. Specifically, it\n\t// sends a TLS alert message, which might block forever if the\n\t// connection is dead and we don't have a deadline set.\n\t_ = c.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))\n\treturn c.tlsConn.Close()\n}\n\nfunc (c internalConn) Type() string {\n\treturn c.connType.String()\n}\n\nfunc (c internalConn) Priority() int {\n\treturn c.priority\n}\n\nfunc (c internalConn) Crypto() string {\n\tcs := c.ConnectionState()\n\treturn fmt.Sprintf(\"%s-%s\", tlsVersionNames[cs.Version], tlsCipherSuiteNames[cs.CipherSuite])\n}\n\nfunc (c internalConn) Transport() string {\n\ttransport := c.connType.Transport()\n\tip, err := osutil.IPFromAddr(c.LocalAddr())\n\tif err != nil {\n\t\treturn transport\n\t}\n\tif ip.To4() != nil {\n\t\treturn transport + \"4\"\n\t}\n\treturn transport + \"6\"\n}\n\nfunc (c internalConn) EstablishedAt() time.Time {\n<|next_version|>\n\t\"github.com/syncthing/syncthing/lib/nat\"\n\t\"github.com/syncthing/syncthing/lib/osutil\"\n\t\"github.com/syncthing/syncthing/lib/protocol\"\n\t\"github.com/syncthing/syncthing/lib/stats\"\n\n\t\"github.com/thejerf/suture/v4\"\n)\n\ntype tlsConn interface {\n\tio.ReadWriteCloser\n\tConnectionState() tls.ConnectionState\n\tRemoteAddr() net.Addr\n\tSetDeadline(time.Time) error\n\tSetWriteDeadline(time.Time) error\n\tLocalAddr() net.Addr\n}\n\n// internalConn is the raw TLS connection plus some metadata on where it\n// came from (type, priority).\ntype internalConn struct {\n\ttlsConn\n\tconnType connType\n\tisLocal bool\n\tpriority int\n\testablishedAt time.Time\n}\n\ntype connType int\n\nconst (\n\tconnTypeRelayClient connType = iota\n\tconnTypeRelayServer\n\tconnTypeTCPClient\n\tconnTypeTCPServer\n\tconnTypeQUICClient\n\tconnTypeQUICServer\n)\n\nfunc (t connType) String() string {\n\tswitch t {\n\tcase connTypeRelayClient:\n\t\treturn \"relay-client\"\n\tcase connTypeRelayServer:\n\t\treturn \"relay-server\"\n\tcase connTypeTCPClient:\n\t\treturn \"tcp-client\"\n\tcase connTypeTCPServer:\n\t\treturn \"tcp-server\"\n\tcase connTypeQUICClient:\n\t\treturn \"quic-client\"\n\tcase connTypeQUICServer:\n\t\treturn \"quic-server\"\n\tdefault:\n\t\treturn \"unknown-type\"\n\t}\n}\n\nfunc (t connType) Transport() string {\n\tswitch t {\n\tcase connTypeRelayClient, connTypeRelayServer:\n\t\treturn \"relay\"\n\tcase connTypeTCPClient, connTypeTCPServer:\n\t\treturn \"tcp\"\n\tcase connTypeQUICClient, connTypeQUICServer:\n\t\treturn \"quic\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc newInternalConn(tc tlsConn, connType connType, priority int) internalConn {\n\treturn internalConn{\n\t\ttlsConn: tc,\n\t\tconnType: connType,\n\t\tpriority: priority,\n\t\testablishedAt: time.Now().Truncate(time.Second),\n\t}\n}\n\nfunc (c internalConn) Close() error {\n\t// *tls.Conn.Close() does more than it says on the tin. Specifically, it\n\t// sends a TLS alert message, which might block forever if the\n\t// connection is dead and we don't have a deadline set.\n\t_ = c.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))\n\treturn c.tlsConn.Close()\n}\n\nfunc (c internalConn) Type() string {\n\treturn c.connType.String()\n}\n\nfunc (c internalConn) IsLocal() bool {\n\treturn c.isLocal\n}\n\nfunc (c internalConn) Priority() int {\n\treturn c.priority\n}\n\nfunc (c internalConn) Crypto() string {\n\tcs := c.ConnectionState()\n\treturn fmt.Sprintf(\"%s-%s\", tlsVersionNames[cs.Version], tlsCipherSuiteNames[cs.CipherSuite])\n}\n\nfunc (c internalConn) Transport() string {\n\ttransport := c.connType.Transport()\n\tip, err := osutil.IPFromAddr(c.LocalAddr())\n\tif err != nil {\n\t\treturn transport\n\t}\n\tif ip.To4() != nil {\n\t\treturn transport + \"4\"\n\t}\n\treturn transport + \"6\"\n}\n\nfunc (c internalConn) EstablishedAt() time.Time {\n", "current_contents": "\t\"github.com/syncthing/syncthing/lib/nat\"\n\t\"github.com/syncthing/syncthing/lib/osutil\"\n\t\"github.com/syncthing/syncthing/lib/protocol\"\n\t\"github.com/syncthing/syncthing/lib/stats\"\n\n\t\"github.com/thejerf/suture/v4\"\n)\n\ntype tlsConn interface {\n\tio.ReadWriteCloser\n\tConnectionState() tls.ConnectionState\n\tRemoteAddr() net.Addr\n\tSetDeadline(time.Time) error\n\tSetWriteDeadline(time.Time) error\n\tLocalAddr() net.Addr\n}\n\n// internalConn is the raw TLS connection plus some metadata on where it\n// came from (type, priority).\ntype internalConn struct {\n\ttlsConn\n\tconnType connType\n\tisLocal bool\n\tpriority int\n\testablishedAt time.Time\n}\n\ntype connType int\n\nconst (\n\tconnTypeRelayClient connType = iota\n\tconnTypeRelayServer\n\tconnTypeTCPClient\n\tconnTypeTCPServer\n\tconnTypeQUICClient\n\tconnTypeQUICServer\n)\n\nfunc (t connType) String() string {\n\tswitch t {\n\tcase connTypeRelayClient:\n\t\treturn \"relay-client\"\n\tcase connTypeRelayServer:\n\t\treturn \"relay-server\"\n\tcase connTypeTCPClient:\n\t\treturn \"tcp-client\"\n\tcase connTypeTCPServer:\n\t\treturn \"tcp-server\"\n\tcase connTypeQUICClient:\n\t\treturn \"quic-client\"\n\tcase connTypeQUICServer:\n\t\treturn \"quic-server\"\n\tdefault:\n\t\treturn \"unknown-type\"\n\t}\n}\n\nfunc (t connType) Transport() string {\n\tswitch t {\n\tcase connTypeRelayClient, connTypeRelayServer:\n\t\treturn \"relay\"\n\tcase connTypeTCPClient, connTypeTCPServer:\n\t\treturn \"tcp\"\n\tcase connTypeQUICClient, connTypeQUICServer:\n\t\treturn \"quic\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc newInternalConn(tc tlsConn, connType connType, priority int) internalConn {\n\treturn internalConn{\n\t\ttlsConn: tc,\n\t\tconnType: connType,\n\t\tpriority: priority,\n\t\testablishedAt: time.Now().Truncate(time.Second),\n\t}\n}\n\nfunc (c internalConn) Close() error {\n\t// *tls.Conn.Close() does more than it says on the tin. Specifically, it\n\t// sends a TLS alert message, which might block forever if the\n\t// connection is dead and we don't have a deadline set.\n\t_ = c.SetWriteDeadline(time.Now().Add(250 * time.Millisecond))\n\treturn c.tlsConn.Close()\n}\n\nfunc (c internalConn) Type() string {\n\treturn c.connType.String()\n}\n\nfunc (c internalConn) Priority() int {\n\treturn c.priority\n}\n\nfunc (c internalConn) Crypto() string {\n\tcs := c.ConnectionState()\n\treturn fmt.Sprintf(\"%s-%s\", tlsVersionNames[cs.Version], tlsCipherSuiteNames[cs.CipherSuite])\n}\n\nfunc (c internalConn) Transport() string {\n\ttransport := c.connType.Transport()\n\tip, err := osutil.IPFromAddr(c.LocalAddr())\n\tif err != nil {\n\t\treturn transport\n\t}\n\tif ip.To4() != nil {\n\t\treturn transport + \"4\"\n\t}\n\treturn transport + \"6\"\n}\n\nfunc (c internalConn) EstablishedAt() time.Time {"} {"commit": "eeb709118024dca017e0c0dd948120b27d55b3a4", "message": "lib/model: Missing fmut-lock on encryption failures (#7841)", "old_file": "lib/model/model.go", "new_file": "lib/model/model.go", "status": "M", "old_contents": "\t\t\tm.evLogger.Log(events.FolderRejected, map[string]string{\n\t\t\t\t\"folder\": folder.ID,\n\t\t\t\t\"folderLabel\": folder.Label,\n\t\t\t\t\"device\": deviceID.String(),\n\t\t\t})\n\t\t\tl.Infof(\"Unexpected folder %s sent from device %q; ensure that the folder exists and that this device is selected under \\\"Share With\\\" in the folder configuration.\", folder.Description(), deviceID)\n\t\t\tcontinue\n\t\t}\n\n\t\tif folder.Paused {\n\t\t\tindexHandlers.Remove(folder.ID)\n\t\t\tpaused[cfg.ID] = struct{}{}\n\t\t\tcontinue\n\t\t}\n\n\t\tif cfg.Paused {\n\t\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.ccCheckEncryption(cfg, folderDevice, ccDeviceInfos[folder.ID], deviceCfg.Untrusted); err != nil {\n\t\t\tsameError := false\n\t\t\tif devs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\t\tsameError = devs[deviceID] == err\n\t\t\t} else {\n\t\t\t\tm.folderEncryptionFailures[folder.ID] = make(map[protocol.DeviceID]error)\n\t\t\t}\n\t\t\tm.folderEncryptionFailures[folder.ID][deviceID] = err\n\t\t\tmsg := fmt.Sprintf(\"Failure checking encryption consistency with device %v for folder %v: %v\", deviceID, cfg.Description(), err)\n\t\t\tif sameError {\n\t\t\t\tl.Debugln(msg)\n\t\t\t} else {\n\t\t\t\tif rerr, ok := err.(*redactedError); ok {\n\t\t\t\t\terr = rerr.redacted\n\t\t\t\t}\n\t\t\t\tm.evLogger.Log(events.Failure, err.Error())\n\t\t\t\tl.Warnln(msg)\n\t\t\t}\n\t\t\treturn tempIndexFolders, paused, err\n\t\t}\n\t\tif devErrs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\tif len(devErrs) == 1 {\n\t\t\t\tdelete(m.folderEncryptionFailures, folder.ID)\n\t\t\t} else {\n\t\t\t\tdelete(m.folderEncryptionFailures[folder.ID], deviceID)\n\t\t\t}\n\t\t}\n\n\t\t// Handle indexes\n\n\t\tif !folder.DisableTempIndexes {\n\t\t\ttempIndexFolders = append(tempIndexFolders, folder.ID)\n\t\t}\n\n\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t}\n\n\tindexHandlers.RemoveAllExcept(seenFolders)\n\texpiredPendingList := make([]map[string]string, 0, len(expiredPending))\n\tfor folder := range expiredPending {\n\t\tif err = m.db.RemovePendingFolderForDevice(folder, deviceID); err != nil {\n\t\t\tmsg := \"Failed to remove pending folder-device entry\"\n\t\t\tl.Warnf(\"%v (%v, %v): %v\", msg, folder, deviceID, err)\n\t\t\tm.evLogger.Log(events.Failure, msg)\n\t\t\tcontinue\n\t\t}\n\t\texpiredPendingList = append(expiredPendingList, map[string]string{\n\t\t\t\"folderID\": folder,\n\t\t\t\"deviceID\": deviceID.String(),\n\t\t})\n\t}", "new_contents": "\t\t\tm.evLogger.Log(events.FolderRejected, map[string]string{\n\t\t\t\t\"folder\": folder.ID,\n\t\t\t\t\"folderLabel\": folder.Label,\n\t\t\t\t\"device\": deviceID.String(),\n\t\t\t})\n\t\t\tl.Infof(\"Unexpected folder %s sent from device %q; ensure that the folder exists and that this device is selected under \\\"Share With\\\" in the folder configuration.\", folder.Description(), deviceID)\n\t\t\tcontinue\n\t\t}\n\n\t\tif folder.Paused {\n\t\t\tindexHandlers.Remove(folder.ID)\n\t\t\tpaused[cfg.ID] = struct{}{}\n\t\t\tcontinue\n\t\t}\n\n\t\tif cfg.Paused {\n\t\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.ccCheckEncryption(cfg, folderDevice, ccDeviceInfos[folder.ID], deviceCfg.Untrusted); err != nil {\n\t\t\tsameError := false\n\t\t\tm.fmut.Lock()\n\t\t\tif devs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\t\tsameError = devs[deviceID] == err\n\t\t\t} else {\n\t\t\t\tm.folderEncryptionFailures[folder.ID] = make(map[protocol.DeviceID]error)\n\t\t\t}\n\t\t\tm.folderEncryptionFailures[folder.ID][deviceID] = err\n\t\t\tm.fmut.Unlock()\n\t\t\tmsg := fmt.Sprintf(\"Failure checking encryption consistency with device %v for folder %v: %v\", deviceID, cfg.Description(), err)\n\t\t\tif sameError {\n\t\t\t\tl.Debugln(msg)\n\t\t\t} else {\n\t\t\t\tif rerr, ok := err.(*redactedError); ok {\n\t\t\t\t\terr = rerr.redacted\n\t\t\t\t}\n\t\t\t\tm.evLogger.Log(events.Failure, err.Error())\n\t\t\t\tl.Warnln(msg)\n\t\t\t}\n\t\t\treturn tempIndexFolders, paused, err\n\t\t}\n\t\tm.fmut.Lock()\n\t\tif devErrs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\tif len(devErrs) == 1 {\n\t\t\t\tdelete(m.folderEncryptionFailures, folder.ID)\n\t\t\t} else {\n\t\t\t\tdelete(m.folderEncryptionFailures[folder.ID], deviceID)\n\t\t\t}\n\t\t}\n\t\tm.fmut.Unlock()\n\n\t\t// Handle indexes\n\n\t\tif !folder.DisableTempIndexes {\n\t\t\ttempIndexFolders = append(tempIndexFolders, folder.ID)\n\t\t}\n\n\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t}\n\n\tindexHandlers.RemoveAllExcept(seenFolders)\n\texpiredPendingList := make([]map[string]string, 0, len(expiredPending))\n\tfor folder := range expiredPending {\n\t\tif err = m.db.RemovePendingFolderForDevice(folder, deviceID); err != nil {\n\t\t\tmsg := \"Failed to remove pending folder-device entry\"\n\t\t\tl.Warnf(\"%v (%v, %v): %v\", msg, folder, deviceID, err)\n\t\t\tm.evLogger.Log(events.Failure, msg)\n\t\t\tcontinue\n\t\t}\n\t\texpiredPendingList = append(expiredPendingList, map[string]string{\n\t\t\t\"folderID\": folder,\n\t\t\t\"deviceID\": deviceID.String(),\n\t\t})\n\t}", "text": "<|original_code|>\n\t\t\tm.evLogger.Log(events.FolderRejected, map[string]string{\n\t\t\t\t\"folder\": folder.ID,\n\t\t\t\t\"folderLabel\": folder.Label,\n\t\t\t\t\"device\": deviceID.String(),\n\t\t\t})\n\t\t\tl.Infof(\"Unexpected folder %s sent from device %q; ensure that the folder exists and that this device is selected under \\\"Share With\\\" in the folder configuration.\", folder.Description(), deviceID)\n\t\t\tcontinue\n\t\t}\n\n\t\tif folder.Paused {\n\t\t\tindexHandlers.Remove(folder.ID)\n\t\t\tpaused[cfg.ID] = struct{}{}\n\t\t\tcontinue\n\t\t}\n\n\t\tif cfg.Paused {\n\t\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.ccCheckEncryption(cfg, folderDevice, ccDeviceInfos[folder.ID], deviceCfg.Untrusted); err != nil {\n\t\t\tsameError := false\n\t\t\tif devs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\t\tsameError = devs[deviceID] == err\n\t\t\t} else {\n\t\t\t\tm.folderEncryptionFailures[folder.ID] = make(map[protocol.DeviceID]error)\n\t\t\t}\n\t\t\tm.folderEncryptionFailures[folder.ID][deviceID] = err\n\t\t\tmsg := fmt.Sprintf(\"Failure checking encryption consistency with device %v for folder %v: %v\", deviceID, cfg.Description(), err)\n\t\t\tif sameError {\n\t\t\t\tl.Debugln(msg)\n\t\t\t} else {\n\t\t\t\tif rerr, ok := err.(*redactedError); ok {\n\t\t\t\t\terr = rerr.redacted\n\t\t\t\t}\n\t\t\t\tm.evLogger.Log(events.Failure, err.Error())\n\t\t\t\tl.Warnln(msg)\n\t\t\t}\n\t\t\treturn tempIndexFolders, paused, err\n\t\t}\n\t\tif devErrs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\tif len(devErrs) == 1 {\n\t\t\t\tdelete(m.folderEncryptionFailures, folder.ID)\n\t\t\t} else {\n\t\t\t\tdelete(m.folderEncryptionFailures[folder.ID], deviceID)\n\t\t\t}\n\t\t}\n\n\t\t// Handle indexes\n\n\t\tif !folder.DisableTempIndexes {\n\t\t\ttempIndexFolders = append(tempIndexFolders, folder.ID)\n\t\t}\n\n\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t}\n\n\tindexHandlers.RemoveAllExcept(seenFolders)\n\texpiredPendingList := make([]map[string]string, 0, len(expiredPending))\n\tfor folder := range expiredPending {\n\t\tif err = m.db.RemovePendingFolderForDevice(folder, deviceID); err != nil {\n\t\t\tmsg := \"Failed to remove pending folder-device entry\"\n\t\t\tl.Warnf(\"%v (%v, %v): %v\", msg, folder, deviceID, err)\n\t\t\tm.evLogger.Log(events.Failure, msg)\n\t\t\tcontinue\n\t\t}\n\t\texpiredPendingList = append(expiredPendingList, map[string]string{\n\t\t\t\"folderID\": folder,\n\t\t\t\"deviceID\": deviceID.String(),\n\t\t})\n\t}\n<|edits_diff|>\n--- lib/model/model.go\n+++ lib/model/model.go\n@@ -20,12 +20,14 @@\n \n \t\tif err := m.ccCheckEncryption(cfg, folderDevice, ccDeviceInfos[folder.ID], deviceCfg.Untrusted); err != nil {\n \t\t\tsameError := false\n+\t\t\tm.fmut.Lock()\n \t\t\tif devs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n \t\t\t\tsameError = devs[deviceID] == err\n \t\t\t} else {\n \t\t\t\tm.folderEncryptionFailures[folder.ID] = make(map[protocol.DeviceID]error)\n \t\t\t}\n \t\t\tm.folderEncryptionFailures[folder.ID][deviceID] = err\n+\t\t\tm.fmut.Unlock()\n \t\t\tmsg := fmt.Sprintf(\"Failure checking encryption consistency with device %v for folder %v: %v\", deviceID, cfg.Description(), err)\n \t\t\tif sameError {\n \t\t\t\tl.Debugln(msg)\n@@ -38,6 +40,7 @@\n \t\t\t}\n \t\t\treturn tempIndexFolders, paused, err\n \t\t}\n+\t\tm.fmut.Lock()\n \t\tif devErrs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n \t\t\tif len(devErrs) == 1 {\n \t\t\t\tdelete(m.folderEncryptionFailures, folder.ID)\n<|current_version|>\n\t\t\tm.evLogger.Log(events.FolderRejected, map[string]string{\n\t\t\t\t\"folder\": folder.ID,\n\t\t\t\t\"folderLabel\": folder.Label,\n\t\t\t\t\"device\": deviceID.String(),\n\t\t\t})\n\t\t\tl.Infof(\"Unexpected folder %s sent from device %q; ensure that the folder exists and that this device is selected under \\\"Share With\\\" in the folder configuration.\", folder.Description(), deviceID)\n\t\t\tcontinue\n\t\t}\n\n\t\tif folder.Paused {\n\t\t\tindexHandlers.Remove(folder.ID)\n\t\t\tpaused[cfg.ID] = struct{}{}\n\t\t\tcontinue\n\t\t}\n\n\t\tif cfg.Paused {\n\t\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.ccCheckEncryption(cfg, folderDevice, ccDeviceInfos[folder.ID], deviceCfg.Untrusted); err != nil {\n\t\t\tsameError := false\n\t\t\tm.fmut.Lock()\n\t\t\tif devs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\t\tsameError = devs[deviceID] == err\n\t\t\t} else {\n\t\t\t\tm.folderEncryptionFailures[folder.ID] = make(map[protocol.DeviceID]error)\n\t\t\t}\n\t\t\tm.folderEncryptionFailures[folder.ID][deviceID] = err\n\t\t\tm.fmut.Unlock()\n\t\t\tmsg := fmt.Sprintf(\"Failure checking encryption consistency with device %v for folder %v: %v\", deviceID, cfg.Description(), err)\n\t\t\tif sameError {\n\t\t\t\tl.Debugln(msg)\n\t\t\t} else {\n\t\t\t\tif rerr, ok := err.(*redactedError); ok {\n\t\t\t\t\terr = rerr.redacted\n\t\t\t\t}\n\t\t\t\tm.evLogger.Log(events.Failure, err.Error())\n\t\t\t\tl.Warnln(msg)\n\t\t\t}\n\t\t\treturn tempIndexFolders, paused, err\n\t\t}\n\t\tm.fmut.Lock()\n\t\tif devErrs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\tif len(devErrs) == 1 {\n\t\t\t\tdelete(m.folderEncryptionFailures, folder.ID)\n\t\t\t} else {\n\t\t\t\tdelete(m.folderEncryptionFailures[folder.ID], deviceID)\n\t\t\t}\n\t\t}\n\n\t\t// Handle indexes\n\n\t\tif !folder.DisableTempIndexes {\n\t\t\ttempIndexFolders = append(tempIndexFolders, folder.ID)\n\t\t}\n\n\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t}\n\n\tindexHandlers.RemoveAllExcept(seenFolders)\n\texpiredPendingList := make([]map[string]string, 0, len(expiredPending))\n\tfor folder := range expiredPending {\n\t\tif err = m.db.RemovePendingFolderForDevice(folder, deviceID); err != nil {\n\t\t\tmsg := \"Failed to remove pending folder-device entry\"\n\t\t\tl.Warnf(\"%v (%v, %v): %v\", msg, folder, deviceID, err)\n\t\t\tm.evLogger.Log(events.Failure, msg)\n\t\t\tcontinue\n\t\t}\n\t\texpiredPendingList = append(expiredPendingList, map[string]string{\n\t\t\t\"folderID\": folder,\n\t\t\t\"deviceID\": deviceID.String(),\n\t\t})\n\t}\n<|next_version|>\n\t\t\tm.evLogger.Log(events.FolderRejected, map[string]string{\n\t\t\t\t\"folder\": folder.ID,\n\t\t\t\t\"folderLabel\": folder.Label,\n\t\t\t\t\"device\": deviceID.String(),\n\t\t\t})\n\t\t\tl.Infof(\"Unexpected folder %s sent from device %q; ensure that the folder exists and that this device is selected under \\\"Share With\\\" in the folder configuration.\", folder.Description(), deviceID)\n\t\t\tcontinue\n\t\t}\n\n\t\tif folder.Paused {\n\t\t\tindexHandlers.Remove(folder.ID)\n\t\t\tpaused[cfg.ID] = struct{}{}\n\t\t\tcontinue\n\t\t}\n\n\t\tif cfg.Paused {\n\t\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.ccCheckEncryption(cfg, folderDevice, ccDeviceInfos[folder.ID], deviceCfg.Untrusted); err != nil {\n\t\t\tsameError := false\n\t\t\tm.fmut.Lock()\n\t\t\tif devs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\t\tsameError = devs[deviceID] == err\n\t\t\t} else {\n\t\t\t\tm.folderEncryptionFailures[folder.ID] = make(map[protocol.DeviceID]error)\n\t\t\t}\n\t\t\tm.folderEncryptionFailures[folder.ID][deviceID] = err\n\t\t\tm.fmut.Unlock()\n\t\t\tmsg := fmt.Sprintf(\"Failure checking encryption consistency with device %v for folder %v: %v\", deviceID, cfg.Description(), err)\n\t\t\tif sameError {\n\t\t\t\tl.Debugln(msg)\n\t\t\t} else {\n\t\t\t\tif rerr, ok := err.(*redactedError); ok {\n\t\t\t\t\terr = rerr.redacted\n\t\t\t\t}\n\t\t\t\tm.evLogger.Log(events.Failure, err.Error())\n\t\t\t\tl.Warnln(msg)\n\t\t\t}\n\t\t\treturn tempIndexFolders, paused, err\n\t\t}\n\t\tm.fmut.Lock()\n\t\tif devErrs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\tif len(devErrs) == 1 {\n\t\t\t\tdelete(m.folderEncryptionFailures, folder.ID)\n\t\t\t} else {\n\t\t\t\tdelete(m.folderEncryptionFailures[folder.ID], deviceID)\n\t\t\t}\n\t\t}\n\t\tm.fmut.Unlock()\n\n\t\t// Handle indexes\n\n\t\tif !folder.DisableTempIndexes {\n\t\t\ttempIndexFolders = append(tempIndexFolders, folder.ID)\n\t\t}\n\n\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t}\n\n\tindexHandlers.RemoveAllExcept(seenFolders)\n\texpiredPendingList := make([]map[string]string, 0, len(expiredPending))\n\tfor folder := range expiredPending {\n\t\tif err = m.db.RemovePendingFolderForDevice(folder, deviceID); err != nil {\n\t\t\tmsg := \"Failed to remove pending folder-device entry\"\n\t\t\tl.Warnf(\"%v (%v, %v): %v\", msg, folder, deviceID, err)\n\t\t\tm.evLogger.Log(events.Failure, msg)\n\t\t\tcontinue\n\t\t}\n\t\texpiredPendingList = append(expiredPendingList, map[string]string{\n\t\t\t\"folderID\": folder,\n\t\t\t\"deviceID\": deviceID.String(),\n\t\t})\n\t}\n", "current_contents": "\t\t\tm.evLogger.Log(events.FolderRejected, map[string]string{\n\t\t\t\t\"folder\": folder.ID,\n\t\t\t\t\"folderLabel\": folder.Label,\n\t\t\t\t\"device\": deviceID.String(),\n\t\t\t})\n\t\t\tl.Infof(\"Unexpected folder %s sent from device %q; ensure that the folder exists and that this device is selected under \\\"Share With\\\" in the folder configuration.\", folder.Description(), deviceID)\n\t\t\tcontinue\n\t\t}\n\n\t\tif folder.Paused {\n\t\t\tindexHandlers.Remove(folder.ID)\n\t\t\tpaused[cfg.ID] = struct{}{}\n\t\t\tcontinue\n\t\t}\n\n\t\tif cfg.Paused {\n\t\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t\t\tcontinue\n\t\t}\n\n\t\tif err := m.ccCheckEncryption(cfg, folderDevice, ccDeviceInfos[folder.ID], deviceCfg.Untrusted); err != nil {\n\t\t\tsameError := false\n\t\t\tm.fmut.Lock()\n\t\t\tif devs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\t\tsameError = devs[deviceID] == err\n\t\t\t} else {\n\t\t\t\tm.folderEncryptionFailures[folder.ID] = make(map[protocol.DeviceID]error)\n\t\t\t}\n\t\t\tm.folderEncryptionFailures[folder.ID][deviceID] = err\n\t\t\tm.fmut.Unlock()\n\t\t\tmsg := fmt.Sprintf(\"Failure checking encryption consistency with device %v for folder %v: %v\", deviceID, cfg.Description(), err)\n\t\t\tif sameError {\n\t\t\t\tl.Debugln(msg)\n\t\t\t} else {\n\t\t\t\tif rerr, ok := err.(*redactedError); ok {\n\t\t\t\t\terr = rerr.redacted\n\t\t\t\t}\n\t\t\t\tm.evLogger.Log(events.Failure, err.Error())\n\t\t\t\tl.Warnln(msg)\n\t\t\t}\n\t\t\treturn tempIndexFolders, paused, err\n\t\t}\n\t\tm.fmut.Lock()\n\t\tif devErrs, ok := m.folderEncryptionFailures[folder.ID]; ok {\n\t\t\tif len(devErrs) == 1 {\n\t\t\t\tdelete(m.folderEncryptionFailures, folder.ID)\n\t\t\t} else {\n\t\t\t\tdelete(m.folderEncryptionFailures[folder.ID], deviceID)\n\t\t\t}\n\t\t}\n\n\t\t// Handle indexes\n\n\t\tif !folder.DisableTempIndexes {\n\t\t\ttempIndexFolders = append(tempIndexFolders, folder.ID)\n\t\t}\n\n\t\tindexHandlers.AddIndexInfo(folder.ID, ccDeviceInfos[folder.ID])\n\t}\n\n\tindexHandlers.RemoveAllExcept(seenFolders)\n\texpiredPendingList := make([]map[string]string, 0, len(expiredPending))\n\tfor folder := range expiredPending {\n\t\tif err = m.db.RemovePendingFolderForDevice(folder, deviceID); err != nil {\n\t\t\tmsg := \"Failed to remove pending folder-device entry\"\n\t\t\tl.Warnf(\"%v (%v, %v): %v\", msg, folder, deviceID, err)\n\t\t\tm.evLogger.Log(events.Failure, msg)\n\t\t\tcontinue\n\t\t}\n\t\texpiredPendingList = append(expiredPendingList, map[string]string{\n\t\t\t\"folderID\": folder,\n\t\t\t\"deviceID\": deviceID.String(),\n\t\t})\n\t}"} {"commit": "31559e908be43778c00014f6f580999dc77019c8", "message": "all: Add untrusted folders behind feature flag (ref #62) (#7055)", "old_file": "lib/config/foldertype.go", "new_file": "lib/config/foldertype.go", "status": "M", "old_contents": "// Copyright (C) 2016 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage config\n\nfunc (t FolderType) String() string {\n\tswitch t {\n\tcase FolderTypeSendReceive:\n\t\treturn \"sendreceive\"\n\tcase FolderTypeSendOnly:\n\t\treturn \"sendonly\"\n\tcase FolderTypeReceiveOnly:\n\t\treturn \"receiveonly\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc (t FolderType) MarshalText() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}\n\nfunc (t *FolderType) UnmarshalText(bs []byte) error {\n\tswitch string(bs) {\n\tcase \"readwrite\", \"sendreceive\":\n\t\t*t = FolderTypeSendReceive\n\tcase \"readonly\", \"sendonly\":\n\t\t*t = FolderTypeSendOnly\n\tcase \"receiveonly\":\n\t\t*t = FolderTypeReceiveOnly\n\tdefault:\n\t\t*t = FolderTypeSendReceive\n\t}\n\treturn nil\n}\n", "new_contents": "// Copyright (C) 2016 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage config\n\nfunc (t FolderType) String() string {\n\tswitch t {\n\tcase FolderTypeSendReceive:\n\t\treturn \"sendreceive\"\n\tcase FolderTypeSendOnly:\n\t\treturn \"sendonly\"\n\tcase FolderTypeReceiveOnly:\n\t\treturn \"receiveonly\"\n\tcase FolderTypeReceiveEncrypted:\n\t\treturn \"receiveencrypted\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc (t FolderType) MarshalText() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}\n\nfunc (t *FolderType) UnmarshalText(bs []byte) error {\n\tswitch string(bs) {\n\tcase \"readwrite\", \"sendreceive\":\n\t\t*t = FolderTypeSendReceive\n\tcase \"readonly\", \"sendonly\":\n\t\t*t = FolderTypeSendOnly\n\tcase \"receiveonly\":\n\t\t*t = FolderTypeReceiveOnly\n\tcase \"receiveencrypted\":\n\t\t*t = FolderTypeReceiveEncrypted\n\tdefault:\n\t\t*t = FolderTypeSendReceive\n\t}\n\treturn nil\n}\n", "text": "<|original_code|>\n// Copyright (C) 2016 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage config\n\nfunc (t FolderType) String() string {\n\tswitch t {\n\tcase FolderTypeSendReceive:\n\t\treturn \"sendreceive\"\n\tcase FolderTypeSendOnly:\n\t\treturn \"sendonly\"\n\tcase FolderTypeReceiveOnly:\n\t\treturn \"receiveonly\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc (t FolderType) MarshalText() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}\n\nfunc (t *FolderType) UnmarshalText(bs []byte) error {\n\tswitch string(bs) {\n\tcase \"readwrite\", \"sendreceive\":\n\t\t*t = FolderTypeSendReceive\n\tcase \"readonly\", \"sendonly\":\n\t\t*t = FolderTypeSendOnly\n\tcase \"receiveonly\":\n\t\t*t = FolderTypeReceiveOnly\n\tdefault:\n\t\t*t = FolderTypeSendReceive\n\t}\n\treturn nil\n}\n\n<|edits_diff|>\n--- lib/config/foldertype.go\n+++ lib/config/foldertype.go\n@@ -14,6 +14,8 @@\n \t\treturn \"sendonly\"\n \tcase FolderTypeReceiveOnly:\n \t\treturn \"receiveonly\"\n+\tcase FolderTypeReceiveEncrypted:\n+\t\treturn \"receiveencrypted\"\n \tdefault:\n \t\treturn \"unknown\"\n \t}\n<|current_version|>\n// Copyright (C) 2016 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage config\n\nfunc (t FolderType) String() string {\n\tswitch t {\n\tcase FolderTypeSendReceive:\n\t\treturn \"sendreceive\"\n\tcase FolderTypeSendOnly:\n\t\treturn \"sendonly\"\n\tcase FolderTypeReceiveOnly:\n\t\treturn \"receiveonly\"\n\tcase FolderTypeReceiveEncrypted:\n\t\treturn \"receiveencrypted\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc (t FolderType) MarshalText() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}\n\nfunc (t *FolderType) UnmarshalText(bs []byte) error {\n\tswitch string(bs) {\n\tcase \"readwrite\", \"sendreceive\":\n\t\t*t = FolderTypeSendReceive\n\tcase \"readonly\", \"sendonly\":\n\t\t*t = FolderTypeSendOnly\n\tcase \"receiveonly\":\n\t\t*t = FolderTypeReceiveOnly\n\tdefault:\n\t\t*t = FolderTypeSendReceive\n\t}\n\treturn nil\n}\n\n<|next_version|>\n// Copyright (C) 2016 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage config\n\nfunc (t FolderType) String() string {\n\tswitch t {\n\tcase FolderTypeSendReceive:\n\t\treturn \"sendreceive\"\n\tcase FolderTypeSendOnly:\n\t\treturn \"sendonly\"\n\tcase FolderTypeReceiveOnly:\n\t\treturn \"receiveonly\"\n\tcase FolderTypeReceiveEncrypted:\n\t\treturn \"receiveencrypted\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc (t FolderType) MarshalText() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}\n\nfunc (t *FolderType) UnmarshalText(bs []byte) error {\n\tswitch string(bs) {\n\tcase \"readwrite\", \"sendreceive\":\n\t\t*t = FolderTypeSendReceive\n\tcase \"readonly\", \"sendonly\":\n\t\t*t = FolderTypeSendOnly\n\tcase \"receiveonly\":\n\t\t*t = FolderTypeReceiveOnly\n\tcase \"receiveencrypted\":\n\t\t*t = FolderTypeReceiveEncrypted\n\tdefault:\n\t\t*t = FolderTypeSendReceive\n\t}\n\treturn nil\n}\n\n", "current_contents": "// Copyright (C) 2016 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage config\n\nfunc (t FolderType) String() string {\n\tswitch t {\n\tcase FolderTypeSendReceive:\n\t\treturn \"sendreceive\"\n\tcase FolderTypeSendOnly:\n\t\treturn \"sendonly\"\n\tcase FolderTypeReceiveOnly:\n\t\treturn \"receiveonly\"\n\tcase FolderTypeReceiveEncrypted:\n\t\treturn \"receiveencrypted\"\n\tdefault:\n\t\treturn \"unknown\"\n\t}\n}\n\nfunc (t FolderType) MarshalText() ([]byte, error) {\n\treturn []byte(t.String()), nil\n}\n\nfunc (t *FolderType) UnmarshalText(bs []byte) error {\n\tswitch string(bs) {\n\tcase \"readwrite\", \"sendreceive\":\n\t\t*t = FolderTypeSendReceive\n\tcase \"readonly\", \"sendonly\":\n\t\t*t = FolderTypeSendOnly\n\tcase \"receiveonly\":\n\t\t*t = FolderTypeReceiveOnly\n\tdefault:\n\t\t*t = FolderTypeSendReceive\n\t}\n\treturn nil\n}\n"} {"commit": "6976219d6da7309b085d02daeefa305429160b7f", "message": "lib/model: Check dir before deletion when pulling (#6741)", "old_file": "lib/fs/filesystem.go", "new_file": "lib/fs/filesystem.go", "status": "M", "old_contents": "const ModeSetuid = FileMode(os.ModeSetuid)\nconst ModeSticky = FileMode(os.ModeSticky)\nconst ModeSymlink = FileMode(os.ModeSymlink)\nconst ModeType = FileMode(os.ModeType)\nconst PathSeparator = os.PathSeparator\nconst OptAppend = os.O_APPEND\nconst OptCreate = os.O_CREATE\nconst OptExclusive = os.O_EXCL\nconst OptReadOnly = os.O_RDONLY\nconst OptReadWrite = os.O_RDWR\nconst OptSync = os.O_SYNC\nconst OptTruncate = os.O_TRUNC\nconst OptWriteOnly = os.O_WRONLY\n\n// SkipDir is used as a return value from WalkFuncs to indicate that\n// the directory named in the call is to be skipped. It is not returned\n// as an error by any function.\nvar SkipDir = filepath.SkipDir\n\n// IsExist is the equivalent of os.IsExist\nvar IsExist = os.IsExist\n\n// IsNotExist is the equivalent of os.IsNotExist\nvar IsNotExist = os.IsNotExist\n\n// IsPermission is the equivalent of os.IsPermission\nvar IsPermission = os.IsPermission\n\n// IsPathSeparator is the equivalent of os.IsPathSeparator\nvar IsPathSeparator = os.IsPathSeparator\n\nfunc NewFilesystem(fsType FilesystemType, uri string) Filesystem {\n\tvar fs Filesystem\n\tswitch fsType {\n\tcase FilesystemTypeBasic:\n\t\tfs = newBasicFilesystem(uri)\n\tcase FilesystemTypeFake:\n\t\tfs = newFakeFilesystem(uri)\n\tdefault:\n\t\tl.Debugln(\"Unknown filesystem\", fsType, uri)\n\t\tfs = &errorFilesystem{\n\t\t\tfsType: fsType,\n\t\t\turi: uri,\n\t\t\terr: errors.New(\"filesystem with type \" + fsType.String() + \" does not exist.\"),\n\t\t}\n\t}\n\n\tif l.ShouldDebug(\"walkfs\") {", "new_contents": "const ModeSetuid = FileMode(os.ModeSetuid)\nconst ModeSticky = FileMode(os.ModeSticky)\nconst ModeSymlink = FileMode(os.ModeSymlink)\nconst ModeType = FileMode(os.ModeType)\nconst PathSeparator = os.PathSeparator\nconst OptAppend = os.O_APPEND\nconst OptCreate = os.O_CREATE\nconst OptExclusive = os.O_EXCL\nconst OptReadOnly = os.O_RDONLY\nconst OptReadWrite = os.O_RDWR\nconst OptSync = os.O_SYNC\nconst OptTruncate = os.O_TRUNC\nconst OptWriteOnly = os.O_WRONLY\n\n// SkipDir is used as a return value from WalkFuncs to indicate that\n// the directory named in the call is to be skipped. It is not returned\n// as an error by any function.\nvar SkipDir = filepath.SkipDir\n\n// IsExist is the equivalent of os.IsExist\nvar IsExist = os.IsExist\n\n// IsExist is the equivalent of os.ErrExist\nvar ErrExist = os.ErrExist\n\n// IsNotExist is the equivalent of os.IsNotExist\nvar IsNotExist = os.IsNotExist\n\n// ErrNotExist is the equivalent of os.ErrNotExist\nvar ErrNotExist = os.ErrNotExist\n\n// IsPermission is the equivalent of os.IsPermission\nvar IsPermission = os.IsPermission\n\n// IsPathSeparator is the equivalent of os.IsPathSeparator\nvar IsPathSeparator = os.IsPathSeparator\n\nfunc NewFilesystem(fsType FilesystemType, uri string) Filesystem {\n\tvar fs Filesystem\n\tswitch fsType {\n\tcase FilesystemTypeBasic:\n\t\tfs = newBasicFilesystem(uri)\n\tcase FilesystemTypeFake:\n\t\tfs = newFakeFilesystem(uri)\n\tdefault:\n\t\tl.Debugln(\"Unknown filesystem\", fsType, uri)\n\t\tfs = &errorFilesystem{\n\t\t\tfsType: fsType,\n\t\t\turi: uri,\n\t\t\terr: errors.New(\"filesystem with type \" + fsType.String() + \" does not exist.\"),\n\t\t}\n\t}\n\n\tif l.ShouldDebug(\"walkfs\") {", "text": "<|original_code|>\nconst ModeSetuid = FileMode(os.ModeSetuid)\nconst ModeSticky = FileMode(os.ModeSticky)\nconst ModeSymlink = FileMode(os.ModeSymlink)\nconst ModeType = FileMode(os.ModeType)\nconst PathSeparator = os.PathSeparator\nconst OptAppend = os.O_APPEND\nconst OptCreate = os.O_CREATE\nconst OptExclusive = os.O_EXCL\nconst OptReadOnly = os.O_RDONLY\nconst OptReadWrite = os.O_RDWR\nconst OptSync = os.O_SYNC\nconst OptTruncate = os.O_TRUNC\nconst OptWriteOnly = os.O_WRONLY\n\n// SkipDir is used as a return value from WalkFuncs to indicate that\n// the directory named in the call is to be skipped. It is not returned\n// as an error by any function.\nvar SkipDir = filepath.SkipDir\n\n// IsExist is the equivalent of os.IsExist\nvar IsExist = os.IsExist\n\n// IsNotExist is the equivalent of os.IsNotExist\nvar IsNotExist = os.IsNotExist\n\n// IsPermission is the equivalent of os.IsPermission\nvar IsPermission = os.IsPermission\n\n// IsPathSeparator is the equivalent of os.IsPathSeparator\nvar IsPathSeparator = os.IsPathSeparator\n\nfunc NewFilesystem(fsType FilesystemType, uri string) Filesystem {\n\tvar fs Filesystem\n\tswitch fsType {\n\tcase FilesystemTypeBasic:\n\t\tfs = newBasicFilesystem(uri)\n\tcase FilesystemTypeFake:\n\t\tfs = newFakeFilesystem(uri)\n\tdefault:\n\t\tl.Debugln(\"Unknown filesystem\", fsType, uri)\n\t\tfs = &errorFilesystem{\n\t\t\tfsType: fsType,\n\t\t\turi: uri,\n\t\t\terr: errors.New(\"filesystem with type \" + fsType.String() + \" does not exist.\"),\n\t\t}\n\t}\n\n\tif l.ShouldDebug(\"walkfs\") {\n<|edits_diff|>\n--- lib/fs/filesystem.go\n+++ lib/fs/filesystem.go\n@@ -19,6 +19,9 @@\n \n // IsExist is the equivalent of os.IsExist\n var IsExist = os.IsExist\n+\n+// IsExist is the equivalent of os.ErrExist\n+var ErrExist = os.ErrExist\n \n // IsNotExist is the equivalent of os.IsNotExist\n var IsNotExist = os.IsNotExist\n<|current_version|>\nconst ModeSetuid = FileMode(os.ModeSetuid)\nconst ModeSticky = FileMode(os.ModeSticky)\nconst ModeSymlink = FileMode(os.ModeSymlink)\nconst ModeType = FileMode(os.ModeType)\nconst PathSeparator = os.PathSeparator\nconst OptAppend = os.O_APPEND\nconst OptCreate = os.O_CREATE\nconst OptExclusive = os.O_EXCL\nconst OptReadOnly = os.O_RDONLY\nconst OptReadWrite = os.O_RDWR\nconst OptSync = os.O_SYNC\nconst OptTruncate = os.O_TRUNC\nconst OptWriteOnly = os.O_WRONLY\n\n// SkipDir is used as a return value from WalkFuncs to indicate that\n// the directory named in the call is to be skipped. It is not returned\n// as an error by any function.\nvar SkipDir = filepath.SkipDir\n\n// IsExist is the equivalent of os.IsExist\nvar IsExist = os.IsExist\n\n// IsExist is the equivalent of os.ErrExist\nvar ErrExist = os.ErrExist\n\n// IsNotExist is the equivalent of os.IsNotExist\nvar IsNotExist = os.IsNotExist\n\n// IsPermission is the equivalent of os.IsPermission\nvar IsPermission = os.IsPermission\n\n// IsPathSeparator is the equivalent of os.IsPathSeparator\nvar IsPathSeparator = os.IsPathSeparator\n\nfunc NewFilesystem(fsType FilesystemType, uri string) Filesystem {\n\tvar fs Filesystem\n\tswitch fsType {\n\tcase FilesystemTypeBasic:\n\t\tfs = newBasicFilesystem(uri)\n\tcase FilesystemTypeFake:\n\t\tfs = newFakeFilesystem(uri)\n\tdefault:\n\t\tl.Debugln(\"Unknown filesystem\", fsType, uri)\n\t\tfs = &errorFilesystem{\n\t\t\tfsType: fsType,\n\t\t\turi: uri,\n\t\t\terr: errors.New(\"filesystem with type \" + fsType.String() + \" does not exist.\"),\n\t\t}\n\t}\n\n\tif l.ShouldDebug(\"walkfs\") {\n<|next_version|>\nconst ModeSetuid = FileMode(os.ModeSetuid)\nconst ModeSticky = FileMode(os.ModeSticky)\nconst ModeSymlink = FileMode(os.ModeSymlink)\nconst ModeType = FileMode(os.ModeType)\nconst PathSeparator = os.PathSeparator\nconst OptAppend = os.O_APPEND\nconst OptCreate = os.O_CREATE\nconst OptExclusive = os.O_EXCL\nconst OptReadOnly = os.O_RDONLY\nconst OptReadWrite = os.O_RDWR\nconst OptSync = os.O_SYNC\nconst OptTruncate = os.O_TRUNC\nconst OptWriteOnly = os.O_WRONLY\n\n// SkipDir is used as a return value from WalkFuncs to indicate that\n// the directory named in the call is to be skipped. It is not returned\n// as an error by any function.\nvar SkipDir = filepath.SkipDir\n\n// IsExist is the equivalent of os.IsExist\nvar IsExist = os.IsExist\n\n// IsExist is the equivalent of os.ErrExist\nvar ErrExist = os.ErrExist\n\n// IsNotExist is the equivalent of os.IsNotExist\nvar IsNotExist = os.IsNotExist\n\n// ErrNotExist is the equivalent of os.ErrNotExist\nvar ErrNotExist = os.ErrNotExist\n\n// IsPermission is the equivalent of os.IsPermission\nvar IsPermission = os.IsPermission\n\n// IsPathSeparator is the equivalent of os.IsPathSeparator\nvar IsPathSeparator = os.IsPathSeparator\n\nfunc NewFilesystem(fsType FilesystemType, uri string) Filesystem {\n\tvar fs Filesystem\n\tswitch fsType {\n\tcase FilesystemTypeBasic:\n\t\tfs = newBasicFilesystem(uri)\n\tcase FilesystemTypeFake:\n\t\tfs = newFakeFilesystem(uri)\n\tdefault:\n\t\tl.Debugln(\"Unknown filesystem\", fsType, uri)\n\t\tfs = &errorFilesystem{\n\t\t\tfsType: fsType,\n\t\t\turi: uri,\n\t\t\terr: errors.New(\"filesystem with type \" + fsType.String() + \" does not exist.\"),\n\t\t}\n\t}\n\n\tif l.ShouldDebug(\"walkfs\") {\n", "current_contents": "const ModeSetuid = FileMode(os.ModeSetuid)\nconst ModeSticky = FileMode(os.ModeSticky)\nconst ModeSymlink = FileMode(os.ModeSymlink)\nconst ModeType = FileMode(os.ModeType)\nconst PathSeparator = os.PathSeparator\nconst OptAppend = os.O_APPEND\nconst OptCreate = os.O_CREATE\nconst OptExclusive = os.O_EXCL\nconst OptReadOnly = os.O_RDONLY\nconst OptReadWrite = os.O_RDWR\nconst OptSync = os.O_SYNC\nconst OptTruncate = os.O_TRUNC\nconst OptWriteOnly = os.O_WRONLY\n\n// SkipDir is used as a return value from WalkFuncs to indicate that\n// the directory named in the call is to be skipped. It is not returned\n// as an error by any function.\nvar SkipDir = filepath.SkipDir\n\n// IsExist is the equivalent of os.IsExist\nvar IsExist = os.IsExist\n\n// IsExist is the equivalent of os.ErrExist\nvar ErrExist = os.ErrExist\n\n// IsNotExist is the equivalent of os.IsNotExist\nvar IsNotExist = os.IsNotExist\n\n// IsPermission is the equivalent of os.IsPermission\nvar IsPermission = os.IsPermission\n\n// IsPathSeparator is the equivalent of os.IsPathSeparator\nvar IsPathSeparator = os.IsPathSeparator\n\nfunc NewFilesystem(fsType FilesystemType, uri string) Filesystem {\n\tvar fs Filesystem\n\tswitch fsType {\n\tcase FilesystemTypeBasic:\n\t\tfs = newBasicFilesystem(uri)\n\tcase FilesystemTypeFake:\n\t\tfs = newFakeFilesystem(uri)\n\tdefault:\n\t\tl.Debugln(\"Unknown filesystem\", fsType, uri)\n\t\tfs = &errorFilesystem{\n\t\t\tfsType: fsType,\n\t\t\turi: uri,\n\t\t\terr: errors.New(\"filesystem with type \" + fsType.String() + \" does not exist.\"),\n\t\t}\n\t}\n\n\tif l.ShouldDebug(\"walkfs\") {"} {"commit": "55937b61ca1cce722a699bbe6d911691402b91ed", "message": "lib/model: Add global request limiter (fixes #6302) (#6303)", "old_file": "lib/model/bytesemaphore.go", "new_file": "lib/model/bytesemaphore.go", "status": "M", "old_contents": "// Copyright (C) 2018 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage model\n\nimport (\n\t\"sync\"\n)\n\ntype byteSemaphore struct {\n\tmax int\n\tavailable int\n\tmut sync.Mutex\n\tcond *sync.Cond\n}\n\nfunc newByteSemaphore(max int) *byteSemaphore {\n\ts := byteSemaphore{\n\t\tmax: max,\n\t\tavailable: max,\n\t}\n\ts.cond = sync.NewCond(&s.mut)\n\treturn &s\n}\n\nfunc (s *byteSemaphore) take(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tfor bytes > s.available {\n\t\ts.cond.Wait()\n\t\tif bytes > s.max {\n\t\t\tbytes = s.max\n\t\t}\n\t}\n\ts.available -= bytes\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) give(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tif s.available+bytes > s.max {\n\t\ts.available = s.max\n\t} else {\n\t\ts.available += bytes\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) setCapacity(cap int) {\n\ts.mut.Lock()\n\tdiff := cap - s.max\n\ts.max = cap\n\ts.available += diff\n\tif s.available < 0 {\n\t\ts.available = 0\n\t} else if s.available > s.max {\n\t\ts.available = s.max\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n", "new_contents": "// Copyright (C) 2018 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage model\n\nimport (\n\t\"sync\"\n)\n\ntype byteSemaphore struct {\n\tmax int\n\tavailable int\n\tmut sync.Mutex\n\tcond *sync.Cond\n}\n\nfunc newByteSemaphore(max int) *byteSemaphore {\n\tif max < 0 {\n\t\tmax = 0\n\t}\n\ts := byteSemaphore{\n\t\tmax: max,\n\t\tavailable: max,\n\t}\n\ts.cond = sync.NewCond(&s.mut)\n\treturn &s\n}\n\nfunc (s *byteSemaphore) take(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tfor bytes > s.available {\n\t\ts.cond.Wait()\n\t\tif bytes > s.max {\n\t\t\tbytes = s.max\n\t\t}\n\t}\n\ts.available -= bytes\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) give(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tif s.available+bytes > s.max {\n\t\ts.available = s.max\n\t} else {\n\t\ts.available += bytes\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) setCapacity(cap int) {\n\tif cap < 0 {\n\t\tcap = 0\n\t}\n\ts.mut.Lock()\n\tdiff := cap - s.max\n\ts.max = cap\n\ts.available += diff\n\tif s.available < 0 {\n\t\ts.available = 0\n\t} else if s.available > s.max {\n\t\ts.available = s.max\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n", "text": "<|original_code|>\n// Copyright (C) 2018 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage model\n\nimport (\n\t\"sync\"\n)\n\ntype byteSemaphore struct {\n\tmax int\n\tavailable int\n\tmut sync.Mutex\n\tcond *sync.Cond\n}\n\nfunc newByteSemaphore(max int) *byteSemaphore {\n\ts := byteSemaphore{\n\t\tmax: max,\n\t\tavailable: max,\n\t}\n\ts.cond = sync.NewCond(&s.mut)\n\treturn &s\n}\n\nfunc (s *byteSemaphore) take(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tfor bytes > s.available {\n\t\ts.cond.Wait()\n\t\tif bytes > s.max {\n\t\t\tbytes = s.max\n\t\t}\n\t}\n\ts.available -= bytes\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) give(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tif s.available+bytes > s.max {\n\t\ts.available = s.max\n\t} else {\n\t\ts.available += bytes\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) setCapacity(cap int) {\n\ts.mut.Lock()\n\tdiff := cap - s.max\n\ts.max = cap\n\ts.available += diff\n\tif s.available < 0 {\n\t\ts.available = 0\n\t} else if s.available > s.max {\n\t\ts.available = s.max\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\n<|edits_diff|>\n--- lib/model/bytesemaphore.go\n+++ lib/model/bytesemaphore.go\n@@ -18,6 +18,9 @@\n }\n \n func newByteSemaphore(max int) *byteSemaphore {\n+\tif max < 0 {\n+\t\tmax = 0\n+\t}\n \ts := byteSemaphore{\n \t\tmax: max,\n \t\tavailable: max,\n<|current_version|>\n// Copyright (C) 2018 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage model\n\nimport (\n\t\"sync\"\n)\n\ntype byteSemaphore struct {\n\tmax int\n\tavailable int\n\tmut sync.Mutex\n\tcond *sync.Cond\n}\n\nfunc newByteSemaphore(max int) *byteSemaphore {\n\tif max < 0 {\n\t\tmax = 0\n\t}\n\ts := byteSemaphore{\n\t\tmax: max,\n\t\tavailable: max,\n\t}\n\ts.cond = sync.NewCond(&s.mut)\n\treturn &s\n}\n\nfunc (s *byteSemaphore) take(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tfor bytes > s.available {\n\t\ts.cond.Wait()\n\t\tif bytes > s.max {\n\t\t\tbytes = s.max\n\t\t}\n\t}\n\ts.available -= bytes\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) give(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tif s.available+bytes > s.max {\n\t\ts.available = s.max\n\t} else {\n\t\ts.available += bytes\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) setCapacity(cap int) {\n\ts.mut.Lock()\n\tdiff := cap - s.max\n\ts.max = cap\n\ts.available += diff\n\tif s.available < 0 {\n\t\ts.available = 0\n\t} else if s.available > s.max {\n\t\ts.available = s.max\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\n<|next_version|>\n// Copyright (C) 2018 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage model\n\nimport (\n\t\"sync\"\n)\n\ntype byteSemaphore struct {\n\tmax int\n\tavailable int\n\tmut sync.Mutex\n\tcond *sync.Cond\n}\n\nfunc newByteSemaphore(max int) *byteSemaphore {\n\tif max < 0 {\n\t\tmax = 0\n\t}\n\ts := byteSemaphore{\n\t\tmax: max,\n\t\tavailable: max,\n\t}\n\ts.cond = sync.NewCond(&s.mut)\n\treturn &s\n}\n\nfunc (s *byteSemaphore) take(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tfor bytes > s.available {\n\t\ts.cond.Wait()\n\t\tif bytes > s.max {\n\t\t\tbytes = s.max\n\t\t}\n\t}\n\ts.available -= bytes\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) give(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tif s.available+bytes > s.max {\n\t\ts.available = s.max\n\t} else {\n\t\ts.available += bytes\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) setCapacity(cap int) {\n\tif cap < 0 {\n\t\tcap = 0\n\t}\n\ts.mut.Lock()\n\tdiff := cap - s.max\n\ts.max = cap\n\ts.available += diff\n\tif s.available < 0 {\n\t\ts.available = 0\n\t} else if s.available > s.max {\n\t\ts.available = s.max\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\n", "current_contents": "// Copyright (C) 2018 The Syncthing Authors.\n//\n// This Source Code Form is subject to the terms of the Mozilla Public\n// License, v. 2.0. If a copy of the MPL was not distributed with this file,\n// You can obtain one at https://mozilla.org/MPL/2.0/.\n\npackage model\n\nimport (\n\t\"sync\"\n)\n\ntype byteSemaphore struct {\n\tmax int\n\tavailable int\n\tmut sync.Mutex\n\tcond *sync.Cond\n}\n\nfunc newByteSemaphore(max int) *byteSemaphore {\n\tif max < 0 {\n\t\tmax = 0\n\t}\n\ts := byteSemaphore{\n\t\tmax: max,\n\t\tavailable: max,\n\t}\n\ts.cond = sync.NewCond(&s.mut)\n\treturn &s\n}\n\nfunc (s *byteSemaphore) take(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tfor bytes > s.available {\n\t\ts.cond.Wait()\n\t\tif bytes > s.max {\n\t\t\tbytes = s.max\n\t\t}\n\t}\n\ts.available -= bytes\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) give(bytes int) {\n\ts.mut.Lock()\n\tif bytes > s.max {\n\t\tbytes = s.max\n\t}\n\tif s.available+bytes > s.max {\n\t\ts.available = s.max\n\t} else {\n\t\ts.available += bytes\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n\nfunc (s *byteSemaphore) setCapacity(cap int) {\n\ts.mut.Lock()\n\tdiff := cap - s.max\n\ts.max = cap\n\ts.available += diff\n\tif s.available < 0 {\n\t\ts.available = 0\n\t} else if s.available > s.max {\n\t\ts.available = s.max\n\t}\n\ts.cond.Broadcast()\n\ts.mut.Unlock()\n}\n"} {"commit": "db0c85318b8059dbb284e029bd8911c3e38efd20", "message": "cmd/syncthing: Account receive only folders in usage report", "old_file": "cmd/syncthing/usage_report.go", "new_file": "cmd/syncthing/usage_report.go", "status": "M", "old_contents": "\n\tres[\"totFiles\"] = totFiles\n\tres[\"folderMaxFiles\"] = maxFiles\n\tres[\"totMiB\"] = totBytes / 1024 / 1024\n\tres[\"folderMaxMiB\"] = maxBytes / 1024 / 1024\n\n\tvar mem runtime.MemStats\n\truntime.ReadMemStats(&mem)\n\tres[\"memoryUsageMiB\"] = (mem.Sys - mem.HeapReleased) / 1024 / 1024\n\tres[\"sha256Perf\"] = cpuBench(5, 125*time.Millisecond, false)\n\tres[\"hashPerf\"] = cpuBench(5, 125*time.Millisecond, true)\n\n\tbytes, err := memorySize()\n\tif err == nil {\n\t\tres[\"memorySize\"] = bytes / 1024 / 1024\n\t}\n\tres[\"numCPU\"] = runtime.NumCPU()\n\n\tvar rescanIntvs []int\n\tfolderUses := map[string]int{\n\t\t\"sendonly\": 0,\n\t\t\"sendreceive\": 0,\n\t\t\"ignorePerms\": 0,\n\t\t\"ignoreDelete\": 0,\n\t\t\"autoNormalize\": 0,\n\t\t\"simpleVersioning\": 0,\n\t\t\"externalVersioning\": 0,\n\t\t\"staggeredVersioning\": 0,\n\t\t\"trashcanVersioning\": 0,\n\t}\n\tfor _, cfg := range cfg.Folders() {\n\t\trescanIntvs = append(rescanIntvs, cfg.RescanIntervalS)\n\n\t\tswitch cfg.Type {\n\t\tcase config.FolderTypeSendOnly:\n\t\t\tfolderUses[\"sendonly\"]++\n\t\tcase config.FolderTypeSendReceive:\n\t\t\tfolderUses[\"sendreceive\"]++\n\t\t}\n\t\tif cfg.IgnorePerms {\n\t\t\tfolderUses[\"ignorePerms\"]++\n\t\t}\n\t\tif cfg.IgnoreDelete {\n\t\t\tfolderUses[\"ignoreDelete\"]++\n\t\t}\n\t\tif cfg.AutoNormalize {\n\t\t\tfolderUses[\"autoNormalize\"]++\n\t\t}\n\t\tif cfg.Versioning.Type != \"\" {\n\t\t\tfolderUses[cfg.Versioning.Type+\"Versioning\"]++\n\t\t}\n\t}\n\tsort.Ints(rescanIntvs)\n\tres[\"rescanIntvs\"] = rescanIntvs\n\tres[\"folderUses\"] = folderUses\n\n\tdeviceUses := map[string]int{\n\t\t\"introducer\": 0,\n\t\t\"customCertName\": 0,\n\t\t\"compressAlways\": 0,\n\t\t\"compressMetadata\": 0,\n\t\t\"compressNever\": 0,", "new_contents": "\n\tres[\"totFiles\"] = totFiles\n\tres[\"folderMaxFiles\"] = maxFiles\n\tres[\"totMiB\"] = totBytes / 1024 / 1024\n\tres[\"folderMaxMiB\"] = maxBytes / 1024 / 1024\n\n\tvar mem runtime.MemStats\n\truntime.ReadMemStats(&mem)\n\tres[\"memoryUsageMiB\"] = (mem.Sys - mem.HeapReleased) / 1024 / 1024\n\tres[\"sha256Perf\"] = cpuBench(5, 125*time.Millisecond, false)\n\tres[\"hashPerf\"] = cpuBench(5, 125*time.Millisecond, true)\n\n\tbytes, err := memorySize()\n\tif err == nil {\n\t\tres[\"memorySize\"] = bytes / 1024 / 1024\n\t}\n\tres[\"numCPU\"] = runtime.NumCPU()\n\n\tvar rescanIntvs []int\n\tfolderUses := map[string]int{\n\t\t\"sendonly\": 0,\n\t\t\"sendreceive\": 0,\n\t\t\"receiveonly\": 0,\n\t\t\"ignorePerms\": 0,\n\t\t\"ignoreDelete\": 0,\n\t\t\"autoNormalize\": 0,\n\t\t\"simpleVersioning\": 0,\n\t\t\"externalVersioning\": 0,\n\t\t\"staggeredVersioning\": 0,\n\t\t\"trashcanVersioning\": 0,\n\t}\n\tfor _, cfg := range cfg.Folders() {\n\t\trescanIntvs = append(rescanIntvs, cfg.RescanIntervalS)\n\n\t\tswitch cfg.Type {\n\t\tcase config.FolderTypeSendOnly:\n\t\t\tfolderUses[\"sendonly\"]++\n\t\tcase config.FolderTypeSendReceive:\n\t\t\tfolderUses[\"sendreceive\"]++\n\t\tcase config.FolderTypeReceiveOnly:\n\t\t\tfolderUses[\"receiveonly\"]++\n\t\t}\n\t\tif cfg.IgnorePerms {\n\t\t\tfolderUses[\"ignorePerms\"]++\n\t\t}\n\t\tif cfg.IgnoreDelete {\n\t\t\tfolderUses[\"ignoreDelete\"]++\n\t\t}\n\t\tif cfg.AutoNormalize {\n\t\t\tfolderUses[\"autoNormalize\"]++\n\t\t}\n\t\tif cfg.Versioning.Type != \"\" {\n\t\t\tfolderUses[cfg.Versioning.Type+\"Versioning\"]++\n\t\t}\n\t}\n\tsort.Ints(rescanIntvs)\n\tres[\"rescanIntvs\"] = rescanIntvs\n\tres[\"folderUses\"] = folderUses\n\n\tdeviceUses := map[string]int{\n\t\t\"introducer\": 0,\n\t\t\"customCertName\": 0,\n\t\t\"compressAlways\": 0,\n\t\t\"compressMetadata\": 0,\n\t\t\"compressNever\": 0,", "text": "<|original_code|>\n\n\tres[\"totFiles\"] = totFiles\n\tres[\"folderMaxFiles\"] = maxFiles\n\tres[\"totMiB\"] = totBytes / 1024 / 1024\n\tres[\"folderMaxMiB\"] = maxBytes / 1024 / 1024\n\n\tvar mem runtime.MemStats\n\truntime.ReadMemStats(&mem)\n\tres[\"memoryUsageMiB\"] = (mem.Sys - mem.HeapReleased) / 1024 / 1024\n\tres[\"sha256Perf\"] = cpuBench(5, 125*time.Millisecond, false)\n\tres[\"hashPerf\"] = cpuBench(5, 125*time.Millisecond, true)\n\n\tbytes, err := memorySize()\n\tif err == nil {\n\t\tres[\"memorySize\"] = bytes / 1024 / 1024\n\t}\n\tres[\"numCPU\"] = runtime.NumCPU()\n\n\tvar rescanIntvs []int\n\tfolderUses := map[string]int{\n\t\t\"sendonly\": 0,\n\t\t\"sendreceive\": 0,\n\t\t\"ignorePerms\": 0,\n\t\t\"ignoreDelete\": 0,\n\t\t\"autoNormalize\": 0,\n\t\t\"simpleVersioning\": 0,\n\t\t\"externalVersioning\": 0,\n\t\t\"staggeredVersioning\": 0,\n\t\t\"trashcanVersioning\": 0,\n\t}\n\tfor _, cfg := range cfg.Folders() {\n\t\trescanIntvs = append(rescanIntvs, cfg.RescanIntervalS)\n\n\t\tswitch cfg.Type {\n\t\tcase config.FolderTypeSendOnly:\n\t\t\tfolderUses[\"sendonly\"]++\n\t\tcase config.FolderTypeSendReceive:\n\t\t\tfolderUses[\"sendreceive\"]++\n\t\t}\n\t\tif cfg.IgnorePerms {\n\t\t\tfolderUses[\"ignorePerms\"]++\n\t\t}\n\t\tif cfg.IgnoreDelete {\n\t\t\tfolderUses[\"ignoreDelete\"]++\n\t\t}\n\t\tif cfg.AutoNormalize {\n\t\t\tfolderUses[\"autoNormalize\"]++\n\t\t}\n\t\tif cfg.Versioning.Type != \"\" {\n\t\t\tfolderUses[cfg.Versioning.Type+\"Versioning\"]++\n\t\t}\n\t}\n\tsort.Ints(rescanIntvs)\n\tres[\"rescanIntvs\"] = rescanIntvs\n\tres[\"folderUses\"] = folderUses\n\n\tdeviceUses := map[string]int{\n\t\t\"introducer\": 0,\n\t\t\"customCertName\": 0,\n\t\t\"compressAlways\": 0,\n\t\t\"compressMetadata\": 0,\n\t\t\"compressNever\": 0,\n<|edits_diff|>\n--- cmd/syncthing/usage_report.go\n+++ cmd/syncthing/usage_report.go\n@@ -20,6 +20,7 @@\n \tfolderUses := map[string]int{\n \t\t\"sendonly\": 0,\n \t\t\"sendreceive\": 0,\n+\t\t\"receiveonly\": 0,\n \t\t\"ignorePerms\": 0,\n \t\t\"ignoreDelete\": 0,\n \t\t\"autoNormalize\": 0,\n<|current_version|>\n\n\tres[\"totFiles\"] = totFiles\n\tres[\"folderMaxFiles\"] = maxFiles\n\tres[\"totMiB\"] = totBytes / 1024 / 1024\n\tres[\"folderMaxMiB\"] = maxBytes / 1024 / 1024\n\n\tvar mem runtime.MemStats\n\truntime.ReadMemStats(&mem)\n\tres[\"memoryUsageMiB\"] = (mem.Sys - mem.HeapReleased) / 1024 / 1024\n\tres[\"sha256Perf\"] = cpuBench(5, 125*time.Millisecond, false)\n\tres[\"hashPerf\"] = cpuBench(5, 125*time.Millisecond, true)\n\n\tbytes, err := memorySize()\n\tif err == nil {\n\t\tres[\"memorySize\"] = bytes / 1024 / 1024\n\t}\n\tres[\"numCPU\"] = runtime.NumCPU()\n\n\tvar rescanIntvs []int\n\tfolderUses := map[string]int{\n\t\t\"sendonly\": 0,\n\t\t\"sendreceive\": 0,\n\t\t\"receiveonly\": 0,\n\t\t\"ignorePerms\": 0,\n\t\t\"ignoreDelete\": 0,\n\t\t\"autoNormalize\": 0,\n\t\t\"simpleVersioning\": 0,\n\t\t\"externalVersioning\": 0,\n\t\t\"staggeredVersioning\": 0,\n\t\t\"trashcanVersioning\": 0,\n\t}\n\tfor _, cfg := range cfg.Folders() {\n\t\trescanIntvs = append(rescanIntvs, cfg.RescanIntervalS)\n\n\t\tswitch cfg.Type {\n\t\tcase config.FolderTypeSendOnly:\n\t\t\tfolderUses[\"sendonly\"]++\n\t\tcase config.FolderTypeSendReceive:\n\t\t\tfolderUses[\"sendreceive\"]++\n\t\t}\n\t\tif cfg.IgnorePerms {\n\t\t\tfolderUses[\"ignorePerms\"]++\n\t\t}\n\t\tif cfg.IgnoreDelete {\n\t\t\tfolderUses[\"ignoreDelete\"]++\n\t\t}\n\t\tif cfg.AutoNormalize {\n\t\t\tfolderUses[\"autoNormalize\"]++\n\t\t}\n\t\tif cfg.Versioning.Type != \"\" {\n\t\t\tfolderUses[cfg.Versioning.Type+\"Versioning\"]++\n\t\t}\n\t}\n\tsort.Ints(rescanIntvs)\n\tres[\"rescanIntvs\"] = rescanIntvs\n\tres[\"folderUses\"] = folderUses\n\n\tdeviceUses := map[string]int{\n\t\t\"introducer\": 0,\n\t\t\"customCertName\": 0,\n\t\t\"compressAlways\": 0,\n\t\t\"compressMetadata\": 0,\n\t\t\"compressNever\": 0,\n<|next_version|>\n\n\tres[\"totFiles\"] = totFiles\n\tres[\"folderMaxFiles\"] = maxFiles\n\tres[\"totMiB\"] = totBytes / 1024 / 1024\n\tres[\"folderMaxMiB\"] = maxBytes / 1024 / 1024\n\n\tvar mem runtime.MemStats\n\truntime.ReadMemStats(&mem)\n\tres[\"memoryUsageMiB\"] = (mem.Sys - mem.HeapReleased) / 1024 / 1024\n\tres[\"sha256Perf\"] = cpuBench(5, 125*time.Millisecond, false)\n\tres[\"hashPerf\"] = cpuBench(5, 125*time.Millisecond, true)\n\n\tbytes, err := memorySize()\n\tif err == nil {\n\t\tres[\"memorySize\"] = bytes / 1024 / 1024\n\t}\n\tres[\"numCPU\"] = runtime.NumCPU()\n\n\tvar rescanIntvs []int\n\tfolderUses := map[string]int{\n\t\t\"sendonly\": 0,\n\t\t\"sendreceive\": 0,\n\t\t\"receiveonly\": 0,\n\t\t\"ignorePerms\": 0,\n\t\t\"ignoreDelete\": 0,\n\t\t\"autoNormalize\": 0,\n\t\t\"simpleVersioning\": 0,\n\t\t\"externalVersioning\": 0,\n\t\t\"staggeredVersioning\": 0,\n\t\t\"trashcanVersioning\": 0,\n\t}\n\tfor _, cfg := range cfg.Folders() {\n\t\trescanIntvs = append(rescanIntvs, cfg.RescanIntervalS)\n\n\t\tswitch cfg.Type {\n\t\tcase config.FolderTypeSendOnly:\n\t\t\tfolderUses[\"sendonly\"]++\n\t\tcase config.FolderTypeSendReceive:\n\t\t\tfolderUses[\"sendreceive\"]++\n\t\tcase config.FolderTypeReceiveOnly:\n\t\t\tfolderUses[\"receiveonly\"]++\n\t\t}\n\t\tif cfg.IgnorePerms {\n\t\t\tfolderUses[\"ignorePerms\"]++\n\t\t}\n\t\tif cfg.IgnoreDelete {\n\t\t\tfolderUses[\"ignoreDelete\"]++\n\t\t}\n\t\tif cfg.AutoNormalize {\n\t\t\tfolderUses[\"autoNormalize\"]++\n\t\t}\n\t\tif cfg.Versioning.Type != \"\" {\n\t\t\tfolderUses[cfg.Versioning.Type+\"Versioning\"]++\n\t\t}\n\t}\n\tsort.Ints(rescanIntvs)\n\tres[\"rescanIntvs\"] = rescanIntvs\n\tres[\"folderUses\"] = folderUses\n\n\tdeviceUses := map[string]int{\n\t\t\"introducer\": 0,\n\t\t\"customCertName\": 0,\n\t\t\"compressAlways\": 0,\n\t\t\"compressMetadata\": 0,\n\t\t\"compressNever\": 0,\n", "current_contents": "\n\tres[\"totFiles\"] = totFiles\n\tres[\"folderMaxFiles\"] = maxFiles\n\tres[\"totMiB\"] = totBytes / 1024 / 1024\n\tres[\"folderMaxMiB\"] = maxBytes / 1024 / 1024\n\n\tvar mem runtime.MemStats\n\truntime.ReadMemStats(&mem)\n\tres[\"memoryUsageMiB\"] = (mem.Sys - mem.HeapReleased) / 1024 / 1024\n\tres[\"sha256Perf\"] = cpuBench(5, 125*time.Millisecond, false)\n\tres[\"hashPerf\"] = cpuBench(5, 125*time.Millisecond, true)\n\n\tbytes, err := memorySize()\n\tif err == nil {\n\t\tres[\"memorySize\"] = bytes / 1024 / 1024\n\t}\n\tres[\"numCPU\"] = runtime.NumCPU()\n\n\tvar rescanIntvs []int\n\tfolderUses := map[string]int{\n\t\t\"sendonly\": 0,\n\t\t\"sendreceive\": 0,\n\t\t\"receiveonly\": 0,\n\t\t\"ignorePerms\": 0,\n\t\t\"ignoreDelete\": 0,\n\t\t\"autoNormalize\": 0,\n\t\t\"simpleVersioning\": 0,\n\t\t\"externalVersioning\": 0,\n\t\t\"staggeredVersioning\": 0,\n\t\t\"trashcanVersioning\": 0,\n\t}\n\tfor _, cfg := range cfg.Folders() {\n\t\trescanIntvs = append(rescanIntvs, cfg.RescanIntervalS)\n\n\t\tswitch cfg.Type {\n\t\tcase config.FolderTypeSendOnly:\n\t\t\tfolderUses[\"sendonly\"]++\n\t\tcase config.FolderTypeSendReceive:\n\t\t\tfolderUses[\"sendreceive\"]++\n\t\t}\n\t\tif cfg.IgnorePerms {\n\t\t\tfolderUses[\"ignorePerms\"]++\n\t\t}\n\t\tif cfg.IgnoreDelete {\n\t\t\tfolderUses[\"ignoreDelete\"]++\n\t\t}\n\t\tif cfg.AutoNormalize {\n\t\t\tfolderUses[\"autoNormalize\"]++\n\t\t}\n\t\tif cfg.Versioning.Type != \"\" {\n\t\t\tfolderUses[cfg.Versioning.Type+\"Versioning\"]++\n\t\t}\n\t}\n\tsort.Ints(rescanIntvs)\n\tres[\"rescanIntvs\"] = rescanIntvs\n\tres[\"folderUses\"] = folderUses\n\n\tdeviceUses := map[string]int{\n\t\t\"introducer\": 0,\n\t\t\"customCertName\": 0,\n\t\t\"compressAlways\": 0,\n\t\t\"compressMetadata\": 0,\n\t\t\"compressNever\": 0,"} {"commit": "6436f1e0f8687a65471f5fec07e85f64adaa66e9", "message": "Fix memory leak in find_lib for some invalid inputs", "old_file": "src/linker.c", "new_file": "src/linker.c", "status": "M", "old_contents": " }\n jv_free(x);\n }\n jv_free(components);\n return name;\n}\n\n// Assumes name has been validated\nstatic jv jv_basename(jv name) {\n const char *s = jv_string_value(name);\n const char *p = strrchr(s, '/');\n if (!p)\n return name;\n jv res = jv_string_fmt(\"%s\", p);\n jv_free(name);\n return res;\n}\n\n// Asummes validated relative path to module\nstatic jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {\n if (!jv_is_valid(rel_path)) {\n jv_free(search);\n return rel_path;\n }\n if (jv_get_kind(rel_path) != JV_KIND_STRING) {\n jv_free(rel_path);\n jv_free(search);\n return jv_invalid_with_msg(jv_string_fmt(\"Module path must be a string\"));\n }\n if (jv_get_kind(search) != JV_KIND_ARRAY) {\n jv_free(rel_path);\n jv_free(search);\n return jv_invalid_with_msg(jv_string_fmt(\"Module search path must be an array\"));\n }\n\n struct stat st;\n int ret;\n\n // Ideally we should cache this somewhere\n search = build_lib_search_chain(jq, search, jq_origin, lib_origin);\n jv err = jv_array_get(jv_copy(search), 1);\n search = jv_array_get(search, 0);\n\n jv bname = jv_basename(jv_copy(rel_path));\n\n jv_array_foreach(search, i, spath) {\n if (jv_get_kind(spath) == JV_KIND_NULL) {\n jv_free(spath);\n break;\n }\n if (jv_get_kind(spath) != JV_KIND_STRING ||\n strcmp(jv_string_value(spath), \"\") == 0) {\n jv_free(spath);\n continue; /* XXX report non-strings in search path?? */\n }\n // Try ${search_dir}/${rel_path}.jq", "new_contents": " }\n jv_free(x);\n }\n jv_free(components);\n return name;\n}\n\n// Assumes name has been validated\nstatic jv jv_basename(jv name) {\n const char *s = jv_string_value(name);\n const char *p = strrchr(s, '/');\n if (!p)\n return name;\n jv res = jv_string_fmt(\"%s\", p);\n jv_free(name);\n return res;\n}\n\n// Asummes validated relative path to module\nstatic jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {\n if (!jv_is_valid(rel_path)) {\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return rel_path;\n }\n if (jv_get_kind(rel_path) != JV_KIND_STRING) {\n jv_free(rel_path);\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return jv_invalid_with_msg(jv_string_fmt(\"Module path must be a string\"));\n }\n if (jv_get_kind(search) != JV_KIND_ARRAY) {\n jv_free(rel_path);\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return jv_invalid_with_msg(jv_string_fmt(\"Module search path must be an array\"));\n }\n\n struct stat st;\n int ret;\n\n // Ideally we should cache this somewhere\n search = build_lib_search_chain(jq, search, jq_origin, lib_origin);\n jv err = jv_array_get(jv_copy(search), 1);\n search = jv_array_get(search, 0);\n\n jv bname = jv_basename(jv_copy(rel_path));\n\n jv_array_foreach(search, i, spath) {\n if (jv_get_kind(spath) == JV_KIND_NULL) {\n jv_free(spath);\n break;\n }\n if (jv_get_kind(spath) != JV_KIND_STRING ||\n strcmp(jv_string_value(spath), \"\") == 0) {\n jv_free(spath);\n continue; /* XXX report non-strings in search path?? */\n }\n // Try ${search_dir}/${rel_path}.jq", "text": "<|original_code|>\n }\n jv_free(x);\n }\n jv_free(components);\n return name;\n}\n\n// Assumes name has been validated\nstatic jv jv_basename(jv name) {\n const char *s = jv_string_value(name);\n const char *p = strrchr(s, '/');\n if (!p)\n return name;\n jv res = jv_string_fmt(\"%s\", p);\n jv_free(name);\n return res;\n}\n\n// Asummes validated relative path to module\nstatic jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {\n if (!jv_is_valid(rel_path)) {\n jv_free(search);\n return rel_path;\n }\n if (jv_get_kind(rel_path) != JV_KIND_STRING) {\n jv_free(rel_path);\n jv_free(search);\n return jv_invalid_with_msg(jv_string_fmt(\"Module path must be a string\"));\n }\n if (jv_get_kind(search) != JV_KIND_ARRAY) {\n jv_free(rel_path);\n jv_free(search);\n return jv_invalid_with_msg(jv_string_fmt(\"Module search path must be an array\"));\n }\n\n struct stat st;\n int ret;\n\n // Ideally we should cache this somewhere\n search = build_lib_search_chain(jq, search, jq_origin, lib_origin);\n jv err = jv_array_get(jv_copy(search), 1);\n search = jv_array_get(search, 0);\n\n jv bname = jv_basename(jv_copy(rel_path));\n\n jv_array_foreach(search, i, spath) {\n if (jv_get_kind(spath) == JV_KIND_NULL) {\n jv_free(spath);\n break;\n }\n if (jv_get_kind(spath) != JV_KIND_STRING ||\n strcmp(jv_string_value(spath), \"\") == 0) {\n jv_free(spath);\n continue; /* XXX report non-strings in search path?? */\n }\n // Try ${search_dir}/${rel_path}.jq\n<|edits_diff|>\n--- src/linker.c\n+++ src/linker.c\n@@ -20,11 +20,15 @@\n static jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {\n if (!jv_is_valid(rel_path)) {\n jv_free(search);\n+ jv_free(jq_origin);\n+ jv_free(lib_origin);\n return rel_path;\n }\n if (jv_get_kind(rel_path) != JV_KIND_STRING) {\n jv_free(rel_path);\n jv_free(search);\n+ jv_free(jq_origin);\n+ jv_free(lib_origin);\n return jv_invalid_with_msg(jv_string_fmt(\"Module path must be a string\"));\n }\n if (jv_get_kind(search) != JV_KIND_ARRAY) {\n<|current_version|>\n }\n jv_free(x);\n }\n jv_free(components);\n return name;\n}\n\n// Assumes name has been validated\nstatic jv jv_basename(jv name) {\n const char *s = jv_string_value(name);\n const char *p = strrchr(s, '/');\n if (!p)\n return name;\n jv res = jv_string_fmt(\"%s\", p);\n jv_free(name);\n return res;\n}\n\n// Asummes validated relative path to module\nstatic jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {\n if (!jv_is_valid(rel_path)) {\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return rel_path;\n }\n if (jv_get_kind(rel_path) != JV_KIND_STRING) {\n jv_free(rel_path);\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return jv_invalid_with_msg(jv_string_fmt(\"Module path must be a string\"));\n }\n if (jv_get_kind(search) != JV_KIND_ARRAY) {\n jv_free(rel_path);\n jv_free(search);\n return jv_invalid_with_msg(jv_string_fmt(\"Module search path must be an array\"));\n }\n\n struct stat st;\n int ret;\n\n // Ideally we should cache this somewhere\n search = build_lib_search_chain(jq, search, jq_origin, lib_origin);\n jv err = jv_array_get(jv_copy(search), 1);\n search = jv_array_get(search, 0);\n\n jv bname = jv_basename(jv_copy(rel_path));\n\n jv_array_foreach(search, i, spath) {\n if (jv_get_kind(spath) == JV_KIND_NULL) {\n jv_free(spath);\n break;\n }\n if (jv_get_kind(spath) != JV_KIND_STRING ||\n strcmp(jv_string_value(spath), \"\") == 0) {\n jv_free(spath);\n continue; /* XXX report non-strings in search path?? */\n }\n // Try ${search_dir}/${rel_path}.jq\n<|next_version|>\n }\n jv_free(x);\n }\n jv_free(components);\n return name;\n}\n\n// Assumes name has been validated\nstatic jv jv_basename(jv name) {\n const char *s = jv_string_value(name);\n const char *p = strrchr(s, '/');\n if (!p)\n return name;\n jv res = jv_string_fmt(\"%s\", p);\n jv_free(name);\n return res;\n}\n\n// Asummes validated relative path to module\nstatic jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {\n if (!jv_is_valid(rel_path)) {\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return rel_path;\n }\n if (jv_get_kind(rel_path) != JV_KIND_STRING) {\n jv_free(rel_path);\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return jv_invalid_with_msg(jv_string_fmt(\"Module path must be a string\"));\n }\n if (jv_get_kind(search) != JV_KIND_ARRAY) {\n jv_free(rel_path);\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return jv_invalid_with_msg(jv_string_fmt(\"Module search path must be an array\"));\n }\n\n struct stat st;\n int ret;\n\n // Ideally we should cache this somewhere\n search = build_lib_search_chain(jq, search, jq_origin, lib_origin);\n jv err = jv_array_get(jv_copy(search), 1);\n search = jv_array_get(search, 0);\n\n jv bname = jv_basename(jv_copy(rel_path));\n\n jv_array_foreach(search, i, spath) {\n if (jv_get_kind(spath) == JV_KIND_NULL) {\n jv_free(spath);\n break;\n }\n if (jv_get_kind(spath) != JV_KIND_STRING ||\n strcmp(jv_string_value(spath), \"\") == 0) {\n jv_free(spath);\n continue; /* XXX report non-strings in search path?? */\n }\n // Try ${search_dir}/${rel_path}.jq\n", "current_contents": " }\n jv_free(x);\n }\n jv_free(components);\n return name;\n}\n\n// Assumes name has been validated\nstatic jv jv_basename(jv name) {\n const char *s = jv_string_value(name);\n const char *p = strrchr(s, '/');\n if (!p)\n return name;\n jv res = jv_string_fmt(\"%s\", p);\n jv_free(name);\n return res;\n}\n\n// Asummes validated relative path to module\nstatic jv find_lib(jq_state *jq, jv rel_path, jv search, const char *suffix, jv jq_origin, jv lib_origin) {\n if (!jv_is_valid(rel_path)) {\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return rel_path;\n }\n if (jv_get_kind(rel_path) != JV_KIND_STRING) {\n jv_free(rel_path);\n jv_free(search);\n jv_free(jq_origin);\n jv_free(lib_origin);\n return jv_invalid_with_msg(jv_string_fmt(\"Module path must be a string\"));\n }\n if (jv_get_kind(search) != JV_KIND_ARRAY) {\n jv_free(rel_path);\n jv_free(search);\n return jv_invalid_with_msg(jv_string_fmt(\"Module search path must be an array\"));\n }\n\n struct stat st;\n int ret;\n\n // Ideally we should cache this somewhere\n search = build_lib_search_chain(jq, search, jq_origin, lib_origin);\n jv err = jv_array_get(jv_copy(search), 1);\n search = jv_array_get(search, 0);\n\n jv bname = jv_basename(jv_copy(rel_path));\n\n jv_array_foreach(search, i, spath) {\n if (jv_get_kind(spath) == JV_KIND_NULL) {\n jv_free(spath);\n break;\n }\n if (jv_get_kind(spath) != JV_KIND_STRING ||\n strcmp(jv_string_value(spath), \"\") == 0) {\n jv_free(spath);\n continue; /* XXX report non-strings in search path?? */\n }\n // Try ${search_dir}/${rel_path}.jq"} {"commit": "33a85679b9f79aa9f002687e2ead8c0cdc4d51cd", "message": "Fix #718", "old_file": "builtin.c", "new_file": "builtin.c", "status": "M", "old_contents": "#define LIBM_DD(name) \\\nstatic jv f_ ## name(jq_state *jq, jv input) { \\\n if (jv_get_kind(input) != JV_KIND_NUMBER) { \\\n return type_error(input, \"number required\"); \\\n } \\\n jv ret = jv_number(name(jv_number_value(input))); \\\n jv_free(input); \\\n return ret; \\\n}\n#include \"libm.h\"\n#undef LIBM_DD\n\nstatic jv f_negate(jq_state *jq, jv input) {\n if (jv_get_kind(input) != JV_KIND_NUMBER) {\n return type_error(input, \"cannot be negated\");\n }\n jv ret = jv_number(-jv_number_value(input));\n jv_free(input);\n return ret;\n}\n\nstatic jv f_startswith(jq_state *jq, jv a, jv b) {\n int alen = jv_string_length_bytes(jv_copy(a));\n int blen = jv_string_length_bytes(jv_copy(b));\n jv ret;\n\n if (blen <= alen && memcmp(jv_string_value(a), jv_string_value(b), blen) == 0)\n ret = jv_true();\n else\n ret = jv_false();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_endswith(jq_state *jq, jv a, jv b) {\n const char *astr = jv_string_value(a);\n const char *bstr = jv_string_value(b);\n size_t alen = jv_string_length_bytes(jv_copy(a));\n size_t blen = jv_string_length_bytes(jv_copy(b));\n jv ret;;\n\n if (alen < blen ||\n memcmp(astr + (alen - blen), bstr, blen) != 0)\n ret = jv_false();\n else\n ret = jv_true();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_ltrimstr(jq_state *jq, jv input, jv left) {\n if (jv_get_kind(f_startswith(jq, jv_copy(input), jv_copy(left))) != JV_KIND_TRUE) {\n jv_free(left);\n return input;\n }\n /*\n * FIXME It'd be better to share the suffix with the original input --\n * that we could do, we just can't share prefixes.", "new_contents": "#define LIBM_DD(name) \\\nstatic jv f_ ## name(jq_state *jq, jv input) { \\\n if (jv_get_kind(input) != JV_KIND_NUMBER) { \\\n return type_error(input, \"number required\"); \\\n } \\\n jv ret = jv_number(name(jv_number_value(input))); \\\n jv_free(input); \\\n return ret; \\\n}\n#include \"libm.h\"\n#undef LIBM_DD\n\nstatic jv f_negate(jq_state *jq, jv input) {\n if (jv_get_kind(input) != JV_KIND_NUMBER) {\n return type_error(input, \"cannot be negated\");\n }\n jv ret = jv_number(-jv_number_value(input));\n jv_free(input);\n return ret;\n}\n\nstatic jv f_startswith(jq_state *jq, jv a, jv b) {\n if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)\n return jv_invalid_with_msg(jv_string(\"startswith() requires string inputs\"));\n int alen = jv_string_length_bytes(jv_copy(a));\n int blen = jv_string_length_bytes(jv_copy(b));\n jv ret;\n\n if (blen <= alen && memcmp(jv_string_value(a), jv_string_value(b), blen) == 0)\n ret = jv_true();\n else\n ret = jv_false();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_endswith(jq_state *jq, jv a, jv b) {\n if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)\n return jv_invalid_with_msg(jv_string(\"endswith() requires string inputs\"));\n const char *astr = jv_string_value(a);\n const char *bstr = jv_string_value(b);\n size_t alen = jv_string_length_bytes(jv_copy(a));\n size_t blen = jv_string_length_bytes(jv_copy(b));\n jv ret;;\n\n if (alen < blen ||\n memcmp(astr + (alen - blen), bstr, blen) != 0)\n ret = jv_false();\n else\n ret = jv_true();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_ltrimstr(jq_state *jq, jv input, jv left) {\n if (jv_get_kind(f_startswith(jq, jv_copy(input), jv_copy(left))) != JV_KIND_TRUE) {\n jv_free(left);\n return input;\n }\n /*\n * FIXME It'd be better to share the suffix with the original input --\n * that we could do, we just can't share prefixes.", "text": "<|original_code|>\n#define LIBM_DD(name) \\\nstatic jv f_ ## name(jq_state *jq, jv input) { \\\n if (jv_get_kind(input) != JV_KIND_NUMBER) { \\\n return type_error(input, \"number required\"); \\\n } \\\n jv ret = jv_number(name(jv_number_value(input))); \\\n jv_free(input); \\\n return ret; \\\n}\n#include \"libm.h\"\n#undef LIBM_DD\n\nstatic jv f_negate(jq_state *jq, jv input) {\n if (jv_get_kind(input) != JV_KIND_NUMBER) {\n return type_error(input, \"cannot be negated\");\n }\n jv ret = jv_number(-jv_number_value(input));\n jv_free(input);\n return ret;\n}\n\nstatic jv f_startswith(jq_state *jq, jv a, jv b) {\n int alen = jv_string_length_bytes(jv_copy(a));\n int blen = jv_string_length_bytes(jv_copy(b));\n jv ret;\n\n if (blen <= alen && memcmp(jv_string_value(a), jv_string_value(b), blen) == 0)\n ret = jv_true();\n else\n ret = jv_false();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_endswith(jq_state *jq, jv a, jv b) {\n const char *astr = jv_string_value(a);\n const char *bstr = jv_string_value(b);\n size_t alen = jv_string_length_bytes(jv_copy(a));\n size_t blen = jv_string_length_bytes(jv_copy(b));\n jv ret;;\n\n if (alen < blen ||\n memcmp(astr + (alen - blen), bstr, blen) != 0)\n ret = jv_false();\n else\n ret = jv_true();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_ltrimstr(jq_state *jq, jv input, jv left) {\n if (jv_get_kind(f_startswith(jq, jv_copy(input), jv_copy(left))) != JV_KIND_TRUE) {\n jv_free(left);\n return input;\n }\n /*\n * FIXME It'd be better to share the suffix with the original input --\n * that we could do, we just can't share prefixes.\n<|edits_diff|>\n--- builtin.c\n+++ builtin.c\n@@ -20,6 +20,8 @@\n }\n \n static jv f_startswith(jq_state *jq, jv a, jv b) {\n+ if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)\n+ return jv_invalid_with_msg(jv_string(\"startswith() requires string inputs\"));\n int alen = jv_string_length_bytes(jv_copy(a));\n int blen = jv_string_length_bytes(jv_copy(b));\n jv ret;\n<|current_version|>\n#define LIBM_DD(name) \\\nstatic jv f_ ## name(jq_state *jq, jv input) { \\\n if (jv_get_kind(input) != JV_KIND_NUMBER) { \\\n return type_error(input, \"number required\"); \\\n } \\\n jv ret = jv_number(name(jv_number_value(input))); \\\n jv_free(input); \\\n return ret; \\\n}\n#include \"libm.h\"\n#undef LIBM_DD\n\nstatic jv f_negate(jq_state *jq, jv input) {\n if (jv_get_kind(input) != JV_KIND_NUMBER) {\n return type_error(input, \"cannot be negated\");\n }\n jv ret = jv_number(-jv_number_value(input));\n jv_free(input);\n return ret;\n}\n\nstatic jv f_startswith(jq_state *jq, jv a, jv b) {\n if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)\n return jv_invalid_with_msg(jv_string(\"startswith() requires string inputs\"));\n int alen = jv_string_length_bytes(jv_copy(a));\n int blen = jv_string_length_bytes(jv_copy(b));\n jv ret;\n\n if (blen <= alen && memcmp(jv_string_value(a), jv_string_value(b), blen) == 0)\n ret = jv_true();\n else\n ret = jv_false();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_endswith(jq_state *jq, jv a, jv b) {\n const char *astr = jv_string_value(a);\n const char *bstr = jv_string_value(b);\n size_t alen = jv_string_length_bytes(jv_copy(a));\n size_t blen = jv_string_length_bytes(jv_copy(b));\n jv ret;;\n\n if (alen < blen ||\n memcmp(astr + (alen - blen), bstr, blen) != 0)\n ret = jv_false();\n else\n ret = jv_true();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_ltrimstr(jq_state *jq, jv input, jv left) {\n if (jv_get_kind(f_startswith(jq, jv_copy(input), jv_copy(left))) != JV_KIND_TRUE) {\n jv_free(left);\n return input;\n }\n /*\n * FIXME It'd be better to share the suffix with the original input --\n * that we could do, we just can't share prefixes.\n<|next_version|>\n#define LIBM_DD(name) \\\nstatic jv f_ ## name(jq_state *jq, jv input) { \\\n if (jv_get_kind(input) != JV_KIND_NUMBER) { \\\n return type_error(input, \"number required\"); \\\n } \\\n jv ret = jv_number(name(jv_number_value(input))); \\\n jv_free(input); \\\n return ret; \\\n}\n#include \"libm.h\"\n#undef LIBM_DD\n\nstatic jv f_negate(jq_state *jq, jv input) {\n if (jv_get_kind(input) != JV_KIND_NUMBER) {\n return type_error(input, \"cannot be negated\");\n }\n jv ret = jv_number(-jv_number_value(input));\n jv_free(input);\n return ret;\n}\n\nstatic jv f_startswith(jq_state *jq, jv a, jv b) {\n if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)\n return jv_invalid_with_msg(jv_string(\"startswith() requires string inputs\"));\n int alen = jv_string_length_bytes(jv_copy(a));\n int blen = jv_string_length_bytes(jv_copy(b));\n jv ret;\n\n if (blen <= alen && memcmp(jv_string_value(a), jv_string_value(b), blen) == 0)\n ret = jv_true();\n else\n ret = jv_false();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_endswith(jq_state *jq, jv a, jv b) {\n if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)\n return jv_invalid_with_msg(jv_string(\"endswith() requires string inputs\"));\n const char *astr = jv_string_value(a);\n const char *bstr = jv_string_value(b);\n size_t alen = jv_string_length_bytes(jv_copy(a));\n size_t blen = jv_string_length_bytes(jv_copy(b));\n jv ret;;\n\n if (alen < blen ||\n memcmp(astr + (alen - blen), bstr, blen) != 0)\n ret = jv_false();\n else\n ret = jv_true();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_ltrimstr(jq_state *jq, jv input, jv left) {\n if (jv_get_kind(f_startswith(jq, jv_copy(input), jv_copy(left))) != JV_KIND_TRUE) {\n jv_free(left);\n return input;\n }\n /*\n * FIXME It'd be better to share the suffix with the original input --\n * that we could do, we just can't share prefixes.\n", "current_contents": "#define LIBM_DD(name) \\\nstatic jv f_ ## name(jq_state *jq, jv input) { \\\n if (jv_get_kind(input) != JV_KIND_NUMBER) { \\\n return type_error(input, \"number required\"); \\\n } \\\n jv ret = jv_number(name(jv_number_value(input))); \\\n jv_free(input); \\\n return ret; \\\n}\n#include \"libm.h\"\n#undef LIBM_DD\n\nstatic jv f_negate(jq_state *jq, jv input) {\n if (jv_get_kind(input) != JV_KIND_NUMBER) {\n return type_error(input, \"cannot be negated\");\n }\n jv ret = jv_number(-jv_number_value(input));\n jv_free(input);\n return ret;\n}\n\nstatic jv f_startswith(jq_state *jq, jv a, jv b) {\n if (jv_get_kind(a) != JV_KIND_STRING || jv_get_kind(b) != JV_KIND_STRING)\n return jv_invalid_with_msg(jv_string(\"startswith() requires string inputs\"));\n int alen = jv_string_length_bytes(jv_copy(a));\n int blen = jv_string_length_bytes(jv_copy(b));\n jv ret;\n\n if (blen <= alen && memcmp(jv_string_value(a), jv_string_value(b), blen) == 0)\n ret = jv_true();\n else\n ret = jv_false();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_endswith(jq_state *jq, jv a, jv b) {\n const char *astr = jv_string_value(a);\n const char *bstr = jv_string_value(b);\n size_t alen = jv_string_length_bytes(jv_copy(a));\n size_t blen = jv_string_length_bytes(jv_copy(b));\n jv ret;;\n\n if (alen < blen ||\n memcmp(astr + (alen - blen), bstr, blen) != 0)\n ret = jv_false();\n else\n ret = jv_true();\n jv_free(a);\n jv_free(b);\n return ret;\n}\n\nstatic jv f_ltrimstr(jq_state *jq, jv input, jv left) {\n if (jv_get_kind(f_startswith(jq, jv_copy(input), jv_copy(left))) != JV_KIND_TRUE) {\n jv_free(left);\n return input;\n }\n /*\n * FIXME It'd be better to share the suffix with the original input --\n * that we could do, we just can't share prefixes."} {"commit": "520c7bb15ea01e9516ff1387ec8b01a5b5b7c1c5", "message": "Fix some confusion between \"null\" and \"invalid\".", "old_file": "c/main.c", "new_file": "c/main.c", "status": "M", "old_contents": "\nvoid run_tests() {\n FILE* testdata = fopen(\"testdata\",\"r\");\n char buf[4096];\n int tests = 0, passed = 0;\n\n while (1) {\n if (!fgets(buf, sizeof(buf), testdata)) break;\n if (skipline(buf)) continue;\n printf(\"Testing %s\\n\", buf);\n int pass = 1;\n block program = compile(buf);\n block_append(&program, gen_op_simple(YIELD));\n block_append(&program, gen_op_simple(BACKTRACK));\n program = gen_cbinding(&builtins, program);\n struct bytecode* bc = block_compile(program);\n block_free(program);\n printf(\"Disassembly:\\n\");\n dump_disassembly(2, bc);\n printf(\"\\n\");\n fgets(buf, sizeof(buf), testdata);\n jv input = jv_parse(buf);\n jq_init(bc, input);\n\n while (fgets(buf, sizeof(buf), testdata)) {\n if (skipline(buf)) break;\n jv expected = jv_parse(buf);\n jv actual = jq_next();\n if (!jv_is_valid(actual)) {\n printf(\"Insufficient results\\n\");\n pass = 0;\n break;\n } else if (!jv_equal(expected, actual)) {\n printf(\"Expected \");\n jv_dump(expected);\n printf(\", but got \");\n jv_dump(actual);\n printf(\"\\n\");\n pass = 0;\n }\n }\n if (pass) {\n jv extra = jq_next();\n if (jv_is_valid(extra)) {\n printf(\"Superfluous result: \");\n jv_dump(extra);\n printf(\"\\n\");\n pass = 0;\n }\n }\n jq_teardown();", "new_contents": "\nvoid run_tests() {\n FILE* testdata = fopen(\"testdata\",\"r\");\n char buf[4096];\n int tests = 0, passed = 0;\n\n while (1) {\n if (!fgets(buf, sizeof(buf), testdata)) break;\n if (skipline(buf)) continue;\n printf(\"Testing %s\\n\", buf);\n int pass = 1;\n block program = compile(buf);\n block_append(&program, gen_op_simple(YIELD));\n block_append(&program, gen_op_simple(BACKTRACK));\n program = gen_cbinding(&builtins, program);\n struct bytecode* bc = block_compile(program);\n block_free(program);\n printf(\"Disassembly:\\n\");\n dump_disassembly(2, bc);\n printf(\"\\n\");\n fgets(buf, sizeof(buf), testdata);\n jv input = jv_parse(buf);\n assert(jv_is_valid(input));\n jq_init(bc, input);\n\n while (fgets(buf, sizeof(buf), testdata)) {\n if (skipline(buf)) break;\n jv expected = jv_parse(buf);\n assert(jv_is_valid(expected));\n jv actual = jq_next();\n if (!jv_is_valid(actual)) {\n printf(\"Insufficient results\\n\");\n pass = 0;\n break;\n } else if (!jv_equal(expected, actual)) {\n printf(\"Expected \");\n jv_dump(expected);\n printf(\", but got \");\n jv_dump(actual);\n printf(\"\\n\");\n pass = 0;\n }\n }\n if (pass) {\n jv extra = jq_next();\n if (jv_is_valid(extra)) {\n printf(\"Superfluous result: \");\n jv_dump(extra);\n printf(\"\\n\");\n pass = 0;\n }\n }\n jq_teardown();", "text": "<|original_code|>\n\nvoid run_tests() {\n FILE* testdata = fopen(\"testdata\",\"r\");\n char buf[4096];\n int tests = 0, passed = 0;\n\n while (1) {\n if (!fgets(buf, sizeof(buf), testdata)) break;\n if (skipline(buf)) continue;\n printf(\"Testing %s\\n\", buf);\n int pass = 1;\n block program = compile(buf);\n block_append(&program, gen_op_simple(YIELD));\n block_append(&program, gen_op_simple(BACKTRACK));\n program = gen_cbinding(&builtins, program);\n struct bytecode* bc = block_compile(program);\n block_free(program);\n printf(\"Disassembly:\\n\");\n dump_disassembly(2, bc);\n printf(\"\\n\");\n fgets(buf, sizeof(buf), testdata);\n jv input = jv_parse(buf);\n jq_init(bc, input);\n\n while (fgets(buf, sizeof(buf), testdata)) {\n if (skipline(buf)) break;\n jv expected = jv_parse(buf);\n jv actual = jq_next();\n if (!jv_is_valid(actual)) {\n printf(\"Insufficient results\\n\");\n pass = 0;\n break;\n } else if (!jv_equal(expected, actual)) {\n printf(\"Expected \");\n jv_dump(expected);\n printf(\", but got \");\n jv_dump(actual);\n printf(\"\\n\");\n pass = 0;\n }\n }\n if (pass) {\n jv extra = jq_next();\n if (jv_is_valid(extra)) {\n printf(\"Superfluous result: \");\n jv_dump(extra);\n printf(\"\\n\");\n pass = 0;\n }\n }\n jq_teardown();\n<|edits_diff|>\n--- c/main.c\n+++ c/main.c\n@@ -20,6 +20,7 @@\n printf(\"\\n\");\n fgets(buf, sizeof(buf), testdata);\n jv input = jv_parse(buf);\n+ assert(jv_is_valid(input));\n jq_init(bc, input);\n \n while (fgets(buf, sizeof(buf), testdata)) {\n<|current_version|>\n\nvoid run_tests() {\n FILE* testdata = fopen(\"testdata\",\"r\");\n char buf[4096];\n int tests = 0, passed = 0;\n\n while (1) {\n if (!fgets(buf, sizeof(buf), testdata)) break;\n if (skipline(buf)) continue;\n printf(\"Testing %s\\n\", buf);\n int pass = 1;\n block program = compile(buf);\n block_append(&program, gen_op_simple(YIELD));\n block_append(&program, gen_op_simple(BACKTRACK));\n program = gen_cbinding(&builtins, program);\n struct bytecode* bc = block_compile(program);\n block_free(program);\n printf(\"Disassembly:\\n\");\n dump_disassembly(2, bc);\n printf(\"\\n\");\n fgets(buf, sizeof(buf), testdata);\n jv input = jv_parse(buf);\n assert(jv_is_valid(input));\n jq_init(bc, input);\n\n while (fgets(buf, sizeof(buf), testdata)) {\n if (skipline(buf)) break;\n jv expected = jv_parse(buf);\n jv actual = jq_next();\n if (!jv_is_valid(actual)) {\n printf(\"Insufficient results\\n\");\n pass = 0;\n break;\n } else if (!jv_equal(expected, actual)) {\n printf(\"Expected \");\n jv_dump(expected);\n printf(\", but got \");\n jv_dump(actual);\n printf(\"\\n\");\n pass = 0;\n }\n }\n if (pass) {\n jv extra = jq_next();\n if (jv_is_valid(extra)) {\n printf(\"Superfluous result: \");\n jv_dump(extra);\n printf(\"\\n\");\n pass = 0;\n }\n }\n jq_teardown();\n<|next_version|>\n\nvoid run_tests() {\n FILE* testdata = fopen(\"testdata\",\"r\");\n char buf[4096];\n int tests = 0, passed = 0;\n\n while (1) {\n if (!fgets(buf, sizeof(buf), testdata)) break;\n if (skipline(buf)) continue;\n printf(\"Testing %s\\n\", buf);\n int pass = 1;\n block program = compile(buf);\n block_append(&program, gen_op_simple(YIELD));\n block_append(&program, gen_op_simple(BACKTRACK));\n program = gen_cbinding(&builtins, program);\n struct bytecode* bc = block_compile(program);\n block_free(program);\n printf(\"Disassembly:\\n\");\n dump_disassembly(2, bc);\n printf(\"\\n\");\n fgets(buf, sizeof(buf), testdata);\n jv input = jv_parse(buf);\n assert(jv_is_valid(input));\n jq_init(bc, input);\n\n while (fgets(buf, sizeof(buf), testdata)) {\n if (skipline(buf)) break;\n jv expected = jv_parse(buf);\n assert(jv_is_valid(expected));\n jv actual = jq_next();\n if (!jv_is_valid(actual)) {\n printf(\"Insufficient results\\n\");\n pass = 0;\n break;\n } else if (!jv_equal(expected, actual)) {\n printf(\"Expected \");\n jv_dump(expected);\n printf(\", but got \");\n jv_dump(actual);\n printf(\"\\n\");\n pass = 0;\n }\n }\n if (pass) {\n jv extra = jq_next();\n if (jv_is_valid(extra)) {\n printf(\"Superfluous result: \");\n jv_dump(extra);\n printf(\"\\n\");\n pass = 0;\n }\n }\n jq_teardown();\n", "current_contents": "\nvoid run_tests() {\n FILE* testdata = fopen(\"testdata\",\"r\");\n char buf[4096];\n int tests = 0, passed = 0;\n\n while (1) {\n if (!fgets(buf, sizeof(buf), testdata)) break;\n if (skipline(buf)) continue;\n printf(\"Testing %s\\n\", buf);\n int pass = 1;\n block program = compile(buf);\n block_append(&program, gen_op_simple(YIELD));\n block_append(&program, gen_op_simple(BACKTRACK));\n program = gen_cbinding(&builtins, program);\n struct bytecode* bc = block_compile(program);\n block_free(program);\n printf(\"Disassembly:\\n\");\n dump_disassembly(2, bc);\n printf(\"\\n\");\n fgets(buf, sizeof(buf), testdata);\n jv input = jv_parse(buf);\n assert(jv_is_valid(input));\n jq_init(bc, input);\n\n while (fgets(buf, sizeof(buf), testdata)) {\n if (skipline(buf)) break;\n jv expected = jv_parse(buf);\n jv actual = jq_next();\n if (!jv_is_valid(actual)) {\n printf(\"Insufficient results\\n\");\n pass = 0;\n break;\n } else if (!jv_equal(expected, actual)) {\n printf(\"Expected \");\n jv_dump(expected);\n printf(\", but got \");\n jv_dump(actual);\n printf(\"\\n\");\n pass = 0;\n }\n }\n if (pass) {\n jv extra = jq_next();\n if (jv_is_valid(extra)) {\n printf(\"Superfluous result: \");\n jv_dump(extra);\n printf(\"\\n\");\n pass = 0;\n }\n }\n jq_teardown();"} {"commit": "d895d39ba973f7296429aac77c1ad6bc8d7341b4", "message": "Support \"null\" in JQ programs", "old_file": "c/builtin.c", "new_file": "c/builtin.c", "status": "M", "old_contents": "#include \"builtin.h\"\n\nstatic void f_false(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_false();\n}\n\nstatic void f_true(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_true();\n}\n\n\nstatic void f_plus(jv input[], jv output[]) {\n jv_free(input[0]);\n jv a = input[2];\n jv b = input[1];\n if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {\n output[0] = jv_number(jv_number_value(a) + \n jv_number_value(b));\n } else if (jv_get_kind(a) == JV_KIND_ARRAY && jv_get_kind(b) == JV_KIND_ARRAY) {\n output[0] = jv_array_concat(a, b);\n } else {\n output[0] = jv_string(\"wtf gaize\");\n jv_free(a);\n jv_free(b);\n }\n}\n\nstruct cfunction function_list[] = {\n {f_true, \"true\", CALL_BUILTIN_1_1},\n {f_false, \"false\", CALL_BUILTIN_1_1},\n {f_plus, \"_plus\", CALL_BUILTIN_3_1},\n};\nstruct symbol_table builtins = {function_list, sizeof(function_list)/sizeof(function_list[0])};\n", "new_contents": "#include \"builtin.h\"\n\nstatic void f_false(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_false();\n}\n\nstatic void f_true(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_true();\n}\n\nstatic void f_null(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_null();\n}\n\nstatic void f_plus(jv input[], jv output[]) {\n jv_free(input[0]);\n jv a = input[2];\n jv b = input[1];\n if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {\n output[0] = jv_number(jv_number_value(a) + \n jv_number_value(b));\n } else if (jv_get_kind(a) == JV_KIND_ARRAY && jv_get_kind(b) == JV_KIND_ARRAY) {\n output[0] = jv_array_concat(a, b);\n } else {\n output[0] = jv_string(\"wtf gaize\");\n jv_free(a);\n jv_free(b);\n }\n}\n\nstruct cfunction function_list[] = {\n {f_true, \"true\", CALL_BUILTIN_1_1},\n {f_false, \"false\", CALL_BUILTIN_1_1},\n {f_null, \"null\", CALL_BUILTIN_1_1},\n {f_plus, \"_plus\", CALL_BUILTIN_3_1},\n};\nstruct symbol_table builtins = {function_list, sizeof(function_list)/sizeof(function_list[0])};\n", "text": "<|original_code|>\n#include \"builtin.h\"\n\nstatic void f_false(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_false();\n}\n\nstatic void f_true(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_true();\n}\n\n\nstatic void f_plus(jv input[], jv output[]) {\n jv_free(input[0]);\n jv a = input[2];\n jv b = input[1];\n if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {\n output[0] = jv_number(jv_number_value(a) + \n jv_number_value(b));\n } else if (jv_get_kind(a) == JV_KIND_ARRAY && jv_get_kind(b) == JV_KIND_ARRAY) {\n output[0] = jv_array_concat(a, b);\n } else {\n output[0] = jv_string(\"wtf gaize\");\n jv_free(a);\n jv_free(b);\n }\n}\n\nstruct cfunction function_list[] = {\n {f_true, \"true\", CALL_BUILTIN_1_1},\n {f_false, \"false\", CALL_BUILTIN_1_1},\n {f_plus, \"_plus\", CALL_BUILTIN_3_1},\n};\nstruct symbol_table builtins = {function_list, sizeof(function_list)/sizeof(function_list[0])};\n\n<|edits_diff|>\n--- c/builtin.c\n+++ c/builtin.c\n@@ -10,6 +10,10 @@\n output[0] = jv_true();\n }\n \n+static void f_null(jv input[], jv output[]) {\n+ jv_free(input[0]);\n+ output[0] = jv_null();\n+}\n \n static void f_plus(jv input[], jv output[]) {\n jv_free(input[0]);\n<|current_version|>\n#include \"builtin.h\"\n\nstatic void f_false(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_false();\n}\n\nstatic void f_true(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_true();\n}\n\nstatic void f_null(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_null();\n}\n\nstatic void f_plus(jv input[], jv output[]) {\n jv_free(input[0]);\n jv a = input[2];\n jv b = input[1];\n if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {\n output[0] = jv_number(jv_number_value(a) + \n jv_number_value(b));\n } else if (jv_get_kind(a) == JV_KIND_ARRAY && jv_get_kind(b) == JV_KIND_ARRAY) {\n output[0] = jv_array_concat(a, b);\n } else {\n output[0] = jv_string(\"wtf gaize\");\n jv_free(a);\n jv_free(b);\n }\n}\n\nstruct cfunction function_list[] = {\n {f_true, \"true\", CALL_BUILTIN_1_1},\n {f_false, \"false\", CALL_BUILTIN_1_1},\n {f_plus, \"_plus\", CALL_BUILTIN_3_1},\n};\nstruct symbol_table builtins = {function_list, sizeof(function_list)/sizeof(function_list[0])};\n\n<|next_version|>\n#include \"builtin.h\"\n\nstatic void f_false(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_false();\n}\n\nstatic void f_true(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_true();\n}\n\nstatic void f_null(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_null();\n}\n\nstatic void f_plus(jv input[], jv output[]) {\n jv_free(input[0]);\n jv a = input[2];\n jv b = input[1];\n if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {\n output[0] = jv_number(jv_number_value(a) + \n jv_number_value(b));\n } else if (jv_get_kind(a) == JV_KIND_ARRAY && jv_get_kind(b) == JV_KIND_ARRAY) {\n output[0] = jv_array_concat(a, b);\n } else {\n output[0] = jv_string(\"wtf gaize\");\n jv_free(a);\n jv_free(b);\n }\n}\n\nstruct cfunction function_list[] = {\n {f_true, \"true\", CALL_BUILTIN_1_1},\n {f_false, \"false\", CALL_BUILTIN_1_1},\n {f_null, \"null\", CALL_BUILTIN_1_1},\n {f_plus, \"_plus\", CALL_BUILTIN_3_1},\n};\nstruct symbol_table builtins = {function_list, sizeof(function_list)/sizeof(function_list[0])};\n\n", "current_contents": "#include \"builtin.h\"\n\nstatic void f_false(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_false();\n}\n\nstatic void f_true(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_true();\n}\n\nstatic void f_null(jv input[], jv output[]) {\n jv_free(input[0]);\n output[0] = jv_null();\n}\n\nstatic void f_plus(jv input[], jv output[]) {\n jv_free(input[0]);\n jv a = input[2];\n jv b = input[1];\n if (jv_get_kind(a) == JV_KIND_NUMBER && jv_get_kind(b) == JV_KIND_NUMBER) {\n output[0] = jv_number(jv_number_value(a) + \n jv_number_value(b));\n } else if (jv_get_kind(a) == JV_KIND_ARRAY && jv_get_kind(b) == JV_KIND_ARRAY) {\n output[0] = jv_array_concat(a, b);\n } else {\n output[0] = jv_string(\"wtf gaize\");\n jv_free(a);\n jv_free(b);\n }\n}\n\nstruct cfunction function_list[] = {\n {f_true, \"true\", CALL_BUILTIN_1_1},\n {f_false, \"false\", CALL_BUILTIN_1_1},\n {f_plus, \"_plus\", CALL_BUILTIN_3_1},\n};\nstruct symbol_table builtins = {function_list, sizeof(function_list)/sizeof(function_list[0])};\n"} {"commit": "e704ed0efb7ce18c59087e7dacbd7b57014597dd", "message": "update tests and project files for stb_ds", "old_file": "tests/image_test.c", "new_file": "tests/image_test.c", "status": "M", "old_contents": " int dist3 = abs(out1[k][2] - out2[k][2]);\n ++count;\n if (out1[k][1] > out2[k][1])\n ++bigcount;\n }\n }\n }\n printf(\"So far: %d (%d big) of %d\\n\", count, bigcount, total);\n }\n printf(\"Final: %d (%d big) of %d\\n\", count, bigcount, total);\n}\n#endif\n\nfloat hdr_data[200][200][3];\n\nvoid dummy_write(void *context, void *data, int len)\n{\n static char dummy[1024];\n if (len > 1024) len = 1024;\n memcpy(dummy, data, len);\n}\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n int w2,h2,n2;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[i], &w2, &h2, &n2);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");", "new_contents": " int dist3 = abs(out1[k][2] - out2[k][2]);\n ++count;\n if (out1[k][1] > out2[k][1])\n ++bigcount;\n }\n }\n }\n printf(\"So far: %d (%d big) of %d\\n\", count, bigcount, total);\n }\n printf(\"Final: %d (%d big) of %d\\n\", count, bigcount, total);\n}\n#endif\n\nfloat hdr_data[200][200][3];\n\nvoid dummy_write(void *context, void *data, int len)\n{\n static char dummy[1024];\n if (len > 1024) len = 1024;\n memcpy(dummy, data, len);\n}\n\nextern void image_write_test(void);\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n image_write_test();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n int w2,h2,n2;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[i], &w2, &h2, &n2);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");", "text": "<|original_code|>\n int dist3 = abs(out1[k][2] - out2[k][2]);\n ++count;\n if (out1[k][1] > out2[k][1])\n ++bigcount;\n }\n }\n }\n printf(\"So far: %d (%d big) of %d\\n\", count, bigcount, total);\n }\n printf(\"Final: %d (%d big) of %d\\n\", count, bigcount, total);\n}\n#endif\n\nfloat hdr_data[200][200][3];\n\nvoid dummy_write(void *context, void *data, int len)\n{\n static char dummy[1024];\n if (len > 1024) len = 1024;\n memcpy(dummy, data, len);\n}\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n int w2,h2,n2;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[i], &w2, &h2, &n2);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n<|edits_diff|>\n--- tests/image_test.c\n+++ tests/image_test.c\n@@ -19,6 +19,8 @@\n if (len > 1024) len = 1024;\n memcpy(dummy, data, len);\n }\n+\n+extern void image_write_test(void);\n \n int main(int argc, char **argv)\n {\n<|current_version|>\n int dist3 = abs(out1[k][2] - out2[k][2]);\n ++count;\n if (out1[k][1] > out2[k][1])\n ++bigcount;\n }\n }\n }\n printf(\"So far: %d (%d big) of %d\\n\", count, bigcount, total);\n }\n printf(\"Final: %d (%d big) of %d\\n\", count, bigcount, total);\n}\n#endif\n\nfloat hdr_data[200][200][3];\n\nvoid dummy_write(void *context, void *data, int len)\n{\n static char dummy[1024];\n if (len > 1024) len = 1024;\n memcpy(dummy, data, len);\n}\n\nextern void image_write_test(void);\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n int w2,h2,n2;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[i], &w2, &h2, &n2);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n<|next_version|>\n int dist3 = abs(out1[k][2] - out2[k][2]);\n ++count;\n if (out1[k][1] > out2[k][1])\n ++bigcount;\n }\n }\n }\n printf(\"So far: %d (%d big) of %d\\n\", count, bigcount, total);\n }\n printf(\"Final: %d (%d big) of %d\\n\", count, bigcount, total);\n}\n#endif\n\nfloat hdr_data[200][200][3];\n\nvoid dummy_write(void *context, void *data, int len)\n{\n static char dummy[1024];\n if (len > 1024) len = 1024;\n memcpy(dummy, data, len);\n}\n\nextern void image_write_test(void);\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n image_write_test();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n int w2,h2,n2;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[i], &w2, &h2, &n2);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n", "current_contents": " int dist3 = abs(out1[k][2] - out2[k][2]);\n ++count;\n if (out1[k][1] > out2[k][1])\n ++bigcount;\n }\n }\n }\n printf(\"So far: %d (%d big) of %d\\n\", count, bigcount, total);\n }\n printf(\"Final: %d (%d big) of %d\\n\", count, bigcount, total);\n}\n#endif\n\nfloat hdr_data[200][200][3];\n\nvoid dummy_write(void *context, void *data, int len)\n{\n static char dummy[1024];\n if (len > 1024) len = 1024;\n memcpy(dummy, data, len);\n}\n\nextern void image_write_test(void);\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n int w2,h2,n2;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[i], &w2, &h2, &n2);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");"} {"commit": "90dc93a1ccbf63df53d3136c6e1b6225840814cf", "message": "fix bug where we couldn't rewind a file that reached EOF, which can happen with < 92-byte PIC,PNM,HDR,TGA", "old_file": "tests/image_test.c", "new_file": "tests/image_test.c", "status": "M", "old_contents": "float hdr_data[200][200][3];\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 3); if (data) free(data); else printf(\"Failed 3\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 4);\n assert(data);\n if (data) {\n char fname[512];\n stb_splitpath(fname, argv[i], STB_FILE);\n stbi_write_png(stb_sprintf(\"output/%s.png\", fname), w, h, 4, data, w*4);\n free(data);\n } else\n printf(\"FAILED 4\\n\");\n }\n } else {\n int i, nope=0;\n #ifdef PNGSUITE_PRIMARY\n char **files = stb_readdir_files(\"pngsuite/primary\");\n #else\n char **files = stb_readdir_files(\"images\");\n #endif\n for (i=0; i < stb_arr_len(files); ++i) {\n int n;\n char **failed = NULL;\n unsigned char *data;\n printf(\".\");\n //printf(\"%s\\n\", files[i]);\n data = stbi_load(files[i], &w, &h, &n, 0); if (data) free(data); else stb_arr_push(failed, \"&n\");\n data = stbi_load(files[i], &w, &h, 0, 1); if (data) free(data); else stb_arr_push(failed, \"1\");\n data = stbi_load(files[i], &w, &h, 0, 2); if (data) free(data); else stb_arr_push(failed, \"2\");", "new_contents": "float hdr_data[200][200][3];\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[1], &w, &h, &n);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 3); if (data) free(data); else printf(\"Failed 3\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 4);\n assert(data);\n assert(res);\n if (data) {\n char fname[512];\n stb_splitpath(fname, argv[i], STB_FILE);\n stbi_write_png(stb_sprintf(\"output/%s.png\", fname), w, h, 4, data, w*4);\n free(data);\n } else\n printf(\"FAILED 4\\n\");\n }\n } else {\n int i, nope=0;\n #ifdef PNGSUITE_PRIMARY\n char **files = stb_readdir_files(\"pngsuite/primary\");\n #else\n char **files = stb_readdir_files(\"images\");\n #endif\n for (i=0; i < stb_arr_len(files); ++i) {\n int n;\n char **failed = NULL;\n unsigned char *data;\n printf(\".\");\n //printf(\"%s\\n\", files[i]);\n data = stbi_load(files[i], &w, &h, &n, 0); if (data) free(data); else stb_arr_push(failed, \"&n\");\n data = stbi_load(files[i], &w, &h, 0, 1); if (data) free(data); else stb_arr_push(failed, \"1\");\n data = stbi_load(files[i], &w, &h, 0, 2); if (data) free(data); else stb_arr_push(failed, \"2\");", "text": "<|original_code|>\nfloat hdr_data[200][200][3];\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 3); if (data) free(data); else printf(\"Failed 3\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 4);\n assert(data);\n if (data) {\n char fname[512];\n stb_splitpath(fname, argv[i], STB_FILE);\n stbi_write_png(stb_sprintf(\"output/%s.png\", fname), w, h, 4, data, w*4);\n free(data);\n } else\n printf(\"FAILED 4\\n\");\n }\n } else {\n int i, nope=0;\n #ifdef PNGSUITE_PRIMARY\n char **files = stb_readdir_files(\"pngsuite/primary\");\n #else\n char **files = stb_readdir_files(\"images\");\n #endif\n for (i=0; i < stb_arr_len(files); ++i) {\n int n;\n char **failed = NULL;\n unsigned char *data;\n printf(\".\");\n //printf(\"%s\\n\", files[i]);\n data = stbi_load(files[i], &w, &h, &n, 0); if (data) free(data); else stb_arr_push(failed, \"&n\");\n data = stbi_load(files[i], &w, &h, 0, 1); if (data) free(data); else stb_arr_push(failed, \"1\");\n data = stbi_load(files[i], &w, &h, 0, 2); if (data) free(data); else stb_arr_push(failed, \"2\");\n<|edits_diff|>\n--- tests/image_test.c\n+++ tests/image_test.c\n@@ -20,8 +20,10 @@\n int i, n;\n \n for (i=1; i < argc; ++i) {\n+ int res;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n+ res = stbi_info(argv[1], &w, &h, &n);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n<|current_version|>\nfloat hdr_data[200][200][3];\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[1], &w, &h, &n);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 3); if (data) free(data); else printf(\"Failed 3\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 4);\n assert(data);\n if (data) {\n char fname[512];\n stb_splitpath(fname, argv[i], STB_FILE);\n stbi_write_png(stb_sprintf(\"output/%s.png\", fname), w, h, 4, data, w*4);\n free(data);\n } else\n printf(\"FAILED 4\\n\");\n }\n } else {\n int i, nope=0;\n #ifdef PNGSUITE_PRIMARY\n char **files = stb_readdir_files(\"pngsuite/primary\");\n #else\n char **files = stb_readdir_files(\"images\");\n #endif\n for (i=0; i < stb_arr_len(files); ++i) {\n int n;\n char **failed = NULL;\n unsigned char *data;\n printf(\".\");\n //printf(\"%s\\n\", files[i]);\n data = stbi_load(files[i], &w, &h, &n, 0); if (data) free(data); else stb_arr_push(failed, \"&n\");\n data = stbi_load(files[i], &w, &h, 0, 1); if (data) free(data); else stb_arr_push(failed, \"1\");\n data = stbi_load(files[i], &w, &h, 0, 2); if (data) free(data); else stb_arr_push(failed, \"2\");\n<|next_version|>\nfloat hdr_data[200][200][3];\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[1], &w, &h, &n);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 3); if (data) free(data); else printf(\"Failed 3\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 4);\n assert(data);\n assert(res);\n if (data) {\n char fname[512];\n stb_splitpath(fname, argv[i], STB_FILE);\n stbi_write_png(stb_sprintf(\"output/%s.png\", fname), w, h, 4, data, w*4);\n free(data);\n } else\n printf(\"FAILED 4\\n\");\n }\n } else {\n int i, nope=0;\n #ifdef PNGSUITE_PRIMARY\n char **files = stb_readdir_files(\"pngsuite/primary\");\n #else\n char **files = stb_readdir_files(\"images\");\n #endif\n for (i=0; i < stb_arr_len(files); ++i) {\n int n;\n char **failed = NULL;\n unsigned char *data;\n printf(\".\");\n //printf(\"%s\\n\", files[i]);\n data = stbi_load(files[i], &w, &h, &n, 0); if (data) free(data); else stb_arr_push(failed, \"&n\");\n data = stbi_load(files[i], &w, &h, 0, 1); if (data) free(data); else stb_arr_push(failed, \"1\");\n data = stbi_load(files[i], &w, &h, 0, 2); if (data) free(data); else stb_arr_push(failed, \"2\");\n", "current_contents": "float hdr_data[200][200][3];\n\nint main(int argc, char **argv)\n{\n int w,h;\n //test_ycbcr();\n\n #if 0\n // test hdr asserts\n for (h=0; h < 100; h += 2)\n for (w=0; w < 200; ++w)\n hdr_data[h][w][0] = (float) rand(),\n hdr_data[h][w][1] = (float) rand(),\n hdr_data[h][w][2] = (float) rand();\n\n stbi_write_hdr(\"output/test.hdr\", 200,200,3,hdr_data[0][0]);\n #endif\n\n if (argc > 1) {\n int i, n;\n\n for (i=1; i < argc; ++i) {\n int res;\n unsigned char *data;\n printf(\"%s\\n\", argv[i]);\n res = stbi_info(argv[1], &w, &h, &n);\n data = stbi_load(argv[i], &w, &h, &n, 4); if (data) free(data); else printf(\"Failed &n\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 1); if (data) free(data); else printf(\"Failed 1\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 2); if (data) free(data); else printf(\"Failed 2\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 3); if (data) free(data); else printf(\"Failed 3\\n\");\n data = stbi_load(argv[i], &w, &h, 0, 4);\n assert(data);\n if (data) {\n char fname[512];\n stb_splitpath(fname, argv[i], STB_FILE);\n stbi_write_png(stb_sprintf(\"output/%s.png\", fname), w, h, 4, data, w*4);\n free(data);\n } else\n printf(\"FAILED 4\\n\");\n }\n } else {\n int i, nope=0;\n #ifdef PNGSUITE_PRIMARY\n char **files = stb_readdir_files(\"pngsuite/primary\");\n #else\n char **files = stb_readdir_files(\"images\");\n #endif\n for (i=0; i < stb_arr_len(files); ++i) {\n int n;\n char **failed = NULL;\n unsigned char *data;\n printf(\".\");\n //printf(\"%s\\n\", files[i]);\n data = stbi_load(files[i], &w, &h, &n, 0); if (data) free(data); else stb_arr_push(failed, \"&n\");\n data = stbi_load(files[i], &w, &h, 0, 1); if (data) free(data); else stb_arr_push(failed, \"1\");\n data = stbi_load(files[i], &w, &h, 0, 2); if (data) free(data); else stb_arr_push(failed, \"2\");"} {"commit": "6c78bb9bb1ccbf91f5f059c13a82badea529012a", "message": "QUIC: fixed anti-amplification with explicit send.", "old_file": "src/event/quic/ngx_event_quic_migration.c", "new_file": "src/event/quic/ngx_event_quic_migration.c", "status": "M", "old_contents": " path->expires = ngx_current_msec + pto;\n return NGX_OK;\n }\n\n /* rc == NGX_DECLINED */\n }\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL expired mtu:%uz\",\n path->seqnum, path->mtud);\n\n path->max_mtu = path->mtud;\n\n ngx_quic_discover_path_mtu(c, path);\n\n return NGX_OK;\n}\n\n\nstatic ngx_int_t\nngx_quic_send_path_mtu_probe(ngx_connection_t *c, ngx_quic_path_t *path)\n{\n ngx_int_t rc;\n ngx_uint_t log_error;\n ngx_quic_frame_t frame;\n ngx_quic_send_ctx_t *ctx;\n ngx_quic_connection_t *qc;\n\n ngx_memzero(&frame, sizeof(ngx_quic_frame_t));\n\n frame.level = ssl_encryption_application;\n frame.type = NGX_QUIC_FT_PING;\n\n qc = ngx_quic_get_connection(c);\n ctx = ngx_quic_get_send_ctx(qc, ssl_encryption_application);\n path->mtu_pnum[path->tries] = ctx->pnum;\n\n ngx_log_debug4(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL send probe \"\n \"mtu:%uz pnum:%uL tries:%ui\",\n path->seqnum, path->mtud, ctx->pnum, path->tries);\n\n log_error = c->log_error;\n c->log_error = NGX_ERROR_IGNORE_EMSGSIZE;\n\n rc = ngx_quic_frame_sendto(c, &frame, path->mtud, path);\n c->log_error = log_error;\n\n if (rc == NGX_ERROR) {\n if (c->write->error) {\n c->write->error = 0;\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL rejected mtu:%uz\",\n path->seqnum, path->mtud);\n\n return NGX_DECLINED;\n }\n\n return NGX_ERROR;\n }\n\n return NGX_OK;\n}\n\n\nngx_int_t\nngx_quic_handle_path_mtu(ngx_connection_t *c, ngx_quic_path_t *path,\n uint64_t min, uint64_t max)\n{", "new_contents": " path->expires = ngx_current_msec + pto;\n return NGX_OK;\n }\n\n /* rc == NGX_DECLINED */\n }\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL expired mtu:%uz\",\n path->seqnum, path->mtud);\n\n path->max_mtu = path->mtud;\n\n ngx_quic_discover_path_mtu(c, path);\n\n return NGX_OK;\n}\n\n\nstatic ngx_int_t\nngx_quic_send_path_mtu_probe(ngx_connection_t *c, ngx_quic_path_t *path)\n{\n size_t mtu;\n ngx_int_t rc;\n ngx_uint_t log_error;\n ngx_quic_frame_t frame;\n ngx_quic_send_ctx_t *ctx;\n ngx_quic_connection_t *qc;\n\n ngx_memzero(&frame, sizeof(ngx_quic_frame_t));\n\n frame.level = ssl_encryption_application;\n frame.type = NGX_QUIC_FT_PING;\n\n qc = ngx_quic_get_connection(c);\n ctx = ngx_quic_get_send_ctx(qc, ssl_encryption_application);\n path->mtu_pnum[path->tries] = ctx->pnum;\n\n ngx_log_debug4(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL send probe \"\n \"mtu:%uz pnum:%uL tries:%ui\",\n path->seqnum, path->mtud, ctx->pnum, path->tries);\n\n log_error = c->log_error;\n c->log_error = NGX_ERROR_IGNORE_EMSGSIZE;\n\n mtu = path->mtu;\n path->mtu = path->mtud;\n\n rc = ngx_quic_frame_sendto(c, &frame, path->mtud, path);\n\n path->mtu = mtu;\n c->log_error = log_error;\n\n if (rc == NGX_ERROR) {\n if (c->write->error) {\n c->write->error = 0;\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL rejected mtu:%uz\",\n path->seqnum, path->mtud);\n\n return NGX_DECLINED;\n }\n\n return NGX_ERROR;\n }\n\n return NGX_OK;\n}\n\n\nngx_int_t\nngx_quic_handle_path_mtu(ngx_connection_t *c, ngx_quic_path_t *path,\n uint64_t min, uint64_t max)\n{", "text": "<|original_code|>\n path->expires = ngx_current_msec + pto;\n return NGX_OK;\n }\n\n /* rc == NGX_DECLINED */\n }\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL expired mtu:%uz\",\n path->seqnum, path->mtud);\n\n path->max_mtu = path->mtud;\n\n ngx_quic_discover_path_mtu(c, path);\n\n return NGX_OK;\n}\n\n\nstatic ngx_int_t\nngx_quic_send_path_mtu_probe(ngx_connection_t *c, ngx_quic_path_t *path)\n{\n ngx_int_t rc;\n ngx_uint_t log_error;\n ngx_quic_frame_t frame;\n ngx_quic_send_ctx_t *ctx;\n ngx_quic_connection_t *qc;\n\n ngx_memzero(&frame, sizeof(ngx_quic_frame_t));\n\n frame.level = ssl_encryption_application;\n frame.type = NGX_QUIC_FT_PING;\n\n qc = ngx_quic_get_connection(c);\n ctx = ngx_quic_get_send_ctx(qc, ssl_encryption_application);\n path->mtu_pnum[path->tries] = ctx->pnum;\n\n ngx_log_debug4(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL send probe \"\n \"mtu:%uz pnum:%uL tries:%ui\",\n path->seqnum, path->mtud, ctx->pnum, path->tries);\n\n log_error = c->log_error;\n c->log_error = NGX_ERROR_IGNORE_EMSGSIZE;\n\n rc = ngx_quic_frame_sendto(c, &frame, path->mtud, path);\n c->log_error = log_error;\n\n if (rc == NGX_ERROR) {\n if (c->write->error) {\n c->write->error = 0;\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL rejected mtu:%uz\",\n path->seqnum, path->mtud);\n\n return NGX_DECLINED;\n }\n\n return NGX_ERROR;\n }\n\n return NGX_OK;\n}\n\n\nngx_int_t\nngx_quic_handle_path_mtu(ngx_connection_t *c, ngx_quic_path_t *path,\n uint64_t min, uint64_t max)\n{\n<|edits_diff|>\n--- src/event/quic/ngx_event_quic_migration.c\n+++ src/event/quic/ngx_event_quic_migration.c\n@@ -20,6 +20,7 @@\n static ngx_int_t\n ngx_quic_send_path_mtu_probe(ngx_connection_t *c, ngx_quic_path_t *path)\n {\n+ size_t mtu;\n ngx_int_t rc;\n ngx_uint_t log_error;\n ngx_quic_frame_t frame;\n@@ -42,6 +43,9 @@\n \n log_error = c->log_error;\n c->log_error = NGX_ERROR_IGNORE_EMSGSIZE;\n+\n+ mtu = path->mtu;\n+ path->mtu = path->mtud;\n \n rc = ngx_quic_frame_sendto(c, &frame, path->mtud, path);\n c->log_error = log_error;\n<|current_version|>\n path->expires = ngx_current_msec + pto;\n return NGX_OK;\n }\n\n /* rc == NGX_DECLINED */\n }\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL expired mtu:%uz\",\n path->seqnum, path->mtud);\n\n path->max_mtu = path->mtud;\n\n ngx_quic_discover_path_mtu(c, path);\n\n return NGX_OK;\n}\n\n\nstatic ngx_int_t\nngx_quic_send_path_mtu_probe(ngx_connection_t *c, ngx_quic_path_t *path)\n{\n size_t mtu;\n ngx_int_t rc;\n ngx_uint_t log_error;\n ngx_quic_frame_t frame;\n ngx_quic_send_ctx_t *ctx;\n ngx_quic_connection_t *qc;\n\n ngx_memzero(&frame, sizeof(ngx_quic_frame_t));\n\n frame.level = ssl_encryption_application;\n frame.type = NGX_QUIC_FT_PING;\n\n qc = ngx_quic_get_connection(c);\n ctx = ngx_quic_get_send_ctx(qc, ssl_encryption_application);\n path->mtu_pnum[path->tries] = ctx->pnum;\n\n ngx_log_debug4(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL send probe \"\n \"mtu:%uz pnum:%uL tries:%ui\",\n path->seqnum, path->mtud, ctx->pnum, path->tries);\n\n log_error = c->log_error;\n c->log_error = NGX_ERROR_IGNORE_EMSGSIZE;\n\n mtu = path->mtu;\n path->mtu = path->mtud;\n\n rc = ngx_quic_frame_sendto(c, &frame, path->mtud, path);\n c->log_error = log_error;\n\n if (rc == NGX_ERROR) {\n if (c->write->error) {\n c->write->error = 0;\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL rejected mtu:%uz\",\n path->seqnum, path->mtud);\n\n return NGX_DECLINED;\n }\n\n return NGX_ERROR;\n }\n\n return NGX_OK;\n}\n\n\nngx_int_t\nngx_quic_handle_path_mtu(ngx_connection_t *c, ngx_quic_path_t *path,\n uint64_t min, uint64_t max)\n{\n<|next_version|>\n path->expires = ngx_current_msec + pto;\n return NGX_OK;\n }\n\n /* rc == NGX_DECLINED */\n }\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL expired mtu:%uz\",\n path->seqnum, path->mtud);\n\n path->max_mtu = path->mtud;\n\n ngx_quic_discover_path_mtu(c, path);\n\n return NGX_OK;\n}\n\n\nstatic ngx_int_t\nngx_quic_send_path_mtu_probe(ngx_connection_t *c, ngx_quic_path_t *path)\n{\n size_t mtu;\n ngx_int_t rc;\n ngx_uint_t log_error;\n ngx_quic_frame_t frame;\n ngx_quic_send_ctx_t *ctx;\n ngx_quic_connection_t *qc;\n\n ngx_memzero(&frame, sizeof(ngx_quic_frame_t));\n\n frame.level = ssl_encryption_application;\n frame.type = NGX_QUIC_FT_PING;\n\n qc = ngx_quic_get_connection(c);\n ctx = ngx_quic_get_send_ctx(qc, ssl_encryption_application);\n path->mtu_pnum[path->tries] = ctx->pnum;\n\n ngx_log_debug4(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL send probe \"\n \"mtu:%uz pnum:%uL tries:%ui\",\n path->seqnum, path->mtud, ctx->pnum, path->tries);\n\n log_error = c->log_error;\n c->log_error = NGX_ERROR_IGNORE_EMSGSIZE;\n\n mtu = path->mtu;\n path->mtu = path->mtud;\n\n rc = ngx_quic_frame_sendto(c, &frame, path->mtud, path);\n\n path->mtu = mtu;\n c->log_error = log_error;\n\n if (rc == NGX_ERROR) {\n if (c->write->error) {\n c->write->error = 0;\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL rejected mtu:%uz\",\n path->seqnum, path->mtud);\n\n return NGX_DECLINED;\n }\n\n return NGX_ERROR;\n }\n\n return NGX_OK;\n}\n\n\nngx_int_t\nngx_quic_handle_path_mtu(ngx_connection_t *c, ngx_quic_path_t *path,\n uint64_t min, uint64_t max)\n{\n", "current_contents": " path->expires = ngx_current_msec + pto;\n return NGX_OK;\n }\n\n /* rc == NGX_DECLINED */\n }\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL expired mtu:%uz\",\n path->seqnum, path->mtud);\n\n path->max_mtu = path->mtud;\n\n ngx_quic_discover_path_mtu(c, path);\n\n return NGX_OK;\n}\n\n\nstatic ngx_int_t\nngx_quic_send_path_mtu_probe(ngx_connection_t *c, ngx_quic_path_t *path)\n{\n size_t mtu;\n ngx_int_t rc;\n ngx_uint_t log_error;\n ngx_quic_frame_t frame;\n ngx_quic_send_ctx_t *ctx;\n ngx_quic_connection_t *qc;\n\n ngx_memzero(&frame, sizeof(ngx_quic_frame_t));\n\n frame.level = ssl_encryption_application;\n frame.type = NGX_QUIC_FT_PING;\n\n qc = ngx_quic_get_connection(c);\n ctx = ngx_quic_get_send_ctx(qc, ssl_encryption_application);\n path->mtu_pnum[path->tries] = ctx->pnum;\n\n ngx_log_debug4(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL send probe \"\n \"mtu:%uz pnum:%uL tries:%ui\",\n path->seqnum, path->mtud, ctx->pnum, path->tries);\n\n log_error = c->log_error;\n c->log_error = NGX_ERROR_IGNORE_EMSGSIZE;\n\n mtu = path->mtu;\n path->mtu = path->mtud;\n\n rc = ngx_quic_frame_sendto(c, &frame, path->mtud, path);\n c->log_error = log_error;\n\n if (rc == NGX_ERROR) {\n if (c->write->error) {\n c->write->error = 0;\n\n ngx_log_debug2(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic path seq:%uL rejected mtu:%uz\",\n path->seqnum, path->mtud);\n\n return NGX_DECLINED;\n }\n\n return NGX_ERROR;\n }\n\n return NGX_OK;\n}\n\n\nngx_int_t\nngx_quic_handle_path_mtu(ngx_connection_t *c, ngx_quic_path_t *path,\n uint64_t min, uint64_t max)\n{"} {"commit": "1fce224f01b5a9b503315bd24e99421e5ca5bd7c", "message": "Mail: parsing of the PROXY protocol from clients.", "old_file": "src/mail/ngx_mail.c", "new_file": "src/mail/ngx_mail.c", "status": "M", "old_contents": "{\n ngx_uint_t i;\n ngx_mail_in_addr_t *addrs;\n struct sockaddr_in *sin;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_mail_add_addrs6(ngx_conf_t *cf, ngx_mail_port_t *mport,\n ngx_mail_conf_addr_t *addr)\n{\n ngx_uint_t i;\n ngx_mail_in6_addr_t *addrs6;\n struct sockaddr_in6 *sin6;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in6_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_mail_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_mail_conf_addr_t *first, *second;\n\n first = (ngx_mail_conf_addr_t *) one;\n second = (ngx_mail_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */", "new_contents": "{\n ngx_uint_t i;\n ngx_mail_in_addr_t *addrs;\n struct sockaddr_in *sin;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_mail_add_addrs6(ngx_conf_t *cf, ngx_mail_port_t *mport,\n ngx_mail_conf_addr_t *addr)\n{\n ngx_uint_t i;\n ngx_mail_in6_addr_t *addrs6;\n struct sockaddr_in6 *sin6;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in6_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_mail_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_mail_conf_addr_t *first, *second;\n\n first = (ngx_mail_conf_addr_t *) one;\n second = (ngx_mail_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */", "text": "<|original_code|>\n{\n ngx_uint_t i;\n ngx_mail_in_addr_t *addrs;\n struct sockaddr_in *sin;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_mail_add_addrs6(ngx_conf_t *cf, ngx_mail_port_t *mport,\n ngx_mail_conf_addr_t *addr)\n{\n ngx_uint_t i;\n ngx_mail_in6_addr_t *addrs6;\n struct sockaddr_in6 *sin6;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in6_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_mail_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_mail_conf_addr_t *first, *second;\n\n first = (ngx_mail_conf_addr_t *) one;\n second = (ngx_mail_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n<|edits_diff|>\n--- src/mail/ngx_mail.c\n+++ src/mail/ngx_mail.c\n@@ -20,6 +20,7 @@\n #if (NGX_MAIL_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n #endif\n+ addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n \n<|current_version|>\n{\n ngx_uint_t i;\n ngx_mail_in_addr_t *addrs;\n struct sockaddr_in *sin;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_mail_add_addrs6(ngx_conf_t *cf, ngx_mail_port_t *mport,\n ngx_mail_conf_addr_t *addr)\n{\n ngx_uint_t i;\n ngx_mail_in6_addr_t *addrs6;\n struct sockaddr_in6 *sin6;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in6_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_mail_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_mail_conf_addr_t *first, *second;\n\n first = (ngx_mail_conf_addr_t *) one;\n second = (ngx_mail_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n<|next_version|>\n{\n ngx_uint_t i;\n ngx_mail_in_addr_t *addrs;\n struct sockaddr_in *sin;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_mail_add_addrs6(ngx_conf_t *cf, ngx_mail_port_t *mport,\n ngx_mail_conf_addr_t *addr)\n{\n ngx_uint_t i;\n ngx_mail_in6_addr_t *addrs6;\n struct sockaddr_in6 *sin6;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in6_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_mail_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_mail_conf_addr_t *first, *second;\n\n first = (ngx_mail_conf_addr_t *) one;\n second = (ngx_mail_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n", "current_contents": "{\n ngx_uint_t i;\n ngx_mail_in_addr_t *addrs;\n struct sockaddr_in *sin;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_mail_add_addrs6(ngx_conf_t *cf, ngx_mail_port_t *mport,\n ngx_mail_conf_addr_t *addr)\n{\n ngx_uint_t i;\n ngx_mail_in6_addr_t *addrs6;\n struct sockaddr_in6 *sin6;\n\n mport->addrs = ngx_pcalloc(cf->pool,\n mport->naddrs * sizeof(ngx_mail_in6_addr_t));\n if (mport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = mport->addrs;\n\n for (i = 0; i < mport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_MAIL_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_mail_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_mail_conf_addr_t *first, *second;\n\n first = (ngx_mail_conf_addr_t *) one;\n second = (ngx_mail_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */"} {"commit": "7250a7688da4ee9ad1a88fd1489bbb19ec2020ce", "message": "QUIC: fixed memory leak in ngx_quic_send_frames().", "old_file": "src/event/ngx_event_quic.c", "new_file": "src/event/ngx_event_quic.c", "status": "M", "old_contents": "\n q = ngx_queue_head(frames);\n start = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_memzero(&pkt, sizeof(ngx_quic_header_t));\n\n now = ngx_current_msec;\n\n p = src;\n out.data = src;\n\n for (q = ngx_queue_head(frames);\n q != ngx_queue_sentinel(frames);\n q = ngx_queue_next(q))\n {\n f = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic frame out: %s\", f->info);\n\n len = ngx_quic_create_frame(p, f);\n if (len == -1) {\n return NGX_ERROR;\n }\n\n if (f->need_ack) {\n pkt.need_ack = 1;\n }\n\n p += len;\n f->pnum = ctx->pnum;\n f->last = now;\n f->plen = 0;\n }\n\n out.len = p - out.data;\n\n while (out.len < 4) {\n *p++ = NGX_QUIC_FT_PADDING;\n out.len++;\n }\n\n qc = c->quic;\n\n keys = &c->quic->keys[start->level];\n\n pkt.secret = &keys->server;\n\n pkt.flags = NGX_QUIC_PKT_FIXED_BIT;\n\n if (start->level == ssl_encryption_initial) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_INITIAL;\n pkt.token = initial_token;\n\n } else if (start->level == ssl_encryption_handshake) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_HANDSHAKE;\n\n } else {\n if (c->quic->key_phase) {\n pkt.flags |= NGX_QUIC_PKT_KPHASE;\n }\n }\n\n ngx_quic_set_packet_number(&pkt, ctx);\n\n pkt.log = c->log;\n pkt.level = start->level;\n pkt.dcid = qc->scid;\n pkt.scid = qc->dcid;\n pkt.payload = out;\n\n res.data = dst;\n\n ngx_log_debug6(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic packet ready: %ui bytes at level %d\"\n \" need_ack: %d number: %L encoded %d:0x%xD\",\n out.len, start->level, pkt.need_ack, pkt.number,\n pkt.num_len, pkt.trunc);\n\n if (ngx_quic_encrypt(&pkt, ssl_conn, &res) != NGX_OK) {\n return NGX_ERROR;\n }\n\n len = c->send(c, res.data, res.len);\n if (len == NGX_ERROR || (size_t) len != res.len) {\n return NGX_ERROR;\n }\n\n /* len == NGX_OK || NGX_AGAIN */\n ctx->pnum++;\n\n if (pkt.need_ack) {\n /* move frames into the sent queue to wait for ack */\n\n if (qc->closing) {\n /* if we are closing, any ack will be discarded */\n ngx_quic_free_frames(c, frames);\n\n } else {\n ngx_queue_add(&ctx->sent, frames);\n if (qc->pto.timer_set) {\n ngx_del_timer(&qc->pto);\n }\n ngx_add_timer(&qc->pto, ngx_quic_pto(c, ctx));\n\n start->plen = len;\n }\n\n qc->congestion.in_flight += len;", "new_contents": "\n q = ngx_queue_head(frames);\n start = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_memzero(&pkt, sizeof(ngx_quic_header_t));\n\n now = ngx_current_msec;\n\n p = src;\n out.data = src;\n\n for (q = ngx_queue_head(frames);\n q != ngx_queue_sentinel(frames);\n q = ngx_queue_next(q))\n {\n f = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic frame out: %s\", f->info);\n\n len = ngx_quic_create_frame(p, f);\n if (len == -1) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n if (f->need_ack) {\n pkt.need_ack = 1;\n }\n\n p += len;\n f->pnum = ctx->pnum;\n f->last = now;\n f->plen = 0;\n }\n\n out.len = p - out.data;\n\n while (out.len < 4) {\n *p++ = NGX_QUIC_FT_PADDING;\n out.len++;\n }\n\n qc = c->quic;\n\n keys = &c->quic->keys[start->level];\n\n pkt.secret = &keys->server;\n\n pkt.flags = NGX_QUIC_PKT_FIXED_BIT;\n\n if (start->level == ssl_encryption_initial) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_INITIAL;\n pkt.token = initial_token;\n\n } else if (start->level == ssl_encryption_handshake) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_HANDSHAKE;\n\n } else {\n if (c->quic->key_phase) {\n pkt.flags |= NGX_QUIC_PKT_KPHASE;\n }\n }\n\n ngx_quic_set_packet_number(&pkt, ctx);\n\n pkt.log = c->log;\n pkt.level = start->level;\n pkt.dcid = qc->scid;\n pkt.scid = qc->dcid;\n pkt.payload = out;\n\n res.data = dst;\n\n ngx_log_debug6(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic packet ready: %ui bytes at level %d\"\n \" need_ack: %d number: %L encoded %d:0x%xD\",\n out.len, start->level, pkt.need_ack, pkt.number,\n pkt.num_len, pkt.trunc);\n\n if (ngx_quic_encrypt(&pkt, ssl_conn, &res) != NGX_OK) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n len = c->send(c, res.data, res.len);\n if (len == NGX_ERROR || (size_t) len != res.len) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n /* len == NGX_OK || NGX_AGAIN */\n ctx->pnum++;\n\n if (pkt.need_ack) {\n /* move frames into the sent queue to wait for ack */\n\n if (qc->closing) {\n /* if we are closing, any ack will be discarded */\n ngx_quic_free_frames(c, frames);\n\n } else {\n ngx_queue_add(&ctx->sent, frames);\n if (qc->pto.timer_set) {\n ngx_del_timer(&qc->pto);\n }\n ngx_add_timer(&qc->pto, ngx_quic_pto(c, ctx));\n\n start->plen = len;\n }\n\n qc->congestion.in_flight += len;", "text": "<|original_code|>\n\n q = ngx_queue_head(frames);\n start = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_memzero(&pkt, sizeof(ngx_quic_header_t));\n\n now = ngx_current_msec;\n\n p = src;\n out.data = src;\n\n for (q = ngx_queue_head(frames);\n q != ngx_queue_sentinel(frames);\n q = ngx_queue_next(q))\n {\n f = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic frame out: %s\", f->info);\n\n len = ngx_quic_create_frame(p, f);\n if (len == -1) {\n return NGX_ERROR;\n }\n\n if (f->need_ack) {\n pkt.need_ack = 1;\n }\n\n p += len;\n f->pnum = ctx->pnum;\n f->last = now;\n f->plen = 0;\n }\n\n out.len = p - out.data;\n\n while (out.len < 4) {\n *p++ = NGX_QUIC_FT_PADDING;\n out.len++;\n }\n\n qc = c->quic;\n\n keys = &c->quic->keys[start->level];\n\n pkt.secret = &keys->server;\n\n pkt.flags = NGX_QUIC_PKT_FIXED_BIT;\n\n if (start->level == ssl_encryption_initial) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_INITIAL;\n pkt.token = initial_token;\n\n } else if (start->level == ssl_encryption_handshake) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_HANDSHAKE;\n\n } else {\n if (c->quic->key_phase) {\n pkt.flags |= NGX_QUIC_PKT_KPHASE;\n }\n }\n\n ngx_quic_set_packet_number(&pkt, ctx);\n\n pkt.log = c->log;\n pkt.level = start->level;\n pkt.dcid = qc->scid;\n pkt.scid = qc->dcid;\n pkt.payload = out;\n\n res.data = dst;\n\n ngx_log_debug6(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic packet ready: %ui bytes at level %d\"\n \" need_ack: %d number: %L encoded %d:0x%xD\",\n out.len, start->level, pkt.need_ack, pkt.number,\n pkt.num_len, pkt.trunc);\n\n if (ngx_quic_encrypt(&pkt, ssl_conn, &res) != NGX_OK) {\n return NGX_ERROR;\n }\n\n len = c->send(c, res.data, res.len);\n if (len == NGX_ERROR || (size_t) len != res.len) {\n return NGX_ERROR;\n }\n\n /* len == NGX_OK || NGX_AGAIN */\n ctx->pnum++;\n\n if (pkt.need_ack) {\n /* move frames into the sent queue to wait for ack */\n\n if (qc->closing) {\n /* if we are closing, any ack will be discarded */\n ngx_quic_free_frames(c, frames);\n\n } else {\n ngx_queue_add(&ctx->sent, frames);\n if (qc->pto.timer_set) {\n ngx_del_timer(&qc->pto);\n }\n ngx_add_timer(&qc->pto, ngx_quic_pto(c, ctx));\n\n start->plen = len;\n }\n\n qc->congestion.in_flight += len;\n<|edits_diff|>\n--- src/event/ngx_event_quic.c\n+++ src/event/ngx_event_quic.c\n@@ -20,6 +20,7 @@\n \n len = ngx_quic_create_frame(p, f);\n if (len == -1) {\n+ ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n \n@@ -78,6 +79,7 @@\n pkt.num_len, pkt.trunc);\n \n if (ngx_quic_encrypt(&pkt, ssl_conn, &res) != NGX_OK) {\n+ ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n \n<|current_version|>\n\n q = ngx_queue_head(frames);\n start = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_memzero(&pkt, sizeof(ngx_quic_header_t));\n\n now = ngx_current_msec;\n\n p = src;\n out.data = src;\n\n for (q = ngx_queue_head(frames);\n q != ngx_queue_sentinel(frames);\n q = ngx_queue_next(q))\n {\n f = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic frame out: %s\", f->info);\n\n len = ngx_quic_create_frame(p, f);\n if (len == -1) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n if (f->need_ack) {\n pkt.need_ack = 1;\n }\n\n p += len;\n f->pnum = ctx->pnum;\n f->last = now;\n f->plen = 0;\n }\n\n out.len = p - out.data;\n\n while (out.len < 4) {\n *p++ = NGX_QUIC_FT_PADDING;\n out.len++;\n }\n\n qc = c->quic;\n\n keys = &c->quic->keys[start->level];\n\n pkt.secret = &keys->server;\n\n pkt.flags = NGX_QUIC_PKT_FIXED_BIT;\n\n if (start->level == ssl_encryption_initial) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_INITIAL;\n pkt.token = initial_token;\n\n } else if (start->level == ssl_encryption_handshake) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_HANDSHAKE;\n\n } else {\n if (c->quic->key_phase) {\n pkt.flags |= NGX_QUIC_PKT_KPHASE;\n }\n }\n\n ngx_quic_set_packet_number(&pkt, ctx);\n\n pkt.log = c->log;\n pkt.level = start->level;\n pkt.dcid = qc->scid;\n pkt.scid = qc->dcid;\n pkt.payload = out;\n\n res.data = dst;\n\n ngx_log_debug6(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic packet ready: %ui bytes at level %d\"\n \" need_ack: %d number: %L encoded %d:0x%xD\",\n out.len, start->level, pkt.need_ack, pkt.number,\n pkt.num_len, pkt.trunc);\n\n if (ngx_quic_encrypt(&pkt, ssl_conn, &res) != NGX_OK) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n len = c->send(c, res.data, res.len);\n if (len == NGX_ERROR || (size_t) len != res.len) {\n return NGX_ERROR;\n }\n\n /* len == NGX_OK || NGX_AGAIN */\n ctx->pnum++;\n\n if (pkt.need_ack) {\n /* move frames into the sent queue to wait for ack */\n\n if (qc->closing) {\n /* if we are closing, any ack will be discarded */\n ngx_quic_free_frames(c, frames);\n\n } else {\n ngx_queue_add(&ctx->sent, frames);\n if (qc->pto.timer_set) {\n ngx_del_timer(&qc->pto);\n }\n ngx_add_timer(&qc->pto, ngx_quic_pto(c, ctx));\n\n start->plen = len;\n }\n\n qc->congestion.in_flight += len;\n<|next_version|>\n\n q = ngx_queue_head(frames);\n start = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_memzero(&pkt, sizeof(ngx_quic_header_t));\n\n now = ngx_current_msec;\n\n p = src;\n out.data = src;\n\n for (q = ngx_queue_head(frames);\n q != ngx_queue_sentinel(frames);\n q = ngx_queue_next(q))\n {\n f = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic frame out: %s\", f->info);\n\n len = ngx_quic_create_frame(p, f);\n if (len == -1) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n if (f->need_ack) {\n pkt.need_ack = 1;\n }\n\n p += len;\n f->pnum = ctx->pnum;\n f->last = now;\n f->plen = 0;\n }\n\n out.len = p - out.data;\n\n while (out.len < 4) {\n *p++ = NGX_QUIC_FT_PADDING;\n out.len++;\n }\n\n qc = c->quic;\n\n keys = &c->quic->keys[start->level];\n\n pkt.secret = &keys->server;\n\n pkt.flags = NGX_QUIC_PKT_FIXED_BIT;\n\n if (start->level == ssl_encryption_initial) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_INITIAL;\n pkt.token = initial_token;\n\n } else if (start->level == ssl_encryption_handshake) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_HANDSHAKE;\n\n } else {\n if (c->quic->key_phase) {\n pkt.flags |= NGX_QUIC_PKT_KPHASE;\n }\n }\n\n ngx_quic_set_packet_number(&pkt, ctx);\n\n pkt.log = c->log;\n pkt.level = start->level;\n pkt.dcid = qc->scid;\n pkt.scid = qc->dcid;\n pkt.payload = out;\n\n res.data = dst;\n\n ngx_log_debug6(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic packet ready: %ui bytes at level %d\"\n \" need_ack: %d number: %L encoded %d:0x%xD\",\n out.len, start->level, pkt.need_ack, pkt.number,\n pkt.num_len, pkt.trunc);\n\n if (ngx_quic_encrypt(&pkt, ssl_conn, &res) != NGX_OK) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n len = c->send(c, res.data, res.len);\n if (len == NGX_ERROR || (size_t) len != res.len) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n /* len == NGX_OK || NGX_AGAIN */\n ctx->pnum++;\n\n if (pkt.need_ack) {\n /* move frames into the sent queue to wait for ack */\n\n if (qc->closing) {\n /* if we are closing, any ack will be discarded */\n ngx_quic_free_frames(c, frames);\n\n } else {\n ngx_queue_add(&ctx->sent, frames);\n if (qc->pto.timer_set) {\n ngx_del_timer(&qc->pto);\n }\n ngx_add_timer(&qc->pto, ngx_quic_pto(c, ctx));\n\n start->plen = len;\n }\n\n qc->congestion.in_flight += len;\n", "current_contents": "\n q = ngx_queue_head(frames);\n start = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_memzero(&pkt, sizeof(ngx_quic_header_t));\n\n now = ngx_current_msec;\n\n p = src;\n out.data = src;\n\n for (q = ngx_queue_head(frames);\n q != ngx_queue_sentinel(frames);\n q = ngx_queue_next(q))\n {\n f = ngx_queue_data(q, ngx_quic_frame_t, queue);\n\n ngx_log_debug1(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic frame out: %s\", f->info);\n\n len = ngx_quic_create_frame(p, f);\n if (len == -1) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n if (f->need_ack) {\n pkt.need_ack = 1;\n }\n\n p += len;\n f->pnum = ctx->pnum;\n f->last = now;\n f->plen = 0;\n }\n\n out.len = p - out.data;\n\n while (out.len < 4) {\n *p++ = NGX_QUIC_FT_PADDING;\n out.len++;\n }\n\n qc = c->quic;\n\n keys = &c->quic->keys[start->level];\n\n pkt.secret = &keys->server;\n\n pkt.flags = NGX_QUIC_PKT_FIXED_BIT;\n\n if (start->level == ssl_encryption_initial) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_INITIAL;\n pkt.token = initial_token;\n\n } else if (start->level == ssl_encryption_handshake) {\n pkt.flags |= NGX_QUIC_PKT_LONG | NGX_QUIC_PKT_HANDSHAKE;\n\n } else {\n if (c->quic->key_phase) {\n pkt.flags |= NGX_QUIC_PKT_KPHASE;\n }\n }\n\n ngx_quic_set_packet_number(&pkt, ctx);\n\n pkt.log = c->log;\n pkt.level = start->level;\n pkt.dcid = qc->scid;\n pkt.scid = qc->dcid;\n pkt.payload = out;\n\n res.data = dst;\n\n ngx_log_debug6(NGX_LOG_DEBUG_EVENT, c->log, 0,\n \"quic packet ready: %ui bytes at level %d\"\n \" need_ack: %d number: %L encoded %d:0x%xD\",\n out.len, start->level, pkt.need_ack, pkt.number,\n pkt.num_len, pkt.trunc);\n\n if (ngx_quic_encrypt(&pkt, ssl_conn, &res) != NGX_OK) {\n ngx_quic_free_frames(c, frames);\n return NGX_ERROR;\n }\n\n len = c->send(c, res.data, res.len);\n if (len == NGX_ERROR || (size_t) len != res.len) {\n return NGX_ERROR;\n }\n\n /* len == NGX_OK || NGX_AGAIN */\n ctx->pnum++;\n\n if (pkt.need_ack) {\n /* move frames into the sent queue to wait for ack */\n\n if (qc->closing) {\n /* if we are closing, any ack will be discarded */\n ngx_quic_free_frames(c, frames);\n\n } else {\n ngx_queue_add(&ctx->sent, frames);\n if (qc->pto.timer_set) {\n ngx_del_timer(&qc->pto);\n }\n ngx_add_timer(&qc->pto, ngx_quic_pto(c, ctx));\n\n start->plen = len;\n }\n\n qc->congestion.in_flight += len;"} {"commit": "36f2873f6b0d8512c053935614fcc6ae9d969858", "message": "QUIC: added \"quic\" listen parameter in Stream.", "old_file": "src/stream/ngx_stream.c", "new_file": "src/stream/ngx_stream.c", "status": "M", "old_contents": "{\n ngx_uint_t i;\n struct sockaddr_in *sin;\n ngx_stream_in_addr_t *addrs;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_stream_add_addrs6(ngx_conf_t *cf, ngx_stream_port_t *stport,\n ngx_stream_conf_addr_t *addr)\n{\n ngx_uint_t i;\n struct sockaddr_in6 *sin6;\n ngx_stream_in6_addr_t *addrs6;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in6_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_stream_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_stream_conf_addr_t *first, *second;\n\n first = (ngx_stream_conf_addr_t *) one;\n second = (ngx_stream_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {", "new_contents": "{\n ngx_uint_t i;\n struct sockaddr_in *sin;\n ngx_stream_in_addr_t *addrs;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n#if (NGX_STREAM_QUIC)\n addrs[i].conf.quic = addr[i].opt.quic;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_stream_add_addrs6(ngx_conf_t *cf, ngx_stream_port_t *stport,\n ngx_stream_conf_addr_t *addr)\n{\n ngx_uint_t i;\n struct sockaddr_in6 *sin6;\n ngx_stream_in6_addr_t *addrs6;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in6_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n#if (NGX_STREAM_QUIC)\n addrs6[i].conf.quic = addr[i].opt.quic;\n#endif\n addrs6[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_stream_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_stream_conf_addr_t *first, *second;\n\n first = (ngx_stream_conf_addr_t *) one;\n second = (ngx_stream_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {", "text": "<|original_code|>\n{\n ngx_uint_t i;\n struct sockaddr_in *sin;\n ngx_stream_in_addr_t *addrs;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_stream_add_addrs6(ngx_conf_t *cf, ngx_stream_port_t *stport,\n ngx_stream_conf_addr_t *addr)\n{\n ngx_uint_t i;\n struct sockaddr_in6 *sin6;\n ngx_stream_in6_addr_t *addrs6;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in6_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_stream_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_stream_conf_addr_t *first, *second;\n\n first = (ngx_stream_conf_addr_t *) one;\n second = (ngx_stream_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n<|edits_diff|>\n--- src/stream/ngx_stream.c\n+++ src/stream/ngx_stream.c\n@@ -19,6 +19,9 @@\n addrs[i].conf.ctx = addr[i].opt.ctx;\n #if (NGX_STREAM_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n+#endif\n+#if (NGX_STREAM_QUIC)\n+ addrs[i].conf.quic = addr[i].opt.quic;\n #endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n<|current_version|>\n{\n ngx_uint_t i;\n struct sockaddr_in *sin;\n ngx_stream_in_addr_t *addrs;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n#if (NGX_STREAM_QUIC)\n addrs[i].conf.quic = addr[i].opt.quic;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_stream_add_addrs6(ngx_conf_t *cf, ngx_stream_port_t *stport,\n ngx_stream_conf_addr_t *addr)\n{\n ngx_uint_t i;\n struct sockaddr_in6 *sin6;\n ngx_stream_in6_addr_t *addrs6;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in6_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_stream_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_stream_conf_addr_t *first, *second;\n\n first = (ngx_stream_conf_addr_t *) one;\n second = (ngx_stream_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n<|next_version|>\n{\n ngx_uint_t i;\n struct sockaddr_in *sin;\n ngx_stream_in_addr_t *addrs;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n#if (NGX_STREAM_QUIC)\n addrs[i].conf.quic = addr[i].opt.quic;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_stream_add_addrs6(ngx_conf_t *cf, ngx_stream_port_t *stport,\n ngx_stream_conf_addr_t *addr)\n{\n ngx_uint_t i;\n struct sockaddr_in6 *sin6;\n ngx_stream_in6_addr_t *addrs6;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in6_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n#if (NGX_STREAM_QUIC)\n addrs6[i].conf.quic = addr[i].opt.quic;\n#endif\n addrs6[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_stream_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_stream_conf_addr_t *first, *second;\n\n first = (ngx_stream_conf_addr_t *) one;\n second = (ngx_stream_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {\n", "current_contents": "{\n ngx_uint_t i;\n struct sockaddr_in *sin;\n ngx_stream_in_addr_t *addrs;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin = (struct sockaddr_in *) addr[i].opt.sockaddr;\n addrs[i].addr = sin->sin_addr.s_addr;\n\n addrs[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs[i].conf.ssl = addr[i].opt.ssl;\n#endif\n#if (NGX_STREAM_QUIC)\n addrs[i].conf.quic = addr[i].opt.quic;\n#endif\n addrs[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n\n#if (NGX_HAVE_INET6)\n\nstatic ngx_int_t\nngx_stream_add_addrs6(ngx_conf_t *cf, ngx_stream_port_t *stport,\n ngx_stream_conf_addr_t *addr)\n{\n ngx_uint_t i;\n struct sockaddr_in6 *sin6;\n ngx_stream_in6_addr_t *addrs6;\n\n stport->addrs = ngx_pcalloc(cf->pool,\n stport->naddrs * sizeof(ngx_stream_in6_addr_t));\n if (stport->addrs == NULL) {\n return NGX_ERROR;\n }\n\n addrs6 = stport->addrs;\n\n for (i = 0; i < stport->naddrs; i++) {\n\n sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;\n addrs6[i].addr6 = sin6->sin6_addr;\n\n addrs6[i].conf.ctx = addr[i].opt.ctx;\n#if (NGX_STREAM_SSL)\n addrs6[i].conf.ssl = addr[i].opt.ssl;\n#endif\n addrs6[i].conf.proxy_protocol = addr[i].opt.proxy_protocol;\n addrs6[i].conf.addr_text = addr[i].opt.addr_text;\n }\n\n return NGX_OK;\n}\n\n#endif\n\n\nstatic ngx_int_t\nngx_stream_cmp_conf_addrs(const void *one, const void *two)\n{\n ngx_stream_conf_addr_t *first, *second;\n\n first = (ngx_stream_conf_addr_t *) one;\n second = (ngx_stream_conf_addr_t *) two;\n\n if (first->opt.wildcard) {\n /* a wildcard must be the last resort, shift it to the end */\n return 1;\n }\n\n if (second->opt.wildcard) {"} {"commit": "bac0cb3bbd507400c9dbac03eacbb6c6937efccd", "message": "Status: introduced the \"ngx_stat_waiting\" counter.", "old_file": "src/core/ngx_connection.c", "new_file": "src/core/ngx_connection.c", "status": "M", "old_contents": " }\n\n } else {\n level = NGX_LOG_CRIT;\n }\n\n /* we use ngx_cycle->log because c->log was in c->pool */\n\n ngx_log_error(level, ngx_cycle->log, err,\n ngx_close_socket_n \" %d failed\", fd);\n }\n}\n\n\nvoid\nngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)\n{\n ngx_log_debug1(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusable connection: %ui\", reusable);\n\n if (c->reusable) {\n ngx_queue_remove(&c->queue);\n }\n\n c->reusable = reusable;\n\n if (reusable) {\n /* need cast as ngx_cycle is volatile */\n\n ngx_queue_insert_head(\n (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);\n }\n}\n\n\nstatic void\nngx_drain_connections(void)\n{\n ngx_int_t i;\n ngx_queue_t *q;\n ngx_connection_t *c;\n\n for (i = 0; i < 32; i++) {\n if (ngx_queue_empty(&ngx_cycle->reusable_connections_queue)) {\n break;\n }\n\n q = ngx_queue_last(&ngx_cycle->reusable_connections_queue);\n c = ngx_queue_data(q, ngx_connection_t, queue);\n\n ngx_log_debug0(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusing connection\");\n\n c->close = 1;\n c->read->handler(c->read);", "new_contents": " }\n\n } else {\n level = NGX_LOG_CRIT;\n }\n\n /* we use ngx_cycle->log because c->log was in c->pool */\n\n ngx_log_error(level, ngx_cycle->log, err,\n ngx_close_socket_n \" %d failed\", fd);\n }\n}\n\n\nvoid\nngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)\n{\n ngx_log_debug1(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusable connection: %ui\", reusable);\n\n if (c->reusable) {\n ngx_queue_remove(&c->queue);\n\n#if (NGX_STAT_STUB)\n (void) ngx_atomic_fetch_add(ngx_stat_waiting, -1);\n#endif\n }\n\n c->reusable = reusable;\n\n if (reusable) {\n /* need cast as ngx_cycle is volatile */\n\n ngx_queue_insert_head(\n (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);\n\n#if (NGX_STAT_STUB)\n (void) ngx_atomic_fetch_add(ngx_stat_waiting, 1);\n#endif\n }\n}\n\n\nstatic void\nngx_drain_connections(void)\n{\n ngx_int_t i;\n ngx_queue_t *q;\n ngx_connection_t *c;\n\n for (i = 0; i < 32; i++) {\n if (ngx_queue_empty(&ngx_cycle->reusable_connections_queue)) {\n break;\n }\n\n q = ngx_queue_last(&ngx_cycle->reusable_connections_queue);\n c = ngx_queue_data(q, ngx_connection_t, queue);\n\n ngx_log_debug0(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusing connection\");\n\n c->close = 1;\n c->read->handler(c->read);", "text": "<|original_code|>\n }\n\n } else {\n level = NGX_LOG_CRIT;\n }\n\n /* we use ngx_cycle->log because c->log was in c->pool */\n\n ngx_log_error(level, ngx_cycle->log, err,\n ngx_close_socket_n \" %d failed\", fd);\n }\n}\n\n\nvoid\nngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)\n{\n ngx_log_debug1(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusable connection: %ui\", reusable);\n\n if (c->reusable) {\n ngx_queue_remove(&c->queue);\n }\n\n c->reusable = reusable;\n\n if (reusable) {\n /* need cast as ngx_cycle is volatile */\n\n ngx_queue_insert_head(\n (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);\n }\n}\n\n\nstatic void\nngx_drain_connections(void)\n{\n ngx_int_t i;\n ngx_queue_t *q;\n ngx_connection_t *c;\n\n for (i = 0; i < 32; i++) {\n if (ngx_queue_empty(&ngx_cycle->reusable_connections_queue)) {\n break;\n }\n\n q = ngx_queue_last(&ngx_cycle->reusable_connections_queue);\n c = ngx_queue_data(q, ngx_connection_t, queue);\n\n ngx_log_debug0(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusing connection\");\n\n c->close = 1;\n c->read->handler(c->read);\n<|edits_diff|>\n--- src/core/ngx_connection.c\n+++ src/core/ngx_connection.c\n@@ -20,6 +20,10 @@\n \n if (c->reusable) {\n ngx_queue_remove(&c->queue);\n+\n+#if (NGX_STAT_STUB)\n+ (void) ngx_atomic_fetch_add(ngx_stat_waiting, -1);\n+#endif\n }\n \n c->reusable = reusable;\n<|current_version|>\n }\n\n } else {\n level = NGX_LOG_CRIT;\n }\n\n /* we use ngx_cycle->log because c->log was in c->pool */\n\n ngx_log_error(level, ngx_cycle->log, err,\n ngx_close_socket_n \" %d failed\", fd);\n }\n}\n\n\nvoid\nngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)\n{\n ngx_log_debug1(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusable connection: %ui\", reusable);\n\n if (c->reusable) {\n ngx_queue_remove(&c->queue);\n\n#if (NGX_STAT_STUB)\n (void) ngx_atomic_fetch_add(ngx_stat_waiting, -1);\n#endif\n }\n\n c->reusable = reusable;\n\n if (reusable) {\n /* need cast as ngx_cycle is volatile */\n\n ngx_queue_insert_head(\n (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);\n }\n}\n\n\nstatic void\nngx_drain_connections(void)\n{\n ngx_int_t i;\n ngx_queue_t *q;\n ngx_connection_t *c;\n\n for (i = 0; i < 32; i++) {\n if (ngx_queue_empty(&ngx_cycle->reusable_connections_queue)) {\n break;\n }\n\n q = ngx_queue_last(&ngx_cycle->reusable_connections_queue);\n c = ngx_queue_data(q, ngx_connection_t, queue);\n\n ngx_log_debug0(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusing connection\");\n\n c->close = 1;\n c->read->handler(c->read);\n<|next_version|>\n }\n\n } else {\n level = NGX_LOG_CRIT;\n }\n\n /* we use ngx_cycle->log because c->log was in c->pool */\n\n ngx_log_error(level, ngx_cycle->log, err,\n ngx_close_socket_n \" %d failed\", fd);\n }\n}\n\n\nvoid\nngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)\n{\n ngx_log_debug1(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusable connection: %ui\", reusable);\n\n if (c->reusable) {\n ngx_queue_remove(&c->queue);\n\n#if (NGX_STAT_STUB)\n (void) ngx_atomic_fetch_add(ngx_stat_waiting, -1);\n#endif\n }\n\n c->reusable = reusable;\n\n if (reusable) {\n /* need cast as ngx_cycle is volatile */\n\n ngx_queue_insert_head(\n (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);\n\n#if (NGX_STAT_STUB)\n (void) ngx_atomic_fetch_add(ngx_stat_waiting, 1);\n#endif\n }\n}\n\n\nstatic void\nngx_drain_connections(void)\n{\n ngx_int_t i;\n ngx_queue_t *q;\n ngx_connection_t *c;\n\n for (i = 0; i < 32; i++) {\n if (ngx_queue_empty(&ngx_cycle->reusable_connections_queue)) {\n break;\n }\n\n q = ngx_queue_last(&ngx_cycle->reusable_connections_queue);\n c = ngx_queue_data(q, ngx_connection_t, queue);\n\n ngx_log_debug0(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusing connection\");\n\n c->close = 1;\n c->read->handler(c->read);\n", "current_contents": " }\n\n } else {\n level = NGX_LOG_CRIT;\n }\n\n /* we use ngx_cycle->log because c->log was in c->pool */\n\n ngx_log_error(level, ngx_cycle->log, err,\n ngx_close_socket_n \" %d failed\", fd);\n }\n}\n\n\nvoid\nngx_reusable_connection(ngx_connection_t *c, ngx_uint_t reusable)\n{\n ngx_log_debug1(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusable connection: %ui\", reusable);\n\n if (c->reusable) {\n ngx_queue_remove(&c->queue);\n\n#if (NGX_STAT_STUB)\n (void) ngx_atomic_fetch_add(ngx_stat_waiting, -1);\n#endif\n }\n\n c->reusable = reusable;\n\n if (reusable) {\n /* need cast as ngx_cycle is volatile */\n\n ngx_queue_insert_head(\n (ngx_queue_t *) &ngx_cycle->reusable_connections_queue, &c->queue);\n }\n}\n\n\nstatic void\nngx_drain_connections(void)\n{\n ngx_int_t i;\n ngx_queue_t *q;\n ngx_connection_t *c;\n\n for (i = 0; i < 32; i++) {\n if (ngx_queue_empty(&ngx_cycle->reusable_connections_queue)) {\n break;\n }\n\n q = ngx_queue_last(&ngx_cycle->reusable_connections_queue);\n c = ngx_queue_data(q, ngx_connection_t, queue);\n\n ngx_log_debug0(NGX_LOG_DEBUG_CORE, c->log, 0,\n \"reusing connection\");\n\n c->close = 1;\n c->read->handler(c->read);"} {"commit": "1b9b19d7e2a2fcd3d2b773b64f198cec354f384c", "message": "Added escaping of double quotes in ngx_escape_html().", "old_file": "src/core/ngx_string.c", "new_file": "src/core/ngx_string.c", "status": "M", "old_contents": " u_char ch;\n ngx_uint_t len;\n\n if (dst == NULL) {\n\n len = 0;\n\n while (size) {\n switch (*src++) {\n\n case '<':\n len += sizeof(\"<\") - 2;\n break;\n\n case '>':\n len += sizeof(\">\") - 2;\n break;\n\n case '&':\n len += sizeof(\"&\") - 2;\n break;\n\n default:\n break;\n }\n size--;\n }\n\n return (uintptr_t) len;\n }\n\n while (size) {\n ch = *src++;\n\n switch (ch) {\n\n case '<':\n *dst++ = '&'; *dst++ = 'l'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '>':\n *dst++ = '&'; *dst++ = 'g'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '&':\n *dst++ = '&'; *dst++ = 'a'; *dst++ = 'm'; *dst++ = 'p';\n *dst++ = ';';\n break;\n\n default:\n *dst++ = ch;\n break;\n }\n size--;\n }\n\n return (uintptr_t) dst;\n}\n\n\nvoid\nngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp,\n ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel)\n{\n ngx_str_node_t *n, *t;\n ngx_rbtree_node_t **p;\n\n for ( ;; ) {\n\n n = (ngx_str_node_t *) node;\n t = (ngx_str_node_t *) temp;", "new_contents": " u_char ch;\n ngx_uint_t len;\n\n if (dst == NULL) {\n\n len = 0;\n\n while (size) {\n switch (*src++) {\n\n case '<':\n len += sizeof(\"<\") - 2;\n break;\n\n case '>':\n len += sizeof(\">\") - 2;\n break;\n\n case '&':\n len += sizeof(\"&\") - 2;\n break;\n\n case '\"':\n len += sizeof(\""\") - 2;\n break;\n\n default:\n break;\n }\n size--;\n }\n\n return (uintptr_t) len;\n }\n\n while (size) {\n ch = *src++;\n\n switch (ch) {\n\n case '<':\n *dst++ = '&'; *dst++ = 'l'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '>':\n *dst++ = '&'; *dst++ = 'g'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '&':\n *dst++ = '&'; *dst++ = 'a'; *dst++ = 'm'; *dst++ = 'p';\n *dst++ = ';';\n break;\n\n case '\"':\n *dst++ = '&'; *dst++ = 'q'; *dst++ = 'u'; *dst++ = 'o';\n *dst++ = 't'; *dst++ = ';';\n break;\n\n default:\n *dst++ = ch;\n break;\n }\n size--;\n }\n\n return (uintptr_t) dst;\n}\n\n\nvoid\nngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp,\n ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel)\n{\n ngx_str_node_t *n, *t;\n ngx_rbtree_node_t **p;\n\n for ( ;; ) {\n\n n = (ngx_str_node_t *) node;\n t = (ngx_str_node_t *) temp;", "text": "<|original_code|>\n u_char ch;\n ngx_uint_t len;\n\n if (dst == NULL) {\n\n len = 0;\n\n while (size) {\n switch (*src++) {\n\n case '<':\n len += sizeof(\"<\") - 2;\n break;\n\n case '>':\n len += sizeof(\">\") - 2;\n break;\n\n case '&':\n len += sizeof(\"&\") - 2;\n break;\n\n default:\n break;\n }\n size--;\n }\n\n return (uintptr_t) len;\n }\n\n while (size) {\n ch = *src++;\n\n switch (ch) {\n\n case '<':\n *dst++ = '&'; *dst++ = 'l'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '>':\n *dst++ = '&'; *dst++ = 'g'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '&':\n *dst++ = '&'; *dst++ = 'a'; *dst++ = 'm'; *dst++ = 'p';\n *dst++ = ';';\n break;\n\n default:\n *dst++ = ch;\n break;\n }\n size--;\n }\n\n return (uintptr_t) dst;\n}\n\n\nvoid\nngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp,\n ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel)\n{\n ngx_str_node_t *n, *t;\n ngx_rbtree_node_t **p;\n\n for ( ;; ) {\n\n n = (ngx_str_node_t *) node;\n t = (ngx_str_node_t *) temp;\n<|edits_diff|>\n--- src/core/ngx_string.c\n+++ src/core/ngx_string.c\n@@ -18,6 +18,10 @@\n \n case '&':\n len += sizeof(\"&\") - 2;\n+ break;\n+\n+ case '\"':\n+ len += sizeof(\""\") - 2;\n break;\n \n default:\n<|current_version|>\n u_char ch;\n ngx_uint_t len;\n\n if (dst == NULL) {\n\n len = 0;\n\n while (size) {\n switch (*src++) {\n\n case '<':\n len += sizeof(\"<\") - 2;\n break;\n\n case '>':\n len += sizeof(\">\") - 2;\n break;\n\n case '&':\n len += sizeof(\"&\") - 2;\n break;\n\n case '\"':\n len += sizeof(\""\") - 2;\n break;\n\n default:\n break;\n }\n size--;\n }\n\n return (uintptr_t) len;\n }\n\n while (size) {\n ch = *src++;\n\n switch (ch) {\n\n case '<':\n *dst++ = '&'; *dst++ = 'l'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '>':\n *dst++ = '&'; *dst++ = 'g'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '&':\n *dst++ = '&'; *dst++ = 'a'; *dst++ = 'm'; *dst++ = 'p';\n *dst++ = ';';\n break;\n\n default:\n *dst++ = ch;\n break;\n }\n size--;\n }\n\n return (uintptr_t) dst;\n}\n\n\nvoid\nngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp,\n ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel)\n{\n ngx_str_node_t *n, *t;\n ngx_rbtree_node_t **p;\n\n for ( ;; ) {\n\n n = (ngx_str_node_t *) node;\n t = (ngx_str_node_t *) temp;\n<|next_version|>\n u_char ch;\n ngx_uint_t len;\n\n if (dst == NULL) {\n\n len = 0;\n\n while (size) {\n switch (*src++) {\n\n case '<':\n len += sizeof(\"<\") - 2;\n break;\n\n case '>':\n len += sizeof(\">\") - 2;\n break;\n\n case '&':\n len += sizeof(\"&\") - 2;\n break;\n\n case '\"':\n len += sizeof(\""\") - 2;\n break;\n\n default:\n break;\n }\n size--;\n }\n\n return (uintptr_t) len;\n }\n\n while (size) {\n ch = *src++;\n\n switch (ch) {\n\n case '<':\n *dst++ = '&'; *dst++ = 'l'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '>':\n *dst++ = '&'; *dst++ = 'g'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '&':\n *dst++ = '&'; *dst++ = 'a'; *dst++ = 'm'; *dst++ = 'p';\n *dst++ = ';';\n break;\n\n case '\"':\n *dst++ = '&'; *dst++ = 'q'; *dst++ = 'u'; *dst++ = 'o';\n *dst++ = 't'; *dst++ = ';';\n break;\n\n default:\n *dst++ = ch;\n break;\n }\n size--;\n }\n\n return (uintptr_t) dst;\n}\n\n\nvoid\nngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp,\n ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel)\n{\n ngx_str_node_t *n, *t;\n ngx_rbtree_node_t **p;\n\n for ( ;; ) {\n\n n = (ngx_str_node_t *) node;\n t = (ngx_str_node_t *) temp;\n", "current_contents": " u_char ch;\n ngx_uint_t len;\n\n if (dst == NULL) {\n\n len = 0;\n\n while (size) {\n switch (*src++) {\n\n case '<':\n len += sizeof(\"<\") - 2;\n break;\n\n case '>':\n len += sizeof(\">\") - 2;\n break;\n\n case '&':\n len += sizeof(\"&\") - 2;\n break;\n\n case '\"':\n len += sizeof(\""\") - 2;\n break;\n\n default:\n break;\n }\n size--;\n }\n\n return (uintptr_t) len;\n }\n\n while (size) {\n ch = *src++;\n\n switch (ch) {\n\n case '<':\n *dst++ = '&'; *dst++ = 'l'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '>':\n *dst++ = '&'; *dst++ = 'g'; *dst++ = 't'; *dst++ = ';';\n break;\n\n case '&':\n *dst++ = '&'; *dst++ = 'a'; *dst++ = 'm'; *dst++ = 'p';\n *dst++ = ';';\n break;\n\n default:\n *dst++ = ch;\n break;\n }\n size--;\n }\n\n return (uintptr_t) dst;\n}\n\n\nvoid\nngx_str_rbtree_insert_value(ngx_rbtree_node_t *temp,\n ngx_rbtree_node_t *node, ngx_rbtree_node_t *sentinel)\n{\n ngx_str_node_t *n, *t;\n ngx_rbtree_node_t **p;\n\n for ( ;; ) {\n\n n = (ngx_str_node_t *) node;\n t = (ngx_str_node_t *) temp;"} {"commit": "42feecbdb694e114e034f0be67d19bba4165c363", "message": "nginx-0.0.1-2002-12-15-09:25:09 import", "old_file": "src/http/ngx_http_modules.c", "new_file": "src/http/ngx_http_modules.c", "status": "M", "old_contents": "\n#include \n\nextern ngx_http_module_t ngx_http_write_filter_module;\nextern ngx_http_module_t ngx_http_output_filter_module;\nextern ngx_http_module_t ngx_http_core_module;\nextern ngx_http_module_t ngx_http_index_module;\n\nngx_http_module_t *ngx_http_modules[] = {\n &ngx_http_write_filter_module,\n &ngx_http_output_filter_module,\n\n &ngx_http_index_module,\n &ngx_http_core_module,\n\n NULL\n};\n", "new_contents": "\n#include \n\nextern ngx_http_module_t ngx_http_header_filter_module;\n\nextern ngx_http_module_t ngx_http_write_filter_module;\nextern ngx_http_module_t ngx_http_output_filter_module;\n\nextern ngx_http_module_t ngx_http_core_module;\nextern ngx_http_module_t ngx_http_index_module;\n\nngx_http_module_t *ngx_http_modules[] = {\n\n &ngx_http_header_filter_module,\n\n &ngx_http_write_filter_module,\n &ngx_http_output_filter_module,\n\n &ngx_http_index_module,\n &ngx_http_core_module,\n\n NULL\n};\n", "text": "<|original_code|>\n\n#include \n\nextern ngx_http_module_t ngx_http_write_filter_module;\nextern ngx_http_module_t ngx_http_output_filter_module;\nextern ngx_http_module_t ngx_http_core_module;\nextern ngx_http_module_t ngx_http_index_module;\n\nngx_http_module_t *ngx_http_modules[] = {\n &ngx_http_write_filter_module,\n &ngx_http_output_filter_module,\n\n &ngx_http_index_module,\n &ngx_http_core_module,\n\n NULL\n};\n\n<|edits_diff|>\n--- src/http/ngx_http_modules.c\n+++ src/http/ngx_http_modules.c\n@@ -1,8 +1,11 @@\n \n #include \n \n+extern ngx_http_module_t ngx_http_header_filter_module;\n+\n extern ngx_http_module_t ngx_http_write_filter_module;\n extern ngx_http_module_t ngx_http_output_filter_module;\n+\n extern ngx_http_module_t ngx_http_core_module;\n extern ngx_http_module_t ngx_http_index_module;\n \n<|current_version|>\n\n#include \n\nextern ngx_http_module_t ngx_http_header_filter_module;\n\nextern ngx_http_module_t ngx_http_write_filter_module;\nextern ngx_http_module_t ngx_http_output_filter_module;\n\nextern ngx_http_module_t ngx_http_core_module;\nextern ngx_http_module_t ngx_http_index_module;\n\nngx_http_module_t *ngx_http_modules[] = {\n &ngx_http_write_filter_module,\n &ngx_http_output_filter_module,\n\n &ngx_http_index_module,\n &ngx_http_core_module,\n\n NULL\n};\n\n<|next_version|>\n\n#include \n\nextern ngx_http_module_t ngx_http_header_filter_module;\n\nextern ngx_http_module_t ngx_http_write_filter_module;\nextern ngx_http_module_t ngx_http_output_filter_module;\n\nextern ngx_http_module_t ngx_http_core_module;\nextern ngx_http_module_t ngx_http_index_module;\n\nngx_http_module_t *ngx_http_modules[] = {\n\n &ngx_http_header_filter_module,\n\n &ngx_http_write_filter_module,\n &ngx_http_output_filter_module,\n\n &ngx_http_index_module,\n &ngx_http_core_module,\n\n NULL\n};\n\n", "current_contents": "\n#include \n\nextern ngx_http_module_t ngx_http_header_filter_module;\n\nextern ngx_http_module_t ngx_http_write_filter_module;\nextern ngx_http_module_t ngx_http_output_filter_module;\n\nextern ngx_http_module_t ngx_http_core_module;\nextern ngx_http_module_t ngx_http_index_module;\n\nngx_http_module_t *ngx_http_modules[] = {\n &ngx_http_write_filter_module,\n &ngx_http_output_filter_module,\n\n &ngx_http_index_module,\n &ngx_http_core_module,\n\n NULL\n};\n"} {"commit": "c66628e52b3727507666fc84c0458a7d5713a4cf", "message": "Add no-detach-on-destroy client option (useful for control mode clients). From laur dot aliste at gmail dot com, GitHub issue 4242.", "old_file": "server-client.c", "new_file": "server-client.c", "status": "M", "old_contents": "server_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup(flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not) {\n\t\t\tif (c->flags & CLIENT_READONLY)\n\t\t\t\tflag &= ~CLIENT_READONLY;\n\t\t\tc->flags &= ~flag;\n\t\t} else\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_FOCUSED)\n\t\tstrlcat(s, \"focused,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_WAITEXIT)\n\t\tstrlcat(s, \"wait-exit,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstruct client_window *", "new_contents": "server_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup(flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\telse if (strcmp(next, \"no-detach-on-destroy\") == 0)\n\t\t\tflag = CLIENT_NO_DETACH_ON_DESTROY;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not) {\n\t\t\tif (c->flags & CLIENT_READONLY)\n\t\t\t\tflag &= ~CLIENT_READONLY;\n\t\t\tc->flags &= ~flag;\n\t\t} else\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_FOCUSED)\n\t\tstrlcat(s, \"focused,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_NO_DETACH_ON_DESTROY)\n\t\tstrlcat(s, \"no-detach-on-destroy,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_WAITEXIT)\n\t\tstrlcat(s, \"wait-exit,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstruct client_window *", "current_contents": "server_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup(flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\telse if (strcmp(next, \"no-detach-on-destroy\") == 0)\n\t\t\tflag = CLIENT_NO_DETACH_ON_DESTROY;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not) {\n\t\t\tif (c->flags & CLIENT_READONLY)\n\t\t\t\tflag &= ~CLIENT_READONLY;\n\t\t\tc->flags &= ~flag;\n\t\t} else\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_FOCUSED)\n\t\tstrlcat(s, \"focused,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_WAITEXIT)\n\t\tstrlcat(s, \"wait-exit,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstruct client_window *", "text": "<|original_code|>\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup(flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not) {\n\t\t\tif (c->flags & CLIENT_READONLY)\n\t\t\t\tflag &= ~CLIENT_READONLY;\n\t\t\tc->flags &= ~flag;\n\t\t} else\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_FOCUSED)\n\t\tstrlcat(s, \"focused,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_WAITEXIT)\n\t\tstrlcat(s, \"wait-exit,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstruct client_window *\n<|edits_diff|>\n--- server-client.c\n+++ server-client.c\n@@ -20,6 +20,8 @@\n \t\t\tflag = CLIENT_IGNORESIZE;\n \t\telse if (strcmp(next, \"active-pane\") == 0)\n \t\t\tflag = CLIENT_ACTIVEPANE;\n+\t\telse if (strcmp(next, \"no-detach-on-destroy\") == 0)\n+\t\t\tflag = CLIENT_NO_DETACH_ON_DESTROY;\n \t\tif (flag == 0)\n \t\t\tcontinue;\n \n<|current_version|>\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup(flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\telse if (strcmp(next, \"no-detach-on-destroy\") == 0)\n\t\t\tflag = CLIENT_NO_DETACH_ON_DESTROY;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not) {\n\t\t\tif (c->flags & CLIENT_READONLY)\n\t\t\t\tflag &= ~CLIENT_READONLY;\n\t\t\tc->flags &= ~flag;\n\t\t} else\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_FOCUSED)\n\t\tstrlcat(s, \"focused,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_WAITEXIT)\n\t\tstrlcat(s, \"wait-exit,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstruct client_window *\n<|next_version|>\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup(flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\telse if (strcmp(next, \"no-detach-on-destroy\") == 0)\n\t\t\tflag = CLIENT_NO_DETACH_ON_DESTROY;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not) {\n\t\t\tif (c->flags & CLIENT_READONLY)\n\t\t\t\tflag &= ~CLIENT_READONLY;\n\t\t\tc->flags &= ~flag;\n\t\t} else\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_FOCUSED)\n\t\tstrlcat(s, \"focused,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_NO_DETACH_ON_DESTROY)\n\t\tstrlcat(s, \"no-detach-on-destroy,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_WAITEXIT)\n\t\tstrlcat(s, \"wait-exit,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstruct client_window *\n"} {"commit": "d6883c02663105334da9fa4c20dc162ab10f608a", "message": "Turn off scrollbar when pane is in alternate screen, from Michael Grant, GitHub issue 4231.", "old_file": "screen-write.c", "new_file": "screen-write.c", "status": "M", "old_contents": "\n\tscreen_write_initctx(ctx, &ttyctx, 0);\n\tttyctx.ptr = str;\n\tttyctx.num = len;\n\tttyctx.allow_invisible_panes = allow_invisible_panes;\n\n\ttty_write(tty_cmd_rawstring, &ttyctx);\n}\n\n/* Turn alternate screen on. */\nvoid\nscreen_write_alternateon(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_on(ctx->s, gc, cursor);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n/* Turn alternate screen off. */\nvoid\nscreen_write_alternateoff(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_off(ctx->s, gc, cursor);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n", "new_contents": "\n\tscreen_write_initctx(ctx, &ttyctx, 0);\n\tttyctx.ptr = str;\n\tttyctx.num = len;\n\tttyctx.allow_invisible_panes = allow_invisible_panes;\n\n\ttty_write(tty_cmd_rawstring, &ttyctx);\n}\n\n/* Turn alternate screen on. */\nvoid\nscreen_write_alternateon(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_on(ctx->s, gc, cursor);\n\tlayout_fix_panes(wp->window, NULL);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n/* Turn alternate screen off. */\nvoid\nscreen_write_alternateoff(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_off(ctx->s, gc, cursor);\n\tlayout_fix_panes(wp->window, NULL);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n", "current_contents": "\n\tscreen_write_initctx(ctx, &ttyctx, 0);\n\tttyctx.ptr = str;\n\tttyctx.num = len;\n\tttyctx.allow_invisible_panes = allow_invisible_panes;\n\n\ttty_write(tty_cmd_rawstring, &ttyctx);\n}\n\n/* Turn alternate screen on. */\nvoid\nscreen_write_alternateon(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_on(ctx->s, gc, cursor);\n\tlayout_fix_panes(wp->window, NULL);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n/* Turn alternate screen off. */\nvoid\nscreen_write_alternateoff(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_off(ctx->s, gc, cursor);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n", "text": "<|original_code|>\n\n\tscreen_write_initctx(ctx, &ttyctx, 0);\n\tttyctx.ptr = str;\n\tttyctx.num = len;\n\tttyctx.allow_invisible_panes = allow_invisible_panes;\n\n\ttty_write(tty_cmd_rawstring, &ttyctx);\n}\n\n/* Turn alternate screen on. */\nvoid\nscreen_write_alternateon(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_on(ctx->s, gc, cursor);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n/* Turn alternate screen off. */\nvoid\nscreen_write_alternateoff(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_off(ctx->s, gc, cursor);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n<|edits_diff|>\n--- screen-write.c\n+++ screen-write.c\n@@ -20,6 +20,7 @@\n \n \tscreen_write_collect_flush(ctx, 0, __func__);\n \tscreen_alternate_on(ctx->s, gc, cursor);\n+\tlayout_fix_panes(wp->window, NULL);\n \n \tscreen_write_initctx(ctx, &ttyctx, 1);\n \tif (ttyctx.redraw_cb != NULL)\n<|current_version|>\n\n\tscreen_write_initctx(ctx, &ttyctx, 0);\n\tttyctx.ptr = str;\n\tttyctx.num = len;\n\tttyctx.allow_invisible_panes = allow_invisible_panes;\n\n\ttty_write(tty_cmd_rawstring, &ttyctx);\n}\n\n/* Turn alternate screen on. */\nvoid\nscreen_write_alternateon(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_on(ctx->s, gc, cursor);\n\tlayout_fix_panes(wp->window, NULL);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n/* Turn alternate screen off. */\nvoid\nscreen_write_alternateoff(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_off(ctx->s, gc, cursor);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n<|next_version|>\n\n\tscreen_write_initctx(ctx, &ttyctx, 0);\n\tttyctx.ptr = str;\n\tttyctx.num = len;\n\tttyctx.allow_invisible_panes = allow_invisible_panes;\n\n\ttty_write(tty_cmd_rawstring, &ttyctx);\n}\n\n/* Turn alternate screen on. */\nvoid\nscreen_write_alternateon(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_on(ctx->s, gc, cursor);\n\tlayout_fix_panes(wp->window, NULL);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n/* Turn alternate screen off. */\nvoid\nscreen_write_alternateoff(struct screen_write_ctx *ctx, struct grid_cell *gc,\n int cursor)\n{\n\tstruct tty_ctx\t\t ttyctx;\n\tstruct window_pane\t*wp = ctx->wp;\n\n\tif (wp != NULL && !options_get_number(wp->options, \"alternate-screen\"))\n\t\treturn;\n\n\tscreen_write_collect_flush(ctx, 0, __func__);\n\tscreen_alternate_off(ctx->s, gc, cursor);\n\tlayout_fix_panes(wp->window, NULL);\n\n\tscreen_write_initctx(ctx, &ttyctx, 1);\n\tif (ttyctx.redraw_cb != NULL)\n\t\tttyctx.redraw_cb(&ttyctx);\n}\n\n"} {"commit": "e86752820993a00e3d28350cbe46878ba95d9012", "message": "Check for NULL returns from bufferevent_new.", "old_file": "control.c", "new_file": "control.c", "status": "M", "old_contents": "\n/* Initialize for control mode. */\nvoid\ncontrol_start(struct client *c)\n{\n\tstruct control_state\t*cs;\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tclose(c->out_fd);\n\t\tc->out_fd = -1;\n\t} else\n\t\tsetblocking(c->out_fd, 0);\n\tsetblocking(c->fd, 0);\n\n\tcs = c->control_state = xcalloc(1, sizeof *cs);\n\tRB_INIT(&cs->panes);\n\tTAILQ_INIT(&cs->pending_list);\n\tTAILQ_INIT(&cs->all_blocks);\n\tRB_INIT(&cs->subs);\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tbufferevent_write(cs->write_event, \"\\033P1000p\", 7);\n\t\tbufferevent_enable(cs->write_event, EV_WRITE);\n\t}\n}\n\n/* Control client ready. */\nvoid\ncontrol_ready(struct client *c)\n{\n\tbufferevent_enable(c->control_state->read_event, EV_READ);\n}\n\n/* Discard all output for a client. */\nvoid\ncontrol_discard(struct client *c)\n{\n\tstruct control_state\t*cs = c->control_state;\n\tstruct control_pane\t*cp;\n", "new_contents": "\n/* Initialize for control mode. */\nvoid\ncontrol_start(struct client *c)\n{\n\tstruct control_state\t*cs;\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tclose(c->out_fd);\n\t\tc->out_fd = -1;\n\t} else\n\t\tsetblocking(c->out_fd, 0);\n\tsetblocking(c->fd, 0);\n\n\tcs = c->control_state = xcalloc(1, sizeof *cs);\n\tRB_INIT(&cs->panes);\n\tTAILQ_INIT(&cs->pending_list);\n\tTAILQ_INIT(&cs->all_blocks);\n\tRB_INIT(&cs->subs);\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\tif (cs->read_event == NULL)\n\t\tfatalx(\"out of memory\");\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t\tif (cs->write_event == NULL)\n\t\t\tfatalx(\"out of memory\");\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tbufferevent_write(cs->write_event, \"\\033P1000p\", 7);\n\t\tbufferevent_enable(cs->write_event, EV_WRITE);\n\t}\n}\n\n/* Control client ready. */\nvoid\ncontrol_ready(struct client *c)\n{\n\tbufferevent_enable(c->control_state->read_event, EV_READ);\n}\n\n/* Discard all output for a client. */\nvoid\ncontrol_discard(struct client *c)\n{\n\tstruct control_state\t*cs = c->control_state;\n\tstruct control_pane\t*cp;\n", "current_contents": "\n/* Initialize for control mode. */\nvoid\ncontrol_start(struct client *c)\n{\n\tstruct control_state\t*cs;\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tclose(c->out_fd);\n\t\tc->out_fd = -1;\n\t} else\n\t\tsetblocking(c->out_fd, 0);\n\tsetblocking(c->fd, 0);\n\n\tcs = c->control_state = xcalloc(1, sizeof *cs);\n\tRB_INIT(&cs->panes);\n\tTAILQ_INIT(&cs->pending_list);\n\tTAILQ_INIT(&cs->all_blocks);\n\tRB_INIT(&cs->subs);\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\tif (cs->read_event == NULL)\n\t\tfatalx(\"out of memory\");\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tbufferevent_write(cs->write_event, \"\\033P1000p\", 7);\n\t\tbufferevent_enable(cs->write_event, EV_WRITE);\n\t}\n}\n\n/* Control client ready. */\nvoid\ncontrol_ready(struct client *c)\n{\n\tbufferevent_enable(c->control_state->read_event, EV_READ);\n}\n\n/* Discard all output for a client. */\nvoid\ncontrol_discard(struct client *c)\n{\n\tstruct control_state\t*cs = c->control_state;\n\tstruct control_pane\t*cp;\n", "text": "<|original_code|>\n\n/* Initialize for control mode. */\nvoid\ncontrol_start(struct client *c)\n{\n\tstruct control_state\t*cs;\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tclose(c->out_fd);\n\t\tc->out_fd = -1;\n\t} else\n\t\tsetblocking(c->out_fd, 0);\n\tsetblocking(c->fd, 0);\n\n\tcs = c->control_state = xcalloc(1, sizeof *cs);\n\tRB_INIT(&cs->panes);\n\tTAILQ_INIT(&cs->pending_list);\n\tTAILQ_INIT(&cs->all_blocks);\n\tRB_INIT(&cs->subs);\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tbufferevent_write(cs->write_event, \"\\033P1000p\", 7);\n\t\tbufferevent_enable(cs->write_event, EV_WRITE);\n\t}\n}\n\n/* Control client ready. */\nvoid\ncontrol_ready(struct client *c)\n{\n\tbufferevent_enable(c->control_state->read_event, EV_READ);\n}\n\n/* Discard all output for a client. */\nvoid\ncontrol_discard(struct client *c)\n{\n\tstruct control_state\t*cs = c->control_state;\n\tstruct control_pane\t*cp;\n\n<|edits_diff|>\n--- control.c\n+++ control.c\n@@ -20,6 +20,8 @@\n \n \tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n \t control_write_callback, control_error_callback, c);\n+\tif (cs->read_event == NULL)\n+\t\tfatalx(\"out of memory\");\n \n \tif (c->flags & CLIENT_CONTROLCONTROL)\n \t\tcs->write_event = cs->read_event;\n<|current_version|>\n\n/* Initialize for control mode. */\nvoid\ncontrol_start(struct client *c)\n{\n\tstruct control_state\t*cs;\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tclose(c->out_fd);\n\t\tc->out_fd = -1;\n\t} else\n\t\tsetblocking(c->out_fd, 0);\n\tsetblocking(c->fd, 0);\n\n\tcs = c->control_state = xcalloc(1, sizeof *cs);\n\tRB_INIT(&cs->panes);\n\tTAILQ_INIT(&cs->pending_list);\n\tTAILQ_INIT(&cs->all_blocks);\n\tRB_INIT(&cs->subs);\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\tif (cs->read_event == NULL)\n\t\tfatalx(\"out of memory\");\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tbufferevent_write(cs->write_event, \"\\033P1000p\", 7);\n\t\tbufferevent_enable(cs->write_event, EV_WRITE);\n\t}\n}\n\n/* Control client ready. */\nvoid\ncontrol_ready(struct client *c)\n{\n\tbufferevent_enable(c->control_state->read_event, EV_READ);\n}\n\n/* Discard all output for a client. */\nvoid\ncontrol_discard(struct client *c)\n{\n\tstruct control_state\t*cs = c->control_state;\n\tstruct control_pane\t*cp;\n\n<|next_version|>\n\n/* Initialize for control mode. */\nvoid\ncontrol_start(struct client *c)\n{\n\tstruct control_state\t*cs;\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tclose(c->out_fd);\n\t\tc->out_fd = -1;\n\t} else\n\t\tsetblocking(c->out_fd, 0);\n\tsetblocking(c->fd, 0);\n\n\tcs = c->control_state = xcalloc(1, sizeof *cs);\n\tRB_INIT(&cs->panes);\n\tTAILQ_INIT(&cs->pending_list);\n\tTAILQ_INIT(&cs->all_blocks);\n\tRB_INIT(&cs->subs);\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\tif (cs->read_event == NULL)\n\t\tfatalx(\"out of memory\");\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t\tif (cs->write_event == NULL)\n\t\t\tfatalx(\"out of memory\");\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tbufferevent_write(cs->write_event, \"\\033P1000p\", 7);\n\t\tbufferevent_enable(cs->write_event, EV_WRITE);\n\t}\n}\n\n/* Control client ready. */\nvoid\ncontrol_ready(struct client *c)\n{\n\tbufferevent_enable(c->control_state->read_event, EV_READ);\n}\n\n/* Discard all output for a client. */\nvoid\ncontrol_discard(struct client *c)\n{\n\tstruct control_state\t*cs = c->control_state;\n\tstruct control_pane\t*cp;\n\n"} {"commit": "33c59100aeb49894550b97cce268f46032f4c8d6", "message": "Fix validation of missing percentage arguments.", "old_file": "arguments.c", "new_file": "arguments.c", "status": "M", "old_contents": "\tfree(formatted);\n\tif (errstr != NULL) {\n\t\t*cause = xstrdup(errstr);\n\t\treturn (0);\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/* Convert an argument to a number which may be a percentage. */\nlong long\nargs_percentage(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage(value, minval, maxval, curval, cause));\n}\n\n/* Convert a string to a number which may be a percentage. */\nlong long\nargs_string_percentage(const char *value, long long minval, long long maxval,\n long long curval, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy;\n\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tll = strtonum(copy, 0, 100, &errstr);\n\t\tfree(copy);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t\tll = (curval * ll) / 100;\n\t\tif (ll < minval) {\n\t\t\t*cause = xstrdup(\"too small\");\n\t\t\treturn (0);\n\t\t}\n\t\tif (ll > maxval) {\n\t\t\t*cause = xstrdup(\"too large\");\n\t\t\treturn (0);\n\t\t}\n\t} else {\n\t\tll = strtonum(value, minval, maxval, &errstr);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/*\n * Convert an argument to a number which may be a percentage, and expand\n * formats.\n */\nlong long\nargs_percentage_and_expand(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage_and_expand(value, minval, maxval, curval,\n\t\t item, cause));\n}\n\n/*\n * Convert a string to a number which may be a percentage, and expand formats.\n */\nlong long\nargs_string_percentage_and_expand(const char *value, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy, *f;\n\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tf = format_single_from_target(item, copy);\n\t\tll = strtonum(f, 0, 100, &errstr);\n\t\tfree(f);", "new_contents": "\tfree(formatted);\n\tif (errstr != NULL) {\n\t\t*cause = xstrdup(errstr);\n\t\treturn (0);\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/* Convert an argument to a number which may be a percentage. */\nlong long\nargs_percentage(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tif (TAILQ_EMPTY(&entry->values)) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage(value, minval, maxval, curval, cause));\n}\n\n/* Convert a string to a number which may be a percentage. */\nlong long\nargs_string_percentage(const char *value, long long minval, long long maxval,\n long long curval, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy;\n\n\tif (valuelen == 0) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tll = strtonum(copy, 0, 100, &errstr);\n\t\tfree(copy);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t\tll = (curval * ll) / 100;\n\t\tif (ll < minval) {\n\t\t\t*cause = xstrdup(\"too small\");\n\t\t\treturn (0);\n\t\t}\n\t\tif (ll > maxval) {\n\t\t\t*cause = xstrdup(\"too large\");\n\t\t\treturn (0);\n\t\t}\n\t} else {\n\t\tll = strtonum(value, minval, maxval, &errstr);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/*\n * Convert an argument to a number which may be a percentage, and expand\n * formats.\n */\nlong long\nargs_percentage_and_expand(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tif (TAILQ_EMPTY(&entry->values)) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage_and_expand(value, minval, maxval, curval,\n\t\t item, cause));\n}\n\n/*\n * Convert a string to a number which may be a percentage, and expand formats.\n */\nlong long\nargs_string_percentage_and_expand(const char *value, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy, *f;\n\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tf = format_single_from_target(item, copy);\n\t\tll = strtonum(f, 0, 100, &errstr);\n\t\tfree(f);", "current_contents": "\tfree(formatted);\n\tif (errstr != NULL) {\n\t\t*cause = xstrdup(errstr);\n\t\treturn (0);\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/* Convert an argument to a number which may be a percentage. */\nlong long\nargs_percentage(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tif (TAILQ_EMPTY(&entry->values)) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage(value, minval, maxval, curval, cause));\n}\n\n/* Convert a string to a number which may be a percentage. */\nlong long\nargs_string_percentage(const char *value, long long minval, long long maxval,\n long long curval, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy;\n\n\tif (valuelen == 0) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tll = strtonum(copy, 0, 100, &errstr);\n\t\tfree(copy);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t\tll = (curval * ll) / 100;\n\t\tif (ll < minval) {\n\t\t\t*cause = xstrdup(\"too small\");\n\t\t\treturn (0);\n\t\t}\n\t\tif (ll > maxval) {\n\t\t\t*cause = xstrdup(\"too large\");\n\t\t\treturn (0);\n\t\t}\n\t} else {\n\t\tll = strtonum(value, minval, maxval, &errstr);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/*\n * Convert an argument to a number which may be a percentage, and expand\n * formats.\n */\nlong long\nargs_percentage_and_expand(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage_and_expand(value, minval, maxval, curval,\n\t\t item, cause));\n}\n\n/*\n * Convert a string to a number which may be a percentage, and expand formats.\n */\nlong long\nargs_string_percentage_and_expand(const char *value, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy, *f;\n\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tf = format_single_from_target(item, copy);\n\t\tll = strtonum(f, 0, 100, &errstr);\n\t\tfree(f);", "text": "<|original_code|>\n\tfree(formatted);\n\tif (errstr != NULL) {\n\t\t*cause = xstrdup(errstr);\n\t\treturn (0);\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/* Convert an argument to a number which may be a percentage. */\nlong long\nargs_percentage(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage(value, minval, maxval, curval, cause));\n}\n\n/* Convert a string to a number which may be a percentage. */\nlong long\nargs_string_percentage(const char *value, long long minval, long long maxval,\n long long curval, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy;\n\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tll = strtonum(copy, 0, 100, &errstr);\n\t\tfree(copy);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t\tll = (curval * ll) / 100;\n\t\tif (ll < minval) {\n\t\t\t*cause = xstrdup(\"too small\");\n\t\t\treturn (0);\n\t\t}\n\t\tif (ll > maxval) {\n\t\t\t*cause = xstrdup(\"too large\");\n\t\t\treturn (0);\n\t\t}\n\t} else {\n\t\tll = strtonum(value, minval, maxval, &errstr);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/*\n * Convert an argument to a number which may be a percentage, and expand\n * formats.\n */\nlong long\nargs_percentage_and_expand(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage_and_expand(value, minval, maxval, curval,\n\t\t item, cause));\n}\n\n/*\n * Convert a string to a number which may be a percentage, and expand formats.\n */\nlong long\nargs_string_percentage_and_expand(const char *value, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy, *f;\n\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tf = format_single_from_target(item, copy);\n\t\tll = strtonum(f, 0, 100, &errstr);\n\t\tfree(f);\n<|edits_diff|>\n--- arguments.c\n+++ arguments.c\n@@ -20,6 +20,10 @@\n \t\t*cause = xstrdup(\"missing\");\n \t\treturn (0);\n \t}\n+\tif (TAILQ_EMPTY(&entry->values)) {\n+\t\t*cause = xstrdup(\"empty\");\n+\t\treturn (0);\n+\t}\n \tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n \treturn (args_string_percentage(value, minval, maxval, curval, cause));\n }\n@@ -34,6 +38,10 @@\n \tsize_t\t\t valuelen = strlen(value);\n \tchar\t\t*copy;\n \n+\tif (valuelen == 0) {\n+\t\t*cause = xstrdup(\"empty\");\n+\t\treturn (0);\n+\t}\n \tif (value[valuelen - 1] == '%') {\n \t\tcopy = xstrdup(value);\n \t\tcopy[valuelen - 1] = '\\0';\n<|current_version|>\n\tfree(formatted);\n\tif (errstr != NULL) {\n\t\t*cause = xstrdup(errstr);\n\t\treturn (0);\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/* Convert an argument to a number which may be a percentage. */\nlong long\nargs_percentage(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tif (TAILQ_EMPTY(&entry->values)) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage(value, minval, maxval, curval, cause));\n}\n\n/* Convert a string to a number which may be a percentage. */\nlong long\nargs_string_percentage(const char *value, long long minval, long long maxval,\n long long curval, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy;\n\n\tif (valuelen == 0) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tll = strtonum(copy, 0, 100, &errstr);\n\t\tfree(copy);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t\tll = (curval * ll) / 100;\n\t\tif (ll < minval) {\n\t\t\t*cause = xstrdup(\"too small\");\n\t\t\treturn (0);\n\t\t}\n\t\tif (ll > maxval) {\n\t\t\t*cause = xstrdup(\"too large\");\n\t\t\treturn (0);\n\t\t}\n\t} else {\n\t\tll = strtonum(value, minval, maxval, &errstr);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/*\n * Convert an argument to a number which may be a percentage, and expand\n * formats.\n */\nlong long\nargs_percentage_and_expand(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage_and_expand(value, minval, maxval, curval,\n\t\t item, cause));\n}\n\n/*\n * Convert a string to a number which may be a percentage, and expand formats.\n */\nlong long\nargs_string_percentage_and_expand(const char *value, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy, *f;\n\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tf = format_single_from_target(item, copy);\n\t\tll = strtonum(f, 0, 100, &errstr);\n\t\tfree(f);\n<|next_version|>\n\tfree(formatted);\n\tif (errstr != NULL) {\n\t\t*cause = xstrdup(errstr);\n\t\treturn (0);\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/* Convert an argument to a number which may be a percentage. */\nlong long\nargs_percentage(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tif (TAILQ_EMPTY(&entry->values)) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage(value, minval, maxval, curval, cause));\n}\n\n/* Convert a string to a number which may be a percentage. */\nlong long\nargs_string_percentage(const char *value, long long minval, long long maxval,\n long long curval, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy;\n\n\tif (valuelen == 0) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tll = strtonum(copy, 0, 100, &errstr);\n\t\tfree(copy);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t\tll = (curval * ll) / 100;\n\t\tif (ll < minval) {\n\t\t\t*cause = xstrdup(\"too small\");\n\t\t\treturn (0);\n\t\t}\n\t\tif (ll > maxval) {\n\t\t\t*cause = xstrdup(\"too large\");\n\t\t\treturn (0);\n\t\t}\n\t} else {\n\t\tll = strtonum(value, minval, maxval, &errstr);\n\t\tif (errstr != NULL) {\n\t\t\t*cause = xstrdup(errstr);\n\t\t\treturn (0);\n\t\t}\n\t}\n\n\t*cause = NULL;\n\treturn (ll);\n}\n\n/*\n * Convert an argument to a number which may be a percentage, and expand\n * formats.\n */\nlong long\nargs_percentage_and_expand(struct args *args, u_char flag, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t\t*value;\n\tstruct args_entry\t*entry;\n\n\tif ((entry = args_find(args, flag)) == NULL) {\n\t\t*cause = xstrdup(\"missing\");\n\t\treturn (0);\n\t}\n\tif (TAILQ_EMPTY(&entry->values)) {\n\t\t*cause = xstrdup(\"empty\");\n\t\treturn (0);\n\t}\n\tvalue = TAILQ_LAST(&entry->values, args_values)->string;\n\treturn (args_string_percentage_and_expand(value, minval, maxval, curval,\n\t\t item, cause));\n}\n\n/*\n * Convert a string to a number which may be a percentage, and expand formats.\n */\nlong long\nargs_string_percentage_and_expand(const char *value, long long minval,\n long long maxval, long long curval, struct cmdq_item *item, char **cause)\n{\n\tconst char\t*errstr;\n\tlong long\t ll;\n\tsize_t\t\t valuelen = strlen(value);\n\tchar\t\t*copy, *f;\n\n\tif (value[valuelen - 1] == '%') {\n\t\tcopy = xstrdup(value);\n\t\tcopy[valuelen - 1] = '\\0';\n\n\t\tf = format_single_from_target(item, copy);\n\t\tll = strtonum(f, 0, 100, &errstr);\n\t\tfree(f);\n"} {"commit": "9c89f7c2af748858e784e8c533c548460bd6b10e", "message": "Store time lines are scrolled into history and display in copy mode.", "old_file": "grid.c", "new_file": "grid.c", "status": "M", "old_contents": "\t\treturn;\n\tfor (yy = 0; yy < ny; yy++)\n\t\tgrid_free_line(gd, gd->hsize + gd->sy - 1 - yy);\n\tgd->hsize -= ny;\n}\n\n/*\n * Scroll the entire visible screen, moving one line into the history. Just\n * allocate a new line at the bottom and move the history size indicator.\n */\nvoid\ngrid_scroll_history(struct grid *gd, u_int bg)\n{\n\tu_int\tyy;\n\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\tgrid_empty_line(gd, yy, bg);\n\n\tgd->hscrolled++;\n\tgrid_compact_line(&gd->linedata[gd->hsize]);\n\tgd->hsize++;\n}\n\n/* Clear the history. */\nvoid\ngrid_clear_history(struct grid *gd)\n{\n\tgrid_trim_history(gd, gd->hsize);\n\n\tgd->hscrolled = 0;\n\tgd->hsize = 0;\n\n\tgd->linedata = xreallocarray(gd->linedata, gd->sy,\n\t sizeof *gd->linedata);\n}\n\n/* Scroll a region up, moving the top line into the history. */\nvoid\ngrid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)\n{\n\tstruct grid_line\t*gl_history, *gl_upper;\n\tu_int\t\t\t yy;\n\n\t/* Create a space for a new line. */\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\n\t/* Move the entire screen down to free a space for this line. */\n\tgl_history = &gd->linedata[gd->hsize];\n\tmemmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);\n\n\t/* Adjust the region and find its start and end. */\n\tupper++;\n\tgl_upper = &gd->linedata[upper];\n\tlower++;\n\n\t/* Move the line into the history. */\n\tmemcpy(gl_history, gl_upper, sizeof *gl_history);\n\n\t/* Then move the region up and clear the bottom line. */\n\tmemmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);\n\tgrid_empty_line(gd, lower, bg);\n\n\t/* Move the history offset down over the line. */\n\tgd->hscrolled++;\n\tgd->hsize++;\n}\n\n/* Expand line to fit to cell. */\nstatic void\ngrid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)\n{\n\tstruct grid_line\t*gl;\n\tu_int\t\t\t xx;\n\n\tgl = &gd->linedata[py];\n\tif (sx <= gl->cellsize)\n\t\treturn;\n\n\tif (sx < gd->sx / 4)\n\t\tsx = gd->sx / 4;\n\telse if (sx < gd->sx / 2)", "new_contents": "\t\treturn;\n\tfor (yy = 0; yy < ny; yy++)\n\t\tgrid_free_line(gd, gd->hsize + gd->sy - 1 - yy);\n\tgd->hsize -= ny;\n}\n\n/*\n * Scroll the entire visible screen, moving one line into the history. Just\n * allocate a new line at the bottom and move the history size indicator.\n */\nvoid\ngrid_scroll_history(struct grid *gd, u_int bg)\n{\n\tu_int\tyy;\n\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\tgrid_empty_line(gd, yy, bg);\n\n\tgd->hscrolled++;\n\tgrid_compact_line(&gd->linedata[gd->hsize]);\n\tgd->linedata[gd->hsize].time = current_time;\n\tgd->hsize++;\n}\n\n/* Clear the history. */\nvoid\ngrid_clear_history(struct grid *gd)\n{\n\tgrid_trim_history(gd, gd->hsize);\n\n\tgd->hscrolled = 0;\n\tgd->hsize = 0;\n\n\tgd->linedata = xreallocarray(gd->linedata, gd->sy,\n\t sizeof *gd->linedata);\n}\n\n/* Scroll a region up, moving the top line into the history. */\nvoid\ngrid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)\n{\n\tstruct grid_line\t*gl_history, *gl_upper;\n\tu_int\t\t\t yy;\n\n\t/* Create a space for a new line. */\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\n\t/* Move the entire screen down to free a space for this line. */\n\tgl_history = &gd->linedata[gd->hsize];\n\tmemmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);\n\n\t/* Adjust the region and find its start and end. */\n\tupper++;\n\tgl_upper = &gd->linedata[upper];\n\tlower++;\n\n\t/* Move the line into the history. */\n\tmemcpy(gl_history, gl_upper, sizeof *gl_history);\n\tgl_history->time = current_time;\n\n\t/* Then move the region up and clear the bottom line. */\n\tmemmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);\n\tgrid_empty_line(gd, lower, bg);\n\n\t/* Move the history offset down over the line. */\n\tgd->hscrolled++;\n\tgd->hsize++;\n}\n\n/* Expand line to fit to cell. */\nstatic void\ngrid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)\n{\n\tstruct grid_line\t*gl;\n\tu_int\t\t\t xx;\n\n\tgl = &gd->linedata[py];\n\tif (sx <= gl->cellsize)\n\t\treturn;\n\n\tif (sx < gd->sx / 4)\n\t\tsx = gd->sx / 4;\n\telse if (sx < gd->sx / 2)", "current_contents": "\t\treturn;\n\tfor (yy = 0; yy < ny; yy++)\n\t\tgrid_free_line(gd, gd->hsize + gd->sy - 1 - yy);\n\tgd->hsize -= ny;\n}\n\n/*\n * Scroll the entire visible screen, moving one line into the history. Just\n * allocate a new line at the bottom and move the history size indicator.\n */\nvoid\ngrid_scroll_history(struct grid *gd, u_int bg)\n{\n\tu_int\tyy;\n\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\tgrid_empty_line(gd, yy, bg);\n\n\tgd->hscrolled++;\n\tgrid_compact_line(&gd->linedata[gd->hsize]);\n\tgd->linedata[gd->hsize].time = current_time;\n\tgd->hsize++;\n}\n\n/* Clear the history. */\nvoid\ngrid_clear_history(struct grid *gd)\n{\n\tgrid_trim_history(gd, gd->hsize);\n\n\tgd->hscrolled = 0;\n\tgd->hsize = 0;\n\n\tgd->linedata = xreallocarray(gd->linedata, gd->sy,\n\t sizeof *gd->linedata);\n}\n\n/* Scroll a region up, moving the top line into the history. */\nvoid\ngrid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)\n{\n\tstruct grid_line\t*gl_history, *gl_upper;\n\tu_int\t\t\t yy;\n\n\t/* Create a space for a new line. */\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\n\t/* Move the entire screen down to free a space for this line. */\n\tgl_history = &gd->linedata[gd->hsize];\n\tmemmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);\n\n\t/* Adjust the region and find its start and end. */\n\tupper++;\n\tgl_upper = &gd->linedata[upper];\n\tlower++;\n\n\t/* Move the line into the history. */\n\tmemcpy(gl_history, gl_upper, sizeof *gl_history);\n\n\t/* Then move the region up and clear the bottom line. */\n\tmemmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);\n\tgrid_empty_line(gd, lower, bg);\n\n\t/* Move the history offset down over the line. */\n\tgd->hscrolled++;\n\tgd->hsize++;\n}\n\n/* Expand line to fit to cell. */\nstatic void\ngrid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)\n{\n\tstruct grid_line\t*gl;\n\tu_int\t\t\t xx;\n\n\tgl = &gd->linedata[py];\n\tif (sx <= gl->cellsize)\n\t\treturn;\n\n\tif (sx < gd->sx / 4)\n\t\tsx = gd->sx / 4;\n\telse if (sx < gd->sx / 2)", "text": "<|original_code|>\n\t\treturn;\n\tfor (yy = 0; yy < ny; yy++)\n\t\tgrid_free_line(gd, gd->hsize + gd->sy - 1 - yy);\n\tgd->hsize -= ny;\n}\n\n/*\n * Scroll the entire visible screen, moving one line into the history. Just\n * allocate a new line at the bottom and move the history size indicator.\n */\nvoid\ngrid_scroll_history(struct grid *gd, u_int bg)\n{\n\tu_int\tyy;\n\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\tgrid_empty_line(gd, yy, bg);\n\n\tgd->hscrolled++;\n\tgrid_compact_line(&gd->linedata[gd->hsize]);\n\tgd->hsize++;\n}\n\n/* Clear the history. */\nvoid\ngrid_clear_history(struct grid *gd)\n{\n\tgrid_trim_history(gd, gd->hsize);\n\n\tgd->hscrolled = 0;\n\tgd->hsize = 0;\n\n\tgd->linedata = xreallocarray(gd->linedata, gd->sy,\n\t sizeof *gd->linedata);\n}\n\n/* Scroll a region up, moving the top line into the history. */\nvoid\ngrid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)\n{\n\tstruct grid_line\t*gl_history, *gl_upper;\n\tu_int\t\t\t yy;\n\n\t/* Create a space for a new line. */\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\n\t/* Move the entire screen down to free a space for this line. */\n\tgl_history = &gd->linedata[gd->hsize];\n\tmemmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);\n\n\t/* Adjust the region and find its start and end. */\n\tupper++;\n\tgl_upper = &gd->linedata[upper];\n\tlower++;\n\n\t/* Move the line into the history. */\n\tmemcpy(gl_history, gl_upper, sizeof *gl_history);\n\n\t/* Then move the region up and clear the bottom line. */\n\tmemmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);\n\tgrid_empty_line(gd, lower, bg);\n\n\t/* Move the history offset down over the line. */\n\tgd->hscrolled++;\n\tgd->hsize++;\n}\n\n/* Expand line to fit to cell. */\nstatic void\ngrid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)\n{\n\tstruct grid_line\t*gl;\n\tu_int\t\t\t xx;\n\n\tgl = &gd->linedata[py];\n\tif (sx <= gl->cellsize)\n\t\treturn;\n\n\tif (sx < gd->sx / 4)\n\t\tsx = gd->sx / 4;\n\telse if (sx < gd->sx / 2)\n<|edits_diff|>\n--- grid.c\n+++ grid.c\n@@ -20,6 +20,7 @@\n \n \tgd->hscrolled++;\n \tgrid_compact_line(&gd->linedata[gd->hsize]);\n+\tgd->linedata[gd->hsize].time = current_time;\n \tgd->hsize++;\n }\n \n<|current_version|>\n\t\treturn;\n\tfor (yy = 0; yy < ny; yy++)\n\t\tgrid_free_line(gd, gd->hsize + gd->sy - 1 - yy);\n\tgd->hsize -= ny;\n}\n\n/*\n * Scroll the entire visible screen, moving one line into the history. Just\n * allocate a new line at the bottom and move the history size indicator.\n */\nvoid\ngrid_scroll_history(struct grid *gd, u_int bg)\n{\n\tu_int\tyy;\n\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\tgrid_empty_line(gd, yy, bg);\n\n\tgd->hscrolled++;\n\tgrid_compact_line(&gd->linedata[gd->hsize]);\n\tgd->linedata[gd->hsize].time = current_time;\n\tgd->hsize++;\n}\n\n/* Clear the history. */\nvoid\ngrid_clear_history(struct grid *gd)\n{\n\tgrid_trim_history(gd, gd->hsize);\n\n\tgd->hscrolled = 0;\n\tgd->hsize = 0;\n\n\tgd->linedata = xreallocarray(gd->linedata, gd->sy,\n\t sizeof *gd->linedata);\n}\n\n/* Scroll a region up, moving the top line into the history. */\nvoid\ngrid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)\n{\n\tstruct grid_line\t*gl_history, *gl_upper;\n\tu_int\t\t\t yy;\n\n\t/* Create a space for a new line. */\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\n\t/* Move the entire screen down to free a space for this line. */\n\tgl_history = &gd->linedata[gd->hsize];\n\tmemmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);\n\n\t/* Adjust the region and find its start and end. */\n\tupper++;\n\tgl_upper = &gd->linedata[upper];\n\tlower++;\n\n\t/* Move the line into the history. */\n\tmemcpy(gl_history, gl_upper, sizeof *gl_history);\n\n\t/* Then move the region up and clear the bottom line. */\n\tmemmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);\n\tgrid_empty_line(gd, lower, bg);\n\n\t/* Move the history offset down over the line. */\n\tgd->hscrolled++;\n\tgd->hsize++;\n}\n\n/* Expand line to fit to cell. */\nstatic void\ngrid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)\n{\n\tstruct grid_line\t*gl;\n\tu_int\t\t\t xx;\n\n\tgl = &gd->linedata[py];\n\tif (sx <= gl->cellsize)\n\t\treturn;\n\n\tif (sx < gd->sx / 4)\n\t\tsx = gd->sx / 4;\n\telse if (sx < gd->sx / 2)\n<|next_version|>\n\t\treturn;\n\tfor (yy = 0; yy < ny; yy++)\n\t\tgrid_free_line(gd, gd->hsize + gd->sy - 1 - yy);\n\tgd->hsize -= ny;\n}\n\n/*\n * Scroll the entire visible screen, moving one line into the history. Just\n * allocate a new line at the bottom and move the history size indicator.\n */\nvoid\ngrid_scroll_history(struct grid *gd, u_int bg)\n{\n\tu_int\tyy;\n\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\tgrid_empty_line(gd, yy, bg);\n\n\tgd->hscrolled++;\n\tgrid_compact_line(&gd->linedata[gd->hsize]);\n\tgd->linedata[gd->hsize].time = current_time;\n\tgd->hsize++;\n}\n\n/* Clear the history. */\nvoid\ngrid_clear_history(struct grid *gd)\n{\n\tgrid_trim_history(gd, gd->hsize);\n\n\tgd->hscrolled = 0;\n\tgd->hsize = 0;\n\n\tgd->linedata = xreallocarray(gd->linedata, gd->sy,\n\t sizeof *gd->linedata);\n}\n\n/* Scroll a region up, moving the top line into the history. */\nvoid\ngrid_scroll_history_region(struct grid *gd, u_int upper, u_int lower, u_int bg)\n{\n\tstruct grid_line\t*gl_history, *gl_upper;\n\tu_int\t\t\t yy;\n\n\t/* Create a space for a new line. */\n\tyy = gd->hsize + gd->sy;\n\tgd->linedata = xreallocarray(gd->linedata, yy + 1,\n\t sizeof *gd->linedata);\n\n\t/* Move the entire screen down to free a space for this line. */\n\tgl_history = &gd->linedata[gd->hsize];\n\tmemmove(gl_history + 1, gl_history, gd->sy * sizeof *gl_history);\n\n\t/* Adjust the region and find its start and end. */\n\tupper++;\n\tgl_upper = &gd->linedata[upper];\n\tlower++;\n\n\t/* Move the line into the history. */\n\tmemcpy(gl_history, gl_upper, sizeof *gl_history);\n\tgl_history->time = current_time;\n\n\t/* Then move the region up and clear the bottom line. */\n\tmemmove(gl_upper, gl_upper + 1, (lower - upper) * sizeof *gl_upper);\n\tgrid_empty_line(gd, lower, bg);\n\n\t/* Move the history offset down over the line. */\n\tgd->hscrolled++;\n\tgd->hsize++;\n}\n\n/* Expand line to fit to cell. */\nstatic void\ngrid_expand_line(struct grid *gd, u_int py, u_int sx, u_int bg)\n{\n\tstruct grid_line\t*gl;\n\tu_int\t\t\t xx;\n\n\tgl = &gd->linedata[py];\n\tif (sx <= gl->cellsize)\n\t\treturn;\n\n\tif (sx < gd->sx / 4)\n\t\tsx = gd->sx / 4;\n\telse if (sx < gd->sx / 2)\n"} {"commit": "2372b0fdc67f17336e39d8eb86019103aad6bb4e", "message": "Add a flag to make a client wait for an empty line before exiting in control mode to avoid stray commands ending up in the shell.", "old_file": "server-client.c", "new_file": "server-client.c", "status": "M", "old_contents": "\t\treturn (s->cwd);\n\tif (c != NULL && (s = c->session) != NULL && s->cwd != NULL)\n\t\treturn (s->cwd);\n\tif ((home = find_home()) != NULL)\n\t\treturn (home);\n\treturn (\"/\");\n}\n\n/* Get control client flags. */\nstatic uint64_t\nserver_client_control_flags(struct client *c, const char *next)\n{\n\tif (strcmp(next, \"pause-after\") == 0) {\n\t\tc->pause_age = 0;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (sscanf(next, \"pause-after=%u\", &c->pause_age) == 1) {\n\t\tc->pause_age *= 1000;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (strcmp(next, \"no-output\") == 0)\n\t\treturn (CLIENT_CONTROL_NOOUTPUT);\n\treturn (0);\n}\n\n/* Set client flags. */\nvoid\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup (flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not)\n\t\t\tc->flags &= ~flag;\n\t\telse\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstatic struct client_window *\nserver_client_get_client_window(struct client *c, u_int id)\n{\n\tstruct client_window\tcw = { .window = id };\n", "new_contents": "\t\treturn (s->cwd);\n\tif (c != NULL && (s = c->session) != NULL && s->cwd != NULL)\n\t\treturn (s->cwd);\n\tif ((home = find_home()) != NULL)\n\t\treturn (home);\n\treturn (\"/\");\n}\n\n/* Get control client flags. */\nstatic uint64_t\nserver_client_control_flags(struct client *c, const char *next)\n{\n\tif (strcmp(next, \"pause-after\") == 0) {\n\t\tc->pause_age = 0;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (sscanf(next, \"pause-after=%u\", &c->pause_age) == 1) {\n\t\tc->pause_age *= 1000;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (strcmp(next, \"no-output\") == 0)\n\t\treturn (CLIENT_CONTROL_NOOUTPUT);\n\tif (strcmp(next, \"wait-exit\") == 0)\n\t\treturn (CLIENT_CONTROL_WAITEXIT);\n\treturn (0);\n}\n\n/* Set client flags. */\nvoid\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup (flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not)\n\t\t\tc->flags &= ~flag;\n\t\telse\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_WAITEXIT)\n\t\tstrlcat(s, \"wait-exit,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstatic struct client_window *\nserver_client_get_client_window(struct client *c, u_int id)\n{\n\tstruct client_window\tcw = { .window = id };\n", "current_contents": "\t\treturn (s->cwd);\n\tif (c != NULL && (s = c->session) != NULL && s->cwd != NULL)\n\t\treturn (s->cwd);\n\tif ((home = find_home()) != NULL)\n\t\treturn (home);\n\treturn (\"/\");\n}\n\n/* Get control client flags. */\nstatic uint64_t\nserver_client_control_flags(struct client *c, const char *next)\n{\n\tif (strcmp(next, \"pause-after\") == 0) {\n\t\tc->pause_age = 0;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (sscanf(next, \"pause-after=%u\", &c->pause_age) == 1) {\n\t\tc->pause_age *= 1000;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (strcmp(next, \"no-output\") == 0)\n\t\treturn (CLIENT_CONTROL_NOOUTPUT);\n\tif (strcmp(next, \"wait-exit\") == 0)\n\t\treturn (CLIENT_CONTROL_WAITEXIT);\n\treturn (0);\n}\n\n/* Set client flags. */\nvoid\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup (flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not)\n\t\t\tc->flags &= ~flag;\n\t\telse\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstatic struct client_window *\nserver_client_get_client_window(struct client *c, u_int id)\n{\n\tstruct client_window\tcw = { .window = id };\n", "text": "<|original_code|>\n\t\treturn (s->cwd);\n\tif (c != NULL && (s = c->session) != NULL && s->cwd != NULL)\n\t\treturn (s->cwd);\n\tif ((home = find_home()) != NULL)\n\t\treturn (home);\n\treturn (\"/\");\n}\n\n/* Get control client flags. */\nstatic uint64_t\nserver_client_control_flags(struct client *c, const char *next)\n{\n\tif (strcmp(next, \"pause-after\") == 0) {\n\t\tc->pause_age = 0;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (sscanf(next, \"pause-after=%u\", &c->pause_age) == 1) {\n\t\tc->pause_age *= 1000;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (strcmp(next, \"no-output\") == 0)\n\t\treturn (CLIENT_CONTROL_NOOUTPUT);\n\treturn (0);\n}\n\n/* Set client flags. */\nvoid\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup (flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not)\n\t\t\tc->flags &= ~flag;\n\t\telse\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstatic struct client_window *\nserver_client_get_client_window(struct client *c, u_int id)\n{\n\tstruct client_window\tcw = { .window = id };\n\n<|edits_diff|>\n--- server-client.c\n+++ server-client.c\n@@ -20,6 +20,8 @@\n \t}\n \tif (strcmp(next, \"no-output\") == 0)\n \t\treturn (CLIENT_CONTROL_NOOUTPUT);\n+\tif (strcmp(next, \"wait-exit\") == 0)\n+\t\treturn (CLIENT_CONTROL_WAITEXIT);\n \treturn (0);\n }\n \n@@ -59,6 +61,7 @@\n \t\t\tcontrol_reset_offsets(c);\n \t}\n \tfree(copy);\n+\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n }\n \n /* Get client flags. This is only flags useful to show to users. */\n<|current_version|>\n\t\treturn (s->cwd);\n\tif (c != NULL && (s = c->session) != NULL && s->cwd != NULL)\n\t\treturn (s->cwd);\n\tif ((home = find_home()) != NULL)\n\t\treturn (home);\n\treturn (\"/\");\n}\n\n/* Get control client flags. */\nstatic uint64_t\nserver_client_control_flags(struct client *c, const char *next)\n{\n\tif (strcmp(next, \"pause-after\") == 0) {\n\t\tc->pause_age = 0;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (sscanf(next, \"pause-after=%u\", &c->pause_age) == 1) {\n\t\tc->pause_age *= 1000;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (strcmp(next, \"no-output\") == 0)\n\t\treturn (CLIENT_CONTROL_NOOUTPUT);\n\tif (strcmp(next, \"wait-exit\") == 0)\n\t\treturn (CLIENT_CONTROL_WAITEXIT);\n\treturn (0);\n}\n\n/* Set client flags. */\nvoid\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup (flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not)\n\t\t\tc->flags &= ~flag;\n\t\telse\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstatic struct client_window *\nserver_client_get_client_window(struct client *c, u_int id)\n{\n\tstruct client_window\tcw = { .window = id };\n\n<|next_version|>\n\t\treturn (s->cwd);\n\tif (c != NULL && (s = c->session) != NULL && s->cwd != NULL)\n\t\treturn (s->cwd);\n\tif ((home = find_home()) != NULL)\n\t\treturn (home);\n\treturn (\"/\");\n}\n\n/* Get control client flags. */\nstatic uint64_t\nserver_client_control_flags(struct client *c, const char *next)\n{\n\tif (strcmp(next, \"pause-after\") == 0) {\n\t\tc->pause_age = 0;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (sscanf(next, \"pause-after=%u\", &c->pause_age) == 1) {\n\t\tc->pause_age *= 1000;\n\t\treturn (CLIENT_CONTROL_PAUSEAFTER);\n\t}\n\tif (strcmp(next, \"no-output\") == 0)\n\t\treturn (CLIENT_CONTROL_NOOUTPUT);\n\tif (strcmp(next, \"wait-exit\") == 0)\n\t\treturn (CLIENT_CONTROL_WAITEXIT);\n\treturn (0);\n}\n\n/* Set client flags. */\nvoid\nserver_client_set_flags(struct client *c, const char *flags)\n{\n\tchar\t*s, *copy, *next;\n\tuint64_t flag;\n\tint\t not;\n\n\ts = copy = xstrdup (flags);\n\twhile ((next = strsep(&s, \",\")) != NULL) {\n\t\tnot = (*next == '!');\n\t\tif (not)\n\t\t\tnext++;\n\n\t\tif (c->flags & CLIENT_CONTROL)\n\t\t\tflag = server_client_control_flags(c, next);\n\t\telse\n\t\t\tflag = 0;\n\t\tif (strcmp(next, \"read-only\") == 0)\n\t\t\tflag = CLIENT_READONLY;\n\t\telse if (strcmp(next, \"ignore-size\") == 0)\n\t\t\tflag = CLIENT_IGNORESIZE;\n\t\telse if (strcmp(next, \"active-pane\") == 0)\n\t\t\tflag = CLIENT_ACTIVEPANE;\n\t\tif (flag == 0)\n\t\t\tcontinue;\n\n\t\tlog_debug(\"client %s set flag %s\", c->name, next);\n\t\tif (not)\n\t\t\tc->flags &= ~flag;\n\t\telse\n\t\t\tc->flags |= flag;\n\t\tif (flag == CLIENT_CONTROL_NOOUTPUT)\n\t\t\tcontrol_reset_offsets(c);\n\t}\n\tfree(copy);\n\tproc_send(c->peer, MSG_FLAGS, -1, &c->flags, sizeof c->flags);\n}\n\n/* Get client flags. This is only flags useful to show to users. */\nconst char *\nserver_client_get_flags(struct client *c)\n{\n\tstatic char\ts[256];\n\tchar\t \ttmp[32];\n\n\t*s = '\\0';\n\tif (c->flags & CLIENT_ATTACHED)\n\t\tstrlcat(s, \"attached,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL)\n\t\tstrlcat(s, \"control-mode,\", sizeof s);\n\tif (c->flags & CLIENT_IGNORESIZE)\n\t\tstrlcat(s, \"ignore-size,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_NOOUTPUT)\n\t\tstrlcat(s, \"no-output,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_WAITEXIT)\n\t\tstrlcat(s, \"wait-exit,\", sizeof s);\n\tif (c->flags & CLIENT_CONTROL_PAUSEAFTER) {\n\t\txsnprintf(tmp, sizeof tmp, \"pause-after=%u,\",\n\t\t c->pause_age / 1000);\n\t\tstrlcat(s, tmp, sizeof s);\n\t}\n\tif (c->flags & CLIENT_READONLY)\n\t\tstrlcat(s, \"read-only,\", sizeof s);\n\tif (c->flags & CLIENT_ACTIVEPANE)\n\t\tstrlcat(s, \"active-pane,\", sizeof s);\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\tstrlcat(s, \"suspended,\", sizeof s);\n\tif (c->flags & CLIENT_UTF8)\n\t\tstrlcat(s, \"UTF-8,\", sizeof s);\n\tif (*s != '\\0')\n\t\ts[strlen(s) - 1] = '\\0';\n\treturn (s);\n}\n\n/* Get client window. */\nstatic struct client_window *\nserver_client_get_client_window(struct client *c, u_int id)\n{\n\tstruct client_window\tcw = { .window = id };\n\n"} {"commit": "b2443aa2f98c1a1fa5d53d4e79a3e7fd221cc365", "message": "Add support for the iTerm2 sychronized updates escape sequence which drastically reduces flickering.", "old_file": "screen-redraw.c", "new_file": "screen-redraw.c", "status": "M", "old_contents": "\n\tctx->pane_status = options_get_number(wo, \"pane-border-status\");\n\n\ttty_window_offset(&c->tty, &ctx->ox, &ctx->oy, &ctx->sx, &ctx->sy);\n\n\tlog_debug(\"%s: %s @%u ox=%u oy=%u sx=%u sy=%u %u/%d\", __func__, c->name,\n\t w->id, ctx->ox, ctx->oy, ctx->sx, ctx->sy, ctx->statuslines,\n\t ctx->statustop);\n}\n\n/* Redraw entire screen. */\nvoid\nscreen_redraw_screen(struct client *c)\n{\n\tstruct screen_redraw_ctx\tctx;\n\tint\t\t\t\tflags;\n\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\treturn;\n\n\tflags = screen_redraw_update(c, c->flags);\n\tscreen_redraw_set_context(c, &ctx);\n\n\tif (flags & (CLIENT_REDRAWWINDOW|CLIENT_REDRAWBORDERS)) {\n\t\tif (ctx.pane_status != PANE_STATUS_OFF)\n\t\t\tscreen_redraw_draw_pane_status(&ctx);\n\t\tscreen_redraw_draw_borders(&ctx);\n\t}\n\tif (flags & CLIENT_REDRAWWINDOW)\n\t\tscreen_redraw_draw_panes(&ctx);\n\tif (ctx.statuslines != 0 &&\n\t (flags & (CLIENT_REDRAWSTATUS|CLIENT_REDRAWSTATUSALWAYS)))\n\t\tscreen_redraw_draw_status(&ctx);\n\tif (c->overlay_draw != NULL && (flags & CLIENT_REDRAWOVERLAY))\n\t\tc->overlay_draw(c, &ctx);\n\ttty_reset(&c->tty);\n}\n\n/* Redraw a single pane. */\nvoid\nscreen_redraw_pane(struct client *c, struct window_pane *wp)\n{\n\tstruct screen_redraw_ctx\t ctx;\n\n\tif (c->overlay_draw != NULL || !window_pane_visible(wp))\n\t\treturn;\n\n\tscreen_redraw_set_context(c, &ctx);\n\n\tscreen_redraw_draw_pane(&ctx, wp);\n\ttty_reset(&c->tty);\n}\n\n/* Draw a border cell. */\nstatic void\nscreen_redraw_draw_borders_cell(struct screen_redraw_ctx *ctx, u_int i, u_int j,\n struct grid_cell *m_active_gc, struct grid_cell *active_gc,\n struct grid_cell *m_other_gc, struct grid_cell *other_gc)\n{\n\tstruct client\t\t*c = ctx->c;\n\tstruct session\t\t*s = c->session;\n\tstruct window\t\t*w = s->curw->window;\n\tstruct tty\t\t*tty = &c->tty;\n\tstruct window_pane\t*wp;\n\tstruct window_pane\t*active = w->active;\n\tstruct window_pane\t*marked = marked_pane.wp;\n\tu_int\t\t\t type, x = ctx->ox + i, y = ctx->oy + j;\n\tint\t\t\t flag, pane_status = ctx->pane_status;\n\n\tif (c->overlay_check != NULL && !c->overlay_check(c, x, y))\n\t\treturn;\n\ttype = screen_redraw_check_cell(c, x, y, pane_status, &wp);\n\tif (type == CELL_INSIDE)\n\t\treturn;\n\tflag = screen_redraw_check_is(x, y, type, pane_status, w, active, wp);", "new_contents": "\n\tctx->pane_status = options_get_number(wo, \"pane-border-status\");\n\n\ttty_window_offset(&c->tty, &ctx->ox, &ctx->oy, &ctx->sx, &ctx->sy);\n\n\tlog_debug(\"%s: %s @%u ox=%u oy=%u sx=%u sy=%u %u/%d\", __func__, c->name,\n\t w->id, ctx->ox, ctx->oy, ctx->sx, ctx->sy, ctx->statuslines,\n\t ctx->statustop);\n}\n\n/* Redraw entire screen. */\nvoid\nscreen_redraw_screen(struct client *c)\n{\n\tstruct screen_redraw_ctx\tctx;\n\tint\t\t\t\tflags;\n\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\treturn;\n\n\tflags = screen_redraw_update(c, c->flags);\n\tscreen_redraw_set_context(c, &ctx);\n\ttty_sync_start(&c->tty);\n\n\tif (flags & (CLIENT_REDRAWWINDOW|CLIENT_REDRAWBORDERS)) {\n\t\tif (ctx.pane_status != PANE_STATUS_OFF)\n\t\t\tscreen_redraw_draw_pane_status(&ctx);\n\t\tscreen_redraw_draw_borders(&ctx);\n\t}\n\tif (flags & CLIENT_REDRAWWINDOW)\n\t\tscreen_redraw_draw_panes(&ctx);\n\tif (ctx.statuslines != 0 &&\n\t (flags & (CLIENT_REDRAWSTATUS|CLIENT_REDRAWSTATUSALWAYS)))\n\t\tscreen_redraw_draw_status(&ctx);\n\tif (c->overlay_draw != NULL && (flags & CLIENT_REDRAWOVERLAY))\n\t\tc->overlay_draw(c, &ctx);\n\n\ttty_reset(&c->tty);\n\ttty_sync_end(&c->tty);\n}\n\n/* Redraw a single pane. */\nvoid\nscreen_redraw_pane(struct client *c, struct window_pane *wp)\n{\n\tstruct screen_redraw_ctx\t ctx;\n\n\tif (c->overlay_draw != NULL || !window_pane_visible(wp))\n\t\treturn;\n\n\tscreen_redraw_set_context(c, &ctx);\n\ttty_sync_start(&c->tty);\n\n\tscreen_redraw_draw_pane(&ctx, wp);\n\n\ttty_reset(&c->tty);\n\ttty_sync_end(&c->tty);\n}\n\n/* Draw a border cell. */\nstatic void\nscreen_redraw_draw_borders_cell(struct screen_redraw_ctx *ctx, u_int i, u_int j,\n struct grid_cell *m_active_gc, struct grid_cell *active_gc,\n struct grid_cell *m_other_gc, struct grid_cell *other_gc)\n{\n\tstruct client\t\t*c = ctx->c;\n\tstruct session\t\t*s = c->session;\n\tstruct window\t\t*w = s->curw->window;\n\tstruct tty\t\t*tty = &c->tty;\n\tstruct window_pane\t*wp;\n\tstruct window_pane\t*active = w->active;\n\tstruct window_pane\t*marked = marked_pane.wp;\n\tu_int\t\t\t type, x = ctx->ox + i, y = ctx->oy + j;\n\tint\t\t\t flag, pane_status = ctx->pane_status;\n\n\tif (c->overlay_check != NULL && !c->overlay_check(c, x, y))\n\t\treturn;\n\ttype = screen_redraw_check_cell(c, x, y, pane_status, &wp);\n\tif (type == CELL_INSIDE)\n\t\treturn;\n\tflag = screen_redraw_check_is(x, y, type, pane_status, w, active, wp);", "current_contents": "\n\tctx->pane_status = options_get_number(wo, \"pane-border-status\");\n\n\ttty_window_offset(&c->tty, &ctx->ox, &ctx->oy, &ctx->sx, &ctx->sy);\n\n\tlog_debug(\"%s: %s @%u ox=%u oy=%u sx=%u sy=%u %u/%d\", __func__, c->name,\n\t w->id, ctx->ox, ctx->oy, ctx->sx, ctx->sy, ctx->statuslines,\n\t ctx->statustop);\n}\n\n/* Redraw entire screen. */\nvoid\nscreen_redraw_screen(struct client *c)\n{\n\tstruct screen_redraw_ctx\tctx;\n\tint\t\t\t\tflags;\n\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\treturn;\n\n\tflags = screen_redraw_update(c, c->flags);\n\tscreen_redraw_set_context(c, &ctx);\n\ttty_sync_start(&c->tty);\n\n\tif (flags & (CLIENT_REDRAWWINDOW|CLIENT_REDRAWBORDERS)) {\n\t\tif (ctx.pane_status != PANE_STATUS_OFF)\n\t\t\tscreen_redraw_draw_pane_status(&ctx);\n\t\tscreen_redraw_draw_borders(&ctx);\n\t}\n\tif (flags & CLIENT_REDRAWWINDOW)\n\t\tscreen_redraw_draw_panes(&ctx);\n\tif (ctx.statuslines != 0 &&\n\t (flags & (CLIENT_REDRAWSTATUS|CLIENT_REDRAWSTATUSALWAYS)))\n\t\tscreen_redraw_draw_status(&ctx);\n\tif (c->overlay_draw != NULL && (flags & CLIENT_REDRAWOVERLAY))\n\t\tc->overlay_draw(c, &ctx);\n\n\ttty_reset(&c->tty);\n\ttty_sync_end(&c->tty);\n}\n\n/* Redraw a single pane. */\nvoid\nscreen_redraw_pane(struct client *c, struct window_pane *wp)\n{\n\tstruct screen_redraw_ctx\t ctx;\n\n\tif (c->overlay_draw != NULL || !window_pane_visible(wp))\n\t\treturn;\n\n\tscreen_redraw_set_context(c, &ctx);\n\ttty_sync_start(&c->tty);\n\n\tscreen_redraw_draw_pane(&ctx, wp);\n\n\ttty_reset(&c->tty);\n}\n\n/* Draw a border cell. */\nstatic void\nscreen_redraw_draw_borders_cell(struct screen_redraw_ctx *ctx, u_int i, u_int j,\n struct grid_cell *m_active_gc, struct grid_cell *active_gc,\n struct grid_cell *m_other_gc, struct grid_cell *other_gc)\n{\n\tstruct client\t\t*c = ctx->c;\n\tstruct session\t\t*s = c->session;\n\tstruct window\t\t*w = s->curw->window;\n\tstruct tty\t\t*tty = &c->tty;\n\tstruct window_pane\t*wp;\n\tstruct window_pane\t*active = w->active;\n\tstruct window_pane\t*marked = marked_pane.wp;\n\tu_int\t\t\t type, x = ctx->ox + i, y = ctx->oy + j;\n\tint\t\t\t flag, pane_status = ctx->pane_status;\n\n\tif (c->overlay_check != NULL && !c->overlay_check(c, x, y))\n\t\treturn;\n\ttype = screen_redraw_check_cell(c, x, y, pane_status, &wp);\n\tif (type == CELL_INSIDE)\n\t\treturn;\n\tflag = screen_redraw_check_is(x, y, type, pane_status, w, active, wp);", "text": "<|original_code|>\n\n\tctx->pane_status = options_get_number(wo, \"pane-border-status\");\n\n\ttty_window_offset(&c->tty, &ctx->ox, &ctx->oy, &ctx->sx, &ctx->sy);\n\n\tlog_debug(\"%s: %s @%u ox=%u oy=%u sx=%u sy=%u %u/%d\", __func__, c->name,\n\t w->id, ctx->ox, ctx->oy, ctx->sx, ctx->sy, ctx->statuslines,\n\t ctx->statustop);\n}\n\n/* Redraw entire screen. */\nvoid\nscreen_redraw_screen(struct client *c)\n{\n\tstruct screen_redraw_ctx\tctx;\n\tint\t\t\t\tflags;\n\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\treturn;\n\n\tflags = screen_redraw_update(c, c->flags);\n\tscreen_redraw_set_context(c, &ctx);\n\n\tif (flags & (CLIENT_REDRAWWINDOW|CLIENT_REDRAWBORDERS)) {\n\t\tif (ctx.pane_status != PANE_STATUS_OFF)\n\t\t\tscreen_redraw_draw_pane_status(&ctx);\n\t\tscreen_redraw_draw_borders(&ctx);\n\t}\n\tif (flags & CLIENT_REDRAWWINDOW)\n\t\tscreen_redraw_draw_panes(&ctx);\n\tif (ctx.statuslines != 0 &&\n\t (flags & (CLIENT_REDRAWSTATUS|CLIENT_REDRAWSTATUSALWAYS)))\n\t\tscreen_redraw_draw_status(&ctx);\n\tif (c->overlay_draw != NULL && (flags & CLIENT_REDRAWOVERLAY))\n\t\tc->overlay_draw(c, &ctx);\n\ttty_reset(&c->tty);\n}\n\n/* Redraw a single pane. */\nvoid\nscreen_redraw_pane(struct client *c, struct window_pane *wp)\n{\n\tstruct screen_redraw_ctx\t ctx;\n\n\tif (c->overlay_draw != NULL || !window_pane_visible(wp))\n\t\treturn;\n\n\tscreen_redraw_set_context(c, &ctx);\n\n\tscreen_redraw_draw_pane(&ctx, wp);\n\ttty_reset(&c->tty);\n}\n\n/* Draw a border cell. */\nstatic void\nscreen_redraw_draw_borders_cell(struct screen_redraw_ctx *ctx, u_int i, u_int j,\n struct grid_cell *m_active_gc, struct grid_cell *active_gc,\n struct grid_cell *m_other_gc, struct grid_cell *other_gc)\n{\n\tstruct client\t\t*c = ctx->c;\n\tstruct session\t\t*s = c->session;\n\tstruct window\t\t*w = s->curw->window;\n\tstruct tty\t\t*tty = &c->tty;\n\tstruct window_pane\t*wp;\n\tstruct window_pane\t*active = w->active;\n\tstruct window_pane\t*marked = marked_pane.wp;\n\tu_int\t\t\t type, x = ctx->ox + i, y = ctx->oy + j;\n\tint\t\t\t flag, pane_status = ctx->pane_status;\n\n\tif (c->overlay_check != NULL && !c->overlay_check(c, x, y))\n\t\treturn;\n\ttype = screen_redraw_check_cell(c, x, y, pane_status, &wp);\n\tif (type == CELL_INSIDE)\n\t\treturn;\n\tflag = screen_redraw_check_is(x, y, type, pane_status, w, active, wp);\n<|edits_diff|>\n--- screen-redraw.c\n+++ screen-redraw.c\n@@ -20,6 +20,7 @@\n \n \tflags = screen_redraw_update(c, c->flags);\n \tscreen_redraw_set_context(c, &ctx);\n+\ttty_sync_start(&c->tty);\n \n \tif (flags & (CLIENT_REDRAWWINDOW|CLIENT_REDRAWBORDERS)) {\n \t\tif (ctx.pane_status != PANE_STATUS_OFF)\n@@ -33,7 +34,9 @@\n \t\tscreen_redraw_draw_status(&ctx);\n \tif (c->overlay_draw != NULL && (flags & CLIENT_REDRAWOVERLAY))\n \t\tc->overlay_draw(c, &ctx);\n+\n \ttty_reset(&c->tty);\n+\ttty_sync_end(&c->tty);\n }\n \n /* Redraw a single pane. */\n@@ -46,8 +49,10 @@\n \t\treturn;\n \n \tscreen_redraw_set_context(c, &ctx);\n+\ttty_sync_start(&c->tty);\n \n \tscreen_redraw_draw_pane(&ctx, wp);\n+\n \ttty_reset(&c->tty);\n }\n \n<|current_version|>\n\n\tctx->pane_status = options_get_number(wo, \"pane-border-status\");\n\n\ttty_window_offset(&c->tty, &ctx->ox, &ctx->oy, &ctx->sx, &ctx->sy);\n\n\tlog_debug(\"%s: %s @%u ox=%u oy=%u sx=%u sy=%u %u/%d\", __func__, c->name,\n\t w->id, ctx->ox, ctx->oy, ctx->sx, ctx->sy, ctx->statuslines,\n\t ctx->statustop);\n}\n\n/* Redraw entire screen. */\nvoid\nscreen_redraw_screen(struct client *c)\n{\n\tstruct screen_redraw_ctx\tctx;\n\tint\t\t\t\tflags;\n\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\treturn;\n\n\tflags = screen_redraw_update(c, c->flags);\n\tscreen_redraw_set_context(c, &ctx);\n\ttty_sync_start(&c->tty);\n\n\tif (flags & (CLIENT_REDRAWWINDOW|CLIENT_REDRAWBORDERS)) {\n\t\tif (ctx.pane_status != PANE_STATUS_OFF)\n\t\t\tscreen_redraw_draw_pane_status(&ctx);\n\t\tscreen_redraw_draw_borders(&ctx);\n\t}\n\tif (flags & CLIENT_REDRAWWINDOW)\n\t\tscreen_redraw_draw_panes(&ctx);\n\tif (ctx.statuslines != 0 &&\n\t (flags & (CLIENT_REDRAWSTATUS|CLIENT_REDRAWSTATUSALWAYS)))\n\t\tscreen_redraw_draw_status(&ctx);\n\tif (c->overlay_draw != NULL && (flags & CLIENT_REDRAWOVERLAY))\n\t\tc->overlay_draw(c, &ctx);\n\n\ttty_reset(&c->tty);\n\ttty_sync_end(&c->tty);\n}\n\n/* Redraw a single pane. */\nvoid\nscreen_redraw_pane(struct client *c, struct window_pane *wp)\n{\n\tstruct screen_redraw_ctx\t ctx;\n\n\tif (c->overlay_draw != NULL || !window_pane_visible(wp))\n\t\treturn;\n\n\tscreen_redraw_set_context(c, &ctx);\n\ttty_sync_start(&c->tty);\n\n\tscreen_redraw_draw_pane(&ctx, wp);\n\n\ttty_reset(&c->tty);\n}\n\n/* Draw a border cell. */\nstatic void\nscreen_redraw_draw_borders_cell(struct screen_redraw_ctx *ctx, u_int i, u_int j,\n struct grid_cell *m_active_gc, struct grid_cell *active_gc,\n struct grid_cell *m_other_gc, struct grid_cell *other_gc)\n{\n\tstruct client\t\t*c = ctx->c;\n\tstruct session\t\t*s = c->session;\n\tstruct window\t\t*w = s->curw->window;\n\tstruct tty\t\t*tty = &c->tty;\n\tstruct window_pane\t*wp;\n\tstruct window_pane\t*active = w->active;\n\tstruct window_pane\t*marked = marked_pane.wp;\n\tu_int\t\t\t type, x = ctx->ox + i, y = ctx->oy + j;\n\tint\t\t\t flag, pane_status = ctx->pane_status;\n\n\tif (c->overlay_check != NULL && !c->overlay_check(c, x, y))\n\t\treturn;\n\ttype = screen_redraw_check_cell(c, x, y, pane_status, &wp);\n\tif (type == CELL_INSIDE)\n\t\treturn;\n\tflag = screen_redraw_check_is(x, y, type, pane_status, w, active, wp);\n<|next_version|>\n\n\tctx->pane_status = options_get_number(wo, \"pane-border-status\");\n\n\ttty_window_offset(&c->tty, &ctx->ox, &ctx->oy, &ctx->sx, &ctx->sy);\n\n\tlog_debug(\"%s: %s @%u ox=%u oy=%u sx=%u sy=%u %u/%d\", __func__, c->name,\n\t w->id, ctx->ox, ctx->oy, ctx->sx, ctx->sy, ctx->statuslines,\n\t ctx->statustop);\n}\n\n/* Redraw entire screen. */\nvoid\nscreen_redraw_screen(struct client *c)\n{\n\tstruct screen_redraw_ctx\tctx;\n\tint\t\t\t\tflags;\n\n\tif (c->flags & CLIENT_SUSPENDED)\n\t\treturn;\n\n\tflags = screen_redraw_update(c, c->flags);\n\tscreen_redraw_set_context(c, &ctx);\n\ttty_sync_start(&c->tty);\n\n\tif (flags & (CLIENT_REDRAWWINDOW|CLIENT_REDRAWBORDERS)) {\n\t\tif (ctx.pane_status != PANE_STATUS_OFF)\n\t\t\tscreen_redraw_draw_pane_status(&ctx);\n\t\tscreen_redraw_draw_borders(&ctx);\n\t}\n\tif (flags & CLIENT_REDRAWWINDOW)\n\t\tscreen_redraw_draw_panes(&ctx);\n\tif (ctx.statuslines != 0 &&\n\t (flags & (CLIENT_REDRAWSTATUS|CLIENT_REDRAWSTATUSALWAYS)))\n\t\tscreen_redraw_draw_status(&ctx);\n\tif (c->overlay_draw != NULL && (flags & CLIENT_REDRAWOVERLAY))\n\t\tc->overlay_draw(c, &ctx);\n\n\ttty_reset(&c->tty);\n\ttty_sync_end(&c->tty);\n}\n\n/* Redraw a single pane. */\nvoid\nscreen_redraw_pane(struct client *c, struct window_pane *wp)\n{\n\tstruct screen_redraw_ctx\t ctx;\n\n\tif (c->overlay_draw != NULL || !window_pane_visible(wp))\n\t\treturn;\n\n\tscreen_redraw_set_context(c, &ctx);\n\ttty_sync_start(&c->tty);\n\n\tscreen_redraw_draw_pane(&ctx, wp);\n\n\ttty_reset(&c->tty);\n\ttty_sync_end(&c->tty);\n}\n\n/* Draw a border cell. */\nstatic void\nscreen_redraw_draw_borders_cell(struct screen_redraw_ctx *ctx, u_int i, u_int j,\n struct grid_cell *m_active_gc, struct grid_cell *active_gc,\n struct grid_cell *m_other_gc, struct grid_cell *other_gc)\n{\n\tstruct client\t\t*c = ctx->c;\n\tstruct session\t\t*s = c->session;\n\tstruct window\t\t*w = s->curw->window;\n\tstruct tty\t\t*tty = &c->tty;\n\tstruct window_pane\t*wp;\n\tstruct window_pane\t*active = w->active;\n\tstruct window_pane\t*marked = marked_pane.wp;\n\tu_int\t\t\t type, x = ctx->ox + i, y = ctx->oy + j;\n\tint\t\t\t flag, pane_status = ctx->pane_status;\n\n\tif (c->overlay_check != NULL && !c->overlay_check(c, x, y))\n\t\treturn;\n\ttype = screen_redraw_check_cell(c, x, y, pane_status, &wp);\n\tif (type == CELL_INSIDE)\n\t\treturn;\n\tflag = screen_redraw_check_is(x, y, type, pane_status, w, active, wp);\n"} {"commit": "5f92f92908b81b4ec66682adb84b9ffc8d83c2f7", "message": "Add a per-pane option set. Pane options inherit from window options (so there should be no change to existing behaviour) and are set and shown with set-option -p and show-options -p.", "old_file": "cmd-swap-pane.c", "new_file": "cmd-swap-pane.c", "status": "M", "old_contents": "\n\tif (src_wp == dst_wp)\n\t\treturn (CMD_RETURN_NORMAL);\n\n\ttmp_wp = TAILQ_PREV(dst_wp, window_panes, entry);\n\tTAILQ_REMOVE(&dst_w->panes, dst_wp, entry);\n\tTAILQ_REPLACE(&src_w->panes, src_wp, dst_wp, entry);\n\tif (tmp_wp == src_wp)\n\t\ttmp_wp = dst_wp;\n\tif (tmp_wp == NULL)\n\t\tTAILQ_INSERT_HEAD(&dst_w->panes, src_wp, entry);\n\telse\n\t\tTAILQ_INSERT_AFTER(&dst_w->panes, tmp_wp, src_wp, entry);\n\n\tsrc_lc = src_wp->layout_cell;\n\tdst_lc = dst_wp->layout_cell;\n\tsrc_lc->wp = dst_wp;\n\tdst_wp->layout_cell = src_lc;\n\tdst_lc->wp = src_wp;\n\tsrc_wp->layout_cell = dst_lc;\n\n\tsrc_wp->window = dst_w;\n\tdst_wp->window = src_w;\n\n\tsx = src_wp->sx; sy = src_wp->sy;\n\txoff = src_wp->xoff; yoff = src_wp->yoff;\n\tsrc_wp->xoff = dst_wp->xoff; src_wp->yoff = dst_wp->yoff;\n\twindow_pane_resize(src_wp, dst_wp->sx, dst_wp->sy);\n\tdst_wp->xoff = xoff; dst_wp->yoff = yoff;\n\twindow_pane_resize(dst_wp, sx, sy);\n\n\tif (!args_has(self->args, 'd')) {\n\t\tif (src_w != dst_w) {\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t\t} else {\n\t\t\ttmp_wp = dst_wp;\n\t\t\twindow_set_active_pane(src_w, tmp_wp, 1);\n\t\t}\n\t} else {\n\t\tif (src_w->active == src_wp)\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\tif (dst_w->active == dst_wp)\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t}\n\tif (src_w != dst_w) {\n\t\tif (src_w->last == src_wp)", "new_contents": "\n\tif (src_wp == dst_wp)\n\t\treturn (CMD_RETURN_NORMAL);\n\n\ttmp_wp = TAILQ_PREV(dst_wp, window_panes, entry);\n\tTAILQ_REMOVE(&dst_w->panes, dst_wp, entry);\n\tTAILQ_REPLACE(&src_w->panes, src_wp, dst_wp, entry);\n\tif (tmp_wp == src_wp)\n\t\ttmp_wp = dst_wp;\n\tif (tmp_wp == NULL)\n\t\tTAILQ_INSERT_HEAD(&dst_w->panes, src_wp, entry);\n\telse\n\t\tTAILQ_INSERT_AFTER(&dst_w->panes, tmp_wp, src_wp, entry);\n\n\tsrc_lc = src_wp->layout_cell;\n\tdst_lc = dst_wp->layout_cell;\n\tsrc_lc->wp = dst_wp;\n\tdst_wp->layout_cell = src_lc;\n\tdst_lc->wp = src_wp;\n\tsrc_wp->layout_cell = dst_lc;\n\n\tsrc_wp->window = dst_w;\n\toptions_set_parent(src_wp->options, dst_w->options);\n\tsrc_wp->flags |= PANE_STYLECHANGED;\n\tdst_wp->window = src_w;\n\toptions_set_parent(dst_wp->options, src_w->options);\n\tdst_wp->flags |= PANE_STYLECHANGED;\n\n\tsx = src_wp->sx; sy = src_wp->sy;\n\txoff = src_wp->xoff; yoff = src_wp->yoff;\n\tsrc_wp->xoff = dst_wp->xoff; src_wp->yoff = dst_wp->yoff;\n\twindow_pane_resize(src_wp, dst_wp->sx, dst_wp->sy);\n\tdst_wp->xoff = xoff; dst_wp->yoff = yoff;\n\twindow_pane_resize(dst_wp, sx, sy);\n\n\tif (!args_has(self->args, 'd')) {\n\t\tif (src_w != dst_w) {\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t\t} else {\n\t\t\ttmp_wp = dst_wp;\n\t\t\twindow_set_active_pane(src_w, tmp_wp, 1);\n\t\t}\n\t} else {\n\t\tif (src_w->active == src_wp)\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\tif (dst_w->active == dst_wp)\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t}\n\tif (src_w != dst_w) {\n\t\tif (src_w->last == src_wp)", "current_contents": "\n\tif (src_wp == dst_wp)\n\t\treturn (CMD_RETURN_NORMAL);\n\n\ttmp_wp = TAILQ_PREV(dst_wp, window_panes, entry);\n\tTAILQ_REMOVE(&dst_w->panes, dst_wp, entry);\n\tTAILQ_REPLACE(&src_w->panes, src_wp, dst_wp, entry);\n\tif (tmp_wp == src_wp)\n\t\ttmp_wp = dst_wp;\n\tif (tmp_wp == NULL)\n\t\tTAILQ_INSERT_HEAD(&dst_w->panes, src_wp, entry);\n\telse\n\t\tTAILQ_INSERT_AFTER(&dst_w->panes, tmp_wp, src_wp, entry);\n\n\tsrc_lc = src_wp->layout_cell;\n\tdst_lc = dst_wp->layout_cell;\n\tsrc_lc->wp = dst_wp;\n\tdst_wp->layout_cell = src_lc;\n\tdst_lc->wp = src_wp;\n\tsrc_wp->layout_cell = dst_lc;\n\n\tsrc_wp->window = dst_w;\n\toptions_set_parent(src_wp->options, dst_w->options);\n\tsrc_wp->flags |= PANE_STYLECHANGED;\n\tdst_wp->window = src_w;\n\n\tsx = src_wp->sx; sy = src_wp->sy;\n\txoff = src_wp->xoff; yoff = src_wp->yoff;\n\tsrc_wp->xoff = dst_wp->xoff; src_wp->yoff = dst_wp->yoff;\n\twindow_pane_resize(src_wp, dst_wp->sx, dst_wp->sy);\n\tdst_wp->xoff = xoff; dst_wp->yoff = yoff;\n\twindow_pane_resize(dst_wp, sx, sy);\n\n\tif (!args_has(self->args, 'd')) {\n\t\tif (src_w != dst_w) {\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t\t} else {\n\t\t\ttmp_wp = dst_wp;\n\t\t\twindow_set_active_pane(src_w, tmp_wp, 1);\n\t\t}\n\t} else {\n\t\tif (src_w->active == src_wp)\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\tif (dst_w->active == dst_wp)\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t}\n\tif (src_w != dst_w) {\n\t\tif (src_w->last == src_wp)", "text": "<|original_code|>\n\n\tif (src_wp == dst_wp)\n\t\treturn (CMD_RETURN_NORMAL);\n\n\ttmp_wp = TAILQ_PREV(dst_wp, window_panes, entry);\n\tTAILQ_REMOVE(&dst_w->panes, dst_wp, entry);\n\tTAILQ_REPLACE(&src_w->panes, src_wp, dst_wp, entry);\n\tif (tmp_wp == src_wp)\n\t\ttmp_wp = dst_wp;\n\tif (tmp_wp == NULL)\n\t\tTAILQ_INSERT_HEAD(&dst_w->panes, src_wp, entry);\n\telse\n\t\tTAILQ_INSERT_AFTER(&dst_w->panes, tmp_wp, src_wp, entry);\n\n\tsrc_lc = src_wp->layout_cell;\n\tdst_lc = dst_wp->layout_cell;\n\tsrc_lc->wp = dst_wp;\n\tdst_wp->layout_cell = src_lc;\n\tdst_lc->wp = src_wp;\n\tsrc_wp->layout_cell = dst_lc;\n\n\tsrc_wp->window = dst_w;\n\tdst_wp->window = src_w;\n\n\tsx = src_wp->sx; sy = src_wp->sy;\n\txoff = src_wp->xoff; yoff = src_wp->yoff;\n\tsrc_wp->xoff = dst_wp->xoff; src_wp->yoff = dst_wp->yoff;\n\twindow_pane_resize(src_wp, dst_wp->sx, dst_wp->sy);\n\tdst_wp->xoff = xoff; dst_wp->yoff = yoff;\n\twindow_pane_resize(dst_wp, sx, sy);\n\n\tif (!args_has(self->args, 'd')) {\n\t\tif (src_w != dst_w) {\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t\t} else {\n\t\t\ttmp_wp = dst_wp;\n\t\t\twindow_set_active_pane(src_w, tmp_wp, 1);\n\t\t}\n\t} else {\n\t\tif (src_w->active == src_wp)\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\tif (dst_w->active == dst_wp)\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t}\n\tif (src_w != dst_w) {\n\t\tif (src_w->last == src_wp)\n<|edits_diff|>\n--- cmd-swap-pane.c\n+++ cmd-swap-pane.c\n@@ -20,6 +20,8 @@\n \tsrc_wp->layout_cell = dst_lc;\n \n \tsrc_wp->window = dst_w;\n+\toptions_set_parent(src_wp->options, dst_w->options);\n+\tsrc_wp->flags |= PANE_STYLECHANGED;\n \tdst_wp->window = src_w;\n \n \tsx = src_wp->sx; sy = src_wp->sy;\n<|current_version|>\n\n\tif (src_wp == dst_wp)\n\t\treturn (CMD_RETURN_NORMAL);\n\n\ttmp_wp = TAILQ_PREV(dst_wp, window_panes, entry);\n\tTAILQ_REMOVE(&dst_w->panes, dst_wp, entry);\n\tTAILQ_REPLACE(&src_w->panes, src_wp, dst_wp, entry);\n\tif (tmp_wp == src_wp)\n\t\ttmp_wp = dst_wp;\n\tif (tmp_wp == NULL)\n\t\tTAILQ_INSERT_HEAD(&dst_w->panes, src_wp, entry);\n\telse\n\t\tTAILQ_INSERT_AFTER(&dst_w->panes, tmp_wp, src_wp, entry);\n\n\tsrc_lc = src_wp->layout_cell;\n\tdst_lc = dst_wp->layout_cell;\n\tsrc_lc->wp = dst_wp;\n\tdst_wp->layout_cell = src_lc;\n\tdst_lc->wp = src_wp;\n\tsrc_wp->layout_cell = dst_lc;\n\n\tsrc_wp->window = dst_w;\n\toptions_set_parent(src_wp->options, dst_w->options);\n\tsrc_wp->flags |= PANE_STYLECHANGED;\n\tdst_wp->window = src_w;\n\n\tsx = src_wp->sx; sy = src_wp->sy;\n\txoff = src_wp->xoff; yoff = src_wp->yoff;\n\tsrc_wp->xoff = dst_wp->xoff; src_wp->yoff = dst_wp->yoff;\n\twindow_pane_resize(src_wp, dst_wp->sx, dst_wp->sy);\n\tdst_wp->xoff = xoff; dst_wp->yoff = yoff;\n\twindow_pane_resize(dst_wp, sx, sy);\n\n\tif (!args_has(self->args, 'd')) {\n\t\tif (src_w != dst_w) {\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t\t} else {\n\t\t\ttmp_wp = dst_wp;\n\t\t\twindow_set_active_pane(src_w, tmp_wp, 1);\n\t\t}\n\t} else {\n\t\tif (src_w->active == src_wp)\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\tif (dst_w->active == dst_wp)\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t}\n\tif (src_w != dst_w) {\n\t\tif (src_w->last == src_wp)\n<|next_version|>\n\n\tif (src_wp == dst_wp)\n\t\treturn (CMD_RETURN_NORMAL);\n\n\ttmp_wp = TAILQ_PREV(dst_wp, window_panes, entry);\n\tTAILQ_REMOVE(&dst_w->panes, dst_wp, entry);\n\tTAILQ_REPLACE(&src_w->panes, src_wp, dst_wp, entry);\n\tif (tmp_wp == src_wp)\n\t\ttmp_wp = dst_wp;\n\tif (tmp_wp == NULL)\n\t\tTAILQ_INSERT_HEAD(&dst_w->panes, src_wp, entry);\n\telse\n\t\tTAILQ_INSERT_AFTER(&dst_w->panes, tmp_wp, src_wp, entry);\n\n\tsrc_lc = src_wp->layout_cell;\n\tdst_lc = dst_wp->layout_cell;\n\tsrc_lc->wp = dst_wp;\n\tdst_wp->layout_cell = src_lc;\n\tdst_lc->wp = src_wp;\n\tsrc_wp->layout_cell = dst_lc;\n\n\tsrc_wp->window = dst_w;\n\toptions_set_parent(src_wp->options, dst_w->options);\n\tsrc_wp->flags |= PANE_STYLECHANGED;\n\tdst_wp->window = src_w;\n\toptions_set_parent(dst_wp->options, src_w->options);\n\tdst_wp->flags |= PANE_STYLECHANGED;\n\n\tsx = src_wp->sx; sy = src_wp->sy;\n\txoff = src_wp->xoff; yoff = src_wp->yoff;\n\tsrc_wp->xoff = dst_wp->xoff; src_wp->yoff = dst_wp->yoff;\n\twindow_pane_resize(src_wp, dst_wp->sx, dst_wp->sy);\n\tdst_wp->xoff = xoff; dst_wp->yoff = yoff;\n\twindow_pane_resize(dst_wp, sx, sy);\n\n\tif (!args_has(self->args, 'd')) {\n\t\tif (src_w != dst_w) {\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t\t} else {\n\t\t\ttmp_wp = dst_wp;\n\t\t\twindow_set_active_pane(src_w, tmp_wp, 1);\n\t\t}\n\t} else {\n\t\tif (src_w->active == src_wp)\n\t\t\twindow_set_active_pane(src_w, dst_wp, 1);\n\t\tif (dst_w->active == dst_wp)\n\t\t\twindow_set_active_pane(dst_w, src_wp, 1);\n\t}\n\tif (src_w != dst_w) {\n\t\tif (src_w->last == src_wp)\n"} {"commit": "92da105b58d2b828974585f21b70d5f1b42049fe", "message": "Free old strings after they have been expanded in format_choose.", "old_file": "format.c", "new_file": "format.c", "status": "M", "old_contents": "\t}\n\tif (*s == '\\0')\n\t\treturn (NULL);\n\treturn (s);\n}\n\n/* Return left and right alternatives separated by commas. */\nstatic int\nformat_choose(struct format_tree *ft, const char *s, char **left, char **right,\n int expand)\n{\n\tconst char\t*cp;\n\tchar\t\t*left0, *right0;\n\n\tcp = format_skip(s, \",\");\n\tif (cp == NULL)\n\t\treturn (-1);\n\tleft0 = xstrndup(s, cp - s);\n\tright0 = xstrdup(cp + 1);\n\n\tif (expand) {\n\t\t*left = format_expand(ft, left0);\n\t\t*right = format_expand(ft, right0);\n\t} else {\n\t\t*left = left0;\n\t\t*right = right0;\n\t}\n\treturn (0);\n}\n\n/* Is this true? */\nint\nformat_true(const char *s)\n{\n\tif (s != NULL && *s != '\\0' && (s[0] != '0' || s[1] != '\\0'))\n\t\treturn (1);\n\treturn (0);\n}\n\n/* Check if modifier end. */\nstatic int\nformat_is_end(char c)\n{\n\treturn (c == ';' || c == ':');\n}\n\n/* Add to modifier list. */", "new_contents": "\t}\n\tif (*s == '\\0')\n\t\treturn (NULL);\n\treturn (s);\n}\n\n/* Return left and right alternatives separated by commas. */\nstatic int\nformat_choose(struct format_tree *ft, const char *s, char **left, char **right,\n int expand)\n{\n\tconst char\t*cp;\n\tchar\t\t*left0, *right0;\n\n\tcp = format_skip(s, \",\");\n\tif (cp == NULL)\n\t\treturn (-1);\n\tleft0 = xstrndup(s, cp - s);\n\tright0 = xstrdup(cp + 1);\n\n\tif (expand) {\n\t\t*left = format_expand(ft, left0);\n\t\tfree(left0);\n\t\t*right = format_expand(ft, right0);\n\t\tfree(right0);\n\t} else {\n\t\t*left = left0;\n\t\t*right = right0;\n\t}\n\treturn (0);\n}\n\n/* Is this true? */\nint\nformat_true(const char *s)\n{\n\tif (s != NULL && *s != '\\0' && (s[0] != '0' || s[1] != '\\0'))\n\t\treturn (1);\n\treturn (0);\n}\n\n/* Check if modifier end. */\nstatic int\nformat_is_end(char c)\n{\n\treturn (c == ';' || c == ':');\n}\n\n/* Add to modifier list. */", "current_contents": "\t}\n\tif (*s == '\\0')\n\t\treturn (NULL);\n\treturn (s);\n}\n\n/* Return left and right alternatives separated by commas. */\nstatic int\nformat_choose(struct format_tree *ft, const char *s, char **left, char **right,\n int expand)\n{\n\tconst char\t*cp;\n\tchar\t\t*left0, *right0;\n\n\tcp = format_skip(s, \",\");\n\tif (cp == NULL)\n\t\treturn (-1);\n\tleft0 = xstrndup(s, cp - s);\n\tright0 = xstrdup(cp + 1);\n\n\tif (expand) {\n\t\t*left = format_expand(ft, left0);\n\t\tfree(left0);\n\t\t*right = format_expand(ft, right0);\n\t} else {\n\t\t*left = left0;\n\t\t*right = right0;\n\t}\n\treturn (0);\n}\n\n/* Is this true? */\nint\nformat_true(const char *s)\n{\n\tif (s != NULL && *s != '\\0' && (s[0] != '0' || s[1] != '\\0'))\n\t\treturn (1);\n\treturn (0);\n}\n\n/* Check if modifier end. */\nstatic int\nformat_is_end(char c)\n{\n\treturn (c == ';' || c == ':');\n}\n\n/* Add to modifier list. */", "text": "<|original_code|>\n\t}\n\tif (*s == '\\0')\n\t\treturn (NULL);\n\treturn (s);\n}\n\n/* Return left and right alternatives separated by commas. */\nstatic int\nformat_choose(struct format_tree *ft, const char *s, char **left, char **right,\n int expand)\n{\n\tconst char\t*cp;\n\tchar\t\t*left0, *right0;\n\n\tcp = format_skip(s, \",\");\n\tif (cp == NULL)\n\t\treturn (-1);\n\tleft0 = xstrndup(s, cp - s);\n\tright0 = xstrdup(cp + 1);\n\n\tif (expand) {\n\t\t*left = format_expand(ft, left0);\n\t\t*right = format_expand(ft, right0);\n\t} else {\n\t\t*left = left0;\n\t\t*right = right0;\n\t}\n\treturn (0);\n}\n\n/* Is this true? */\nint\nformat_true(const char *s)\n{\n\tif (s != NULL && *s != '\\0' && (s[0] != '0' || s[1] != '\\0'))\n\t\treturn (1);\n\treturn (0);\n}\n\n/* Check if modifier end. */\nstatic int\nformat_is_end(char c)\n{\n\treturn (c == ';' || c == ':');\n}\n\n/* Add to modifier list. */\n<|edits_diff|>\n--- format.c\n+++ format.c\n@@ -20,6 +20,7 @@\n \n \tif (expand) {\n \t\t*left = format_expand(ft, left0);\n+\t\tfree(left0);\n \t\t*right = format_expand(ft, right0);\n \t} else {\n \t\t*left = left0;\n<|current_version|>\n\t}\n\tif (*s == '\\0')\n\t\treturn (NULL);\n\treturn (s);\n}\n\n/* Return left and right alternatives separated by commas. */\nstatic int\nformat_choose(struct format_tree *ft, const char *s, char **left, char **right,\n int expand)\n{\n\tconst char\t*cp;\n\tchar\t\t*left0, *right0;\n\n\tcp = format_skip(s, \",\");\n\tif (cp == NULL)\n\t\treturn (-1);\n\tleft0 = xstrndup(s, cp - s);\n\tright0 = xstrdup(cp + 1);\n\n\tif (expand) {\n\t\t*left = format_expand(ft, left0);\n\t\tfree(left0);\n\t\t*right = format_expand(ft, right0);\n\t} else {\n\t\t*left = left0;\n\t\t*right = right0;\n\t}\n\treturn (0);\n}\n\n/* Is this true? */\nint\nformat_true(const char *s)\n{\n\tif (s != NULL && *s != '\\0' && (s[0] != '0' || s[1] != '\\0'))\n\t\treturn (1);\n\treturn (0);\n}\n\n/* Check if modifier end. */\nstatic int\nformat_is_end(char c)\n{\n\treturn (c == ';' || c == ':');\n}\n\n/* Add to modifier list. */\n<|next_version|>\n\t}\n\tif (*s == '\\0')\n\t\treturn (NULL);\n\treturn (s);\n}\n\n/* Return left and right alternatives separated by commas. */\nstatic int\nformat_choose(struct format_tree *ft, const char *s, char **left, char **right,\n int expand)\n{\n\tconst char\t*cp;\n\tchar\t\t*left0, *right0;\n\n\tcp = format_skip(s, \",\");\n\tif (cp == NULL)\n\t\treturn (-1);\n\tleft0 = xstrndup(s, cp - s);\n\tright0 = xstrdup(cp + 1);\n\n\tif (expand) {\n\t\t*left = format_expand(ft, left0);\n\t\tfree(left0);\n\t\t*right = format_expand(ft, right0);\n\t\tfree(right0);\n\t} else {\n\t\t*left = left0;\n\t\t*right = right0;\n\t}\n\treturn (0);\n}\n\n/* Is this true? */\nint\nformat_true(const char *s)\n{\n\tif (s != NULL && *s != '\\0' && (s[0] != '0' || s[1] != '\\0'))\n\t\treturn (1);\n\treturn (0);\n}\n\n/* Check if modifier end. */\nstatic int\nformat_is_end(char c)\n{\n\treturn (c == ';' || c == ':');\n}\n\n/* Add to modifier list. */\n"} {"commit": "749f67b7d801eed03345fef9c04206fbd079c3cb", "message": "evbuffer_new and bufferevent_new can both fail (when malloc fails) and return NULL. GitHub issue 1547.", "old_file": "server-client.c", "new_file": "server-client.c", "status": "M", "old_contents": "server_client_create(int fd)\n{\n\tstruct client\t*c;\n\n\tsetblocking(fd, 0);\n\n\tc = xcalloc(1, sizeof *c);\n\tc->references = 1;\n\tc->peer = proc_add_peer(server_proc, fd, server_client_dispatch, c);\n\n\tif (gettimeofday(&c->creation_time, NULL) != 0)\n\t\tfatal(\"gettimeofday failed\");\n\tmemcpy(&c->activity_time, &c->creation_time, sizeof c->activity_time);\n\n\tc->environ = environ_create();\n\n\tc->fd = -1;\n\tc->cwd = NULL;\n\n\tTAILQ_INIT(&c->queue);\n\n\tc->stdin_data = evbuffer_new();\n\tc->stdout_data = evbuffer_new();\n\tc->stderr_data = evbuffer_new();\n\n\tc->tty.fd = -1;\n\tc->title = NULL;\n\n\tc->session = NULL;\n\tc->last_session = NULL;\n\n\tc->tty.sx = 80;\n\tc->tty.sy = 24;\n\n\tscreen_init(&c->status.status, c->tty.sx, 1, 0);\n\n\tc->message_string = NULL;\n\tTAILQ_INIT(&c->message_log);\n\n\tc->prompt_string = NULL;\n\tc->prompt_buffer = NULL;\n\tc->prompt_index = 0;\n\n\tc->flags |= CLIENT_FOCUSED;\n\n\tc->keytable = key_bindings_get_table(\"root\", 1);\n\tc->keytable->references++;\n", "new_contents": "server_client_create(int fd)\n{\n\tstruct client\t*c;\n\n\tsetblocking(fd, 0);\n\n\tc = xcalloc(1, sizeof *c);\n\tc->references = 1;\n\tc->peer = proc_add_peer(server_proc, fd, server_client_dispatch, c);\n\n\tif (gettimeofday(&c->creation_time, NULL) != 0)\n\t\tfatal(\"gettimeofday failed\");\n\tmemcpy(&c->activity_time, &c->creation_time, sizeof c->activity_time);\n\n\tc->environ = environ_create();\n\n\tc->fd = -1;\n\tc->cwd = NULL;\n\n\tTAILQ_INIT(&c->queue);\n\n\tc->stdin_data = evbuffer_new();\n\tif (c->stdin_data == NULL)\n\t\tfatalx(\"out of memory\");\n\tc->stdout_data = evbuffer_new();\n\tif (c->stdout_data == NULL)\n\t\tfatalx(\"out of memory\");\n\tc->stderr_data = evbuffer_new();\n\tif (c->stderr_data == NULL)\n\t\tfatalx(\"out of memory\");\n\n\tc->tty.fd = -1;\n\tc->title = NULL;\n\n\tc->session = NULL;\n\tc->last_session = NULL;\n\n\tc->tty.sx = 80;\n\tc->tty.sy = 24;\n\n\tscreen_init(&c->status.status, c->tty.sx, 1, 0);\n\n\tc->message_string = NULL;\n\tTAILQ_INIT(&c->message_log);\n\n\tc->prompt_string = NULL;\n\tc->prompt_buffer = NULL;\n\tc->prompt_index = 0;\n\n\tc->flags |= CLIENT_FOCUSED;\n\n\tc->keytable = key_bindings_get_table(\"root\", 1);\n\tc->keytable->references++;\n", "current_contents": "server_client_create(int fd)\n{\n\tstruct client\t*c;\n\n\tsetblocking(fd, 0);\n\n\tc = xcalloc(1, sizeof *c);\n\tc->references = 1;\n\tc->peer = proc_add_peer(server_proc, fd, server_client_dispatch, c);\n\n\tif (gettimeofday(&c->creation_time, NULL) != 0)\n\t\tfatal(\"gettimeofday failed\");\n\tmemcpy(&c->activity_time, &c->creation_time, sizeof c->activity_time);\n\n\tc->environ = environ_create();\n\n\tc->fd = -1;\n\tc->cwd = NULL;\n\n\tTAILQ_INIT(&c->queue);\n\n\tc->stdin_data = evbuffer_new();\n\tif (c->stdin_data == NULL)\n\t\tfatalx(\"out of memory\");\n\tc->stdout_data = evbuffer_new();\n\tif (c->stdout_data == NULL)\n\t\tfatalx(\"out of memory\");\n\tc->stderr_data = evbuffer_new();\n\n\tc->tty.fd = -1;\n\tc->title = NULL;\n\n\tc->session = NULL;\n\tc->last_session = NULL;\n\n\tc->tty.sx = 80;\n\tc->tty.sy = 24;\n\n\tscreen_init(&c->status.status, c->tty.sx, 1, 0);\n\n\tc->message_string = NULL;\n\tTAILQ_INIT(&c->message_log);\n\n\tc->prompt_string = NULL;\n\tc->prompt_buffer = NULL;\n\tc->prompt_index = 0;\n\n\tc->flags |= CLIENT_FOCUSED;\n\n\tc->keytable = key_bindings_get_table(\"root\", 1);\n\tc->keytable->references++;\n", "text": "<|original_code|>\nserver_client_create(int fd)\n{\n\tstruct client\t*c;\n\n\tsetblocking(fd, 0);\n\n\tc = xcalloc(1, sizeof *c);\n\tc->references = 1;\n\tc->peer = proc_add_peer(server_proc, fd, server_client_dispatch, c);\n\n\tif (gettimeofday(&c->creation_time, NULL) != 0)\n\t\tfatal(\"gettimeofday failed\");\n\tmemcpy(&c->activity_time, &c->creation_time, sizeof c->activity_time);\n\n\tc->environ = environ_create();\n\n\tc->fd = -1;\n\tc->cwd = NULL;\n\n\tTAILQ_INIT(&c->queue);\n\n\tc->stdin_data = evbuffer_new();\n\tc->stdout_data = evbuffer_new();\n\tc->stderr_data = evbuffer_new();\n\n\tc->tty.fd = -1;\n\tc->title = NULL;\n\n\tc->session = NULL;\n\tc->last_session = NULL;\n\n\tc->tty.sx = 80;\n\tc->tty.sy = 24;\n\n\tscreen_init(&c->status.status, c->tty.sx, 1, 0);\n\n\tc->message_string = NULL;\n\tTAILQ_INIT(&c->message_log);\n\n\tc->prompt_string = NULL;\n\tc->prompt_buffer = NULL;\n\tc->prompt_index = 0;\n\n\tc->flags |= CLIENT_FOCUSED;\n\n\tc->keytable = key_bindings_get_table(\"root\", 1);\n\tc->keytable->references++;\n\n<|edits_diff|>\n--- server-client.c\n+++ server-client.c\n@@ -20,7 +20,11 @@\n \tTAILQ_INIT(&c->queue);\n \n \tc->stdin_data = evbuffer_new();\n+\tif (c->stdin_data == NULL)\n+\t\tfatalx(\"out of memory\");\n \tc->stdout_data = evbuffer_new();\n+\tif (c->stdout_data == NULL)\n+\t\tfatalx(\"out of memory\");\n \tc->stderr_data = evbuffer_new();\n \n \tc->tty.fd = -1;\n<|current_version|>\nserver_client_create(int fd)\n{\n\tstruct client\t*c;\n\n\tsetblocking(fd, 0);\n\n\tc = xcalloc(1, sizeof *c);\n\tc->references = 1;\n\tc->peer = proc_add_peer(server_proc, fd, server_client_dispatch, c);\n\n\tif (gettimeofday(&c->creation_time, NULL) != 0)\n\t\tfatal(\"gettimeofday failed\");\n\tmemcpy(&c->activity_time, &c->creation_time, sizeof c->activity_time);\n\n\tc->environ = environ_create();\n\n\tc->fd = -1;\n\tc->cwd = NULL;\n\n\tTAILQ_INIT(&c->queue);\n\n\tc->stdin_data = evbuffer_new();\n\tif (c->stdin_data == NULL)\n\t\tfatalx(\"out of memory\");\n\tc->stdout_data = evbuffer_new();\n\tif (c->stdout_data == NULL)\n\t\tfatalx(\"out of memory\");\n\tc->stderr_data = evbuffer_new();\n\n\tc->tty.fd = -1;\n\tc->title = NULL;\n\n\tc->session = NULL;\n\tc->last_session = NULL;\n\n\tc->tty.sx = 80;\n\tc->tty.sy = 24;\n\n\tscreen_init(&c->status.status, c->tty.sx, 1, 0);\n\n\tc->message_string = NULL;\n\tTAILQ_INIT(&c->message_log);\n\n\tc->prompt_string = NULL;\n\tc->prompt_buffer = NULL;\n\tc->prompt_index = 0;\n\n\tc->flags |= CLIENT_FOCUSED;\n\n\tc->keytable = key_bindings_get_table(\"root\", 1);\n\tc->keytable->references++;\n\n<|next_version|>\nserver_client_create(int fd)\n{\n\tstruct client\t*c;\n\n\tsetblocking(fd, 0);\n\n\tc = xcalloc(1, sizeof *c);\n\tc->references = 1;\n\tc->peer = proc_add_peer(server_proc, fd, server_client_dispatch, c);\n\n\tif (gettimeofday(&c->creation_time, NULL) != 0)\n\t\tfatal(\"gettimeofday failed\");\n\tmemcpy(&c->activity_time, &c->creation_time, sizeof c->activity_time);\n\n\tc->environ = environ_create();\n\n\tc->fd = -1;\n\tc->cwd = NULL;\n\n\tTAILQ_INIT(&c->queue);\n\n\tc->stdin_data = evbuffer_new();\n\tif (c->stdin_data == NULL)\n\t\tfatalx(\"out of memory\");\n\tc->stdout_data = evbuffer_new();\n\tif (c->stdout_data == NULL)\n\t\tfatalx(\"out of memory\");\n\tc->stderr_data = evbuffer_new();\n\tif (c->stderr_data == NULL)\n\t\tfatalx(\"out of memory\");\n\n\tc->tty.fd = -1;\n\tc->title = NULL;\n\n\tc->session = NULL;\n\tc->last_session = NULL;\n\n\tc->tty.sx = 80;\n\tc->tty.sy = 24;\n\n\tscreen_init(&c->status.status, c->tty.sx, 1, 0);\n\n\tc->message_string = NULL;\n\tTAILQ_INIT(&c->message_log);\n\n\tc->prompt_string = NULL;\n\tc->prompt_buffer = NULL;\n\tc->prompt_index = 0;\n\n\tc->flags |= CLIENT_FOCUSED;\n\n\tc->keytable = key_bindings_get_table(\"root\", 1);\n\tc->keytable->references++;\n\n"} {"commit": "d091253a5d240fe867cf966a6d3edc0ddd028d1a", "message": "Missing va_end, from Anton Lindqvist.", "old_file": "log.c", "new_file": "log.c", "status": "M", "old_contents": "/* Log a debug message. */\nvoid\nlog_debug(const char *msg, ...)\n{\n\tva_list\tap;\n\n\tva_start(ap, msg);\n\tlog_vwrite(msg, ap);\n\tva_end(ap);\n}\n\n/* Log a critical error with error string and die. */\n__dead void\nfatal(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s: %s\", msg, strerror(errno)) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\texit(1);\n}\n\n/* Log a critical error and die. */\n__dead void\nfatalx(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s\", msg) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\texit(1);\n}\n", "new_contents": "/* Log a debug message. */\nvoid\nlog_debug(const char *msg, ...)\n{\n\tva_list\tap;\n\n\tva_start(ap, msg);\n\tlog_vwrite(msg, ap);\n\tva_end(ap);\n}\n\n/* Log a critical error with error string and die. */\n__dead void\nfatal(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s: %s\", msg, strerror(errno)) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\tva_end(ap);\n\texit(1);\n}\n\n/* Log a critical error and die. */\n__dead void\nfatalx(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s\", msg) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\tva_end(ap);\n\texit(1);\n}\n", "current_contents": "/* Log a debug message. */\nvoid\nlog_debug(const char *msg, ...)\n{\n\tva_list\tap;\n\n\tva_start(ap, msg);\n\tlog_vwrite(msg, ap);\n\tva_end(ap);\n}\n\n/* Log a critical error with error string and die. */\n__dead void\nfatal(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s: %s\", msg, strerror(errno)) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\tva_end(ap);\n\texit(1);\n}\n\n/* Log a critical error and die. */\n__dead void\nfatalx(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s\", msg) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\texit(1);\n}\n", "text": "<|original_code|>\n/* Log a debug message. */\nvoid\nlog_debug(const char *msg, ...)\n{\n\tva_list\tap;\n\n\tva_start(ap, msg);\n\tlog_vwrite(msg, ap);\n\tva_end(ap);\n}\n\n/* Log a critical error with error string and die. */\n__dead void\nfatal(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s: %s\", msg, strerror(errno)) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\texit(1);\n}\n\n/* Log a critical error and die. */\n__dead void\nfatalx(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s\", msg) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\texit(1);\n}\n\n<|edits_diff|>\n--- log.c\n+++ log.c\n@@ -20,6 +20,7 @@\n \tif (asprintf(&fmt, \"fatal: %s: %s\", msg, strerror(errno)) == -1)\n \t\texit(1);\n \tlog_vwrite(fmt, ap);\n+\tva_end(ap);\n \texit(1);\n }\n \n<|current_version|>\n/* Log a debug message. */\nvoid\nlog_debug(const char *msg, ...)\n{\n\tva_list\tap;\n\n\tva_start(ap, msg);\n\tlog_vwrite(msg, ap);\n\tva_end(ap);\n}\n\n/* Log a critical error with error string and die. */\n__dead void\nfatal(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s: %s\", msg, strerror(errno)) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\tva_end(ap);\n\texit(1);\n}\n\n/* Log a critical error and die. */\n__dead void\nfatalx(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s\", msg) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\texit(1);\n}\n\n<|next_version|>\n/* Log a debug message. */\nvoid\nlog_debug(const char *msg, ...)\n{\n\tva_list\tap;\n\n\tva_start(ap, msg);\n\tlog_vwrite(msg, ap);\n\tva_end(ap);\n}\n\n/* Log a critical error with error string and die. */\n__dead void\nfatal(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s: %s\", msg, strerror(errno)) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\tva_end(ap);\n\texit(1);\n}\n\n/* Log a critical error and die. */\n__dead void\nfatalx(const char *msg, ...)\n{\n\tchar\t*fmt;\n\tva_list\t ap;\n\n\tva_start(ap, msg);\n\tif (asprintf(&fmt, \"fatal: %s\", msg) == -1)\n\t\texit(1);\n\tlog_vwrite(fmt, ap);\n\tva_end(ap);\n\texit(1);\n}\n\n"} {"commit": "5e4d9a3197a229ecb30d51f5b7e6756ef31dc1d2", "message": "Move the cursor back into the last column on CUU/CUD to match xterm behaviour. From George Nachman.", "old_file": "screen-write.c", "new_file": "screen-write.c", "status": "M", "old_contents": "\n\ts->mode &= ~mode;\n}\n\n/* Cursor up by ny. */\nvoid\nscreen_write_cursorup(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy < s->rupper) {\n\t\t/* Above region. */\n\t\tif (ny > s->cy)\n\t\t\tny = s->cy;\n\t} else {\n\t\t/* Below region. */\n\t\tif (ny > s->cy - s->rupper)\n\t\t\tny = s->cy - s->rupper;\n\t}\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy -= ny;\n}\n\n/* Cursor down by ny. */\nvoid\nscreen_write_cursordown(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy > s->rlower) {\n\t\t/* Below region. */\n\t\tif (ny > screen_size_y(s) - 1 - s->cy)\n\t\t\tny = screen_size_y(s) - 1 - s->cy;\n\t} else {\n\t\t/* Above region. */\n\t\tif (ny > s->rlower - s->cy)\n\t\t\tny = s->rlower - s->cy;\n\t}\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy += ny;\n}\n\n/* Cursor right by nx. */\nvoid\nscreen_write_cursorright(struct screen_write_ctx *ctx, u_int nx)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (nx == 0)\n\t\tnx = 1;\n\n\tif (nx > screen_size_x(s) - 1 - s->cx)\n\t\tnx = screen_size_x(s) - 1 - s->cx;\n\tif (nx == 0)\n\t\treturn;\n\n\ts->cx += nx;\n}\n\n/* Cursor left by nx. */", "new_contents": "\n\ts->mode &= ~mode;\n}\n\n/* Cursor up by ny. */\nvoid\nscreen_write_cursorup(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy < s->rupper) {\n\t\t/* Above region. */\n\t\tif (ny > s->cy)\n\t\t\tny = s->cy;\n\t} else {\n\t\t/* Below region. */\n\t\tif (ny > s->cy - s->rupper)\n\t\t\tny = s->cy - s->rupper;\n\t}\n\tif (s->cx == screen_size_x(s))\n\t s->cx--;\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy -= ny;\n}\n\n/* Cursor down by ny. */\nvoid\nscreen_write_cursordown(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy > s->rlower) {\n\t\t/* Below region. */\n\t\tif (ny > screen_size_y(s) - 1 - s->cy)\n\t\t\tny = screen_size_y(s) - 1 - s->cy;\n\t} else {\n\t\t/* Above region. */\n\t\tif (ny > s->rlower - s->cy)\n\t\t\tny = s->rlower - s->cy;\n\t}\n\tif (s->cx == screen_size_x(s))\n\t s->cx--;\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy += ny;\n}\n\n/* Cursor right by nx. */\nvoid\nscreen_write_cursorright(struct screen_write_ctx *ctx, u_int nx)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (nx == 0)\n\t\tnx = 1;\n\n\tif (nx > screen_size_x(s) - 1 - s->cx)\n\t\tnx = screen_size_x(s) - 1 - s->cx;\n\tif (nx == 0)\n\t\treturn;\n\n\ts->cx += nx;\n}\n\n/* Cursor left by nx. */", "current_contents": "\n\ts->mode &= ~mode;\n}\n\n/* Cursor up by ny. */\nvoid\nscreen_write_cursorup(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy < s->rupper) {\n\t\t/* Above region. */\n\t\tif (ny > s->cy)\n\t\t\tny = s->cy;\n\t} else {\n\t\t/* Below region. */\n\t\tif (ny > s->cy - s->rupper)\n\t\t\tny = s->cy - s->rupper;\n\t}\n\tif (s->cx == screen_size_x(s))\n\t s->cx--;\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy -= ny;\n}\n\n/* Cursor down by ny. */\nvoid\nscreen_write_cursordown(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy > s->rlower) {\n\t\t/* Below region. */\n\t\tif (ny > screen_size_y(s) - 1 - s->cy)\n\t\t\tny = screen_size_y(s) - 1 - s->cy;\n\t} else {\n\t\t/* Above region. */\n\t\tif (ny > s->rlower - s->cy)\n\t\t\tny = s->rlower - s->cy;\n\t}\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy += ny;\n}\n\n/* Cursor right by nx. */\nvoid\nscreen_write_cursorright(struct screen_write_ctx *ctx, u_int nx)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (nx == 0)\n\t\tnx = 1;\n\n\tif (nx > screen_size_x(s) - 1 - s->cx)\n\t\tnx = screen_size_x(s) - 1 - s->cx;\n\tif (nx == 0)\n\t\treturn;\n\n\ts->cx += nx;\n}\n\n/* Cursor left by nx. */", "text": "<|original_code|>\n\n\ts->mode &= ~mode;\n}\n\n/* Cursor up by ny. */\nvoid\nscreen_write_cursorup(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy < s->rupper) {\n\t\t/* Above region. */\n\t\tif (ny > s->cy)\n\t\t\tny = s->cy;\n\t} else {\n\t\t/* Below region. */\n\t\tif (ny > s->cy - s->rupper)\n\t\t\tny = s->cy - s->rupper;\n\t}\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy -= ny;\n}\n\n/* Cursor down by ny. */\nvoid\nscreen_write_cursordown(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy > s->rlower) {\n\t\t/* Below region. */\n\t\tif (ny > screen_size_y(s) - 1 - s->cy)\n\t\t\tny = screen_size_y(s) - 1 - s->cy;\n\t} else {\n\t\t/* Above region. */\n\t\tif (ny > s->rlower - s->cy)\n\t\t\tny = s->rlower - s->cy;\n\t}\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy += ny;\n}\n\n/* Cursor right by nx. */\nvoid\nscreen_write_cursorright(struct screen_write_ctx *ctx, u_int nx)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (nx == 0)\n\t\tnx = 1;\n\n\tif (nx > screen_size_x(s) - 1 - s->cx)\n\t\tnx = screen_size_x(s) - 1 - s->cx;\n\tif (nx == 0)\n\t\treturn;\n\n\ts->cx += nx;\n}\n\n/* Cursor left by nx. */\n<|edits_diff|>\n--- screen-write.c\n+++ screen-write.c\n@@ -20,6 +20,8 @@\n \t\tif (ny > s->cy - s->rupper)\n \t\t\tny = s->cy - s->rupper;\n \t}\n+\tif (s->cx == screen_size_x(s))\n+\t s->cx--;\n \tif (ny == 0)\n \t\treturn;\n \n<|current_version|>\n\n\ts->mode &= ~mode;\n}\n\n/* Cursor up by ny. */\nvoid\nscreen_write_cursorup(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy < s->rupper) {\n\t\t/* Above region. */\n\t\tif (ny > s->cy)\n\t\t\tny = s->cy;\n\t} else {\n\t\t/* Below region. */\n\t\tif (ny > s->cy - s->rupper)\n\t\t\tny = s->cy - s->rupper;\n\t}\n\tif (s->cx == screen_size_x(s))\n\t s->cx--;\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy -= ny;\n}\n\n/* Cursor down by ny. */\nvoid\nscreen_write_cursordown(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy > s->rlower) {\n\t\t/* Below region. */\n\t\tif (ny > screen_size_y(s) - 1 - s->cy)\n\t\t\tny = screen_size_y(s) - 1 - s->cy;\n\t} else {\n\t\t/* Above region. */\n\t\tif (ny > s->rlower - s->cy)\n\t\t\tny = s->rlower - s->cy;\n\t}\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy += ny;\n}\n\n/* Cursor right by nx. */\nvoid\nscreen_write_cursorright(struct screen_write_ctx *ctx, u_int nx)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (nx == 0)\n\t\tnx = 1;\n\n\tif (nx > screen_size_x(s) - 1 - s->cx)\n\t\tnx = screen_size_x(s) - 1 - s->cx;\n\tif (nx == 0)\n\t\treturn;\n\n\ts->cx += nx;\n}\n\n/* Cursor left by nx. */\n<|next_version|>\n\n\ts->mode &= ~mode;\n}\n\n/* Cursor up by ny. */\nvoid\nscreen_write_cursorup(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy < s->rupper) {\n\t\t/* Above region. */\n\t\tif (ny > s->cy)\n\t\t\tny = s->cy;\n\t} else {\n\t\t/* Below region. */\n\t\tif (ny > s->cy - s->rupper)\n\t\t\tny = s->cy - s->rupper;\n\t}\n\tif (s->cx == screen_size_x(s))\n\t s->cx--;\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy -= ny;\n}\n\n/* Cursor down by ny. */\nvoid\nscreen_write_cursordown(struct screen_write_ctx *ctx, u_int ny)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (ny == 0)\n\t\tny = 1;\n\n\tif (s->cy > s->rlower) {\n\t\t/* Below region. */\n\t\tif (ny > screen_size_y(s) - 1 - s->cy)\n\t\t\tny = screen_size_y(s) - 1 - s->cy;\n\t} else {\n\t\t/* Above region. */\n\t\tif (ny > s->rlower - s->cy)\n\t\t\tny = s->rlower - s->cy;\n\t}\n\tif (s->cx == screen_size_x(s))\n\t s->cx--;\n\tif (ny == 0)\n\t\treturn;\n\n\ts->cy += ny;\n}\n\n/* Cursor right by nx. */\nvoid\nscreen_write_cursorright(struct screen_write_ctx *ctx, u_int nx)\n{\n\tstruct screen\t*s = ctx->s;\n\n\tif (nx == 0)\n\t\tnx = 1;\n\n\tif (nx > screen_size_x(s) - 1 - s->cx)\n\t\tnx = screen_size_x(s) - 1 - s->cx;\n\tif (nx == 0)\n\t\treturn;\n\n\ts->cx += nx;\n}\n\n/* Cursor left by nx. */\n"} {"commit": "c71844de631186f3df7ff5a6e3aab613da1e4853", "message": "Add resize-pane -Z to temporary zoom the active pane to occupy the full window or unzoom (restored to the normal layout) if it already zoomed, bound to C-b z by default. The pane is unzoomed on pretty much any excuse whatsoever.", "old_file": "cmd-join-pane.c", "new_file": "cmd-join-pane.c", "status": "M", "old_contents": "{\n\treturn (join_pane(self, cmdq, self->entry == &cmd_join_pane_entry));\n}\n\nenum cmd_retval\njoin_pane(struct cmd *self, struct cmd_q *cmdq, int not_same_window)\n{\n\tstruct args\t\t*args = self->args;\n\tstruct session\t\t*dst_s;\n\tstruct winlink\t\t*src_wl, *dst_wl;\n\tstruct window\t\t*src_w, *dst_w;\n\tstruct window_pane\t*src_wp, *dst_wp;\n\tchar\t\t\t*cause;\n\tint\t\t\t size, percentage, dst_idx;\n\tenum layout_type\t type;\n\tstruct layout_cell\t*lc;\n\n\tdst_wl = cmd_find_pane(cmdq, args_get(args, 't'), &dst_s, &dst_wp);\n\tif (dst_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tdst_w = dst_wl->window;\n\tdst_idx = dst_wl->idx;\n\n\tsrc_wl = cmd_find_pane(cmdq, args_get(args, 's'), NULL, &src_wp);\n\tif (src_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tsrc_w = src_wl->window;\n\n\tif (not_same_window && src_w == dst_w) {\n\t\tcmdq_error(cmdq, \"can't join a pane to its own window\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\tif (!not_same_window && src_wp == dst_wp) {\n\t\tcmdq_error(cmdq, \"source and target panes must be different\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\n\ttype = LAYOUT_TOPBOTTOM;\n\tif (args_has(args, 'h'))\n\t\ttype = LAYOUT_LEFTRIGHT;\n\n\tsize = -1;\n\tif (args_has(args, 'l')) {\n\t\tsize = args_strtonum(args, 'l', 0, INT_MAX, &cause);\n\t\tif (cause != NULL) {\n\t\t\tcmdq_error(cmdq, \"size %s\", cause);\n\t\t\tfree(cause);\n\t\t\treturn (CMD_RETURN_ERROR);\n\t\t}\n\t} else if (args_has(args, 'p')) {\n\t\tpercentage = args_strtonum(args, 'p', 0, 100, &cause);", "new_contents": "{\n\treturn (join_pane(self, cmdq, self->entry == &cmd_join_pane_entry));\n}\n\nenum cmd_retval\njoin_pane(struct cmd *self, struct cmd_q *cmdq, int not_same_window)\n{\n\tstruct args\t\t*args = self->args;\n\tstruct session\t\t*dst_s;\n\tstruct winlink\t\t*src_wl, *dst_wl;\n\tstruct window\t\t*src_w, *dst_w;\n\tstruct window_pane\t*src_wp, *dst_wp;\n\tchar\t\t\t*cause;\n\tint\t\t\t size, percentage, dst_idx;\n\tenum layout_type\t type;\n\tstruct layout_cell\t*lc;\n\n\tdst_wl = cmd_find_pane(cmdq, args_get(args, 't'), &dst_s, &dst_wp);\n\tif (dst_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tdst_w = dst_wl->window;\n\tdst_idx = dst_wl->idx;\n\tserver_unzoom_window(dst_w);\n\n\tsrc_wl = cmd_find_pane(cmdq, args_get(args, 's'), NULL, &src_wp);\n\tif (src_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tsrc_w = src_wl->window;\n\tserver_unzoom_window(src_w);\n\n\tif (not_same_window && src_w == dst_w) {\n\t\tcmdq_error(cmdq, \"can't join a pane to its own window\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\tif (!not_same_window && src_wp == dst_wp) {\n\t\tcmdq_error(cmdq, \"source and target panes must be different\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\n\ttype = LAYOUT_TOPBOTTOM;\n\tif (args_has(args, 'h'))\n\t\ttype = LAYOUT_LEFTRIGHT;\n\n\tsize = -1;\n\tif (args_has(args, 'l')) {\n\t\tsize = args_strtonum(args, 'l', 0, INT_MAX, &cause);\n\t\tif (cause != NULL) {\n\t\t\tcmdq_error(cmdq, \"size %s\", cause);\n\t\t\tfree(cause);\n\t\t\treturn (CMD_RETURN_ERROR);\n\t\t}\n\t} else if (args_has(args, 'p')) {\n\t\tpercentage = args_strtonum(args, 'p', 0, 100, &cause);", "current_contents": "{\n\treturn (join_pane(self, cmdq, self->entry == &cmd_join_pane_entry));\n}\n\nenum cmd_retval\njoin_pane(struct cmd *self, struct cmd_q *cmdq, int not_same_window)\n{\n\tstruct args\t\t*args = self->args;\n\tstruct session\t\t*dst_s;\n\tstruct winlink\t\t*src_wl, *dst_wl;\n\tstruct window\t\t*src_w, *dst_w;\n\tstruct window_pane\t*src_wp, *dst_wp;\n\tchar\t\t\t*cause;\n\tint\t\t\t size, percentage, dst_idx;\n\tenum layout_type\t type;\n\tstruct layout_cell\t*lc;\n\n\tdst_wl = cmd_find_pane(cmdq, args_get(args, 't'), &dst_s, &dst_wp);\n\tif (dst_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tdst_w = dst_wl->window;\n\tdst_idx = dst_wl->idx;\n\tserver_unzoom_window(dst_w);\n\n\tsrc_wl = cmd_find_pane(cmdq, args_get(args, 's'), NULL, &src_wp);\n\tif (src_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tsrc_w = src_wl->window;\n\n\tif (not_same_window && src_w == dst_w) {\n\t\tcmdq_error(cmdq, \"can't join a pane to its own window\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\tif (!not_same_window && src_wp == dst_wp) {\n\t\tcmdq_error(cmdq, \"source and target panes must be different\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\n\ttype = LAYOUT_TOPBOTTOM;\n\tif (args_has(args, 'h'))\n\t\ttype = LAYOUT_LEFTRIGHT;\n\n\tsize = -1;\n\tif (args_has(args, 'l')) {\n\t\tsize = args_strtonum(args, 'l', 0, INT_MAX, &cause);\n\t\tif (cause != NULL) {\n\t\t\tcmdq_error(cmdq, \"size %s\", cause);\n\t\t\tfree(cause);\n\t\t\treturn (CMD_RETURN_ERROR);\n\t\t}\n\t} else if (args_has(args, 'p')) {\n\t\tpercentage = args_strtonum(args, 'p', 0, 100, &cause);", "text": "<|original_code|>\n{\n\treturn (join_pane(self, cmdq, self->entry == &cmd_join_pane_entry));\n}\n\nenum cmd_retval\njoin_pane(struct cmd *self, struct cmd_q *cmdq, int not_same_window)\n{\n\tstruct args\t\t*args = self->args;\n\tstruct session\t\t*dst_s;\n\tstruct winlink\t\t*src_wl, *dst_wl;\n\tstruct window\t\t*src_w, *dst_w;\n\tstruct window_pane\t*src_wp, *dst_wp;\n\tchar\t\t\t*cause;\n\tint\t\t\t size, percentage, dst_idx;\n\tenum layout_type\t type;\n\tstruct layout_cell\t*lc;\n\n\tdst_wl = cmd_find_pane(cmdq, args_get(args, 't'), &dst_s, &dst_wp);\n\tif (dst_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tdst_w = dst_wl->window;\n\tdst_idx = dst_wl->idx;\n\n\tsrc_wl = cmd_find_pane(cmdq, args_get(args, 's'), NULL, &src_wp);\n\tif (src_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tsrc_w = src_wl->window;\n\n\tif (not_same_window && src_w == dst_w) {\n\t\tcmdq_error(cmdq, \"can't join a pane to its own window\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\tif (!not_same_window && src_wp == dst_wp) {\n\t\tcmdq_error(cmdq, \"source and target panes must be different\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\n\ttype = LAYOUT_TOPBOTTOM;\n\tif (args_has(args, 'h'))\n\t\ttype = LAYOUT_LEFTRIGHT;\n\n\tsize = -1;\n\tif (args_has(args, 'l')) {\n\t\tsize = args_strtonum(args, 'l', 0, INT_MAX, &cause);\n\t\tif (cause != NULL) {\n\t\t\tcmdq_error(cmdq, \"size %s\", cause);\n\t\t\tfree(cause);\n\t\t\treturn (CMD_RETURN_ERROR);\n\t\t}\n\t} else if (args_has(args, 'p')) {\n\t\tpercentage = args_strtonum(args, 'p', 0, 100, &cause);\n<|edits_diff|>\n--- cmd-join-pane.c\n+++ cmd-join-pane.c\n@@ -20,6 +20,7 @@\n \t\treturn (CMD_RETURN_ERROR);\n \tdst_w = dst_wl->window;\n \tdst_idx = dst_wl->idx;\n+\tserver_unzoom_window(dst_w);\n \n \tsrc_wl = cmd_find_pane(cmdq, args_get(args, 's'), NULL, &src_wp);\n \tif (src_wl == NULL)\n<|current_version|>\n{\n\treturn (join_pane(self, cmdq, self->entry == &cmd_join_pane_entry));\n}\n\nenum cmd_retval\njoin_pane(struct cmd *self, struct cmd_q *cmdq, int not_same_window)\n{\n\tstruct args\t\t*args = self->args;\n\tstruct session\t\t*dst_s;\n\tstruct winlink\t\t*src_wl, *dst_wl;\n\tstruct window\t\t*src_w, *dst_w;\n\tstruct window_pane\t*src_wp, *dst_wp;\n\tchar\t\t\t*cause;\n\tint\t\t\t size, percentage, dst_idx;\n\tenum layout_type\t type;\n\tstruct layout_cell\t*lc;\n\n\tdst_wl = cmd_find_pane(cmdq, args_get(args, 't'), &dst_s, &dst_wp);\n\tif (dst_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tdst_w = dst_wl->window;\n\tdst_idx = dst_wl->idx;\n\tserver_unzoom_window(dst_w);\n\n\tsrc_wl = cmd_find_pane(cmdq, args_get(args, 's'), NULL, &src_wp);\n\tif (src_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tsrc_w = src_wl->window;\n\n\tif (not_same_window && src_w == dst_w) {\n\t\tcmdq_error(cmdq, \"can't join a pane to its own window\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\tif (!not_same_window && src_wp == dst_wp) {\n\t\tcmdq_error(cmdq, \"source and target panes must be different\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\n\ttype = LAYOUT_TOPBOTTOM;\n\tif (args_has(args, 'h'))\n\t\ttype = LAYOUT_LEFTRIGHT;\n\n\tsize = -1;\n\tif (args_has(args, 'l')) {\n\t\tsize = args_strtonum(args, 'l', 0, INT_MAX, &cause);\n\t\tif (cause != NULL) {\n\t\t\tcmdq_error(cmdq, \"size %s\", cause);\n\t\t\tfree(cause);\n\t\t\treturn (CMD_RETURN_ERROR);\n\t\t}\n\t} else if (args_has(args, 'p')) {\n\t\tpercentage = args_strtonum(args, 'p', 0, 100, &cause);\n<|next_version|>\n{\n\treturn (join_pane(self, cmdq, self->entry == &cmd_join_pane_entry));\n}\n\nenum cmd_retval\njoin_pane(struct cmd *self, struct cmd_q *cmdq, int not_same_window)\n{\n\tstruct args\t\t*args = self->args;\n\tstruct session\t\t*dst_s;\n\tstruct winlink\t\t*src_wl, *dst_wl;\n\tstruct window\t\t*src_w, *dst_w;\n\tstruct window_pane\t*src_wp, *dst_wp;\n\tchar\t\t\t*cause;\n\tint\t\t\t size, percentage, dst_idx;\n\tenum layout_type\t type;\n\tstruct layout_cell\t*lc;\n\n\tdst_wl = cmd_find_pane(cmdq, args_get(args, 't'), &dst_s, &dst_wp);\n\tif (dst_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tdst_w = dst_wl->window;\n\tdst_idx = dst_wl->idx;\n\tserver_unzoom_window(dst_w);\n\n\tsrc_wl = cmd_find_pane(cmdq, args_get(args, 's'), NULL, &src_wp);\n\tif (src_wl == NULL)\n\t\treturn (CMD_RETURN_ERROR);\n\tsrc_w = src_wl->window;\n\tserver_unzoom_window(src_w);\n\n\tif (not_same_window && src_w == dst_w) {\n\t\tcmdq_error(cmdq, \"can't join a pane to its own window\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\tif (!not_same_window && src_wp == dst_wp) {\n\t\tcmdq_error(cmdq, \"source and target panes must be different\");\n\t\treturn (CMD_RETURN_ERROR);\n\t}\n\n\ttype = LAYOUT_TOPBOTTOM;\n\tif (args_has(args, 'h'))\n\t\ttype = LAYOUT_LEFTRIGHT;\n\n\tsize = -1;\n\tif (args_has(args, 'l')) {\n\t\tsize = args_strtonum(args, 'l', 0, INT_MAX, &cause);\n\t\tif (cause != NULL) {\n\t\t\tcmdq_error(cmdq, \"size %s\", cause);\n\t\t\tfree(cause);\n\t\t\treturn (CMD_RETURN_ERROR);\n\t\t}\n\t} else if (args_has(args, 'p')) {\n\t\tpercentage = args_strtonum(args, 'p', 0, 100, &cause);\n"} {"commit": "f41efd9d89f6596a4dc0600fd23ba56d69d1c47c", "message": "Sync OpenBSD patchset 1069:", "old_file": "cmd-attach-session.c", "new_file": "cmd-attach-session.c", "status": "M", "old_contents": "\t\treturn (-1);\n\n\tif (ctx->cmdclient == NULL && ctx->curclient == NULL)\n\t\treturn (0);\n\n\tif (ctx->cmdclient == NULL) {\n\t\tif (args_has(self->args, 'd')) {\n\t\t\t/*\n\t\t\t * Can't use server_write_session in case attaching to\n\t\t\t * the same session as currently attached to.\n\t\t\t */\n\t\t\tfor (i = 0; i < ARRAY_LENGTH(&clients); i++) {\n\t\t\t\tc = ARRAY_ITEM(&clients, i);\n\t\t\t\tif (c == NULL || c->session != s)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (c == ctx->curclient)\n\t\t\t\t\tcontinue;\n\t\t\t\tserver_write_client(c, MSG_DETACH, NULL, 0);\n\t\t\t}\n\t\t}\n\n\t\tctx->curclient->session = s;\n\t\tsession_update_activity(s);\n\t\tserver_redraw_client(ctx->curclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t} else {\n\t\tif (!(ctx->cmdclient->flags & CLIENT_TERMINAL)) {\n\t\t\tctx->error(ctx, \"not a terminal\");\n\t\t\treturn (-1);\n\t\t}\n\n\t\toverrides =\n\t\t options_get_string(&s->options, \"terminal-overrides\");\n\t\tif (tty_open(&ctx->cmdclient->tty, overrides, &cause) != 0) {\n\t\t\tctx->error(ctx, \"terminal open failed: %s\", cause);\n\t\t\txfree(cause);\n\t\t\treturn (-1);\n\t\t}\n\n\t\tif (args_has(self->args, 'r'))\n\t\t\tctx->cmdclient->flags |= CLIENT_READONLY;\n\n\t\tif (args_has(self->args, 'd'))\n\t\t\tserver_write_session(s, MSG_DETACH, NULL, 0);\n\n\t\tctx->cmdclient->session = s;\n\t\tsession_update_activity(s);\n\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\n\t\tupdate = options_get_string(&s->options, \"update-environment\");\n\t\tenviron_update(update, &ctx->cmdclient->environ, &s->environ);\n\n\t\tserver_redraw_client(ctx->cmdclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\treturn (1);\t/* 1 means don't tell command client to exit */\n}\n", "new_contents": "\t\treturn (-1);\n\n\tif (ctx->cmdclient == NULL && ctx->curclient == NULL)\n\t\treturn (0);\n\n\tif (ctx->cmdclient == NULL) {\n\t\tif (args_has(self->args, 'd')) {\n\t\t\t/*\n\t\t\t * Can't use server_write_session in case attaching to\n\t\t\t * the same session as currently attached to.\n\t\t\t */\n\t\t\tfor (i = 0; i < ARRAY_LENGTH(&clients); i++) {\n\t\t\t\tc = ARRAY_ITEM(&clients, i);\n\t\t\t\tif (c == NULL || c->session != s)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (c == ctx->curclient)\n\t\t\t\t\tcontinue;\n\t\t\t\tserver_write_client(c, MSG_DETACH, NULL, 0);\n\t\t\t}\n\t\t}\n\n\t\tctx->curclient->session = s;\n\t\tnotify_attached_session_changed(ctx->curclient);\n\t\tsession_update_activity(s);\n\t\tserver_redraw_client(ctx->curclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t} else {\n\t\tif (!(ctx->cmdclient->flags & CLIENT_TERMINAL)) {\n\t\t\tctx->error(ctx, \"not a terminal\");\n\t\t\treturn (-1);\n\t\t}\n\n\t\toverrides =\n\t\t options_get_string(&s->options, \"terminal-overrides\");\n\t\tif (tty_open(&ctx->cmdclient->tty, overrides, &cause) != 0) {\n\t\t\tctx->error(ctx, \"terminal open failed: %s\", cause);\n\t\t\txfree(cause);\n\t\t\treturn (-1);\n\t\t}\n\n\t\tif (args_has(self->args, 'r'))\n\t\t\tctx->cmdclient->flags |= CLIENT_READONLY;\n\n\t\tif (args_has(self->args, 'd'))\n\t\t\tserver_write_session(s, MSG_DETACH, NULL, 0);\n\n\t\tctx->cmdclient->session = s;\n\t\tnotify_attached_session_changed(ctx->cmdclient);\n\t\tsession_update_activity(s);\n\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\n\t\tupdate = options_get_string(&s->options, \"update-environment\");\n\t\tenviron_update(update, &ctx->cmdclient->environ, &s->environ);\n\n\t\tserver_redraw_client(ctx->cmdclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\treturn (1);\t/* 1 means don't tell command client to exit */\n}\n", "current_contents": "\t\treturn (-1);\n\n\tif (ctx->cmdclient == NULL && ctx->curclient == NULL)\n\t\treturn (0);\n\n\tif (ctx->cmdclient == NULL) {\n\t\tif (args_has(self->args, 'd')) {\n\t\t\t/*\n\t\t\t * Can't use server_write_session in case attaching to\n\t\t\t * the same session as currently attached to.\n\t\t\t */\n\t\t\tfor (i = 0; i < ARRAY_LENGTH(&clients); i++) {\n\t\t\t\tc = ARRAY_ITEM(&clients, i);\n\t\t\t\tif (c == NULL || c->session != s)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (c == ctx->curclient)\n\t\t\t\t\tcontinue;\n\t\t\t\tserver_write_client(c, MSG_DETACH, NULL, 0);\n\t\t\t}\n\t\t}\n\n\t\tctx->curclient->session = s;\n\t\tnotify_attached_session_changed(ctx->curclient);\n\t\tsession_update_activity(s);\n\t\tserver_redraw_client(ctx->curclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t} else {\n\t\tif (!(ctx->cmdclient->flags & CLIENT_TERMINAL)) {\n\t\t\tctx->error(ctx, \"not a terminal\");\n\t\t\treturn (-1);\n\t\t}\n\n\t\toverrides =\n\t\t options_get_string(&s->options, \"terminal-overrides\");\n\t\tif (tty_open(&ctx->cmdclient->tty, overrides, &cause) != 0) {\n\t\t\tctx->error(ctx, \"terminal open failed: %s\", cause);\n\t\t\txfree(cause);\n\t\t\treturn (-1);\n\t\t}\n\n\t\tif (args_has(self->args, 'r'))\n\t\t\tctx->cmdclient->flags |= CLIENT_READONLY;\n\n\t\tif (args_has(self->args, 'd'))\n\t\t\tserver_write_session(s, MSG_DETACH, NULL, 0);\n\n\t\tctx->cmdclient->session = s;\n\t\tsession_update_activity(s);\n\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\n\t\tupdate = options_get_string(&s->options, \"update-environment\");\n\t\tenviron_update(update, &ctx->cmdclient->environ, &s->environ);\n\n\t\tserver_redraw_client(ctx->cmdclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\treturn (1);\t/* 1 means don't tell command client to exit */\n}\n", "text": "<|original_code|>\n\t\treturn (-1);\n\n\tif (ctx->cmdclient == NULL && ctx->curclient == NULL)\n\t\treturn (0);\n\n\tif (ctx->cmdclient == NULL) {\n\t\tif (args_has(self->args, 'd')) {\n\t\t\t/*\n\t\t\t * Can't use server_write_session in case attaching to\n\t\t\t * the same session as currently attached to.\n\t\t\t */\n\t\t\tfor (i = 0; i < ARRAY_LENGTH(&clients); i++) {\n\t\t\t\tc = ARRAY_ITEM(&clients, i);\n\t\t\t\tif (c == NULL || c->session != s)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (c == ctx->curclient)\n\t\t\t\t\tcontinue;\n\t\t\t\tserver_write_client(c, MSG_DETACH, NULL, 0);\n\t\t\t}\n\t\t}\n\n\t\tctx->curclient->session = s;\n\t\tsession_update_activity(s);\n\t\tserver_redraw_client(ctx->curclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t} else {\n\t\tif (!(ctx->cmdclient->flags & CLIENT_TERMINAL)) {\n\t\t\tctx->error(ctx, \"not a terminal\");\n\t\t\treturn (-1);\n\t\t}\n\n\t\toverrides =\n\t\t options_get_string(&s->options, \"terminal-overrides\");\n\t\tif (tty_open(&ctx->cmdclient->tty, overrides, &cause) != 0) {\n\t\t\tctx->error(ctx, \"terminal open failed: %s\", cause);\n\t\t\txfree(cause);\n\t\t\treturn (-1);\n\t\t}\n\n\t\tif (args_has(self->args, 'r'))\n\t\t\tctx->cmdclient->flags |= CLIENT_READONLY;\n\n\t\tif (args_has(self->args, 'd'))\n\t\t\tserver_write_session(s, MSG_DETACH, NULL, 0);\n\n\t\tctx->cmdclient->session = s;\n\t\tsession_update_activity(s);\n\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\n\t\tupdate = options_get_string(&s->options, \"update-environment\");\n\t\tenviron_update(update, &ctx->cmdclient->environ, &s->environ);\n\n\t\tserver_redraw_client(ctx->cmdclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\treturn (1);\t/* 1 means don't tell command client to exit */\n}\n\n<|edits_diff|>\n--- cmd-attach-session.c\n+++ cmd-attach-session.c\n@@ -20,6 +20,7 @@\n \t\t}\n \n \t\tctx->curclient->session = s;\n+\t\tnotify_attached_session_changed(ctx->curclient);\n \t\tsession_update_activity(s);\n \t\tserver_redraw_client(ctx->curclient);\n \t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n<|current_version|>\n\t\treturn (-1);\n\n\tif (ctx->cmdclient == NULL && ctx->curclient == NULL)\n\t\treturn (0);\n\n\tif (ctx->cmdclient == NULL) {\n\t\tif (args_has(self->args, 'd')) {\n\t\t\t/*\n\t\t\t * Can't use server_write_session in case attaching to\n\t\t\t * the same session as currently attached to.\n\t\t\t */\n\t\t\tfor (i = 0; i < ARRAY_LENGTH(&clients); i++) {\n\t\t\t\tc = ARRAY_ITEM(&clients, i);\n\t\t\t\tif (c == NULL || c->session != s)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (c == ctx->curclient)\n\t\t\t\t\tcontinue;\n\t\t\t\tserver_write_client(c, MSG_DETACH, NULL, 0);\n\t\t\t}\n\t\t}\n\n\t\tctx->curclient->session = s;\n\t\tnotify_attached_session_changed(ctx->curclient);\n\t\tsession_update_activity(s);\n\t\tserver_redraw_client(ctx->curclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t} else {\n\t\tif (!(ctx->cmdclient->flags & CLIENT_TERMINAL)) {\n\t\t\tctx->error(ctx, \"not a terminal\");\n\t\t\treturn (-1);\n\t\t}\n\n\t\toverrides =\n\t\t options_get_string(&s->options, \"terminal-overrides\");\n\t\tif (tty_open(&ctx->cmdclient->tty, overrides, &cause) != 0) {\n\t\t\tctx->error(ctx, \"terminal open failed: %s\", cause);\n\t\t\txfree(cause);\n\t\t\treturn (-1);\n\t\t}\n\n\t\tif (args_has(self->args, 'r'))\n\t\t\tctx->cmdclient->flags |= CLIENT_READONLY;\n\n\t\tif (args_has(self->args, 'd'))\n\t\t\tserver_write_session(s, MSG_DETACH, NULL, 0);\n\n\t\tctx->cmdclient->session = s;\n\t\tsession_update_activity(s);\n\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\n\t\tupdate = options_get_string(&s->options, \"update-environment\");\n\t\tenviron_update(update, &ctx->cmdclient->environ, &s->environ);\n\n\t\tserver_redraw_client(ctx->cmdclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\treturn (1);\t/* 1 means don't tell command client to exit */\n}\n\n<|next_version|>\n\t\treturn (-1);\n\n\tif (ctx->cmdclient == NULL && ctx->curclient == NULL)\n\t\treturn (0);\n\n\tif (ctx->cmdclient == NULL) {\n\t\tif (args_has(self->args, 'd')) {\n\t\t\t/*\n\t\t\t * Can't use server_write_session in case attaching to\n\t\t\t * the same session as currently attached to.\n\t\t\t */\n\t\t\tfor (i = 0; i < ARRAY_LENGTH(&clients); i++) {\n\t\t\t\tc = ARRAY_ITEM(&clients, i);\n\t\t\t\tif (c == NULL || c->session != s)\n\t\t\t\t\tcontinue;\n\t\t\t\tif (c == ctx->curclient)\n\t\t\t\t\tcontinue;\n\t\t\t\tserver_write_client(c, MSG_DETACH, NULL, 0);\n\t\t\t}\n\t\t}\n\n\t\tctx->curclient->session = s;\n\t\tnotify_attached_session_changed(ctx->curclient);\n\t\tsession_update_activity(s);\n\t\tserver_redraw_client(ctx->curclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t} else {\n\t\tif (!(ctx->cmdclient->flags & CLIENT_TERMINAL)) {\n\t\t\tctx->error(ctx, \"not a terminal\");\n\t\t\treturn (-1);\n\t\t}\n\n\t\toverrides =\n\t\t options_get_string(&s->options, \"terminal-overrides\");\n\t\tif (tty_open(&ctx->cmdclient->tty, overrides, &cause) != 0) {\n\t\t\tctx->error(ctx, \"terminal open failed: %s\", cause);\n\t\t\txfree(cause);\n\t\t\treturn (-1);\n\t\t}\n\n\t\tif (args_has(self->args, 'r'))\n\t\t\tctx->cmdclient->flags |= CLIENT_READONLY;\n\n\t\tif (args_has(self->args, 'd'))\n\t\t\tserver_write_session(s, MSG_DETACH, NULL, 0);\n\n\t\tctx->cmdclient->session = s;\n\t\tnotify_attached_session_changed(ctx->cmdclient);\n\t\tsession_update_activity(s);\n\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\n\t\tupdate = options_get_string(&s->options, \"update-environment\");\n\t\tenviron_update(update, &ctx->cmdclient->environ, &s->environ);\n\n\t\tserver_redraw_client(ctx->cmdclient);\n\t\ts->curw->flags &= ~WINLINK_ALERTFLAGS;\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\treturn (1);\t/* 1 means don't tell command client to exit */\n}\n\n"} {"commit": "e87d4b43abdba32698ed44590f7fd84cf6891c8d", "message": "Need to call recalculate_sizes() when changing window with the mouse, from marcel partap.", "old_file": "server-client.c", "new_file": "server-client.c", "status": "M", "old_contents": "\t\t\tstatus_update_jobs(c);\n\t\t\tc->flags |= CLIENT_STATUS;\n\t\t}\n\t}\n}\n\n/* Check for mouse keys. */\nvoid\nserver_client_check_mouse(\n struct client *c, struct window_pane *wp, struct mouse_event *mouse)\n{\n\tstruct session\t*s = c->session;\n\tstruct options\t*oo = &s->options;\n\tint\t\t statusat;\n\n\tstatusat = status_at_line(c);\n\n\t/* Is this a window selection click on the status line? */\n\tif (statusat != -1 && mouse->y == (u_int)statusat &&\n\t options_get_number(oo, \"mouse-select-window\")) {\n\t\tif (mouse->b == MOUSE_UP && c->last_mouse.b != MOUSE_UP) {\n\t\t\tstatus_set_window_at(c, mouse->x);\n\t\t\treturn;\n\t\t}\n\t\tif (mouse->b & MOUSE_45) {\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_1) {\n\t\t\t\tsession_previous(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t}\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_2) {\n\t\t\t\tsession_next(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tmemcpy(&c->last_mouse, mouse, sizeof c->last_mouse);\n\t\treturn;\n\t}\n\n\t/*\n\t * Not on status line - adjust mouse position if status line is at the\n\t * top and limit if at the bottom. From here on a struct mouse\n\t * represents the offset onto the window itself.\n\t */\n\tif (statusat == 0 &&mouse->y > 0)\n\t\tmouse->y--;\n\telse if (statusat > 0 && mouse->y >= (u_int)statusat)\n\t\tmouse->y = statusat - 1;\n\n\t/* Is this a pane selection? Allow down only in copy mode. */\n\tif (options_get_number(oo, \"mouse-select-pane\") &&\n\t ((!(mouse->b & MOUSE_DRAG) && mouse->b != MOUSE_UP) ||\n\t wp->mode != &window_copy_mode)) {\n\t\twindow_set_active_at(wp->window, mouse->x, mouse->y);\n\t\tserver_redraw_window_borders(wp->window);\n\t\twp = wp->window->active; /* may have changed */", "new_contents": "\t\t\tstatus_update_jobs(c);\n\t\t\tc->flags |= CLIENT_STATUS;\n\t\t}\n\t}\n}\n\n/* Check for mouse keys. */\nvoid\nserver_client_check_mouse(\n struct client *c, struct window_pane *wp, struct mouse_event *mouse)\n{\n\tstruct session\t*s = c->session;\n\tstruct options\t*oo = &s->options;\n\tint\t\t statusat;\n\n\tstatusat = status_at_line(c);\n\n\t/* Is this a window selection click on the status line? */\n\tif (statusat != -1 && mouse->y == (u_int)statusat &&\n\t options_get_number(oo, \"mouse-select-window\")) {\n\t\tif (mouse->b == MOUSE_UP && c->last_mouse.b != MOUSE_UP) {\n\t\t\tstatus_set_window_at(c, mouse->x);\n\t\t\trecalculate_sizes();\n\t\t\treturn;\n\t\t}\n\t\tif (mouse->b & MOUSE_45) {\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_1) {\n\t\t\t\tsession_previous(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t\trecalculate_sizes();\n\t\t\t}\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_2) {\n\t\t\t\tsession_next(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t\trecalculate_sizes();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tmemcpy(&c->last_mouse, mouse, sizeof c->last_mouse);\n\t\treturn;\n\t}\n\n\t/*\n\t * Not on status line - adjust mouse position if status line is at the\n\t * top and limit if at the bottom. From here on a struct mouse\n\t * represents the offset onto the window itself.\n\t */\n\tif (statusat == 0 &&mouse->y > 0)\n\t\tmouse->y--;\n\telse if (statusat > 0 && mouse->y >= (u_int)statusat)\n\t\tmouse->y = statusat - 1;\n\n\t/* Is this a pane selection? Allow down only in copy mode. */\n\tif (options_get_number(oo, \"mouse-select-pane\") &&\n\t ((!(mouse->b & MOUSE_DRAG) && mouse->b != MOUSE_UP) ||\n\t wp->mode != &window_copy_mode)) {\n\t\twindow_set_active_at(wp->window, mouse->x, mouse->y);\n\t\tserver_redraw_window_borders(wp->window);\n\t\twp = wp->window->active; /* may have changed */", "current_contents": "\t\t\tstatus_update_jobs(c);\n\t\t\tc->flags |= CLIENT_STATUS;\n\t\t}\n\t}\n}\n\n/* Check for mouse keys. */\nvoid\nserver_client_check_mouse(\n struct client *c, struct window_pane *wp, struct mouse_event *mouse)\n{\n\tstruct session\t*s = c->session;\n\tstruct options\t*oo = &s->options;\n\tint\t\t statusat;\n\n\tstatusat = status_at_line(c);\n\n\t/* Is this a window selection click on the status line? */\n\tif (statusat != -1 && mouse->y == (u_int)statusat &&\n\t options_get_number(oo, \"mouse-select-window\")) {\n\t\tif (mouse->b == MOUSE_UP && c->last_mouse.b != MOUSE_UP) {\n\t\t\tstatus_set_window_at(c, mouse->x);\n\t\t\trecalculate_sizes();\n\t\t\treturn;\n\t\t}\n\t\tif (mouse->b & MOUSE_45) {\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_1) {\n\t\t\t\tsession_previous(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t\trecalculate_sizes();\n\t\t\t}\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_2) {\n\t\t\t\tsession_next(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tmemcpy(&c->last_mouse, mouse, sizeof c->last_mouse);\n\t\treturn;\n\t}\n\n\t/*\n\t * Not on status line - adjust mouse position if status line is at the\n\t * top and limit if at the bottom. From here on a struct mouse\n\t * represents the offset onto the window itself.\n\t */\n\tif (statusat == 0 &&mouse->y > 0)\n\t\tmouse->y--;\n\telse if (statusat > 0 && mouse->y >= (u_int)statusat)\n\t\tmouse->y = statusat - 1;\n\n\t/* Is this a pane selection? Allow down only in copy mode. */\n\tif (options_get_number(oo, \"mouse-select-pane\") &&\n\t ((!(mouse->b & MOUSE_DRAG) && mouse->b != MOUSE_UP) ||\n\t wp->mode != &window_copy_mode)) {\n\t\twindow_set_active_at(wp->window, mouse->x, mouse->y);\n\t\tserver_redraw_window_borders(wp->window);\n\t\twp = wp->window->active; /* may have changed */", "text": "<|original_code|>\n\t\t\tstatus_update_jobs(c);\n\t\t\tc->flags |= CLIENT_STATUS;\n\t\t}\n\t}\n}\n\n/* Check for mouse keys. */\nvoid\nserver_client_check_mouse(\n struct client *c, struct window_pane *wp, struct mouse_event *mouse)\n{\n\tstruct session\t*s = c->session;\n\tstruct options\t*oo = &s->options;\n\tint\t\t statusat;\n\n\tstatusat = status_at_line(c);\n\n\t/* Is this a window selection click on the status line? */\n\tif (statusat != -1 && mouse->y == (u_int)statusat &&\n\t options_get_number(oo, \"mouse-select-window\")) {\n\t\tif (mouse->b == MOUSE_UP && c->last_mouse.b != MOUSE_UP) {\n\t\t\tstatus_set_window_at(c, mouse->x);\n\t\t\treturn;\n\t\t}\n\t\tif (mouse->b & MOUSE_45) {\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_1) {\n\t\t\t\tsession_previous(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t}\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_2) {\n\t\t\t\tsession_next(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tmemcpy(&c->last_mouse, mouse, sizeof c->last_mouse);\n\t\treturn;\n\t}\n\n\t/*\n\t * Not on status line - adjust mouse position if status line is at the\n\t * top and limit if at the bottom. From here on a struct mouse\n\t * represents the offset onto the window itself.\n\t */\n\tif (statusat == 0 &&mouse->y > 0)\n\t\tmouse->y--;\n\telse if (statusat > 0 && mouse->y >= (u_int)statusat)\n\t\tmouse->y = statusat - 1;\n\n\t/* Is this a pane selection? Allow down only in copy mode. */\n\tif (options_get_number(oo, \"mouse-select-pane\") &&\n\t ((!(mouse->b & MOUSE_DRAG) && mouse->b != MOUSE_UP) ||\n\t wp->mode != &window_copy_mode)) {\n\t\twindow_set_active_at(wp->window, mouse->x, mouse->y);\n\t\tserver_redraw_window_borders(wp->window);\n\t\twp = wp->window->active; /* may have changed */\n<|edits_diff|>\n--- server-client.c\n+++ server-client.c\n@@ -20,12 +20,14 @@\n \t options_get_number(oo, \"mouse-select-window\")) {\n \t\tif (mouse->b == MOUSE_UP && c->last_mouse.b != MOUSE_UP) {\n \t\t\tstatus_set_window_at(c, mouse->x);\n+\t\t\trecalculate_sizes();\n \t\t\treturn;\n \t\t}\n \t\tif (mouse->b & MOUSE_45) {\n \t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_1) {\n \t\t\t\tsession_previous(c->session, 0);\n \t\t\t\tserver_redraw_session(s);\n+\t\t\t\trecalculate_sizes();\n \t\t\t}\n \t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_2) {\n \t\t\t\tsession_next(c->session, 0);\n<|current_version|>\n\t\t\tstatus_update_jobs(c);\n\t\t\tc->flags |= CLIENT_STATUS;\n\t\t}\n\t}\n}\n\n/* Check for mouse keys. */\nvoid\nserver_client_check_mouse(\n struct client *c, struct window_pane *wp, struct mouse_event *mouse)\n{\n\tstruct session\t*s = c->session;\n\tstruct options\t*oo = &s->options;\n\tint\t\t statusat;\n\n\tstatusat = status_at_line(c);\n\n\t/* Is this a window selection click on the status line? */\n\tif (statusat != -1 && mouse->y == (u_int)statusat &&\n\t options_get_number(oo, \"mouse-select-window\")) {\n\t\tif (mouse->b == MOUSE_UP && c->last_mouse.b != MOUSE_UP) {\n\t\t\tstatus_set_window_at(c, mouse->x);\n\t\t\trecalculate_sizes();\n\t\t\treturn;\n\t\t}\n\t\tif (mouse->b & MOUSE_45) {\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_1) {\n\t\t\t\tsession_previous(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t\trecalculate_sizes();\n\t\t\t}\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_2) {\n\t\t\t\tsession_next(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tmemcpy(&c->last_mouse, mouse, sizeof c->last_mouse);\n\t\treturn;\n\t}\n\n\t/*\n\t * Not on status line - adjust mouse position if status line is at the\n\t * top and limit if at the bottom. From here on a struct mouse\n\t * represents the offset onto the window itself.\n\t */\n\tif (statusat == 0 &&mouse->y > 0)\n\t\tmouse->y--;\n\telse if (statusat > 0 && mouse->y >= (u_int)statusat)\n\t\tmouse->y = statusat - 1;\n\n\t/* Is this a pane selection? Allow down only in copy mode. */\n\tif (options_get_number(oo, \"mouse-select-pane\") &&\n\t ((!(mouse->b & MOUSE_DRAG) && mouse->b != MOUSE_UP) ||\n\t wp->mode != &window_copy_mode)) {\n\t\twindow_set_active_at(wp->window, mouse->x, mouse->y);\n\t\tserver_redraw_window_borders(wp->window);\n\t\twp = wp->window->active; /* may have changed */\n<|next_version|>\n\t\t\tstatus_update_jobs(c);\n\t\t\tc->flags |= CLIENT_STATUS;\n\t\t}\n\t}\n}\n\n/* Check for mouse keys. */\nvoid\nserver_client_check_mouse(\n struct client *c, struct window_pane *wp, struct mouse_event *mouse)\n{\n\tstruct session\t*s = c->session;\n\tstruct options\t*oo = &s->options;\n\tint\t\t statusat;\n\n\tstatusat = status_at_line(c);\n\n\t/* Is this a window selection click on the status line? */\n\tif (statusat != -1 && mouse->y == (u_int)statusat &&\n\t options_get_number(oo, \"mouse-select-window\")) {\n\t\tif (mouse->b == MOUSE_UP && c->last_mouse.b != MOUSE_UP) {\n\t\t\tstatus_set_window_at(c, mouse->x);\n\t\t\trecalculate_sizes();\n\t\t\treturn;\n\t\t}\n\t\tif (mouse->b & MOUSE_45) {\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_1) {\n\t\t\t\tsession_previous(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t\trecalculate_sizes();\n\t\t\t}\n\t\t\tif ((mouse->b & MOUSE_BUTTON) == MOUSE_2) {\n\t\t\t\tsession_next(c->session, 0);\n\t\t\t\tserver_redraw_session(s);\n\t\t\t\trecalculate_sizes();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tmemcpy(&c->last_mouse, mouse, sizeof c->last_mouse);\n\t\treturn;\n\t}\n\n\t/*\n\t * Not on status line - adjust mouse position if status line is at the\n\t * top and limit if at the bottom. From here on a struct mouse\n\t * represents the offset onto the window itself.\n\t */\n\tif (statusat == 0 &&mouse->y > 0)\n\t\tmouse->y--;\n\telse if (statusat > 0 && mouse->y >= (u_int)statusat)\n\t\tmouse->y = statusat - 1;\n\n\t/* Is this a pane selection? Allow down only in copy mode. */\n\tif (options_get_number(oo, \"mouse-select-pane\") &&\n\t ((!(mouse->b & MOUSE_DRAG) && mouse->b != MOUSE_UP) ||\n\t wp->mode != &window_copy_mode)) {\n\t\twindow_set_active_at(wp->window, mouse->x, mouse->y);\n\t\tserver_redraw_window_borders(wp->window);\n\t\twp = wp->window->active; /* may have changed */\n"} {"commit": "51487ed22f0acf199f64728f3efc15a3c9ad615f", "message": "Track the last session for a client and add a flag to switch-client and a key binding (L) to move a client back to its last session.", "old_file": "cmd-new-session.c", "new_file": "cmd-new-session.c", "status": "M", "old_contents": "\t\tw->name = xstrdup(data->winname);\n\n\t\toptions_set_number(&w->options, \"automatic-rename\", 0);\n\t}\n\n\t/*\n\t * If a target session is given, this is to be part of a session group,\n\t * so add it to the group and synchronize.\n\t */\n\tif (groupwith != NULL) {\n\t\tsession_group_add(groupwith, s);\n\t\tsession_group_synchronize_to(s);\n\t\tsession_select(s, RB_ROOT(&s->windows)->idx);\n\t}\n\n\t/*\n\t * Set the client to the new session. If a command client exists, it is\n\t * taking this session and needs to get MSG_READY and stay around.\n\t */\n\tif (!detached) {\n\t\tif (ctx->cmdclient != NULL) {\n\t\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\t\t\tctx->cmdclient->session = s;\n\t\t\tserver_redraw_client(ctx->cmdclient);\n\t\t} else {\n\t\t\tctx->curclient->session = s;\n\t\t\tserver_redraw_client(ctx->curclient);\n\t\t}\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\t/*\n\t * If there are still configuration file errors to display, put the new\n\t * session's current window into more mode and display them now.\n\t */\n\tif (cfg_finished && !ARRAY_EMPTY(&cfg_causes)) {\n\t\twp = s->curw->window->active;\n\t\twindow_pane_set_mode(wp, &window_copy_mode);\n\t\twindow_copy_init_for_output(wp);\n\t\tfor (i = 0; i < ARRAY_LENGTH(&cfg_causes); i++) {\n\t\t\tcause = ARRAY_ITEM(&cfg_causes, i);\n\t\t\twindow_copy_add(wp, \"%s\", cause);\n\t\t\txfree(cause);\n\t\t}\n\t\tARRAY_FREE(&cfg_causes);\n\t}\n\n\treturn (!detached);\t/* 1 means don't tell command client to exit */", "new_contents": "\t\tw->name = xstrdup(data->winname);\n\n\t\toptions_set_number(&w->options, \"automatic-rename\", 0);\n\t}\n\n\t/*\n\t * If a target session is given, this is to be part of a session group,\n\t * so add it to the group and synchronize.\n\t */\n\tif (groupwith != NULL) {\n\t\tsession_group_add(groupwith, s);\n\t\tsession_group_synchronize_to(s);\n\t\tsession_select(s, RB_ROOT(&s->windows)->idx);\n\t}\n\n\t/*\n\t * Set the client to the new session. If a command client exists, it is\n\t * taking this session and needs to get MSG_READY and stay around.\n\t */\n\tif (!detached) {\n\t\tif (ctx->cmdclient != NULL) {\n\t\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\t\t\tif (ctx->cmdclient->session != NULL) {\n\t\t\t\tsession_index(ctx->cmdclient->session,\n\t\t\t\t &ctx->cmdclient->last_session);\n\t\t\t}\n\t\t\tctx->cmdclient->session = s;\n\t\t\tserver_redraw_client(ctx->cmdclient);\n\t\t} else {\n\t\t\tif (ctx->curclient->session != NULL) {\n\t\t\t\tsession_index(ctx->curclient->session,\n\t\t\t\t &ctx->curclient->last_session);\n\t\t\t}\n\t\t\tctx->curclient->session = s;\n\t\t\tserver_redraw_client(ctx->curclient);\n\t\t}\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\t/*\n\t * If there are still configuration file errors to display, put the new\n\t * session's current window into more mode and display them now.\n\t */\n\tif (cfg_finished && !ARRAY_EMPTY(&cfg_causes)) {\n\t\twp = s->curw->window->active;\n\t\twindow_pane_set_mode(wp, &window_copy_mode);\n\t\twindow_copy_init_for_output(wp);\n\t\tfor (i = 0; i < ARRAY_LENGTH(&cfg_causes); i++) {\n\t\t\tcause = ARRAY_ITEM(&cfg_causes, i);\n\t\t\twindow_copy_add(wp, \"%s\", cause);\n\t\t\txfree(cause);\n\t\t}\n\t\tARRAY_FREE(&cfg_causes);\n\t}\n\n\treturn (!detached);\t/* 1 means don't tell command client to exit */", "current_contents": "\t\tw->name = xstrdup(data->winname);\n\n\t\toptions_set_number(&w->options, \"automatic-rename\", 0);\n\t}\n\n\t/*\n\t * If a target session is given, this is to be part of a session group,\n\t * so add it to the group and synchronize.\n\t */\n\tif (groupwith != NULL) {\n\t\tsession_group_add(groupwith, s);\n\t\tsession_group_synchronize_to(s);\n\t\tsession_select(s, RB_ROOT(&s->windows)->idx);\n\t}\n\n\t/*\n\t * Set the client to the new session. If a command client exists, it is\n\t * taking this session and needs to get MSG_READY and stay around.\n\t */\n\tif (!detached) {\n\t\tif (ctx->cmdclient != NULL) {\n\t\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\t\t\tif (ctx->cmdclient->session != NULL) {\n\t\t\t\tsession_index(ctx->cmdclient->session,\n\t\t\t\t &ctx->cmdclient->last_session);\n\t\t\t}\n\t\t\tctx->cmdclient->session = s;\n\t\t\tserver_redraw_client(ctx->cmdclient);\n\t\t} else {\n\t\t\tctx->curclient->session = s;\n\t\t\tserver_redraw_client(ctx->curclient);\n\t\t}\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\t/*\n\t * If there are still configuration file errors to display, put the new\n\t * session's current window into more mode and display them now.\n\t */\n\tif (cfg_finished && !ARRAY_EMPTY(&cfg_causes)) {\n\t\twp = s->curw->window->active;\n\t\twindow_pane_set_mode(wp, &window_copy_mode);\n\t\twindow_copy_init_for_output(wp);\n\t\tfor (i = 0; i < ARRAY_LENGTH(&cfg_causes); i++) {\n\t\t\tcause = ARRAY_ITEM(&cfg_causes, i);\n\t\t\twindow_copy_add(wp, \"%s\", cause);\n\t\t\txfree(cause);\n\t\t}\n\t\tARRAY_FREE(&cfg_causes);\n\t}\n\n\treturn (!detached);\t/* 1 means don't tell command client to exit */", "text": "<|original_code|>\n\t\tw->name = xstrdup(data->winname);\n\n\t\toptions_set_number(&w->options, \"automatic-rename\", 0);\n\t}\n\n\t/*\n\t * If a target session is given, this is to be part of a session group,\n\t * so add it to the group and synchronize.\n\t */\n\tif (groupwith != NULL) {\n\t\tsession_group_add(groupwith, s);\n\t\tsession_group_synchronize_to(s);\n\t\tsession_select(s, RB_ROOT(&s->windows)->idx);\n\t}\n\n\t/*\n\t * Set the client to the new session. If a command client exists, it is\n\t * taking this session and needs to get MSG_READY and stay around.\n\t */\n\tif (!detached) {\n\t\tif (ctx->cmdclient != NULL) {\n\t\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\t\t\tctx->cmdclient->session = s;\n\t\t\tserver_redraw_client(ctx->cmdclient);\n\t\t} else {\n\t\t\tctx->curclient->session = s;\n\t\t\tserver_redraw_client(ctx->curclient);\n\t\t}\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\t/*\n\t * If there are still configuration file errors to display, put the new\n\t * session's current window into more mode and display them now.\n\t */\n\tif (cfg_finished && !ARRAY_EMPTY(&cfg_causes)) {\n\t\twp = s->curw->window->active;\n\t\twindow_pane_set_mode(wp, &window_copy_mode);\n\t\twindow_copy_init_for_output(wp);\n\t\tfor (i = 0; i < ARRAY_LENGTH(&cfg_causes); i++) {\n\t\t\tcause = ARRAY_ITEM(&cfg_causes, i);\n\t\t\twindow_copy_add(wp, \"%s\", cause);\n\t\t\txfree(cause);\n\t\t}\n\t\tARRAY_FREE(&cfg_causes);\n\t}\n\n\treturn (!detached);\t/* 1 means don't tell command client to exit */\n<|edits_diff|>\n--- cmd-new-session.c\n+++ cmd-new-session.c\n@@ -20,6 +20,10 @@\n \tif (!detached) {\n \t\tif (ctx->cmdclient != NULL) {\n \t\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n+\t\t\tif (ctx->cmdclient->session != NULL) {\n+\t\t\t\tsession_index(ctx->cmdclient->session,\n+\t\t\t\t &ctx->cmdclient->last_session);\n+\t\t\t}\n \t\t\tctx->cmdclient->session = s;\n \t\t\tserver_redraw_client(ctx->cmdclient);\n \t\t} else {\n<|current_version|>\n\t\tw->name = xstrdup(data->winname);\n\n\t\toptions_set_number(&w->options, \"automatic-rename\", 0);\n\t}\n\n\t/*\n\t * If a target session is given, this is to be part of a session group,\n\t * so add it to the group and synchronize.\n\t */\n\tif (groupwith != NULL) {\n\t\tsession_group_add(groupwith, s);\n\t\tsession_group_synchronize_to(s);\n\t\tsession_select(s, RB_ROOT(&s->windows)->idx);\n\t}\n\n\t/*\n\t * Set the client to the new session. If a command client exists, it is\n\t * taking this session and needs to get MSG_READY and stay around.\n\t */\n\tif (!detached) {\n\t\tif (ctx->cmdclient != NULL) {\n\t\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\t\t\tif (ctx->cmdclient->session != NULL) {\n\t\t\t\tsession_index(ctx->cmdclient->session,\n\t\t\t\t &ctx->cmdclient->last_session);\n\t\t\t}\n\t\t\tctx->cmdclient->session = s;\n\t\t\tserver_redraw_client(ctx->cmdclient);\n\t\t} else {\n\t\t\tctx->curclient->session = s;\n\t\t\tserver_redraw_client(ctx->curclient);\n\t\t}\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\t/*\n\t * If there are still configuration file errors to display, put the new\n\t * session's current window into more mode and display them now.\n\t */\n\tif (cfg_finished && !ARRAY_EMPTY(&cfg_causes)) {\n\t\twp = s->curw->window->active;\n\t\twindow_pane_set_mode(wp, &window_copy_mode);\n\t\twindow_copy_init_for_output(wp);\n\t\tfor (i = 0; i < ARRAY_LENGTH(&cfg_causes); i++) {\n\t\t\tcause = ARRAY_ITEM(&cfg_causes, i);\n\t\t\twindow_copy_add(wp, \"%s\", cause);\n\t\t\txfree(cause);\n\t\t}\n\t\tARRAY_FREE(&cfg_causes);\n\t}\n\n\treturn (!detached);\t/* 1 means don't tell command client to exit */\n<|next_version|>\n\t\tw->name = xstrdup(data->winname);\n\n\t\toptions_set_number(&w->options, \"automatic-rename\", 0);\n\t}\n\n\t/*\n\t * If a target session is given, this is to be part of a session group,\n\t * so add it to the group and synchronize.\n\t */\n\tif (groupwith != NULL) {\n\t\tsession_group_add(groupwith, s);\n\t\tsession_group_synchronize_to(s);\n\t\tsession_select(s, RB_ROOT(&s->windows)->idx);\n\t}\n\n\t/*\n\t * Set the client to the new session. If a command client exists, it is\n\t * taking this session and needs to get MSG_READY and stay around.\n\t */\n\tif (!detached) {\n\t\tif (ctx->cmdclient != NULL) {\n\t\t\tserver_write_client(ctx->cmdclient, MSG_READY, NULL, 0);\n\t\t\tif (ctx->cmdclient->session != NULL) {\n\t\t\t\tsession_index(ctx->cmdclient->session,\n\t\t\t\t &ctx->cmdclient->last_session);\n\t\t\t}\n\t\t\tctx->cmdclient->session = s;\n\t\t\tserver_redraw_client(ctx->cmdclient);\n\t\t} else {\n\t\t\tif (ctx->curclient->session != NULL) {\n\t\t\t\tsession_index(ctx->curclient->session,\n\t\t\t\t &ctx->curclient->last_session);\n\t\t\t}\n\t\t\tctx->curclient->session = s;\n\t\t\tserver_redraw_client(ctx->curclient);\n\t\t}\n\t}\n\trecalculate_sizes();\n\tserver_update_socket();\n\n\t/*\n\t * If there are still configuration file errors to display, put the new\n\t * session's current window into more mode and display them now.\n\t */\n\tif (cfg_finished && !ARRAY_EMPTY(&cfg_causes)) {\n\t\twp = s->curw->window->active;\n\t\twindow_pane_set_mode(wp, &window_copy_mode);\n\t\twindow_copy_init_for_output(wp);\n\t\tfor (i = 0; i < ARRAY_LENGTH(&cfg_causes); i++) {\n\t\t\tcause = ARRAY_ITEM(&cfg_causes, i);\n\t\t\twindow_copy_add(wp, \"%s\", cause);\n\t\t\txfree(cause);\n\t\t}\n\t\tARRAY_FREE(&cfg_causes);\n\t}\n\n\treturn (!detached);\t/* 1 means don't tell command client to exit */\n"} {"commit": "3a89d1ef7f4e9da3b3606df9385b79a77322963e", "message": "copy mode uses the real screen as backing and if it is updated while copying, strange things can happen. So, freeze reading from the pty while in copy mode.", "old_file": "window-copy.c", "new_file": "window-copy.c", "status": "M", "old_contents": "\tstruct screen\t\t\t*s;\n\tstruct screen_write_ctx\t \t ctx;\n\tu_int\t\t\t\t i;\n\tint\t\t\t\t keys;\n\n\twp->modedata = data = xmalloc(sizeof *data);\n\tdata->oy = 0;\n\tdata->cx = wp->base.cx;\n\tdata->cy = wp->base.cy;\n\n\tdata->lastcx = 0;\n\tdata->lastsx = 0;\n\n\tdata->rectflag = 0;\n\n\tdata->inputtype = WINDOW_COPY_OFF;\n\tdata->inputprompt = NULL;\n\tdata->inputstr = xstrdup(\"\");\n\n\tdata->searchtype = WINDOW_COPY_OFF;\n\tdata->searchstr = NULL;\n\n\ts = &data->screen;\n\tscreen_init(s, screen_size_x(&wp->base), screen_size_y(&wp->base), 0);\n\tif (options_get_number(&wp->window->options, \"mode-mouse\"))\n\t\ts->mode |= MODE_MOUSE;\n\n\tkeys = options_get_number(&wp->window->options, \"mode-keys\");\n\tif (keys == MODEKEY_EMACS)\n\t\tmode_key_init(&data->mdata, &mode_key_tree_emacs_copy);\n\telse\n\t\tmode_key_init(&data->mdata, &mode_key_tree_vi_copy);\n\n\ts->cx = data->cx;\n\ts->cy = data->cy;\n\n\tscreen_write_start(&ctx, NULL, s);\n\tfor (i = 0; i < screen_size_y(s); i++)\n\t\twindow_copy_write_line(wp, &ctx, i);\n\tscreen_write_cursormove(&ctx, data->cx, data->cy);\n\tscreen_write_stop(&ctx);\n\n\treturn (s);\n}\n\nvoid\nwindow_copy_free(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\n\tif (data->searchstr != NULL)\n\t\txfree(data->searchstr);\n\txfree(data->inputstr);\n\n\tscreen_free(&data->screen);\n\n\txfree(data);\n}\n\nvoid\nwindow_copy_pageup(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\tstruct screen\t\t\t*s = &data->screen;\n\tu_int\t\t\t\t n;\n\n\tn = 1;\n\tif (screen_size_y(s) > 2)\n\t\tn = screen_size_y(s) - 2;\n\tif (data->oy + n > screen_hsize(&wp->base))\n\t\tdata->oy = screen_hsize(&wp->base);\n\telse\n\t\tdata->oy += n;", "new_contents": "\tstruct screen\t\t\t*s;\n\tstruct screen_write_ctx\t \t ctx;\n\tu_int\t\t\t\t i;\n\tint\t\t\t\t keys;\n\n\twp->modedata = data = xmalloc(sizeof *data);\n\tdata->oy = 0;\n\tdata->cx = wp->base.cx;\n\tdata->cy = wp->base.cy;\n\n\tdata->lastcx = 0;\n\tdata->lastsx = 0;\n\n\tdata->rectflag = 0;\n\n\tdata->inputtype = WINDOW_COPY_OFF;\n\tdata->inputprompt = NULL;\n\tdata->inputstr = xstrdup(\"\");\n\n\tdata->searchtype = WINDOW_COPY_OFF;\n\tdata->searchstr = NULL;\n\n\twp->flags |= PANE_FREEZE;\n\tbufferevent_disable(wp->event, EV_READ|EV_WRITE);\n\n\ts = &data->screen;\n\tscreen_init(s, screen_size_x(&wp->base), screen_size_y(&wp->base), 0);\n\tif (options_get_number(&wp->window->options, \"mode-mouse\"))\n\t\ts->mode |= MODE_MOUSE;\n\n\tkeys = options_get_number(&wp->window->options, \"mode-keys\");\n\tif (keys == MODEKEY_EMACS)\n\t\tmode_key_init(&data->mdata, &mode_key_tree_emacs_copy);\n\telse\n\t\tmode_key_init(&data->mdata, &mode_key_tree_vi_copy);\n\n\ts->cx = data->cx;\n\ts->cy = data->cy;\n\n\tscreen_write_start(&ctx, NULL, s);\n\tfor (i = 0; i < screen_size_y(s); i++)\n\t\twindow_copy_write_line(wp, &ctx, i);\n\tscreen_write_cursormove(&ctx, data->cx, data->cy);\n\tscreen_write_stop(&ctx);\n\n\treturn (s);\n}\n\nvoid\nwindow_copy_free(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\n\twp->flags &= ~PANE_FREEZE;\n\tbufferevent_enable(wp->event, EV_READ|EV_WRITE);\n\n\tif (data->searchstr != NULL)\n\t\txfree(data->searchstr);\n\txfree(data->inputstr);\n\n\tscreen_free(&data->screen);\n\n\txfree(data);\n}\n\nvoid\nwindow_copy_pageup(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\tstruct screen\t\t\t*s = &data->screen;\n\tu_int\t\t\t\t n;\n\n\tn = 1;\n\tif (screen_size_y(s) > 2)\n\t\tn = screen_size_y(s) - 2;\n\tif (data->oy + n > screen_hsize(&wp->base))\n\t\tdata->oy = screen_hsize(&wp->base);\n\telse\n\t\tdata->oy += n;", "current_contents": "\tstruct screen\t\t\t*s;\n\tstruct screen_write_ctx\t \t ctx;\n\tu_int\t\t\t\t i;\n\tint\t\t\t\t keys;\n\n\twp->modedata = data = xmalloc(sizeof *data);\n\tdata->oy = 0;\n\tdata->cx = wp->base.cx;\n\tdata->cy = wp->base.cy;\n\n\tdata->lastcx = 0;\n\tdata->lastsx = 0;\n\n\tdata->rectflag = 0;\n\n\tdata->inputtype = WINDOW_COPY_OFF;\n\tdata->inputprompt = NULL;\n\tdata->inputstr = xstrdup(\"\");\n\n\tdata->searchtype = WINDOW_COPY_OFF;\n\tdata->searchstr = NULL;\n\n\twp->flags |= PANE_FREEZE;\n\tbufferevent_disable(wp->event, EV_READ|EV_WRITE);\n\n\ts = &data->screen;\n\tscreen_init(s, screen_size_x(&wp->base), screen_size_y(&wp->base), 0);\n\tif (options_get_number(&wp->window->options, \"mode-mouse\"))\n\t\ts->mode |= MODE_MOUSE;\n\n\tkeys = options_get_number(&wp->window->options, \"mode-keys\");\n\tif (keys == MODEKEY_EMACS)\n\t\tmode_key_init(&data->mdata, &mode_key_tree_emacs_copy);\n\telse\n\t\tmode_key_init(&data->mdata, &mode_key_tree_vi_copy);\n\n\ts->cx = data->cx;\n\ts->cy = data->cy;\n\n\tscreen_write_start(&ctx, NULL, s);\n\tfor (i = 0; i < screen_size_y(s); i++)\n\t\twindow_copy_write_line(wp, &ctx, i);\n\tscreen_write_cursormove(&ctx, data->cx, data->cy);\n\tscreen_write_stop(&ctx);\n\n\treturn (s);\n}\n\nvoid\nwindow_copy_free(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\n\tif (data->searchstr != NULL)\n\t\txfree(data->searchstr);\n\txfree(data->inputstr);\n\n\tscreen_free(&data->screen);\n\n\txfree(data);\n}\n\nvoid\nwindow_copy_pageup(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\tstruct screen\t\t\t*s = &data->screen;\n\tu_int\t\t\t\t n;\n\n\tn = 1;\n\tif (screen_size_y(s) > 2)\n\t\tn = screen_size_y(s) - 2;\n\tif (data->oy + n > screen_hsize(&wp->base))\n\t\tdata->oy = screen_hsize(&wp->base);\n\telse\n\t\tdata->oy += n;", "text": "<|original_code|>\n\tstruct screen\t\t\t*s;\n\tstruct screen_write_ctx\t \t ctx;\n\tu_int\t\t\t\t i;\n\tint\t\t\t\t keys;\n\n\twp->modedata = data = xmalloc(sizeof *data);\n\tdata->oy = 0;\n\tdata->cx = wp->base.cx;\n\tdata->cy = wp->base.cy;\n\n\tdata->lastcx = 0;\n\tdata->lastsx = 0;\n\n\tdata->rectflag = 0;\n\n\tdata->inputtype = WINDOW_COPY_OFF;\n\tdata->inputprompt = NULL;\n\tdata->inputstr = xstrdup(\"\");\n\n\tdata->searchtype = WINDOW_COPY_OFF;\n\tdata->searchstr = NULL;\n\n\ts = &data->screen;\n\tscreen_init(s, screen_size_x(&wp->base), screen_size_y(&wp->base), 0);\n\tif (options_get_number(&wp->window->options, \"mode-mouse\"))\n\t\ts->mode |= MODE_MOUSE;\n\n\tkeys = options_get_number(&wp->window->options, \"mode-keys\");\n\tif (keys == MODEKEY_EMACS)\n\t\tmode_key_init(&data->mdata, &mode_key_tree_emacs_copy);\n\telse\n\t\tmode_key_init(&data->mdata, &mode_key_tree_vi_copy);\n\n\ts->cx = data->cx;\n\ts->cy = data->cy;\n\n\tscreen_write_start(&ctx, NULL, s);\n\tfor (i = 0; i < screen_size_y(s); i++)\n\t\twindow_copy_write_line(wp, &ctx, i);\n\tscreen_write_cursormove(&ctx, data->cx, data->cy);\n\tscreen_write_stop(&ctx);\n\n\treturn (s);\n}\n\nvoid\nwindow_copy_free(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\n\tif (data->searchstr != NULL)\n\t\txfree(data->searchstr);\n\txfree(data->inputstr);\n\n\tscreen_free(&data->screen);\n\n\txfree(data);\n}\n\nvoid\nwindow_copy_pageup(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\tstruct screen\t\t\t*s = &data->screen;\n\tu_int\t\t\t\t n;\n\n\tn = 1;\n\tif (screen_size_y(s) > 2)\n\t\tn = screen_size_y(s) - 2;\n\tif (data->oy + n > screen_hsize(&wp->base))\n\t\tdata->oy = screen_hsize(&wp->base);\n\telse\n\t\tdata->oy += n;\n<|edits_diff|>\n--- window-copy.c\n+++ window-copy.c\n@@ -19,6 +19,9 @@\n \n \tdata->searchtype = WINDOW_COPY_OFF;\n \tdata->searchstr = NULL;\n+\n+\twp->flags |= PANE_FREEZE;\n+\tbufferevent_disable(wp->event, EV_READ|EV_WRITE);\n \n \ts = &data->screen;\n \tscreen_init(s, screen_size_x(&wp->base), screen_size_y(&wp->base), 0);\n<|current_version|>\n\tstruct screen\t\t\t*s;\n\tstruct screen_write_ctx\t \t ctx;\n\tu_int\t\t\t\t i;\n\tint\t\t\t\t keys;\n\n\twp->modedata = data = xmalloc(sizeof *data);\n\tdata->oy = 0;\n\tdata->cx = wp->base.cx;\n\tdata->cy = wp->base.cy;\n\n\tdata->lastcx = 0;\n\tdata->lastsx = 0;\n\n\tdata->rectflag = 0;\n\n\tdata->inputtype = WINDOW_COPY_OFF;\n\tdata->inputprompt = NULL;\n\tdata->inputstr = xstrdup(\"\");\n\n\tdata->searchtype = WINDOW_COPY_OFF;\n\tdata->searchstr = NULL;\n\n\twp->flags |= PANE_FREEZE;\n\tbufferevent_disable(wp->event, EV_READ|EV_WRITE);\n\n\ts = &data->screen;\n\tscreen_init(s, screen_size_x(&wp->base), screen_size_y(&wp->base), 0);\n\tif (options_get_number(&wp->window->options, \"mode-mouse\"))\n\t\ts->mode |= MODE_MOUSE;\n\n\tkeys = options_get_number(&wp->window->options, \"mode-keys\");\n\tif (keys == MODEKEY_EMACS)\n\t\tmode_key_init(&data->mdata, &mode_key_tree_emacs_copy);\n\telse\n\t\tmode_key_init(&data->mdata, &mode_key_tree_vi_copy);\n\n\ts->cx = data->cx;\n\ts->cy = data->cy;\n\n\tscreen_write_start(&ctx, NULL, s);\n\tfor (i = 0; i < screen_size_y(s); i++)\n\t\twindow_copy_write_line(wp, &ctx, i);\n\tscreen_write_cursormove(&ctx, data->cx, data->cy);\n\tscreen_write_stop(&ctx);\n\n\treturn (s);\n}\n\nvoid\nwindow_copy_free(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\n\tif (data->searchstr != NULL)\n\t\txfree(data->searchstr);\n\txfree(data->inputstr);\n\n\tscreen_free(&data->screen);\n\n\txfree(data);\n}\n\nvoid\nwindow_copy_pageup(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\tstruct screen\t\t\t*s = &data->screen;\n\tu_int\t\t\t\t n;\n\n\tn = 1;\n\tif (screen_size_y(s) > 2)\n\t\tn = screen_size_y(s) - 2;\n\tif (data->oy + n > screen_hsize(&wp->base))\n\t\tdata->oy = screen_hsize(&wp->base);\n\telse\n\t\tdata->oy += n;\n<|next_version|>\n\tstruct screen\t\t\t*s;\n\tstruct screen_write_ctx\t \t ctx;\n\tu_int\t\t\t\t i;\n\tint\t\t\t\t keys;\n\n\twp->modedata = data = xmalloc(sizeof *data);\n\tdata->oy = 0;\n\tdata->cx = wp->base.cx;\n\tdata->cy = wp->base.cy;\n\n\tdata->lastcx = 0;\n\tdata->lastsx = 0;\n\n\tdata->rectflag = 0;\n\n\tdata->inputtype = WINDOW_COPY_OFF;\n\tdata->inputprompt = NULL;\n\tdata->inputstr = xstrdup(\"\");\n\n\tdata->searchtype = WINDOW_COPY_OFF;\n\tdata->searchstr = NULL;\n\n\twp->flags |= PANE_FREEZE;\n\tbufferevent_disable(wp->event, EV_READ|EV_WRITE);\n\n\ts = &data->screen;\n\tscreen_init(s, screen_size_x(&wp->base), screen_size_y(&wp->base), 0);\n\tif (options_get_number(&wp->window->options, \"mode-mouse\"))\n\t\ts->mode |= MODE_MOUSE;\n\n\tkeys = options_get_number(&wp->window->options, \"mode-keys\");\n\tif (keys == MODEKEY_EMACS)\n\t\tmode_key_init(&data->mdata, &mode_key_tree_emacs_copy);\n\telse\n\t\tmode_key_init(&data->mdata, &mode_key_tree_vi_copy);\n\n\ts->cx = data->cx;\n\ts->cy = data->cy;\n\n\tscreen_write_start(&ctx, NULL, s);\n\tfor (i = 0; i < screen_size_y(s); i++)\n\t\twindow_copy_write_line(wp, &ctx, i);\n\tscreen_write_cursormove(&ctx, data->cx, data->cy);\n\tscreen_write_stop(&ctx);\n\n\treturn (s);\n}\n\nvoid\nwindow_copy_free(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\n\twp->flags &= ~PANE_FREEZE;\n\tbufferevent_enable(wp->event, EV_READ|EV_WRITE);\n\n\tif (data->searchstr != NULL)\n\t\txfree(data->searchstr);\n\txfree(data->inputstr);\n\n\tscreen_free(&data->screen);\n\n\txfree(data);\n}\n\nvoid\nwindow_copy_pageup(struct window_pane *wp)\n{\n\tstruct window_copy_mode_data\t*data = wp->modedata;\n\tstruct screen\t\t\t*s = &data->screen;\n\tu_int\t\t\t\t n;\n\n\tn = 1;\n\tif (screen_size_y(s) > 2)\n\t\tn = screen_size_y(s) - 2;\n\tif (data->oy + n > screen_hsize(&wp->base))\n\t\tdata->oy = screen_hsize(&wp->base);\n\telse\n\t\tdata->oy += n;\n"} {"commit": "5b634657980ecfa2d65e9ffec622dfd842839628", "message": "Add icon override setting for newTabMenu entries (#18116)", "old_file": "src/cascadia/TerminalSettingsModel/ActionEntry.cpp", "new_file": "src/cascadia/TerminalSettingsModel/ActionEntry.cpp", "status": "M", "old_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ActionEntry.h\"\r\n#include \"JsonUtils.h\"\r\n\r\n#include \"ActionEntry.g.cpp\"\r\n\r\nusing namespace Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\n\r\nstatic constexpr std::string_view ActionIdKey{ \"id\" };\r\n\r\nActionEntry::ActionEntry() noexcept :\r\n ActionEntryT(NewTabMenuEntryType::Action)\r\n{\r\n}\r\n\r\nJson::Value ActionEntry::ToJson() const\r\n{\r\n auto json = NewTabMenuEntry::ToJson();\r\n\r\n JsonUtils::SetValueForKey(json, ActionIdKey, _ActionId);\r\n\r\n return json;\r\n}\r\n\r\nwinrt::com_ptr ActionEntry::FromJson(const Json::Value& json)\r\n{\r\n auto entry = winrt::make_self();\r\n\r\n JsonUtils::GetValueForKey(json, ActionIdKey, entry->_ActionId);\r\n\r\n return entry;\r\n}\r\n", "new_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ActionEntry.h\"\r\n#include \"JsonUtils.h\"\r\n\r\n#include \"ActionEntry.g.cpp\"\r\n\r\nusing namespace Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\n\r\nstatic constexpr std::string_view ActionIdKey{ \"id\" };\r\nstatic constexpr std::string_view IconKey{ \"icon\" };\r\n\r\nActionEntry::ActionEntry() noexcept :\r\n ActionEntryT(NewTabMenuEntryType::Action)\r\n{\r\n}\r\n\r\nJson::Value ActionEntry::ToJson() const\r\n{\r\n auto json = NewTabMenuEntry::ToJson();\r\n\r\n JsonUtils::SetValueForKey(json, ActionIdKey, _ActionId);\r\n JsonUtils::SetValueForKey(json, IconKey, _Icon);\r\n\r\n return json;\r\n}\r\n\r\nwinrt::com_ptr ActionEntry::FromJson(const Json::Value& json)\r\n{\r\n auto entry = winrt::make_self();\r\n\r\n JsonUtils::GetValueForKey(json, ActionIdKey, entry->_ActionId);\r\n JsonUtils::GetValueForKey(json, IconKey, entry->_Icon);\r\n\r\n return entry;\r\n}\r\n", "text": "<|original_code|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ActionEntry.h\"\r\n#include \"JsonUtils.h\"\r\n\r\n#include \"ActionEntry.g.cpp\"\r\n\r\nusing namespace Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\n\r\nstatic constexpr std::string_view ActionIdKey{ \"id\" };\r\n\r\nActionEntry::ActionEntry() noexcept :\r\n ActionEntryT(NewTabMenuEntryType::Action)\r\n{\r\n}\r\n\r\nJson::Value ActionEntry::ToJson() const\r\n{\r\n auto json = NewTabMenuEntry::ToJson();\r\n\r\n JsonUtils::SetValueForKey(json, ActionIdKey, _ActionId);\r\n\r\n return json;\r\n}\r\n\r\nwinrt::com_ptr ActionEntry::FromJson(const Json::Value& json)\r\n{\r\n auto entry = winrt::make_self();\r\n\r\n JsonUtils::GetValueForKey(json, ActionIdKey, entry->_ActionId);\r\n\r\n return entry;\r\n}\r\n\n<|edits_diff|>\n--- src/cascadia/TerminalSettingsModel/ActionEntry.cpp\n+++ src/cascadia/TerminalSettingsModel/ActionEntry.cpp\n@@ -11,6 +11,7 @@\n using namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\n \n static constexpr std::string_view ActionIdKey{ \"id\" };\n+static constexpr std::string_view IconKey{ \"icon\" };\n \n ActionEntry::ActionEntry() noexcept :\n ActionEntryT(NewTabMenuEntryType::Action)\n@@ -22,6 +23,7 @@\n auto json = NewTabMenuEntry::ToJson();\n \n JsonUtils::SetValueForKey(json, ActionIdKey, _ActionId);\n+ JsonUtils::SetValueForKey(json, IconKey, _Icon);\n \n return json;\n }\n<|current_version|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ActionEntry.h\"\r\n#include \"JsonUtils.h\"\r\n\r\n#include \"ActionEntry.g.cpp\"\r\n\r\nusing namespace Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\n\r\nstatic constexpr std::string_view ActionIdKey{ \"id\" };\r\nstatic constexpr std::string_view IconKey{ \"icon\" };\r\n\r\nActionEntry::ActionEntry() noexcept :\r\n ActionEntryT(NewTabMenuEntryType::Action)\r\n{\r\n}\r\n\r\nJson::Value ActionEntry::ToJson() const\r\n{\r\n auto json = NewTabMenuEntry::ToJson();\r\n\r\n JsonUtils::SetValueForKey(json, ActionIdKey, _ActionId);\r\n JsonUtils::SetValueForKey(json, IconKey, _Icon);\r\n\r\n return json;\r\n}\r\n\r\nwinrt::com_ptr ActionEntry::FromJson(const Json::Value& json)\r\n{\r\n auto entry = winrt::make_self();\r\n\r\n JsonUtils::GetValueForKey(json, ActionIdKey, entry->_ActionId);\r\n\r\n return entry;\r\n}\r\n\n<|next_version|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ActionEntry.h\"\r\n#include \"JsonUtils.h\"\r\n\r\n#include \"ActionEntry.g.cpp\"\r\n\r\nusing namespace Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\n\r\nstatic constexpr std::string_view ActionIdKey{ \"id\" };\r\nstatic constexpr std::string_view IconKey{ \"icon\" };\r\n\r\nActionEntry::ActionEntry() noexcept :\r\n ActionEntryT(NewTabMenuEntryType::Action)\r\n{\r\n}\r\n\r\nJson::Value ActionEntry::ToJson() const\r\n{\r\n auto json = NewTabMenuEntry::ToJson();\r\n\r\n JsonUtils::SetValueForKey(json, ActionIdKey, _ActionId);\r\n JsonUtils::SetValueForKey(json, IconKey, _Icon);\r\n\r\n return json;\r\n}\r\n\r\nwinrt::com_ptr ActionEntry::FromJson(const Json::Value& json)\r\n{\r\n auto entry = winrt::make_self();\r\n\r\n JsonUtils::GetValueForKey(json, ActionIdKey, entry->_ActionId);\r\n JsonUtils::GetValueForKey(json, IconKey, entry->_Icon);\r\n\r\n return entry;\r\n}\r\n\n", "current_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ActionEntry.h\"\r\n#include \"JsonUtils.h\"\r\n\r\n#include \"ActionEntry.g.cpp\"\r\n\r\nusing namespace Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\n\r\nstatic constexpr std::string_view ActionIdKey{ \"id\" };\r\nstatic constexpr std::string_view IconKey{ \"icon\" };\r\n\r\nActionEntry::ActionEntry() noexcept :\r\n ActionEntryT(NewTabMenuEntryType::Action)\r\n{\r\n}\r\n\r\nJson::Value ActionEntry::ToJson() const\r\n{\r\n auto json = NewTabMenuEntry::ToJson();\r\n\r\n JsonUtils::SetValueForKey(json, ActionIdKey, _ActionId);\r\n JsonUtils::SetValueForKey(json, IconKey, _Icon);\r\n\r\n return json;\r\n}\r\n\r\nwinrt::com_ptr ActionEntry::FromJson(const Json::Value& json)\r\n{\r\n auto entry = winrt::make_self();\r\n\r\n JsonUtils::GetValueForKey(json, ActionIdKey, entry->_ActionId);\r\n\r\n return entry;\r\n}\r\n"} {"commit": "18d86bca091f1316f4176b90cfac6973f990966d", "message": "Add a Compatibility and Terminal page to the Settings UI (#17895)", "old_file": "src/cascadia/TerminalSettingsEditor/Profiles_Base.cpp", "new_file": "src/cascadia/TerminalSettingsEditor/Profiles_Base.cpp", "status": "M", "old_contents": "#include \"Profiles_Base.h\"\n#include \"Profiles_Base.g.cpp\"\n#include \"ProfileViewModel.h\"\n\n#include \n#include \"..\\WinRTUtils\\inc\\Utils.h\"\n\nusing namespace winrt::Windows::UI::Xaml;\nusing namespace winrt::Windows::UI::Xaml::Controls;\nusing namespace winrt::Windows::UI::Xaml::Navigation;\n\nnamespace winrt::Microsoft::Terminal::Settings::Editor::implementation\n{\n Profiles_Base::Profiles_Base()\n {\n InitializeComponent();\n\n const auto startingDirCheckboxTooltip{ ToolTipService::GetToolTip(StartingDirectoryUseParentCheckbox()) };\n Automation::AutomationProperties::SetFullDescription(StartingDirectoryUseParentCheckbox(), unbox_value(startingDirCheckboxTooltip));\n\n Automation::AutomationProperties::SetName(DeleteButton(), RS_(L\"Profile_DeleteButton/Text\"));\n AppearanceNavigator().Content(box_value(RS_(L\"Profile_Appearance/Header\")));\n AdvancedNavigator().Content(box_value(RS_(L\"Profile_Advanced/Header\")));\n }\n\n void Profiles_Base::OnNavigatedTo(const NavigationEventArgs& e)\n {\n const auto args = e.Parameter().as();\n _Profile = args.Profile();\n _windowRoot = args.WindowRoot();\n\n // Check the use parent directory box if the starting directory is empty\n if (_Profile.StartingDirectory().empty())\n {\n StartingDirectoryUseParentCheckbox().IsChecked(true);\n }\n\n _layoutUpdatedRevoker = LayoutUpdated(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {\n // This event fires every time the layout changes, but it is always the last one to fire\n // in any layout change chain. That gives us great flexibility in finding the right point\n // at which to initialize our renderer (and our terminal).\n // Any earlier than the last layout update and we may not know the terminal's starting size.\n\n // Only let this succeed once.\n _layoutUpdatedRevoker.revoke();\n\n if (_Profile.FocusDeleteButton())\n {\n DeleteButton().Focus(FocusState::Programmatic);\n _Profile.FocusDeleteButton(false);\n }\n });\n }\n\n void Profiles_Base::OnNavigatedFrom(const NavigationEventArgs& /*e*/)\n {\n _ViewModelChangedRevoker.revoke();\n }\n\n void Profiles_Base::Appearance_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Appearance);\n }\n\n void Profiles_Base::Advanced_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Advanced);\n }\n\n void Profiles_Base::DeleteConfirmation_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*e*/)\n {\n winrt::get_self(_Profile)->DeleteProfile();\n }\n\n safe_void_coroutine Profiles_Base::Commandline_Click(const IInspectable&, const RoutedEventArgs&)\n {\n auto lifetime = get_strong();\n\n static constexpr COMDLG_FILTERSPEC supportedFileTypes[] = {\n { L\"Executable Files (*.exe, *.cmd, *.bat)\", L\"*.exe;*.cmd;*.bat\" },\n { L\"All Files (*.*)\", L\"*.*\" }\n };\n\n static constexpr winrt::guid clientGuidExecutables{ 0x2E7E4331, 0x0800, 0x48E6, { 0xB0, 0x17, 0xA1, 0x4C, 0xD8, 0x73, 0xDD, 0x58 } };\n const auto parentHwnd{ reinterpret_cast(_windowRoot.GetHostingWindow()) };\n auto path = co_await OpenFilePicker(parentHwnd, [](auto&& dialog) {", "new_contents": "#include \"Profiles_Base.h\"\n#include \"Profiles_Base.g.cpp\"\n#include \"ProfileViewModel.h\"\n\n#include \n#include \"..\\WinRTUtils\\inc\\Utils.h\"\n\nusing namespace winrt::Windows::UI::Xaml;\nusing namespace winrt::Windows::UI::Xaml::Controls;\nusing namespace winrt::Windows::UI::Xaml::Navigation;\n\nnamespace winrt::Microsoft::Terminal::Settings::Editor::implementation\n{\n Profiles_Base::Profiles_Base()\n {\n InitializeComponent();\n\n const auto startingDirCheckboxTooltip{ ToolTipService::GetToolTip(StartingDirectoryUseParentCheckbox()) };\n Automation::AutomationProperties::SetFullDescription(StartingDirectoryUseParentCheckbox(), unbox_value(startingDirCheckboxTooltip));\n\n Automation::AutomationProperties::SetName(DeleteButton(), RS_(L\"Profile_DeleteButton/Text\"));\n AppearanceNavigator().Content(box_value(RS_(L\"Profile_Appearance/Header\")));\n TerminalNavigator().Content(box_value(RS_(L\"Profile_Terminal/Header\")));\n AdvancedNavigator().Content(box_value(RS_(L\"Profile_Advanced/Header\")));\n }\n\n void Profiles_Base::OnNavigatedTo(const NavigationEventArgs& e)\n {\n const auto args = e.Parameter().as();\n _Profile = args.Profile();\n _windowRoot = args.WindowRoot();\n\n // Check the use parent directory box if the starting directory is empty\n if (_Profile.StartingDirectory().empty())\n {\n StartingDirectoryUseParentCheckbox().IsChecked(true);\n }\n\n _layoutUpdatedRevoker = LayoutUpdated(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {\n // This event fires every time the layout changes, but it is always the last one to fire\n // in any layout change chain. That gives us great flexibility in finding the right point\n // at which to initialize our renderer (and our terminal).\n // Any earlier than the last layout update and we may not know the terminal's starting size.\n\n // Only let this succeed once.\n _layoutUpdatedRevoker.revoke();\n\n if (_Profile.FocusDeleteButton())\n {\n DeleteButton().Focus(FocusState::Programmatic);\n _Profile.FocusDeleteButton(false);\n }\n });\n }\n\n void Profiles_Base::OnNavigatedFrom(const NavigationEventArgs& /*e*/)\n {\n _ViewModelChangedRevoker.revoke();\n }\n\n void Profiles_Base::Appearance_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Appearance);\n }\n\n void Profiles_Base::Terminal_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Terminal);\n }\n\n void Profiles_Base::Advanced_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Advanced);\n }\n\n void Profiles_Base::DeleteConfirmation_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*e*/)\n {\n winrt::get_self(_Profile)->DeleteProfile();\n }\n\n safe_void_coroutine Profiles_Base::Commandline_Click(const IInspectable&, const RoutedEventArgs&)\n {\n auto lifetime = get_strong();\n\n static constexpr COMDLG_FILTERSPEC supportedFileTypes[] = {\n { L\"Executable Files (*.exe, *.cmd, *.bat)\", L\"*.exe;*.cmd;*.bat\" },\n { L\"All Files (*.*)\", L\"*.*\" }\n };\n\n static constexpr winrt::guid clientGuidExecutables{ 0x2E7E4331, 0x0800, 0x48E6, { 0xB0, 0x17, 0xA1, 0x4C, 0xD8, 0x73, 0xDD, 0x58 } };\n const auto parentHwnd{ reinterpret_cast(_windowRoot.GetHostingWindow()) };\n auto path = co_await OpenFilePicker(parentHwnd, [](auto&& dialog) {", "text": "<|original_code|>\n#include \"Profiles_Base.h\"\n#include \"Profiles_Base.g.cpp\"\n#include \"ProfileViewModel.h\"\n\n#include \n#include \"..\\WinRTUtils\\inc\\Utils.h\"\n\nusing namespace winrt::Windows::UI::Xaml;\nusing namespace winrt::Windows::UI::Xaml::Controls;\nusing namespace winrt::Windows::UI::Xaml::Navigation;\n\nnamespace winrt::Microsoft::Terminal::Settings::Editor::implementation\n{\n Profiles_Base::Profiles_Base()\n {\n InitializeComponent();\n\n const auto startingDirCheckboxTooltip{ ToolTipService::GetToolTip(StartingDirectoryUseParentCheckbox()) };\n Automation::AutomationProperties::SetFullDescription(StartingDirectoryUseParentCheckbox(), unbox_value(startingDirCheckboxTooltip));\n\n Automation::AutomationProperties::SetName(DeleteButton(), RS_(L\"Profile_DeleteButton/Text\"));\n AppearanceNavigator().Content(box_value(RS_(L\"Profile_Appearance/Header\")));\n AdvancedNavigator().Content(box_value(RS_(L\"Profile_Advanced/Header\")));\n }\n\n void Profiles_Base::OnNavigatedTo(const NavigationEventArgs& e)\n {\n const auto args = e.Parameter().as();\n _Profile = args.Profile();\n _windowRoot = args.WindowRoot();\n\n // Check the use parent directory box if the starting directory is empty\n if (_Profile.StartingDirectory().empty())\n {\n StartingDirectoryUseParentCheckbox().IsChecked(true);\n }\n\n _layoutUpdatedRevoker = LayoutUpdated(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {\n // This event fires every time the layout changes, but it is always the last one to fire\n // in any layout change chain. That gives us great flexibility in finding the right point\n // at which to initialize our renderer (and our terminal).\n // Any earlier than the last layout update and we may not know the terminal's starting size.\n\n // Only let this succeed once.\n _layoutUpdatedRevoker.revoke();\n\n if (_Profile.FocusDeleteButton())\n {\n DeleteButton().Focus(FocusState::Programmatic);\n _Profile.FocusDeleteButton(false);\n }\n });\n }\n\n void Profiles_Base::OnNavigatedFrom(const NavigationEventArgs& /*e*/)\n {\n _ViewModelChangedRevoker.revoke();\n }\n\n void Profiles_Base::Appearance_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Appearance);\n }\n\n void Profiles_Base::Advanced_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Advanced);\n }\n\n void Profiles_Base::DeleteConfirmation_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*e*/)\n {\n winrt::get_self(_Profile)->DeleteProfile();\n }\n\n safe_void_coroutine Profiles_Base::Commandline_Click(const IInspectable&, const RoutedEventArgs&)\n {\n auto lifetime = get_strong();\n\n static constexpr COMDLG_FILTERSPEC supportedFileTypes[] = {\n { L\"Executable Files (*.exe, *.cmd, *.bat)\", L\"*.exe;*.cmd;*.bat\" },\n { L\"All Files (*.*)\", L\"*.*\" }\n };\n\n static constexpr winrt::guid clientGuidExecutables{ 0x2E7E4331, 0x0800, 0x48E6, { 0xB0, 0x17, 0xA1, 0x4C, 0xD8, 0x73, 0xDD, 0x58 } };\n const auto parentHwnd{ reinterpret_cast(_windowRoot.GetHostingWindow()) };\n auto path = co_await OpenFilePicker(parentHwnd, [](auto&& dialog) {\n<|edits_diff|>\n--- src/cascadia/TerminalSettingsEditor/Profiles_Base.cpp\n+++ src/cascadia/TerminalSettingsEditor/Profiles_Base.cpp\n@@ -20,6 +20,7 @@\n \n Automation::AutomationProperties::SetName(DeleteButton(), RS_(L\"Profile_DeleteButton/Text\"));\n AppearanceNavigator().Content(box_value(RS_(L\"Profile_Appearance/Header\")));\n+ TerminalNavigator().Content(box_value(RS_(L\"Profile_Terminal/Header\")));\n AdvancedNavigator().Content(box_value(RS_(L\"Profile_Advanced/Header\")));\n }\n \n<|current_version|>\n#include \"Profiles_Base.h\"\n#include \"Profiles_Base.g.cpp\"\n#include \"ProfileViewModel.h\"\n\n#include \n#include \"..\\WinRTUtils\\inc\\Utils.h\"\n\nusing namespace winrt::Windows::UI::Xaml;\nusing namespace winrt::Windows::UI::Xaml::Controls;\nusing namespace winrt::Windows::UI::Xaml::Navigation;\n\nnamespace winrt::Microsoft::Terminal::Settings::Editor::implementation\n{\n Profiles_Base::Profiles_Base()\n {\n InitializeComponent();\n\n const auto startingDirCheckboxTooltip{ ToolTipService::GetToolTip(StartingDirectoryUseParentCheckbox()) };\n Automation::AutomationProperties::SetFullDescription(StartingDirectoryUseParentCheckbox(), unbox_value(startingDirCheckboxTooltip));\n\n Automation::AutomationProperties::SetName(DeleteButton(), RS_(L\"Profile_DeleteButton/Text\"));\n AppearanceNavigator().Content(box_value(RS_(L\"Profile_Appearance/Header\")));\n TerminalNavigator().Content(box_value(RS_(L\"Profile_Terminal/Header\")));\n AdvancedNavigator().Content(box_value(RS_(L\"Profile_Advanced/Header\")));\n }\n\n void Profiles_Base::OnNavigatedTo(const NavigationEventArgs& e)\n {\n const auto args = e.Parameter().as();\n _Profile = args.Profile();\n _windowRoot = args.WindowRoot();\n\n // Check the use parent directory box if the starting directory is empty\n if (_Profile.StartingDirectory().empty())\n {\n StartingDirectoryUseParentCheckbox().IsChecked(true);\n }\n\n _layoutUpdatedRevoker = LayoutUpdated(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {\n // This event fires every time the layout changes, but it is always the last one to fire\n // in any layout change chain. That gives us great flexibility in finding the right point\n // at which to initialize our renderer (and our terminal).\n // Any earlier than the last layout update and we may not know the terminal's starting size.\n\n // Only let this succeed once.\n _layoutUpdatedRevoker.revoke();\n\n if (_Profile.FocusDeleteButton())\n {\n DeleteButton().Focus(FocusState::Programmatic);\n _Profile.FocusDeleteButton(false);\n }\n });\n }\n\n void Profiles_Base::OnNavigatedFrom(const NavigationEventArgs& /*e*/)\n {\n _ViewModelChangedRevoker.revoke();\n }\n\n void Profiles_Base::Appearance_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Appearance);\n }\n\n void Profiles_Base::Advanced_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Advanced);\n }\n\n void Profiles_Base::DeleteConfirmation_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*e*/)\n {\n winrt::get_self(_Profile)->DeleteProfile();\n }\n\n safe_void_coroutine Profiles_Base::Commandline_Click(const IInspectable&, const RoutedEventArgs&)\n {\n auto lifetime = get_strong();\n\n static constexpr COMDLG_FILTERSPEC supportedFileTypes[] = {\n { L\"Executable Files (*.exe, *.cmd, *.bat)\", L\"*.exe;*.cmd;*.bat\" },\n { L\"All Files (*.*)\", L\"*.*\" }\n };\n\n static constexpr winrt::guid clientGuidExecutables{ 0x2E7E4331, 0x0800, 0x48E6, { 0xB0, 0x17, 0xA1, 0x4C, 0xD8, 0x73, 0xDD, 0x58 } };\n const auto parentHwnd{ reinterpret_cast(_windowRoot.GetHostingWindow()) };\n auto path = co_await OpenFilePicker(parentHwnd, [](auto&& dialog) {\n<|next_version|>\n#include \"Profiles_Base.h\"\n#include \"Profiles_Base.g.cpp\"\n#include \"ProfileViewModel.h\"\n\n#include \n#include \"..\\WinRTUtils\\inc\\Utils.h\"\n\nusing namespace winrt::Windows::UI::Xaml;\nusing namespace winrt::Windows::UI::Xaml::Controls;\nusing namespace winrt::Windows::UI::Xaml::Navigation;\n\nnamespace winrt::Microsoft::Terminal::Settings::Editor::implementation\n{\n Profiles_Base::Profiles_Base()\n {\n InitializeComponent();\n\n const auto startingDirCheckboxTooltip{ ToolTipService::GetToolTip(StartingDirectoryUseParentCheckbox()) };\n Automation::AutomationProperties::SetFullDescription(StartingDirectoryUseParentCheckbox(), unbox_value(startingDirCheckboxTooltip));\n\n Automation::AutomationProperties::SetName(DeleteButton(), RS_(L\"Profile_DeleteButton/Text\"));\n AppearanceNavigator().Content(box_value(RS_(L\"Profile_Appearance/Header\")));\n TerminalNavigator().Content(box_value(RS_(L\"Profile_Terminal/Header\")));\n AdvancedNavigator().Content(box_value(RS_(L\"Profile_Advanced/Header\")));\n }\n\n void Profiles_Base::OnNavigatedTo(const NavigationEventArgs& e)\n {\n const auto args = e.Parameter().as();\n _Profile = args.Profile();\n _windowRoot = args.WindowRoot();\n\n // Check the use parent directory box if the starting directory is empty\n if (_Profile.StartingDirectory().empty())\n {\n StartingDirectoryUseParentCheckbox().IsChecked(true);\n }\n\n _layoutUpdatedRevoker = LayoutUpdated(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {\n // This event fires every time the layout changes, but it is always the last one to fire\n // in any layout change chain. That gives us great flexibility in finding the right point\n // at which to initialize our renderer (and our terminal).\n // Any earlier than the last layout update and we may not know the terminal's starting size.\n\n // Only let this succeed once.\n _layoutUpdatedRevoker.revoke();\n\n if (_Profile.FocusDeleteButton())\n {\n DeleteButton().Focus(FocusState::Programmatic);\n _Profile.FocusDeleteButton(false);\n }\n });\n }\n\n void Profiles_Base::OnNavigatedFrom(const NavigationEventArgs& /*e*/)\n {\n _ViewModelChangedRevoker.revoke();\n }\n\n void Profiles_Base::Appearance_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Appearance);\n }\n\n void Profiles_Base::Terminal_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Terminal);\n }\n\n void Profiles_Base::Advanced_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Advanced);\n }\n\n void Profiles_Base::DeleteConfirmation_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*e*/)\n {\n winrt::get_self(_Profile)->DeleteProfile();\n }\n\n safe_void_coroutine Profiles_Base::Commandline_Click(const IInspectable&, const RoutedEventArgs&)\n {\n auto lifetime = get_strong();\n\n static constexpr COMDLG_FILTERSPEC supportedFileTypes[] = {\n { L\"Executable Files (*.exe, *.cmd, *.bat)\", L\"*.exe;*.cmd;*.bat\" },\n { L\"All Files (*.*)\", L\"*.*\" }\n };\n\n static constexpr winrt::guid clientGuidExecutables{ 0x2E7E4331, 0x0800, 0x48E6, { 0xB0, 0x17, 0xA1, 0x4C, 0xD8, 0x73, 0xDD, 0x58 } };\n const auto parentHwnd{ reinterpret_cast(_windowRoot.GetHostingWindow()) };\n auto path = co_await OpenFilePicker(parentHwnd, [](auto&& dialog) {\n", "current_contents": "#include \"Profiles_Base.h\"\n#include \"Profiles_Base.g.cpp\"\n#include \"ProfileViewModel.h\"\n\n#include \n#include \"..\\WinRTUtils\\inc\\Utils.h\"\n\nusing namespace winrt::Windows::UI::Xaml;\nusing namespace winrt::Windows::UI::Xaml::Controls;\nusing namespace winrt::Windows::UI::Xaml::Navigation;\n\nnamespace winrt::Microsoft::Terminal::Settings::Editor::implementation\n{\n Profiles_Base::Profiles_Base()\n {\n InitializeComponent();\n\n const auto startingDirCheckboxTooltip{ ToolTipService::GetToolTip(StartingDirectoryUseParentCheckbox()) };\n Automation::AutomationProperties::SetFullDescription(StartingDirectoryUseParentCheckbox(), unbox_value(startingDirCheckboxTooltip));\n\n Automation::AutomationProperties::SetName(DeleteButton(), RS_(L\"Profile_DeleteButton/Text\"));\n AppearanceNavigator().Content(box_value(RS_(L\"Profile_Appearance/Header\")));\n TerminalNavigator().Content(box_value(RS_(L\"Profile_Terminal/Header\")));\n AdvancedNavigator().Content(box_value(RS_(L\"Profile_Advanced/Header\")));\n }\n\n void Profiles_Base::OnNavigatedTo(const NavigationEventArgs& e)\n {\n const auto args = e.Parameter().as();\n _Profile = args.Profile();\n _windowRoot = args.WindowRoot();\n\n // Check the use parent directory box if the starting directory is empty\n if (_Profile.StartingDirectory().empty())\n {\n StartingDirectoryUseParentCheckbox().IsChecked(true);\n }\n\n _layoutUpdatedRevoker = LayoutUpdated(winrt::auto_revoke, [this](auto /*s*/, auto /*e*/) {\n // This event fires every time the layout changes, but it is always the last one to fire\n // in any layout change chain. That gives us great flexibility in finding the right point\n // at which to initialize our renderer (and our terminal).\n // Any earlier than the last layout update and we may not know the terminal's starting size.\n\n // Only let this succeed once.\n _layoutUpdatedRevoker.revoke();\n\n if (_Profile.FocusDeleteButton())\n {\n DeleteButton().Focus(FocusState::Programmatic);\n _Profile.FocusDeleteButton(false);\n }\n });\n }\n\n void Profiles_Base::OnNavigatedFrom(const NavigationEventArgs& /*e*/)\n {\n _ViewModelChangedRevoker.revoke();\n }\n\n void Profiles_Base::Appearance_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Appearance);\n }\n\n void Profiles_Base::Advanced_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*args*/)\n {\n _Profile.CurrentPage(ProfileSubPage::Advanced);\n }\n\n void Profiles_Base::DeleteConfirmation_Click(const IInspectable& /*sender*/, const RoutedEventArgs& /*e*/)\n {\n winrt::get_self(_Profile)->DeleteProfile();\n }\n\n safe_void_coroutine Profiles_Base::Commandline_Click(const IInspectable&, const RoutedEventArgs&)\n {\n auto lifetime = get_strong();\n\n static constexpr COMDLG_FILTERSPEC supportedFileTypes[] = {\n { L\"Executable Files (*.exe, *.cmd, *.bat)\", L\"*.exe;*.cmd;*.bat\" },\n { L\"All Files (*.*)\", L\"*.*\" }\n };\n\n static constexpr winrt::guid clientGuidExecutables{ 0x2E7E4331, 0x0800, 0x48E6, { 0xB0, 0x17, 0xA1, 0x4C, 0xD8, 0x73, 0xDD, 0x58 } };\n const auto parentHwnd{ reinterpret_cast(_windowRoot.GetHostingWindow()) };\n auto path = co_await OpenFilePicker(parentHwnd, [](auto&& dialog) {"} {"commit": "54dc2c4432857919a6a87682a09bca06608155ed", "message": "Add tooltips to context menus (#14058)", "old_file": "src/cascadia/TerminalApp/TabBase.cpp", "new_file": "src/cascadia/TerminalApp/TabBase.cpp", "status": "M", "old_contents": " _AppendCloseMenuItems(contextMenuFlyout);\r\n TabViewItem().ContextFlyout(contextMenuFlyout);\r\n }\r\n\r\n // Method Description:\r\n // - Append the close menu items to the context menu flyout\r\n // Arguments:\r\n // - flyout - the menu flyout to which the close items must be appended\r\n // Return Value:\r\n // - \r\n void TabBase::_AppendCloseMenuItems(winrt::Windows::UI::Xaml::Controls::MenuFlyout flyout)\r\n {\r\n auto weakThis{ get_weak() };\r\n\r\n // Close tabs after\r\n _closeTabsAfterMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseTabsAfter();\r\n }\r\n });\r\n _closeTabsAfterMenuItem.Text(RS_(L\"TabCloseAfter\"));\r\n\r\n // Close other tabs\r\n _closeOtherTabsMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseOtherTabs();\r\n }\r\n });\r\n _closeOtherTabsMenuItem.Text(RS_(L\"TabCloseOther\"));\r\n\r\n // Close\r\n Controls::MenuFlyoutItem closeTabMenuItem;\r\n Controls::FontIcon closeSymbol;\r\n closeSymbol.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\r\n closeSymbol.Glyph(L\"\\xE711\");\r\n\r\n closeTabMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseRequestedHandlers(nullptr, nullptr);\r\n }\r\n });\r\n closeTabMenuItem.Text(RS_(L\"TabClose\"));\r\n closeTabMenuItem.Icon(closeSymbol);\r\n\r\n // GH#8238 append the close menu items to the flyout itself until crash in XAML is fixed\r\n //Controls::MenuFlyoutSubItem closeSubMenu;\r\n //closeSubMenu.Text(RS_(L\"TabCloseSubMenu\"));\r\n //closeSubMenu.Items().Append(_closeTabsAfterMenuItem);\r\n //closeSubMenu.Items().Append(_closeOtherTabsMenuItem);\r\n //flyout.Items().Append(closeSubMenu);\r\n flyout.Items().Append(_closeTabsAfterMenuItem);\r\n flyout.Items().Append(_closeOtherTabsMenuItem);\r\n flyout.Items().Append(closeTabMenuItem);\r\n }\r\n\r\n // Method Description:\r\n // - Enable the Close menu items based on tab index and total number of tabs\r\n // Arguments:\r\n // - \r\n // Return Value:\r\n // - \r\n void TabBase::_EnableCloseMenuItems()\r\n {\r\n // close other tabs is enabled only if there are other tabs\r\n _closeOtherTabsMenuItem.IsEnabled(TabViewNumTabs() > 1);\r\n // close tabs after is enabled only if there are other tabs on the right\r\n _closeTabsAfterMenuItem.IsEnabled(TabViewIndex() < TabViewNumTabs() - 1);\r", "new_contents": " _AppendCloseMenuItems(contextMenuFlyout);\r\n TabViewItem().ContextFlyout(contextMenuFlyout);\r\n }\r\n\r\n // Method Description:\r\n // - Append the close menu items to the context menu flyout\r\n // Arguments:\r\n // - flyout - the menu flyout to which the close items must be appended\r\n // Return Value:\r\n // - \r\n void TabBase::_AppendCloseMenuItems(winrt::Windows::UI::Xaml::Controls::MenuFlyout flyout)\r\n {\r\n auto weakThis{ get_weak() };\r\n\r\n // Close tabs after\r\n _closeTabsAfterMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseTabsAfter();\r\n }\r\n });\r\n _closeTabsAfterMenuItem.Text(RS_(L\"TabCloseAfter\"));\r\n const auto closeTabsAfterToolTip = RS_(L\"TabCloseAfterToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(_closeTabsAfterMenuItem, box_value(closeTabsAfterToolTip));\r\n Automation::AutomationProperties::SetHelpText(_closeTabsAfterMenuItem, closeTabsAfterToolTip);\r\n\r\n // Close other tabs\r\n _closeOtherTabsMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseOtherTabs();\r\n }\r\n });\r\n _closeOtherTabsMenuItem.Text(RS_(L\"TabCloseOther\"));\r\n const auto closeOtherTabsToolTip = RS_(L\"TabCloseOtherToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(_closeOtherTabsMenuItem, box_value(closeOtherTabsToolTip));\r\n Automation::AutomationProperties::SetHelpText(_closeOtherTabsMenuItem, closeOtherTabsToolTip);\r\n\r\n // Close\r\n Controls::MenuFlyoutItem closeTabMenuItem;\r\n Controls::FontIcon closeSymbol;\r\n closeSymbol.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\r\n closeSymbol.Glyph(L\"\\xE711\");\r\n\r\n closeTabMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseRequestedHandlers(nullptr, nullptr);\r\n }\r\n });\r\n closeTabMenuItem.Text(RS_(L\"TabClose\"));\r\n closeTabMenuItem.Icon(closeSymbol);\r\n const auto closeTabToolTip = RS_(L\"TabCloseToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(closeTabMenuItem, box_value(closeTabToolTip));\r\n Automation::AutomationProperties::SetHelpText(closeTabMenuItem, closeTabToolTip);\r\n\r\n // GH#8238 append the close menu items to the flyout itself until crash in XAML is fixed\r\n //Controls::MenuFlyoutSubItem closeSubMenu;\r\n //closeSubMenu.Text(RS_(L\"TabCloseSubMenu\"));\r\n //closeSubMenu.Items().Append(_closeTabsAfterMenuItem);\r\n //closeSubMenu.Items().Append(_closeOtherTabsMenuItem);\r\n //flyout.Items().Append(closeSubMenu);\r\n flyout.Items().Append(_closeTabsAfterMenuItem);\r\n flyout.Items().Append(_closeOtherTabsMenuItem);\r\n flyout.Items().Append(closeTabMenuItem);\r\n }\r\n\r\n // Method Description:\r\n // - Enable the Close menu items based on tab index and total number of tabs\r\n // Arguments:\r\n // - \r\n // Return Value:\r\n // - \r\n void TabBase::_EnableCloseMenuItems()\r\n {\r\n // close other tabs is enabled only if there are other tabs\r\n _closeOtherTabsMenuItem.IsEnabled(TabViewNumTabs() > 1);\r\n // close tabs after is enabled only if there are other tabs on the right\r\n _closeTabsAfterMenuItem.IsEnabled(TabViewIndex() < TabViewNumTabs() - 1);\r", "text": "<|original_code|>\n _AppendCloseMenuItems(contextMenuFlyout);\r\n TabViewItem().ContextFlyout(contextMenuFlyout);\r\n }\r\n\r\n // Method Description:\r\n // - Append the close menu items to the context menu flyout\r\n // Arguments:\r\n // - flyout - the menu flyout to which the close items must be appended\r\n // Return Value:\r\n // - \r\n void TabBase::_AppendCloseMenuItems(winrt::Windows::UI::Xaml::Controls::MenuFlyout flyout)\r\n {\r\n auto weakThis{ get_weak() };\r\n\r\n // Close tabs after\r\n _closeTabsAfterMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseTabsAfter();\r\n }\r\n });\r\n _closeTabsAfterMenuItem.Text(RS_(L\"TabCloseAfter\"));\r\n\r\n // Close other tabs\r\n _closeOtherTabsMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseOtherTabs();\r\n }\r\n });\r\n _closeOtherTabsMenuItem.Text(RS_(L\"TabCloseOther\"));\r\n\r\n // Close\r\n Controls::MenuFlyoutItem closeTabMenuItem;\r\n Controls::FontIcon closeSymbol;\r\n closeSymbol.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\r\n closeSymbol.Glyph(L\"\\xE711\");\r\n\r\n closeTabMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseRequestedHandlers(nullptr, nullptr);\r\n }\r\n });\r\n closeTabMenuItem.Text(RS_(L\"TabClose\"));\r\n closeTabMenuItem.Icon(closeSymbol);\r\n\r\n // GH#8238 append the close menu items to the flyout itself until crash in XAML is fixed\r\n //Controls::MenuFlyoutSubItem closeSubMenu;\r\n //closeSubMenu.Text(RS_(L\"TabCloseSubMenu\"));\r\n //closeSubMenu.Items().Append(_closeTabsAfterMenuItem);\r\n //closeSubMenu.Items().Append(_closeOtherTabsMenuItem);\r\n //flyout.Items().Append(closeSubMenu);\r\n flyout.Items().Append(_closeTabsAfterMenuItem);\r\n flyout.Items().Append(_closeOtherTabsMenuItem);\r\n flyout.Items().Append(closeTabMenuItem);\r\n }\r\n\r\n // Method Description:\r\n // - Enable the Close menu items based on tab index and total number of tabs\r\n // Arguments:\r\n // - \r\n // Return Value:\r\n // - \r\n void TabBase::_EnableCloseMenuItems()\r\n {\r\n // close other tabs is enabled only if there are other tabs\r\n _closeOtherTabsMenuItem.IsEnabled(TabViewNumTabs() > 1);\r\n // close tabs after is enabled only if there are other tabs on the right\r\n _closeTabsAfterMenuItem.IsEnabled(TabViewIndex() < TabViewNumTabs() - 1);\r\n<|edits_diff|>\n--- src/cascadia/TerminalApp/TabBase.cpp\n+++ src/cascadia/TerminalApp/TabBase.cpp\n@@ -20,6 +20,10 @@\n }\n });\n _closeTabsAfterMenuItem.Text(RS_(L\"TabCloseAfter\"));\n+ const auto closeTabsAfterToolTip = RS_(L\"TabCloseAfterToolTip\");\n+\n+ WUX::Controls::ToolTipService::SetToolTip(_closeTabsAfterMenuItem, box_value(closeTabsAfterToolTip));\n+ Automation::AutomationProperties::SetHelpText(_closeTabsAfterMenuItem, closeTabsAfterToolTip);\n \n // Close other tabs\n _closeOtherTabsMenuItem.Click([weakThis](auto&&, auto&&) {\n@@ -29,6 +33,10 @@\n }\n });\n _closeOtherTabsMenuItem.Text(RS_(L\"TabCloseOther\"));\n+ const auto closeOtherTabsToolTip = RS_(L\"TabCloseOtherToolTip\");\n+\n+ WUX::Controls::ToolTipService::SetToolTip(_closeOtherTabsMenuItem, box_value(closeOtherTabsToolTip));\n+ Automation::AutomationProperties::SetHelpText(_closeOtherTabsMenuItem, closeOtherTabsToolTip);\n \n // Close\n Controls::MenuFlyoutItem closeTabMenuItem;\n<|current_version|>\n _AppendCloseMenuItems(contextMenuFlyout);\r\n TabViewItem().ContextFlyout(contextMenuFlyout);\r\n }\r\n\r\n // Method Description:\r\n // - Append the close menu items to the context menu flyout\r\n // Arguments:\r\n // - flyout - the menu flyout to which the close items must be appended\r\n // Return Value:\r\n // - \r\n void TabBase::_AppendCloseMenuItems(winrt::Windows::UI::Xaml::Controls::MenuFlyout flyout)\r\n {\r\n auto weakThis{ get_weak() };\r\n\r\n // Close tabs after\r\n _closeTabsAfterMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseTabsAfter();\r\n }\r\n });\r\n _closeTabsAfterMenuItem.Text(RS_(L\"TabCloseAfter\"));\r\n const auto closeTabsAfterToolTip = RS_(L\"TabCloseAfterToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(_closeTabsAfterMenuItem, box_value(closeTabsAfterToolTip));\r\n Automation::AutomationProperties::SetHelpText(_closeTabsAfterMenuItem, closeTabsAfterToolTip);\r\n\r\n // Close other tabs\r\n _closeOtherTabsMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseOtherTabs();\r\n }\r\n });\r\n _closeOtherTabsMenuItem.Text(RS_(L\"TabCloseOther\"));\r\n const auto closeOtherTabsToolTip = RS_(L\"TabCloseOtherToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(_closeOtherTabsMenuItem, box_value(closeOtherTabsToolTip));\r\n Automation::AutomationProperties::SetHelpText(_closeOtherTabsMenuItem, closeOtherTabsToolTip);\r\n\r\n // Close\r\n Controls::MenuFlyoutItem closeTabMenuItem;\r\n Controls::FontIcon closeSymbol;\r\n closeSymbol.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\r\n closeSymbol.Glyph(L\"\\xE711\");\r\n\r\n closeTabMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseRequestedHandlers(nullptr, nullptr);\r\n }\r\n });\r\n closeTabMenuItem.Text(RS_(L\"TabClose\"));\r\n closeTabMenuItem.Icon(closeSymbol);\r\n\r\n // GH#8238 append the close menu items to the flyout itself until crash in XAML is fixed\r\n //Controls::MenuFlyoutSubItem closeSubMenu;\r\n //closeSubMenu.Text(RS_(L\"TabCloseSubMenu\"));\r\n //closeSubMenu.Items().Append(_closeTabsAfterMenuItem);\r\n //closeSubMenu.Items().Append(_closeOtherTabsMenuItem);\r\n //flyout.Items().Append(closeSubMenu);\r\n flyout.Items().Append(_closeTabsAfterMenuItem);\r\n flyout.Items().Append(_closeOtherTabsMenuItem);\r\n flyout.Items().Append(closeTabMenuItem);\r\n }\r\n\r\n // Method Description:\r\n // - Enable the Close menu items based on tab index and total number of tabs\r\n // Arguments:\r\n // - \r\n // Return Value:\r\n // - \r\n void TabBase::_EnableCloseMenuItems()\r\n {\r\n // close other tabs is enabled only if there are other tabs\r\n _closeOtherTabsMenuItem.IsEnabled(TabViewNumTabs() > 1);\r\n // close tabs after is enabled only if there are other tabs on the right\r\n _closeTabsAfterMenuItem.IsEnabled(TabViewIndex() < TabViewNumTabs() - 1);\r\n<|next_version|>\n _AppendCloseMenuItems(contextMenuFlyout);\r\n TabViewItem().ContextFlyout(contextMenuFlyout);\r\n }\r\n\r\n // Method Description:\r\n // - Append the close menu items to the context menu flyout\r\n // Arguments:\r\n // - flyout - the menu flyout to which the close items must be appended\r\n // Return Value:\r\n // - \r\n void TabBase::_AppendCloseMenuItems(winrt::Windows::UI::Xaml::Controls::MenuFlyout flyout)\r\n {\r\n auto weakThis{ get_weak() };\r\n\r\n // Close tabs after\r\n _closeTabsAfterMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseTabsAfter();\r\n }\r\n });\r\n _closeTabsAfterMenuItem.Text(RS_(L\"TabCloseAfter\"));\r\n const auto closeTabsAfterToolTip = RS_(L\"TabCloseAfterToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(_closeTabsAfterMenuItem, box_value(closeTabsAfterToolTip));\r\n Automation::AutomationProperties::SetHelpText(_closeTabsAfterMenuItem, closeTabsAfterToolTip);\r\n\r\n // Close other tabs\r\n _closeOtherTabsMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseOtherTabs();\r\n }\r\n });\r\n _closeOtherTabsMenuItem.Text(RS_(L\"TabCloseOther\"));\r\n const auto closeOtherTabsToolTip = RS_(L\"TabCloseOtherToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(_closeOtherTabsMenuItem, box_value(closeOtherTabsToolTip));\r\n Automation::AutomationProperties::SetHelpText(_closeOtherTabsMenuItem, closeOtherTabsToolTip);\r\n\r\n // Close\r\n Controls::MenuFlyoutItem closeTabMenuItem;\r\n Controls::FontIcon closeSymbol;\r\n closeSymbol.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\r\n closeSymbol.Glyph(L\"\\xE711\");\r\n\r\n closeTabMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseRequestedHandlers(nullptr, nullptr);\r\n }\r\n });\r\n closeTabMenuItem.Text(RS_(L\"TabClose\"));\r\n closeTabMenuItem.Icon(closeSymbol);\r\n const auto closeTabToolTip = RS_(L\"TabCloseToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(closeTabMenuItem, box_value(closeTabToolTip));\r\n Automation::AutomationProperties::SetHelpText(closeTabMenuItem, closeTabToolTip);\r\n\r\n // GH#8238 append the close menu items to the flyout itself until crash in XAML is fixed\r\n //Controls::MenuFlyoutSubItem closeSubMenu;\r\n //closeSubMenu.Text(RS_(L\"TabCloseSubMenu\"));\r\n //closeSubMenu.Items().Append(_closeTabsAfterMenuItem);\r\n //closeSubMenu.Items().Append(_closeOtherTabsMenuItem);\r\n //flyout.Items().Append(closeSubMenu);\r\n flyout.Items().Append(_closeTabsAfterMenuItem);\r\n flyout.Items().Append(_closeOtherTabsMenuItem);\r\n flyout.Items().Append(closeTabMenuItem);\r\n }\r\n\r\n // Method Description:\r\n // - Enable the Close menu items based on tab index and total number of tabs\r\n // Arguments:\r\n // - \r\n // Return Value:\r\n // - \r\n void TabBase::_EnableCloseMenuItems()\r\n {\r\n // close other tabs is enabled only if there are other tabs\r\n _closeOtherTabsMenuItem.IsEnabled(TabViewNumTabs() > 1);\r\n // close tabs after is enabled only if there are other tabs on the right\r\n _closeTabsAfterMenuItem.IsEnabled(TabViewIndex() < TabViewNumTabs() - 1);\r\n", "current_contents": " _AppendCloseMenuItems(contextMenuFlyout);\r\n TabViewItem().ContextFlyout(contextMenuFlyout);\r\n }\r\n\r\n // Method Description:\r\n // - Append the close menu items to the context menu flyout\r\n // Arguments:\r\n // - flyout - the menu flyout to which the close items must be appended\r\n // Return Value:\r\n // - \r\n void TabBase::_AppendCloseMenuItems(winrt::Windows::UI::Xaml::Controls::MenuFlyout flyout)\r\n {\r\n auto weakThis{ get_weak() };\r\n\r\n // Close tabs after\r\n _closeTabsAfterMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseTabsAfter();\r\n }\r\n });\r\n _closeTabsAfterMenuItem.Text(RS_(L\"TabCloseAfter\"));\r\n const auto closeTabsAfterToolTip = RS_(L\"TabCloseAfterToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(_closeTabsAfterMenuItem, box_value(closeTabsAfterToolTip));\r\n Automation::AutomationProperties::SetHelpText(_closeTabsAfterMenuItem, closeTabsAfterToolTip);\r\n\r\n // Close other tabs\r\n _closeOtherTabsMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseOtherTabs();\r\n }\r\n });\r\n _closeOtherTabsMenuItem.Text(RS_(L\"TabCloseOther\"));\r\n const auto closeOtherTabsToolTip = RS_(L\"TabCloseOtherToolTip\");\r\n\r\n WUX::Controls::ToolTipService::SetToolTip(_closeOtherTabsMenuItem, box_value(closeOtherTabsToolTip));\r\n Automation::AutomationProperties::SetHelpText(_closeOtherTabsMenuItem, closeOtherTabsToolTip);\r\n\r\n // Close\r\n Controls::MenuFlyoutItem closeTabMenuItem;\r\n Controls::FontIcon closeSymbol;\r\n closeSymbol.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\r\n closeSymbol.Glyph(L\"\\xE711\");\r\n\r\n closeTabMenuItem.Click([weakThis](auto&&, auto&&) {\r\n if (auto tab{ weakThis.get() })\r\n {\r\n tab->_CloseRequestedHandlers(nullptr, nullptr);\r\n }\r\n });\r\n closeTabMenuItem.Text(RS_(L\"TabClose\"));\r\n closeTabMenuItem.Icon(closeSymbol);\r\n\r\n // GH#8238 append the close menu items to the flyout itself until crash in XAML is fixed\r\n //Controls::MenuFlyoutSubItem closeSubMenu;\r\n //closeSubMenu.Text(RS_(L\"TabCloseSubMenu\"));\r\n //closeSubMenu.Items().Append(_closeTabsAfterMenuItem);\r\n //closeSubMenu.Items().Append(_closeOtherTabsMenuItem);\r\n //flyout.Items().Append(closeSubMenu);\r\n flyout.Items().Append(_closeTabsAfterMenuItem);\r\n flyout.Items().Append(_closeOtherTabsMenuItem);\r\n flyout.Items().Append(closeTabMenuItem);\r\n }\r\n\r\n // Method Description:\r\n // - Enable the Close menu items based on tab index and total number of tabs\r\n // Arguments:\r\n // - \r\n // Return Value:\r\n // - \r\n void TabBase::_EnableCloseMenuItems()\r\n {\r\n // close other tabs is enabled only if there are other tabs\r\n _closeOtherTabsMenuItem.IsEnabled(TabViewNumTabs() > 1);\r\n // close tabs after is enabled only if there are other tabs on the right\r\n _closeTabsAfterMenuItem.IsEnabled(TabViewIndex() < TabViewNumTabs() - 1);\r"} {"commit": "54dc2c4432857919a6a87682a09bca06608155ed", "message": "Add tooltips to context menus (#14058)", "old_file": "src/cascadia/TerminalApp/TerminalPage.cpp", "new_file": "src/cascadia/TerminalApp/TerminalPage.cpp", "status": "M", "old_contents": "\n // add menu separator\n auto separatorItem = WUX::Controls::MenuFlyoutSeparator{};\n newTabFlyout.Items().Append(separatorItem);\n\n // add static items\n {\n // GH#2455 - Make sure to try/catch calls to Application::Current,\n // because that _won't_ be an instance of TerminalApp::App in the\n // LocalTests\n auto isUwp = false;\n try\n {\n isUwp = ::winrt::Windows::UI::Xaml::Application::Current().as<::winrt::TerminalApp::App>().Logic().IsUwp();\n }\n CATCH_LOG();\n\n if (!isUwp)\n {\n // Create the settings button.\n auto settingsItem = WUX::Controls::MenuFlyoutItem{};\n settingsItem.Text(RS_(L\"SettingsMenuItem\"));\n\n WUX::Controls::SymbolIcon ico{};\n ico.Symbol(WUX::Controls::Symbol::Setting);\n settingsItem.Icon(ico);\n\n settingsItem.Click({ this, &TerminalPage::_SettingsButtonOnClick });\n newTabFlyout.Items().Append(settingsItem);\n\n const auto settingsKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::OpenSettings, OpenSettingsArgs{ SettingsTarget::SettingsUI }) };\n if (settingsKeyChord)\n {\n _SetAcceleratorForMenuItem(settingsItem, settingsKeyChord);\n }\n\n // Create the command palette button.\n auto commandPaletteFlyout = WUX::Controls::MenuFlyoutItem{};\n commandPaletteFlyout.Text(RS_(L\"CommandPaletteMenuItem\"));\n\n WUX::Controls::FontIcon commandPaletteIcon{};\n commandPaletteIcon.Glyph(L\"\\xE945\");\n commandPaletteIcon.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\n commandPaletteFlyout.Icon(commandPaletteIcon);\n\n commandPaletteFlyout.Click({ this, &TerminalPage::_CommandPaletteButtonOnClick });\n newTabFlyout.Items().Append(commandPaletteFlyout);\n\n const auto commandPaletteKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::ToggleCommandPalette) };\n if (commandPaletteKeyChord)\n {\n _SetAcceleratorForMenuItem(commandPaletteFlyout, commandPaletteKeyChord);\n }\n }\n\n // Create the about button.\n auto aboutFlyout = WUX::Controls::MenuFlyoutItem{};\n aboutFlyout.Text(RS_(L\"AboutMenuItem\"));\n\n WUX::Controls::SymbolIcon aboutIcon{};\n aboutIcon.Symbol(WUX::Controls::Symbol::Help);\n aboutFlyout.Icon(aboutIcon);\n\n aboutFlyout.Click({ this, &TerminalPage::_AboutButtonOnClick });\n newTabFlyout.Items().Append(aboutFlyout);\n }\n\n // Before opening the fly-out set focus on the current tab\n // so no matter how fly-out is closed later on the focus will return to some tab.\n // We cannot do it on closing because if the window loses focus (alt+tab)\n // the closing event is not fired.\n // It is important to set the focus on the tab\n // Since the previous focus location might be discarded in the background,\n // e.g., the command palette will be dismissed by the menu,\n // and then closing the fly-out will move the focus to wrong location.\n newTabFlyout.Opening([this](auto&&, auto&&) {\n _FocusCurrentTab(true);\n });\n _newTabButton.Flyout(newTabFlyout);\n }\n\n // Function Description:", "new_contents": "\n // add menu separator\n auto separatorItem = WUX::Controls::MenuFlyoutSeparator{};\n newTabFlyout.Items().Append(separatorItem);\n\n // add static items\n {\n // GH#2455 - Make sure to try/catch calls to Application::Current,\n // because that _won't_ be an instance of TerminalApp::App in the\n // LocalTests\n auto isUwp = false;\n try\n {\n isUwp = ::winrt::Windows::UI::Xaml::Application::Current().as<::winrt::TerminalApp::App>().Logic().IsUwp();\n }\n CATCH_LOG();\n\n if (!isUwp)\n {\n // Create the settings button.\n auto settingsItem = WUX::Controls::MenuFlyoutItem{};\n settingsItem.Text(RS_(L\"SettingsMenuItem\"));\n const auto settingsToolTip = RS_(L\"SettingsToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(settingsItem, box_value(settingsToolTip));\n Automation::AutomationProperties::SetHelpText(settingsItem, settingsToolTip);\n\n WUX::Controls::SymbolIcon ico{};\n ico.Symbol(WUX::Controls::Symbol::Setting);\n settingsItem.Icon(ico);\n\n settingsItem.Click({ this, &TerminalPage::_SettingsButtonOnClick });\n newTabFlyout.Items().Append(settingsItem);\n\n const auto settingsKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::OpenSettings, OpenSettingsArgs{ SettingsTarget::SettingsUI }) };\n if (settingsKeyChord)\n {\n _SetAcceleratorForMenuItem(settingsItem, settingsKeyChord);\n }\n\n // Create the command palette button.\n auto commandPaletteFlyout = WUX::Controls::MenuFlyoutItem{};\n commandPaletteFlyout.Text(RS_(L\"CommandPaletteMenuItem\"));\n const auto commandPaletteToolTip = RS_(L\"CommandPaletteToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(commandPaletteFlyout, box_value(commandPaletteToolTip));\n Automation::AutomationProperties::SetHelpText(commandPaletteFlyout, commandPaletteToolTip);\n\n WUX::Controls::FontIcon commandPaletteIcon{};\n commandPaletteIcon.Glyph(L\"\\xE945\");\n commandPaletteIcon.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\n commandPaletteFlyout.Icon(commandPaletteIcon);\n\n commandPaletteFlyout.Click({ this, &TerminalPage::_CommandPaletteButtonOnClick });\n newTabFlyout.Items().Append(commandPaletteFlyout);\n\n const auto commandPaletteKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::ToggleCommandPalette) };\n if (commandPaletteKeyChord)\n {\n _SetAcceleratorForMenuItem(commandPaletteFlyout, commandPaletteKeyChord);\n }\n }\n\n // Create the about button.\n auto aboutFlyout = WUX::Controls::MenuFlyoutItem{};\n aboutFlyout.Text(RS_(L\"AboutMenuItem\"));\n const auto aboutToolTip = RS_(L\"AboutToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(aboutFlyout, box_value(aboutToolTip));\n Automation::AutomationProperties::SetHelpText(aboutFlyout, aboutToolTip);\n\n WUX::Controls::SymbolIcon aboutIcon{};\n aboutIcon.Symbol(WUX::Controls::Symbol::Help);\n aboutFlyout.Icon(aboutIcon);\n\n aboutFlyout.Click({ this, &TerminalPage::_AboutButtonOnClick });\n newTabFlyout.Items().Append(aboutFlyout);\n }\n\n // Before opening the fly-out set focus on the current tab\n // so no matter how fly-out is closed later on the focus will return to some tab.\n // We cannot do it on closing because if the window loses focus (alt+tab)\n // the closing event is not fired.\n // It is important to set the focus on the tab\n // Since the previous focus location might be discarded in the background,\n // e.g., the command palette will be dismissed by the menu,\n // and then closing the fly-out will move the focus to wrong location.\n newTabFlyout.Opening([this](auto&&, auto&&) {\n _FocusCurrentTab(true);\n });\n _newTabButton.Flyout(newTabFlyout);\n }\n\n // Function Description:", "text": "<|original_code|>\n\n // add menu separator\n auto separatorItem = WUX::Controls::MenuFlyoutSeparator{};\n newTabFlyout.Items().Append(separatorItem);\n\n // add static items\n {\n // GH#2455 - Make sure to try/catch calls to Application::Current,\n // because that _won't_ be an instance of TerminalApp::App in the\n // LocalTests\n auto isUwp = false;\n try\n {\n isUwp = ::winrt::Windows::UI::Xaml::Application::Current().as<::winrt::TerminalApp::App>().Logic().IsUwp();\n }\n CATCH_LOG();\n\n if (!isUwp)\n {\n // Create the settings button.\n auto settingsItem = WUX::Controls::MenuFlyoutItem{};\n settingsItem.Text(RS_(L\"SettingsMenuItem\"));\n\n WUX::Controls::SymbolIcon ico{};\n ico.Symbol(WUX::Controls::Symbol::Setting);\n settingsItem.Icon(ico);\n\n settingsItem.Click({ this, &TerminalPage::_SettingsButtonOnClick });\n newTabFlyout.Items().Append(settingsItem);\n\n const auto settingsKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::OpenSettings, OpenSettingsArgs{ SettingsTarget::SettingsUI }) };\n if (settingsKeyChord)\n {\n _SetAcceleratorForMenuItem(settingsItem, settingsKeyChord);\n }\n\n // Create the command palette button.\n auto commandPaletteFlyout = WUX::Controls::MenuFlyoutItem{};\n commandPaletteFlyout.Text(RS_(L\"CommandPaletteMenuItem\"));\n\n WUX::Controls::FontIcon commandPaletteIcon{};\n commandPaletteIcon.Glyph(L\"\\xE945\");\n commandPaletteIcon.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\n commandPaletteFlyout.Icon(commandPaletteIcon);\n\n commandPaletteFlyout.Click({ this, &TerminalPage::_CommandPaletteButtonOnClick });\n newTabFlyout.Items().Append(commandPaletteFlyout);\n\n const auto commandPaletteKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::ToggleCommandPalette) };\n if (commandPaletteKeyChord)\n {\n _SetAcceleratorForMenuItem(commandPaletteFlyout, commandPaletteKeyChord);\n }\n }\n\n // Create the about button.\n auto aboutFlyout = WUX::Controls::MenuFlyoutItem{};\n aboutFlyout.Text(RS_(L\"AboutMenuItem\"));\n\n WUX::Controls::SymbolIcon aboutIcon{};\n aboutIcon.Symbol(WUX::Controls::Symbol::Help);\n aboutFlyout.Icon(aboutIcon);\n\n aboutFlyout.Click({ this, &TerminalPage::_AboutButtonOnClick });\n newTabFlyout.Items().Append(aboutFlyout);\n }\n\n // Before opening the fly-out set focus on the current tab\n // so no matter how fly-out is closed later on the focus will return to some tab.\n // We cannot do it on closing because if the window loses focus (alt+tab)\n // the closing event is not fired.\n // It is important to set the focus on the tab\n // Since the previous focus location might be discarded in the background,\n // e.g., the command palette will be dismissed by the menu,\n // and then closing the fly-out will move the focus to wrong location.\n newTabFlyout.Opening([this](auto&&, auto&&) {\n _FocusCurrentTab(true);\n });\n _newTabButton.Flyout(newTabFlyout);\n }\n\n // Function Description:\n<|edits_diff|>\n--- src/cascadia/TerminalApp/TerminalPage.cpp\n+++ src/cascadia/TerminalApp/TerminalPage.cpp\n@@ -20,6 +20,10 @@\n // Create the settings button.\n auto settingsItem = WUX::Controls::MenuFlyoutItem{};\n settingsItem.Text(RS_(L\"SettingsMenuItem\"));\n+ const auto settingsToolTip = RS_(L\"SettingsToolTip\");\n+\n+ WUX::Controls::ToolTipService::SetToolTip(settingsItem, box_value(settingsToolTip));\n+ Automation::AutomationProperties::SetHelpText(settingsItem, settingsToolTip);\n \n WUX::Controls::SymbolIcon ico{};\n ico.Symbol(WUX::Controls::Symbol::Setting);\n@@ -37,6 +41,10 @@\n // Create the command palette button.\n auto commandPaletteFlyout = WUX::Controls::MenuFlyoutItem{};\n commandPaletteFlyout.Text(RS_(L\"CommandPaletteMenuItem\"));\n+ const auto commandPaletteToolTip = RS_(L\"CommandPaletteToolTip\");\n+\n+ WUX::Controls::ToolTipService::SetToolTip(commandPaletteFlyout, box_value(commandPaletteToolTip));\n+ Automation::AutomationProperties::SetHelpText(commandPaletteFlyout, commandPaletteToolTip);\n \n WUX::Controls::FontIcon commandPaletteIcon{};\n commandPaletteIcon.Glyph(L\"\\xE945\");\n<|current_version|>\n\n // add menu separator\n auto separatorItem = WUX::Controls::MenuFlyoutSeparator{};\n newTabFlyout.Items().Append(separatorItem);\n\n // add static items\n {\n // GH#2455 - Make sure to try/catch calls to Application::Current,\n // because that _won't_ be an instance of TerminalApp::App in the\n // LocalTests\n auto isUwp = false;\n try\n {\n isUwp = ::winrt::Windows::UI::Xaml::Application::Current().as<::winrt::TerminalApp::App>().Logic().IsUwp();\n }\n CATCH_LOG();\n\n if (!isUwp)\n {\n // Create the settings button.\n auto settingsItem = WUX::Controls::MenuFlyoutItem{};\n settingsItem.Text(RS_(L\"SettingsMenuItem\"));\n const auto settingsToolTip = RS_(L\"SettingsToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(settingsItem, box_value(settingsToolTip));\n Automation::AutomationProperties::SetHelpText(settingsItem, settingsToolTip);\n\n WUX::Controls::SymbolIcon ico{};\n ico.Symbol(WUX::Controls::Symbol::Setting);\n settingsItem.Icon(ico);\n\n settingsItem.Click({ this, &TerminalPage::_SettingsButtonOnClick });\n newTabFlyout.Items().Append(settingsItem);\n\n const auto settingsKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::OpenSettings, OpenSettingsArgs{ SettingsTarget::SettingsUI }) };\n if (settingsKeyChord)\n {\n _SetAcceleratorForMenuItem(settingsItem, settingsKeyChord);\n }\n\n // Create the command palette button.\n auto commandPaletteFlyout = WUX::Controls::MenuFlyoutItem{};\n commandPaletteFlyout.Text(RS_(L\"CommandPaletteMenuItem\"));\n const auto commandPaletteToolTip = RS_(L\"CommandPaletteToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(commandPaletteFlyout, box_value(commandPaletteToolTip));\n Automation::AutomationProperties::SetHelpText(commandPaletteFlyout, commandPaletteToolTip);\n\n WUX::Controls::FontIcon commandPaletteIcon{};\n commandPaletteIcon.Glyph(L\"\\xE945\");\n commandPaletteIcon.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\n commandPaletteFlyout.Icon(commandPaletteIcon);\n\n commandPaletteFlyout.Click({ this, &TerminalPage::_CommandPaletteButtonOnClick });\n newTabFlyout.Items().Append(commandPaletteFlyout);\n\n const auto commandPaletteKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::ToggleCommandPalette) };\n if (commandPaletteKeyChord)\n {\n _SetAcceleratorForMenuItem(commandPaletteFlyout, commandPaletteKeyChord);\n }\n }\n\n // Create the about button.\n auto aboutFlyout = WUX::Controls::MenuFlyoutItem{};\n aboutFlyout.Text(RS_(L\"AboutMenuItem\"));\n\n WUX::Controls::SymbolIcon aboutIcon{};\n aboutIcon.Symbol(WUX::Controls::Symbol::Help);\n aboutFlyout.Icon(aboutIcon);\n\n aboutFlyout.Click({ this, &TerminalPage::_AboutButtonOnClick });\n newTabFlyout.Items().Append(aboutFlyout);\n }\n\n // Before opening the fly-out set focus on the current tab\n // so no matter how fly-out is closed later on the focus will return to some tab.\n // We cannot do it on closing because if the window loses focus (alt+tab)\n // the closing event is not fired.\n // It is important to set the focus on the tab\n // Since the previous focus location might be discarded in the background,\n // e.g., the command palette will be dismissed by the menu,\n // and then closing the fly-out will move the focus to wrong location.\n newTabFlyout.Opening([this](auto&&, auto&&) {\n _FocusCurrentTab(true);\n });\n _newTabButton.Flyout(newTabFlyout);\n }\n\n // Function Description:\n<|next_version|>\n\n // add menu separator\n auto separatorItem = WUX::Controls::MenuFlyoutSeparator{};\n newTabFlyout.Items().Append(separatorItem);\n\n // add static items\n {\n // GH#2455 - Make sure to try/catch calls to Application::Current,\n // because that _won't_ be an instance of TerminalApp::App in the\n // LocalTests\n auto isUwp = false;\n try\n {\n isUwp = ::winrt::Windows::UI::Xaml::Application::Current().as<::winrt::TerminalApp::App>().Logic().IsUwp();\n }\n CATCH_LOG();\n\n if (!isUwp)\n {\n // Create the settings button.\n auto settingsItem = WUX::Controls::MenuFlyoutItem{};\n settingsItem.Text(RS_(L\"SettingsMenuItem\"));\n const auto settingsToolTip = RS_(L\"SettingsToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(settingsItem, box_value(settingsToolTip));\n Automation::AutomationProperties::SetHelpText(settingsItem, settingsToolTip);\n\n WUX::Controls::SymbolIcon ico{};\n ico.Symbol(WUX::Controls::Symbol::Setting);\n settingsItem.Icon(ico);\n\n settingsItem.Click({ this, &TerminalPage::_SettingsButtonOnClick });\n newTabFlyout.Items().Append(settingsItem);\n\n const auto settingsKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::OpenSettings, OpenSettingsArgs{ SettingsTarget::SettingsUI }) };\n if (settingsKeyChord)\n {\n _SetAcceleratorForMenuItem(settingsItem, settingsKeyChord);\n }\n\n // Create the command palette button.\n auto commandPaletteFlyout = WUX::Controls::MenuFlyoutItem{};\n commandPaletteFlyout.Text(RS_(L\"CommandPaletteMenuItem\"));\n const auto commandPaletteToolTip = RS_(L\"CommandPaletteToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(commandPaletteFlyout, box_value(commandPaletteToolTip));\n Automation::AutomationProperties::SetHelpText(commandPaletteFlyout, commandPaletteToolTip);\n\n WUX::Controls::FontIcon commandPaletteIcon{};\n commandPaletteIcon.Glyph(L\"\\xE945\");\n commandPaletteIcon.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\n commandPaletteFlyout.Icon(commandPaletteIcon);\n\n commandPaletteFlyout.Click({ this, &TerminalPage::_CommandPaletteButtonOnClick });\n newTabFlyout.Items().Append(commandPaletteFlyout);\n\n const auto commandPaletteKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::ToggleCommandPalette) };\n if (commandPaletteKeyChord)\n {\n _SetAcceleratorForMenuItem(commandPaletteFlyout, commandPaletteKeyChord);\n }\n }\n\n // Create the about button.\n auto aboutFlyout = WUX::Controls::MenuFlyoutItem{};\n aboutFlyout.Text(RS_(L\"AboutMenuItem\"));\n const auto aboutToolTip = RS_(L\"AboutToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(aboutFlyout, box_value(aboutToolTip));\n Automation::AutomationProperties::SetHelpText(aboutFlyout, aboutToolTip);\n\n WUX::Controls::SymbolIcon aboutIcon{};\n aboutIcon.Symbol(WUX::Controls::Symbol::Help);\n aboutFlyout.Icon(aboutIcon);\n\n aboutFlyout.Click({ this, &TerminalPage::_AboutButtonOnClick });\n newTabFlyout.Items().Append(aboutFlyout);\n }\n\n // Before opening the fly-out set focus on the current tab\n // so no matter how fly-out is closed later on the focus will return to some tab.\n // We cannot do it on closing because if the window loses focus (alt+tab)\n // the closing event is not fired.\n // It is important to set the focus on the tab\n // Since the previous focus location might be discarded in the background,\n // e.g., the command palette will be dismissed by the menu,\n // and then closing the fly-out will move the focus to wrong location.\n newTabFlyout.Opening([this](auto&&, auto&&) {\n _FocusCurrentTab(true);\n });\n _newTabButton.Flyout(newTabFlyout);\n }\n\n // Function Description:\n", "current_contents": "\n // add menu separator\n auto separatorItem = WUX::Controls::MenuFlyoutSeparator{};\n newTabFlyout.Items().Append(separatorItem);\n\n // add static items\n {\n // GH#2455 - Make sure to try/catch calls to Application::Current,\n // because that _won't_ be an instance of TerminalApp::App in the\n // LocalTests\n auto isUwp = false;\n try\n {\n isUwp = ::winrt::Windows::UI::Xaml::Application::Current().as<::winrt::TerminalApp::App>().Logic().IsUwp();\n }\n CATCH_LOG();\n\n if (!isUwp)\n {\n // Create the settings button.\n auto settingsItem = WUX::Controls::MenuFlyoutItem{};\n settingsItem.Text(RS_(L\"SettingsMenuItem\"));\n const auto settingsToolTip = RS_(L\"SettingsToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(settingsItem, box_value(settingsToolTip));\n Automation::AutomationProperties::SetHelpText(settingsItem, settingsToolTip);\n\n WUX::Controls::SymbolIcon ico{};\n ico.Symbol(WUX::Controls::Symbol::Setting);\n settingsItem.Icon(ico);\n\n settingsItem.Click({ this, &TerminalPage::_SettingsButtonOnClick });\n newTabFlyout.Items().Append(settingsItem);\n\n const auto settingsKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::OpenSettings, OpenSettingsArgs{ SettingsTarget::SettingsUI }) };\n if (settingsKeyChord)\n {\n _SetAcceleratorForMenuItem(settingsItem, settingsKeyChord);\n }\n\n // Create the command palette button.\n auto commandPaletteFlyout = WUX::Controls::MenuFlyoutItem{};\n commandPaletteFlyout.Text(RS_(L\"CommandPaletteMenuItem\"));\n const auto commandPaletteToolTip = RS_(L\"CommandPaletteToolTip\");\n\n WUX::Controls::ToolTipService::SetToolTip(commandPaletteFlyout, box_value(commandPaletteToolTip));\n Automation::AutomationProperties::SetHelpText(commandPaletteFlyout, commandPaletteToolTip);\n\n WUX::Controls::FontIcon commandPaletteIcon{};\n commandPaletteIcon.Glyph(L\"\\xE945\");\n commandPaletteIcon.FontFamily(Media::FontFamily{ L\"Segoe Fluent Icons, Segoe MDL2 Assets\" });\n commandPaletteFlyout.Icon(commandPaletteIcon);\n\n commandPaletteFlyout.Click({ this, &TerminalPage::_CommandPaletteButtonOnClick });\n newTabFlyout.Items().Append(commandPaletteFlyout);\n\n const auto commandPaletteKeyChord{ actionMap.GetKeyBindingForAction(ShortcutAction::ToggleCommandPalette) };\n if (commandPaletteKeyChord)\n {\n _SetAcceleratorForMenuItem(commandPaletteFlyout, commandPaletteKeyChord);\n }\n }\n\n // Create the about button.\n auto aboutFlyout = WUX::Controls::MenuFlyoutItem{};\n aboutFlyout.Text(RS_(L\"AboutMenuItem\"));\n\n WUX::Controls::SymbolIcon aboutIcon{};\n aboutIcon.Symbol(WUX::Controls::Symbol::Help);\n aboutFlyout.Icon(aboutIcon);\n\n aboutFlyout.Click({ this, &TerminalPage::_AboutButtonOnClick });\n newTabFlyout.Items().Append(aboutFlyout);\n }\n\n // Before opening the fly-out set focus on the current tab\n // so no matter how fly-out is closed later on the focus will return to some tab.\n // We cannot do it on closing because if the window loses focus (alt+tab)\n // the closing event is not fired.\n // It is important to set the focus on the tab\n // Since the previous focus location might be discarded in the background,\n // e.g., the command palette will be dismissed by the menu,\n // and then closing the fly-out will move the focus to wrong location.\n newTabFlyout.Opening([this](auto&&, auto&&) {\n _FocusCurrentTab(true);\n });\n _newTabButton.Flyout(newTabFlyout);\n }\n\n // Function Description:"} {"commit": "aa4e9f541456c45efabdbd5b69a6db101d3e74eb", "message": "Also hide the scroll marks when hiding the scrollbar (#13454)", "old_file": "src/cascadia/TerminalControl/TermControl.cpp", "new_file": "src/cascadia/TerminalControl/TermControl.cpp", "status": "M", "old_contents": " // - \r\n void TermControl::_ApplyUISettings()\r\n {\r\n _InitializeBackgroundBrush();\r\n\r\n // settings might be out-of-proc in the future\r\n auto settings{ _core.Settings() };\r\n\r\n // Apply padding as swapChainPanel's margin\r\n const auto newMargin = ParseThicknessFromPadding(settings.Padding());\r\n SwapChainPanel().Margin(newMargin);\r\n\r\n TSFInputControl().Margin(newMargin);\r\n\r\n // Apply settings for scrollbar\r\n if (settings.ScrollState() == ScrollbarState::Hidden)\r\n {\r\n // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the\r\n // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to\r\n // achieve the intended effect.\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);\r\n ScrollBar().Visibility(Visibility::Collapsed);\r\n }\r\n else // (default or Visible)\r\n {\r\n // Default behavior\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);\r\n ScrollBar().Visibility(Visibility::Visible);\r\n }\r\n\r\n _interactivity.UpdateSettings();\r\n if (_automationPeer)\r\n {\r\n _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,\r\n newMargin.Top,\r\n newMargin.Right,\r\n newMargin.Bottom });\r\n }\r\n\r\n _showMarksInScrollbar = settings.ShowMarks();\r\n // Clear out all the current marks\r\n ScrollBarCanvas().Children().Clear();\r\n // When we hot reload the settings, the core will send us a scrollbar\r\n // update. If we enabled scrollbar marks, then great, when we handle\r\n // that message, we'll redraw them.\r\n }\r\n\r\n // Method Description:\r\n // - Sets background image and applies its settings (stretch, opacity and alignment)\r\n // - Checks path validity\r\n // Arguments:\r\n // - newAppearance\r", "new_contents": " // - \r\n void TermControl::_ApplyUISettings()\r\n {\r\n _InitializeBackgroundBrush();\r\n\r\n // settings might be out-of-proc in the future\r\n auto settings{ _core.Settings() };\r\n\r\n // Apply padding as swapChainPanel's margin\r\n const auto newMargin = ParseThicknessFromPadding(settings.Padding());\r\n SwapChainPanel().Margin(newMargin);\r\n\r\n TSFInputControl().Margin(newMargin);\r\n\r\n // Apply settings for scrollbar\r\n if (settings.ScrollState() == ScrollbarState::Hidden)\r\n {\r\n // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the\r\n // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to\r\n // achieve the intended effect.\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);\r\n ScrollBar().Visibility(Visibility::Collapsed);\r\n ScrollMarksGrid().Visibility(Visibility::Collapsed);\r\n }\r\n else // (default or Visible)\r\n {\r\n // Default behavior\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);\r\n ScrollBar().Visibility(Visibility::Visible);\r\n ScrollMarksGrid().Visibility(Visibility::Visible);\r\n }\r\n\r\n _interactivity.UpdateSettings();\r\n if (_automationPeer)\r\n {\r\n _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,\r\n newMargin.Top,\r\n newMargin.Right,\r\n newMargin.Bottom });\r\n }\r\n\r\n _showMarksInScrollbar = settings.ShowMarks();\r\n // Clear out all the current marks\r\n ScrollBarCanvas().Children().Clear();\r\n // When we hot reload the settings, the core will send us a scrollbar\r\n // update. If we enabled scrollbar marks, then great, when we handle\r\n // that message, we'll redraw them.\r\n }\r\n\r\n // Method Description:\r\n // - Sets background image and applies its settings (stretch, opacity and alignment)\r\n // - Checks path validity\r\n // Arguments:\r\n // - newAppearance\r", "text": "<|original_code|>\n // - \r\n void TermControl::_ApplyUISettings()\r\n {\r\n _InitializeBackgroundBrush();\r\n\r\n // settings might be out-of-proc in the future\r\n auto settings{ _core.Settings() };\r\n\r\n // Apply padding as swapChainPanel's margin\r\n const auto newMargin = ParseThicknessFromPadding(settings.Padding());\r\n SwapChainPanel().Margin(newMargin);\r\n\r\n TSFInputControl().Margin(newMargin);\r\n\r\n // Apply settings for scrollbar\r\n if (settings.ScrollState() == ScrollbarState::Hidden)\r\n {\r\n // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the\r\n // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to\r\n // achieve the intended effect.\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);\r\n ScrollBar().Visibility(Visibility::Collapsed);\r\n }\r\n else // (default or Visible)\r\n {\r\n // Default behavior\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);\r\n ScrollBar().Visibility(Visibility::Visible);\r\n }\r\n\r\n _interactivity.UpdateSettings();\r\n if (_automationPeer)\r\n {\r\n _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,\r\n newMargin.Top,\r\n newMargin.Right,\r\n newMargin.Bottom });\r\n }\r\n\r\n _showMarksInScrollbar = settings.ShowMarks();\r\n // Clear out all the current marks\r\n ScrollBarCanvas().Children().Clear();\r\n // When we hot reload the settings, the core will send us a scrollbar\r\n // update. If we enabled scrollbar marks, then great, when we handle\r\n // that message, we'll redraw them.\r\n }\r\n\r\n // Method Description:\r\n // - Sets background image and applies its settings (stretch, opacity and alignment)\r\n // - Checks path validity\r\n // Arguments:\r\n // - newAppearance\r\n<|edits_diff|>\n--- src/cascadia/TerminalControl/TermControl.cpp\n+++ src/cascadia/TerminalControl/TermControl.cpp\n@@ -20,6 +20,7 @@\n // achieve the intended effect.\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);\n ScrollBar().Visibility(Visibility::Collapsed);\n+ ScrollMarksGrid().Visibility(Visibility::Collapsed);\n }\n else // (default or Visible)\n {\n<|current_version|>\n // - \r\n void TermControl::_ApplyUISettings()\r\n {\r\n _InitializeBackgroundBrush();\r\n\r\n // settings might be out-of-proc in the future\r\n auto settings{ _core.Settings() };\r\n\r\n // Apply padding as swapChainPanel's margin\r\n const auto newMargin = ParseThicknessFromPadding(settings.Padding());\r\n SwapChainPanel().Margin(newMargin);\r\n\r\n TSFInputControl().Margin(newMargin);\r\n\r\n // Apply settings for scrollbar\r\n if (settings.ScrollState() == ScrollbarState::Hidden)\r\n {\r\n // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the\r\n // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to\r\n // achieve the intended effect.\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);\r\n ScrollBar().Visibility(Visibility::Collapsed);\r\n ScrollMarksGrid().Visibility(Visibility::Collapsed);\r\n }\r\n else // (default or Visible)\r\n {\r\n // Default behavior\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);\r\n ScrollBar().Visibility(Visibility::Visible);\r\n }\r\n\r\n _interactivity.UpdateSettings();\r\n if (_automationPeer)\r\n {\r\n _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,\r\n newMargin.Top,\r\n newMargin.Right,\r\n newMargin.Bottom });\r\n }\r\n\r\n _showMarksInScrollbar = settings.ShowMarks();\r\n // Clear out all the current marks\r\n ScrollBarCanvas().Children().Clear();\r\n // When we hot reload the settings, the core will send us a scrollbar\r\n // update. If we enabled scrollbar marks, then great, when we handle\r\n // that message, we'll redraw them.\r\n }\r\n\r\n // Method Description:\r\n // - Sets background image and applies its settings (stretch, opacity and alignment)\r\n // - Checks path validity\r\n // Arguments:\r\n // - newAppearance\r\n<|next_version|>\n // - \r\n void TermControl::_ApplyUISettings()\r\n {\r\n _InitializeBackgroundBrush();\r\n\r\n // settings might be out-of-proc in the future\r\n auto settings{ _core.Settings() };\r\n\r\n // Apply padding as swapChainPanel's margin\r\n const auto newMargin = ParseThicknessFromPadding(settings.Padding());\r\n SwapChainPanel().Margin(newMargin);\r\n\r\n TSFInputControl().Margin(newMargin);\r\n\r\n // Apply settings for scrollbar\r\n if (settings.ScrollState() == ScrollbarState::Hidden)\r\n {\r\n // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the\r\n // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to\r\n // achieve the intended effect.\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);\r\n ScrollBar().Visibility(Visibility::Collapsed);\r\n ScrollMarksGrid().Visibility(Visibility::Collapsed);\r\n }\r\n else // (default or Visible)\r\n {\r\n // Default behavior\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);\r\n ScrollBar().Visibility(Visibility::Visible);\r\n ScrollMarksGrid().Visibility(Visibility::Visible);\r\n }\r\n\r\n _interactivity.UpdateSettings();\r\n if (_automationPeer)\r\n {\r\n _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,\r\n newMargin.Top,\r\n newMargin.Right,\r\n newMargin.Bottom });\r\n }\r\n\r\n _showMarksInScrollbar = settings.ShowMarks();\r\n // Clear out all the current marks\r\n ScrollBarCanvas().Children().Clear();\r\n // When we hot reload the settings, the core will send us a scrollbar\r\n // update. If we enabled scrollbar marks, then great, when we handle\r\n // that message, we'll redraw them.\r\n }\r\n\r\n // Method Description:\r\n // - Sets background image and applies its settings (stretch, opacity and alignment)\r\n // - Checks path validity\r\n // Arguments:\r\n // - newAppearance\r\n", "current_contents": " // - \r\n void TermControl::_ApplyUISettings()\r\n {\r\n _InitializeBackgroundBrush();\r\n\r\n // settings might be out-of-proc in the future\r\n auto settings{ _core.Settings() };\r\n\r\n // Apply padding as swapChainPanel's margin\r\n const auto newMargin = ParseThicknessFromPadding(settings.Padding());\r\n SwapChainPanel().Margin(newMargin);\r\n\r\n TSFInputControl().Margin(newMargin);\r\n\r\n // Apply settings for scrollbar\r\n if (settings.ScrollState() == ScrollbarState::Hidden)\r\n {\r\n // In the scenario where the user has turned off the OS setting to automatically hide scrollbars, the\r\n // Terminal scrollbar would still be visible; so, we need to set the control's visibility accordingly to\r\n // achieve the intended effect.\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::None);\r\n ScrollBar().Visibility(Visibility::Collapsed);\r\n ScrollMarksGrid().Visibility(Visibility::Collapsed);\r\n }\r\n else // (default or Visible)\r\n {\r\n // Default behavior\r\n ScrollBar().IndicatorMode(Controls::Primitives::ScrollingIndicatorMode::MouseIndicator);\r\n ScrollBar().Visibility(Visibility::Visible);\r\n }\r\n\r\n _interactivity.UpdateSettings();\r\n if (_automationPeer)\r\n {\r\n _automationPeer.SetControlPadding(Core::Padding{ newMargin.Left,\r\n newMargin.Top,\r\n newMargin.Right,\r\n newMargin.Bottom });\r\n }\r\n\r\n _showMarksInScrollbar = settings.ShowMarks();\r\n // Clear out all the current marks\r\n ScrollBarCanvas().Children().Clear();\r\n // When we hot reload the settings, the core will send us a scrollbar\r\n // update. If we enabled scrollbar marks, then great, when we handle\r\n // that message, we'll redraw them.\r\n }\r\n\r\n // Method Description:\r\n // - Sets background image and applies its settings (stretch, opacity and alignment)\r\n // - Checks path validity\r\n // Arguments:\r\n // - newAppearance\r"} {"commit": "f12ee745efab97c9e40ccafc2b649e9c15cfda78", "message": "Update the scrollbar postiton on `scrollToMark` (#13291)", "old_file": "src/cascadia/TerminalControl/ControlCore.cpp", "new_file": "src/cascadia/TerminalControl/ControlCore.cpp", "status": "M", "old_contents": " minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n case ScrollToMarkDirection::Previous:\r\n default:\r\n {\r\n int minDistance = INT_MAX;\r\n for (const auto& mark : marks)\r\n {\r\n const auto delta = currentOffset - mark.start.y;\r\n if (delta > 0 && delta < minDistance)\r\n {\r\n tgt = mark;\r\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n\r\n if (tgt.has_value())\r\n {\r\n UserScrollViewport(tgt->start.y);\r\n }\r\n else\r\n {\r\n if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)\r\n {\r\n UserScrollViewport(BufferHeight());\r\n }\r\n else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)\r\n {\r\n UserScrollViewport(0);\r\n }\r\n }\r\n }\r\n}\r\n", "new_contents": " minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n case ScrollToMarkDirection::Previous:\r\n default:\r\n {\r\n int minDistance = INT_MAX;\r\n for (const auto& mark : marks)\r\n {\r\n const auto delta = currentOffset - mark.start.y;\r\n if (delta > 0 && delta < minDistance)\r\n {\r\n tgt = mark;\r\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n\r\n const auto viewHeight = ViewHeight();\r\n const auto bufferSize = BufferHeight();\r\n\r\n // UserScrollViewport, to update the Terminal about where the viewport should be\r\n // then raise a _terminalScrollPositionChanged to inform the control to update the scrollbar.\r\n if (tgt.has_value())\r\n {\r\n UserScrollViewport(tgt->start.y);\r\n _terminalScrollPositionChanged(tgt->start.y, viewHeight, bufferSize);\r\n }\r\n else\r\n {\r\n if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)\r\n {\r\n UserScrollViewport(BufferHeight());\r\n _terminalScrollPositionChanged(BufferHeight(), viewHeight, bufferSize);\r\n }\r\n else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)\r\n {\r\n UserScrollViewport(0);\r\n _terminalScrollPositionChanged(0, viewHeight, bufferSize);\r\n }\r\n }\r\n }\r\n}\r\n", "text": "<|original_code|>\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n case ScrollToMarkDirection::Previous:\r\n default:\r\n {\r\n int minDistance = INT_MAX;\r\n for (const auto& mark : marks)\r\n {\r\n const auto delta = currentOffset - mark.start.y;\r\n if (delta > 0 && delta < minDistance)\r\n {\r\n tgt = mark;\r\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n\r\n if (tgt.has_value())\r\n {\r\n UserScrollViewport(tgt->start.y);\r\n }\r\n else\r\n {\r\n if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)\r\n {\r\n UserScrollViewport(BufferHeight());\r\n }\r\n else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)\r\n {\r\n UserScrollViewport(0);\r\n }\r\n }\r\n }\r\n}\r\n\n<|edits_diff|>\n--- src/cascadia/TerminalControl/ControlCore.cpp\n+++ src/cascadia/TerminalControl/ControlCore.cpp\n@@ -20,15 +20,22 @@\n }\n }\n \n+ const auto viewHeight = ViewHeight();\n+ const auto bufferSize = BufferHeight();\n+\n+ // UserScrollViewport, to update the Terminal about where the viewport should be\n+ // then raise a _terminalScrollPositionChanged to inform the control to update the scrollbar.\n if (tgt.has_value())\n {\n UserScrollViewport(tgt->start.y);\n+ _terminalScrollPositionChanged(tgt->start.y, viewHeight, bufferSize);\n }\n else\n {\n if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)\n {\n UserScrollViewport(BufferHeight());\n+ _terminalScrollPositionChanged(BufferHeight(), viewHeight, bufferSize);\n }\n else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)\n {\n<|current_version|>\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n case ScrollToMarkDirection::Previous:\r\n default:\r\n {\r\n int minDistance = INT_MAX;\r\n for (const auto& mark : marks)\r\n {\r\n const auto delta = currentOffset - mark.start.y;\r\n if (delta > 0 && delta < minDistance)\r\n {\r\n tgt = mark;\r\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n\r\n const auto viewHeight = ViewHeight();\r\n const auto bufferSize = BufferHeight();\r\n\r\n // UserScrollViewport, to update the Terminal about where the viewport should be\r\n // then raise a _terminalScrollPositionChanged to inform the control to update the scrollbar.\r\n if (tgt.has_value())\r\n {\r\n UserScrollViewport(tgt->start.y);\r\n _terminalScrollPositionChanged(tgt->start.y, viewHeight, bufferSize);\r\n }\r\n else\r\n {\r\n if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)\r\n {\r\n UserScrollViewport(BufferHeight());\r\n _terminalScrollPositionChanged(BufferHeight(), viewHeight, bufferSize);\r\n }\r\n else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)\r\n {\r\n UserScrollViewport(0);\r\n }\r\n }\r\n }\r\n}\r\n\n<|next_version|>\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n case ScrollToMarkDirection::Previous:\r\n default:\r\n {\r\n int minDistance = INT_MAX;\r\n for (const auto& mark : marks)\r\n {\r\n const auto delta = currentOffset - mark.start.y;\r\n if (delta > 0 && delta < minDistance)\r\n {\r\n tgt = mark;\r\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n\r\n const auto viewHeight = ViewHeight();\r\n const auto bufferSize = BufferHeight();\r\n\r\n // UserScrollViewport, to update the Terminal about where the viewport should be\r\n // then raise a _terminalScrollPositionChanged to inform the control to update the scrollbar.\r\n if (tgt.has_value())\r\n {\r\n UserScrollViewport(tgt->start.y);\r\n _terminalScrollPositionChanged(tgt->start.y, viewHeight, bufferSize);\r\n }\r\n else\r\n {\r\n if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)\r\n {\r\n UserScrollViewport(BufferHeight());\r\n _terminalScrollPositionChanged(BufferHeight(), viewHeight, bufferSize);\r\n }\r\n else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)\r\n {\r\n UserScrollViewport(0);\r\n _terminalScrollPositionChanged(0, viewHeight, bufferSize);\r\n }\r\n }\r\n }\r\n}\r\n\n", "current_contents": " minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n case ScrollToMarkDirection::Previous:\r\n default:\r\n {\r\n int minDistance = INT_MAX;\r\n for (const auto& mark : marks)\r\n {\r\n const auto delta = currentOffset - mark.start.y;\r\n if (delta > 0 && delta < minDistance)\r\n {\r\n tgt = mark;\r\n minDistance = delta;\r\n }\r\n }\r\n break;\r\n }\r\n }\r\n\r\n const auto viewHeight = ViewHeight();\r\n const auto bufferSize = BufferHeight();\r\n\r\n // UserScrollViewport, to update the Terminal about where the viewport should be\r\n // then raise a _terminalScrollPositionChanged to inform the control to update the scrollbar.\r\n if (tgt.has_value())\r\n {\r\n UserScrollViewport(tgt->start.y);\r\n _terminalScrollPositionChanged(tgt->start.y, viewHeight, bufferSize);\r\n }\r\n else\r\n {\r\n if (direction == ScrollToMarkDirection::Last || direction == ScrollToMarkDirection::Next)\r\n {\r\n UserScrollViewport(BufferHeight());\r\n _terminalScrollPositionChanged(BufferHeight(), viewHeight, bufferSize);\r\n }\r\n else if (direction == ScrollToMarkDirection::First || direction == ScrollToMarkDirection::Previous)\r\n {\r\n UserScrollViewport(0);\r\n }\r\n }\r\n }\r\n}\r\n"} {"commit": "19a5eb208dc2f51fc38361d887f1ace2bb9dfd6f", "message": "Add tooltips for nav items in the SUI (#12448)", "old_file": "src/cascadia/TerminalSettingsEditor/MainPage.cpp", "new_file": "src/cascadia/TerminalSettingsEditor/MainPage.cpp", "status": "M", "old_contents": " _Navigate(*profileViewModel, subPage);\r\n }\r\n else\r\n {\r\n _Navigate(tag.as(), subPage);\r\n }\r\n }\r\n }\r\n\r\n void MainPage::_InitializeProfilesList()\r\n {\r\n const auto menuItems = SettingsNav().MenuItems();\r\n\r\n // Manually create a NavigationViewItem for each profile\r\n // and keep a reference to them in a map so that we\r\n // can easily modify the correct one when the associated\r\n // profile changes.\r\n for (const auto& profile : _settingsClone.AllProfiles())\r\n {\r\n if (!profile.Deleted())\r\n {\r\n auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));\r\n menuItems.Append(navItem);\r\n }\r\n }\r\n\r\n // Top off (the end of the nav view) with the Add Profile item\r\n MUX::Controls::NavigationViewItem addProfileItem;\r\n addProfileItem.Content(box_value(RS_(L\"Nav_AddNewProfile/Content\")));\r\n addProfileItem.Tag(box_value(addProfileTag));\r\n\r\n FontIcon icon;\r\n // This is the \"Add\" symbol\r\n icon.Glyph(L\"\\xE710\");\r\n addProfileItem.Icon(icon);\r\n\r\n menuItems.Append(addProfileItem);\r\n }\r\n\r\n void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)\r\n {\r\n const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };\r\n const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };\r\n const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };\r\n SettingsNav().MenuItems().InsertAt(index, navItem);\r\n\r\n // Select and navigate to the new profile\r\n SettingsNav().SelectedItem(navItem);\r\n _Navigate(profileViewModel, BreadcrumbSubPage::None);\r\n }\r\n\r\n MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)\r\n {\r", "new_contents": " _Navigate(*profileViewModel, subPage);\r\n }\r\n else\r\n {\r\n _Navigate(tag.as(), subPage);\r\n }\r\n }\r\n }\r\n\r\n void MainPage::_InitializeProfilesList()\r\n {\r\n const auto menuItems = SettingsNav().MenuItems();\r\n\r\n // Manually create a NavigationViewItem for each profile\r\n // and keep a reference to them in a map so that we\r\n // can easily modify the correct one when the associated\r\n // profile changes.\r\n for (const auto& profile : _settingsClone.AllProfiles())\r\n {\r\n if (!profile.Deleted())\r\n {\r\n auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));\r\n Controls::ToolTipService::SetToolTip(navItem, box_value(profile.Name()));\r\n menuItems.Append(navItem);\r\n }\r\n }\r\n\r\n // Top off (the end of the nav view) with the Add Profile item\r\n MUX::Controls::NavigationViewItem addProfileItem;\r\n addProfileItem.Content(box_value(RS_(L\"Nav_AddNewProfile/Content\")));\r\n Controls::ToolTipService::SetToolTip(addProfileItem, box_value(RS_(L\"Nav_AddNewProfile/Content\")));\r\n addProfileItem.Tag(box_value(addProfileTag));\r\n\r\n FontIcon icon;\r\n // This is the \"Add\" symbol\r\n icon.Glyph(L\"\\xE710\");\r\n addProfileItem.Icon(icon);\r\n\r\n menuItems.Append(addProfileItem);\r\n }\r\n\r\n void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)\r\n {\r\n const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };\r\n const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };\r\n const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };\r\n SettingsNav().MenuItems().InsertAt(index, navItem);\r\n\r\n // Select and navigate to the new profile\r\n SettingsNav().SelectedItem(navItem);\r\n _Navigate(profileViewModel, BreadcrumbSubPage::None);\r\n }\r\n\r\n MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)\r\n {\r", "text": "<|original_code|>\n _Navigate(*profileViewModel, subPage);\r\n }\r\n else\r\n {\r\n _Navigate(tag.as(), subPage);\r\n }\r\n }\r\n }\r\n\r\n void MainPage::_InitializeProfilesList()\r\n {\r\n const auto menuItems = SettingsNav().MenuItems();\r\n\r\n // Manually create a NavigationViewItem for each profile\r\n // and keep a reference to them in a map so that we\r\n // can easily modify the correct one when the associated\r\n // profile changes.\r\n for (const auto& profile : _settingsClone.AllProfiles())\r\n {\r\n if (!profile.Deleted())\r\n {\r\n auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));\r\n menuItems.Append(navItem);\r\n }\r\n }\r\n\r\n // Top off (the end of the nav view) with the Add Profile item\r\n MUX::Controls::NavigationViewItem addProfileItem;\r\n addProfileItem.Content(box_value(RS_(L\"Nav_AddNewProfile/Content\")));\r\n addProfileItem.Tag(box_value(addProfileTag));\r\n\r\n FontIcon icon;\r\n // This is the \"Add\" symbol\r\n icon.Glyph(L\"\\xE710\");\r\n addProfileItem.Icon(icon);\r\n\r\n menuItems.Append(addProfileItem);\r\n }\r\n\r\n void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)\r\n {\r\n const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };\r\n const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };\r\n const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };\r\n SettingsNav().MenuItems().InsertAt(index, navItem);\r\n\r\n // Select and navigate to the new profile\r\n SettingsNav().SelectedItem(navItem);\r\n _Navigate(profileViewModel, BreadcrumbSubPage::None);\r\n }\r\n\r\n MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)\r\n {\r\n<|edits_diff|>\n--- src/cascadia/TerminalSettingsEditor/MainPage.cpp\n+++ src/cascadia/TerminalSettingsEditor/MainPage.cpp\n@@ -20,6 +20,7 @@\n if (!profile.Deleted())\n {\n auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));\n+ Controls::ToolTipService::SetToolTip(navItem, box_value(profile.Name()));\n menuItems.Append(navItem);\n }\n }\n<|current_version|>\n _Navigate(*profileViewModel, subPage);\r\n }\r\n else\r\n {\r\n _Navigate(tag.as(), subPage);\r\n }\r\n }\r\n }\r\n\r\n void MainPage::_InitializeProfilesList()\r\n {\r\n const auto menuItems = SettingsNav().MenuItems();\r\n\r\n // Manually create a NavigationViewItem for each profile\r\n // and keep a reference to them in a map so that we\r\n // can easily modify the correct one when the associated\r\n // profile changes.\r\n for (const auto& profile : _settingsClone.AllProfiles())\r\n {\r\n if (!profile.Deleted())\r\n {\r\n auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));\r\n Controls::ToolTipService::SetToolTip(navItem, box_value(profile.Name()));\r\n menuItems.Append(navItem);\r\n }\r\n }\r\n\r\n // Top off (the end of the nav view) with the Add Profile item\r\n MUX::Controls::NavigationViewItem addProfileItem;\r\n addProfileItem.Content(box_value(RS_(L\"Nav_AddNewProfile/Content\")));\r\n addProfileItem.Tag(box_value(addProfileTag));\r\n\r\n FontIcon icon;\r\n // This is the \"Add\" symbol\r\n icon.Glyph(L\"\\xE710\");\r\n addProfileItem.Icon(icon);\r\n\r\n menuItems.Append(addProfileItem);\r\n }\r\n\r\n void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)\r\n {\r\n const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };\r\n const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };\r\n const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };\r\n SettingsNav().MenuItems().InsertAt(index, navItem);\r\n\r\n // Select and navigate to the new profile\r\n SettingsNav().SelectedItem(navItem);\r\n _Navigate(profileViewModel, BreadcrumbSubPage::None);\r\n }\r\n\r\n MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)\r\n {\r\n<|next_version|>\n _Navigate(*profileViewModel, subPage);\r\n }\r\n else\r\n {\r\n _Navigate(tag.as(), subPage);\r\n }\r\n }\r\n }\r\n\r\n void MainPage::_InitializeProfilesList()\r\n {\r\n const auto menuItems = SettingsNav().MenuItems();\r\n\r\n // Manually create a NavigationViewItem for each profile\r\n // and keep a reference to them in a map so that we\r\n // can easily modify the correct one when the associated\r\n // profile changes.\r\n for (const auto& profile : _settingsClone.AllProfiles())\r\n {\r\n if (!profile.Deleted())\r\n {\r\n auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));\r\n Controls::ToolTipService::SetToolTip(navItem, box_value(profile.Name()));\r\n menuItems.Append(navItem);\r\n }\r\n }\r\n\r\n // Top off (the end of the nav view) with the Add Profile item\r\n MUX::Controls::NavigationViewItem addProfileItem;\r\n addProfileItem.Content(box_value(RS_(L\"Nav_AddNewProfile/Content\")));\r\n Controls::ToolTipService::SetToolTip(addProfileItem, box_value(RS_(L\"Nav_AddNewProfile/Content\")));\r\n addProfileItem.Tag(box_value(addProfileTag));\r\n\r\n FontIcon icon;\r\n // This is the \"Add\" symbol\r\n icon.Glyph(L\"\\xE710\");\r\n addProfileItem.Icon(icon);\r\n\r\n menuItems.Append(addProfileItem);\r\n }\r\n\r\n void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)\r\n {\r\n const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };\r\n const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };\r\n const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };\r\n SettingsNav().MenuItems().InsertAt(index, navItem);\r\n\r\n // Select and navigate to the new profile\r\n SettingsNav().SelectedItem(navItem);\r\n _Navigate(profileViewModel, BreadcrumbSubPage::None);\r\n }\r\n\r\n MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)\r\n {\r\n", "current_contents": " _Navigate(*profileViewModel, subPage);\r\n }\r\n else\r\n {\r\n _Navigate(tag.as(), subPage);\r\n }\r\n }\r\n }\r\n\r\n void MainPage::_InitializeProfilesList()\r\n {\r\n const auto menuItems = SettingsNav().MenuItems();\r\n\r\n // Manually create a NavigationViewItem for each profile\r\n // and keep a reference to them in a map so that we\r\n // can easily modify the correct one when the associated\r\n // profile changes.\r\n for (const auto& profile : _settingsClone.AllProfiles())\r\n {\r\n if (!profile.Deleted())\r\n {\r\n auto navItem = _CreateProfileNavViewItem(_viewModelForProfile(profile, _settingsClone));\r\n Controls::ToolTipService::SetToolTip(navItem, box_value(profile.Name()));\r\n menuItems.Append(navItem);\r\n }\r\n }\r\n\r\n // Top off (the end of the nav view) with the Add Profile item\r\n MUX::Controls::NavigationViewItem addProfileItem;\r\n addProfileItem.Content(box_value(RS_(L\"Nav_AddNewProfile/Content\")));\r\n addProfileItem.Tag(box_value(addProfileTag));\r\n\r\n FontIcon icon;\r\n // This is the \"Add\" symbol\r\n icon.Glyph(L\"\\xE710\");\r\n addProfileItem.Icon(icon);\r\n\r\n menuItems.Append(addProfileItem);\r\n }\r\n\r\n void MainPage::_CreateAndNavigateToNewProfile(const uint32_t index, const Model::Profile& profile)\r\n {\r\n const auto newProfile{ profile ? profile : _settingsClone.CreateNewProfile() };\r\n const auto profileViewModel{ _viewModelForProfile(newProfile, _settingsClone) };\r\n const auto navItem{ _CreateProfileNavViewItem(profileViewModel) };\r\n SettingsNav().MenuItems().InsertAt(index, navItem);\r\n\r\n // Select and navigate to the new profile\r\n SettingsNav().SelectedItem(navItem);\r\n _Navigate(profileViewModel, BreadcrumbSubPage::None);\r\n }\r\n\r\n MUX::Controls::NavigationViewItem MainPage::_CreateProfileNavViewItem(const Editor::ProfileViewModel& profile)\r\n {\r"} {"commit": "acbfb3015f0358bb8551566cf763acafb978da85", "message": "Persist Runtime TabTitle and Maximize/Focus/Fullscreen states (#12073)", "old_file": "src/cascadia/TerminalSettingsModel/ApplicationState.cpp", "new_file": "src/cascadia/TerminalSettingsModel/ApplicationState.cpp", "status": "M", "old_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ApplicationState.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"ApplicationState.g.cpp\"\r\n#include \"WindowLayout.g.cpp\"\r\n#include \"ActionAndArgs.h\"\r\n#include \"JsonUtils.h\"\r\n#include \"FileUtils.h\"\r\n#include \"../../types/inc/utils.hpp\"\r\n\r\nstatic constexpr std::wstring_view stateFileName{ L\"state.json\" };\r\nstatic constexpr std::wstring_view elevatedStateFileName{ L\"elevated-state.json\" };\r\n\r\nstatic constexpr std::string_view TabLayoutKey{ \"tabLayout\" };\r\nstatic constexpr std::string_view InitialPositionKey{ \"initialPosition\" };\r\nstatic constexpr std::string_view InitialSizeKey{ \"initialSize\" };\r\n\r\nnamespace Microsoft::Terminal::Settings::Model::JsonUtils\r\n{\r\n using namespace winrt::Microsoft::Terminal::Settings::Model;\r\n\r\n template<>\r\n struct ConversionTrait\r\n {\r\n WindowLayout FromJson(const Json::Value& json)\r\n {\r\n auto layout = winrt::make_self();\r\n\r\n GetValueForKey(json, TabLayoutKey, layout->_TabLayout);\r\n GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);\r\n GetValueForKey(json, InitialSizeKey, layout->_InitialSize);\r\n\r\n return *layout;\r\n }\r\n\r\n bool CanConvert(const Json::Value& json)\r\n {\r\n return json.isObject();\r\n }\r\n\r\n Json::Value ToJson(const WindowLayout& val)\r\n {\r\n Json::Value json{ Json::objectValue };\r\n\r\n SetValueForKey(json, TabLayoutKey, val.TabLayout());\r\n SetValueForKey(json, InitialPositionKey, val.InitialPosition());\r\n SetValueForKey(json, InitialSizeKey, val.InitialSize());\r\n\r\n return json;\r\n }\r\n\r\n std::string TypeDescription() const\r\n {\r\n return \"WindowLayout\";\r\n }\r\n };\r\n}\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\n\r\nnamespace winrt::Microsoft::Terminal::Settings::Model::implementation\r\n{\r\n winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)\r\n {\r\n JsonUtils::ConversionTrait trait;\r\n auto json = trait.ToJson(layout);\r\n\r\n Json::StreamWriterBuilder wbuilder;\r\n const auto content = Json::writeString(wbuilder, json);\r\n return hstring{ til::u8u16(content) };\r", "new_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ApplicationState.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"ApplicationState.g.cpp\"\r\n#include \"WindowLayout.g.cpp\"\r\n#include \"ActionAndArgs.h\"\r\n#include \"JsonUtils.h\"\r\n#include \"FileUtils.h\"\r\n#include \"../../types/inc/utils.hpp\"\r\n\r\nstatic constexpr std::wstring_view stateFileName{ L\"state.json\" };\r\nstatic constexpr std::wstring_view elevatedStateFileName{ L\"elevated-state.json\" };\r\n\r\nstatic constexpr std::string_view TabLayoutKey{ \"tabLayout\" };\r\nstatic constexpr std::string_view InitialPositionKey{ \"initialPosition\" };\r\nstatic constexpr std::string_view InitialSizeKey{ \"initialSize\" };\r\nstatic constexpr std::string_view LaunchModeKey{ \"launchMode\" };\r\n\r\nnamespace Microsoft::Terminal::Settings::Model::JsonUtils\r\n{\r\n using namespace winrt::Microsoft::Terminal::Settings::Model;\r\n\r\n template<>\r\n struct ConversionTrait\r\n {\r\n WindowLayout FromJson(const Json::Value& json)\r\n {\r\n auto layout = winrt::make_self();\r\n\r\n GetValueForKey(json, TabLayoutKey, layout->_TabLayout);\r\n GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);\r\n GetValueForKey(json, LaunchModeKey, layout->_LaunchMode);\r\n GetValueForKey(json, InitialSizeKey, layout->_InitialSize);\r\n\r\n return *layout;\r\n }\r\n\r\n bool CanConvert(const Json::Value& json)\r\n {\r\n return json.isObject();\r\n }\r\n\r\n Json::Value ToJson(const WindowLayout& val)\r\n {\r\n Json::Value json{ Json::objectValue };\r\n\r\n SetValueForKey(json, TabLayoutKey, val.TabLayout());\r\n SetValueForKey(json, InitialPositionKey, val.InitialPosition());\r\n SetValueForKey(json, LaunchModeKey, val.LaunchMode());\r\n SetValueForKey(json, InitialSizeKey, val.InitialSize());\r\n\r\n return json;\r\n }\r\n\r\n std::string TypeDescription() const\r\n {\r\n return \"WindowLayout\";\r\n }\r\n };\r\n}\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\n\r\nnamespace winrt::Microsoft::Terminal::Settings::Model::implementation\r\n{\r\n winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)\r\n {\r\n JsonUtils::ConversionTrait trait;\r\n auto json = trait.ToJson(layout);\r\n\r\n Json::StreamWriterBuilder wbuilder;\r\n const auto content = Json::writeString(wbuilder, json);\r\n return hstring{ til::u8u16(content) };\r", "text": "<|original_code|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ApplicationState.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"ApplicationState.g.cpp\"\r\n#include \"WindowLayout.g.cpp\"\r\n#include \"ActionAndArgs.h\"\r\n#include \"JsonUtils.h\"\r\n#include \"FileUtils.h\"\r\n#include \"../../types/inc/utils.hpp\"\r\n\r\nstatic constexpr std::wstring_view stateFileName{ L\"state.json\" };\r\nstatic constexpr std::wstring_view elevatedStateFileName{ L\"elevated-state.json\" };\r\n\r\nstatic constexpr std::string_view TabLayoutKey{ \"tabLayout\" };\r\nstatic constexpr std::string_view InitialPositionKey{ \"initialPosition\" };\r\nstatic constexpr std::string_view InitialSizeKey{ \"initialSize\" };\r\n\r\nnamespace Microsoft::Terminal::Settings::Model::JsonUtils\r\n{\r\n using namespace winrt::Microsoft::Terminal::Settings::Model;\r\n\r\n template<>\r\n struct ConversionTrait\r\n {\r\n WindowLayout FromJson(const Json::Value& json)\r\n {\r\n auto layout = winrt::make_self();\r\n\r\n GetValueForKey(json, TabLayoutKey, layout->_TabLayout);\r\n GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);\r\n GetValueForKey(json, InitialSizeKey, layout->_InitialSize);\r\n\r\n return *layout;\r\n }\r\n\r\n bool CanConvert(const Json::Value& json)\r\n {\r\n return json.isObject();\r\n }\r\n\r\n Json::Value ToJson(const WindowLayout& val)\r\n {\r\n Json::Value json{ Json::objectValue };\r\n\r\n SetValueForKey(json, TabLayoutKey, val.TabLayout());\r\n SetValueForKey(json, InitialPositionKey, val.InitialPosition());\r\n SetValueForKey(json, InitialSizeKey, val.InitialSize());\r\n\r\n return json;\r\n }\r\n\r\n std::string TypeDescription() const\r\n {\r\n return \"WindowLayout\";\r\n }\r\n };\r\n}\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\n\r\nnamespace winrt::Microsoft::Terminal::Settings::Model::implementation\r\n{\r\n winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)\r\n {\r\n JsonUtils::ConversionTrait trait;\r\n auto json = trait.ToJson(layout);\r\n\r\n Json::StreamWriterBuilder wbuilder;\r\n const auto content = Json::writeString(wbuilder, json);\r\n return hstring{ til::u8u16(content) };\r\n<|edits_diff|>\n--- src/cascadia/TerminalSettingsModel/ApplicationState.cpp\n+++ src/cascadia/TerminalSettingsModel/ApplicationState.cpp\n@@ -17,6 +17,7 @@\n static constexpr std::string_view TabLayoutKey{ \"tabLayout\" };\n static constexpr std::string_view InitialPositionKey{ \"initialPosition\" };\n static constexpr std::string_view InitialSizeKey{ \"initialSize\" };\n+static constexpr std::string_view LaunchModeKey{ \"launchMode\" };\n \n namespace Microsoft::Terminal::Settings::Model::JsonUtils\n {\n@@ -31,6 +32,7 @@\n \n GetValueForKey(json, TabLayoutKey, layout->_TabLayout);\n GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);\n+ GetValueForKey(json, LaunchModeKey, layout->_LaunchMode);\n GetValueForKey(json, InitialSizeKey, layout->_InitialSize);\n \n return *layout;\n<|current_version|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ApplicationState.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"ApplicationState.g.cpp\"\r\n#include \"WindowLayout.g.cpp\"\r\n#include \"ActionAndArgs.h\"\r\n#include \"JsonUtils.h\"\r\n#include \"FileUtils.h\"\r\n#include \"../../types/inc/utils.hpp\"\r\n\r\nstatic constexpr std::wstring_view stateFileName{ L\"state.json\" };\r\nstatic constexpr std::wstring_view elevatedStateFileName{ L\"elevated-state.json\" };\r\n\r\nstatic constexpr std::string_view TabLayoutKey{ \"tabLayout\" };\r\nstatic constexpr std::string_view InitialPositionKey{ \"initialPosition\" };\r\nstatic constexpr std::string_view InitialSizeKey{ \"initialSize\" };\r\nstatic constexpr std::string_view LaunchModeKey{ \"launchMode\" };\r\n\r\nnamespace Microsoft::Terminal::Settings::Model::JsonUtils\r\n{\r\n using namespace winrt::Microsoft::Terminal::Settings::Model;\r\n\r\n template<>\r\n struct ConversionTrait\r\n {\r\n WindowLayout FromJson(const Json::Value& json)\r\n {\r\n auto layout = winrt::make_self();\r\n\r\n GetValueForKey(json, TabLayoutKey, layout->_TabLayout);\r\n GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);\r\n GetValueForKey(json, LaunchModeKey, layout->_LaunchMode);\r\n GetValueForKey(json, InitialSizeKey, layout->_InitialSize);\r\n\r\n return *layout;\r\n }\r\n\r\n bool CanConvert(const Json::Value& json)\r\n {\r\n return json.isObject();\r\n }\r\n\r\n Json::Value ToJson(const WindowLayout& val)\r\n {\r\n Json::Value json{ Json::objectValue };\r\n\r\n SetValueForKey(json, TabLayoutKey, val.TabLayout());\r\n SetValueForKey(json, InitialPositionKey, val.InitialPosition());\r\n SetValueForKey(json, InitialSizeKey, val.InitialSize());\r\n\r\n return json;\r\n }\r\n\r\n std::string TypeDescription() const\r\n {\r\n return \"WindowLayout\";\r\n }\r\n };\r\n}\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\n\r\nnamespace winrt::Microsoft::Terminal::Settings::Model::implementation\r\n{\r\n winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)\r\n {\r\n JsonUtils::ConversionTrait trait;\r\n auto json = trait.ToJson(layout);\r\n\r\n Json::StreamWriterBuilder wbuilder;\r\n const auto content = Json::writeString(wbuilder, json);\r\n return hstring{ til::u8u16(content) };\r\n<|next_version|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ApplicationState.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"ApplicationState.g.cpp\"\r\n#include \"WindowLayout.g.cpp\"\r\n#include \"ActionAndArgs.h\"\r\n#include \"JsonUtils.h\"\r\n#include \"FileUtils.h\"\r\n#include \"../../types/inc/utils.hpp\"\r\n\r\nstatic constexpr std::wstring_view stateFileName{ L\"state.json\" };\r\nstatic constexpr std::wstring_view elevatedStateFileName{ L\"elevated-state.json\" };\r\n\r\nstatic constexpr std::string_view TabLayoutKey{ \"tabLayout\" };\r\nstatic constexpr std::string_view InitialPositionKey{ \"initialPosition\" };\r\nstatic constexpr std::string_view InitialSizeKey{ \"initialSize\" };\r\nstatic constexpr std::string_view LaunchModeKey{ \"launchMode\" };\r\n\r\nnamespace Microsoft::Terminal::Settings::Model::JsonUtils\r\n{\r\n using namespace winrt::Microsoft::Terminal::Settings::Model;\r\n\r\n template<>\r\n struct ConversionTrait\r\n {\r\n WindowLayout FromJson(const Json::Value& json)\r\n {\r\n auto layout = winrt::make_self();\r\n\r\n GetValueForKey(json, TabLayoutKey, layout->_TabLayout);\r\n GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);\r\n GetValueForKey(json, LaunchModeKey, layout->_LaunchMode);\r\n GetValueForKey(json, InitialSizeKey, layout->_InitialSize);\r\n\r\n return *layout;\r\n }\r\n\r\n bool CanConvert(const Json::Value& json)\r\n {\r\n return json.isObject();\r\n }\r\n\r\n Json::Value ToJson(const WindowLayout& val)\r\n {\r\n Json::Value json{ Json::objectValue };\r\n\r\n SetValueForKey(json, TabLayoutKey, val.TabLayout());\r\n SetValueForKey(json, InitialPositionKey, val.InitialPosition());\r\n SetValueForKey(json, LaunchModeKey, val.LaunchMode());\r\n SetValueForKey(json, InitialSizeKey, val.InitialSize());\r\n\r\n return json;\r\n }\r\n\r\n std::string TypeDescription() const\r\n {\r\n return \"WindowLayout\";\r\n }\r\n };\r\n}\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\n\r\nnamespace winrt::Microsoft::Terminal::Settings::Model::implementation\r\n{\r\n winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)\r\n {\r\n JsonUtils::ConversionTrait trait;\r\n auto json = trait.ToJson(layout);\r\n\r\n Json::StreamWriterBuilder wbuilder;\r\n const auto content = Json::writeString(wbuilder, json);\r\n return hstring{ til::u8u16(content) };\r\n", "current_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"ApplicationState.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"ApplicationState.g.cpp\"\r\n#include \"WindowLayout.g.cpp\"\r\n#include \"ActionAndArgs.h\"\r\n#include \"JsonUtils.h\"\r\n#include \"FileUtils.h\"\r\n#include \"../../types/inc/utils.hpp\"\r\n\r\nstatic constexpr std::wstring_view stateFileName{ L\"state.json\" };\r\nstatic constexpr std::wstring_view elevatedStateFileName{ L\"elevated-state.json\" };\r\n\r\nstatic constexpr std::string_view TabLayoutKey{ \"tabLayout\" };\r\nstatic constexpr std::string_view InitialPositionKey{ \"initialPosition\" };\r\nstatic constexpr std::string_view InitialSizeKey{ \"initialSize\" };\r\nstatic constexpr std::string_view LaunchModeKey{ \"launchMode\" };\r\n\r\nnamespace Microsoft::Terminal::Settings::Model::JsonUtils\r\n{\r\n using namespace winrt::Microsoft::Terminal::Settings::Model;\r\n\r\n template<>\r\n struct ConversionTrait\r\n {\r\n WindowLayout FromJson(const Json::Value& json)\r\n {\r\n auto layout = winrt::make_self();\r\n\r\n GetValueForKey(json, TabLayoutKey, layout->_TabLayout);\r\n GetValueForKey(json, InitialPositionKey, layout->_InitialPosition);\r\n GetValueForKey(json, LaunchModeKey, layout->_LaunchMode);\r\n GetValueForKey(json, InitialSizeKey, layout->_InitialSize);\r\n\r\n return *layout;\r\n }\r\n\r\n bool CanConvert(const Json::Value& json)\r\n {\r\n return json.isObject();\r\n }\r\n\r\n Json::Value ToJson(const WindowLayout& val)\r\n {\r\n Json::Value json{ Json::objectValue };\r\n\r\n SetValueForKey(json, TabLayoutKey, val.TabLayout());\r\n SetValueForKey(json, InitialPositionKey, val.InitialPosition());\r\n SetValueForKey(json, InitialSizeKey, val.InitialSize());\r\n\r\n return json;\r\n }\r\n\r\n std::string TypeDescription() const\r\n {\r\n return \"WindowLayout\";\r\n }\r\n };\r\n}\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\n\r\nnamespace winrt::Microsoft::Terminal::Settings::Model::implementation\r\n{\r\n winrt::hstring WindowLayout::ToJson(const Model::WindowLayout& layout)\r\n {\r\n JsonUtils::ConversionTrait trait;\r\n auto json = trait.ToJson(layout);\r\n\r\n Json::StreamWriterBuilder wbuilder;\r\n const auto content = Json::writeString(wbuilder, json);\r\n return hstring{ til::u8u16(content) };\r"} {"commit": "f84da18d1e3b10ab36caa507412219616d8f161f", "message": "Add profile generators for Visual Studio (#7774)", "old_file": "src/cascadia/TerminalSettingsModel/CascadiaSettings.cpp", "new_file": "src/cascadia/TerminalSettingsModel/CascadiaSettings.cpp", "status": "M", "old_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"CascadiaSettings.g.cpp\"\r\n\r\n#include \r\n\r\n#include \"AzureCloudShellGenerator.h\"\r\n#include \"PowershellCoreProfileGenerator.h\"\r\n#include \"WslDistroGenerator.h\"\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal;\r\nusing namespace winrt::Microsoft::Terminal::Control;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\nusing namespace winrt::Windows::Foundation::Collections;\r\nusing namespace Microsoft::Console;\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L\"ms-appx:///ProfileIcons/\" };\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L\".png\" };\r\nstatic constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L\"{9acb9455-ca41-5af7-950f-6bca1bc9722f}\" };\r\n\r\n// make sure this matches defaults.json.\r\nstatic constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L\"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}\" };\r\n\r\nCascadiaSettings::CascadiaSettings() :\r\n CascadiaSettings(true)\r\n{\r\n}\r\n\r\n// Constructor Description:\r\n// - Creates a new settings object. If addDynamicProfiles is true, we'll\r\n// automatically add the built-in profile generators to our list of profile\r\n// generators. Set this to `false` for unit testing.\r\n// Arguments:\r\n// - addDynamicProfiles: if true, we'll add the built-in DPGs.\r\nCascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :\r\n _globals{ winrt::make_self() },\r\n _allProfiles{ winrt::single_threaded_observable_vector() },\r\n _activeProfiles{ winrt::single_threaded_observable_vector() },\r\n _warnings{ winrt::single_threaded_vector() },\r\n _deserializationErrorMessage{ L\"\" },\r\n _defaultTerminals{ winrt::single_threaded_observable_vector() },\r\n _currentDefaultTerminal{ nullptr }\r\n{\r\n if (addDynamicProfiles)\r\n {\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n }\r\n}\r\n\r\nCascadiaSettings::CascadiaSettings(winrt::hstring json) :\r\n CascadiaSettings(false)\r\n{\r\n const auto jsonString{ til::u16u8(json) };\r\n _ParseJsonString(jsonString, false);\r\n _ApplyDefaultsFromUserSettings();\r\n LayerJson(_userSettings);\r\n _ValidateSettings();\r\n}\r\n\r\nwinrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const\r\n{\r\n // dynamic profile generators added by default\r\n auto settings{ winrt::make_self() };\r\n settings->_globals = _globals->Copy();\r\n for (auto warning : _warnings)\r\n {\r\n settings->_warnings.Append(warning);\r\n }\r\n settings->_loadError = _loadError;\r\n settings->_deserializationErrorMessage = _deserializationErrorMessage;\r", "new_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"CascadiaSettings.g.cpp\"\r\n\r\n#include \r\n\r\n#include \"AzureCloudShellGenerator.h\"\r\n#include \"PowershellCoreProfileGenerator.h\"\r\n#include \"VsDevCmdGenerator.h\"\r\n#include \"VsDevShellGenerator.h\"\r\n#include \"WslDistroGenerator.h\"\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal;\r\nusing namespace winrt::Microsoft::Terminal::Control;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\nusing namespace winrt::Windows::Foundation::Collections;\r\nusing namespace Microsoft::Console;\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L\"ms-appx:///ProfileIcons/\" };\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L\".png\" };\r\nstatic constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L\"{9acb9455-ca41-5af7-950f-6bca1bc9722f}\" };\r\n\r\n// make sure this matches defaults.json.\r\nstatic constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L\"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}\" };\r\n\r\nCascadiaSettings::CascadiaSettings() :\r\n CascadiaSettings(true)\r\n{\r\n}\r\n\r\n// Constructor Description:\r\n// - Creates a new settings object. If addDynamicProfiles is true, we'll\r\n// automatically add the built-in profile generators to our list of profile\r\n// generators. Set this to `false` for unit testing.\r\n// Arguments:\r\n// - addDynamicProfiles: if true, we'll add the built-in DPGs.\r\nCascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :\r\n _globals{ winrt::make_self() },\r\n _allProfiles{ winrt::single_threaded_observable_vector() },\r\n _activeProfiles{ winrt::single_threaded_observable_vector() },\r\n _warnings{ winrt::single_threaded_vector() },\r\n _deserializationErrorMessage{ L\"\" },\r\n _defaultTerminals{ winrt::single_threaded_observable_vector() },\r\n _currentDefaultTerminal{ nullptr }\r\n{\r\n if (addDynamicProfiles)\r\n {\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n }\r\n}\r\n\r\nCascadiaSettings::CascadiaSettings(winrt::hstring json) :\r\n CascadiaSettings(false)\r\n{\r\n const auto jsonString{ til::u16u8(json) };\r\n _ParseJsonString(jsonString, false);\r\n _ApplyDefaultsFromUserSettings();\r\n LayerJson(_userSettings);\r\n _ValidateSettings();\r\n}\r\n\r\nwinrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const\r\n{\r\n // dynamic profile generators added by default\r\n auto settings{ winrt::make_self() };\r\n settings->_globals = _globals->Copy();\r\n for (auto warning : _warnings)\r\n {\r\n settings->_warnings.Append(warning);\r\n }\r\n settings->_loadError = _loadError;\r\n settings->_deserializationErrorMessage = _deserializationErrorMessage;\r", "text": "<|original_code|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"CascadiaSettings.g.cpp\"\r\n\r\n#include \r\n\r\n#include \"AzureCloudShellGenerator.h\"\r\n#include \"PowershellCoreProfileGenerator.h\"\r\n#include \"WslDistroGenerator.h\"\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal;\r\nusing namespace winrt::Microsoft::Terminal::Control;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\nusing namespace winrt::Windows::Foundation::Collections;\r\nusing namespace Microsoft::Console;\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L\"ms-appx:///ProfileIcons/\" };\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L\".png\" };\r\nstatic constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L\"{9acb9455-ca41-5af7-950f-6bca1bc9722f}\" };\r\n\r\n// make sure this matches defaults.json.\r\nstatic constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L\"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}\" };\r\n\r\nCascadiaSettings::CascadiaSettings() :\r\n CascadiaSettings(true)\r\n{\r\n}\r\n\r\n// Constructor Description:\r\n// - Creates a new settings object. If addDynamicProfiles is true, we'll\r\n// automatically add the built-in profile generators to our list of profile\r\n// generators. Set this to `false` for unit testing.\r\n// Arguments:\r\n// - addDynamicProfiles: if true, we'll add the built-in DPGs.\r\nCascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :\r\n _globals{ winrt::make_self() },\r\n _allProfiles{ winrt::single_threaded_observable_vector() },\r\n _activeProfiles{ winrt::single_threaded_observable_vector() },\r\n _warnings{ winrt::single_threaded_vector() },\r\n _deserializationErrorMessage{ L\"\" },\r\n _defaultTerminals{ winrt::single_threaded_observable_vector() },\r\n _currentDefaultTerminal{ nullptr }\r\n{\r\n if (addDynamicProfiles)\r\n {\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n }\r\n}\r\n\r\nCascadiaSettings::CascadiaSettings(winrt::hstring json) :\r\n CascadiaSettings(false)\r\n{\r\n const auto jsonString{ til::u16u8(json) };\r\n _ParseJsonString(jsonString, false);\r\n _ApplyDefaultsFromUserSettings();\r\n LayerJson(_userSettings);\r\n _ValidateSettings();\r\n}\r\n\r\nwinrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const\r\n{\r\n // dynamic profile generators added by default\r\n auto settings{ winrt::make_self() };\r\n settings->_globals = _globals->Copy();\r\n for (auto warning : _warnings)\r\n {\r\n settings->_warnings.Append(warning);\r\n }\r\n settings->_loadError = _loadError;\r\n settings->_deserializationErrorMessage = _deserializationErrorMessage;\r\n<|edits_diff|>\n--- src/cascadia/TerminalSettingsModel/CascadiaSettings.cpp\n+++ src/cascadia/TerminalSettingsModel/CascadiaSettings.cpp\n@@ -9,6 +9,8 @@\n \n #include \"AzureCloudShellGenerator.h\"\n #include \"PowershellCoreProfileGenerator.h\"\n+#include \"VsDevCmdGenerator.h\"\n+#include \"VsDevShellGenerator.h\"\n #include \"WslDistroGenerator.h\"\n \n using namespace ::Microsoft::Terminal::Settings::Model;\n<|current_version|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"CascadiaSettings.g.cpp\"\r\n\r\n#include \r\n\r\n#include \"AzureCloudShellGenerator.h\"\r\n#include \"PowershellCoreProfileGenerator.h\"\r\n#include \"VsDevCmdGenerator.h\"\r\n#include \"VsDevShellGenerator.h\"\r\n#include \"WslDistroGenerator.h\"\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal;\r\nusing namespace winrt::Microsoft::Terminal::Control;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\nusing namespace winrt::Windows::Foundation::Collections;\r\nusing namespace Microsoft::Console;\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L\"ms-appx:///ProfileIcons/\" };\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L\".png\" };\r\nstatic constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L\"{9acb9455-ca41-5af7-950f-6bca1bc9722f}\" };\r\n\r\n// make sure this matches defaults.json.\r\nstatic constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L\"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}\" };\r\n\r\nCascadiaSettings::CascadiaSettings() :\r\n CascadiaSettings(true)\r\n{\r\n}\r\n\r\n// Constructor Description:\r\n// - Creates a new settings object. If addDynamicProfiles is true, we'll\r\n// automatically add the built-in profile generators to our list of profile\r\n// generators. Set this to `false` for unit testing.\r\n// Arguments:\r\n// - addDynamicProfiles: if true, we'll add the built-in DPGs.\r\nCascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :\r\n _globals{ winrt::make_self() },\r\n _allProfiles{ winrt::single_threaded_observable_vector() },\r\n _activeProfiles{ winrt::single_threaded_observable_vector() },\r\n _warnings{ winrt::single_threaded_vector() },\r\n _deserializationErrorMessage{ L\"\" },\r\n _defaultTerminals{ winrt::single_threaded_observable_vector() },\r\n _currentDefaultTerminal{ nullptr }\r\n{\r\n if (addDynamicProfiles)\r\n {\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n }\r\n}\r\n\r\nCascadiaSettings::CascadiaSettings(winrt::hstring json) :\r\n CascadiaSettings(false)\r\n{\r\n const auto jsonString{ til::u16u8(json) };\r\n _ParseJsonString(jsonString, false);\r\n _ApplyDefaultsFromUserSettings();\r\n LayerJson(_userSettings);\r\n _ValidateSettings();\r\n}\r\n\r\nwinrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const\r\n{\r\n // dynamic profile generators added by default\r\n auto settings{ winrt::make_self() };\r\n settings->_globals = _globals->Copy();\r\n for (auto warning : _warnings)\r\n {\r\n settings->_warnings.Append(warning);\r\n }\r\n settings->_loadError = _loadError;\r\n settings->_deserializationErrorMessage = _deserializationErrorMessage;\r\n<|next_version|>\n// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"CascadiaSettings.g.cpp\"\r\n\r\n#include \r\n\r\n#include \"AzureCloudShellGenerator.h\"\r\n#include \"PowershellCoreProfileGenerator.h\"\r\n#include \"VsDevCmdGenerator.h\"\r\n#include \"VsDevShellGenerator.h\"\r\n#include \"WslDistroGenerator.h\"\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal;\r\nusing namespace winrt::Microsoft::Terminal::Control;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\nusing namespace winrt::Windows::Foundation::Collections;\r\nusing namespace Microsoft::Console;\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L\"ms-appx:///ProfileIcons/\" };\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L\".png\" };\r\nstatic constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L\"{9acb9455-ca41-5af7-950f-6bca1bc9722f}\" };\r\n\r\n// make sure this matches defaults.json.\r\nstatic constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L\"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}\" };\r\n\r\nCascadiaSettings::CascadiaSettings() :\r\n CascadiaSettings(true)\r\n{\r\n}\r\n\r\n// Constructor Description:\r\n// - Creates a new settings object. If addDynamicProfiles is true, we'll\r\n// automatically add the built-in profile generators to our list of profile\r\n// generators. Set this to `false` for unit testing.\r\n// Arguments:\r\n// - addDynamicProfiles: if true, we'll add the built-in DPGs.\r\nCascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :\r\n _globals{ winrt::make_self() },\r\n _allProfiles{ winrt::single_threaded_observable_vector() },\r\n _activeProfiles{ winrt::single_threaded_observable_vector() },\r\n _warnings{ winrt::single_threaded_vector() },\r\n _deserializationErrorMessage{ L\"\" },\r\n _defaultTerminals{ winrt::single_threaded_observable_vector() },\r\n _currentDefaultTerminal{ nullptr }\r\n{\r\n if (addDynamicProfiles)\r\n {\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n }\r\n}\r\n\r\nCascadiaSettings::CascadiaSettings(winrt::hstring json) :\r\n CascadiaSettings(false)\r\n{\r\n const auto jsonString{ til::u16u8(json) };\r\n _ParseJsonString(jsonString, false);\r\n _ApplyDefaultsFromUserSettings();\r\n LayerJson(_userSettings);\r\n _ValidateSettings();\r\n}\r\n\r\nwinrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const\r\n{\r\n // dynamic profile generators added by default\r\n auto settings{ winrt::make_self() };\r\n settings->_globals = _globals->Copy();\r\n for (auto warning : _warnings)\r\n {\r\n settings->_warnings.Append(warning);\r\n }\r\n settings->_loadError = _loadError;\r\n settings->_deserializationErrorMessage = _deserializationErrorMessage;\r\n", "current_contents": "// Copyright (c) Microsoft Corporation.\r\n// Licensed under the MIT license.\r\n\r\n#include \"pch.h\"\r\n#include \"CascadiaSettings.h\"\r\n#include \"CascadiaSettings.g.cpp\"\r\n\r\n#include \r\n\r\n#include \"AzureCloudShellGenerator.h\"\r\n#include \"PowershellCoreProfileGenerator.h\"\r\n#include \"VsDevCmdGenerator.h\"\r\n#include \"VsDevShellGenerator.h\"\r\n#include \"WslDistroGenerator.h\"\r\n\r\nusing namespace ::Microsoft::Terminal::Settings::Model;\r\nusing namespace winrt::Microsoft::Terminal;\r\nusing namespace winrt::Microsoft::Terminal::Control;\r\nusing namespace winrt::Microsoft::Terminal::Settings::Model::implementation;\r\nusing namespace winrt::Windows::Foundation::Collections;\r\nusing namespace Microsoft::Console;\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_PATH{ L\"ms-appx:///ProfileIcons/\" };\r\n\r\nstatic constexpr std::wstring_view PACKAGED_PROFILE_ICON_EXTENSION{ L\".png\" };\r\nstatic constexpr std::wstring_view DEFAULT_LINUX_ICON_GUID{ L\"{9acb9455-ca41-5af7-950f-6bca1bc9722f}\" };\r\n\r\n// make sure this matches defaults.json.\r\nstatic constexpr std::wstring_view DEFAULT_WINDOWS_POWERSHELL_GUID{ L\"{61c54bbd-c2c6-5271-96e7-009a87ff44bf}\" };\r\n\r\nCascadiaSettings::CascadiaSettings() :\r\n CascadiaSettings(true)\r\n{\r\n}\r\n\r\n// Constructor Description:\r\n// - Creates a new settings object. If addDynamicProfiles is true, we'll\r\n// automatically add the built-in profile generators to our list of profile\r\n// generators. Set this to `false` for unit testing.\r\n// Arguments:\r\n// - addDynamicProfiles: if true, we'll add the built-in DPGs.\r\nCascadiaSettings::CascadiaSettings(const bool addDynamicProfiles) :\r\n _globals{ winrt::make_self() },\r\n _allProfiles{ winrt::single_threaded_observable_vector() },\r\n _activeProfiles{ winrt::single_threaded_observable_vector() },\r\n _warnings{ winrt::single_threaded_vector() },\r\n _deserializationErrorMessage{ L\"\" },\r\n _defaultTerminals{ winrt::single_threaded_observable_vector() },\r\n _currentDefaultTerminal{ nullptr }\r\n{\r\n if (addDynamicProfiles)\r\n {\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n _profileGenerators.emplace_back(std::make_unique());\r\n }\r\n}\r\n\r\nCascadiaSettings::CascadiaSettings(winrt::hstring json) :\r\n CascadiaSettings(false)\r\n{\r\n const auto jsonString{ til::u16u8(json) };\r\n _ParseJsonString(jsonString, false);\r\n _ApplyDefaultsFromUserSettings();\r\n LayerJson(_userSettings);\r\n _ValidateSettings();\r\n}\r\n\r\nwinrt::Microsoft::Terminal::Settings::Model::CascadiaSettings CascadiaSettings::Copy() const\r\n{\r\n // dynamic profile generators added by default\r\n auto settings{ winrt::make_self() };\r\n settings->_globals = _globals->Copy();\r\n for (auto warning : _warnings)\r\n {\r\n settings->_warnings.Append(warning);\r\n }\r\n settings->_loadError = _loadError;\r\n settings->_deserializationErrorMessage = _deserializationErrorMessage;\r"} {"commit": "bee6fb4368a59e6d72a92f5df7770d012368ef1a", "message": "Add the ability to quit all terminal instances (#11143)", "old_file": "src/cascadia/UnitTests_Remoting/RemotingTests.cpp", "new_file": "src/cascadia/UnitTests_Remoting/RemotingTests.cpp", "status": "M", "old_contents": " // class can be used to replace a peasant inside a Monarch, to emulate that\r\n // peasant process dying. Any time the monarch tries to do something to this\r\n // peasant, it'll throw an exception.\r\n struct DeadPeasant : implements\r\n {\r\n DeadPeasant() = default;\r\n void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetID() { throw winrt::hresult_error{}; };\r\n winrt::hstring WindowName() { throw winrt::hresult_error{}; };\r\n winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };\r\n void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetPID() { throw winrt::hresult_error{}; };\r\n bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void RequestIdentifyWindows() { throw winrt::hresult_error{}; };\r\n void DisplayWindowId() { throw winrt::hresult_error{}; };\r\n Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }\r\n Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }\r\n void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };\r\n void RequestShowTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestHideTrayIcon() { throw winrt::hresult_error{}; };\r\n TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);\r\n TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);\r\n TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);\r\n TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);\r\n TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n };\r\n\r\n class RemotingTests\r\n {\r\n BEGIN_TEST_CLASS(RemotingTests)\r\n END_TEST_CLASS()\r\n\r\n TEST_METHOD(CreateMonarch);\r\n TEST_METHOD(CreatePeasant);\r\n TEST_METHOD(CreatePeasantWithNew);\r\n TEST_METHOD(AddPeasants);\r\n TEST_METHOD(GetPeasantsByID);\r\n TEST_METHOD(AddPeasantsToNewMonarch);\r\n TEST_METHOD(RemovePeasantFromMonarchWhenFreed);\r\n\r\n TEST_METHOD(ProposeCommandlineNoWindow);\r\n TEST_METHOD(ProposeCommandlineGivenWindow);\r\n TEST_METHOD(ProposeCommandlineNegativeWindow);\r\n TEST_METHOD(ProposeCommandlineCurrentWindow);\r\n TEST_METHOD(ProposeCommandlineNonExistentWindow);\r\n TEST_METHOD(ProposeCommandlineDeadWindow);\r\n\r\n TEST_METHOD(MostRecentWindowSameDesktops);\r\n TEST_METHOD(MostRecentWindowDifferentDesktops);\r", "new_contents": " // class can be used to replace a peasant inside a Monarch, to emulate that\r\n // peasant process dying. Any time the monarch tries to do something to this\r\n // peasant, it'll throw an exception.\r\n struct DeadPeasant : implements\r\n {\r\n DeadPeasant() = default;\r\n void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetID() { throw winrt::hresult_error{}; };\r\n winrt::hstring WindowName() { throw winrt::hresult_error{}; };\r\n winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };\r\n void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetPID() { throw winrt::hresult_error{}; };\r\n bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void RequestIdentifyWindows() { throw winrt::hresult_error{}; };\r\n void DisplayWindowId() { throw winrt::hresult_error{}; };\r\n Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }\r\n Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }\r\n void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };\r\n void RequestShowTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestHideTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestQuitAll() { throw winrt::hresult_error{}; };\r\n void Quit() { throw winrt::hresult_error{}; };\r\n TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);\r\n TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);\r\n TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);\r\n TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);\r\n TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(QuitAllRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(QuitRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n };\r\n\r\n class RemotingTests\r\n {\r\n BEGIN_TEST_CLASS(RemotingTests)\r\n END_TEST_CLASS()\r\n\r\n TEST_METHOD(CreateMonarch);\r\n TEST_METHOD(CreatePeasant);\r\n TEST_METHOD(CreatePeasantWithNew);\r\n TEST_METHOD(AddPeasants);\r\n TEST_METHOD(GetPeasantsByID);\r\n TEST_METHOD(AddPeasantsToNewMonarch);\r\n TEST_METHOD(RemovePeasantFromMonarchWhenFreed);\r\n\r\n TEST_METHOD(ProposeCommandlineNoWindow);\r\n TEST_METHOD(ProposeCommandlineGivenWindow);\r\n TEST_METHOD(ProposeCommandlineNegativeWindow);\r\n TEST_METHOD(ProposeCommandlineCurrentWindow);\r\n TEST_METHOD(ProposeCommandlineNonExistentWindow);\r\n TEST_METHOD(ProposeCommandlineDeadWindow);\r\n\r\n TEST_METHOD(MostRecentWindowSameDesktops);\r\n TEST_METHOD(MostRecentWindowDifferentDesktops);\r", "text": "<|original_code|>\n // class can be used to replace a peasant inside a Monarch, to emulate that\r\n // peasant process dying. Any time the monarch tries to do something to this\r\n // peasant, it'll throw an exception.\r\n struct DeadPeasant : implements\r\n {\r\n DeadPeasant() = default;\r\n void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetID() { throw winrt::hresult_error{}; };\r\n winrt::hstring WindowName() { throw winrt::hresult_error{}; };\r\n winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };\r\n void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetPID() { throw winrt::hresult_error{}; };\r\n bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void RequestIdentifyWindows() { throw winrt::hresult_error{}; };\r\n void DisplayWindowId() { throw winrt::hresult_error{}; };\r\n Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }\r\n Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }\r\n void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };\r\n void RequestShowTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestHideTrayIcon() { throw winrt::hresult_error{}; };\r\n TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);\r\n TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);\r\n TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);\r\n TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);\r\n TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n };\r\n\r\n class RemotingTests\r\n {\r\n BEGIN_TEST_CLASS(RemotingTests)\r\n END_TEST_CLASS()\r\n\r\n TEST_METHOD(CreateMonarch);\r\n TEST_METHOD(CreatePeasant);\r\n TEST_METHOD(CreatePeasantWithNew);\r\n TEST_METHOD(AddPeasants);\r\n TEST_METHOD(GetPeasantsByID);\r\n TEST_METHOD(AddPeasantsToNewMonarch);\r\n TEST_METHOD(RemovePeasantFromMonarchWhenFreed);\r\n\r\n TEST_METHOD(ProposeCommandlineNoWindow);\r\n TEST_METHOD(ProposeCommandlineGivenWindow);\r\n TEST_METHOD(ProposeCommandlineNegativeWindow);\r\n TEST_METHOD(ProposeCommandlineCurrentWindow);\r\n TEST_METHOD(ProposeCommandlineNonExistentWindow);\r\n TEST_METHOD(ProposeCommandlineDeadWindow);\r\n\r\n TEST_METHOD(MostRecentWindowSameDesktops);\r\n TEST_METHOD(MostRecentWindowDifferentDesktops);\r\n<|edits_diff|>\n--- src/cascadia/UnitTests_Remoting/RemotingTests.cpp\n+++ src/cascadia/UnitTests_Remoting/RemotingTests.cpp\n@@ -20,6 +20,8 @@\n void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };\n void RequestShowTrayIcon() { throw winrt::hresult_error{}; };\n void RequestHideTrayIcon() { throw winrt::hresult_error{}; };\n+ void RequestQuitAll() { throw winrt::hresult_error{}; };\n+ void Quit() { throw winrt::hresult_error{}; };\n TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);\n TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);\n TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\n<|current_version|>\n // class can be used to replace a peasant inside a Monarch, to emulate that\r\n // peasant process dying. Any time the monarch tries to do something to this\r\n // peasant, it'll throw an exception.\r\n struct DeadPeasant : implements\r\n {\r\n DeadPeasant() = default;\r\n void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetID() { throw winrt::hresult_error{}; };\r\n winrt::hstring WindowName() { throw winrt::hresult_error{}; };\r\n winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };\r\n void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetPID() { throw winrt::hresult_error{}; };\r\n bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void RequestIdentifyWindows() { throw winrt::hresult_error{}; };\r\n void DisplayWindowId() { throw winrt::hresult_error{}; };\r\n Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }\r\n Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }\r\n void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };\r\n void RequestShowTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestHideTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestQuitAll() { throw winrt::hresult_error{}; };\r\n void Quit() { throw winrt::hresult_error{}; };\r\n TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);\r\n TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);\r\n TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);\r\n TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);\r\n TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n };\r\n\r\n class RemotingTests\r\n {\r\n BEGIN_TEST_CLASS(RemotingTests)\r\n END_TEST_CLASS()\r\n\r\n TEST_METHOD(CreateMonarch);\r\n TEST_METHOD(CreatePeasant);\r\n TEST_METHOD(CreatePeasantWithNew);\r\n TEST_METHOD(AddPeasants);\r\n TEST_METHOD(GetPeasantsByID);\r\n TEST_METHOD(AddPeasantsToNewMonarch);\r\n TEST_METHOD(RemovePeasantFromMonarchWhenFreed);\r\n\r\n TEST_METHOD(ProposeCommandlineNoWindow);\r\n TEST_METHOD(ProposeCommandlineGivenWindow);\r\n TEST_METHOD(ProposeCommandlineNegativeWindow);\r\n TEST_METHOD(ProposeCommandlineCurrentWindow);\r\n TEST_METHOD(ProposeCommandlineNonExistentWindow);\r\n TEST_METHOD(ProposeCommandlineDeadWindow);\r\n\r\n TEST_METHOD(MostRecentWindowSameDesktops);\r\n TEST_METHOD(MostRecentWindowDifferentDesktops);\r\n<|next_version|>\n // class can be used to replace a peasant inside a Monarch, to emulate that\r\n // peasant process dying. Any time the monarch tries to do something to this\r\n // peasant, it'll throw an exception.\r\n struct DeadPeasant : implements\r\n {\r\n DeadPeasant() = default;\r\n void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetID() { throw winrt::hresult_error{}; };\r\n winrt::hstring WindowName() { throw winrt::hresult_error{}; };\r\n winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };\r\n void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetPID() { throw winrt::hresult_error{}; };\r\n bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void RequestIdentifyWindows() { throw winrt::hresult_error{}; };\r\n void DisplayWindowId() { throw winrt::hresult_error{}; };\r\n Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }\r\n Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }\r\n void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };\r\n void RequestShowTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestHideTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestQuitAll() { throw winrt::hresult_error{}; };\r\n void Quit() { throw winrt::hresult_error{}; };\r\n TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);\r\n TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);\r\n TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);\r\n TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);\r\n TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(QuitAllRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(QuitRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n };\r\n\r\n class RemotingTests\r\n {\r\n BEGIN_TEST_CLASS(RemotingTests)\r\n END_TEST_CLASS()\r\n\r\n TEST_METHOD(CreateMonarch);\r\n TEST_METHOD(CreatePeasant);\r\n TEST_METHOD(CreatePeasantWithNew);\r\n TEST_METHOD(AddPeasants);\r\n TEST_METHOD(GetPeasantsByID);\r\n TEST_METHOD(AddPeasantsToNewMonarch);\r\n TEST_METHOD(RemovePeasantFromMonarchWhenFreed);\r\n\r\n TEST_METHOD(ProposeCommandlineNoWindow);\r\n TEST_METHOD(ProposeCommandlineGivenWindow);\r\n TEST_METHOD(ProposeCommandlineNegativeWindow);\r\n TEST_METHOD(ProposeCommandlineCurrentWindow);\r\n TEST_METHOD(ProposeCommandlineNonExistentWindow);\r\n TEST_METHOD(ProposeCommandlineDeadWindow);\r\n\r\n TEST_METHOD(MostRecentWindowSameDesktops);\r\n TEST_METHOD(MostRecentWindowDifferentDesktops);\r\n", "current_contents": " // class can be used to replace a peasant inside a Monarch, to emulate that\r\n // peasant process dying. Any time the monarch tries to do something to this\r\n // peasant, it'll throw an exception.\r\n struct DeadPeasant : implements\r\n {\r\n DeadPeasant() = default;\r\n void AssignID(uint64_t /*id*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetID() { throw winrt::hresult_error{}; };\r\n winrt::hstring WindowName() { throw winrt::hresult_error{}; };\r\n winrt::hstring ActiveTabTitle() { throw winrt::hresult_error{}; };\r\n void ActiveTabTitle(const winrt::hstring& /*value*/) { throw winrt::hresult_error{}; };\r\n uint64_t GetPID() { throw winrt::hresult_error{}; };\r\n bool ExecuteCommandline(const Remoting::CommandlineArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void ActivateWindow(const Remoting::WindowActivatedArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void RequestIdentifyWindows() { throw winrt::hresult_error{}; };\r\n void DisplayWindowId() { throw winrt::hresult_error{}; };\r\n Remoting::CommandlineArgs InitialArgs() { throw winrt::hresult_error{}; }\r\n Remoting::WindowActivatedArgs GetLastActivatedArgs() { throw winrt::hresult_error{}; }\r\n void RequestRename(const Remoting::RenameRequestArgs& /*args*/) { throw winrt::hresult_error{}; }\r\n void Summon(const Remoting::SummonWindowBehavior& /*args*/) { throw winrt::hresult_error{}; };\r\n void RequestShowTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestHideTrayIcon() { throw winrt::hresult_error{}; };\r\n void RequestQuitAll() { throw winrt::hresult_error{}; };\r\n void Quit() { throw winrt::hresult_error{}; };\r\n TYPED_EVENT(WindowActivated, winrt::Windows::Foundation::IInspectable, Remoting::WindowActivatedArgs);\r\n TYPED_EVENT(ExecuteCommandlineRequested, winrt::Windows::Foundation::IInspectable, Remoting::CommandlineArgs);\r\n TYPED_EVENT(IdentifyWindowsRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(DisplayWindowIdRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(RenameRequested, winrt::Windows::Foundation::IInspectable, Remoting::RenameRequestArgs);\r\n TYPED_EVENT(SummonRequested, winrt::Windows::Foundation::IInspectable, Remoting::SummonWindowBehavior);\r\n TYPED_EVENT(ShowTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n TYPED_EVENT(HideTrayIconRequested, winrt::Windows::Foundation::IInspectable, winrt::Windows::Foundation::IInspectable);\r\n };\r\n\r\n class RemotingTests\r\n {\r\n BEGIN_TEST_CLASS(RemotingTests)\r\n END_TEST_CLASS()\r\n\r\n TEST_METHOD(CreateMonarch);\r\n TEST_METHOD(CreatePeasant);\r\n TEST_METHOD(CreatePeasantWithNew);\r\n TEST_METHOD(AddPeasants);\r\n TEST_METHOD(GetPeasantsByID);\r\n TEST_METHOD(AddPeasantsToNewMonarch);\r\n TEST_METHOD(RemovePeasantFromMonarchWhenFreed);\r\n\r\n TEST_METHOD(ProposeCommandlineNoWindow);\r\n TEST_METHOD(ProposeCommandlineGivenWindow);\r\n TEST_METHOD(ProposeCommandlineNegativeWindow);\r\n TEST_METHOD(ProposeCommandlineCurrentWindow);\r\n TEST_METHOD(ProposeCommandlineNonExistentWindow);\r\n TEST_METHOD(ProposeCommandlineDeadWindow);\r\n\r\n TEST_METHOD(MostRecentWindowSameDesktops);\r\n TEST_METHOD(MostRecentWindowDifferentDesktops);\r"} {"commit": "ea1518e839abe668c20f7e0074c0721f803da898", "message": "llama-tts : avoid crashes related to bad model file paths (#12482)", "old_file": "examples/tts/tts.cpp", "new_file": "examples/tts/tts.cpp", "status": "M", "old_contents": "\n const int n_parallel = params.n_parallel;\n const int n_predict = params.n_predict;\n\n common_init();\n\n // init LLM\n\n llama_backend_init();\n llama_numa_init(params.numa);\n\n llama_model * model_ttc = NULL; // text-to-codes\n llama_model * model_cts = NULL; // codes-to-speech\n\n llama_context * ctx_ttc = NULL;\n llama_context * ctx_cts = NULL;\n\n common_init_result llama_init_ttc = common_init_from_params(params);\n\n model_ttc = llama_init_ttc.model.get();\n ctx_ttc = llama_init_ttc.context.get();\n\n const llama_vocab * vocab = llama_model_get_vocab(model_ttc);\n\n // TODO: refactor in a common struct\n params.model = params.vocoder.model;\n params.model_url = params.vocoder.model_url;\n params.hf_repo = params.vocoder.hf_repo;\n params.hf_file = params.vocoder.hf_file;\n\n params.embedding = true;\n\n common_init_result llama_init_cts = common_init_from_params(params);\n\n model_cts = llama_init_cts.model.get();\n ctx_cts = llama_init_cts.context.get();\n\n std::vector smpl(n_parallel);\n for (int i = 0; i < n_parallel; ++i) {\n params.sampling.no_perf = (i != 0);\n params.sampling.seed = params.sampling.seed + 1;\n\n smpl[i] = common_sampler_init(model_ttc, params.sampling);\n }\n\n LOG_INF(\"sampler seed: %u\\n\", common_sampler_get_seed(smpl[0]));\n LOG_INF(\"sampler params: \\n%s\\n\", params.sampling.print().c_str());\n LOG_INF(\"sampler chain: %s\\n\", common_sampler_print(smpl[0]).c_str());\n\n LOG_INF(\"%s: loading done\\n\", __func__);\n\n const auto t_main_start = ggml_time_us();\n\n std::vector codes;\n std::vector guide_tokens;\n\n // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json\n std::string audio_text = \"<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>\";\n std::string audio_data = R\"(<|audio_start|>\nthe<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>", "new_contents": "\n const int n_parallel = params.n_parallel;\n const int n_predict = params.n_predict;\n\n common_init();\n\n // init LLM\n\n llama_backend_init();\n llama_numa_init(params.numa);\n\n llama_model * model_ttc = NULL; // text-to-codes\n llama_model * model_cts = NULL; // codes-to-speech\n\n llama_context * ctx_ttc = NULL;\n llama_context * ctx_cts = NULL;\n\n common_init_result llama_init_ttc = common_init_from_params(params);\n\n model_ttc = llama_init_ttc.model.get();\n ctx_ttc = llama_init_ttc.context.get();\n\n if (model_ttc == nullptr || ctx_ttc == nullptr) {\n return ENOENT;\n }\n\n const llama_vocab * vocab = llama_model_get_vocab(model_ttc);\n\n // TODO: refactor in a common struct\n params.model = params.vocoder.model;\n params.model_url = params.vocoder.model_url;\n params.hf_repo = params.vocoder.hf_repo;\n params.hf_file = params.vocoder.hf_file;\n\n params.embedding = true;\n\n common_init_result llama_init_cts = common_init_from_params(params);\n\n model_cts = llama_init_cts.model.get();\n ctx_cts = llama_init_cts.context.get();\n\n if (model_cts == nullptr || ctx_cts == nullptr) {\n return ENOENT;\n }\n\n std::vector smpl(n_parallel);\n for (int i = 0; i < n_parallel; ++i) {\n params.sampling.no_perf = (i != 0);\n params.sampling.seed = params.sampling.seed + 1;\n\n smpl[i] = common_sampler_init(model_ttc, params.sampling);\n }\n\n LOG_INF(\"sampler seed: %u\\n\", common_sampler_get_seed(smpl[0]));\n LOG_INF(\"sampler params: \\n%s\\n\", params.sampling.print().c_str());\n LOG_INF(\"sampler chain: %s\\n\", common_sampler_print(smpl[0]).c_str());\n\n LOG_INF(\"%s: loading done\\n\", __func__);\n\n const auto t_main_start = ggml_time_us();\n\n std::vector codes;\n std::vector guide_tokens;\n\n // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json\n std::string audio_text = \"<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>\";\n std::string audio_data = R\"(<|audio_start|>\nthe<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>", "text": "<|original_code|>\n\n const int n_parallel = params.n_parallel;\n const int n_predict = params.n_predict;\n\n common_init();\n\n // init LLM\n\n llama_backend_init();\n llama_numa_init(params.numa);\n\n llama_model * model_ttc = NULL; // text-to-codes\n llama_model * model_cts = NULL; // codes-to-speech\n\n llama_context * ctx_ttc = NULL;\n llama_context * ctx_cts = NULL;\n\n common_init_result llama_init_ttc = common_init_from_params(params);\n\n model_ttc = llama_init_ttc.model.get();\n ctx_ttc = llama_init_ttc.context.get();\n\n const llama_vocab * vocab = llama_model_get_vocab(model_ttc);\n\n // TODO: refactor in a common struct\n params.model = params.vocoder.model;\n params.model_url = params.vocoder.model_url;\n params.hf_repo = params.vocoder.hf_repo;\n params.hf_file = params.vocoder.hf_file;\n\n params.embedding = true;\n\n common_init_result llama_init_cts = common_init_from_params(params);\n\n model_cts = llama_init_cts.model.get();\n ctx_cts = llama_init_cts.context.get();\n\n std::vector smpl(n_parallel);\n for (int i = 0; i < n_parallel; ++i) {\n params.sampling.no_perf = (i != 0);\n params.sampling.seed = params.sampling.seed + 1;\n\n smpl[i] = common_sampler_init(model_ttc, params.sampling);\n }\n\n LOG_INF(\"sampler seed: %u\\n\", common_sampler_get_seed(smpl[0]));\n LOG_INF(\"sampler params: \\n%s\\n\", params.sampling.print().c_str());\n LOG_INF(\"sampler chain: %s\\n\", common_sampler_print(smpl[0]).c_str());\n\n LOG_INF(\"%s: loading done\\n\", __func__);\n\n const auto t_main_start = ggml_time_us();\n\n std::vector codes;\n std::vector guide_tokens;\n\n // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json\n std::string audio_text = \"<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>\";\n std::string audio_data = R\"(<|audio_start|>\nthe<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>\n<|edits_diff|>\n--- examples/tts/tts.cpp\n+++ examples/tts/tts.cpp\n@@ -19,6 +19,10 @@\n \n model_ttc = llama_init_ttc.model.get();\n ctx_ttc = llama_init_ttc.context.get();\n+\n+ if (model_ttc == nullptr || ctx_ttc == nullptr) {\n+ return ENOENT;\n+ }\n \n const llama_vocab * vocab = llama_model_get_vocab(model_ttc);\n \n<|current_version|>\n\n const int n_parallel = params.n_parallel;\n const int n_predict = params.n_predict;\n\n common_init();\n\n // init LLM\n\n llama_backend_init();\n llama_numa_init(params.numa);\n\n llama_model * model_ttc = NULL; // text-to-codes\n llama_model * model_cts = NULL; // codes-to-speech\n\n llama_context * ctx_ttc = NULL;\n llama_context * ctx_cts = NULL;\n\n common_init_result llama_init_ttc = common_init_from_params(params);\n\n model_ttc = llama_init_ttc.model.get();\n ctx_ttc = llama_init_ttc.context.get();\n\n if (model_ttc == nullptr || ctx_ttc == nullptr) {\n return ENOENT;\n }\n\n const llama_vocab * vocab = llama_model_get_vocab(model_ttc);\n\n // TODO: refactor in a common struct\n params.model = params.vocoder.model;\n params.model_url = params.vocoder.model_url;\n params.hf_repo = params.vocoder.hf_repo;\n params.hf_file = params.vocoder.hf_file;\n\n params.embedding = true;\n\n common_init_result llama_init_cts = common_init_from_params(params);\n\n model_cts = llama_init_cts.model.get();\n ctx_cts = llama_init_cts.context.get();\n\n std::vector smpl(n_parallel);\n for (int i = 0; i < n_parallel; ++i) {\n params.sampling.no_perf = (i != 0);\n params.sampling.seed = params.sampling.seed + 1;\n\n smpl[i] = common_sampler_init(model_ttc, params.sampling);\n }\n\n LOG_INF(\"sampler seed: %u\\n\", common_sampler_get_seed(smpl[0]));\n LOG_INF(\"sampler params: \\n%s\\n\", params.sampling.print().c_str());\n LOG_INF(\"sampler chain: %s\\n\", common_sampler_print(smpl[0]).c_str());\n\n LOG_INF(\"%s: loading done\\n\", __func__);\n\n const auto t_main_start = ggml_time_us();\n\n std::vector codes;\n std::vector guide_tokens;\n\n // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json\n std::string audio_text = \"<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>\";\n std::string audio_data = R\"(<|audio_start|>\nthe<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>\n<|next_version|>\n\n const int n_parallel = params.n_parallel;\n const int n_predict = params.n_predict;\n\n common_init();\n\n // init LLM\n\n llama_backend_init();\n llama_numa_init(params.numa);\n\n llama_model * model_ttc = NULL; // text-to-codes\n llama_model * model_cts = NULL; // codes-to-speech\n\n llama_context * ctx_ttc = NULL;\n llama_context * ctx_cts = NULL;\n\n common_init_result llama_init_ttc = common_init_from_params(params);\n\n model_ttc = llama_init_ttc.model.get();\n ctx_ttc = llama_init_ttc.context.get();\n\n if (model_ttc == nullptr || ctx_ttc == nullptr) {\n return ENOENT;\n }\n\n const llama_vocab * vocab = llama_model_get_vocab(model_ttc);\n\n // TODO: refactor in a common struct\n params.model = params.vocoder.model;\n params.model_url = params.vocoder.model_url;\n params.hf_repo = params.vocoder.hf_repo;\n params.hf_file = params.vocoder.hf_file;\n\n params.embedding = true;\n\n common_init_result llama_init_cts = common_init_from_params(params);\n\n model_cts = llama_init_cts.model.get();\n ctx_cts = llama_init_cts.context.get();\n\n if (model_cts == nullptr || ctx_cts == nullptr) {\n return ENOENT;\n }\n\n std::vector smpl(n_parallel);\n for (int i = 0; i < n_parallel; ++i) {\n params.sampling.no_perf = (i != 0);\n params.sampling.seed = params.sampling.seed + 1;\n\n smpl[i] = common_sampler_init(model_ttc, params.sampling);\n }\n\n LOG_INF(\"sampler seed: %u\\n\", common_sampler_get_seed(smpl[0]));\n LOG_INF(\"sampler params: \\n%s\\n\", params.sampling.print().c_str());\n LOG_INF(\"sampler chain: %s\\n\", common_sampler_print(smpl[0]).c_str());\n\n LOG_INF(\"%s: loading done\\n\", __func__);\n\n const auto t_main_start = ggml_time_us();\n\n std::vector codes;\n std::vector guide_tokens;\n\n // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json\n std::string audio_text = \"<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>\";\n std::string audio_data = R\"(<|audio_start|>\nthe<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>\n", "current_contents": "\n const int n_parallel = params.n_parallel;\n const int n_predict = params.n_predict;\n\n common_init();\n\n // init LLM\n\n llama_backend_init();\n llama_numa_init(params.numa);\n\n llama_model * model_ttc = NULL; // text-to-codes\n llama_model * model_cts = NULL; // codes-to-speech\n\n llama_context * ctx_ttc = NULL;\n llama_context * ctx_cts = NULL;\n\n common_init_result llama_init_ttc = common_init_from_params(params);\n\n model_ttc = llama_init_ttc.model.get();\n ctx_ttc = llama_init_ttc.context.get();\n\n if (model_ttc == nullptr || ctx_ttc == nullptr) {\n return ENOENT;\n }\n\n const llama_vocab * vocab = llama_model_get_vocab(model_ttc);\n\n // TODO: refactor in a common struct\n params.model = params.vocoder.model;\n params.model_url = params.vocoder.model_url;\n params.hf_repo = params.vocoder.hf_repo;\n params.hf_file = params.vocoder.hf_file;\n\n params.embedding = true;\n\n common_init_result llama_init_cts = common_init_from_params(params);\n\n model_cts = llama_init_cts.model.get();\n ctx_cts = llama_init_cts.context.get();\n\n std::vector smpl(n_parallel);\n for (int i = 0; i < n_parallel; ++i) {\n params.sampling.no_perf = (i != 0);\n params.sampling.seed = params.sampling.seed + 1;\n\n smpl[i] = common_sampler_init(model_ttc, params.sampling);\n }\n\n LOG_INF(\"sampler seed: %u\\n\", common_sampler_get_seed(smpl[0]));\n LOG_INF(\"sampler params: \\n%s\\n\", params.sampling.print().c_str());\n LOG_INF(\"sampler chain: %s\\n\", common_sampler_print(smpl[0]).c_str());\n\n LOG_INF(\"%s: loading done\\n\", __func__);\n\n const auto t_main_start = ggml_time_us();\n\n std::vector codes;\n std::vector guide_tokens;\n\n // the default speaker profile is from: https://github.com/edwko/OuteTTS/blob/main/outetts/version/v1/default_speakers/en_male_1.json\n std::string audio_text = \"<|text_start|>the<|text_sep|>overall<|text_sep|>package<|text_sep|>from<|text_sep|>just<|text_sep|>two<|text_sep|>people<|text_sep|>is<|text_sep|>pretty<|text_sep|>remarkable<|text_sep|>sure<|text_sep|>i<|text_sep|>have<|text_sep|>some<|text_sep|>critiques<|text_sep|>about<|text_sep|>some<|text_sep|>of<|text_sep|>the<|text_sep|>gameplay<|text_sep|>aspects<|text_sep|>but<|text_sep|>its<|text_sep|>still<|text_sep|>really<|text_sep|>enjoyable<|text_sep|>and<|text_sep|>it<|text_sep|>looks<|text_sep|>lovely<|text_sep|>\";\n std::string audio_data = R\"(<|audio_start|>\nthe<|t_0.08|><|code_start|><|257|><|740|><|636|><|913|><|788|><|1703|><|code_end|>"} {"commit": "c9ee7118d5644dd3df70ea6878b36a9761616aab", "message": "check for nans in imatrix and quantize (#7807)", "old_file": "examples/imatrix/imatrix.cpp", "new_file": "examples/imatrix/imatrix.cpp", "status": "M", "old_contents": " if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);\n }\n // loop over all possible experts, regardless if they are used or not in the batch\n for (int ex = 0; ex < n_as; ++ex) {\n size_t e_start = ex*src1->ne[0];\n\n for (int idx = 0; idx < n_ids; ++idx) {\n for (int row = 0; row < (int)src1->ne[2]; ++row) {\n const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);\n\n GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check\n\n if (excur != ex) continue;\n\n const int64_t i11 = idx % src1->ne[1];\n const int64_t i12 = row;\n const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);\n\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[e_start + j] += x[j]*x[j];\n e.counts[e_start + j]++;\n }\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n } else {\n auto & e = m_stats[wname];\n if (e.values.empty()) {\n e.values.resize(src1->ne[0], 0);\n e.counts.resize(src1->ne[0], 0);\n }\n else if (e.values.size() != (size_t)src1->ne[0]) {\n fprintf(stderr, \"Oops: inconsistent size for %s (%d vs %d)\\n\", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);\n exit(1); //GGML_ASSERT(false);\n }\n ++e.ncall;\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);\n }\n for (int row = 0; row < (int)src1->ne[1]; ++row) {\n const float * x = data + row * src1->ne[0];\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[j] += x[j]*x[j];\n e.counts[j]++;\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n\n return true;\n}\n\nvoid IMatrixCollector::save_imatrix(int ncall) const {\n auto fname = m_params.out_file;\n if (fname.empty()) {\n fname = \"imatrix.dat\";\n }\n\n if (ncall > 0) {\n fname += \".at_\";", "new_contents": " if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);\n }\n // loop over all possible experts, regardless if they are used or not in the batch\n for (int ex = 0; ex < n_as; ++ex) {\n size_t e_start = ex*src1->ne[0];\n\n for (int idx = 0; idx < n_ids; ++idx) {\n for (int row = 0; row < (int)src1->ne[2]; ++row) {\n const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);\n\n GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check\n\n if (excur != ex) continue;\n\n const int64_t i11 = idx % src1->ne[1];\n const int64_t i12 = row;\n const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);\n\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[e_start + j] += x[j]*x[j];\n e.counts[e_start + j]++;\n if (!std::isfinite(e.values[e_start + j])) {\n fprintf(stderr, \"%f detected in %s\\n\", e.values[e_start + j], wname.c_str());\n exit(1);\n }\n }\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n } else {\n auto & e = m_stats[wname];\n if (e.values.empty()) {\n e.values.resize(src1->ne[0], 0);\n e.counts.resize(src1->ne[0], 0);\n }\n else if (e.values.size() != (size_t)src1->ne[0]) {\n fprintf(stderr, \"Oops: inconsistent size for %s (%d vs %d)\\n\", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);\n exit(1); //GGML_ASSERT(false);\n }\n ++e.ncall;\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);\n }\n for (int row = 0; row < (int)src1->ne[1]; ++row) {\n const float * x = data + row * src1->ne[0];\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[j] += x[j]*x[j];\n e.counts[j]++;\n if (!std::isfinite(e.values[j])) {\n fprintf(stderr, \"%f detected in %s\\n\", e.values[j], wname.c_str());\n exit(1);\n }\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n\n return true;\n}\n\nvoid IMatrixCollector::save_imatrix(int ncall) const {\n auto fname = m_params.out_file;\n if (fname.empty()) {\n fname = \"imatrix.dat\";\n }\n\n if (ncall > 0) {\n fname += \".at_\";", "text": "<|original_code|>\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);\n }\n // loop over all possible experts, regardless if they are used or not in the batch\n for (int ex = 0; ex < n_as; ++ex) {\n size_t e_start = ex*src1->ne[0];\n\n for (int idx = 0; idx < n_ids; ++idx) {\n for (int row = 0; row < (int)src1->ne[2]; ++row) {\n const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);\n\n GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check\n\n if (excur != ex) continue;\n\n const int64_t i11 = idx % src1->ne[1];\n const int64_t i12 = row;\n const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);\n\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[e_start + j] += x[j]*x[j];\n e.counts[e_start + j]++;\n }\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n } else {\n auto & e = m_stats[wname];\n if (e.values.empty()) {\n e.values.resize(src1->ne[0], 0);\n e.counts.resize(src1->ne[0], 0);\n }\n else if (e.values.size() != (size_t)src1->ne[0]) {\n fprintf(stderr, \"Oops: inconsistent size for %s (%d vs %d)\\n\", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);\n exit(1); //GGML_ASSERT(false);\n }\n ++e.ncall;\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);\n }\n for (int row = 0; row < (int)src1->ne[1]; ++row) {\n const float * x = data + row * src1->ne[0];\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[j] += x[j]*x[j];\n e.counts[j]++;\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n\n return true;\n}\n\nvoid IMatrixCollector::save_imatrix(int ncall) const {\n auto fname = m_params.out_file;\n if (fname.empty()) {\n fname = \"imatrix.dat\";\n }\n\n if (ncall > 0) {\n fname += \".at_\";\n<|edits_diff|>\n--- examples/imatrix/imatrix.cpp\n+++ examples/imatrix/imatrix.cpp\n@@ -20,6 +20,10 @@\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[e_start + j] += x[j]*x[j];\n e.counts[e_start + j]++;\n+ if (!std::isfinite(e.values[e_start + j])) {\n+ fprintf(stderr, \"%f detected in %s\\n\", e.values[e_start + j], wname.c_str());\n+ exit(1);\n+ }\n }\n }\n }\n<|current_version|>\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);\n }\n // loop over all possible experts, regardless if they are used or not in the batch\n for (int ex = 0; ex < n_as; ++ex) {\n size_t e_start = ex*src1->ne[0];\n\n for (int idx = 0; idx < n_ids; ++idx) {\n for (int row = 0; row < (int)src1->ne[2]; ++row) {\n const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);\n\n GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check\n\n if (excur != ex) continue;\n\n const int64_t i11 = idx % src1->ne[1];\n const int64_t i12 = row;\n const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);\n\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[e_start + j] += x[j]*x[j];\n e.counts[e_start + j]++;\n if (!std::isfinite(e.values[e_start + j])) {\n fprintf(stderr, \"%f detected in %s\\n\", e.values[e_start + j], wname.c_str());\n exit(1);\n }\n }\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n } else {\n auto & e = m_stats[wname];\n if (e.values.empty()) {\n e.values.resize(src1->ne[0], 0);\n e.counts.resize(src1->ne[0], 0);\n }\n else if (e.values.size() != (size_t)src1->ne[0]) {\n fprintf(stderr, \"Oops: inconsistent size for %s (%d vs %d)\\n\", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);\n exit(1); //GGML_ASSERT(false);\n }\n ++e.ncall;\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);\n }\n for (int row = 0; row < (int)src1->ne[1]; ++row) {\n const float * x = data + row * src1->ne[0];\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[j] += x[j]*x[j];\n e.counts[j]++;\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n\n return true;\n}\n\nvoid IMatrixCollector::save_imatrix(int ncall) const {\n auto fname = m_params.out_file;\n if (fname.empty()) {\n fname = \"imatrix.dat\";\n }\n\n if (ncall > 0) {\n fname += \".at_\";\n<|next_version|>\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);\n }\n // loop over all possible experts, regardless if they are used or not in the batch\n for (int ex = 0; ex < n_as; ++ex) {\n size_t e_start = ex*src1->ne[0];\n\n for (int idx = 0; idx < n_ids; ++idx) {\n for (int row = 0; row < (int)src1->ne[2]; ++row) {\n const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);\n\n GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check\n\n if (excur != ex) continue;\n\n const int64_t i11 = idx % src1->ne[1];\n const int64_t i12 = row;\n const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);\n\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[e_start + j] += x[j]*x[j];\n e.counts[e_start + j]++;\n if (!std::isfinite(e.values[e_start + j])) {\n fprintf(stderr, \"%f detected in %s\\n\", e.values[e_start + j], wname.c_str());\n exit(1);\n }\n }\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n } else {\n auto & e = m_stats[wname];\n if (e.values.empty()) {\n e.values.resize(src1->ne[0], 0);\n e.counts.resize(src1->ne[0], 0);\n }\n else if (e.values.size() != (size_t)src1->ne[0]) {\n fprintf(stderr, \"Oops: inconsistent size for %s (%d vs %d)\\n\", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);\n exit(1); //GGML_ASSERT(false);\n }\n ++e.ncall;\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);\n }\n for (int row = 0; row < (int)src1->ne[1]; ++row) {\n const float * x = data + row * src1->ne[0];\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[j] += x[j]*x[j];\n e.counts[j]++;\n if (!std::isfinite(e.values[j])) {\n fprintf(stderr, \"%f detected in %s\\n\", e.values[j], wname.c_str());\n exit(1);\n }\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n\n return true;\n}\n\nvoid IMatrixCollector::save_imatrix(int ncall) const {\n auto fname = m_params.out_file;\n if (fname.empty()) {\n fname = \"imatrix.dat\";\n }\n\n if (ncall > 0) {\n fname += \".at_\";\n", "current_contents": " if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[2], (int)src1->type);\n }\n // loop over all possible experts, regardless if they are used or not in the batch\n for (int ex = 0; ex < n_as; ++ex) {\n size_t e_start = ex*src1->ne[0];\n\n for (int idx = 0; idx < n_ids; ++idx) {\n for (int row = 0; row < (int)src1->ne[2]; ++row) {\n const int excur = *(const int32_t *) (m_ids.data() + row*ids->nb[1] + idx*ids->nb[0]);\n\n GGML_ASSERT(excur >= 0 && excur < n_as); // sanity check\n\n if (excur != ex) continue;\n\n const int64_t i11 = idx % src1->ne[1];\n const int64_t i12 = row;\n const float * x = (const float *)((const char *)data + i11*src1->nb[1] + i12*src1->nb[2]);\n\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[e_start + j] += x[j]*x[j];\n e.counts[e_start + j]++;\n if (!std::isfinite(e.values[e_start + j])) {\n fprintf(stderr, \"%f detected in %s\\n\", e.values[e_start + j], wname.c_str());\n exit(1);\n }\n }\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n } else {\n auto & e = m_stats[wname];\n if (e.values.empty()) {\n e.values.resize(src1->ne[0], 0);\n e.counts.resize(src1->ne[0], 0);\n }\n else if (e.values.size() != (size_t)src1->ne[0]) {\n fprintf(stderr, \"Oops: inconsistent size for %s (%d vs %d)\\n\", wname.c_str(), (int)e.values.size(), (int)src1->ne[0]);\n exit(1); //GGML_ASSERT(false);\n }\n ++e.ncall;\n if (m_params.verbosity > 1) {\n printf(\"%s[%d]: %32s, %s, %5d x %5d, %d\\n\", __func__, m_last_call, wname.c_str(), ggml_op_name(t->op), (int)src1->ne[0], (int)src1->ne[1], (int)src1->type);\n }\n for (int row = 0; row < (int)src1->ne[1]; ++row) {\n const float * x = data + row * src1->ne[0];\n for (int j = 0; j < (int)src1->ne[0]; ++j) {\n e.values[j] += x[j]*x[j];\n e.counts[j]++;\n }\n }\n if (e.ncall > m_last_call) {\n m_last_call = e.ncall;\n if (m_last_call % m_params.n_out_freq == 0) {\n save_imatrix();\n }\n if (m_params.n_save_freq > 0 && m_last_call%m_params.n_save_freq == 0) {\n save_imatrix(m_last_call);\n }\n }\n }\n\n return true;\n}\n\nvoid IMatrixCollector::save_imatrix(int ncall) const {\n auto fname = m_params.out_file;\n if (fname.empty()) {\n fname = \"imatrix.dat\";\n }\n\n if (ncall > 0) {\n fname += \".at_\";"} {"commit": "e7e4df031b9e29d4b55a4e0b0295187f6b213db1", "message": "llama : ggml-backend integration (#4766)", "old_file": "examples/batched-bench/batched-bench.cpp", "new_file": "examples/batched-bench/batched-bench.cpp", "status": "M", "old_contents": " }\n\n if (argc >= 7) {\n n_pp = parse_list(argv[6]);\n }\n\n if (argc >= 8) {\n n_tg = parse_list(argv[7]);\n }\n\n if (argc >= 9) {\n n_pl = parse_list(argv[8]);\n }\n\n // init LLM\n\n llama_backend_init(params.numa);\n\n // initialize the model\n\n llama_model_params model_params = llama_model_default_params();\n\n model_params.n_gpu_layers = n_gpu_layers;\n\n llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);\n\n if (model == NULL) {\n fprintf(stderr , \"%s: error: unable to load model\\n\" , __func__);\n return 1;\n }\n\n llama_context_params ctx_params = llama_context_default_params();\n\n ctx_params.seed = 1234;\n ctx_params.n_ctx = n_kv_max;\n ctx_params.n_batch = 512;\n ctx_params.mul_mat_q = mmq;\n\n ctx_params.n_threads = params.n_threads;\n ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;\n\n llama_context * ctx = llama_new_context_with_model(model, ctx_params);\n\n if (ctx == NULL) {\n fprintf(stderr , \"%s: error: failed to create the llama_context\\n\" , __func__);\n return 1;\n }", "new_contents": " }\n\n if (argc >= 7) {\n n_pp = parse_list(argv[6]);\n }\n\n if (argc >= 8) {\n n_tg = parse_list(argv[7]);\n }\n\n if (argc >= 9) {\n n_pl = parse_list(argv[8]);\n }\n\n // init LLM\n\n llama_backend_init(params.numa);\n\n // initialize the model\n\n llama_model_params model_params = llama_model_default_params();\n\n const std::vector t_split (LLAMA_MAX_DEVICES, 0.0f);\n\n model_params.n_gpu_layers = n_gpu_layers;\n model_params.tensor_split = t_split.data();\n\n llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);\n\n if (model == NULL) {\n fprintf(stderr , \"%s: error: unable to load model\\n\" , __func__);\n return 1;\n }\n\n llama_context_params ctx_params = llama_context_default_params();\n\n ctx_params.seed = 1234;\n ctx_params.n_ctx = n_kv_max;\n ctx_params.n_batch = 512;\n ctx_params.mul_mat_q = mmq;\n\n ctx_params.n_threads = params.n_threads;\n ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;\n\n llama_context * ctx = llama_new_context_with_model(model, ctx_params);\n\n if (ctx == NULL) {\n fprintf(stderr , \"%s: error: failed to create the llama_context\\n\" , __func__);\n return 1;\n }", "text": "<|original_code|>\n }\n\n if (argc >= 7) {\n n_pp = parse_list(argv[6]);\n }\n\n if (argc >= 8) {\n n_tg = parse_list(argv[7]);\n }\n\n if (argc >= 9) {\n n_pl = parse_list(argv[8]);\n }\n\n // init LLM\n\n llama_backend_init(params.numa);\n\n // initialize the model\n\n llama_model_params model_params = llama_model_default_params();\n\n model_params.n_gpu_layers = n_gpu_layers;\n\n llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);\n\n if (model == NULL) {\n fprintf(stderr , \"%s: error: unable to load model\\n\" , __func__);\n return 1;\n }\n\n llama_context_params ctx_params = llama_context_default_params();\n\n ctx_params.seed = 1234;\n ctx_params.n_ctx = n_kv_max;\n ctx_params.n_batch = 512;\n ctx_params.mul_mat_q = mmq;\n\n ctx_params.n_threads = params.n_threads;\n ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;\n\n llama_context * ctx = llama_new_context_with_model(model, ctx_params);\n\n if (ctx == NULL) {\n fprintf(stderr , \"%s: error: failed to create the llama_context\\n\" , __func__);\n return 1;\n }\n<|edits_diff|>\n--- examples/batched-bench/batched-bench.cpp\n+++ examples/batched-bench/batched-bench.cpp\n@@ -19,6 +19,8 @@\n // initialize the model\n \n llama_model_params model_params = llama_model_default_params();\n+\n+ const std::vector t_split (LLAMA_MAX_DEVICES, 0.0f);\n \n model_params.n_gpu_layers = n_gpu_layers;\n \n<|current_version|>\n }\n\n if (argc >= 7) {\n n_pp = parse_list(argv[6]);\n }\n\n if (argc >= 8) {\n n_tg = parse_list(argv[7]);\n }\n\n if (argc >= 9) {\n n_pl = parse_list(argv[8]);\n }\n\n // init LLM\n\n llama_backend_init(params.numa);\n\n // initialize the model\n\n llama_model_params model_params = llama_model_default_params();\n\n const std::vector t_split (LLAMA_MAX_DEVICES, 0.0f);\n\n model_params.n_gpu_layers = n_gpu_layers;\n\n llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);\n\n if (model == NULL) {\n fprintf(stderr , \"%s: error: unable to load model\\n\" , __func__);\n return 1;\n }\n\n llama_context_params ctx_params = llama_context_default_params();\n\n ctx_params.seed = 1234;\n ctx_params.n_ctx = n_kv_max;\n ctx_params.n_batch = 512;\n ctx_params.mul_mat_q = mmq;\n\n ctx_params.n_threads = params.n_threads;\n ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;\n\n llama_context * ctx = llama_new_context_with_model(model, ctx_params);\n\n if (ctx == NULL) {\n fprintf(stderr , \"%s: error: failed to create the llama_context\\n\" , __func__);\n return 1;\n }\n<|next_version|>\n }\n\n if (argc >= 7) {\n n_pp = parse_list(argv[6]);\n }\n\n if (argc >= 8) {\n n_tg = parse_list(argv[7]);\n }\n\n if (argc >= 9) {\n n_pl = parse_list(argv[8]);\n }\n\n // init LLM\n\n llama_backend_init(params.numa);\n\n // initialize the model\n\n llama_model_params model_params = llama_model_default_params();\n\n const std::vector t_split (LLAMA_MAX_DEVICES, 0.0f);\n\n model_params.n_gpu_layers = n_gpu_layers;\n model_params.tensor_split = t_split.data();\n\n llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);\n\n if (model == NULL) {\n fprintf(stderr , \"%s: error: unable to load model\\n\" , __func__);\n return 1;\n }\n\n llama_context_params ctx_params = llama_context_default_params();\n\n ctx_params.seed = 1234;\n ctx_params.n_ctx = n_kv_max;\n ctx_params.n_batch = 512;\n ctx_params.mul_mat_q = mmq;\n\n ctx_params.n_threads = params.n_threads;\n ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;\n\n llama_context * ctx = llama_new_context_with_model(model, ctx_params);\n\n if (ctx == NULL) {\n fprintf(stderr , \"%s: error: failed to create the llama_context\\n\" , __func__);\n return 1;\n }\n", "current_contents": " }\n\n if (argc >= 7) {\n n_pp = parse_list(argv[6]);\n }\n\n if (argc >= 8) {\n n_tg = parse_list(argv[7]);\n }\n\n if (argc >= 9) {\n n_pl = parse_list(argv[8]);\n }\n\n // init LLM\n\n llama_backend_init(params.numa);\n\n // initialize the model\n\n llama_model_params model_params = llama_model_default_params();\n\n const std::vector t_split (LLAMA_MAX_DEVICES, 0.0f);\n\n model_params.n_gpu_layers = n_gpu_layers;\n\n llama_model * model = llama_load_model_from_file(params.model.c_str(), model_params);\n\n if (model == NULL) {\n fprintf(stderr , \"%s: error: unable to load model\\n\" , __func__);\n return 1;\n }\n\n llama_context_params ctx_params = llama_context_default_params();\n\n ctx_params.seed = 1234;\n ctx_params.n_ctx = n_kv_max;\n ctx_params.n_batch = 512;\n ctx_params.mul_mat_q = mmq;\n\n ctx_params.n_threads = params.n_threads;\n ctx_params.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;\n\n llama_context * ctx = llama_new_context_with_model(model, ctx_params);\n\n if (ctx == NULL) {\n fprintf(stderr , \"%s: error: failed to create the llama_context\\n\" , __func__);\n return 1;\n }"} {"commit": "8687c1f2581d059cd5b6a9502f89bd343566062a", "message": "llama : remember and restore kv cache data pointers (#1104)", "old_file": "llama.cpp", "new_file": "llama.cpp", "status": "M", "old_contents": "// ongoing prediction with the model.\nconst uint8_t * llama_get_kv_cache(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.addr;\n}\n\n// Returns the size of the KV cache\nsize_t llama_get_kv_cache_size(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.size;\n}\n\nint llama_get_kv_cache_token_count(struct llama_context * ctx) {\n return ctx->model.kv_self.n;\n}\n\n// Sets the KV cache containing the current context for the model\nvoid llama_set_kv_cache(\n struct llama_context * ctx,\n const uint8_t * kv_cache,\n size_t n_size,\n int n_token_count) {\n // Make sure we have the same kv cache setup\n LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);\n memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);\n ctx->model.kv_self.n = n_token_count;\n}\n\nint llama_eval(\n struct llama_context * ctx,\n const llama_token * tokens,\n int n_tokens,\n int n_past,\n int n_threads) {\n if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {\n fprintf(stderr, \"%s: failed to eval\\n\", __func__);\n return 1;\n }\n // get a more accurate load time, upon first eval\n if (!ctx->has_evaluated_once) {\n ctx->t_load_us = ggml_time_us() - ctx->t_start_us;\n ctx->has_evaluated_once = true;\n }\n return 0;\n}\n\nint llama_tokenize(\n struct llama_context * ctx,\n const char * text,", "new_contents": "// ongoing prediction with the model.\nconst uint8_t * llama_get_kv_cache(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.addr;\n}\n\n// Returns the size of the KV cache\nsize_t llama_get_kv_cache_size(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.size;\n}\n\nint llama_get_kv_cache_token_count(struct llama_context * ctx) {\n return ctx->model.kv_self.n;\n}\n\n// Sets the KV cache containing the current context for the model\nvoid llama_set_kv_cache(\n struct llama_context * ctx,\n const uint8_t * kv_cache,\n size_t n_size,\n int n_token_count) {\n // Make sure we have the same kv cache setup\n LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);\n void * k_data = ctx->model.kv_self.k->data; // remember data pointers\n void * v_data = ctx->model.kv_self.v->data; // because their value is stored in buf and overwritten by memcpy\n memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);\n ctx->model.kv_self.k->data = k_data; // restore correct data pointers\n ctx->model.kv_self.v->data = v_data;\n ctx->model.kv_self.n = n_token_count;\n}\n\nint llama_eval(\n struct llama_context * ctx,\n const llama_token * tokens,\n int n_tokens,\n int n_past,\n int n_threads) {\n if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {\n fprintf(stderr, \"%s: failed to eval\\n\", __func__);\n return 1;\n }\n // get a more accurate load time, upon first eval\n if (!ctx->has_evaluated_once) {\n ctx->t_load_us = ggml_time_us() - ctx->t_start_us;\n ctx->has_evaluated_once = true;\n }\n return 0;\n}\n\nint llama_tokenize(\n struct llama_context * ctx,\n const char * text,", "text": "<|original_code|>\n// ongoing prediction with the model.\nconst uint8_t * llama_get_kv_cache(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.addr;\n}\n\n// Returns the size of the KV cache\nsize_t llama_get_kv_cache_size(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.size;\n}\n\nint llama_get_kv_cache_token_count(struct llama_context * ctx) {\n return ctx->model.kv_self.n;\n}\n\n// Sets the KV cache containing the current context for the model\nvoid llama_set_kv_cache(\n struct llama_context * ctx,\n const uint8_t * kv_cache,\n size_t n_size,\n int n_token_count) {\n // Make sure we have the same kv cache setup\n LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);\n memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);\n ctx->model.kv_self.n = n_token_count;\n}\n\nint llama_eval(\n struct llama_context * ctx,\n const llama_token * tokens,\n int n_tokens,\n int n_past,\n int n_threads) {\n if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {\n fprintf(stderr, \"%s: failed to eval\\n\", __func__);\n return 1;\n }\n // get a more accurate load time, upon first eval\n if (!ctx->has_evaluated_once) {\n ctx->t_load_us = ggml_time_us() - ctx->t_start_us;\n ctx->has_evaluated_once = true;\n }\n return 0;\n}\n\nint llama_tokenize(\n struct llama_context * ctx,\n const char * text,\n<|edits_diff|>\n--- llama.cpp\n+++ llama.cpp\n@@ -20,6 +20,8 @@\n int n_token_count) {\n // Make sure we have the same kv cache setup\n LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);\n+ void * k_data = ctx->model.kv_self.k->data; // remember data pointers\n+ void * v_data = ctx->model.kv_self.v->data; // because their value is stored in buf and overwritten by memcpy\n memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);\n ctx->model.kv_self.n = n_token_count;\n }\n<|current_version|>\n// ongoing prediction with the model.\nconst uint8_t * llama_get_kv_cache(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.addr;\n}\n\n// Returns the size of the KV cache\nsize_t llama_get_kv_cache_size(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.size;\n}\n\nint llama_get_kv_cache_token_count(struct llama_context * ctx) {\n return ctx->model.kv_self.n;\n}\n\n// Sets the KV cache containing the current context for the model\nvoid llama_set_kv_cache(\n struct llama_context * ctx,\n const uint8_t * kv_cache,\n size_t n_size,\n int n_token_count) {\n // Make sure we have the same kv cache setup\n LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);\n void * k_data = ctx->model.kv_self.k->data; // remember data pointers\n void * v_data = ctx->model.kv_self.v->data; // because their value is stored in buf and overwritten by memcpy\n memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);\n ctx->model.kv_self.n = n_token_count;\n}\n\nint llama_eval(\n struct llama_context * ctx,\n const llama_token * tokens,\n int n_tokens,\n int n_past,\n int n_threads) {\n if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {\n fprintf(stderr, \"%s: failed to eval\\n\", __func__);\n return 1;\n }\n // get a more accurate load time, upon first eval\n if (!ctx->has_evaluated_once) {\n ctx->t_load_us = ggml_time_us() - ctx->t_start_us;\n ctx->has_evaluated_once = true;\n }\n return 0;\n}\n\nint llama_tokenize(\n struct llama_context * ctx,\n const char * text,\n<|next_version|>\n// ongoing prediction with the model.\nconst uint8_t * llama_get_kv_cache(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.addr;\n}\n\n// Returns the size of the KV cache\nsize_t llama_get_kv_cache_size(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.size;\n}\n\nint llama_get_kv_cache_token_count(struct llama_context * ctx) {\n return ctx->model.kv_self.n;\n}\n\n// Sets the KV cache containing the current context for the model\nvoid llama_set_kv_cache(\n struct llama_context * ctx,\n const uint8_t * kv_cache,\n size_t n_size,\n int n_token_count) {\n // Make sure we have the same kv cache setup\n LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);\n void * k_data = ctx->model.kv_self.k->data; // remember data pointers\n void * v_data = ctx->model.kv_self.v->data; // because their value is stored in buf and overwritten by memcpy\n memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);\n ctx->model.kv_self.k->data = k_data; // restore correct data pointers\n ctx->model.kv_self.v->data = v_data;\n ctx->model.kv_self.n = n_token_count;\n}\n\nint llama_eval(\n struct llama_context * ctx,\n const llama_token * tokens,\n int n_tokens,\n int n_past,\n int n_threads) {\n if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {\n fprintf(stderr, \"%s: failed to eval\\n\", __func__);\n return 1;\n }\n // get a more accurate load time, upon first eval\n if (!ctx->has_evaluated_once) {\n ctx->t_load_us = ggml_time_us() - ctx->t_start_us;\n ctx->has_evaluated_once = true;\n }\n return 0;\n}\n\nint llama_tokenize(\n struct llama_context * ctx,\n const char * text,\n", "current_contents": "// ongoing prediction with the model.\nconst uint8_t * llama_get_kv_cache(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.addr;\n}\n\n// Returns the size of the KV cache\nsize_t llama_get_kv_cache_size(struct llama_context * ctx) {\n return ctx->model.kv_self.buf.size;\n}\n\nint llama_get_kv_cache_token_count(struct llama_context * ctx) {\n return ctx->model.kv_self.n;\n}\n\n// Sets the KV cache containing the current context for the model\nvoid llama_set_kv_cache(\n struct llama_context * ctx,\n const uint8_t * kv_cache,\n size_t n_size,\n int n_token_count) {\n // Make sure we have the same kv cache setup\n LLAMA_ASSERT(ctx->model.kv_self.buf.size == n_size);\n void * k_data = ctx->model.kv_self.k->data; // remember data pointers\n void * v_data = ctx->model.kv_self.v->data; // because their value is stored in buf and overwritten by memcpy\n memcpy(ctx->model.kv_self.buf.addr, kv_cache, n_size);\n ctx->model.kv_self.n = n_token_count;\n}\n\nint llama_eval(\n struct llama_context * ctx,\n const llama_token * tokens,\n int n_tokens,\n int n_past,\n int n_threads) {\n if (!llama_eval_internal(*ctx, tokens, n_tokens, n_past, n_threads)) {\n fprintf(stderr, \"%s: failed to eval\\n\", __func__);\n return 1;\n }\n // get a more accurate load time, upon first eval\n if (!ctx->has_evaluated_once) {\n ctx->t_load_us = ggml_time_us() - ctx->t_start_us;\n ctx->has_evaluated_once = true;\n }\n return 0;\n}\n\nint llama_tokenize(\n struct llama_context * ctx,\n const char * text,"} {"commit": "c23792bc3164d3190677c8bf2273d53f32b57caa", "message": "Allow for text angle/gradient to be retrieved (#4070)", "old_file": "src/ccmain/tesseractclass.cpp", "new_file": "src/ccmain/tesseractclass.cpp", "status": "M", "old_contents": " , double_MEMBER(lstm_rating_coefficient, 5,\n \"Sets the rating coefficient for the lstm choices. The smaller the \"\n \"coefficient, the better are the ratings for each choice and less \"\n \"information is lost due to the cut off at 0. The standard value is \"\n \"5\",\n this->params())\n , BOOL_MEMBER(pageseg_apply_music_mask, false,\n \"Detect music staff and remove intersecting components\", this->params())\n ,\n\n backup_config_file_(nullptr)\n , pix_binary_(nullptr)\n , pix_grey_(nullptr)\n , pix_original_(nullptr)\n , pix_thresholds_(nullptr)\n , source_resolution_(0)\n , textord_(this)\n , right_to_left_(false)\n , scaled_color_(nullptr)\n , scaled_factor_(-1)\n , deskew_(1.0f, 0.0f)\n , reskew_(1.0f, 0.0f)\n , most_recently_used_(this)\n , font_table_size_(0)\n#ifndef DISABLED_LEGACY_ENGINE\n , equ_detect_(nullptr)\n#endif // ndef DISABLED_LEGACY_ENGINE\n , lstm_recognizer_(nullptr)\n , train_line_page_num_(0) {}\n\nTesseract::~Tesseract() {\n Clear();\n pix_original_.destroy();\n end_tesseract();\n for (auto *lang : sub_langs_) {\n delete lang;\n }\n delete lstm_recognizer_;\n lstm_recognizer_ = nullptr;\n}\n\nDict &Tesseract::getDict() {\n if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {\n if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {\n return *lstm_recognizer_->GetDict();\n }\n }\n return Classify::getDict();\n}\n\nvoid Tesseract::Clear() {\n std::string debug_name = imagebasename + \"_debug.pdf\";\n pixa_debug_.WritePDF(debug_name.c_str());\n pix_binary_.destroy();\n pix_grey_.destroy();\n pix_thresholds_.destroy();\n scaled_color_.destroy();\n deskew_ = FCOORD(1.0f, 0.0f);\n reskew_ = FCOORD(1.0f, 0.0f);\n splitter_.Clear();\n scaled_factor_ = -1;\n for (auto &sub_lang : sub_langs_) {\n sub_lang->Clear();\n }\n}\n\n#ifndef DISABLED_LEGACY_ENGINE\n\nvoid Tesseract::SetEquationDetect(EquationDetect *detector) {\n equ_detect_ = detector;\n equ_detect_->SetLangTesseract(this);\n}\n\n// Clear all memory of adaption for this and all subclassifiers.\nvoid Tesseract::ResetAdaptiveClassifier() {\n ResetAdaptiveClassifierInternal();\n for (auto &sub_lang : sub_langs_) {\n sub_lang->ResetAdaptiveClassifierInternal();\n }\n}\n\n#endif // ndef DISABLED_LEGACY_ENGINE\n", "new_contents": " , double_MEMBER(lstm_rating_coefficient, 5,\n \"Sets the rating coefficient for the lstm choices. The smaller the \"\n \"coefficient, the better are the ratings for each choice and less \"\n \"information is lost due to the cut off at 0. The standard value is \"\n \"5\",\n this->params())\n , BOOL_MEMBER(pageseg_apply_music_mask, false,\n \"Detect music staff and remove intersecting components\", this->params())\n ,\n\n backup_config_file_(nullptr)\n , pix_binary_(nullptr)\n , pix_grey_(nullptr)\n , pix_original_(nullptr)\n , pix_thresholds_(nullptr)\n , source_resolution_(0)\n , textord_(this)\n , right_to_left_(false)\n , scaled_color_(nullptr)\n , scaled_factor_(-1)\n , deskew_(1.0f, 0.0f)\n , reskew_(1.0f, 0.0f)\n , gradient_(0.0f)\n , most_recently_used_(this)\n , font_table_size_(0)\n#ifndef DISABLED_LEGACY_ENGINE\n , equ_detect_(nullptr)\n#endif // ndef DISABLED_LEGACY_ENGINE\n , lstm_recognizer_(nullptr)\n , train_line_page_num_(0) {}\n\nTesseract::~Tesseract() {\n Clear();\n pix_original_.destroy();\n end_tesseract();\n for (auto *lang : sub_langs_) {\n delete lang;\n }\n delete lstm_recognizer_;\n lstm_recognizer_ = nullptr;\n}\n\nDict &Tesseract::getDict() {\n if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {\n if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {\n return *lstm_recognizer_->GetDict();\n }\n }\n return Classify::getDict();\n}\n\nvoid Tesseract::Clear() {\n std::string debug_name = imagebasename + \"_debug.pdf\";\n pixa_debug_.WritePDF(debug_name.c_str());\n pix_binary_.destroy();\n pix_grey_.destroy();\n pix_thresholds_.destroy();\n scaled_color_.destroy();\n deskew_ = FCOORD(1.0f, 0.0f);\n reskew_ = FCOORD(1.0f, 0.0f);\n gradient_ = 0.0f;\n splitter_.Clear();\n scaled_factor_ = -1;\n for (auto &sub_lang : sub_langs_) {\n sub_lang->Clear();\n }\n}\n\n#ifndef DISABLED_LEGACY_ENGINE\n\nvoid Tesseract::SetEquationDetect(EquationDetect *detector) {\n equ_detect_ = detector;\n equ_detect_->SetLangTesseract(this);\n}\n\n// Clear all memory of adaption for this and all subclassifiers.\nvoid Tesseract::ResetAdaptiveClassifier() {\n ResetAdaptiveClassifierInternal();\n for (auto &sub_lang : sub_langs_) {\n sub_lang->ResetAdaptiveClassifierInternal();\n }\n}\n\n#endif // ndef DISABLED_LEGACY_ENGINE\n", "text": "<|original_code|>\n , double_MEMBER(lstm_rating_coefficient, 5,\n \"Sets the rating coefficient for the lstm choices. The smaller the \"\n \"coefficient, the better are the ratings for each choice and less \"\n \"information is lost due to the cut off at 0. The standard value is \"\n \"5\",\n this->params())\n , BOOL_MEMBER(pageseg_apply_music_mask, false,\n \"Detect music staff and remove intersecting components\", this->params())\n ,\n\n backup_config_file_(nullptr)\n , pix_binary_(nullptr)\n , pix_grey_(nullptr)\n , pix_original_(nullptr)\n , pix_thresholds_(nullptr)\n , source_resolution_(0)\n , textord_(this)\n , right_to_left_(false)\n , scaled_color_(nullptr)\n , scaled_factor_(-1)\n , deskew_(1.0f, 0.0f)\n , reskew_(1.0f, 0.0f)\n , most_recently_used_(this)\n , font_table_size_(0)\n#ifndef DISABLED_LEGACY_ENGINE\n , equ_detect_(nullptr)\n#endif // ndef DISABLED_LEGACY_ENGINE\n , lstm_recognizer_(nullptr)\n , train_line_page_num_(0) {}\n\nTesseract::~Tesseract() {\n Clear();\n pix_original_.destroy();\n end_tesseract();\n for (auto *lang : sub_langs_) {\n delete lang;\n }\n delete lstm_recognizer_;\n lstm_recognizer_ = nullptr;\n}\n\nDict &Tesseract::getDict() {\n if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {\n if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {\n return *lstm_recognizer_->GetDict();\n }\n }\n return Classify::getDict();\n}\n\nvoid Tesseract::Clear() {\n std::string debug_name = imagebasename + \"_debug.pdf\";\n pixa_debug_.WritePDF(debug_name.c_str());\n pix_binary_.destroy();\n pix_grey_.destroy();\n pix_thresholds_.destroy();\n scaled_color_.destroy();\n deskew_ = FCOORD(1.0f, 0.0f);\n reskew_ = FCOORD(1.0f, 0.0f);\n splitter_.Clear();\n scaled_factor_ = -1;\n for (auto &sub_lang : sub_langs_) {\n sub_lang->Clear();\n }\n}\n\n#ifndef DISABLED_LEGACY_ENGINE\n\nvoid Tesseract::SetEquationDetect(EquationDetect *detector) {\n equ_detect_ = detector;\n equ_detect_->SetLangTesseract(this);\n}\n\n// Clear all memory of adaption for this and all subclassifiers.\nvoid Tesseract::ResetAdaptiveClassifier() {\n ResetAdaptiveClassifierInternal();\n for (auto &sub_lang : sub_langs_) {\n sub_lang->ResetAdaptiveClassifierInternal();\n }\n}\n\n#endif // ndef DISABLED_LEGACY_ENGINE\n\n<|edits_diff|>\n--- src/ccmain/tesseractclass.cpp\n+++ src/ccmain/tesseractclass.cpp\n@@ -20,6 +20,7 @@\n , scaled_factor_(-1)\n , deskew_(1.0f, 0.0f)\n , reskew_(1.0f, 0.0f)\n+ , gradient_(0.0f)\n , most_recently_used_(this)\n , font_table_size_(0)\n #ifndef DISABLED_LEGACY_ENGINE\n<|current_version|>\n , double_MEMBER(lstm_rating_coefficient, 5,\n \"Sets the rating coefficient for the lstm choices. The smaller the \"\n \"coefficient, the better are the ratings for each choice and less \"\n \"information is lost due to the cut off at 0. The standard value is \"\n \"5\",\n this->params())\n , BOOL_MEMBER(pageseg_apply_music_mask, false,\n \"Detect music staff and remove intersecting components\", this->params())\n ,\n\n backup_config_file_(nullptr)\n , pix_binary_(nullptr)\n , pix_grey_(nullptr)\n , pix_original_(nullptr)\n , pix_thresholds_(nullptr)\n , source_resolution_(0)\n , textord_(this)\n , right_to_left_(false)\n , scaled_color_(nullptr)\n , scaled_factor_(-1)\n , deskew_(1.0f, 0.0f)\n , reskew_(1.0f, 0.0f)\n , gradient_(0.0f)\n , most_recently_used_(this)\n , font_table_size_(0)\n#ifndef DISABLED_LEGACY_ENGINE\n , equ_detect_(nullptr)\n#endif // ndef DISABLED_LEGACY_ENGINE\n , lstm_recognizer_(nullptr)\n , train_line_page_num_(0) {}\n\nTesseract::~Tesseract() {\n Clear();\n pix_original_.destroy();\n end_tesseract();\n for (auto *lang : sub_langs_) {\n delete lang;\n }\n delete lstm_recognizer_;\n lstm_recognizer_ = nullptr;\n}\n\nDict &Tesseract::getDict() {\n if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {\n if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {\n return *lstm_recognizer_->GetDict();\n }\n }\n return Classify::getDict();\n}\n\nvoid Tesseract::Clear() {\n std::string debug_name = imagebasename + \"_debug.pdf\";\n pixa_debug_.WritePDF(debug_name.c_str());\n pix_binary_.destroy();\n pix_grey_.destroy();\n pix_thresholds_.destroy();\n scaled_color_.destroy();\n deskew_ = FCOORD(1.0f, 0.0f);\n reskew_ = FCOORD(1.0f, 0.0f);\n splitter_.Clear();\n scaled_factor_ = -1;\n for (auto &sub_lang : sub_langs_) {\n sub_lang->Clear();\n }\n}\n\n#ifndef DISABLED_LEGACY_ENGINE\n\nvoid Tesseract::SetEquationDetect(EquationDetect *detector) {\n equ_detect_ = detector;\n equ_detect_->SetLangTesseract(this);\n}\n\n// Clear all memory of adaption for this and all subclassifiers.\nvoid Tesseract::ResetAdaptiveClassifier() {\n ResetAdaptiveClassifierInternal();\n for (auto &sub_lang : sub_langs_) {\n sub_lang->ResetAdaptiveClassifierInternal();\n }\n}\n\n#endif // ndef DISABLED_LEGACY_ENGINE\n\n<|next_version|>\n , double_MEMBER(lstm_rating_coefficient, 5,\n \"Sets the rating coefficient for the lstm choices. The smaller the \"\n \"coefficient, the better are the ratings for each choice and less \"\n \"information is lost due to the cut off at 0. The standard value is \"\n \"5\",\n this->params())\n , BOOL_MEMBER(pageseg_apply_music_mask, false,\n \"Detect music staff and remove intersecting components\", this->params())\n ,\n\n backup_config_file_(nullptr)\n , pix_binary_(nullptr)\n , pix_grey_(nullptr)\n , pix_original_(nullptr)\n , pix_thresholds_(nullptr)\n , source_resolution_(0)\n , textord_(this)\n , right_to_left_(false)\n , scaled_color_(nullptr)\n , scaled_factor_(-1)\n , deskew_(1.0f, 0.0f)\n , reskew_(1.0f, 0.0f)\n , gradient_(0.0f)\n , most_recently_used_(this)\n , font_table_size_(0)\n#ifndef DISABLED_LEGACY_ENGINE\n , equ_detect_(nullptr)\n#endif // ndef DISABLED_LEGACY_ENGINE\n , lstm_recognizer_(nullptr)\n , train_line_page_num_(0) {}\n\nTesseract::~Tesseract() {\n Clear();\n pix_original_.destroy();\n end_tesseract();\n for (auto *lang : sub_langs_) {\n delete lang;\n }\n delete lstm_recognizer_;\n lstm_recognizer_ = nullptr;\n}\n\nDict &Tesseract::getDict() {\n if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {\n if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {\n return *lstm_recognizer_->GetDict();\n }\n }\n return Classify::getDict();\n}\n\nvoid Tesseract::Clear() {\n std::string debug_name = imagebasename + \"_debug.pdf\";\n pixa_debug_.WritePDF(debug_name.c_str());\n pix_binary_.destroy();\n pix_grey_.destroy();\n pix_thresholds_.destroy();\n scaled_color_.destroy();\n deskew_ = FCOORD(1.0f, 0.0f);\n reskew_ = FCOORD(1.0f, 0.0f);\n gradient_ = 0.0f;\n splitter_.Clear();\n scaled_factor_ = -1;\n for (auto &sub_lang : sub_langs_) {\n sub_lang->Clear();\n }\n}\n\n#ifndef DISABLED_LEGACY_ENGINE\n\nvoid Tesseract::SetEquationDetect(EquationDetect *detector) {\n equ_detect_ = detector;\n equ_detect_->SetLangTesseract(this);\n}\n\n// Clear all memory of adaption for this and all subclassifiers.\nvoid Tesseract::ResetAdaptiveClassifier() {\n ResetAdaptiveClassifierInternal();\n for (auto &sub_lang : sub_langs_) {\n sub_lang->ResetAdaptiveClassifierInternal();\n }\n}\n\n#endif // ndef DISABLED_LEGACY_ENGINE\n\n", "current_contents": " , double_MEMBER(lstm_rating_coefficient, 5,\n \"Sets the rating coefficient for the lstm choices. The smaller the \"\n \"coefficient, the better are the ratings for each choice and less \"\n \"information is lost due to the cut off at 0. The standard value is \"\n \"5\",\n this->params())\n , BOOL_MEMBER(pageseg_apply_music_mask, false,\n \"Detect music staff and remove intersecting components\", this->params())\n ,\n\n backup_config_file_(nullptr)\n , pix_binary_(nullptr)\n , pix_grey_(nullptr)\n , pix_original_(nullptr)\n , pix_thresholds_(nullptr)\n , source_resolution_(0)\n , textord_(this)\n , right_to_left_(false)\n , scaled_color_(nullptr)\n , scaled_factor_(-1)\n , deskew_(1.0f, 0.0f)\n , reskew_(1.0f, 0.0f)\n , gradient_(0.0f)\n , most_recently_used_(this)\n , font_table_size_(0)\n#ifndef DISABLED_LEGACY_ENGINE\n , equ_detect_(nullptr)\n#endif // ndef DISABLED_LEGACY_ENGINE\n , lstm_recognizer_(nullptr)\n , train_line_page_num_(0) {}\n\nTesseract::~Tesseract() {\n Clear();\n pix_original_.destroy();\n end_tesseract();\n for (auto *lang : sub_langs_) {\n delete lang;\n }\n delete lstm_recognizer_;\n lstm_recognizer_ = nullptr;\n}\n\nDict &Tesseract::getDict() {\n if (0 == Classify::getDict().NumDawgs() && AnyLSTMLang()) {\n if (lstm_recognizer_ && lstm_recognizer_->GetDict()) {\n return *lstm_recognizer_->GetDict();\n }\n }\n return Classify::getDict();\n}\n\nvoid Tesseract::Clear() {\n std::string debug_name = imagebasename + \"_debug.pdf\";\n pixa_debug_.WritePDF(debug_name.c_str());\n pix_binary_.destroy();\n pix_grey_.destroy();\n pix_thresholds_.destroy();\n scaled_color_.destroy();\n deskew_ = FCOORD(1.0f, 0.0f);\n reskew_ = FCOORD(1.0f, 0.0f);\n splitter_.Clear();\n scaled_factor_ = -1;\n for (auto &sub_lang : sub_langs_) {\n sub_lang->Clear();\n }\n}\n\n#ifndef DISABLED_LEGACY_ENGINE\n\nvoid Tesseract::SetEquationDetect(EquationDetect *detector) {\n equ_detect_ = detector;\n equ_detect_->SetLangTesseract(this);\n}\n\n// Clear all memory of adaption for this and all subclassifiers.\nvoid Tesseract::ResetAdaptiveClassifier() {\n ResetAdaptiveClassifierInternal();\n for (auto &sub_lang : sub_langs_) {\n sub_lang->ResetAdaptiveClassifierInternal();\n }\n}\n\n#endif // ndef DISABLED_LEGACY_ENGINE\n"} {"commit": "a701454ae58cd97f60868712284f9161569eb82f", "message": "Fix vector resize with init for all elements (issue #3473) (#3474)", "old_file": "src/ccstruct/blobs.cpp", "new_file": "src/ccstruct/blobs.cpp", "status": "M", "old_contents": "}\n\n// Computes the precise bounding box of the coords that are generated by\n// GetEdgeCoords. This may be different from the bounding box of the polygon.\nvoid TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {\n TBOX box = bounding_box();\n *precise_box = TBOX();\n CollectEdges(box, precise_box, nullptr, nullptr, nullptr);\n precise_box->move(box.botleft());\n}\n\n// Adds edges to the given vectors.\n// For all the edge steps in all the outlines, or polygonal approximation\n// where there are no edge steps, collects the steps into x_coords/y_coords.\n// x_coords is a collection of the x-coords of vertical edges for each\n// y-coord starting at box.bottom().\n// y_coords is a collection of the y-coords of horizontal edges for each\n// x-coord starting at box.left().\n// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.\n// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.\nvoid TBLOB::GetEdgeCoords(const TBOX &box, std::vector> &x_coords,\n std::vector> &y_coords) const {\n x_coords.resize(box.height());\n y_coords.resize(box.width());\n CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);\n // Sort the output vectors.\n for (auto &coord : x_coords) {\n std::sort(coord.begin(), coord.end());\n }\n for (auto &coord : y_coords) {\n std::sort(coord.begin(), coord.end());\n }\n}\n\n// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over\n// the integer coordinate grid to properly weight long vectors.\nstatic void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {\n FCOORD step(pt2);\n step -= pt1;\n int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));\n int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));\n int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));\n int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));\n if (xstart == xend && ystart == yend) {\n return; // Nothing to do.\n }\n double weight = step.length() / (xend - xstart + yend - ystart);", "new_contents": "}\n\n// Computes the precise bounding box of the coords that are generated by\n// GetEdgeCoords. This may be different from the bounding box of the polygon.\nvoid TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {\n TBOX box = bounding_box();\n *precise_box = TBOX();\n CollectEdges(box, precise_box, nullptr, nullptr, nullptr);\n precise_box->move(box.botleft());\n}\n\n// Adds edges to the given vectors.\n// For all the edge steps in all the outlines, or polygonal approximation\n// where there are no edge steps, collects the steps into x_coords/y_coords.\n// x_coords is a collection of the x-coords of vertical edges for each\n// y-coord starting at box.bottom().\n// y_coords is a collection of the y-coords of horizontal edges for each\n// x-coord starting at box.left().\n// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.\n// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.\nvoid TBLOB::GetEdgeCoords(const TBOX &box, std::vector> &x_coords,\n std::vector> &y_coords) const {\n x_coords.clear();\n x_coords.resize(box.height());\n y_coords.clear();\n y_coords.resize(box.width());\n CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);\n // Sort the output vectors.\n for (auto &coord : x_coords) {\n std::sort(coord.begin(), coord.end());\n }\n for (auto &coord : y_coords) {\n std::sort(coord.begin(), coord.end());\n }\n}\n\n// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over\n// the integer coordinate grid to properly weight long vectors.\nstatic void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {\n FCOORD step(pt2);\n step -= pt1;\n int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));\n int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));\n int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));\n int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));\n if (xstart == xend && ystart == yend) {\n return; // Nothing to do.\n }\n double weight = step.length() / (xend - xstart + yend - ystart);", "text": "<|original_code|>\n}\n\n// Computes the precise bounding box of the coords that are generated by\n// GetEdgeCoords. This may be different from the bounding box of the polygon.\nvoid TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {\n TBOX box = bounding_box();\n *precise_box = TBOX();\n CollectEdges(box, precise_box, nullptr, nullptr, nullptr);\n precise_box->move(box.botleft());\n}\n\n// Adds edges to the given vectors.\n// For all the edge steps in all the outlines, or polygonal approximation\n// where there are no edge steps, collects the steps into x_coords/y_coords.\n// x_coords is a collection of the x-coords of vertical edges for each\n// y-coord starting at box.bottom().\n// y_coords is a collection of the y-coords of horizontal edges for each\n// x-coord starting at box.left().\n// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.\n// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.\nvoid TBLOB::GetEdgeCoords(const TBOX &box, std::vector> &x_coords,\n std::vector> &y_coords) const {\n x_coords.resize(box.height());\n y_coords.resize(box.width());\n CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);\n // Sort the output vectors.\n for (auto &coord : x_coords) {\n std::sort(coord.begin(), coord.end());\n }\n for (auto &coord : y_coords) {\n std::sort(coord.begin(), coord.end());\n }\n}\n\n// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over\n// the integer coordinate grid to properly weight long vectors.\nstatic void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {\n FCOORD step(pt2);\n step -= pt1;\n int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));\n int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));\n int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));\n int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));\n if (xstart == xend && ystart == yend) {\n return; // Nothing to do.\n }\n double weight = step.length() / (xend - xstart + yend - ystart);\n<|edits_diff|>\n--- src/ccstruct/blobs.cpp\n+++ src/ccstruct/blobs.cpp\n@@ -20,6 +20,7 @@\n // Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.\n void TBLOB::GetEdgeCoords(const TBOX &box, std::vector> &x_coords,\n std::vector> &y_coords) const {\n+ x_coords.clear();\n x_coords.resize(box.height());\n y_coords.resize(box.width());\n CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);\n<|current_version|>\n}\n\n// Computes the precise bounding box of the coords that are generated by\n// GetEdgeCoords. This may be different from the bounding box of the polygon.\nvoid TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {\n TBOX box = bounding_box();\n *precise_box = TBOX();\n CollectEdges(box, precise_box, nullptr, nullptr, nullptr);\n precise_box->move(box.botleft());\n}\n\n// Adds edges to the given vectors.\n// For all the edge steps in all the outlines, or polygonal approximation\n// where there are no edge steps, collects the steps into x_coords/y_coords.\n// x_coords is a collection of the x-coords of vertical edges for each\n// y-coord starting at box.bottom().\n// y_coords is a collection of the y-coords of horizontal edges for each\n// x-coord starting at box.left().\n// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.\n// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.\nvoid TBLOB::GetEdgeCoords(const TBOX &box, std::vector> &x_coords,\n std::vector> &y_coords) const {\n x_coords.clear();\n x_coords.resize(box.height());\n y_coords.resize(box.width());\n CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);\n // Sort the output vectors.\n for (auto &coord : x_coords) {\n std::sort(coord.begin(), coord.end());\n }\n for (auto &coord : y_coords) {\n std::sort(coord.begin(), coord.end());\n }\n}\n\n// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over\n// the integer coordinate grid to properly weight long vectors.\nstatic void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {\n FCOORD step(pt2);\n step -= pt1;\n int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));\n int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));\n int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));\n int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));\n if (xstart == xend && ystart == yend) {\n return; // Nothing to do.\n }\n double weight = step.length() / (xend - xstart + yend - ystart);\n<|next_version|>\n}\n\n// Computes the precise bounding box of the coords that are generated by\n// GetEdgeCoords. This may be different from the bounding box of the polygon.\nvoid TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {\n TBOX box = bounding_box();\n *precise_box = TBOX();\n CollectEdges(box, precise_box, nullptr, nullptr, nullptr);\n precise_box->move(box.botleft());\n}\n\n// Adds edges to the given vectors.\n// For all the edge steps in all the outlines, or polygonal approximation\n// where there are no edge steps, collects the steps into x_coords/y_coords.\n// x_coords is a collection of the x-coords of vertical edges for each\n// y-coord starting at box.bottom().\n// y_coords is a collection of the y-coords of horizontal edges for each\n// x-coord starting at box.left().\n// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.\n// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.\nvoid TBLOB::GetEdgeCoords(const TBOX &box, std::vector> &x_coords,\n std::vector> &y_coords) const {\n x_coords.clear();\n x_coords.resize(box.height());\n y_coords.clear();\n y_coords.resize(box.width());\n CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);\n // Sort the output vectors.\n for (auto &coord : x_coords) {\n std::sort(coord.begin(), coord.end());\n }\n for (auto &coord : y_coords) {\n std::sort(coord.begin(), coord.end());\n }\n}\n\n// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over\n// the integer coordinate grid to properly weight long vectors.\nstatic void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {\n FCOORD step(pt2);\n step -= pt1;\n int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));\n int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));\n int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));\n int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));\n if (xstart == xend && ystart == yend) {\n return; // Nothing to do.\n }\n double weight = step.length() / (xend - xstart + yend - ystart);\n", "current_contents": "}\n\n// Computes the precise bounding box of the coords that are generated by\n// GetEdgeCoords. This may be different from the bounding box of the polygon.\nvoid TBLOB::GetPreciseBoundingBox(TBOX *precise_box) const {\n TBOX box = bounding_box();\n *precise_box = TBOX();\n CollectEdges(box, precise_box, nullptr, nullptr, nullptr);\n precise_box->move(box.botleft());\n}\n\n// Adds edges to the given vectors.\n// For all the edge steps in all the outlines, or polygonal approximation\n// where there are no edge steps, collects the steps into x_coords/y_coords.\n// x_coords is a collection of the x-coords of vertical edges for each\n// y-coord starting at box.bottom().\n// y_coords is a collection of the y-coords of horizontal edges for each\n// x-coord starting at box.left().\n// Eg x_coords[0] is a collection of the x-coords of edges at y=bottom.\n// Eg x_coords[1] is a collection of the x-coords of edges at y=bottom + 1.\nvoid TBLOB::GetEdgeCoords(const TBOX &box, std::vector> &x_coords,\n std::vector> &y_coords) const {\n x_coords.clear();\n x_coords.resize(box.height());\n y_coords.resize(box.width());\n CollectEdges(box, nullptr, nullptr, &x_coords, &y_coords);\n // Sort the output vectors.\n for (auto &coord : x_coords) {\n std::sort(coord.begin(), coord.end());\n }\n for (auto &coord : y_coords) {\n std::sort(coord.begin(), coord.end());\n }\n}\n\n// Accumulates the segment between pt1 and pt2 in the LLSQ, quantizing over\n// the integer coordinate grid to properly weight long vectors.\nstatic void SegmentLLSQ(const FCOORD &pt1, const FCOORD &pt2, LLSQ *accumulator) {\n FCOORD step(pt2);\n step -= pt1;\n int xstart = IntCastRounded(std::min(pt1.x(), pt2.x()));\n int xend = IntCastRounded(std::max(pt1.x(), pt2.x()));\n int ystart = IntCastRounded(std::min(pt1.y(), pt2.y()));\n int yend = IntCastRounded(std::max(pt1.y(), pt2.y()));\n if (xstart == xend && ystart == yend) {\n return; // Nothing to do.\n }\n double weight = step.length() / (xend - xstart + yend - ystart);"} {"commit": "a701454ae58cd97f60868712284f9161569eb82f", "message": "Fix vector resize with init for all elements (issue #3473) (#3474)", "old_file": "src/lstm/recodebeam.cpp", "new_file": "src/lstm/recodebeam.cpp", "status": "M", "old_contents": " line_box.bottom(),\n static_cast(std::ceil(character_boundaries_[i + 1] * scale_factor)) +\n line_box.left(),\n line_box.top());\n b_it.add_after_then_move(C_BLOB::FakeBlob(box));\n }\n }\n // Make a fake word from the blobs.\n WERD *word = new WERD(&blobs, leading_space, nullptr);\n // Make a WERD_RES from the word.\n auto *word_res = new WERD_RES(word);\n word_res->end = word_end - word_start + leading_space;\n word_res->uch_set = unicharset;\n word_res->combination = true; // Give it ownership of the word.\n word_res->space_certainty = space_certainty;\n word_res->ratings = new MATRIX(word_end - word_start, 1);\n return word_res;\n}\n\n// Fills top_n_flags_ with bools that are true iff the corresponding output\n// is one of the top_n.\nvoid RecodeBeamSearch::ComputeTopN(const float *outputs, int num_outputs, int top_n) {\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if (top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n }\n }\n }\n top_n_flags_[null_char_] = TN_TOP2;\n}\n\nvoid RecodeBeamSearch::ComputeSecTopN(std::unordered_set *exList, const float *outputs,\n int num_outputs, int top_n) {\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if ((top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) && !exList->count(i)) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();", "new_contents": " line_box.bottom(),\n static_cast(std::ceil(character_boundaries_[i + 1] * scale_factor)) +\n line_box.left(),\n line_box.top());\n b_it.add_after_then_move(C_BLOB::FakeBlob(box));\n }\n }\n // Make a fake word from the blobs.\n WERD *word = new WERD(&blobs, leading_space, nullptr);\n // Make a WERD_RES from the word.\n auto *word_res = new WERD_RES(word);\n word_res->end = word_end - word_start + leading_space;\n word_res->uch_set = unicharset;\n word_res->combination = true; // Give it ownership of the word.\n word_res->space_certainty = space_certainty;\n word_res->ratings = new MATRIX(word_end - word_start, 1);\n return word_res;\n}\n\n// Fills top_n_flags_ with bools that are true iff the corresponding output\n// is one of the top_n.\nvoid RecodeBeamSearch::ComputeTopN(const float *outputs, int num_outputs, int top_n) {\n top_n_flags_.clear();\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if (top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n }\n }\n }\n top_n_flags_[null_char_] = TN_TOP2;\n}\n\nvoid RecodeBeamSearch::ComputeSecTopN(std::unordered_set *exList, const float *outputs,\n int num_outputs, int top_n) {\n top_n_flags_.clear();\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if ((top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) && !exList->count(i)) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();", "text": "<|original_code|>\n line_box.bottom(),\n static_cast(std::ceil(character_boundaries_[i + 1] * scale_factor)) +\n line_box.left(),\n line_box.top());\n b_it.add_after_then_move(C_BLOB::FakeBlob(box));\n }\n }\n // Make a fake word from the blobs.\n WERD *word = new WERD(&blobs, leading_space, nullptr);\n // Make a WERD_RES from the word.\n auto *word_res = new WERD_RES(word);\n word_res->end = word_end - word_start + leading_space;\n word_res->uch_set = unicharset;\n word_res->combination = true; // Give it ownership of the word.\n word_res->space_certainty = space_certainty;\n word_res->ratings = new MATRIX(word_end - word_start, 1);\n return word_res;\n}\n\n// Fills top_n_flags_ with bools that are true iff the corresponding output\n// is one of the top_n.\nvoid RecodeBeamSearch::ComputeTopN(const float *outputs, int num_outputs, int top_n) {\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if (top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n }\n }\n }\n top_n_flags_[null_char_] = TN_TOP2;\n}\n\nvoid RecodeBeamSearch::ComputeSecTopN(std::unordered_set *exList, const float *outputs,\n int num_outputs, int top_n) {\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if ((top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) && !exList->count(i)) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n<|edits_diff|>\n--- src/lstm/recodebeam.cpp\n+++ src/lstm/recodebeam.cpp\n@@ -20,6 +20,7 @@\n // Fills top_n_flags_ with bools that are true iff the corresponding output\n // is one of the top_n.\n void RecodeBeamSearch::ComputeTopN(const float *outputs, int num_outputs, int top_n) {\n+ top_n_flags_.clear();\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n<|current_version|>\n line_box.bottom(),\n static_cast(std::ceil(character_boundaries_[i + 1] * scale_factor)) +\n line_box.left(),\n line_box.top());\n b_it.add_after_then_move(C_BLOB::FakeBlob(box));\n }\n }\n // Make a fake word from the blobs.\n WERD *word = new WERD(&blobs, leading_space, nullptr);\n // Make a WERD_RES from the word.\n auto *word_res = new WERD_RES(word);\n word_res->end = word_end - word_start + leading_space;\n word_res->uch_set = unicharset;\n word_res->combination = true; // Give it ownership of the word.\n word_res->space_certainty = space_certainty;\n word_res->ratings = new MATRIX(word_end - word_start, 1);\n return word_res;\n}\n\n// Fills top_n_flags_ with bools that are true iff the corresponding output\n// is one of the top_n.\nvoid RecodeBeamSearch::ComputeTopN(const float *outputs, int num_outputs, int top_n) {\n top_n_flags_.clear();\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if (top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n }\n }\n }\n top_n_flags_[null_char_] = TN_TOP2;\n}\n\nvoid RecodeBeamSearch::ComputeSecTopN(std::unordered_set *exList, const float *outputs,\n int num_outputs, int top_n) {\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if ((top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) && !exList->count(i)) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n<|next_version|>\n line_box.bottom(),\n static_cast(std::ceil(character_boundaries_[i + 1] * scale_factor)) +\n line_box.left(),\n line_box.top());\n b_it.add_after_then_move(C_BLOB::FakeBlob(box));\n }\n }\n // Make a fake word from the blobs.\n WERD *word = new WERD(&blobs, leading_space, nullptr);\n // Make a WERD_RES from the word.\n auto *word_res = new WERD_RES(word);\n word_res->end = word_end - word_start + leading_space;\n word_res->uch_set = unicharset;\n word_res->combination = true; // Give it ownership of the word.\n word_res->space_certainty = space_certainty;\n word_res->ratings = new MATRIX(word_end - word_start, 1);\n return word_res;\n}\n\n// Fills top_n_flags_ with bools that are true iff the corresponding output\n// is one of the top_n.\nvoid RecodeBeamSearch::ComputeTopN(const float *outputs, int num_outputs, int top_n) {\n top_n_flags_.clear();\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if (top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n }\n }\n }\n top_n_flags_[null_char_] = TN_TOP2;\n}\n\nvoid RecodeBeamSearch::ComputeSecTopN(std::unordered_set *exList, const float *outputs,\n int num_outputs, int top_n) {\n top_n_flags_.clear();\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if ((top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) && !exList->count(i)) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n", "current_contents": " line_box.bottom(),\n static_cast(std::ceil(character_boundaries_[i + 1] * scale_factor)) +\n line_box.left(),\n line_box.top());\n b_it.add_after_then_move(C_BLOB::FakeBlob(box));\n }\n }\n // Make a fake word from the blobs.\n WERD *word = new WERD(&blobs, leading_space, nullptr);\n // Make a WERD_RES from the word.\n auto *word_res = new WERD_RES(word);\n word_res->end = word_end - word_start + leading_space;\n word_res->uch_set = unicharset;\n word_res->combination = true; // Give it ownership of the word.\n word_res->space_certainty = space_certainty;\n word_res->ratings = new MATRIX(word_end - word_start, 1);\n return word_res;\n}\n\n// Fills top_n_flags_ with bools that are true iff the corresponding output\n// is one of the top_n.\nvoid RecodeBeamSearch::ComputeTopN(const float *outputs, int num_outputs, int top_n) {\n top_n_flags_.clear();\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if (top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();\n }\n }\n }\n top_n_flags_[null_char_] = TN_TOP2;\n}\n\nvoid RecodeBeamSearch::ComputeSecTopN(std::unordered_set *exList, const float *outputs,\n int num_outputs, int top_n) {\n top_n_flags_.resize(num_outputs, TN_ALSO_RAN);\n top_code_ = -1;\n second_code_ = -1;\n top_heap_.clear();\n for (int i = 0; i < num_outputs; ++i) {\n if ((top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) && !exList->count(i)) {\n TopPair entry(outputs[i], i);\n top_heap_.Push(&entry);\n if (top_heap_.size() > top_n) {\n top_heap_.Pop(&entry);\n }\n }\n }\n while (!top_heap_.empty()) {\n TopPair entry;\n top_heap_.Pop(&entry);\n if (top_heap_.size() > 1) {\n top_n_flags_[entry.data()] = TN_TOPN;\n } else {\n top_n_flags_[entry.data()] = TN_TOP2;\n if (top_heap_.empty()) {\n top_code_ = entry.data();\n } else {\n second_code_ = entry.data();"} {"commit": "660b36640132775fdc31c4031e9d8c896127d876", "message": "Fix issues reported by Coverity Scan (#1409)", "old_file": "textord/baselinedetect.cpp", "new_file": "textord/baselinedetect.cpp", "status": "M", "old_contents": " tprintf(\"Linespacing model only moves current line by %g for row at:\",\n shift);\n bounding_box_.print();\n }\n } else if (debug > 1) {\n tprintf(\"Linespacing model not close enough to any mode for row at:\");\n bounding_box_.print();\n }\n return fmod(PerpDisp(direction), line_spacing);\n}\n\n// Sets up displacement_modes_ with the top few modes of the perpendicular\n// distance of each blob from the given direction vector, after rounding.\nvoid BaselineRow::SetupBlobDisplacements(const FCOORD& direction) {\n // Set of perpendicular displacements of the blob bottoms from the required\n // baseline direction.\n GenericVector perp_blob_dists;\n displacement_modes_.truncate(0);\n // Gather the skew-corrected position of every blob.\n double min_dist = MAX_FLOAT32;\n double max_dist = -MAX_FLOAT32;\n BLOBNBOX_IT blob_it(blobs_);\n bool debug = false;\n for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {\n BLOBNBOX* blob = blob_it.data();\n const TBOX& box = blob->bounding_box();\n#ifdef kDebugYCoord\n if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) debug = true;\n#endif\n FCOORD blob_pos((box.left() + box.right()) / 2.0f,\n blob->baseline_position());\n double offset = direction * blob_pos;\n perp_blob_dists.push_back(offset);\n if (debug) {\n tprintf(\"Displacement %g for blob at:\", offset);\n box.print();\n }\n UpdateRange(offset, &min_dist, &max_dist);\n }\n // Set up a histogram using disp_quant_factor_ as the bucket size.\n STATS dist_stats(IntCastRounded(min_dist / disp_quant_factor_),\n IntCastRounded(max_dist / disp_quant_factor_) + 1);\n for (int i = 0; i < perp_blob_dists.size(); ++i) {\n dist_stats.add(IntCastRounded(perp_blob_dists[i] / disp_quant_factor_), 1);\n }\n GenericVector > scaled_modes;\n dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);\n if (debug) {\n for (int i = 0; i < scaled_modes.size(); ++i) {\n tprintf(\"Top mode = %g * %d\\n\",\n scaled_modes[i].key * disp_quant_factor_, scaled_modes[i].data);\n }\n }\n for (int i = 0; i < scaled_modes.size(); ++i)\n displacement_modes_.push_back(disp_quant_factor_ * scaled_modes[i].key);\n}\n\n// Fits a line in the given direction to blobs that are close to the given\n// target_offset perpendicular displacement from the direction. The fit\n// error is allowed to be cheat_allowance worse than the existing fit, and\n// will still be used.\n// If cheat_allowance > 0, the new fit will be good and replace the current\n// fit if it has better fit (with cheat) OR its error is below\n// max_baseline_error_ and the old fit is marked bad.\n// Otherwise the new fit will only replace the old if it is really better,\n// or the old fit is marked bad and the new fit has sufficient points, as\n// well as being within the max_baseline_error_.\nvoid BaselineRow::FitConstrainedIfBetter(int debug,\n const FCOORD& direction,\n double cheat_allowance,\n double target_offset) {\n double halfrange = fit_halfrange_ * direction.length();\n double min_dist = target_offset - halfrange;\n double max_dist = target_offset + halfrange;\n ICOORD line_pt;\n double new_error = fitter_.ConstrainedFit(direction, min_dist, max_dist,\n debug > 2, &line_pt);", "new_contents": " tprintf(\"Linespacing model only moves current line by %g for row at:\",\n shift);\n bounding_box_.print();\n }\n } else if (debug > 1) {\n tprintf(\"Linespacing model not close enough to any mode for row at:\");\n bounding_box_.print();\n }\n return fmod(PerpDisp(direction), line_spacing);\n}\n\n// Sets up displacement_modes_ with the top few modes of the perpendicular\n// distance of each blob from the given direction vector, after rounding.\nvoid BaselineRow::SetupBlobDisplacements(const FCOORD& direction) {\n // Set of perpendicular displacements of the blob bottoms from the required\n // baseline direction.\n GenericVector perp_blob_dists;\n displacement_modes_.truncate(0);\n // Gather the skew-corrected position of every blob.\n double min_dist = MAX_FLOAT32;\n double max_dist = -MAX_FLOAT32;\n BLOBNBOX_IT blob_it(blobs_);\n#ifdef kDebugYCoord\n bool debug = false;\n#endif\n for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {\n BLOBNBOX* blob = blob_it.data();\n const TBOX& box = blob->bounding_box();\n#ifdef kDebugYCoord\n if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) debug = true;\n#endif\n FCOORD blob_pos((box.left() + box.right()) / 2.0f,\n blob->baseline_position());\n double offset = direction * blob_pos;\n perp_blob_dists.push_back(offset);\n#ifdef kDebugYCoord\n if (debug) {\n tprintf(\"Displacement %g for blob at:\", offset);\n box.print();\n }\n#endif\n UpdateRange(offset, &min_dist, &max_dist);\n }\n // Set up a histogram using disp_quant_factor_ as the bucket size.\n STATS dist_stats(IntCastRounded(min_dist / disp_quant_factor_),\n IntCastRounded(max_dist / disp_quant_factor_) + 1);\n for (int i = 0; i < perp_blob_dists.size(); ++i) {\n dist_stats.add(IntCastRounded(perp_blob_dists[i] / disp_quant_factor_), 1);\n }\n GenericVector > scaled_modes;\n dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);\n#ifdef kDebugYCoord\n if (debug) {\n for (int i = 0; i < scaled_modes.size(); ++i) {\n tprintf(\"Top mode = %g * %d\\n\",\n scaled_modes[i].key * disp_quant_factor_, scaled_modes[i].data);\n }\n }\n#endif\n for (int i = 0; i < scaled_modes.size(); ++i)\n displacement_modes_.push_back(disp_quant_factor_ * scaled_modes[i].key);\n}\n\n// Fits a line in the given direction to blobs that are close to the given\n// target_offset perpendicular displacement from the direction. The fit\n// error is allowed to be cheat_allowance worse than the existing fit, and\n// will still be used.\n// If cheat_allowance > 0, the new fit will be good and replace the current\n// fit if it has better fit (with cheat) OR its error is below\n// max_baseline_error_ and the old fit is marked bad.\n// Otherwise the new fit will only replace the old if it is really better,\n// or the old fit is marked bad and the new fit has sufficient points, as\n// well as being within the max_baseline_error_.\nvoid BaselineRow::FitConstrainedIfBetter(int debug,\n const FCOORD& direction,\n double cheat_allowance,\n double target_offset) {\n double halfrange = fit_halfrange_ * direction.length();\n double min_dist = target_offset - halfrange;\n double max_dist = target_offset + halfrange;\n ICOORD line_pt;\n double new_error = fitter_.ConstrainedFit(direction, min_dist, max_dist,\n debug > 2, &line_pt);", "text": "<|original_code|>\n tprintf(\"Linespacing model only moves current line by %g for row at:\",\n shift);\n bounding_box_.print();\n }\n } else if (debug > 1) {\n tprintf(\"Linespacing model not close enough to any mode for row at:\");\n bounding_box_.print();\n }\n return fmod(PerpDisp(direction), line_spacing);\n}\n\n// Sets up displacement_modes_ with the top few modes of the perpendicular\n// distance of each blob from the given direction vector, after rounding.\nvoid BaselineRow::SetupBlobDisplacements(const FCOORD& direction) {\n // Set of perpendicular displacements of the blob bottoms from the required\n // baseline direction.\n GenericVector perp_blob_dists;\n displacement_modes_.truncate(0);\n // Gather the skew-corrected position of every blob.\n double min_dist = MAX_FLOAT32;\n double max_dist = -MAX_FLOAT32;\n BLOBNBOX_IT blob_it(blobs_);\n bool debug = false;\n for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {\n BLOBNBOX* blob = blob_it.data();\n const TBOX& box = blob->bounding_box();\n#ifdef kDebugYCoord\n if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) debug = true;\n#endif\n FCOORD blob_pos((box.left() + box.right()) / 2.0f,\n blob->baseline_position());\n double offset = direction * blob_pos;\n perp_blob_dists.push_back(offset);\n if (debug) {\n tprintf(\"Displacement %g for blob at:\", offset);\n box.print();\n }\n UpdateRange(offset, &min_dist, &max_dist);\n }\n // Set up a histogram using disp_quant_factor_ as the bucket size.\n STATS dist_stats(IntCastRounded(min_dist / disp_quant_factor_),\n IntCastRounded(max_dist / disp_quant_factor_) + 1);\n for (int i = 0; i < perp_blob_dists.size(); ++i) {\n dist_stats.add(IntCastRounded(perp_blob_dists[i] / disp_quant_factor_), 1);\n }\n GenericVector > scaled_modes;\n dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);\n if (debug) {\n for (int i = 0; i < scaled_modes.size(); ++i) {\n tprintf(\"Top mode = %g * %d\\n\",\n scaled_modes[i].key * disp_quant_factor_, scaled_modes[i].data);\n }\n }\n for (int i = 0; i < scaled_modes.size(); ++i)\n displacement_modes_.push_back(disp_quant_factor_ * scaled_modes[i].key);\n}\n\n// Fits a line in the given direction to blobs that are close to the given\n// target_offset perpendicular displacement from the direction. The fit\n// error is allowed to be cheat_allowance worse than the existing fit, and\n// will still be used.\n// If cheat_allowance > 0, the new fit will be good and replace the current\n// fit if it has better fit (with cheat) OR its error is below\n// max_baseline_error_ and the old fit is marked bad.\n// Otherwise the new fit will only replace the old if it is really better,\n// or the old fit is marked bad and the new fit has sufficient points, as\n// well as being within the max_baseline_error_.\nvoid BaselineRow::FitConstrainedIfBetter(int debug,\n const FCOORD& direction,\n double cheat_allowance,\n double target_offset) {\n double halfrange = fit_halfrange_ * direction.length();\n double min_dist = target_offset - halfrange;\n double max_dist = target_offset + halfrange;\n ICOORD line_pt;\n double new_error = fitter_.ConstrainedFit(direction, min_dist, max_dist,\n debug > 2, &line_pt);\n<|edits_diff|>\n--- textord/baselinedetect.cpp\n+++ textord/baselinedetect.cpp\n@@ -20,7 +20,9 @@\n double min_dist = MAX_FLOAT32;\n double max_dist = -MAX_FLOAT32;\n BLOBNBOX_IT blob_it(blobs_);\n+#ifdef kDebugYCoord\n bool debug = false;\n+#endif\n for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {\n BLOBNBOX* blob = blob_it.data();\n const TBOX& box = blob->bounding_box();\n@@ -31,10 +33,12 @@\n blob->baseline_position());\n double offset = direction * blob_pos;\n perp_blob_dists.push_back(offset);\n+#ifdef kDebugYCoord\n if (debug) {\n tprintf(\"Displacement %g for blob at:\", offset);\n box.print();\n }\n+#endif\n UpdateRange(offset, &min_dist, &max_dist);\n }\n // Set up a histogram using disp_quant_factor_ as the bucket size.\n@@ -45,6 +49,7 @@\n }\n GenericVector > scaled_modes;\n dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);\n+#ifdef kDebugYCoord\n if (debug) {\n for (int i = 0; i < scaled_modes.size(); ++i) {\n tprintf(\"Top mode = %g * %d\\n\",\n<|current_version|>\n tprintf(\"Linespacing model only moves current line by %g for row at:\",\n shift);\n bounding_box_.print();\n }\n } else if (debug > 1) {\n tprintf(\"Linespacing model not close enough to any mode for row at:\");\n bounding_box_.print();\n }\n return fmod(PerpDisp(direction), line_spacing);\n}\n\n// Sets up displacement_modes_ with the top few modes of the perpendicular\n// distance of each blob from the given direction vector, after rounding.\nvoid BaselineRow::SetupBlobDisplacements(const FCOORD& direction) {\n // Set of perpendicular displacements of the blob bottoms from the required\n // baseline direction.\n GenericVector perp_blob_dists;\n displacement_modes_.truncate(0);\n // Gather the skew-corrected position of every blob.\n double min_dist = MAX_FLOAT32;\n double max_dist = -MAX_FLOAT32;\n BLOBNBOX_IT blob_it(blobs_);\n#ifdef kDebugYCoord\n bool debug = false;\n#endif\n for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {\n BLOBNBOX* blob = blob_it.data();\n const TBOX& box = blob->bounding_box();\n#ifdef kDebugYCoord\n if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) debug = true;\n#endif\n FCOORD blob_pos((box.left() + box.right()) / 2.0f,\n blob->baseline_position());\n double offset = direction * blob_pos;\n perp_blob_dists.push_back(offset);\n#ifdef kDebugYCoord\n if (debug) {\n tprintf(\"Displacement %g for blob at:\", offset);\n box.print();\n }\n#endif\n UpdateRange(offset, &min_dist, &max_dist);\n }\n // Set up a histogram using disp_quant_factor_ as the bucket size.\n STATS dist_stats(IntCastRounded(min_dist / disp_quant_factor_),\n IntCastRounded(max_dist / disp_quant_factor_) + 1);\n for (int i = 0; i < perp_blob_dists.size(); ++i) {\n dist_stats.add(IntCastRounded(perp_blob_dists[i] / disp_quant_factor_), 1);\n }\n GenericVector > scaled_modes;\n dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);\n#ifdef kDebugYCoord\n if (debug) {\n for (int i = 0; i < scaled_modes.size(); ++i) {\n tprintf(\"Top mode = %g * %d\\n\",\n scaled_modes[i].key * disp_quant_factor_, scaled_modes[i].data);\n }\n }\n for (int i = 0; i < scaled_modes.size(); ++i)\n displacement_modes_.push_back(disp_quant_factor_ * scaled_modes[i].key);\n}\n\n// Fits a line in the given direction to blobs that are close to the given\n// target_offset perpendicular displacement from the direction. The fit\n// error is allowed to be cheat_allowance worse than the existing fit, and\n// will still be used.\n// If cheat_allowance > 0, the new fit will be good and replace the current\n// fit if it has better fit (with cheat) OR its error is below\n// max_baseline_error_ and the old fit is marked bad.\n// Otherwise the new fit will only replace the old if it is really better,\n// or the old fit is marked bad and the new fit has sufficient points, as\n// well as being within the max_baseline_error_.\nvoid BaselineRow::FitConstrainedIfBetter(int debug,\n const FCOORD& direction,\n double cheat_allowance,\n double target_offset) {\n double halfrange = fit_halfrange_ * direction.length();\n double min_dist = target_offset - halfrange;\n double max_dist = target_offset + halfrange;\n ICOORD line_pt;\n double new_error = fitter_.ConstrainedFit(direction, min_dist, max_dist,\n debug > 2, &line_pt);\n<|next_version|>\n tprintf(\"Linespacing model only moves current line by %g for row at:\",\n shift);\n bounding_box_.print();\n }\n } else if (debug > 1) {\n tprintf(\"Linespacing model not close enough to any mode for row at:\");\n bounding_box_.print();\n }\n return fmod(PerpDisp(direction), line_spacing);\n}\n\n// Sets up displacement_modes_ with the top few modes of the perpendicular\n// distance of each blob from the given direction vector, after rounding.\nvoid BaselineRow::SetupBlobDisplacements(const FCOORD& direction) {\n // Set of perpendicular displacements of the blob bottoms from the required\n // baseline direction.\n GenericVector perp_blob_dists;\n displacement_modes_.truncate(0);\n // Gather the skew-corrected position of every blob.\n double min_dist = MAX_FLOAT32;\n double max_dist = -MAX_FLOAT32;\n BLOBNBOX_IT blob_it(blobs_);\n#ifdef kDebugYCoord\n bool debug = false;\n#endif\n for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {\n BLOBNBOX* blob = blob_it.data();\n const TBOX& box = blob->bounding_box();\n#ifdef kDebugYCoord\n if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) debug = true;\n#endif\n FCOORD blob_pos((box.left() + box.right()) / 2.0f,\n blob->baseline_position());\n double offset = direction * blob_pos;\n perp_blob_dists.push_back(offset);\n#ifdef kDebugYCoord\n if (debug) {\n tprintf(\"Displacement %g for blob at:\", offset);\n box.print();\n }\n#endif\n UpdateRange(offset, &min_dist, &max_dist);\n }\n // Set up a histogram using disp_quant_factor_ as the bucket size.\n STATS dist_stats(IntCastRounded(min_dist / disp_quant_factor_),\n IntCastRounded(max_dist / disp_quant_factor_) + 1);\n for (int i = 0; i < perp_blob_dists.size(); ++i) {\n dist_stats.add(IntCastRounded(perp_blob_dists[i] / disp_quant_factor_), 1);\n }\n GenericVector > scaled_modes;\n dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);\n#ifdef kDebugYCoord\n if (debug) {\n for (int i = 0; i < scaled_modes.size(); ++i) {\n tprintf(\"Top mode = %g * %d\\n\",\n scaled_modes[i].key * disp_quant_factor_, scaled_modes[i].data);\n }\n }\n#endif\n for (int i = 0; i < scaled_modes.size(); ++i)\n displacement_modes_.push_back(disp_quant_factor_ * scaled_modes[i].key);\n}\n\n// Fits a line in the given direction to blobs that are close to the given\n// target_offset perpendicular displacement from the direction. The fit\n// error is allowed to be cheat_allowance worse than the existing fit, and\n// will still be used.\n// If cheat_allowance > 0, the new fit will be good and replace the current\n// fit if it has better fit (with cheat) OR its error is below\n// max_baseline_error_ and the old fit is marked bad.\n// Otherwise the new fit will only replace the old if it is really better,\n// or the old fit is marked bad and the new fit has sufficient points, as\n// well as being within the max_baseline_error_.\nvoid BaselineRow::FitConstrainedIfBetter(int debug,\n const FCOORD& direction,\n double cheat_allowance,\n double target_offset) {\n double halfrange = fit_halfrange_ * direction.length();\n double min_dist = target_offset - halfrange;\n double max_dist = target_offset + halfrange;\n ICOORD line_pt;\n double new_error = fitter_.ConstrainedFit(direction, min_dist, max_dist,\n debug > 2, &line_pt);\n", "current_contents": " tprintf(\"Linespacing model only moves current line by %g for row at:\",\n shift);\n bounding_box_.print();\n }\n } else if (debug > 1) {\n tprintf(\"Linespacing model not close enough to any mode for row at:\");\n bounding_box_.print();\n }\n return fmod(PerpDisp(direction), line_spacing);\n}\n\n// Sets up displacement_modes_ with the top few modes of the perpendicular\n// distance of each blob from the given direction vector, after rounding.\nvoid BaselineRow::SetupBlobDisplacements(const FCOORD& direction) {\n // Set of perpendicular displacements of the blob bottoms from the required\n // baseline direction.\n GenericVector perp_blob_dists;\n displacement_modes_.truncate(0);\n // Gather the skew-corrected position of every blob.\n double min_dist = MAX_FLOAT32;\n double max_dist = -MAX_FLOAT32;\n BLOBNBOX_IT blob_it(blobs_);\n#ifdef kDebugYCoord\n bool debug = false;\n#endif\n for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {\n BLOBNBOX* blob = blob_it.data();\n const TBOX& box = blob->bounding_box();\n#ifdef kDebugYCoord\n if (box.bottom() < kDebugYCoord && box.top() > kDebugYCoord) debug = true;\n#endif\n FCOORD blob_pos((box.left() + box.right()) / 2.0f,\n blob->baseline_position());\n double offset = direction * blob_pos;\n perp_blob_dists.push_back(offset);\n#ifdef kDebugYCoord\n if (debug) {\n tprintf(\"Displacement %g for blob at:\", offset);\n box.print();\n }\n#endif\n UpdateRange(offset, &min_dist, &max_dist);\n }\n // Set up a histogram using disp_quant_factor_ as the bucket size.\n STATS dist_stats(IntCastRounded(min_dist / disp_quant_factor_),\n IntCastRounded(max_dist / disp_quant_factor_) + 1);\n for (int i = 0; i < perp_blob_dists.size(); ++i) {\n dist_stats.add(IntCastRounded(perp_blob_dists[i] / disp_quant_factor_), 1);\n }\n GenericVector > scaled_modes;\n dist_stats.top_n_modes(kMaxDisplacementsModes, &scaled_modes);\n#ifdef kDebugYCoord\n if (debug) {\n for (int i = 0; i < scaled_modes.size(); ++i) {\n tprintf(\"Top mode = %g * %d\\n\",\n scaled_modes[i].key * disp_quant_factor_, scaled_modes[i].data);\n }\n }\n for (int i = 0; i < scaled_modes.size(); ++i)\n displacement_modes_.push_back(disp_quant_factor_ * scaled_modes[i].key);\n}\n\n// Fits a line in the given direction to blobs that are close to the given\n// target_offset perpendicular displacement from the direction. The fit\n// error is allowed to be cheat_allowance worse than the existing fit, and\n// will still be used.\n// If cheat_allowance > 0, the new fit will be good and replace the current\n// fit if it has better fit (with cheat) OR its error is below\n// max_baseline_error_ and the old fit is marked bad.\n// Otherwise the new fit will only replace the old if it is really better,\n// or the old fit is marked bad and the new fit has sufficient points, as\n// well as being within the max_baseline_error_.\nvoid BaselineRow::FitConstrainedIfBetter(int debug,\n const FCOORD& direction,\n double cheat_allowance,\n double target_offset) {\n double halfrange = fit_halfrange_ * direction.length();\n double min_dist = target_offset - halfrange;\n double max_dist = target_offset + halfrange;\n ICOORD line_pt;\n double new_error = fitter_.ConstrainedFit(direction, min_dist, max_dist,\n debug > 2, &line_pt);"} {"commit": "d8b1456dd56bace3be63988e94f69f1b9351e930", "message": "Changes to ccutil for 3.00", "old_file": "ccutil/tprintf.cpp", "new_file": "ccutil/tprintf.cpp", "status": "M", "old_contents": " * Created: Wed Jun 28 15:01:15 BST 1995\n *\n * (C) Copyright 1995, Hewlett-Packard Ltd.\n ** Licensed under the Apache License, Version 2.0 (the \"License\");\n ** you may not use this file except in compliance with the License.\n ** You may obtain a copy of the License at\n ** http://www.apache.org/licenses/LICENSE-2.0\n ** Unless required by applicable law or agreed to in writing, software\n ** distributed under the License is distributed on an \"AS IS\" BASIS,\n ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ** See the License for the specific language governing permissions and\n ** limitations under the License.\n *\n **********************************************************************/\n#include \"mfcpch.h\" //precompiled headers\n#include \n#include \n#include \"strngs.h\"\n#include \"varable.h\"\n#include \"debugwin.h\"\n//#include \"ipeerr.h\"\n#include \"tprintf.h\"\n\n#define MAX_MSG_LEN 1024\n\n#define EXTERN\nDLLSYM STRING_VAR (debug_file, \"\", \"File to send tprintf output to\");\nDLLSYM BOOL_VAR (debug_window_on, FALSE,\n\"Send tprintf to window unless file set\");\n\nDLLSYM void\ntprintf ( //Trace printf\nconst char *format, ... //special message\n) {\n va_list args; //variable args\n static FILE *debugfp = NULL; //debug file\n //debug window\n static DEBUG_WIN *debugwin = NULL;\n inT32 offset = 0; //into message\n static char msg[MAX_MSG_LEN + 1];\n\n va_start(args, format); //variable list\n #ifdef __MSW32__\n //Format into msg\n offset += _vsnprintf (msg + offset, MAX_MSG_LEN - offset, format, args);\n #else\n //Format into msg\n offset += vsprintf (msg + offset, format, args);\n #endif\n va_end(args);\n\n if (debugfp == NULL && strlen (debug_file.string ()) > 0)\n debugfp = fopen (debug_file.string (), \"w\");\n else if (debugfp != NULL && strlen (debug_file.string ()) == 0) {\n fclose(debugfp);\n debugfp = NULL;\n }\n if (debugfp != NULL)\n fprintf (debugfp, \"%s\", msg);\n else {\n\n if (debug_window_on) {\n if (debugwin == NULL)\n //in pixels\n debugwin = new DEBUG_WIN (\"Debug Window\", DEBUG_WIN_XPOS, DEBUG_WIN_YPOS,\n //in pixels\n DEBUG_WIN_XSIZE, DEBUG_WIN_YSIZE,\n debug_lines);\n debugwin->dprintf (msg);\n }\n else {\n fprintf (stderr, \"%s\", msg);\n }\n }\n}\n\n\n/*************************************************************************\n * pause_continue()\n * UI for a debugging pause - to see an intermediate state\n * Returns TRUE to continue as normal to the next pause in the current mode;\n * FALSE to quit the current pausing mode.\n *************************************************************************/\n\nDLLSYM BOOL8\n //special message\npause_continue (const char *format, ...\n) {\n va_list args; //variable args\n char msg[1000];\n STRING str = STRING (\"DEBUG PAUSE:\\n\");\n\n va_start(args, format); //variable list\n vsprintf(msg, format, args); //Format into msg\n va_end(args);\n\n #ifdef GRAPHICS_DISABLED\n // No interaction allowed -> simply go on", "new_contents": " * Created: Wed Jun 28 15:01:15 BST 1995\n *\n * (C) Copyright 1995, Hewlett-Packard Ltd.\n ** Licensed under the Apache License, Version 2.0 (the \"License\");\n ** you may not use this file except in compliance with the License.\n ** You may obtain a copy of the License at\n ** http://www.apache.org/licenses/LICENSE-2.0\n ** Unless required by applicable law or agreed to in writing, software\n ** distributed under the License is distributed on an \"AS IS\" BASIS,\n ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ** See the License for the specific language governing permissions and\n ** limitations under the License.\n *\n **********************************************************************/\n#include \"mfcpch.h\" //precompiled headers\n#include \n#include \n#include \"strngs.h\"\n#include \"varable.h\"\n#include \"debugwin.h\"\n//#include \"ipeerr.h\"\n#include \"tprintf.h\"\n#include \"ccutil.h\"\n\n#define MAX_MSG_LEN 1024\n\n#define EXTERN\nDLLSYM STRING_VAR (debug_file, \"\", \"File to send tprintf output to\");\nDLLSYM BOOL_VAR (debug_window_on, FALSE,\n\"Send tprintf to window unless file set\");\n\nDLLSYM void\ntprintf ( //Trace printf\nconst char *format, ... //special message\n) {\n tesseract::tprintfMutex.Lock();\n va_list args; //variable args\n static FILE *debugfp = NULL; //debug file\n //debug window\n static DEBUG_WIN *debugwin = NULL;\n inT32 offset = 0; //into message\n static char msg[MAX_MSG_LEN + 1];\n\n va_start(args, format); //variable list\n #ifdef __MSW32__\n //Format into msg\n offset += _vsnprintf (msg + offset, MAX_MSG_LEN - offset, format, args);\n #else\n //Format into msg\n offset += vsprintf (msg + offset, format, args);\n #endif\n va_end(args);\n\n if (debugfp == NULL && strlen (debug_file.string ()) > 0)\n debugfp = fopen (debug_file.string (), \"w\");\n else if (debugfp != NULL && strlen (debug_file.string ()) == 0) {\n fclose(debugfp);\n debugfp = NULL;\n }\n if (debugfp != NULL)\n fprintf (debugfp, \"%s\", msg);\n else {\n\n if (debug_window_on) {\n if (debugwin == NULL)\n //in pixels\n debugwin = new DEBUG_WIN (\"Debug Window\", DEBUG_WIN_XPOS, DEBUG_WIN_YPOS,\n //in pixels\n DEBUG_WIN_XSIZE, DEBUG_WIN_YSIZE,\n debug_lines);\n debugwin->dprintf (msg);\n }\n else {\n fprintf (stderr, \"%s\", msg);\n }\n }\n tesseract::tprintfMutex.Unlock();\n}\n\n\n/*************************************************************************\n * pause_continue()\n * UI for a debugging pause - to see an intermediate state\n * Returns TRUE to continue as normal to the next pause in the current mode;\n * FALSE to quit the current pausing mode.\n *************************************************************************/\n\nDLLSYM BOOL8\n //special message\npause_continue (const char *format, ...\n) {\n va_list args; //variable args\n char msg[1000];\n STRING str = STRING (\"DEBUG PAUSE:\\n\");\n\n va_start(args, format); //variable list\n vsprintf(msg, format, args); //Format into msg\n va_end(args);\n\n #ifdef GRAPHICS_DISABLED\n // No interaction allowed -> simply go on", "text": "<|original_code|>\n * Created: Wed Jun 28 15:01:15 BST 1995\n *\n * (C) Copyright 1995, Hewlett-Packard Ltd.\n ** Licensed under the Apache License, Version 2.0 (the \"License\");\n ** you may not use this file except in compliance with the License.\n ** You may obtain a copy of the License at\n ** http://www.apache.org/licenses/LICENSE-2.0\n ** Unless required by applicable law or agreed to in writing, software\n ** distributed under the License is distributed on an \"AS IS\" BASIS,\n ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ** See the License for the specific language governing permissions and\n ** limitations under the License.\n *\n **********************************************************************/\n#include \"mfcpch.h\" //precompiled headers\n#include \n#include \n#include \"strngs.h\"\n#include \"varable.h\"\n#include \"debugwin.h\"\n//#include \"ipeerr.h\"\n#include \"tprintf.h\"\n\n#define MAX_MSG_LEN 1024\n\n#define EXTERN\nDLLSYM STRING_VAR (debug_file, \"\", \"File to send tprintf output to\");\nDLLSYM BOOL_VAR (debug_window_on, FALSE,\n\"Send tprintf to window unless file set\");\n\nDLLSYM void\ntprintf ( //Trace printf\nconst char *format, ... //special message\n) {\n va_list args; //variable args\n static FILE *debugfp = NULL; //debug file\n //debug window\n static DEBUG_WIN *debugwin = NULL;\n inT32 offset = 0; //into message\n static char msg[MAX_MSG_LEN + 1];\n\n va_start(args, format); //variable list\n #ifdef __MSW32__\n //Format into msg\n offset += _vsnprintf (msg + offset, MAX_MSG_LEN - offset, format, args);\n #else\n //Format into msg\n offset += vsprintf (msg + offset, format, args);\n #endif\n va_end(args);\n\n if (debugfp == NULL && strlen (debug_file.string ()) > 0)\n debugfp = fopen (debug_file.string (), \"w\");\n else if (debugfp != NULL && strlen (debug_file.string ()) == 0) {\n fclose(debugfp);\n debugfp = NULL;\n }\n if (debugfp != NULL)\n fprintf (debugfp, \"%s\", msg);\n else {\n\n if (debug_window_on) {\n if (debugwin == NULL)\n //in pixels\n debugwin = new DEBUG_WIN (\"Debug Window\", DEBUG_WIN_XPOS, DEBUG_WIN_YPOS,\n //in pixels\n DEBUG_WIN_XSIZE, DEBUG_WIN_YSIZE,\n debug_lines);\n debugwin->dprintf (msg);\n }\n else {\n fprintf (stderr, \"%s\", msg);\n }\n }\n}\n\n\n/*************************************************************************\n * pause_continue()\n * UI for a debugging pause - to see an intermediate state\n * Returns TRUE to continue as normal to the next pause in the current mode;\n * FALSE to quit the current pausing mode.\n *************************************************************************/\n\nDLLSYM BOOL8\n //special message\npause_continue (const char *format, ...\n) {\n va_list args; //variable args\n char msg[1000];\n STRING str = STRING (\"DEBUG PAUSE:\\n\");\n\n va_start(args, format); //variable list\n vsprintf(msg, format, args); //Format into msg\n va_end(args);\n\n #ifdef GRAPHICS_DISABLED\n // No interaction allowed -> simply go on\n<|edits_diff|>\n--- ccutil/tprintf.cpp\n+++ ccutil/tprintf.cpp\n@@ -20,6 +20,7 @@\n #include \"debugwin.h\"\n //#include \"ipeerr.h\"\n #include \"tprintf.h\"\n+#include \"ccutil.h\"\n \n #define MAX_MSG_LEN 1024\n \n@@ -32,6 +33,7 @@\n tprintf ( //Trace printf\n const char *format, ... //special message\n ) {\n+ tesseract::tprintfMutex.Lock();\n va_list args; //variable args\n static FILE *debugfp = NULL; //debug file\n //debug window\n<|current_version|>\n * Created: Wed Jun 28 15:01:15 BST 1995\n *\n * (C) Copyright 1995, Hewlett-Packard Ltd.\n ** Licensed under the Apache License, Version 2.0 (the \"License\");\n ** you may not use this file except in compliance with the License.\n ** You may obtain a copy of the License at\n ** http://www.apache.org/licenses/LICENSE-2.0\n ** Unless required by applicable law or agreed to in writing, software\n ** distributed under the License is distributed on an \"AS IS\" BASIS,\n ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ** See the License for the specific language governing permissions and\n ** limitations under the License.\n *\n **********************************************************************/\n#include \"mfcpch.h\" //precompiled headers\n#include \n#include \n#include \"strngs.h\"\n#include \"varable.h\"\n#include \"debugwin.h\"\n//#include \"ipeerr.h\"\n#include \"tprintf.h\"\n#include \"ccutil.h\"\n\n#define MAX_MSG_LEN 1024\n\n#define EXTERN\nDLLSYM STRING_VAR (debug_file, \"\", \"File to send tprintf output to\");\nDLLSYM BOOL_VAR (debug_window_on, FALSE,\n\"Send tprintf to window unless file set\");\n\nDLLSYM void\ntprintf ( //Trace printf\nconst char *format, ... //special message\n) {\n tesseract::tprintfMutex.Lock();\n va_list args; //variable args\n static FILE *debugfp = NULL; //debug file\n //debug window\n static DEBUG_WIN *debugwin = NULL;\n inT32 offset = 0; //into message\n static char msg[MAX_MSG_LEN + 1];\n\n va_start(args, format); //variable list\n #ifdef __MSW32__\n //Format into msg\n offset += _vsnprintf (msg + offset, MAX_MSG_LEN - offset, format, args);\n #else\n //Format into msg\n offset += vsprintf (msg + offset, format, args);\n #endif\n va_end(args);\n\n if (debugfp == NULL && strlen (debug_file.string ()) > 0)\n debugfp = fopen (debug_file.string (), \"w\");\n else if (debugfp != NULL && strlen (debug_file.string ()) == 0) {\n fclose(debugfp);\n debugfp = NULL;\n }\n if (debugfp != NULL)\n fprintf (debugfp, \"%s\", msg);\n else {\n\n if (debug_window_on) {\n if (debugwin == NULL)\n //in pixels\n debugwin = new DEBUG_WIN (\"Debug Window\", DEBUG_WIN_XPOS, DEBUG_WIN_YPOS,\n //in pixels\n DEBUG_WIN_XSIZE, DEBUG_WIN_YSIZE,\n debug_lines);\n debugwin->dprintf (msg);\n }\n else {\n fprintf (stderr, \"%s\", msg);\n }\n }\n}\n\n\n/*************************************************************************\n * pause_continue()\n * UI for a debugging pause - to see an intermediate state\n * Returns TRUE to continue as normal to the next pause in the current mode;\n * FALSE to quit the current pausing mode.\n *************************************************************************/\n\nDLLSYM BOOL8\n //special message\npause_continue (const char *format, ...\n) {\n va_list args; //variable args\n char msg[1000];\n STRING str = STRING (\"DEBUG PAUSE:\\n\");\n\n va_start(args, format); //variable list\n vsprintf(msg, format, args); //Format into msg\n va_end(args);\n\n #ifdef GRAPHICS_DISABLED\n // No interaction allowed -> simply go on\n<|next_version|>\n * Created: Wed Jun 28 15:01:15 BST 1995\n *\n * (C) Copyright 1995, Hewlett-Packard Ltd.\n ** Licensed under the Apache License, Version 2.0 (the \"License\");\n ** you may not use this file except in compliance with the License.\n ** You may obtain a copy of the License at\n ** http://www.apache.org/licenses/LICENSE-2.0\n ** Unless required by applicable law or agreed to in writing, software\n ** distributed under the License is distributed on an \"AS IS\" BASIS,\n ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ** See the License for the specific language governing permissions and\n ** limitations under the License.\n *\n **********************************************************************/\n#include \"mfcpch.h\" //precompiled headers\n#include \n#include \n#include \"strngs.h\"\n#include \"varable.h\"\n#include \"debugwin.h\"\n//#include \"ipeerr.h\"\n#include \"tprintf.h\"\n#include \"ccutil.h\"\n\n#define MAX_MSG_LEN 1024\n\n#define EXTERN\nDLLSYM STRING_VAR (debug_file, \"\", \"File to send tprintf output to\");\nDLLSYM BOOL_VAR (debug_window_on, FALSE,\n\"Send tprintf to window unless file set\");\n\nDLLSYM void\ntprintf ( //Trace printf\nconst char *format, ... //special message\n) {\n tesseract::tprintfMutex.Lock();\n va_list args; //variable args\n static FILE *debugfp = NULL; //debug file\n //debug window\n static DEBUG_WIN *debugwin = NULL;\n inT32 offset = 0; //into message\n static char msg[MAX_MSG_LEN + 1];\n\n va_start(args, format); //variable list\n #ifdef __MSW32__\n //Format into msg\n offset += _vsnprintf (msg + offset, MAX_MSG_LEN - offset, format, args);\n #else\n //Format into msg\n offset += vsprintf (msg + offset, format, args);\n #endif\n va_end(args);\n\n if (debugfp == NULL && strlen (debug_file.string ()) > 0)\n debugfp = fopen (debug_file.string (), \"w\");\n else if (debugfp != NULL && strlen (debug_file.string ()) == 0) {\n fclose(debugfp);\n debugfp = NULL;\n }\n if (debugfp != NULL)\n fprintf (debugfp, \"%s\", msg);\n else {\n\n if (debug_window_on) {\n if (debugwin == NULL)\n //in pixels\n debugwin = new DEBUG_WIN (\"Debug Window\", DEBUG_WIN_XPOS, DEBUG_WIN_YPOS,\n //in pixels\n DEBUG_WIN_XSIZE, DEBUG_WIN_YSIZE,\n debug_lines);\n debugwin->dprintf (msg);\n }\n else {\n fprintf (stderr, \"%s\", msg);\n }\n }\n tesseract::tprintfMutex.Unlock();\n}\n\n\n/*************************************************************************\n * pause_continue()\n * UI for a debugging pause - to see an intermediate state\n * Returns TRUE to continue as normal to the next pause in the current mode;\n * FALSE to quit the current pausing mode.\n *************************************************************************/\n\nDLLSYM BOOL8\n //special message\npause_continue (const char *format, ...\n) {\n va_list args; //variable args\n char msg[1000];\n STRING str = STRING (\"DEBUG PAUSE:\\n\");\n\n va_start(args, format); //variable list\n vsprintf(msg, format, args); //Format into msg\n va_end(args);\n\n #ifdef GRAPHICS_DISABLED\n // No interaction allowed -> simply go on\n", "current_contents": " * Created: Wed Jun 28 15:01:15 BST 1995\n *\n * (C) Copyright 1995, Hewlett-Packard Ltd.\n ** Licensed under the Apache License, Version 2.0 (the \"License\");\n ** you may not use this file except in compliance with the License.\n ** You may obtain a copy of the License at\n ** http://www.apache.org/licenses/LICENSE-2.0\n ** Unless required by applicable law or agreed to in writing, software\n ** distributed under the License is distributed on an \"AS IS\" BASIS,\n ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n ** See the License for the specific language governing permissions and\n ** limitations under the License.\n *\n **********************************************************************/\n#include \"mfcpch.h\" //precompiled headers\n#include \n#include \n#include \"strngs.h\"\n#include \"varable.h\"\n#include \"debugwin.h\"\n//#include \"ipeerr.h\"\n#include \"tprintf.h\"\n#include \"ccutil.h\"\n\n#define MAX_MSG_LEN 1024\n\n#define EXTERN\nDLLSYM STRING_VAR (debug_file, \"\", \"File to send tprintf output to\");\nDLLSYM BOOL_VAR (debug_window_on, FALSE,\n\"Send tprintf to window unless file set\");\n\nDLLSYM void\ntprintf ( //Trace printf\nconst char *format, ... //special message\n) {\n tesseract::tprintfMutex.Lock();\n va_list args; //variable args\n static FILE *debugfp = NULL; //debug file\n //debug window\n static DEBUG_WIN *debugwin = NULL;\n inT32 offset = 0; //into message\n static char msg[MAX_MSG_LEN + 1];\n\n va_start(args, format); //variable list\n #ifdef __MSW32__\n //Format into msg\n offset += _vsnprintf (msg + offset, MAX_MSG_LEN - offset, format, args);\n #else\n //Format into msg\n offset += vsprintf (msg + offset, format, args);\n #endif\n va_end(args);\n\n if (debugfp == NULL && strlen (debug_file.string ()) > 0)\n debugfp = fopen (debug_file.string (), \"w\");\n else if (debugfp != NULL && strlen (debug_file.string ()) == 0) {\n fclose(debugfp);\n debugfp = NULL;\n }\n if (debugfp != NULL)\n fprintf (debugfp, \"%s\", msg);\n else {\n\n if (debug_window_on) {\n if (debugwin == NULL)\n //in pixels\n debugwin = new DEBUG_WIN (\"Debug Window\", DEBUG_WIN_XPOS, DEBUG_WIN_YPOS,\n //in pixels\n DEBUG_WIN_XSIZE, DEBUG_WIN_YSIZE,\n debug_lines);\n debugwin->dprintf (msg);\n }\n else {\n fprintf (stderr, \"%s\", msg);\n }\n }\n}\n\n\n/*************************************************************************\n * pause_continue()\n * UI for a debugging pause - to see an intermediate state\n * Returns TRUE to continue as normal to the next pause in the current mode;\n * FALSE to quit the current pausing mode.\n *************************************************************************/\n\nDLLSYM BOOL8\n //special message\npause_continue (const char *format, ...\n) {\n va_list args; //variable args\n char msg[1000];\n STRING str = STRING (\"DEBUG PAUSE:\\n\");\n\n va_start(args, format); //variable list\n vsprintf(msg, format, args); //Format into msg\n va_end(args);\n\n #ifdef GRAPHICS_DISABLED\n // No interaction allowed -> simply go on"} {"commit": "591a18a9c4bf421de05a0eee7e85dea25f64209d", "message": "Backends: SDL2, SDL3: ignore events of other SDL windows. (#7853)", "old_file": "backends/imgui_impl_sdl2.cpp", "new_file": "backends/imgui_impl_sdl2.cpp", "status": "M", "old_contents": " ImGuiIO& io = ImGui::GetIO();\n io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);\n io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);\n io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);\n io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);\n}\n\n// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.\n// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.\n// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.\n// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.\n// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.\nbool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)\n{\n ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();\n IM_ASSERT(bd != nullptr && \"Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?\");\n ImGuiIO& io = ImGui::GetIO();\n\n switch (event->type)\n {\n case SDL_MOUSEMOTION:\n {\n ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);\n io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);\n return true;\n }\n case SDL_MOUSEWHEEL:\n {\n //IMGUI_DEBUG_LOG(\"wheel %.2f %.2f, precise %.2f %.2f\\n\", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);\n#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!\n float wheel_x = -event->wheel.preciseX;\n float wheel_y = event->wheel.preciseY;\n#else\n float wheel_x = -(float)event->wheel.x;\n float wheel_y = (float)event->wheel.y;\n#endif\n#ifdef __EMSCRIPTEN__\n wheel_x /= 100.0f;\n#endif\n io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseWheelEvent(wheel_x, wheel_y);\n return true;\n }\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n int mouse_button = -1;\n if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }\n if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }\n if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }\n if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }\n if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }\n if (mouse_button == -1)\n break;\n io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));\n bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));\n return true;\n }\n case SDL_TEXTINPUT:\n {\n io.AddInputCharactersUTF8(event->text.text);\n return true;\n }\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n {\n ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);\n ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);\n io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));\n io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.\n return true;\n }\n case SDL_WINDOWEVENT:\n {\n // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.\n // - However we won't get a correct LEAVE event for a captured window.\n // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,\n // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why\n // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.\n Uint8 window_event = event->window.event;\n if (window_event == SDL_WINDOWEVENT_ENTER)\n {\n bd->MouseWindowID = event->window.windowID;\n bd->MouseLastLeaveFrame = 0;\n }\n if (window_event == SDL_WINDOWEVENT_LEAVE)\n bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;\n if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)\n io.AddFocusEvent(true);\n else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)\n io.AddFocusEvent(false);\n return true;\n }\n case SDL_CONTROLLERDEVICEADDED:\n case SDL_CONTROLLERDEVICEREMOVED:\n {\n bd->WantUpdateGamepadsList = true;\n return true;", "new_contents": " ImGuiIO& io = ImGui::GetIO();\n io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);\n io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);\n io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);\n io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);\n}\n\n// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.\n// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.\n// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.\n// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.\n// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.\nbool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)\n{\n ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();\n IM_ASSERT(bd != nullptr && \"Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?\");\n ImGuiIO& io = ImGui::GetIO();\n\n switch (event->type)\n {\n case SDL_MOUSEMOTION:\n {\n if (event->motion.windowID != SDL_GetWindowID(bd->Window))\n return false;\n ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);\n io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);\n return true;\n }\n case SDL_MOUSEWHEEL:\n {\n if (event->wheel.windowID != SDL_GetWindowID(bd->Window))\n return false;\n //IMGUI_DEBUG_LOG(\"wheel %.2f %.2f, precise %.2f %.2f\\n\", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);\n#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!\n float wheel_x = -event->wheel.preciseX;\n float wheel_y = event->wheel.preciseY;\n#else\n float wheel_x = -(float)event->wheel.x;\n float wheel_y = (float)event->wheel.y;\n#endif\n#ifdef __EMSCRIPTEN__\n wheel_x /= 100.0f;\n#endif\n io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseWheelEvent(wheel_x, wheel_y);\n return true;\n }\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n if (event->button.windowID != SDL_GetWindowID(bd->Window))\n return false;\n int mouse_button = -1;\n if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }\n if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }\n if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }\n if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }\n if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }\n if (mouse_button == -1)\n break;\n io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));\n bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));\n return true;\n }\n case SDL_TEXTINPUT:\n {\n if (event->text.windowID != SDL_GetWindowID(bd->Window))\n return false;\n io.AddInputCharactersUTF8(event->text.text);\n return true;\n }\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n {\n if (event->key.windowID != SDL_GetWindowID(bd->Window))\n return false;\n ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);\n ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);\n io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));\n io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.\n return true;\n }\n case SDL_WINDOWEVENT:\n {\n if (event->window.windowID != SDL_GetWindowID(bd->Window))\n return false;\n // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.\n // - However we won't get a correct LEAVE event for a captured window.\n // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,\n // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why\n // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.\n Uint8 window_event = event->window.event;\n if (window_event == SDL_WINDOWEVENT_ENTER)\n {\n bd->MouseWindowID = event->window.windowID;\n bd->MouseLastLeaveFrame = 0;\n }\n if (window_event == SDL_WINDOWEVENT_LEAVE)\n bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;\n if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)\n io.AddFocusEvent(true);\n else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)\n io.AddFocusEvent(false);\n return true;\n }\n case SDL_CONTROLLERDEVICEADDED:\n case SDL_CONTROLLERDEVICEREMOVED:\n {\n bd->WantUpdateGamepadsList = true;\n return true;", "current_contents": " ImGuiIO& io = ImGui::GetIO();\n io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);\n io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);\n io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);\n io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);\n}\n\n// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.\n// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.\n// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.\n// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.\n// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.\nbool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)\n{\n ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();\n IM_ASSERT(bd != nullptr && \"Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?\");\n ImGuiIO& io = ImGui::GetIO();\n\n switch (event->type)\n {\n case SDL_MOUSEMOTION:\n {\n if (event->motion.windowID != SDL_GetWindowID(bd->Window))\n return false;\n ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);\n io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);\n return true;\n }\n case SDL_MOUSEWHEEL:\n {\n if (event->wheel.windowID != SDL_GetWindowID(bd->Window))\n return false;\n //IMGUI_DEBUG_LOG(\"wheel %.2f %.2f, precise %.2f %.2f\\n\", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);\n#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!\n float wheel_x = -event->wheel.preciseX;\n float wheel_y = event->wheel.preciseY;\n#else\n float wheel_x = -(float)event->wheel.x;\n float wheel_y = (float)event->wheel.y;\n#endif\n#ifdef __EMSCRIPTEN__\n wheel_x /= 100.0f;\n#endif\n io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseWheelEvent(wheel_x, wheel_y);\n return true;\n }\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n if (event->button.windowID != SDL_GetWindowID(bd->Window))\n return false;\n int mouse_button = -1;\n if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }\n if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }\n if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }\n if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }\n if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }\n if (mouse_button == -1)\n break;\n io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));\n bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));\n return true;\n }\n case SDL_TEXTINPUT:\n {\n if (event->text.windowID != SDL_GetWindowID(bd->Window))\n return false;\n io.AddInputCharactersUTF8(event->text.text);\n return true;\n }\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n {\n if (event->key.windowID != SDL_GetWindowID(bd->Window))\n return false;\n ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);\n ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);\n io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));\n io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.\n return true;\n }\n case SDL_WINDOWEVENT:\n {\n // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.\n // - However we won't get a correct LEAVE event for a captured window.\n // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,\n // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why\n // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.\n Uint8 window_event = event->window.event;\n if (window_event == SDL_WINDOWEVENT_ENTER)\n {\n bd->MouseWindowID = event->window.windowID;\n bd->MouseLastLeaveFrame = 0;\n }\n if (window_event == SDL_WINDOWEVENT_LEAVE)\n bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;\n if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)\n io.AddFocusEvent(true);\n else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)\n io.AddFocusEvent(false);\n return true;\n }\n case SDL_CONTROLLERDEVICEADDED:\n case SDL_CONTROLLERDEVICEREMOVED:\n {\n bd->WantUpdateGamepadsList = true;\n return true;", "text": "<|original_code|>\n ImGuiIO& io = ImGui::GetIO();\n io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);\n io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);\n io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);\n io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);\n}\n\n// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.\n// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.\n// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.\n// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.\n// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.\nbool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)\n{\n ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();\n IM_ASSERT(bd != nullptr && \"Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?\");\n ImGuiIO& io = ImGui::GetIO();\n\n switch (event->type)\n {\n case SDL_MOUSEMOTION:\n {\n ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);\n io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);\n return true;\n }\n case SDL_MOUSEWHEEL:\n {\n //IMGUI_DEBUG_LOG(\"wheel %.2f %.2f, precise %.2f %.2f\\n\", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);\n#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!\n float wheel_x = -event->wheel.preciseX;\n float wheel_y = event->wheel.preciseY;\n#else\n float wheel_x = -(float)event->wheel.x;\n float wheel_y = (float)event->wheel.y;\n#endif\n#ifdef __EMSCRIPTEN__\n wheel_x /= 100.0f;\n#endif\n io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseWheelEvent(wheel_x, wheel_y);\n return true;\n }\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n int mouse_button = -1;\n if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }\n if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }\n if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }\n if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }\n if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }\n if (mouse_button == -1)\n break;\n io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));\n bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));\n return true;\n }\n case SDL_TEXTINPUT:\n {\n io.AddInputCharactersUTF8(event->text.text);\n return true;\n }\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n {\n ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);\n ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);\n io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));\n io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.\n return true;\n }\n case SDL_WINDOWEVENT:\n {\n // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.\n // - However we won't get a correct LEAVE event for a captured window.\n // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,\n // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why\n // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.\n Uint8 window_event = event->window.event;\n if (window_event == SDL_WINDOWEVENT_ENTER)\n {\n bd->MouseWindowID = event->window.windowID;\n bd->MouseLastLeaveFrame = 0;\n }\n if (window_event == SDL_WINDOWEVENT_LEAVE)\n bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;\n if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)\n io.AddFocusEvent(true);\n else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)\n io.AddFocusEvent(false);\n return true;\n }\n case SDL_CONTROLLERDEVICEADDED:\n case SDL_CONTROLLERDEVICEREMOVED:\n {\n bd->WantUpdateGamepadsList = true;\n return true;\n<|edits_diff|>\n--- backends/imgui_impl_sdl2.cpp\n+++ backends/imgui_impl_sdl2.cpp\n@@ -20,6 +20,8 @@\n {\n case SDL_MOUSEMOTION:\n {\n+ if (event->motion.windowID != SDL_GetWindowID(bd->Window))\n+ return false;\n ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);\n io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);\n@@ -27,6 +29,8 @@\n }\n case SDL_MOUSEWHEEL:\n {\n+ if (event->wheel.windowID != SDL_GetWindowID(bd->Window))\n+ return false;\n //IMGUI_DEBUG_LOG(\"wheel %.2f %.2f, precise %.2f %.2f\\n\", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);\n #if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!\n float wheel_x = -event->wheel.preciseX;\n@@ -45,6 +49,8 @@\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n+ if (event->button.windowID != SDL_GetWindowID(bd->Window))\n+ return false;\n int mouse_button = -1;\n if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }\n if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }\n@@ -60,12 +66,16 @@\n }\n case SDL_TEXTINPUT:\n {\n+ if (event->text.windowID != SDL_GetWindowID(bd->Window))\n+ return false;\n io.AddInputCharactersUTF8(event->text.text);\n return true;\n }\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n {\n+ if (event->key.windowID != SDL_GetWindowID(bd->Window))\n+ return false;\n ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);\n ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);\n io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));\n<|current_version|>\n ImGuiIO& io = ImGui::GetIO();\n io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);\n io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);\n io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);\n io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);\n}\n\n// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.\n// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.\n// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.\n// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.\n// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.\nbool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)\n{\n ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();\n IM_ASSERT(bd != nullptr && \"Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?\");\n ImGuiIO& io = ImGui::GetIO();\n\n switch (event->type)\n {\n case SDL_MOUSEMOTION:\n {\n if (event->motion.windowID != SDL_GetWindowID(bd->Window))\n return false;\n ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);\n io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);\n return true;\n }\n case SDL_MOUSEWHEEL:\n {\n if (event->wheel.windowID != SDL_GetWindowID(bd->Window))\n return false;\n //IMGUI_DEBUG_LOG(\"wheel %.2f %.2f, precise %.2f %.2f\\n\", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);\n#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!\n float wheel_x = -event->wheel.preciseX;\n float wheel_y = event->wheel.preciseY;\n#else\n float wheel_x = -(float)event->wheel.x;\n float wheel_y = (float)event->wheel.y;\n#endif\n#ifdef __EMSCRIPTEN__\n wheel_x /= 100.0f;\n#endif\n io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseWheelEvent(wheel_x, wheel_y);\n return true;\n }\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n if (event->button.windowID != SDL_GetWindowID(bd->Window))\n return false;\n int mouse_button = -1;\n if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }\n if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }\n if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }\n if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }\n if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }\n if (mouse_button == -1)\n break;\n io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));\n bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));\n return true;\n }\n case SDL_TEXTINPUT:\n {\n if (event->text.windowID != SDL_GetWindowID(bd->Window))\n return false;\n io.AddInputCharactersUTF8(event->text.text);\n return true;\n }\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n {\n if (event->key.windowID != SDL_GetWindowID(bd->Window))\n return false;\n ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);\n ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);\n io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));\n io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.\n return true;\n }\n case SDL_WINDOWEVENT:\n {\n // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.\n // - However we won't get a correct LEAVE event for a captured window.\n // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,\n // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why\n // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.\n Uint8 window_event = event->window.event;\n if (window_event == SDL_WINDOWEVENT_ENTER)\n {\n bd->MouseWindowID = event->window.windowID;\n bd->MouseLastLeaveFrame = 0;\n }\n if (window_event == SDL_WINDOWEVENT_LEAVE)\n bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;\n if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)\n io.AddFocusEvent(true);\n else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)\n io.AddFocusEvent(false);\n return true;\n }\n case SDL_CONTROLLERDEVICEADDED:\n case SDL_CONTROLLERDEVICEREMOVED:\n {\n bd->WantUpdateGamepadsList = true;\n return true;\n<|next_version|>\n ImGuiIO& io = ImGui::GetIO();\n io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);\n io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);\n io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);\n io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);\n}\n\n// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.\n// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.\n// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.\n// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.\n// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.\nbool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)\n{\n ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();\n IM_ASSERT(bd != nullptr && \"Context or backend not initialized! Did you call ImGui_ImplSDL2_Init()?\");\n ImGuiIO& io = ImGui::GetIO();\n\n switch (event->type)\n {\n case SDL_MOUSEMOTION:\n {\n if (event->motion.windowID != SDL_GetWindowID(bd->Window))\n return false;\n ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);\n io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);\n return true;\n }\n case SDL_MOUSEWHEEL:\n {\n if (event->wheel.windowID != SDL_GetWindowID(bd->Window))\n return false;\n //IMGUI_DEBUG_LOG(\"wheel %.2f %.2f, precise %.2f %.2f\\n\", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);\n#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!\n float wheel_x = -event->wheel.preciseX;\n float wheel_y = event->wheel.preciseY;\n#else\n float wheel_x = -(float)event->wheel.x;\n float wheel_y = (float)event->wheel.y;\n#endif\n#ifdef __EMSCRIPTEN__\n wheel_x /= 100.0f;\n#endif\n io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseWheelEvent(wheel_x, wheel_y);\n return true;\n }\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n {\n if (event->button.windowID != SDL_GetWindowID(bd->Window))\n return false;\n int mouse_button = -1;\n if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }\n if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }\n if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }\n if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }\n if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }\n if (mouse_button == -1)\n break;\n io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);\n io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));\n bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));\n return true;\n }\n case SDL_TEXTINPUT:\n {\n if (event->text.windowID != SDL_GetWindowID(bd->Window))\n return false;\n io.AddInputCharactersUTF8(event->text.text);\n return true;\n }\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n {\n if (event->key.windowID != SDL_GetWindowID(bd->Window))\n return false;\n ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);\n ImGuiKey key = ImGui_ImplSDL2_KeyEventToImGuiKey(event->key.keysym.sym, event->key.keysym.scancode);\n io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));\n io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.\n return true;\n }\n case SDL_WINDOWEVENT:\n {\n if (event->window.windowID != SDL_GetWindowID(bd->Window))\n return false;\n // - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.\n // - However we won't get a correct LEAVE event for a captured window.\n // - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,\n // causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why\n // we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.\n Uint8 window_event = event->window.event;\n if (window_event == SDL_WINDOWEVENT_ENTER)\n {\n bd->MouseWindowID = event->window.windowID;\n bd->MouseLastLeaveFrame = 0;\n }\n if (window_event == SDL_WINDOWEVENT_LEAVE)\n bd->MouseLastLeaveFrame = ImGui::GetFrameCount() + 1;\n if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)\n io.AddFocusEvent(true);\n else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)\n io.AddFocusEvent(false);\n return true;\n }\n case SDL_CONTROLLERDEVICEADDED:\n case SDL_CONTROLLERDEVICEREMOVED:\n {\n bd->WantUpdateGamepadsList = true;\n return true;\n"} {"commit": "a1566c5e1ba22755c359e3079f5f25ab53f1eafb", "message": "Tables: fixed 28a283b breaking PageDown on tables with no interactive items.", "old_file": "imgui_tables.cpp", "new_file": "imgui_tables.cpp", "status": "M", "old_contents": " // Pop from id stack\n IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, \"Mismatching PushID/PopID!\");\n IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, \"Too many PopItemWidth!\");\n if (table->InstanceCurrent > 0)\n PopID();\n PopID();\n\n // Restore window data that we modified\n const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;\n inner_window->WorkRect = temp_data->HostBackupWorkRect;\n inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;\n inner_window->SkipItems = table->HostSkipItems;\n outer_window->DC.CursorPos = table->OuterRect.Min;\n outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;\n outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;\n outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;\n\n // Layout in outer window\n // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding\n // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)\n if (inner_window != outer_window)\n {\n inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.\n EndChild();\n }\n else\n {\n ItemSize(table->OuterRect.GetSize());\n ItemAdd(table->OuterRect, 0);\n }\n\n // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar\n if (table->Flags & ImGuiTableFlags_NoHostExtendX)\n {\n // FIXME-TABLE: Could we remove this section?\n // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents\n IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);\n }\n else if (temp_data->UserOuterSize.x <= 0.0f)\n {\n const float decoration_size = table->TempData->AngledHeadersExtraWidth + ((table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f);\n outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));\n }\n else\n {\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);", "new_contents": " // Pop from id stack\n IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, \"Mismatching PushID/PopID!\");\n IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, \"Too many PopItemWidth!\");\n if (table->InstanceCurrent > 0)\n PopID();\n PopID();\n\n // Restore window data that we modified\n const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;\n inner_window->WorkRect = temp_data->HostBackupWorkRect;\n inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;\n inner_window->SkipItems = table->HostSkipItems;\n outer_window->DC.CursorPos = table->OuterRect.Min;\n outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;\n outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;\n outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;\n\n // Layout in outer window\n // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding\n // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)\n if (inner_window != outer_window)\n {\n short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask;\n inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.\n EndChild();\n inner_window->DC.NavLayersActiveMask = backup_nav_layers_active_mask;\n }\n else\n {\n ItemSize(table->OuterRect.GetSize());\n ItemAdd(table->OuterRect, 0);\n }\n\n // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar\n if (table->Flags & ImGuiTableFlags_NoHostExtendX)\n {\n // FIXME-TABLE: Could we remove this section?\n // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents\n IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);\n }\n else if (temp_data->UserOuterSize.x <= 0.0f)\n {\n const float decoration_size = table->TempData->AngledHeadersExtraWidth + ((table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f);\n outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));\n }\n else\n {\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);", "current_contents": " // Pop from id stack\n IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, \"Mismatching PushID/PopID!\");\n IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, \"Too many PopItemWidth!\");\n if (table->InstanceCurrent > 0)\n PopID();\n PopID();\n\n // Restore window data that we modified\n const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;\n inner_window->WorkRect = temp_data->HostBackupWorkRect;\n inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;\n inner_window->SkipItems = table->HostSkipItems;\n outer_window->DC.CursorPos = table->OuterRect.Min;\n outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;\n outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;\n outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;\n\n // Layout in outer window\n // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding\n // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)\n if (inner_window != outer_window)\n {\n short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask;\n inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.\n EndChild();\n }\n else\n {\n ItemSize(table->OuterRect.GetSize());\n ItemAdd(table->OuterRect, 0);\n }\n\n // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar\n if (table->Flags & ImGuiTableFlags_NoHostExtendX)\n {\n // FIXME-TABLE: Could we remove this section?\n // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents\n IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);\n }\n else if (temp_data->UserOuterSize.x <= 0.0f)\n {\n const float decoration_size = table->TempData->AngledHeadersExtraWidth + ((table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f);\n outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));\n }\n else\n {\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);", "text": "<|original_code|>\n // Pop from id stack\n IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, \"Mismatching PushID/PopID!\");\n IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, \"Too many PopItemWidth!\");\n if (table->InstanceCurrent > 0)\n PopID();\n PopID();\n\n // Restore window data that we modified\n const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;\n inner_window->WorkRect = temp_data->HostBackupWorkRect;\n inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;\n inner_window->SkipItems = table->HostSkipItems;\n outer_window->DC.CursorPos = table->OuterRect.Min;\n outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;\n outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;\n outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;\n\n // Layout in outer window\n // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding\n // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)\n if (inner_window != outer_window)\n {\n inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.\n EndChild();\n }\n else\n {\n ItemSize(table->OuterRect.GetSize());\n ItemAdd(table->OuterRect, 0);\n }\n\n // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar\n if (table->Flags & ImGuiTableFlags_NoHostExtendX)\n {\n // FIXME-TABLE: Could we remove this section?\n // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents\n IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);\n }\n else if (temp_data->UserOuterSize.x <= 0.0f)\n {\n const float decoration_size = table->TempData->AngledHeadersExtraWidth + ((table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f);\n outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));\n }\n else\n {\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);\n<|edits_diff|>\n--- imgui_tables.cpp\n+++ imgui_tables.cpp\n@@ -20,6 +20,7 @@\n // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)\n if (inner_window != outer_window)\n {\n+ short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask;\n inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.\n EndChild();\n }\n<|current_version|>\n // Pop from id stack\n IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, \"Mismatching PushID/PopID!\");\n IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, \"Too many PopItemWidth!\");\n if (table->InstanceCurrent > 0)\n PopID();\n PopID();\n\n // Restore window data that we modified\n const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;\n inner_window->WorkRect = temp_data->HostBackupWorkRect;\n inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;\n inner_window->SkipItems = table->HostSkipItems;\n outer_window->DC.CursorPos = table->OuterRect.Min;\n outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;\n outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;\n outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;\n\n // Layout in outer window\n // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding\n // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)\n if (inner_window != outer_window)\n {\n short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask;\n inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.\n EndChild();\n }\n else\n {\n ItemSize(table->OuterRect.GetSize());\n ItemAdd(table->OuterRect, 0);\n }\n\n // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar\n if (table->Flags & ImGuiTableFlags_NoHostExtendX)\n {\n // FIXME-TABLE: Could we remove this section?\n // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents\n IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);\n }\n else if (temp_data->UserOuterSize.x <= 0.0f)\n {\n const float decoration_size = table->TempData->AngledHeadersExtraWidth + ((table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f);\n outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));\n }\n else\n {\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);\n<|next_version|>\n // Pop from id stack\n IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table_instance->TableInstanceID, \"Mismatching PushID/PopID!\");\n IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, \"Too many PopItemWidth!\");\n if (table->InstanceCurrent > 0)\n PopID();\n PopID();\n\n // Restore window data that we modified\n const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;\n inner_window->WorkRect = temp_data->HostBackupWorkRect;\n inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;\n inner_window->SkipItems = table->HostSkipItems;\n outer_window->DC.CursorPos = table->OuterRect.Min;\n outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;\n outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;\n outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;\n\n // Layout in outer window\n // (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding\n // CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)\n if (inner_window != outer_window)\n {\n short backup_nav_layers_active_mask = inner_window->DC.NavLayersActiveMask;\n inner_window->DC.NavLayersActiveMask |= 1 << ImGuiNavLayer_Main; // So empty table don't appear to navigate differently.\n EndChild();\n inner_window->DC.NavLayersActiveMask = backup_nav_layers_active_mask;\n }\n else\n {\n ItemSize(table->OuterRect.GetSize());\n ItemAdd(table->OuterRect, 0);\n }\n\n // Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar\n if (table->Flags & ImGuiTableFlags_NoHostExtendX)\n {\n // FIXME-TABLE: Could we remove this section?\n // ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents\n IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);\n }\n else if (temp_data->UserOuterSize.x <= 0.0f)\n {\n const float decoration_size = table->TempData->AngledHeadersExtraWidth + ((table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f);\n outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));\n }\n else\n {\n outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);\n"} {"commit": "6656553fa493b87b5780132a7a4cb01e80b4e996", "message": "Nav: Record/restore preferred position on each given axis.", "old_file": "imgui_widgets.cpp", "new_file": "imgui_widgets.cpp", "status": "M", "old_contents": " bool toggled = false;\n if (!is_leaf)\n {\n if (pressed && g.DragDropHoldJustPressedId != id)\n {\n if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id))\n toggled = true;\n if (flags & ImGuiTreeNodeFlags_OpenOnArrow)\n toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job\n if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)\n toggled = true;\n }\n else if (pressed && g.DragDropHoldJustPressedId == id)\n {\n IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);\n if (!is_open) // When using Drag and Drop \"hold to open\" we keep the node highlighted after opening, but never close it again.\n toggled = true;\n }\n\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)\n {\n toggled = true;\n NavMoveRequestCancel();\n }\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?\n {\n toggled = true;\n NavMoveRequestCancel();\n }\n\n if (toggled)\n {\n is_open = !is_open;\n window->DC.StateStorage->SetInt(id, is_open);\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;\n }\n }\n if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n const ImU32 text_col = GetColorU32(ImGuiCol_Text);\n ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;\n if (display_frame)\n {\n // Framed type\n const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);", "new_contents": " bool toggled = false;\n if (!is_leaf)\n {\n if (pressed && g.DragDropHoldJustPressedId != id)\n {\n if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id))\n toggled = true;\n if (flags & ImGuiTreeNodeFlags_OpenOnArrow)\n toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job\n if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)\n toggled = true;\n }\n else if (pressed && g.DragDropHoldJustPressedId == id)\n {\n IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);\n if (!is_open) // When using Drag and Drop \"hold to open\" we keep the node highlighted after opening, but never close it again.\n toggled = true;\n }\n\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)\n {\n toggled = true;\n NavClearPreferredPosForAxis(ImGuiAxis_X);\n NavMoveRequestCancel();\n }\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?\n {\n toggled = true;\n NavClearPreferredPosForAxis(ImGuiAxis_X);\n NavMoveRequestCancel();\n }\n\n if (toggled)\n {\n is_open = !is_open;\n window->DC.StateStorage->SetInt(id, is_open);\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;\n }\n }\n if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n const ImU32 text_col = GetColorU32(ImGuiCol_Text);\n ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;\n if (display_frame)\n {\n // Framed type\n const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);", "current_contents": " bool toggled = false;\n if (!is_leaf)\n {\n if (pressed && g.DragDropHoldJustPressedId != id)\n {\n if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id))\n toggled = true;\n if (flags & ImGuiTreeNodeFlags_OpenOnArrow)\n toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job\n if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)\n toggled = true;\n }\n else if (pressed && g.DragDropHoldJustPressedId == id)\n {\n IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);\n if (!is_open) // When using Drag and Drop \"hold to open\" we keep the node highlighted after opening, but never close it again.\n toggled = true;\n }\n\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)\n {\n toggled = true;\n NavClearPreferredPosForAxis(ImGuiAxis_X);\n NavMoveRequestCancel();\n }\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?\n {\n toggled = true;\n NavMoveRequestCancel();\n }\n\n if (toggled)\n {\n is_open = !is_open;\n window->DC.StateStorage->SetInt(id, is_open);\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;\n }\n }\n if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n const ImU32 text_col = GetColorU32(ImGuiCol_Text);\n ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;\n if (display_frame)\n {\n // Framed type\n const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);", "text": "<|original_code|>\n bool toggled = false;\n if (!is_leaf)\n {\n if (pressed && g.DragDropHoldJustPressedId != id)\n {\n if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id))\n toggled = true;\n if (flags & ImGuiTreeNodeFlags_OpenOnArrow)\n toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job\n if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)\n toggled = true;\n }\n else if (pressed && g.DragDropHoldJustPressedId == id)\n {\n IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);\n if (!is_open) // When using Drag and Drop \"hold to open\" we keep the node highlighted after opening, but never close it again.\n toggled = true;\n }\n\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)\n {\n toggled = true;\n NavMoveRequestCancel();\n }\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?\n {\n toggled = true;\n NavMoveRequestCancel();\n }\n\n if (toggled)\n {\n is_open = !is_open;\n window->DC.StateStorage->SetInt(id, is_open);\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;\n }\n }\n if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n const ImU32 text_col = GetColorU32(ImGuiCol_Text);\n ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;\n if (display_frame)\n {\n // Framed type\n const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n<|edits_diff|>\n--- imgui_widgets.cpp\n+++ imgui_widgets.cpp\n@@ -20,6 +20,7 @@\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)\n {\n toggled = true;\n+ NavClearPreferredPosForAxis(ImGuiAxis_X);\n NavMoveRequestCancel();\n }\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?\n<|current_version|>\n bool toggled = false;\n if (!is_leaf)\n {\n if (pressed && g.DragDropHoldJustPressedId != id)\n {\n if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id))\n toggled = true;\n if (flags & ImGuiTreeNodeFlags_OpenOnArrow)\n toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job\n if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)\n toggled = true;\n }\n else if (pressed && g.DragDropHoldJustPressedId == id)\n {\n IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);\n if (!is_open) // When using Drag and Drop \"hold to open\" we keep the node highlighted after opening, but never close it again.\n toggled = true;\n }\n\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)\n {\n toggled = true;\n NavClearPreferredPosForAxis(ImGuiAxis_X);\n NavMoveRequestCancel();\n }\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?\n {\n toggled = true;\n NavMoveRequestCancel();\n }\n\n if (toggled)\n {\n is_open = !is_open;\n window->DC.StateStorage->SetInt(id, is_open);\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;\n }\n }\n if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n const ImU32 text_col = GetColorU32(ImGuiCol_Text);\n ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;\n if (display_frame)\n {\n // Framed type\n const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n<|next_version|>\n bool toggled = false;\n if (!is_leaf)\n {\n if (pressed && g.DragDropHoldJustPressedId != id)\n {\n if ((flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) == 0 || (g.NavActivateId == id))\n toggled = true;\n if (flags & ImGuiTreeNodeFlags_OpenOnArrow)\n toggled |= is_mouse_x_over_arrow && !g.NavDisableMouseHover; // Lightweight equivalent of IsMouseHoveringRect() since ButtonBehavior() already did the job\n if ((flags & ImGuiTreeNodeFlags_OpenOnDoubleClick) && g.IO.MouseClickedCount[0] == 2)\n toggled = true;\n }\n else if (pressed && g.DragDropHoldJustPressedId == id)\n {\n IM_ASSERT(button_flags & ImGuiButtonFlags_PressedOnDragDropHold);\n if (!is_open) // When using Drag and Drop \"hold to open\" we keep the node highlighted after opening, but never close it again.\n toggled = true;\n }\n\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Left && is_open)\n {\n toggled = true;\n NavClearPreferredPosForAxis(ImGuiAxis_X);\n NavMoveRequestCancel();\n }\n if (g.NavId == id && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?\n {\n toggled = true;\n NavClearPreferredPosForAxis(ImGuiAxis_X);\n NavMoveRequestCancel();\n }\n\n if (toggled)\n {\n is_open = !is_open;\n window->DC.StateStorage->SetInt(id, is_open);\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledOpen;\n }\n }\n if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, TreeNodeBehavior() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n g.LastItemData.StatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n const ImU32 text_col = GetColorU32(ImGuiCol_Text);\n ImGuiNavHighlightFlags nav_highlight_flags = ImGuiNavHighlightFlags_TypeThin;\n if (display_frame)\n {\n // Framed type\n const ImU32 bg_col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n"} {"commit": "612b787b0d594d878117fe05732eee8e01e45cff", "message": "Menus: fixed top-level menu from not consistently using style.PopupRounding. (#4788)", "old_file": "imgui_widgets.cpp", "new_file": "imgui_widgets.cpp", "status": "M", "old_contents": " if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu(\"options\", has_object)) { ..use object.. }'\n want_close = true;\n if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))\n ClosePopupToLevel(g.BeginPopupStack.Size, true);\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));\n PopID();\n\n if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)\n {\n // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.\n OpenPopup(label);\n return false;\n }\n\n menu_is_open |= want_open;\n if (want_open)\n OpenPopup(label);\n\n if (menu_is_open)\n {\n SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos.\n menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\n }\n else\n {\n g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\n }\n\n return menu_is_open;\n}\n\nbool ImGui::BeginMenu(const char* label, bool enabled)\n{\n return BeginMenuEx(label, NULL, enabled);\n}\n\nvoid ImGui::EndMenu()\n{\n // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).\n // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.\n // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.\n ImGuiContext& g = *GImGui;\n ImGuiWindow* window = g.CurrentWindow;\n if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)\n if (g.NavWindow && (g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow == window)\n {", "new_contents": " if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu(\"options\", has_object)) { ..use object.. }'\n want_close = true;\n if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))\n ClosePopupToLevel(g.BeginPopupStack.Size, true);\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));\n PopID();\n\n if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)\n {\n // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.\n OpenPopup(label);\n return false;\n }\n\n menu_is_open |= want_open;\n if (want_open)\n OpenPopup(label);\n\n if (menu_is_open)\n {\n SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos.\n PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding\n menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\n PopStyleVar();\n }\n else\n {\n g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\n }\n\n return menu_is_open;\n}\n\nbool ImGui::BeginMenu(const char* label, bool enabled)\n{\n return BeginMenuEx(label, NULL, enabled);\n}\n\nvoid ImGui::EndMenu()\n{\n // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).\n // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.\n // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.\n ImGuiContext& g = *GImGui;\n ImGuiWindow* window = g.CurrentWindow;\n if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)\n if (g.NavWindow && (g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow == window)\n {", "current_contents": " if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu(\"options\", has_object)) { ..use object.. }'\n want_close = true;\n if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))\n ClosePopupToLevel(g.BeginPopupStack.Size, true);\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));\n PopID();\n\n if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)\n {\n // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.\n OpenPopup(label);\n return false;\n }\n\n menu_is_open |= want_open;\n if (want_open)\n OpenPopup(label);\n\n if (menu_is_open)\n {\n SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos.\n PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding\n menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\n }\n else\n {\n g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\n }\n\n return menu_is_open;\n}\n\nbool ImGui::BeginMenu(const char* label, bool enabled)\n{\n return BeginMenuEx(label, NULL, enabled);\n}\n\nvoid ImGui::EndMenu()\n{\n // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).\n // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.\n // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.\n ImGuiContext& g = *GImGui;\n ImGuiWindow* window = g.CurrentWindow;\n if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)\n if (g.NavWindow && (g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow == window)\n {", "text": "<|original_code|>\n if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu(\"options\", has_object)) { ..use object.. }'\n want_close = true;\n if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))\n ClosePopupToLevel(g.BeginPopupStack.Size, true);\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));\n PopID();\n\n if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)\n {\n // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.\n OpenPopup(label);\n return false;\n }\n\n menu_is_open |= want_open;\n if (want_open)\n OpenPopup(label);\n\n if (menu_is_open)\n {\n SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos.\n menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\n }\n else\n {\n g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\n }\n\n return menu_is_open;\n}\n\nbool ImGui::BeginMenu(const char* label, bool enabled)\n{\n return BeginMenuEx(label, NULL, enabled);\n}\n\nvoid ImGui::EndMenu()\n{\n // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).\n // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.\n // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.\n ImGuiContext& g = *GImGui;\n ImGuiWindow* window = g.CurrentWindow;\n if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)\n if (g.NavWindow && (g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow == window)\n {\n<|edits_diff|>\n--- imgui_widgets.cpp\n+++ imgui_widgets.cpp\n@@ -20,6 +20,7 @@\n if (menu_is_open)\n {\n SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos.\n+ PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding\n menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\n }\n else\n<|current_version|>\n if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu(\"options\", has_object)) { ..use object.. }'\n want_close = true;\n if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))\n ClosePopupToLevel(g.BeginPopupStack.Size, true);\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));\n PopID();\n\n if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)\n {\n // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.\n OpenPopup(label);\n return false;\n }\n\n menu_is_open |= want_open;\n if (want_open)\n OpenPopup(label);\n\n if (menu_is_open)\n {\n SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos.\n PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding\n menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\n }\n else\n {\n g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\n }\n\n return menu_is_open;\n}\n\nbool ImGui::BeginMenu(const char* label, bool enabled)\n{\n return BeginMenuEx(label, NULL, enabled);\n}\n\nvoid ImGui::EndMenu()\n{\n // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).\n // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.\n // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.\n ImGuiContext& g = *GImGui;\n ImGuiWindow* window = g.CurrentWindow;\n if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)\n if (g.NavWindow && (g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow == window)\n {\n<|next_version|>\n if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu(\"options\", has_object)) { ..use object.. }'\n want_close = true;\n if (want_close && IsPopupOpen(id, ImGuiPopupFlags_None))\n ClosePopupToLevel(g.BeginPopupStack.Size, true);\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, g.LastItemData.StatusFlags | ImGuiItemStatusFlags_Openable | (menu_is_open ? ImGuiItemStatusFlags_Opened : 0));\n PopID();\n\n if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.BeginPopupStack.Size)\n {\n // Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.\n OpenPopup(label);\n return false;\n }\n\n menu_is_open |= want_open;\n if (want_open)\n OpenPopup(label);\n\n if (menu_is_open)\n {\n SetNextWindowPos(popup_pos, ImGuiCond_Always); // Note: this is super misleading! The value will serve as reference for FindBestWindowPosForPopup(), not actual pos.\n PushStyleVar(ImGuiStyleVar_ChildRounding, style.PopupRounding); // First level will use _PopupRounding, subsequent will use _ChildRounding\n menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)\n PopStyleVar();\n }\n else\n {\n g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values\n }\n\n return menu_is_open;\n}\n\nbool ImGui::BeginMenu(const char* label, bool enabled)\n{\n return BeginMenuEx(label, NULL, enabled);\n}\n\nvoid ImGui::EndMenu()\n{\n // Nav: When a left move request _within our child menu_ failed, close ourselves (the _parent_ menu).\n // A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.\n // However, it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.\n ImGuiContext& g = *GImGui;\n ImGuiWindow* window = g.CurrentWindow;\n if (g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)\n if (g.NavWindow && (g.NavWindow->RootWindowForNav->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->RootWindowForNav->ParentWindow == window)\n {\n"} {"commit": "8da7d3c3e5cd428b4dd7cf277af05c0d889439b7", "message": "Tables: Initial commit. [Squashed 123+5 commits from tables_wip/]", "old_file": "imgui_widgets.cpp", "new_file": "imgui_widgets.cpp", "status": "M", "old_contents": " window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;\n item_add = ItemAdd(bb, id);\n window->DC.ItemFlags = backup_item_flags;\n }\n else\n {\n item_add = ItemAdd(bb, id);\n }\n\n if (span_all_columns)\n {\n window->ClipRect.Min.x = backup_clip_rect_min_x;\n window->ClipRect.Max.x = backup_clip_rect_max_x;\n }\n\n if (!item_add)\n return false;\n\n // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,\n // which would be advantageous since most selectable are not selected.\n if (span_all_columns && window->DC.CurrentColumns)\n PushColumnsBackground();\n\n // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries\n ImGuiButtonFlags button_flags = 0;\n if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }\n if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }\n if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }\n if (flags & ImGuiSelectableFlags_Disabled) { button_flags |= ImGuiButtonFlags_Disabled; }\n if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }\n if (flags & ImGuiSelectableFlags_AllowItemOverlap) { button_flags |= ImGuiButtonFlags_AllowItemOverlap; }\n\n if (flags & ImGuiSelectableFlags_Disabled)\n selected = false;\n\n const bool was_selected = selected;\n bool hovered, held;\n bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);\n\n // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard\n if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))\n {\n if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)\n {\n g.NavDisableHighlight = true;\n SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent);\n }\n }\n if (pressed)\n MarkItemEdited(id);\n\n if (flags & ImGuiSelectableFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, Selectable() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))\n hovered = true;\n if (hovered || selected)\n {\n const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n RenderFrame(bb.Min, bb.Max, col, false, 0.0f);\n RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);\n }\n\n if (span_all_columns && window->DC.CurrentColumns)\n PopColumnsBackground();\n\n if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);\n RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);\n if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();\n\n // Automatically close popups\n if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))\n CloseCurrentPopup();\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);\n return pressed;\n}\n\nbool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)\n{\n if (Selectable(label, *p_selected, flags, size_arg))\n {\n *p_selected = !*p_selected;\n return true;\n }\n return false;\n}\n\n//-------------------------------------------------------------------------", "new_contents": " window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;\n item_add = ItemAdd(bb, id);\n window->DC.ItemFlags = backup_item_flags;\n }\n else\n {\n item_add = ItemAdd(bb, id);\n }\n\n if (span_all_columns)\n {\n window->ClipRect.Min.x = backup_clip_rect_min_x;\n window->ClipRect.Max.x = backup_clip_rect_max_x;\n }\n\n if (!item_add)\n return false;\n\n // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,\n // which would be advantageous since most selectable are not selected.\n if (span_all_columns && window->DC.CurrentColumns)\n PushColumnsBackground();\n else if ((flags & ImGuiSelectableFlags_SpanAllColumns) && g.CurrentTable)\n PushTableBackground();\n\n // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries\n ImGuiButtonFlags button_flags = 0;\n if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }\n if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }\n if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }\n if (flags & ImGuiSelectableFlags_Disabled) { button_flags |= ImGuiButtonFlags_Disabled; }\n if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }\n if (flags & ImGuiSelectableFlags_AllowItemOverlap) { button_flags |= ImGuiButtonFlags_AllowItemOverlap; }\n\n if (flags & ImGuiSelectableFlags_Disabled)\n selected = false;\n\n const bool was_selected = selected;\n bool hovered, held;\n bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);\n\n // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard\n if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))\n {\n if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)\n {\n g.NavDisableHighlight = true;\n SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent);\n }\n }\n if (pressed)\n MarkItemEdited(id);\n\n if (flags & ImGuiSelectableFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, Selectable() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))\n hovered = true;\n if (hovered || selected)\n {\n const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n RenderFrame(bb.Min, bb.Max, col, false, 0.0f);\n RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);\n }\n\n if (span_all_columns && window->DC.CurrentColumns)\n PopColumnsBackground();\n else if (span_all_columns && g.CurrentTable)\n PopTableBackground();\n\n if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);\n RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);\n if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();\n\n // Automatically close popups\n if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))\n CloseCurrentPopup();\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);\n return pressed;\n}\n\nbool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)\n{\n if (Selectable(label, *p_selected, flags, size_arg))\n {\n *p_selected = !*p_selected;\n return true;\n }\n return false;\n}\n\n//-------------------------------------------------------------------------", "current_contents": " window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;\n item_add = ItemAdd(bb, id);\n window->DC.ItemFlags = backup_item_flags;\n }\n else\n {\n item_add = ItemAdd(bb, id);\n }\n\n if (span_all_columns)\n {\n window->ClipRect.Min.x = backup_clip_rect_min_x;\n window->ClipRect.Max.x = backup_clip_rect_max_x;\n }\n\n if (!item_add)\n return false;\n\n // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,\n // which would be advantageous since most selectable are not selected.\n if (span_all_columns && window->DC.CurrentColumns)\n PushColumnsBackground();\n else if ((flags & ImGuiSelectableFlags_SpanAllColumns) && g.CurrentTable)\n PushTableBackground();\n\n // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries\n ImGuiButtonFlags button_flags = 0;\n if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }\n if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }\n if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }\n if (flags & ImGuiSelectableFlags_Disabled) { button_flags |= ImGuiButtonFlags_Disabled; }\n if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }\n if (flags & ImGuiSelectableFlags_AllowItemOverlap) { button_flags |= ImGuiButtonFlags_AllowItemOverlap; }\n\n if (flags & ImGuiSelectableFlags_Disabled)\n selected = false;\n\n const bool was_selected = selected;\n bool hovered, held;\n bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);\n\n // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard\n if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))\n {\n if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)\n {\n g.NavDisableHighlight = true;\n SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent);\n }\n }\n if (pressed)\n MarkItemEdited(id);\n\n if (flags & ImGuiSelectableFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, Selectable() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))\n hovered = true;\n if (hovered || selected)\n {\n const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n RenderFrame(bb.Min, bb.Max, col, false, 0.0f);\n RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);\n }\n\n if (span_all_columns && window->DC.CurrentColumns)\n PopColumnsBackground();\n\n if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);\n RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);\n if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();\n\n // Automatically close popups\n if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))\n CloseCurrentPopup();\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);\n return pressed;\n}\n\nbool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)\n{\n if (Selectable(label, *p_selected, flags, size_arg))\n {\n *p_selected = !*p_selected;\n return true;\n }\n return false;\n}\n\n//-------------------------------------------------------------------------", "text": "<|original_code|>\n window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;\n item_add = ItemAdd(bb, id);\n window->DC.ItemFlags = backup_item_flags;\n }\n else\n {\n item_add = ItemAdd(bb, id);\n }\n\n if (span_all_columns)\n {\n window->ClipRect.Min.x = backup_clip_rect_min_x;\n window->ClipRect.Max.x = backup_clip_rect_max_x;\n }\n\n if (!item_add)\n return false;\n\n // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,\n // which would be advantageous since most selectable are not selected.\n if (span_all_columns && window->DC.CurrentColumns)\n PushColumnsBackground();\n\n // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries\n ImGuiButtonFlags button_flags = 0;\n if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }\n if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }\n if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }\n if (flags & ImGuiSelectableFlags_Disabled) { button_flags |= ImGuiButtonFlags_Disabled; }\n if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }\n if (flags & ImGuiSelectableFlags_AllowItemOverlap) { button_flags |= ImGuiButtonFlags_AllowItemOverlap; }\n\n if (flags & ImGuiSelectableFlags_Disabled)\n selected = false;\n\n const bool was_selected = selected;\n bool hovered, held;\n bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);\n\n // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard\n if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))\n {\n if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)\n {\n g.NavDisableHighlight = true;\n SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent);\n }\n }\n if (pressed)\n MarkItemEdited(id);\n\n if (flags & ImGuiSelectableFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, Selectable() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))\n hovered = true;\n if (hovered || selected)\n {\n const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n RenderFrame(bb.Min, bb.Max, col, false, 0.0f);\n RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);\n }\n\n if (span_all_columns && window->DC.CurrentColumns)\n PopColumnsBackground();\n\n if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);\n RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);\n if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();\n\n // Automatically close popups\n if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))\n CloseCurrentPopup();\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);\n return pressed;\n}\n\nbool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)\n{\n if (Selectable(label, *p_selected, flags, size_arg))\n {\n *p_selected = !*p_selected;\n return true;\n }\n return false;\n}\n\n//-------------------------------------------------------------------------\n<|edits_diff|>\n--- imgui_widgets.cpp\n+++ imgui_widgets.cpp\n@@ -20,6 +20,8 @@\n // which would be advantageous since most selectable are not selected.\n if (span_all_columns && window->DC.CurrentColumns)\n PushColumnsBackground();\n+ else if ((flags & ImGuiSelectableFlags_SpanAllColumns) && g.CurrentTable)\n+ PushTableBackground();\n \n // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries\n ImGuiButtonFlags button_flags = 0;\n<|current_version|>\n window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;\n item_add = ItemAdd(bb, id);\n window->DC.ItemFlags = backup_item_flags;\n }\n else\n {\n item_add = ItemAdd(bb, id);\n }\n\n if (span_all_columns)\n {\n window->ClipRect.Min.x = backup_clip_rect_min_x;\n window->ClipRect.Max.x = backup_clip_rect_max_x;\n }\n\n if (!item_add)\n return false;\n\n // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,\n // which would be advantageous since most selectable are not selected.\n if (span_all_columns && window->DC.CurrentColumns)\n PushColumnsBackground();\n else if ((flags & ImGuiSelectableFlags_SpanAllColumns) && g.CurrentTable)\n PushTableBackground();\n\n // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries\n ImGuiButtonFlags button_flags = 0;\n if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }\n if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }\n if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }\n if (flags & ImGuiSelectableFlags_Disabled) { button_flags |= ImGuiButtonFlags_Disabled; }\n if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }\n if (flags & ImGuiSelectableFlags_AllowItemOverlap) { button_flags |= ImGuiButtonFlags_AllowItemOverlap; }\n\n if (flags & ImGuiSelectableFlags_Disabled)\n selected = false;\n\n const bool was_selected = selected;\n bool hovered, held;\n bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);\n\n // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard\n if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))\n {\n if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)\n {\n g.NavDisableHighlight = true;\n SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent);\n }\n }\n if (pressed)\n MarkItemEdited(id);\n\n if (flags & ImGuiSelectableFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, Selectable() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))\n hovered = true;\n if (hovered || selected)\n {\n const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n RenderFrame(bb.Min, bb.Max, col, false, 0.0f);\n RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);\n }\n\n if (span_all_columns && window->DC.CurrentColumns)\n PopColumnsBackground();\n\n if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);\n RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);\n if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();\n\n // Automatically close popups\n if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))\n CloseCurrentPopup();\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);\n return pressed;\n}\n\nbool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)\n{\n if (Selectable(label, *p_selected, flags, size_arg))\n {\n *p_selected = !*p_selected;\n return true;\n }\n return false;\n}\n\n//-------------------------------------------------------------------------\n<|next_version|>\n window->DC.ItemFlags |= ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNavDefaultFocus;\n item_add = ItemAdd(bb, id);\n window->DC.ItemFlags = backup_item_flags;\n }\n else\n {\n item_add = ItemAdd(bb, id);\n }\n\n if (span_all_columns)\n {\n window->ClipRect.Min.x = backup_clip_rect_min_x;\n window->ClipRect.Max.x = backup_clip_rect_max_x;\n }\n\n if (!item_add)\n return false;\n\n // FIXME: We can standardize the behavior of those two, we could also keep the fast path of override ClipRect + full push on render only,\n // which would be advantageous since most selectable are not selected.\n if (span_all_columns && window->DC.CurrentColumns)\n PushColumnsBackground();\n else if ((flags & ImGuiSelectableFlags_SpanAllColumns) && g.CurrentTable)\n PushTableBackground();\n\n // We use NoHoldingActiveID on menus so user can click and _hold_ on a menu then drag to browse child entries\n ImGuiButtonFlags button_flags = 0;\n if (flags & ImGuiSelectableFlags_NoHoldingActiveID) { button_flags |= ImGuiButtonFlags_NoHoldingActiveId; }\n if (flags & ImGuiSelectableFlags_SelectOnClick) { button_flags |= ImGuiButtonFlags_PressedOnClick; }\n if (flags & ImGuiSelectableFlags_SelectOnRelease) { button_flags |= ImGuiButtonFlags_PressedOnRelease; }\n if (flags & ImGuiSelectableFlags_Disabled) { button_flags |= ImGuiButtonFlags_Disabled; }\n if (flags & ImGuiSelectableFlags_AllowDoubleClick) { button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick; }\n if (flags & ImGuiSelectableFlags_AllowItemOverlap) { button_flags |= ImGuiButtonFlags_AllowItemOverlap; }\n\n if (flags & ImGuiSelectableFlags_Disabled)\n selected = false;\n\n const bool was_selected = selected;\n bool hovered, held;\n bool pressed = ButtonBehavior(bb, id, &hovered, &held, button_flags);\n\n // Update NavId when clicking or when Hovering (this doesn't happen on most widgets), so navigation can be resumed with gamepad/keyboard\n if (pressed || (hovered && (flags & ImGuiSelectableFlags_SetNavIdOnHover)))\n {\n if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerCurrent)\n {\n g.NavDisableHighlight = true;\n SetNavID(id, window->DC.NavLayerCurrent, window->DC.NavFocusScopeIdCurrent);\n }\n }\n if (pressed)\n MarkItemEdited(id);\n\n if (flags & ImGuiSelectableFlags_AllowItemOverlap)\n SetItemAllowOverlap();\n\n // In this branch, Selectable() cannot toggle the selection so this will never trigger.\n if (selected != was_selected) //-V547\n window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_ToggledSelection;\n\n // Render\n if (held && (flags & ImGuiSelectableFlags_DrawHoveredWhenHeld))\n hovered = true;\n if (hovered || selected)\n {\n const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);\n RenderFrame(bb.Min, bb.Max, col, false, 0.0f);\n RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);\n }\n\n if (span_all_columns && window->DC.CurrentColumns)\n PopColumnsBackground();\n else if (span_all_columns && g.CurrentTable)\n PopTableBackground();\n\n if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_TextDisabled]);\n RenderTextClipped(text_min, text_max, label, NULL, &label_size, style.SelectableTextAlign, &bb);\n if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();\n\n // Automatically close popups\n if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))\n CloseCurrentPopup();\n\n IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.ItemFlags);\n return pressed;\n}\n\nbool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)\n{\n if (Selectable(label, *p_selected, flags, size_arg))\n {\n *p_selected = !*p_selected;\n return true;\n }\n return false;\n}\n\n//-------------------------------------------------------------------------\n"} {"commit": "945a5097734265baf4db188fb9dfa2093733bb91", "message": "Implement ImGuiMouseCursor_NotAllowed mouse cursor.", "old_file": "examples/imgui_impl_glfw.cpp", "new_file": "examples/imgui_impl_glfw.cpp", "status": "M", "old_contents": " io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;\n io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;\n io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;\n io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;\n io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;\n\n io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;\n io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;\n io.ClipboardUserData = g_Window;\n#if defined(_WIN32)\n io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);\n#endif\n\n g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);\n#if GLFW_HAS_NEW_CURSORS\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);\n#else\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n#endif\n\n // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.\n g_PrevUserCallbackMousebutton = NULL;\n g_PrevUserCallbackScroll = NULL;\n g_PrevUserCallbackKey = NULL;\n g_PrevUserCallbackChar = NULL;\n if (install_callbacks)\n {\n g_InstalledCallbacks = true;\n g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);\n g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);\n g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);\n g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);\n }\n\n g_ClientApi = client_api;\n return true;\n}\n\nbool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)\n{\n return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);\n}", "new_contents": " io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;\n io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;\n io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;\n io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;\n io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;\n\n io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;\n io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;\n io.ClipboardUserData = g_Window;\n#if defined(_WIN32)\n io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);\n#endif\n\n g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);\n#if GLFW_HAS_NEW_CURSORS\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);\n#else\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n#endif\n\n // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.\n g_PrevUserCallbackMousebutton = NULL;\n g_PrevUserCallbackScroll = NULL;\n g_PrevUserCallbackKey = NULL;\n g_PrevUserCallbackChar = NULL;\n if (install_callbacks)\n {\n g_InstalledCallbacks = true;\n g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);\n g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);\n g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);\n g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);\n }\n\n g_ClientApi = client_api;\n return true;\n}\n\nbool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)\n{\n return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);\n}", "current_contents": " io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;\n io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;\n io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;\n io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;\n io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;\n\n io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;\n io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;\n io.ClipboardUserData = g_Window;\n#if defined(_WIN32)\n io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);\n#endif\n\n g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);\n#if GLFW_HAS_NEW_CURSORS\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);\n#else\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n#endif\n\n // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.\n g_PrevUserCallbackMousebutton = NULL;\n g_PrevUserCallbackScroll = NULL;\n g_PrevUserCallbackKey = NULL;\n g_PrevUserCallbackChar = NULL;\n if (install_callbacks)\n {\n g_InstalledCallbacks = true;\n g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);\n g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);\n g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);\n g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);\n }\n\n g_ClientApi = client_api;\n return true;\n}\n\nbool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)\n{\n return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);\n}", "text": "<|original_code|>\n io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;\n io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;\n io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;\n io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;\n io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;\n\n io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;\n io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;\n io.ClipboardUserData = g_Window;\n#if defined(_WIN32)\n io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);\n#endif\n\n g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);\n#if GLFW_HAS_NEW_CURSORS\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);\n#else\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n#endif\n\n // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.\n g_PrevUserCallbackMousebutton = NULL;\n g_PrevUserCallbackScroll = NULL;\n g_PrevUserCallbackKey = NULL;\n g_PrevUserCallbackChar = NULL;\n if (install_callbacks)\n {\n g_InstalledCallbacks = true;\n g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);\n g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);\n g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);\n g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);\n }\n\n g_ClientApi = client_api;\n return true;\n}\n\nbool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)\n{\n return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);\n}\n<|edits_diff|>\n--- examples/imgui_impl_glfw.cpp\n+++ examples/imgui_impl_glfw.cpp\n@@ -20,6 +20,7 @@\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);\n+ g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);\n #else\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n<|current_version|>\n io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;\n io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;\n io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;\n io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;\n io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;\n\n io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;\n io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;\n io.ClipboardUserData = g_Window;\n#if defined(_WIN32)\n io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);\n#endif\n\n g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);\n#if GLFW_HAS_NEW_CURSORS\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);\n#else\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n#endif\n\n // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.\n g_PrevUserCallbackMousebutton = NULL;\n g_PrevUserCallbackScroll = NULL;\n g_PrevUserCallbackKey = NULL;\n g_PrevUserCallbackChar = NULL;\n if (install_callbacks)\n {\n g_InstalledCallbacks = true;\n g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);\n g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);\n g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);\n g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);\n }\n\n g_ClientApi = client_api;\n return true;\n}\n\nbool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)\n{\n return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);\n}\n<|next_version|>\n io.KeyMap[ImGuiKey_C] = GLFW_KEY_C;\n io.KeyMap[ImGuiKey_V] = GLFW_KEY_V;\n io.KeyMap[ImGuiKey_X] = GLFW_KEY_X;\n io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y;\n io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z;\n\n io.SetClipboardTextFn = ImGui_ImplGlfw_SetClipboardText;\n io.GetClipboardTextFn = ImGui_ImplGlfw_GetClipboardText;\n io.ClipboardUserData = g_Window;\n#if defined(_WIN32)\n io.ImeWindowHandle = (void*)glfwGetWin32Window(g_Window);\n#endif\n\n g_MouseCursors[ImGuiMouseCursor_Arrow] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_TextInput] = glfwCreateStandardCursor(GLFW_IBEAM_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNS] = glfwCreateStandardCursor(GLFW_VRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeEW] = glfwCreateStandardCursor(GLFW_HRESIZE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_Hand] = glfwCreateStandardCursor(GLFW_HAND_CURSOR);\n#if GLFW_HAS_NEW_CURSORS\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_RESIZE_ALL_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_RESIZE_NESW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_RESIZE_NWSE_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_NOT_ALLOWED_CURSOR);\n#else\n g_MouseCursors[ImGuiMouseCursor_ResizeAll] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n g_MouseCursors[ImGuiMouseCursor_NotAllowed] = glfwCreateStandardCursor(GLFW_ARROW_CURSOR);\n#endif\n\n // Chain GLFW callbacks: our callbacks will call the user's previously installed callbacks, if any.\n g_PrevUserCallbackMousebutton = NULL;\n g_PrevUserCallbackScroll = NULL;\n g_PrevUserCallbackKey = NULL;\n g_PrevUserCallbackChar = NULL;\n if (install_callbacks)\n {\n g_InstalledCallbacks = true;\n g_PrevUserCallbackMousebutton = glfwSetMouseButtonCallback(window, ImGui_ImplGlfw_MouseButtonCallback);\n g_PrevUserCallbackScroll = glfwSetScrollCallback(window, ImGui_ImplGlfw_ScrollCallback);\n g_PrevUserCallbackKey = glfwSetKeyCallback(window, ImGui_ImplGlfw_KeyCallback);\n g_PrevUserCallbackChar = glfwSetCharCallback(window, ImGui_ImplGlfw_CharCallback);\n }\n\n g_ClientApi = client_api;\n return true;\n}\n\nbool ImGui_ImplGlfw_InitForOpenGL(GLFWwindow* window, bool install_callbacks)\n{\n return ImGui_ImplGlfw_Init(window, install_callbacks, GlfwClientApi_OpenGL);\n}\n"} {"commit": "69cc00f91fa440476453ab30d2597481f6b96c6d", "message": "ImGuiStorage: Added bool helper functions for completeness.", "old_file": "imgui.cpp", "new_file": "imgui.cpp", "status": "M", "old_contents": " ImVector::iterator mid = first + count2;\n if (mid->key < key)\n {\n first = ++mid;\n count -= count2 + 1;\n }\n else\n {\n count = count2;\n }\n }\n return first;\n}\n\nint ImGuiStorage::GetInt(ImU32 key, int default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_i;\n}\n\nfloat ImGuiStorage::GetFloat(ImU32 key, float default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_f;\n}\n\nvoid* ImGuiStorage::GetVoidPtr(ImGuiID key) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return NULL;\n return it->val_p;\n}\n\n// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.\nint* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_i;\n}\n\nfloat* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_f;\n}\n\nvoid** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_p;\n}\n\n// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)\nvoid ImGuiStorage::SetInt(ImU32 key, int val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_i = val;\n}\n\nvoid ImGuiStorage::SetFloat(ImU32 key, float val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_f = val;\n}\n\nvoid ImGuiStorage::SetVoidPtr(ImU32 key, void* val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_p = val;\n}\n", "new_contents": " ImVector::iterator mid = first + count2;\n if (mid->key < key)\n {\n first = ++mid;\n count -= count2 + 1;\n }\n else\n {\n count = count2;\n }\n }\n return first;\n}\n\nint ImGuiStorage::GetInt(ImU32 key, int default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_i;\n}\n\nbool ImGuiStorage::GetBool(ImU32 key, bool default_val) const\n{\n return GetInt(key, default_val ? 1 : 0) != 0;\n}\n\nfloat ImGuiStorage::GetFloat(ImU32 key, float default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_f;\n}\n\nvoid* ImGuiStorage::GetVoidPtr(ImGuiID key) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return NULL;\n return it->val_p;\n}\n\n// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.\nint* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_i;\n}\n\nbool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)\n{\n return (bool*)GetIntRef(key, default_val ? 1 : 0);\n}\n\nfloat* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_f;\n}\n\nvoid** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_p;\n}\n\n// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)\nvoid ImGuiStorage::SetInt(ImU32 key, int val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_i = val;\n}\n\nvoid ImGuiStorage::SetBool(ImU32 key, bool val)\n{\n SetInt(key, val ? 1 : 0);\n}\n\nvoid ImGuiStorage::SetFloat(ImU32 key, float val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_f = val;\n}\n\nvoid ImGuiStorage::SetVoidPtr(ImU32 key, void* val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_p = val;\n}\n", "current_contents": " ImVector::iterator mid = first + count2;\n if (mid->key < key)\n {\n first = ++mid;\n count -= count2 + 1;\n }\n else\n {\n count = count2;\n }\n }\n return first;\n}\n\nint ImGuiStorage::GetInt(ImU32 key, int default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_i;\n}\n\nbool ImGuiStorage::GetBool(ImU32 key, bool default_val) const\n{\n return GetInt(key, default_val ? 1 : 0) != 0;\n}\n\nfloat ImGuiStorage::GetFloat(ImU32 key, float default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_f;\n}\n\nvoid* ImGuiStorage::GetVoidPtr(ImGuiID key) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return NULL;\n return it->val_p;\n}\n\n// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.\nint* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_i;\n}\n\nbool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)\n{\n return (bool*)GetIntRef(key, default_val ? 1 : 0);\n}\n\nfloat* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_f;\n}\n\nvoid** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_p;\n}\n\n// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)\nvoid ImGuiStorage::SetInt(ImU32 key, int val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_i = val;\n}\n\nvoid ImGuiStorage::SetFloat(ImU32 key, float val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_f = val;\n}\n\nvoid ImGuiStorage::SetVoidPtr(ImU32 key, void* val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_p = val;\n}\n", "text": "<|original_code|>\n ImVector::iterator mid = first + count2;\n if (mid->key < key)\n {\n first = ++mid;\n count -= count2 + 1;\n }\n else\n {\n count = count2;\n }\n }\n return first;\n}\n\nint ImGuiStorage::GetInt(ImU32 key, int default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_i;\n}\n\nfloat ImGuiStorage::GetFloat(ImU32 key, float default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_f;\n}\n\nvoid* ImGuiStorage::GetVoidPtr(ImGuiID key) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return NULL;\n return it->val_p;\n}\n\n// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.\nint* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_i;\n}\n\nfloat* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_f;\n}\n\nvoid** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_p;\n}\n\n// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)\nvoid ImGuiStorage::SetInt(ImU32 key, int val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_i = val;\n}\n\nvoid ImGuiStorage::SetFloat(ImU32 key, float val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_f = val;\n}\n\nvoid ImGuiStorage::SetVoidPtr(ImU32 key, void* val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_p = val;\n}\n\n<|edits_diff|>\n--- imgui.cpp\n+++ imgui.cpp\n@@ -18,6 +18,11 @@\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_i;\n+}\n+\n+bool ImGuiStorage::GetBool(ImU32 key, bool default_val) const\n+{\n+ return GetInt(key, default_val ? 1 : 0) != 0;\n }\n \n float ImGuiStorage::GetFloat(ImU32 key, float default_val) const\n@@ -43,6 +48,11 @@\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_i;\n+}\n+\n+bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)\n+{\n+ return (bool*)GetIntRef(key, default_val ? 1 : 0);\n }\n \n float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)\n<|current_version|>\n ImVector::iterator mid = first + count2;\n if (mid->key < key)\n {\n first = ++mid;\n count -= count2 + 1;\n }\n else\n {\n count = count2;\n }\n }\n return first;\n}\n\nint ImGuiStorage::GetInt(ImU32 key, int default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_i;\n}\n\nbool ImGuiStorage::GetBool(ImU32 key, bool default_val) const\n{\n return GetInt(key, default_val ? 1 : 0) != 0;\n}\n\nfloat ImGuiStorage::GetFloat(ImU32 key, float default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_f;\n}\n\nvoid* ImGuiStorage::GetVoidPtr(ImGuiID key) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return NULL;\n return it->val_p;\n}\n\n// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.\nint* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_i;\n}\n\nbool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)\n{\n return (bool*)GetIntRef(key, default_val ? 1 : 0);\n}\n\nfloat* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_f;\n}\n\nvoid** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_p;\n}\n\n// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)\nvoid ImGuiStorage::SetInt(ImU32 key, int val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_i = val;\n}\n\nvoid ImGuiStorage::SetFloat(ImU32 key, float val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_f = val;\n}\n\nvoid ImGuiStorage::SetVoidPtr(ImU32 key, void* val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_p = val;\n}\n\n<|next_version|>\n ImVector::iterator mid = first + count2;\n if (mid->key < key)\n {\n first = ++mid;\n count -= count2 + 1;\n }\n else\n {\n count = count2;\n }\n }\n return first;\n}\n\nint ImGuiStorage::GetInt(ImU32 key, int default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_i;\n}\n\nbool ImGuiStorage::GetBool(ImU32 key, bool default_val) const\n{\n return GetInt(key, default_val ? 1 : 0) != 0;\n}\n\nfloat ImGuiStorage::GetFloat(ImU32 key, float default_val) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return default_val;\n return it->val_f;\n}\n\nvoid* ImGuiStorage::GetVoidPtr(ImGuiID key) const\n{\n ImVector::iterator it = LowerBound(const_cast&>(Data), key);\n if (it == Data.end() || it->key != key)\n return NULL;\n return it->val_p;\n}\n\n// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.\nint* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_i;\n}\n\nbool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)\n{\n return (bool*)GetIntRef(key, default_val ? 1 : 0);\n}\n\nfloat* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_f;\n}\n\nvoid** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n it = Data.insert(it, Pair(key, default_val));\n return &it->val_p;\n}\n\n// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)\nvoid ImGuiStorage::SetInt(ImU32 key, int val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_i = val;\n}\n\nvoid ImGuiStorage::SetBool(ImU32 key, bool val)\n{\n SetInt(key, val ? 1 : 0);\n}\n\nvoid ImGuiStorage::SetFloat(ImU32 key, float val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_f = val;\n}\n\nvoid ImGuiStorage::SetVoidPtr(ImU32 key, void* val)\n{\n ImVector::iterator it = LowerBound(Data, key);\n if (it == Data.end() || it->key != key)\n {\n Data.insert(it, Pair(key, val));\n return;\n }\n it->val_p = val;\n}\n\n"} {"commit": "b0730f29cf2376a27591197eb793410370fdd32b", "message": ":bug: fix logics", "old_file": "test/src/unit-diagnostics.cpp", "new_file": "test/src/unit-diagnostics.cpp", "status": "M", "old_contents": " }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562#pullrequestreview-574858448\")\n {\n CHECK_THROWS_WITH_AS(json({\"0\", \"0\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n CHECK_THROWS_WITH_AS(json({\"0\", \"1\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562/files/380a613f2b5d32425021129cd1f371ddcfd54ddf#r563259793\")\n {\n json j;\n j[\"/foo\"] = {1, 2, 3};\n CHECK_THROWS_WITH_AS(j.unflatten(), \"[json.exception.type_error.315] (/~1foo) values in object must be primitive\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/issues/2838\")\n {\n // void push_back(basic_json&& val)\n {\n json j_arr = json::array();\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // void push_back(const basic_json& val)\n {\n json j_arr = json::array();\n auto object = json::object();\n j_arr.push_back(object);\n j_arr.push_back(object);\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // reference emplace_back(Args&& ... args)\n {\n json j_arr = json::array();\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, size_type cnt, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), 2, json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n {\n json j_arr = json::array();\n json j_objects = {json::object(), json::object()};\n j_arr.insert(j_arr.begin(), j_objects.begin(), j_objects.end());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n }\n}", "new_contents": " }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562#pullrequestreview-574858448\")\n {\n CHECK_THROWS_WITH_AS(json({\"0\", \"0\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n CHECK_THROWS_WITH_AS(json({\"0\", \"1\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562/files/380a613f2b5d32425021129cd1f371ddcfd54ddf#r563259793\")\n {\n json j;\n j[\"/foo\"] = {1, 2, 3};\n CHECK_THROWS_WITH_AS(j.unflatten(), \"[json.exception.type_error.315] (/~1foo) values in object must be primitive\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/issues/2838\")\n {\n // void push_back(basic_json&& val)\n {\n json j_arr = json::array();\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // void push_back(const basic_json& val)\n {\n json j_arr = json::array();\n auto object = json::object();\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // reference emplace_back(Args&& ... args)\n {\n json j_arr = json::array();\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, size_type cnt, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), 2, json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n {\n json j_arr = json::array();\n json j_objects = {json::object(), json::object()};\n j_arr.insert(j_arr.begin(), j_objects.begin(), j_objects.end());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n }\n}", "current_contents": " }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562#pullrequestreview-574858448\")\n {\n CHECK_THROWS_WITH_AS(json({\"0\", \"0\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n CHECK_THROWS_WITH_AS(json({\"0\", \"1\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562/files/380a613f2b5d32425021129cd1f371ddcfd54ddf#r563259793\")\n {\n json j;\n j[\"/foo\"] = {1, 2, 3};\n CHECK_THROWS_WITH_AS(j.unflatten(), \"[json.exception.type_error.315] (/~1foo) values in object must be primitive\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/issues/2838\")\n {\n // void push_back(basic_json&& val)\n {\n json j_arr = json::array();\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // void push_back(const basic_json& val)\n {\n json j_arr = json::array();\n auto object = json::object();\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // reference emplace_back(Args&& ... args)\n {\n json j_arr = json::array();\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, size_type cnt, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), 2, json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n {\n json j_arr = json::array();\n json j_objects = {json::object(), json::object()};\n j_arr.insert(j_arr.begin(), j_objects.begin(), j_objects.end());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n }\n}", "text": "<|original_code|>\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562#pullrequestreview-574858448\")\n {\n CHECK_THROWS_WITH_AS(json({\"0\", \"0\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n CHECK_THROWS_WITH_AS(json({\"0\", \"1\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562/files/380a613f2b5d32425021129cd1f371ddcfd54ddf#r563259793\")\n {\n json j;\n j[\"/foo\"] = {1, 2, 3};\n CHECK_THROWS_WITH_AS(j.unflatten(), \"[json.exception.type_error.315] (/~1foo) values in object must be primitive\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/issues/2838\")\n {\n // void push_back(basic_json&& val)\n {\n json j_arr = json::array();\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // void push_back(const basic_json& val)\n {\n json j_arr = json::array();\n auto object = json::object();\n j_arr.push_back(object);\n j_arr.push_back(object);\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // reference emplace_back(Args&& ... args)\n {\n json j_arr = json::array();\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, size_type cnt, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), 2, json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n {\n json j_arr = json::array();\n json j_objects = {json::object(), json::object()};\n j_arr.insert(j_arr.begin(), j_objects.begin(), j_objects.end());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n }\n}\n<|edits_diff|>\n--- test/src/unit-diagnostics.cpp\n+++ test/src/unit-diagnostics.cpp\n@@ -20,6 +20,8 @@\n json j_arr = json::array();\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n+ j_arr.push_back(json::object());\n+ j_arr.push_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n@@ -30,6 +32,8 @@\n auto object = json::object();\n j_arr.push_back(object);\n j_arr.push_back(object);\n+ j_arr.push_back(object);\n+ j_arr.push_back(object);\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n@@ -37,6 +41,8 @@\n // reference emplace_back(Args&& ... args)\n {\n json j_arr = json::array();\n+ j_arr.emplace_back(json::object());\n+ j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n json j_obj = json::object();\n<|current_version|>\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562#pullrequestreview-574858448\")\n {\n CHECK_THROWS_WITH_AS(json({\"0\", \"0\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n CHECK_THROWS_WITH_AS(json({\"0\", \"1\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562/files/380a613f2b5d32425021129cd1f371ddcfd54ddf#r563259793\")\n {\n json j;\n j[\"/foo\"] = {1, 2, 3};\n CHECK_THROWS_WITH_AS(j.unflatten(), \"[json.exception.type_error.315] (/~1foo) values in object must be primitive\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/issues/2838\")\n {\n // void push_back(basic_json&& val)\n {\n json j_arr = json::array();\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // void push_back(const basic_json& val)\n {\n json j_arr = json::array();\n auto object = json::object();\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // reference emplace_back(Args&& ... args)\n {\n json j_arr = json::array();\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, size_type cnt, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), 2, json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n {\n json j_arr = json::array();\n json j_objects = {json::object(), json::object()};\n j_arr.insert(j_arr.begin(), j_objects.begin(), j_objects.end());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n }\n}\n<|next_version|>\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562#pullrequestreview-574858448\")\n {\n CHECK_THROWS_WITH_AS(json({\"0\", \"0\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n CHECK_THROWS_WITH_AS(json({\"0\", \"1\"})[1].get(), \"[json.exception.type_error.302] (/1) type must be number, but is string\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/pull/2562/files/380a613f2b5d32425021129cd1f371ddcfd54ddf#r563259793\")\n {\n json j;\n j[\"/foo\"] = {1, 2, 3};\n CHECK_THROWS_WITH_AS(j.unflatten(), \"[json.exception.type_error.315] (/~1foo) values in object must be primitive\", json::type_error);\n }\n\n SECTION(\"Regression test for https://github.com/nlohmann/json/issues/2838\")\n {\n // void push_back(basic_json&& val)\n {\n json j_arr = json::array();\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n j_arr.push_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // void push_back(const basic_json& val)\n {\n json j_arr = json::array();\n auto object = json::object();\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n j_arr.push_back(object);\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // reference emplace_back(Args&& ... args)\n {\n json j_arr = json::array();\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n j_arr.emplace_back(json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n j_arr.insert(j_arr.begin(), json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, size_type cnt, const basic_json& val)\n {\n json j_arr = json::array();\n j_arr.insert(j_arr.begin(), 2, json::object());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n\n // iterator insert(const_iterator pos, const_iterator first, const_iterator last)\n {\n json j_arr = json::array();\n json j_objects = {json::object(), json::object()};\n j_arr.insert(j_arr.begin(), j_objects.begin(), j_objects.end());\n json j_obj = json::object();\n j_obj[\"key\"] = j_arr;\n }\n }\n}\n"} {"commit": "a0000c32355a0ed5284c366380ec730b350ad988", "message": "finished the last of the warnings", "old_file": "test/src/unit-cbor.cpp", "new_file": "test/src/unit-cbor.cpp", "status": "M", "old_contents": "\n SECTION(\"-0 (1 00000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x80, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -0.0);\n }\n\n SECTION(\"2**-24 (0 00000 0000000001)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x00, 0x01}));\n json::number_float_t d = j;\n CHECK(d == std::pow(2.0, -24.0));\n }\n }\n\n SECTION(\"exp = 0b11111\")\n {\n SECTION(\"infinity (0 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n CHECK(d == std::numeric_limits::infinity());\n CHECK(j.dump() == \"null\");\n }\n\n SECTION(\"-infinity (1 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xfc, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -std::numeric_limits::infinity());\n CHECK(j.dump() == \"null\");\n }\n }\n\n SECTION(\"other values from https://en.wikipedia.org/wiki/Half-precision_floating-point_format\")\n {\n SECTION(\"1 (0 01111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x3c, 0x00}));\n json::number_float_t d = j;\n CHECK(d == 1);\n }\n\n SECTION(\"-2 (1 10000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xc0, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -2);\n }\n\n SECTION(\"65504 (0 11110 1111111111)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7b, 0xff}));\n json::number_float_t d = j;\n CHECK(d == 65504);\n }\n }\n\n SECTION(\"infinity\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n CHECK(not std::isfinite(d));\n CHECK(j.dump() == \"null\");\n }", "new_contents": "\n SECTION(\"-0 (1 00000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x80, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -0.0);\n }\n\n SECTION(\"2**-24 (0 00000 0000000001)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x00, 0x01}));\n json::number_float_t d = j;\n CHECK(d == std::pow(2.0, -24.0));\n }\n }\n\n SECTION(\"exp = 0b11111\")\n {\n SECTION(\"infinity (0 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == std::numeric_limits::infinity());\n DOCTEST_GCC_SUPPRESS_WARNING_POP\n CHECK(j.dump() == \"null\");\n }\n\n SECTION(\"-infinity (1 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xfc, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -std::numeric_limits::infinity());\n CHECK(j.dump() == \"null\");\n }\n }\n\n SECTION(\"other values from https://en.wikipedia.org/wiki/Half-precision_floating-point_format\")\n {\n SECTION(\"1 (0 01111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x3c, 0x00}));\n json::number_float_t d = j;\n DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == 1);\n DOCTEST_GCC_SUPPRESS_WARNING_POP\n }\n\n SECTION(\"-2 (1 10000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xc0, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -2);\n }\n\n SECTION(\"65504 (0 11110 1111111111)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7b, 0xff}));\n json::number_float_t d = j;\n CHECK(d == 65504);\n }\n }\n\n SECTION(\"infinity\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n CHECK(not std::isfinite(d));\n CHECK(j.dump() == \"null\");\n }", "current_contents": "\n SECTION(\"-0 (1 00000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x80, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -0.0);\n }\n\n SECTION(\"2**-24 (0 00000 0000000001)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x00, 0x01}));\n json::number_float_t d = j;\n CHECK(d == std::pow(2.0, -24.0));\n }\n }\n\n SECTION(\"exp = 0b11111\")\n {\n SECTION(\"infinity (0 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == std::numeric_limits::infinity());\n DOCTEST_GCC_SUPPRESS_WARNING_POP\n CHECK(j.dump() == \"null\");\n }\n\n SECTION(\"-infinity (1 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xfc, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -std::numeric_limits::infinity());\n CHECK(j.dump() == \"null\");\n }\n }\n\n SECTION(\"other values from https://en.wikipedia.org/wiki/Half-precision_floating-point_format\")\n {\n SECTION(\"1 (0 01111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x3c, 0x00}));\n json::number_float_t d = j;\n DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == 1);\n }\n\n SECTION(\"-2 (1 10000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xc0, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -2);\n }\n\n SECTION(\"65504 (0 11110 1111111111)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7b, 0xff}));\n json::number_float_t d = j;\n CHECK(d == 65504);\n }\n }\n\n SECTION(\"infinity\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n CHECK(not std::isfinite(d));\n CHECK(j.dump() == \"null\");\n }", "text": "<|original_code|>\n\n SECTION(\"-0 (1 00000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x80, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -0.0);\n }\n\n SECTION(\"2**-24 (0 00000 0000000001)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x00, 0x01}));\n json::number_float_t d = j;\n CHECK(d == std::pow(2.0, -24.0));\n }\n }\n\n SECTION(\"exp = 0b11111\")\n {\n SECTION(\"infinity (0 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n CHECK(d == std::numeric_limits::infinity());\n CHECK(j.dump() == \"null\");\n }\n\n SECTION(\"-infinity (1 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xfc, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -std::numeric_limits::infinity());\n CHECK(j.dump() == \"null\");\n }\n }\n\n SECTION(\"other values from https://en.wikipedia.org/wiki/Half-precision_floating-point_format\")\n {\n SECTION(\"1 (0 01111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x3c, 0x00}));\n json::number_float_t d = j;\n CHECK(d == 1);\n }\n\n SECTION(\"-2 (1 10000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xc0, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -2);\n }\n\n SECTION(\"65504 (0 11110 1111111111)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7b, 0xff}));\n json::number_float_t d = j;\n CHECK(d == 65504);\n }\n }\n\n SECTION(\"infinity\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n CHECK(not std::isfinite(d));\n CHECK(j.dump() == \"null\");\n }\n<|edits_diff|>\n--- test/src/unit-cbor.cpp\n+++ test/src/unit-cbor.cpp\n@@ -20,7 +20,9 @@\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n+ DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == std::numeric_limits::infinity());\n+ DOCTEST_GCC_SUPPRESS_WARNING_POP\n CHECK(j.dump() == \"null\");\n }\n \n@@ -39,6 +41,7 @@\n {\n json j = json::from_cbor(std::vector({0xf9, 0x3c, 0x00}));\n json::number_float_t d = j;\n+ DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == 1);\n }\n \n<|current_version|>\n\n SECTION(\"-0 (1 00000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x80, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -0.0);\n }\n\n SECTION(\"2**-24 (0 00000 0000000001)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x00, 0x01}));\n json::number_float_t d = j;\n CHECK(d == std::pow(2.0, -24.0));\n }\n }\n\n SECTION(\"exp = 0b11111\")\n {\n SECTION(\"infinity (0 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == std::numeric_limits::infinity());\n DOCTEST_GCC_SUPPRESS_WARNING_POP\n CHECK(j.dump() == \"null\");\n }\n\n SECTION(\"-infinity (1 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xfc, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -std::numeric_limits::infinity());\n CHECK(j.dump() == \"null\");\n }\n }\n\n SECTION(\"other values from https://en.wikipedia.org/wiki/Half-precision_floating-point_format\")\n {\n SECTION(\"1 (0 01111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x3c, 0x00}));\n json::number_float_t d = j;\n DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == 1);\n }\n\n SECTION(\"-2 (1 10000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xc0, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -2);\n }\n\n SECTION(\"65504 (0 11110 1111111111)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7b, 0xff}));\n json::number_float_t d = j;\n CHECK(d == 65504);\n }\n }\n\n SECTION(\"infinity\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n CHECK(not std::isfinite(d));\n CHECK(j.dump() == \"null\");\n }\n<|next_version|>\n\n SECTION(\"-0 (1 00000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x80, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -0.0);\n }\n\n SECTION(\"2**-24 (0 00000 0000000001)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x00, 0x01}));\n json::number_float_t d = j;\n CHECK(d == std::pow(2.0, -24.0));\n }\n }\n\n SECTION(\"exp = 0b11111\")\n {\n SECTION(\"infinity (0 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == std::numeric_limits::infinity());\n DOCTEST_GCC_SUPPRESS_WARNING_POP\n CHECK(j.dump() == \"null\");\n }\n\n SECTION(\"-infinity (1 11111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xfc, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -std::numeric_limits::infinity());\n CHECK(j.dump() == \"null\");\n }\n }\n\n SECTION(\"other values from https://en.wikipedia.org/wiki/Half-precision_floating-point_format\")\n {\n SECTION(\"1 (0 01111 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x3c, 0x00}));\n json::number_float_t d = j;\n DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(\"-Wfloat-equal\")\n CHECK(d == 1);\n DOCTEST_GCC_SUPPRESS_WARNING_POP\n }\n\n SECTION(\"-2 (1 10000 0000000000)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0xc0, 0x00}));\n json::number_float_t d = j;\n CHECK(d == -2);\n }\n\n SECTION(\"65504 (0 11110 1111111111)\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7b, 0xff}));\n json::number_float_t d = j;\n CHECK(d == 65504);\n }\n }\n\n SECTION(\"infinity\")\n {\n json j = json::from_cbor(std::vector({0xf9, 0x7c, 0x00}));\n json::number_float_t d = j;\n CHECK(not std::isfinite(d));\n CHECK(j.dump() == \"null\");\n }\n"} {"commit": "6d0294ba6cbff7089574797d1c3a7394fcd1ad50", "message": "Support of 12-bit vector codecs for SaDecodeKernels (#2745)", "old_file": "tests/test_cppcontrib_sa_decode.cpp", "new_file": "tests/test_cppcontrib_sa_decode.cpp", "status": "M", "old_contents": "}\n\n// test IndexRowwiseMinMax\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_IVF256_PQ16) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndex2LevelDecoder(NSAMPLES, 256, \"MinMax,IVF256,PQ16np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_PQ16) {\n using SubT = faiss::cppcontrib::IndexPQDecoder<256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndexPQDecoder(NSAMPLES, 256, \"MinMax,PQ16np\");\n}\n\n// implemented for AVX2 and ARM so far\n#if defined(__AVX2__) || defined(__ARM_NEON)\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 256, \"PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 160, \"PQ20x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF256_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 10, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10_ALTERNATIVE) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_Residual4x8_PQ8x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 20, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 160, \"Residual4x8,PQ8x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual1x9_PQ16x10) {\n // It is acceptable to use COARSE_BITS=16 in this case,\n // because there's only one coarse quantizer element.\n // It won't work for \"Residual2x9,PQ16x10\".\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual1x9,PQ16x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual4x10_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 10, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual4x10,PQ16x10\");\n}\n\n#endif\n", "new_contents": "}\n\n// test IndexRowwiseMinMax\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_IVF256_PQ16) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndex2LevelDecoder(NSAMPLES, 256, \"MinMax,IVF256,PQ16np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_PQ16) {\n using SubT = faiss::cppcontrib::IndexPQDecoder<256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndexPQDecoder(NSAMPLES, 256, \"MinMax,PQ16np\");\n}\n\n// implemented for AVX2 and ARM so far\n#if defined(__AVX2__) || defined(__ARM_NEON)\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 256, \"PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x12) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 12>;\n testIndexPQDecoder(NSAMPLES * 16, 256, \"PQ16x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 160, \"PQ20x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x12) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 12>;\n testIndexPQDecoder(NSAMPLES * 16, 160, \"PQ20x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x12) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 12>;\n testIndex2LevelDecoder(NSAMPLES * 16, 256, \"IVF256,PQ16x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF256_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 10, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10_ALTERNATIVE) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_Residual4x8_PQ8x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 20, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 160, \"Residual4x8,PQ8x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual1x9_PQ16x10) {\n // It is acceptable to use COARSE_BITS=16 in this case,\n // because there's only one coarse quantizer element.\n // It won't work for \"Residual2x9,PQ16x10\".\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual1x9,PQ16x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual4x10_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 10, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual4x10,PQ16x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual4x12_PQ16x12) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 12, 12>;\n testIndex2LevelDecoder(NSAMPLES * 16, 256, \"Residual4x12,PQ16x12\");\n}\n\n#endif\n", "current_contents": "}\n\n// test IndexRowwiseMinMax\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_IVF256_PQ16) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndex2LevelDecoder(NSAMPLES, 256, \"MinMax,IVF256,PQ16np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_PQ16) {\n using SubT = faiss::cppcontrib::IndexPQDecoder<256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndexPQDecoder(NSAMPLES, 256, \"MinMax,PQ16np\");\n}\n\n// implemented for AVX2 and ARM so far\n#if defined(__AVX2__) || defined(__ARM_NEON)\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 256, \"PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x12) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 12>;\n testIndexPQDecoder(NSAMPLES * 16, 256, \"PQ16x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 160, \"PQ20x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x12) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 12>;\n testIndexPQDecoder(NSAMPLES * 16, 160, \"PQ20x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x12) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 12>;\n testIndex2LevelDecoder(NSAMPLES * 16, 256, \"IVF256,PQ16x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF256_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 10, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10_ALTERNATIVE) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_Residual4x8_PQ8x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 20, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 160, \"Residual4x8,PQ8x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual1x9_PQ16x10) {\n // It is acceptable to use COARSE_BITS=16 in this case,\n // because there's only one coarse quantizer element.\n // It won't work for \"Residual2x9,PQ16x10\".\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual1x9,PQ16x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual4x10_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 10, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual4x10,PQ16x10\");\n}\n\n#endif\n", "text": "<|original_code|>\n}\n\n// test IndexRowwiseMinMax\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_IVF256_PQ16) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndex2LevelDecoder(NSAMPLES, 256, \"MinMax,IVF256,PQ16np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_PQ16) {\n using SubT = faiss::cppcontrib::IndexPQDecoder<256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndexPQDecoder(NSAMPLES, 256, \"MinMax,PQ16np\");\n}\n\n// implemented for AVX2 and ARM so far\n#if defined(__AVX2__) || defined(__ARM_NEON)\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 256, \"PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 160, \"PQ20x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF256_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 10, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10_ALTERNATIVE) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_Residual4x8_PQ8x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 20, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 160, \"Residual4x8,PQ8x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual1x9_PQ16x10) {\n // It is acceptable to use COARSE_BITS=16 in this case,\n // because there's only one coarse quantizer element.\n // It won't work for \"Residual2x9,PQ16x10\".\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual1x9,PQ16x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual4x10_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 10, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual4x10,PQ16x10\");\n}\n\n#endif\n\n<|edits_diff|>\n--- tests/test_cppcontrib_sa_decode.cpp\n+++ tests/test_cppcontrib_sa_decode.cpp\n@@ -20,14 +20,29 @@\n testIndexPQDecoder(NSAMPLES * 4, 256, \"PQ16x10np\");\n }\n \n+TEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x12) {\n+ using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 12>;\n+ testIndexPQDecoder(NSAMPLES * 16, 256, \"PQ16x12np\");\n+}\n+\n TEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 160, \"PQ20x10np\");\n }\n \n+TEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x12) {\n+ using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 12>;\n+ testIndexPQDecoder(NSAMPLES * 16, 160, \"PQ20x12np\");\n+}\n+\n TEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"IVF256,PQ16x10np\");\n+}\n+\n+TEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x12) {\n+ using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 12>;\n+ testIndex2LevelDecoder(NSAMPLES * 16, 256, \"IVF256,PQ16x12np\");\n }\n \n TEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF256_PQ16x10) {\n<|current_version|>\n}\n\n// test IndexRowwiseMinMax\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_IVF256_PQ16) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndex2LevelDecoder(NSAMPLES, 256, \"MinMax,IVF256,PQ16np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_PQ16) {\n using SubT = faiss::cppcontrib::IndexPQDecoder<256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndexPQDecoder(NSAMPLES, 256, \"MinMax,PQ16np\");\n}\n\n// implemented for AVX2 and ARM so far\n#if defined(__AVX2__) || defined(__ARM_NEON)\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 256, \"PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x12) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 12>;\n testIndexPQDecoder(NSAMPLES * 16, 256, \"PQ16x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 160, \"PQ20x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x12) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 12>;\n testIndexPQDecoder(NSAMPLES * 16, 160, \"PQ20x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x12) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 12>;\n testIndex2LevelDecoder(NSAMPLES * 16, 256, \"IVF256,PQ16x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF256_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 10, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10_ALTERNATIVE) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_Residual4x8_PQ8x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 20, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 160, \"Residual4x8,PQ8x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual1x9_PQ16x10) {\n // It is acceptable to use COARSE_BITS=16 in this case,\n // because there's only one coarse quantizer element.\n // It won't work for \"Residual2x9,PQ16x10\".\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual1x9,PQ16x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual4x10_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 10, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual4x10,PQ16x10\");\n}\n\n#endif\n\n<|next_version|>\n}\n\n// test IndexRowwiseMinMax\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_IVF256_PQ16) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndex2LevelDecoder(NSAMPLES, 256, \"MinMax,IVF256,PQ16np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAX_PQ16) {\n using SubT = faiss::cppcontrib::IndexPQDecoder<256, 16>;\n using T = faiss::cppcontrib::IndexMinMaxDecoder;\n testMinMaxIndexPQDecoder(NSAMPLES, 256, \"MinMax,PQ16np\");\n}\n\n// implemented for AVX2 and ARM so far\n#if defined(__AVX2__) || defined(__ARM_NEON)\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 256, \"PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_PQ16x12) {\n using T = faiss::cppcontrib::IndexPQDecoder<256, 16, 12>;\n testIndexPQDecoder(NSAMPLES * 16, 256, \"PQ16x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x10) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 10>;\n testIndexPQDecoder(NSAMPLES * 4, 160, \"PQ20x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_PQ20x12) {\n using T = faiss::cppcontrib::IndexPQDecoder<160, 8, 12>;\n testIndexPQDecoder(NSAMPLES * 16, 160, \"PQ20x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_IVF256_PQ16x12) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 12>;\n testIndex2LevelDecoder(NSAMPLES * 16, 256, \"IVF256,PQ16x12np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF256_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 8, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF256,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 10, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_MINMAXFP16_IVF1024_PQ16x10_ALTERNATIVE) {\n using SubT = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n using T = faiss::cppcontrib::IndexMinMaxFP16Decoder;\n testMinMaxIndex2LevelDecoder(\n NSAMPLES * 4, 256, \"MinMaxFP16,IVF1024,PQ16x10np\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D160_Residual4x8_PQ8x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<160, 40, 20, 8, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 160, \"Residual4x8,PQ8x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual1x9_PQ16x10) {\n // It is acceptable to use COARSE_BITS=16 in this case,\n // because there's only one coarse quantizer element.\n // It won't work for \"Residual2x9,PQ16x10\".\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 256, 16, 16, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual1x9,PQ16x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual4x10_PQ16x10) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 10, 10>;\n testIndex2LevelDecoder(NSAMPLES * 4, 256, \"Residual4x10,PQ16x10\");\n}\n\nTEST(TEST_CPPCONTRIB_SA_DECODE, D256_Residual4x12_PQ16x12) {\n using T = faiss::cppcontrib::Index2LevelDecoder<256, 64, 16, 12, 12>;\n testIndex2LevelDecoder(NSAMPLES * 16, 256, \"Residual4x12,PQ16x12\");\n}\n\n#endif\n\n"} {"commit": "7cce100c92e45427f46d912f625bcb9b6cb85ed3", "message": "C_API: Improve PreTransformIndex (#1945)", "old_file": "c_api/Clustering_c.cpp", "new_file": "c_api/Clustering_c.cpp", "status": "M", "old_contents": " */\n\n// Copyright 2004-present Facebook. All Rights Reserved.\n// -*- c++ -*-\n\n#include \"Clustering_c.h\"\n#include \n#include \n#include \n#include \"macros_impl.h\"\n\nextern \"C\" {\n\nusing faiss::Clustering;\nusing faiss::ClusteringIterationStats;\nusing faiss::ClusteringParameters;\nusing faiss::Index;\n\nDEFINE_GETTER(Clustering, int, niter)\nDEFINE_GETTER(Clustering, int, nredo)\nDEFINE_GETTER(Clustering, int, verbose)\nDEFINE_GETTER(Clustering, int, spherical)\nDEFINE_GETTER(Clustering, int, update_index)\nDEFINE_GETTER(Clustering, int, frozen_centroids)\n\nDEFINE_GETTER(Clustering, int, min_points_per_centroid)\nDEFINE_GETTER(Clustering, int, max_points_per_centroid)\n\nDEFINE_GETTER(Clustering, int, seed)\n\n/// getter for d\nDEFINE_GETTER(Clustering, size_t, d)\n\n/// getter for k\nDEFINE_GETTER(Clustering, size_t, k)\n\nDEFINE_GETTER(ClusteringIterationStats, float, obj)\nDEFINE_GETTER(ClusteringIterationStats, double, time)\nDEFINE_GETTER(ClusteringIterationStats, double, time_search)\nDEFINE_GETTER(ClusteringIterationStats, double, imbalance_factor)\nDEFINE_GETTER(ClusteringIterationStats, int, nsplit)\n\nvoid faiss_ClusteringParameters_init(FaissClusteringParameters* params) {\n ClusteringParameters d;\n params->frozen_centroids = d.frozen_centroids;\n params->max_points_per_centroid = d.max_points_per_centroid;\n params->min_points_per_centroid = d.min_points_per_centroid;\n params->niter = d.niter;\n params->nredo = d.nredo;\n params->seed = d.seed;\n params->spherical = d.spherical;\n params->update_index = d.update_index;\n params->verbose = d.verbose;\n}\n\n// This conversion is required because the two types are not memory-compatible\ninline ClusteringParameters from_faiss_c(\n const FaissClusteringParameters* params) {\n ClusteringParameters o;\n o.frozen_centroids = params->frozen_centroids;\n o.max_points_per_centroid = params->max_points_per_centroid;\n o.min_points_per_centroid = params->min_points_per_centroid;\n o.niter = params->niter;\n o.nredo = params->nredo;\n o.seed = params->seed;\n o.spherical = params->spherical;\n o.update_index = params->update_index;\n o.verbose = params->verbose;\n return o;\n}\n\n/// getter for centroids (size = k * d)\nvoid faiss_Clustering_centroids(\n FaissClustering* clustering,\n float** centroids,\n size_t* size) {\n std::vector& v =\n reinterpret_cast(clustering)->centroids;\n if (centroids) {\n *centroids = v.data();\n }\n if (size) {\n *size = v.size();\n }\n}\n\n/// getter for iteration stats\nvoid faiss_Clustering_iteration_stats(\n FaissClustering* clustering,\n FaissClusteringIterationStats** iteration_stats,\n size_t* size) {\n std::vector& v =", "new_contents": " */\n\n// Copyright 2004-present Facebook. All Rights Reserved.\n// -*- c++ -*-\n\n#include \"Clustering_c.h\"\n#include \n#include \n#include \n#include \"macros_impl.h\"\n\nextern \"C\" {\n\nusing faiss::Clustering;\nusing faiss::ClusteringIterationStats;\nusing faiss::ClusteringParameters;\nusing faiss::Index;\n\nDEFINE_GETTER(Clustering, int, niter)\nDEFINE_GETTER(Clustering, int, nredo)\nDEFINE_GETTER(Clustering, int, verbose)\nDEFINE_GETTER(Clustering, int, spherical)\nDEFINE_GETTER(Clustering, int, int_centroids)\nDEFINE_GETTER(Clustering, int, update_index)\nDEFINE_GETTER(Clustering, int, frozen_centroids)\n\nDEFINE_GETTER(Clustering, int, min_points_per_centroid)\nDEFINE_GETTER(Clustering, int, max_points_per_centroid)\n\nDEFINE_GETTER(Clustering, int, seed)\nDEFINE_GETTER(Clustering, size_t, decode_block_size)\n\n/// getter for d\nDEFINE_GETTER(Clustering, size_t, d)\n\n/// getter for k\nDEFINE_GETTER(Clustering, size_t, k)\n\nDEFINE_GETTER(ClusteringIterationStats, float, obj)\nDEFINE_GETTER(ClusteringIterationStats, double, time)\nDEFINE_GETTER(ClusteringIterationStats, double, time_search)\nDEFINE_GETTER(ClusteringIterationStats, double, imbalance_factor)\nDEFINE_GETTER(ClusteringIterationStats, int, nsplit)\n\nvoid faiss_ClusteringParameters_init(FaissClusteringParameters* params) {\n ClusteringParameters d;\n params->frozen_centroids = d.frozen_centroids;\n params->max_points_per_centroid = d.max_points_per_centroid;\n params->min_points_per_centroid = d.min_points_per_centroid;\n params->niter = d.niter;\n params->nredo = d.nredo;\n params->seed = d.seed;\n params->spherical = d.spherical;\n params->int_centroids = d.int_centroids;\n params->update_index = d.update_index;\n params->verbose = d.verbose;\n params->decode_block_size = d.decode_block_size;\n}\n\n// This conversion is required because the two types are not memory-compatible\ninline ClusteringParameters from_faiss_c(\n const FaissClusteringParameters* params) {\n ClusteringParameters o;\n o.frozen_centroids = params->frozen_centroids;\n o.max_points_per_centroid = params->max_points_per_centroid;\n o.min_points_per_centroid = params->min_points_per_centroid;\n o.niter = params->niter;\n o.nredo = params->nredo;\n o.seed = params->seed;\n o.spherical = params->spherical;\n o.update_index = params->update_index;\n o.int_centroids = params->int_centroids;\n o.verbose = params->verbose;\n o.decode_block_size = params->decode_block_size;\n return o;\n}\n\n/// getter for centroids (size = k * d)\nvoid faiss_Clustering_centroids(\n FaissClustering* clustering,\n float** centroids,\n size_t* size) {\n std::vector& v =\n reinterpret_cast(clustering)->centroids;\n if (centroids) {\n *centroids = v.data();\n }\n if (size) {\n *size = v.size();\n }\n}\n\n/// getter for iteration stats\nvoid faiss_Clustering_iteration_stats(\n FaissClustering* clustering,\n FaissClusteringIterationStats** iteration_stats,\n size_t* size) {\n std::vector& v =", "current_contents": " */\n\n// Copyright 2004-present Facebook. All Rights Reserved.\n// -*- c++ -*-\n\n#include \"Clustering_c.h\"\n#include \n#include \n#include \n#include \"macros_impl.h\"\n\nextern \"C\" {\n\nusing faiss::Clustering;\nusing faiss::ClusteringIterationStats;\nusing faiss::ClusteringParameters;\nusing faiss::Index;\n\nDEFINE_GETTER(Clustering, int, niter)\nDEFINE_GETTER(Clustering, int, nredo)\nDEFINE_GETTER(Clustering, int, verbose)\nDEFINE_GETTER(Clustering, int, spherical)\nDEFINE_GETTER(Clustering, int, int_centroids)\nDEFINE_GETTER(Clustering, int, update_index)\nDEFINE_GETTER(Clustering, int, frozen_centroids)\n\nDEFINE_GETTER(Clustering, int, min_points_per_centroid)\nDEFINE_GETTER(Clustering, int, max_points_per_centroid)\n\nDEFINE_GETTER(Clustering, int, seed)\nDEFINE_GETTER(Clustering, size_t, decode_block_size)\n\n/// getter for d\nDEFINE_GETTER(Clustering, size_t, d)\n\n/// getter for k\nDEFINE_GETTER(Clustering, size_t, k)\n\nDEFINE_GETTER(ClusteringIterationStats, float, obj)\nDEFINE_GETTER(ClusteringIterationStats, double, time)\nDEFINE_GETTER(ClusteringIterationStats, double, time_search)\nDEFINE_GETTER(ClusteringIterationStats, double, imbalance_factor)\nDEFINE_GETTER(ClusteringIterationStats, int, nsplit)\n\nvoid faiss_ClusteringParameters_init(FaissClusteringParameters* params) {\n ClusteringParameters d;\n params->frozen_centroids = d.frozen_centroids;\n params->max_points_per_centroid = d.max_points_per_centroid;\n params->min_points_per_centroid = d.min_points_per_centroid;\n params->niter = d.niter;\n params->nredo = d.nredo;\n params->seed = d.seed;\n params->spherical = d.spherical;\n params->int_centroids = d.int_centroids;\n params->update_index = d.update_index;\n params->verbose = d.verbose;\n params->decode_block_size = d.decode_block_size;\n}\n\n// This conversion is required because the two types are not memory-compatible\ninline ClusteringParameters from_faiss_c(\n const FaissClusteringParameters* params) {\n ClusteringParameters o;\n o.frozen_centroids = params->frozen_centroids;\n o.max_points_per_centroid = params->max_points_per_centroid;\n o.min_points_per_centroid = params->min_points_per_centroid;\n o.niter = params->niter;\n o.nredo = params->nredo;\n o.seed = params->seed;\n o.spherical = params->spherical;\n o.update_index = params->update_index;\n o.int_centroids = params->int_centroids;\n o.verbose = params->verbose;\n return o;\n}\n\n/// getter for centroids (size = k * d)\nvoid faiss_Clustering_centroids(\n FaissClustering* clustering,\n float** centroids,\n size_t* size) {\n std::vector& v =\n reinterpret_cast(clustering)->centroids;\n if (centroids) {\n *centroids = v.data();\n }\n if (size) {\n *size = v.size();\n }\n}\n\n/// getter for iteration stats\nvoid faiss_Clustering_iteration_stats(\n FaissClustering* clustering,\n FaissClusteringIterationStats** iteration_stats,\n size_t* size) {\n std::vector& v =", "text": "<|original_code|>\n */\n\n// Copyright 2004-present Facebook. All Rights Reserved.\n// -*- c++ -*-\n\n#include \"Clustering_c.h\"\n#include \n#include \n#include \n#include \"macros_impl.h\"\n\nextern \"C\" {\n\nusing faiss::Clustering;\nusing faiss::ClusteringIterationStats;\nusing faiss::ClusteringParameters;\nusing faiss::Index;\n\nDEFINE_GETTER(Clustering, int, niter)\nDEFINE_GETTER(Clustering, int, nredo)\nDEFINE_GETTER(Clustering, int, verbose)\nDEFINE_GETTER(Clustering, int, spherical)\nDEFINE_GETTER(Clustering, int, update_index)\nDEFINE_GETTER(Clustering, int, frozen_centroids)\n\nDEFINE_GETTER(Clustering, int, min_points_per_centroid)\nDEFINE_GETTER(Clustering, int, max_points_per_centroid)\n\nDEFINE_GETTER(Clustering, int, seed)\n\n/// getter for d\nDEFINE_GETTER(Clustering, size_t, d)\n\n/// getter for k\nDEFINE_GETTER(Clustering, size_t, k)\n\nDEFINE_GETTER(ClusteringIterationStats, float, obj)\nDEFINE_GETTER(ClusteringIterationStats, double, time)\nDEFINE_GETTER(ClusteringIterationStats, double, time_search)\nDEFINE_GETTER(ClusteringIterationStats, double, imbalance_factor)\nDEFINE_GETTER(ClusteringIterationStats, int, nsplit)\n\nvoid faiss_ClusteringParameters_init(FaissClusteringParameters* params) {\n ClusteringParameters d;\n params->frozen_centroids = d.frozen_centroids;\n params->max_points_per_centroid = d.max_points_per_centroid;\n params->min_points_per_centroid = d.min_points_per_centroid;\n params->niter = d.niter;\n params->nredo = d.nredo;\n params->seed = d.seed;\n params->spherical = d.spherical;\n params->update_index = d.update_index;\n params->verbose = d.verbose;\n}\n\n// This conversion is required because the two types are not memory-compatible\ninline ClusteringParameters from_faiss_c(\n const FaissClusteringParameters* params) {\n ClusteringParameters o;\n o.frozen_centroids = params->frozen_centroids;\n o.max_points_per_centroid = params->max_points_per_centroid;\n o.min_points_per_centroid = params->min_points_per_centroid;\n o.niter = params->niter;\n o.nredo = params->nredo;\n o.seed = params->seed;\n o.spherical = params->spherical;\n o.update_index = params->update_index;\n o.verbose = params->verbose;\n return o;\n}\n\n/// getter for centroids (size = k * d)\nvoid faiss_Clustering_centroids(\n FaissClustering* clustering,\n float** centroids,\n size_t* size) {\n std::vector& v =\n reinterpret_cast(clustering)->centroids;\n if (centroids) {\n *centroids = v.data();\n }\n if (size) {\n *size = v.size();\n }\n}\n\n/// getter for iteration stats\nvoid faiss_Clustering_iteration_stats(\n FaissClustering* clustering,\n FaissClusteringIterationStats** iteration_stats,\n size_t* size) {\n std::vector& v =\n<|edits_diff|>\n--- c_api/Clustering_c.cpp\n+++ c_api/Clustering_c.cpp\n@@ -20,6 +20,7 @@\n DEFINE_GETTER(Clustering, int, nredo)\n DEFINE_GETTER(Clustering, int, verbose)\n DEFINE_GETTER(Clustering, int, spherical)\n+DEFINE_GETTER(Clustering, int, int_centroids)\n DEFINE_GETTER(Clustering, int, update_index)\n DEFINE_GETTER(Clustering, int, frozen_centroids)\n \n@@ -27,6 +28,7 @@\n DEFINE_GETTER(Clustering, int, max_points_per_centroid)\n \n DEFINE_GETTER(Clustering, int, seed)\n+DEFINE_GETTER(Clustering, size_t, decode_block_size)\n \n /// getter for d\n DEFINE_GETTER(Clustering, size_t, d)\n@@ -49,8 +51,10 @@\n params->nredo = d.nredo;\n params->seed = d.seed;\n params->spherical = d.spherical;\n+ params->int_centroids = d.int_centroids;\n params->update_index = d.update_index;\n params->verbose = d.verbose;\n+ params->decode_block_size = d.decode_block_size;\n }\n \n // This conversion is required because the two types are not memory-compatible\n@@ -65,6 +69,7 @@\n o.seed = params->seed;\n o.spherical = params->spherical;\n o.update_index = params->update_index;\n+ o.int_centroids = params->int_centroids;\n o.verbose = params->verbose;\n return o;\n }\n<|current_version|>\n */\n\n// Copyright 2004-present Facebook. All Rights Reserved.\n// -*- c++ -*-\n\n#include \"Clustering_c.h\"\n#include \n#include \n#include \n#include \"macros_impl.h\"\n\nextern \"C\" {\n\nusing faiss::Clustering;\nusing faiss::ClusteringIterationStats;\nusing faiss::ClusteringParameters;\nusing faiss::Index;\n\nDEFINE_GETTER(Clustering, int, niter)\nDEFINE_GETTER(Clustering, int, nredo)\nDEFINE_GETTER(Clustering, int, verbose)\nDEFINE_GETTER(Clustering, int, spherical)\nDEFINE_GETTER(Clustering, int, int_centroids)\nDEFINE_GETTER(Clustering, int, update_index)\nDEFINE_GETTER(Clustering, int, frozen_centroids)\n\nDEFINE_GETTER(Clustering, int, min_points_per_centroid)\nDEFINE_GETTER(Clustering, int, max_points_per_centroid)\n\nDEFINE_GETTER(Clustering, int, seed)\nDEFINE_GETTER(Clustering, size_t, decode_block_size)\n\n/// getter for d\nDEFINE_GETTER(Clustering, size_t, d)\n\n/// getter for k\nDEFINE_GETTER(Clustering, size_t, k)\n\nDEFINE_GETTER(ClusteringIterationStats, float, obj)\nDEFINE_GETTER(ClusteringIterationStats, double, time)\nDEFINE_GETTER(ClusteringIterationStats, double, time_search)\nDEFINE_GETTER(ClusteringIterationStats, double, imbalance_factor)\nDEFINE_GETTER(ClusteringIterationStats, int, nsplit)\n\nvoid faiss_ClusteringParameters_init(FaissClusteringParameters* params) {\n ClusteringParameters d;\n params->frozen_centroids = d.frozen_centroids;\n params->max_points_per_centroid = d.max_points_per_centroid;\n params->min_points_per_centroid = d.min_points_per_centroid;\n params->niter = d.niter;\n params->nredo = d.nredo;\n params->seed = d.seed;\n params->spherical = d.spherical;\n params->int_centroids = d.int_centroids;\n params->update_index = d.update_index;\n params->verbose = d.verbose;\n params->decode_block_size = d.decode_block_size;\n}\n\n// This conversion is required because the two types are not memory-compatible\ninline ClusteringParameters from_faiss_c(\n const FaissClusteringParameters* params) {\n ClusteringParameters o;\n o.frozen_centroids = params->frozen_centroids;\n o.max_points_per_centroid = params->max_points_per_centroid;\n o.min_points_per_centroid = params->min_points_per_centroid;\n o.niter = params->niter;\n o.nredo = params->nredo;\n o.seed = params->seed;\n o.spherical = params->spherical;\n o.update_index = params->update_index;\n o.int_centroids = params->int_centroids;\n o.verbose = params->verbose;\n return o;\n}\n\n/// getter for centroids (size = k * d)\nvoid faiss_Clustering_centroids(\n FaissClustering* clustering,\n float** centroids,\n size_t* size) {\n std::vector& v =\n reinterpret_cast(clustering)->centroids;\n if (centroids) {\n *centroids = v.data();\n }\n if (size) {\n *size = v.size();\n }\n}\n\n/// getter for iteration stats\nvoid faiss_Clustering_iteration_stats(\n FaissClustering* clustering,\n FaissClusteringIterationStats** iteration_stats,\n size_t* size) {\n std::vector& v =\n<|next_version|>\n */\n\n// Copyright 2004-present Facebook. All Rights Reserved.\n// -*- c++ -*-\n\n#include \"Clustering_c.h\"\n#include \n#include \n#include \n#include \"macros_impl.h\"\n\nextern \"C\" {\n\nusing faiss::Clustering;\nusing faiss::ClusteringIterationStats;\nusing faiss::ClusteringParameters;\nusing faiss::Index;\n\nDEFINE_GETTER(Clustering, int, niter)\nDEFINE_GETTER(Clustering, int, nredo)\nDEFINE_GETTER(Clustering, int, verbose)\nDEFINE_GETTER(Clustering, int, spherical)\nDEFINE_GETTER(Clustering, int, int_centroids)\nDEFINE_GETTER(Clustering, int, update_index)\nDEFINE_GETTER(Clustering, int, frozen_centroids)\n\nDEFINE_GETTER(Clustering, int, min_points_per_centroid)\nDEFINE_GETTER(Clustering, int, max_points_per_centroid)\n\nDEFINE_GETTER(Clustering, int, seed)\nDEFINE_GETTER(Clustering, size_t, decode_block_size)\n\n/// getter for d\nDEFINE_GETTER(Clustering, size_t, d)\n\n/// getter for k\nDEFINE_GETTER(Clustering, size_t, k)\n\nDEFINE_GETTER(ClusteringIterationStats, float, obj)\nDEFINE_GETTER(ClusteringIterationStats, double, time)\nDEFINE_GETTER(ClusteringIterationStats, double, time_search)\nDEFINE_GETTER(ClusteringIterationStats, double, imbalance_factor)\nDEFINE_GETTER(ClusteringIterationStats, int, nsplit)\n\nvoid faiss_ClusteringParameters_init(FaissClusteringParameters* params) {\n ClusteringParameters d;\n params->frozen_centroids = d.frozen_centroids;\n params->max_points_per_centroid = d.max_points_per_centroid;\n params->min_points_per_centroid = d.min_points_per_centroid;\n params->niter = d.niter;\n params->nredo = d.nredo;\n params->seed = d.seed;\n params->spherical = d.spherical;\n params->int_centroids = d.int_centroids;\n params->update_index = d.update_index;\n params->verbose = d.verbose;\n params->decode_block_size = d.decode_block_size;\n}\n\n// This conversion is required because the two types are not memory-compatible\ninline ClusteringParameters from_faiss_c(\n const FaissClusteringParameters* params) {\n ClusteringParameters o;\n o.frozen_centroids = params->frozen_centroids;\n o.max_points_per_centroid = params->max_points_per_centroid;\n o.min_points_per_centroid = params->min_points_per_centroid;\n o.niter = params->niter;\n o.nredo = params->nredo;\n o.seed = params->seed;\n o.spherical = params->spherical;\n o.update_index = params->update_index;\n o.int_centroids = params->int_centroids;\n o.verbose = params->verbose;\n o.decode_block_size = params->decode_block_size;\n return o;\n}\n\n/// getter for centroids (size = k * d)\nvoid faiss_Clustering_centroids(\n FaissClustering* clustering,\n float** centroids,\n size_t* size) {\n std::vector& v =\n reinterpret_cast(clustering)->centroids;\n if (centroids) {\n *centroids = v.data();\n }\n if (size) {\n *size = v.size();\n }\n}\n\n/// getter for iteration stats\nvoid faiss_Clustering_iteration_stats(\n FaissClustering* clustering,\n FaissClusteringIterationStats** iteration_stats,\n size_t* size) {\n std::vector& v =\n"} {"commit": "84de783ce628c184857305f28b57d86fb7cabbcd", "message": "Add support for TS config files (#16828)", "old_file": "tests/integration/run-cli.js", "new_file": "tests/integration/run-cli.js", "status": "M", "old_contents": " resolve(result);\n });\n\n stream.on(\"error\", (error) => {\n reject(error);\n });\n });\n\nconst removeFinalNewLine = (string) =>\n string.endsWith(\"\\n\") ? string.slice(0, -1) : string;\n\nconst SUPPORTS_DISABLE_WARNING_FLAG =\n Number(process.versions.node.split(\".\")[0]) >= 20;\n\nfunction runCliWorker(dir, args, options) {\n const result = {\n status: undefined,\n stdout: \"\",\n stderr: \"\",\n write: [],\n };\n\n const worker = new Worker(CLI_WORKER_FILE, {\n argv: args,\n execArgv: [\n \"--trace-deprecation\",\n ...(SUPPORTS_DISABLE_WARNING_FLAG\n ? [\"--disable-warning=ExperimentalWarning\"]\n : []),\n ],\n stdout: true,\n stderr: true,\n env: {\n ...process.env,\n FORCE_COLOR: 0,\n },\n workerData: {\n dir,\n options,\n },\n trackUnmanagedFds: false,\n });\n\n worker.on(\"message\", ({ action, data }) => {\n if (action === \"write-file\") {\n result.write.push(data);\n }\n });\n\n return new Promise((resolve, reject) => {\n worker.on(\"exit\", async (code) => {\n result.status = code;\n result.stdout = removeFinalNewLine(await streamToString(worker.stdout));", "new_contents": " resolve(result);\n });\n\n stream.on(\"error\", (error) => {\n reject(error);\n });\n });\n\nconst removeFinalNewLine = (string) =>\n string.endsWith(\"\\n\") ? string.slice(0, -1) : string;\n\nconst SUPPORTS_DISABLE_WARNING_FLAG =\n Number(process.versions.node.split(\".\")[0]) >= 20;\n\nfunction runCliWorker(dir, args, options) {\n const result = {\n status: undefined,\n stdout: \"\",\n stderr: \"\",\n write: [],\n };\n\n const nodeOptions = options?.nodeOptions ?? [];\n\n const worker = new Worker(CLI_WORKER_FILE, {\n argv: args,\n execArgv: [\n \"--trace-deprecation\",\n ...(SUPPORTS_DISABLE_WARNING_FLAG\n ? [\"--disable-warning=ExperimentalWarning\"]\n : []),\n ...nodeOptions,\n ],\n stdout: true,\n stderr: true,\n env: {\n ...process.env,\n FORCE_COLOR: 0,\n },\n workerData: {\n dir,\n options,\n },\n trackUnmanagedFds: false,\n });\n\n worker.on(\"message\", ({ action, data }) => {\n if (action === \"write-file\") {\n result.write.push(data);\n }\n });\n\n return new Promise((resolve, reject) => {\n worker.on(\"exit\", async (code) => {\n result.status = code;\n result.stdout = removeFinalNewLine(await streamToString(worker.stdout));", "text": "<|original_code|>\n resolve(result);\n });\n\n stream.on(\"error\", (error) => {\n reject(error);\n });\n });\n\nconst removeFinalNewLine = (string) =>\n string.endsWith(\"\\n\") ? string.slice(0, -1) : string;\n\nconst SUPPORTS_DISABLE_WARNING_FLAG =\n Number(process.versions.node.split(\".\")[0]) >= 20;\n\nfunction runCliWorker(dir, args, options) {\n const result = {\n status: undefined,\n stdout: \"\",\n stderr: \"\",\n write: [],\n };\n\n const worker = new Worker(CLI_WORKER_FILE, {\n argv: args,\n execArgv: [\n \"--trace-deprecation\",\n ...(SUPPORTS_DISABLE_WARNING_FLAG\n ? [\"--disable-warning=ExperimentalWarning\"]\n : []),\n ],\n stdout: true,\n stderr: true,\n env: {\n ...process.env,\n FORCE_COLOR: 0,\n },\n workerData: {\n dir,\n options,\n },\n trackUnmanagedFds: false,\n });\n\n worker.on(\"message\", ({ action, data }) => {\n if (action === \"write-file\") {\n result.write.push(data);\n }\n });\n\n return new Promise((resolve, reject) => {\n worker.on(\"exit\", async (code) => {\n result.status = code;\n result.stdout = removeFinalNewLine(await streamToString(worker.stdout));\n<|edits_diff|>\n--- tests/integration/run-cli.js\n+++ tests/integration/run-cli.js\n@@ -19,6 +19,8 @@\n stderr: \"\",\n write: [],\n };\n+\n+ const nodeOptions = options?.nodeOptions ?? [];\n \n const worker = new Worker(CLI_WORKER_FILE, {\n argv: args,\n<|current_version|>\n resolve(result);\n });\n\n stream.on(\"error\", (error) => {\n reject(error);\n });\n });\n\nconst removeFinalNewLine = (string) =>\n string.endsWith(\"\\n\") ? string.slice(0, -1) : string;\n\nconst SUPPORTS_DISABLE_WARNING_FLAG =\n Number(process.versions.node.split(\".\")[0]) >= 20;\n\nfunction runCliWorker(dir, args, options) {\n const result = {\n status: undefined,\n stdout: \"\",\n stderr: \"\",\n write: [],\n };\n\n const nodeOptions = options?.nodeOptions ?? [];\n\n const worker = new Worker(CLI_WORKER_FILE, {\n argv: args,\n execArgv: [\n \"--trace-deprecation\",\n ...(SUPPORTS_DISABLE_WARNING_FLAG\n ? [\"--disable-warning=ExperimentalWarning\"]\n : []),\n ],\n stdout: true,\n stderr: true,\n env: {\n ...process.env,\n FORCE_COLOR: 0,\n },\n workerData: {\n dir,\n options,\n },\n trackUnmanagedFds: false,\n });\n\n worker.on(\"message\", ({ action, data }) => {\n if (action === \"write-file\") {\n result.write.push(data);\n }\n });\n\n return new Promise((resolve, reject) => {\n worker.on(\"exit\", async (code) => {\n result.status = code;\n result.stdout = removeFinalNewLine(await streamToString(worker.stdout));\n<|next_version|>\n resolve(result);\n });\n\n stream.on(\"error\", (error) => {\n reject(error);\n });\n });\n\nconst removeFinalNewLine = (string) =>\n string.endsWith(\"\\n\") ? string.slice(0, -1) : string;\n\nconst SUPPORTS_DISABLE_WARNING_FLAG =\n Number(process.versions.node.split(\".\")[0]) >= 20;\n\nfunction runCliWorker(dir, args, options) {\n const result = {\n status: undefined,\n stdout: \"\",\n stderr: \"\",\n write: [],\n };\n\n const nodeOptions = options?.nodeOptions ?? [];\n\n const worker = new Worker(CLI_WORKER_FILE, {\n argv: args,\n execArgv: [\n \"--trace-deprecation\",\n ...(SUPPORTS_DISABLE_WARNING_FLAG\n ? [\"--disable-warning=ExperimentalWarning\"]\n : []),\n ...nodeOptions,\n ],\n stdout: true,\n stderr: true,\n env: {\n ...process.env,\n FORCE_COLOR: 0,\n },\n workerData: {\n dir,\n options,\n },\n trackUnmanagedFds: false,\n });\n\n worker.on(\"message\", ({ action, data }) => {\n if (action === \"write-file\") {\n result.write.push(data);\n }\n });\n\n return new Promise((resolve, reject) => {\n worker.on(\"exit\", async (code) => {\n result.status = code;\n result.stdout = removeFinalNewLine(await streamToString(worker.stdout));\n", "current_contents": " resolve(result);\n });\n\n stream.on(\"error\", (error) => {\n reject(error);\n });\n });\n\nconst removeFinalNewLine = (string) =>\n string.endsWith(\"\\n\") ? string.slice(0, -1) : string;\n\nconst SUPPORTS_DISABLE_WARNING_FLAG =\n Number(process.versions.node.split(\".\")[0]) >= 20;\n\nfunction runCliWorker(dir, args, options) {\n const result = {\n status: undefined,\n stdout: \"\",\n stderr: \"\",\n write: [],\n };\n\n const nodeOptions = options?.nodeOptions ?? [];\n\n const worker = new Worker(CLI_WORKER_FILE, {\n argv: args,\n execArgv: [\n \"--trace-deprecation\",\n ...(SUPPORTS_DISABLE_WARNING_FLAG\n ? [\"--disable-warning=ExperimentalWarning\"]\n : []),\n ],\n stdout: true,\n stderr: true,\n env: {\n ...process.env,\n FORCE_COLOR: 0,\n },\n workerData: {\n dir,\n options,\n },\n trackUnmanagedFds: false,\n });\n\n worker.on(\"message\", ({ action, data }) => {\n if (action === \"write-file\") {\n result.write.push(data);\n }\n });\n\n return new Promise((resolve, reject) => {\n worker.on(\"exit\", async (code) => {\n result.status = code;\n result.stdout = removeFinalNewLine(await streamToString(worker.stdout));"} {"commit": "d2c415deae368e7224e315bf69bf2e89129cd4d9", "message": "Update meriyah to v6 (#16667)", "old_file": "tests/format/js/strings/format.test.js", "new_file": "tests/format/js/strings/format.test.js", "status": "M", "old_contents": "runFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"es5\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n },\n});\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"all\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n },\n});\n", "new_contents": "runFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"es5\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n meriyah: [\"non-octal-eight-and-nine.js\"],\n },\n});\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"all\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n meriyah: [\"non-octal-eight-and-nine.js\"],\n },\n});\n", "text": "<|original_code|>\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"es5\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n },\n});\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"all\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n },\n});\n\n<|edits_diff|>\n--- tests/format/js/strings/format.test.js\n+++ tests/format/js/strings/format.test.js\n@@ -3,6 +3,7 @@\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n+ meriyah: [\"non-octal-eight-and-nine.js\"],\n },\n });\n runFormatTest(import.meta, [\"babel\", \"flow\"], {\n<|current_version|>\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"es5\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n meriyah: [\"non-octal-eight-and-nine.js\"],\n },\n});\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"all\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n },\n});\n\n<|next_version|>\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"es5\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n meriyah: [\"non-octal-eight-and-nine.js\"],\n },\n});\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"all\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n meriyah: [\"non-octal-eight-and-nine.js\"],\n },\n});\n\n", "current_contents": "runFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"es5\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n meriyah: [\"non-octal-eight-and-nine.js\"],\n },\n});\nrunFormatTest(import.meta, [\"babel\", \"flow\"], {\n trailingComma: \"all\",\n errors: {\n acorn: [\"non-octal-eight-and-nine.js\"],\n espree: [\"non-octal-eight-and-nine.js\"],\n },\n});\n"} {"commit": "105bb7beffae44972a29c3b20d25227ae5e2f713", "message": "Flow: add support for bigint enums (#16268)", "old_file": "src/language-js/print/enum.js", "new_file": "src/language-js/print/enum.js", "status": "M", "old_contents": "import { printDeclareToken } from \"./misc.js\";\nimport { printObject } from \"./object.js\";\n\nfunction printEnumMembers(path, print, options) {\n return printObject(path, options, print);\n}\n\n/*\n- `EnumBooleanMember`(flow)\n- `EnumNumberMember`(flow)\n- `EnumStringMember`(flow)\n- `EnumDefaultedMember`(flow)\n- `TSEnumMember`(TypeScript)\n*/\nfunction printEnumMember(path, print) {\n const { node } = path;\n\n let idDoc = print(\"id\");\n\n if (node.computed) {\n idDoc = [\"[\", idDoc, \"]\"];\n }\n\n let initializerDoc = \"\";\n\n // `TSEnumMember`\n if (node.initializer) {\n initializerDoc = print(\"initializer\");\n }\n\n // Flow\n if (node.init) {\n initializerDoc = print(\"init\");\n }\n\n if (!initializerDoc) {\n return idDoc;\n }\n\n return [idDoc, \" = \", initializerDoc];\n}\n\n/*\n- `EnumBooleanBody`(flow)\n- `EnumNumberBody`(flow)\n- `EnumStringBody`(flow)\n- `EnumSymbolBody`(flow)\n*/\nfunction printEnumBody(path, print, options) {\n const { node } = path;\n let type;\n\n if (node.type === \"EnumSymbolBody\" || node.explicitType) {\n switch (node.type) {\n case \"EnumBooleanBody\":\n type = \"boolean\";\n break;\n case \"EnumNumberBody\":\n type = \"number\";\n break;\n case \"EnumStringBody\":\n type = \"string\";\n break;\n case \"EnumSymbolBody\":\n type = \"symbol\";\n break;\n }\n }\n\n return [type ? `of ${type} ` : \"\", printEnumMembers(path, print, options)];\n}\n\n/*\n- `DeclareEnum`(flow)\n- `EnumDeclaration`(flow)\n- `TSEnumDeclaration`(TypeScript)\n*/\nfunction printEnumDeclaration(path, print, options) {\n const { node } = path;\n return [\n printDeclareToken(path),\n node.const ? \"const \" : \"\",\n \"enum \",", "new_contents": "import { printDeclareToken } from \"./misc.js\";\nimport { printObject } from \"./object.js\";\n\nfunction printEnumMembers(path, print, options) {\n return printObject(path, options, print);\n}\n\n/*\n- `EnumBooleanMember`(flow)\n- `EnumNumberMember`(flow)\n- `EnumBigIntMember`(flow)\n- `EnumStringMember`(flow)\n- `EnumDefaultedMember`(flow)\n- `TSEnumMember`(TypeScript)\n*/\nfunction printEnumMember(path, print) {\n const { node } = path;\n\n let idDoc = print(\"id\");\n\n if (node.computed) {\n idDoc = [\"[\", idDoc, \"]\"];\n }\n\n let initializerDoc = \"\";\n\n // `TSEnumMember`\n if (node.initializer) {\n initializerDoc = print(\"initializer\");\n }\n\n // Flow\n if (node.init) {\n initializerDoc = print(\"init\");\n }\n\n if (!initializerDoc) {\n return idDoc;\n }\n\n return [idDoc, \" = \", initializerDoc];\n}\n\n/*\n- `EnumBooleanBody`(flow)\n- `EnumNumberBody`(flow)\n- `EnumBigIntBody`(flow)\n- `EnumStringBody`(flow)\n- `EnumSymbolBody`(flow)\n*/\nfunction printEnumBody(path, print, options) {\n const { node } = path;\n let type;\n\n if (node.type === \"EnumSymbolBody\" || node.explicitType) {\n switch (node.type) {\n case \"EnumBooleanBody\":\n type = \"boolean\";\n break;\n case \"EnumNumberBody\":\n type = \"number\";\n break;\n case \"EnumBigIntBody\":\n type = \"bigint\";\n break;\n case \"EnumStringBody\":\n type = \"string\";\n break;\n case \"EnumSymbolBody\":\n type = \"symbol\";\n break;\n }\n }\n\n return [type ? `of ${type} ` : \"\", printEnumMembers(path, print, options)];\n}\n\n/*\n- `DeclareEnum`(flow)\n- `EnumDeclaration`(flow)\n- `TSEnumDeclaration`(TypeScript)\n*/\nfunction printEnumDeclaration(path, print, options) {\n const { node } = path;\n return [\n printDeclareToken(path),\n node.const ? \"const \" : \"\",\n \"enum \",", "text": "<|original_code|>\nimport { printDeclareToken } from \"./misc.js\";\nimport { printObject } from \"./object.js\";\n\nfunction printEnumMembers(path, print, options) {\n return printObject(path, options, print);\n}\n\n/*\n- `EnumBooleanMember`(flow)\n- `EnumNumberMember`(flow)\n- `EnumStringMember`(flow)\n- `EnumDefaultedMember`(flow)\n- `TSEnumMember`(TypeScript)\n*/\nfunction printEnumMember(path, print) {\n const { node } = path;\n\n let idDoc = print(\"id\");\n\n if (node.computed) {\n idDoc = [\"[\", idDoc, \"]\"];\n }\n\n let initializerDoc = \"\";\n\n // `TSEnumMember`\n if (node.initializer) {\n initializerDoc = print(\"initializer\");\n }\n\n // Flow\n if (node.init) {\n initializerDoc = print(\"init\");\n }\n\n if (!initializerDoc) {\n return idDoc;\n }\n\n return [idDoc, \" = \", initializerDoc];\n}\n\n/*\n- `EnumBooleanBody`(flow)\n- `EnumNumberBody`(flow)\n- `EnumStringBody`(flow)\n- `EnumSymbolBody`(flow)\n*/\nfunction printEnumBody(path, print, options) {\n const { node } = path;\n let type;\n\n if (node.type === \"EnumSymbolBody\" || node.explicitType) {\n switch (node.type) {\n case \"EnumBooleanBody\":\n type = \"boolean\";\n break;\n case \"EnumNumberBody\":\n type = \"number\";\n break;\n case \"EnumStringBody\":\n type = \"string\";\n break;\n case \"EnumSymbolBody\":\n type = \"symbol\";\n break;\n }\n }\n\n return [type ? `of ${type} ` : \"\", printEnumMembers(path, print, options)];\n}\n\n/*\n- `DeclareEnum`(flow)\n- `EnumDeclaration`(flow)\n- `TSEnumDeclaration`(TypeScript)\n*/\nfunction printEnumDeclaration(path, print, options) {\n const { node } = path;\n return [\n printDeclareToken(path),\n node.const ? \"const \" : \"\",\n \"enum \",\n<|edits_diff|>\n--- src/language-js/print/enum.js\n+++ src/language-js/print/enum.js\n@@ -8,6 +8,7 @@\n /*\n - `EnumBooleanMember`(flow)\n - `EnumNumberMember`(flow)\n+- `EnumBigIntMember`(flow)\n - `EnumStringMember`(flow)\n - `EnumDefaultedMember`(flow)\n - `TSEnumMember`(TypeScript)\n@@ -43,6 +44,7 @@\n /*\n - `EnumBooleanBody`(flow)\n - `EnumNumberBody`(flow)\n+- `EnumBigIntBody`(flow)\n - `EnumStringBody`(flow)\n - `EnumSymbolBody`(flow)\n */\n<|current_version|>\nimport { printDeclareToken } from \"./misc.js\";\nimport { printObject } from \"./object.js\";\n\nfunction printEnumMembers(path, print, options) {\n return printObject(path, options, print);\n}\n\n/*\n- `EnumBooleanMember`(flow)\n- `EnumNumberMember`(flow)\n- `EnumBigIntMember`(flow)\n- `EnumStringMember`(flow)\n- `EnumDefaultedMember`(flow)\n- `TSEnumMember`(TypeScript)\n*/\nfunction printEnumMember(path, print) {\n const { node } = path;\n\n let idDoc = print(\"id\");\n\n if (node.computed) {\n idDoc = [\"[\", idDoc, \"]\"];\n }\n\n let initializerDoc = \"\";\n\n // `TSEnumMember`\n if (node.initializer) {\n initializerDoc = print(\"initializer\");\n }\n\n // Flow\n if (node.init) {\n initializerDoc = print(\"init\");\n }\n\n if (!initializerDoc) {\n return idDoc;\n }\n\n return [idDoc, \" = \", initializerDoc];\n}\n\n/*\n- `EnumBooleanBody`(flow)\n- `EnumNumberBody`(flow)\n- `EnumBigIntBody`(flow)\n- `EnumStringBody`(flow)\n- `EnumSymbolBody`(flow)\n*/\nfunction printEnumBody(path, print, options) {\n const { node } = path;\n let type;\n\n if (node.type === \"EnumSymbolBody\" || node.explicitType) {\n switch (node.type) {\n case \"EnumBooleanBody\":\n type = \"boolean\";\n break;\n case \"EnumNumberBody\":\n type = \"number\";\n break;\n case \"EnumStringBody\":\n type = \"string\";\n break;\n case \"EnumSymbolBody\":\n type = \"symbol\";\n break;\n }\n }\n\n return [type ? `of ${type} ` : \"\", printEnumMembers(path, print, options)];\n}\n\n/*\n- `DeclareEnum`(flow)\n- `EnumDeclaration`(flow)\n- `TSEnumDeclaration`(TypeScript)\n*/\nfunction printEnumDeclaration(path, print, options) {\n const { node } = path;\n return [\n printDeclareToken(path),\n node.const ? \"const \" : \"\",\n \"enum \",\n<|next_version|>\nimport { printDeclareToken } from \"./misc.js\";\nimport { printObject } from \"./object.js\";\n\nfunction printEnumMembers(path, print, options) {\n return printObject(path, options, print);\n}\n\n/*\n- `EnumBooleanMember`(flow)\n- `EnumNumberMember`(flow)\n- `EnumBigIntMember`(flow)\n- `EnumStringMember`(flow)\n- `EnumDefaultedMember`(flow)\n- `TSEnumMember`(TypeScript)\n*/\nfunction printEnumMember(path, print) {\n const { node } = path;\n\n let idDoc = print(\"id\");\n\n if (node.computed) {\n idDoc = [\"[\", idDoc, \"]\"];\n }\n\n let initializerDoc = \"\";\n\n // `TSEnumMember`\n if (node.initializer) {\n initializerDoc = print(\"initializer\");\n }\n\n // Flow\n if (node.init) {\n initializerDoc = print(\"init\");\n }\n\n if (!initializerDoc) {\n return idDoc;\n }\n\n return [idDoc, \" = \", initializerDoc];\n}\n\n/*\n- `EnumBooleanBody`(flow)\n- `EnumNumberBody`(flow)\n- `EnumBigIntBody`(flow)\n- `EnumStringBody`(flow)\n- `EnumSymbolBody`(flow)\n*/\nfunction printEnumBody(path, print, options) {\n const { node } = path;\n let type;\n\n if (node.type === \"EnumSymbolBody\" || node.explicitType) {\n switch (node.type) {\n case \"EnumBooleanBody\":\n type = \"boolean\";\n break;\n case \"EnumNumberBody\":\n type = \"number\";\n break;\n case \"EnumBigIntBody\":\n type = \"bigint\";\n break;\n case \"EnumStringBody\":\n type = \"string\";\n break;\n case \"EnumSymbolBody\":\n type = \"symbol\";\n break;\n }\n }\n\n return [type ? `of ${type} ` : \"\", printEnumMembers(path, print, options)];\n}\n\n/*\n- `DeclareEnum`(flow)\n- `EnumDeclaration`(flow)\n- `TSEnumDeclaration`(TypeScript)\n*/\nfunction printEnumDeclaration(path, print, options) {\n const { node } = path;\n return [\n printDeclareToken(path),\n node.const ? \"const \" : \"\",\n \"enum \",\n", "current_contents": "import { printDeclareToken } from \"./misc.js\";\nimport { printObject } from \"./object.js\";\n\nfunction printEnumMembers(path, print, options) {\n return printObject(path, options, print);\n}\n\n/*\n- `EnumBooleanMember`(flow)\n- `EnumNumberMember`(flow)\n- `EnumBigIntMember`(flow)\n- `EnumStringMember`(flow)\n- `EnumDefaultedMember`(flow)\n- `TSEnumMember`(TypeScript)\n*/\nfunction printEnumMember(path, print) {\n const { node } = path;\n\n let idDoc = print(\"id\");\n\n if (node.computed) {\n idDoc = [\"[\", idDoc, \"]\"];\n }\n\n let initializerDoc = \"\";\n\n // `TSEnumMember`\n if (node.initializer) {\n initializerDoc = print(\"initializer\");\n }\n\n // Flow\n if (node.init) {\n initializerDoc = print(\"init\");\n }\n\n if (!initializerDoc) {\n return idDoc;\n }\n\n return [idDoc, \" = \", initializerDoc];\n}\n\n/*\n- `EnumBooleanBody`(flow)\n- `EnumNumberBody`(flow)\n- `EnumBigIntBody`(flow)\n- `EnumStringBody`(flow)\n- `EnumSymbolBody`(flow)\n*/\nfunction printEnumBody(path, print, options) {\n const { node } = path;\n let type;\n\n if (node.type === \"EnumSymbolBody\" || node.explicitType) {\n switch (node.type) {\n case \"EnumBooleanBody\":\n type = \"boolean\";\n break;\n case \"EnumNumberBody\":\n type = \"number\";\n break;\n case \"EnumStringBody\":\n type = \"string\";\n break;\n case \"EnumSymbolBody\":\n type = \"symbol\";\n break;\n }\n }\n\n return [type ? `of ${type} ` : \"\", printEnumMembers(path, print, options)];\n}\n\n/*\n- `DeclareEnum`(flow)\n- `EnumDeclaration`(flow)\n- `TSEnumDeclaration`(TypeScript)\n*/\nfunction printEnumDeclaration(path, print, options) {\n const { node } = path;\n return [\n printDeclareToken(path),\n node.const ? \"const \" : \"\",\n \"enum \","} {"commit": "b9d0c993b9089dda7292046f54e31d72d5058ee9", "message": "Use `Array#findLast()` (#15805)", "old_file": "scripts/build/transform/transforms/index.js", "new_file": "scripts/build/transform/transforms/index.js", "status": "M", "old_contents": "import transformObjectHasOwnCall from \"./transform-object-has-own.js\";\nimport transformRelativeIndexing from \"./transform-relative-indexing.js\";\nimport transformStringReplaceAll from \"./transform-string-replace-all.js\";\n\nexport default [\n transformObjectHasOwnCall,\n transformRelativeIndexing,\n transformStringReplaceAll,\n];\n", "new_contents": "import transformObjectHasOwnCall from \"./transform-object-has-own.js\";\nimport transformRelativeIndexing from \"./transform-relative-indexing.js\";\nimport transformStringReplaceAll from \"./transform-string-replace-all.js\";\nimport transformArrayFindLast from \"./transform-array-find-last.js\";\n\nexport default [\n transformObjectHasOwnCall,\n transformRelativeIndexing,\n transformStringReplaceAll,\n transformArrayFindLast,\n];\n", "text": "<|original_code|>\nimport transformObjectHasOwnCall from \"./transform-object-has-own.js\";\nimport transformRelativeIndexing from \"./transform-relative-indexing.js\";\nimport transformStringReplaceAll from \"./transform-string-replace-all.js\";\n\nexport default [\n transformObjectHasOwnCall,\n transformRelativeIndexing,\n transformStringReplaceAll,\n];\n\n<|edits_diff|>\n--- scripts/build/transform/transforms/index.js\n+++ scripts/build/transform/transforms/index.js\n@@ -1,6 +1,7 @@\n import transformObjectHasOwnCall from \"./transform-object-has-own.js\";\n import transformRelativeIndexing from \"./transform-relative-indexing.js\";\n import transformStringReplaceAll from \"./transform-string-replace-all.js\";\n+import transformArrayFindLast from \"./transform-array-find-last.js\";\n \n export default [\n transformObjectHasOwnCall,\n<|current_version|>\nimport transformObjectHasOwnCall from \"./transform-object-has-own.js\";\nimport transformRelativeIndexing from \"./transform-relative-indexing.js\";\nimport transformStringReplaceAll from \"./transform-string-replace-all.js\";\nimport transformArrayFindLast from \"./transform-array-find-last.js\";\n\nexport default [\n transformObjectHasOwnCall,\n transformRelativeIndexing,\n transformStringReplaceAll,\n];\n\n<|next_version|>\nimport transformObjectHasOwnCall from \"./transform-object-has-own.js\";\nimport transformRelativeIndexing from \"./transform-relative-indexing.js\";\nimport transformStringReplaceAll from \"./transform-string-replace-all.js\";\nimport transformArrayFindLast from \"./transform-array-find-last.js\";\n\nexport default [\n transformObjectHasOwnCall,\n transformRelativeIndexing,\n transformStringReplaceAll,\n transformArrayFindLast,\n];\n\n", "current_contents": "import transformObjectHasOwnCall from \"./transform-object-has-own.js\";\nimport transformRelativeIndexing from \"./transform-relative-indexing.js\";\nimport transformStringReplaceAll from \"./transform-string-replace-all.js\";\nimport transformArrayFindLast from \"./transform-array-find-last.js\";\n\nexport default [\n transformObjectHasOwnCall,\n transformRelativeIndexing,\n transformStringReplaceAll,\n];\n"} {"commit": "863368e1ba915eb885eca20c493ddad740cb8df2", "message": "Add `--next` flag to release script (#15816)", "old_file": "scripts/release/parse-arguments.js", "new_file": "scripts/release/parse-arguments.js", "status": "M", "old_contents": "import { parseArgs } from \"node:util\";\n\nfunction parseArguments() {\n const {\n values: {\n version,\n repo = \"git@github.com:prettier/prettier.git\",\n manual = false,\n dry = false,\n \"skip-dependencies-install\": skipDependenciesInstall = false,\n },\n } = parseArgs({\n options: {\n version: {\n type: \"string\",\n },\n repo: {\n type: \"string\",\n },\n dry: {\n type: \"boolean\",\n },\n manual: {\n type: \"boolean\",\n },\n \"skip-dependencies-install\": {\n type: \"boolean\",\n },\n },\n });\n\n return {\n version,\n repo,\n manual,\n dry,\n skipDependenciesInstall,\n };\n}\n\nexport default parseArguments;\n", "new_contents": "import { parseArgs } from \"node:util\";\n\nfunction parseArguments() {\n const {\n values: {\n version,\n repo = \"git@github.com:prettier/prettier.git\",\n manual = false,\n dry = false,\n \"skip-dependencies-install\": skipDependenciesInstall = false,\n next = false,\n },\n } = parseArgs({\n options: {\n version: {\n type: \"string\",\n },\n repo: {\n type: \"string\",\n },\n dry: {\n type: \"boolean\",\n },\n manual: {\n type: \"boolean\",\n },\n \"skip-dependencies-install\": {\n type: \"boolean\",\n },\n next: {\n type: \"boolean\",\n },\n },\n });\n\n return {\n version,\n repo,\n manual,\n dry,\n skipDependenciesInstall,\n next,\n };\n}\n\nexport default parseArguments;\n", "text": "<|original_code|>\nimport { parseArgs } from \"node:util\";\n\nfunction parseArguments() {\n const {\n values: {\n version,\n repo = \"git@github.com:prettier/prettier.git\",\n manual = false,\n dry = false,\n \"skip-dependencies-install\": skipDependenciesInstall = false,\n },\n } = parseArgs({\n options: {\n version: {\n type: \"string\",\n },\n repo: {\n type: \"string\",\n },\n dry: {\n type: \"boolean\",\n },\n manual: {\n type: \"boolean\",\n },\n \"skip-dependencies-install\": {\n type: \"boolean\",\n },\n },\n });\n\n return {\n version,\n repo,\n manual,\n dry,\n skipDependenciesInstall,\n };\n}\n\nexport default parseArguments;\n\n<|edits_diff|>\n--- scripts/release/parse-arguments.js\n+++ scripts/release/parse-arguments.js\n@@ -8,6 +8,7 @@\n manual = false,\n dry = false,\n \"skip-dependencies-install\": skipDependenciesInstall = false,\n+ next = false,\n },\n } = parseArgs({\n options: {\n@@ -26,6 +27,9 @@\n \"skip-dependencies-install\": {\n type: \"boolean\",\n },\n+ next: {\n+ type: \"boolean\",\n+ },\n },\n });\n \n<|current_version|>\nimport { parseArgs } from \"node:util\";\n\nfunction parseArguments() {\n const {\n values: {\n version,\n repo = \"git@github.com:prettier/prettier.git\",\n manual = false,\n dry = false,\n \"skip-dependencies-install\": skipDependenciesInstall = false,\n next = false,\n },\n } = parseArgs({\n options: {\n version: {\n type: \"string\",\n },\n repo: {\n type: \"string\",\n },\n dry: {\n type: \"boolean\",\n },\n manual: {\n type: \"boolean\",\n },\n \"skip-dependencies-install\": {\n type: \"boolean\",\n },\n next: {\n type: \"boolean\",\n },\n },\n });\n\n return {\n version,\n repo,\n manual,\n dry,\n skipDependenciesInstall,\n };\n}\n\nexport default parseArguments;\n\n<|next_version|>\nimport { parseArgs } from \"node:util\";\n\nfunction parseArguments() {\n const {\n values: {\n version,\n repo = \"git@github.com:prettier/prettier.git\",\n manual = false,\n dry = false,\n \"skip-dependencies-install\": skipDependenciesInstall = false,\n next = false,\n },\n } = parseArgs({\n options: {\n version: {\n type: \"string\",\n },\n repo: {\n type: \"string\",\n },\n dry: {\n type: \"boolean\",\n },\n manual: {\n type: \"boolean\",\n },\n \"skip-dependencies-install\": {\n type: \"boolean\",\n },\n next: {\n type: \"boolean\",\n },\n },\n });\n\n return {\n version,\n repo,\n manual,\n dry,\n skipDependenciesInstall,\n next,\n };\n}\n\nexport default parseArguments;\n\n", "current_contents": "import { parseArgs } from \"node:util\";\n\nfunction parseArguments() {\n const {\n values: {\n version,\n repo = \"git@github.com:prettier/prettier.git\",\n manual = false,\n dry = false,\n \"skip-dependencies-install\": skipDependenciesInstall = false,\n next = false,\n },\n } = parseArgs({\n options: {\n version: {\n type: \"string\",\n },\n repo: {\n type: \"string\",\n },\n dry: {\n type: \"boolean\",\n },\n manual: {\n type: \"boolean\",\n },\n \"skip-dependencies-install\": {\n type: \"boolean\",\n },\n next: {\n type: \"boolean\",\n },\n },\n });\n\n return {\n version,\n repo,\n manual,\n dry,\n skipDependenciesInstall,\n };\n}\n\nexport default parseArguments;\n"} {"commit": "97fda8c11d829d649c9d5d0b04885e7762b53b47", "message": "Remove `showInternal` option from `getSupportInfo()` (#14621)", "old_file": "src/index.js", "new_file": "src/index.js", "status": "M", "old_contents": "import * as core from \"./main/core.js\";\nimport { getSupportInfo as getSupportInfoWithoutPlugins } from \"./main/support.js\";\nimport getFileInfoWithoutPlugins from \"./common/get-file-info.js\";\nimport {\n loadBuiltinPlugins,\n loadPlugins,\n searchPlugins,\n clearCache as clearPluginCache,\n} from \"./main/plugins/index.js\";\nimport {\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n} from \"./config/resolve-config.js\";\nimport * as errors from \"./common/errors.js\";\nimport * as coreOptions from \"./main/core-options.evaluate.js\";\nimport { createIsIgnoredFunction } from \"./utils/ignore.js\";\nimport { formatOptionsHiddenDefaults } from \"./main/normalize-format-options.js\";\nimport normalizeOptions from \"./main/normalize-options.js\";\nimport arrayify from \"./utils/arrayify.js\";\nimport partition from \"./utils/partition.js\";\nimport isNonEmptyArray from \"./utils/is-non-empty-array.js\";\n\n/**\n * @param {*} fn\n * @param {number} [optionsArgumentIndex]\n * @returns {*}\n */\nfunction withPlugins(\n fn,\n optionsArgumentIndex = 1 // Usually `options` is the 2nd argument\n) {\n return async (...args) => {\n const options = args[optionsArgumentIndex] ?? {};\n const { plugins = [], pluginSearchDirs } = options;\n\n args[optionsArgumentIndex] = {\n ...options,\n plugins: (\n await Promise.all([\n loadBuiltinPlugins(),\n // TODO: standalone version allow `plugins` to be `prettierPlugins` which is an object, should allow that too\n loadPlugins(plugins),\n options.pluginSearchDirs === false\n ? []\n : searchPlugins(pluginSearchDirs),\n ])\n ).flat(),\n };\n\n return fn(...args);\n };\n}\n\nconst formatWithCursor = withPlugins(core.formatWithCursor);\n\nasync function format(text, options) {\n const { formatted } = await formatWithCursor(text, {\n ...options,\n cursorOffset: -1,\n });\n return formatted;\n}\n\nasync function check(text, options) {\n return (await format(text, options)) === text;\n}\n\n// eslint-disable-next-line require-await\nasync function clearCache() {\n clearConfigCache();\n clearPluginCache();\n}\n\n/** @type {typeof getFileInfoWithoutPlugins} */\nconst getFileInfo = withPlugins(getFileInfoWithoutPlugins);\n\n/** @type {typeof getSupportInfoWithoutPlugins} */\nconst getSupportInfo = withPlugins(getSupportInfoWithoutPlugins, 0);\n\n// Internal shared with cli\nconst sharedWithCli = {\n errors,\n coreOptions,\n createIsIgnoredFunction,\n formatOptionsHiddenDefaults,\n normalizeOptions,\n getSupportInfoWithoutPlugins,\n vnopts,\n fastGlob,\n utils: {\n arrayify,\n isNonEmptyArray,\n partition,\n },\n};\n\nconst debugApis = {\n parse: withPlugins(core.parse),\n formatAST: withPlugins(core.formatAst),\n formatDoc: withPlugins(core.formatDoc),\n printToDoc: withPlugins(core.printToDoc),\n printDocToString: withPlugins(core.printDocToString),\n};\n\nexport {\n formatWithCursor,\n format,\n check,\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n getFileInfo,\n getSupportInfo,\n sharedWithCli as __internal,\n debugApis as __debug,\n};\nexport * as util from \"./utils/public.js\";", "new_contents": "import * as core from \"./main/core.js\";\nimport { getSupportInfo as getSupportInfoWithoutPlugins } from \"./main/support.js\";\nimport getFileInfoWithoutPlugins from \"./common/get-file-info.js\";\nimport {\n loadBuiltinPlugins,\n loadPlugins,\n searchPlugins,\n clearCache as clearPluginCache,\n} from \"./main/plugins/index.js\";\nimport {\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n} from \"./config/resolve-config.js\";\nimport * as errors from \"./common/errors.js\";\nimport * as coreOptions from \"./main/core-options.evaluate.js\";\nimport { createIsIgnoredFunction } from \"./utils/ignore.js\";\nimport { formatOptionsHiddenDefaults } from \"./main/normalize-format-options.js\";\nimport normalizeOptions from \"./main/normalize-options.js\";\nimport arrayify from \"./utils/arrayify.js\";\nimport partition from \"./utils/partition.js\";\nimport isNonEmptyArray from \"./utils/is-non-empty-array.js\";\nimport omit from \"./utils/object-omit.js\";\n\n/**\n * @param {*} fn\n * @param {number} [optionsArgumentIndex]\n * @returns {*}\n */\nfunction withPlugins(\n fn,\n optionsArgumentIndex = 1 // Usually `options` is the 2nd argument\n) {\n return async (...args) => {\n const options = args[optionsArgumentIndex] ?? {};\n const { plugins = [], pluginSearchDirs } = options;\n\n args[optionsArgumentIndex] = {\n ...options,\n plugins: (\n await Promise.all([\n loadBuiltinPlugins(),\n // TODO: standalone version allow `plugins` to be `prettierPlugins` which is an object, should allow that too\n loadPlugins(plugins),\n options.pluginSearchDirs === false\n ? []\n : searchPlugins(pluginSearchDirs),\n ])\n ).flat(),\n };\n\n return fn(...args);\n };\n}\n\nconst formatWithCursor = withPlugins(core.formatWithCursor);\n\nasync function format(text, options) {\n const { formatted } = await formatWithCursor(text, {\n ...options,\n cursorOffset: -1,\n });\n return formatted;\n}\n\nasync function check(text, options) {\n return (await format(text, options)) === text;\n}\n\n// eslint-disable-next-line require-await\nasync function clearCache() {\n clearConfigCache();\n clearPluginCache();\n}\n\n/** @type {typeof getFileInfoWithoutPlugins} */\nconst getFileInfo = withPlugins(getFileInfoWithoutPlugins);\n\n/** @type {typeof getSupportInfoWithoutPlugins} */\nconst getSupportInfo = withPlugins(getSupportInfoWithoutPlugins, 0);\n\n// Internal shared with cli\nconst sharedWithCli = {\n errors,\n coreOptions,\n createIsIgnoredFunction,\n formatOptionsHiddenDefaults,\n normalizeOptions,\n getSupportInfoWithoutPlugins,\n vnopts,\n fastGlob,\n utils: {\n arrayify,\n isNonEmptyArray,\n partition,\n omit,\n },\n};\n\nconst debugApis = {\n parse: withPlugins(core.parse),\n formatAST: withPlugins(core.formatAst),\n formatDoc: withPlugins(core.formatDoc),\n printToDoc: withPlugins(core.printToDoc),\n printDocToString: withPlugins(core.printDocToString),\n};\n\nexport {\n formatWithCursor,\n format,\n check,\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n getFileInfo,\n getSupportInfo,\n sharedWithCli as __internal,\n debugApis as __debug,\n};\nexport * as util from \"./utils/public.js\";", "text": "<|original_code|>\nimport * as core from \"./main/core.js\";\nimport { getSupportInfo as getSupportInfoWithoutPlugins } from \"./main/support.js\";\nimport getFileInfoWithoutPlugins from \"./common/get-file-info.js\";\nimport {\n loadBuiltinPlugins,\n loadPlugins,\n searchPlugins,\n clearCache as clearPluginCache,\n} from \"./main/plugins/index.js\";\nimport {\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n} from \"./config/resolve-config.js\";\nimport * as errors from \"./common/errors.js\";\nimport * as coreOptions from \"./main/core-options.evaluate.js\";\nimport { createIsIgnoredFunction } from \"./utils/ignore.js\";\nimport { formatOptionsHiddenDefaults } from \"./main/normalize-format-options.js\";\nimport normalizeOptions from \"./main/normalize-options.js\";\nimport arrayify from \"./utils/arrayify.js\";\nimport partition from \"./utils/partition.js\";\nimport isNonEmptyArray from \"./utils/is-non-empty-array.js\";\n\n/**\n * @param {*} fn\n * @param {number} [optionsArgumentIndex]\n * @returns {*}\n */\nfunction withPlugins(\n fn,\n optionsArgumentIndex = 1 // Usually `options` is the 2nd argument\n) {\n return async (...args) => {\n const options = args[optionsArgumentIndex] ?? {};\n const { plugins = [], pluginSearchDirs } = options;\n\n args[optionsArgumentIndex] = {\n ...options,\n plugins: (\n await Promise.all([\n loadBuiltinPlugins(),\n // TODO: standalone version allow `plugins` to be `prettierPlugins` which is an object, should allow that too\n loadPlugins(plugins),\n options.pluginSearchDirs === false\n ? []\n : searchPlugins(pluginSearchDirs),\n ])\n ).flat(),\n };\n\n return fn(...args);\n };\n}\n\nconst formatWithCursor = withPlugins(core.formatWithCursor);\n\nasync function format(text, options) {\n const { formatted } = await formatWithCursor(text, {\n ...options,\n cursorOffset: -1,\n });\n return formatted;\n}\n\nasync function check(text, options) {\n return (await format(text, options)) === text;\n}\n\n// eslint-disable-next-line require-await\nasync function clearCache() {\n clearConfigCache();\n clearPluginCache();\n}\n\n/** @type {typeof getFileInfoWithoutPlugins} */\nconst getFileInfo = withPlugins(getFileInfoWithoutPlugins);\n\n/** @type {typeof getSupportInfoWithoutPlugins} */\nconst getSupportInfo = withPlugins(getSupportInfoWithoutPlugins, 0);\n\n// Internal shared with cli\nconst sharedWithCli = {\n errors,\n coreOptions,\n createIsIgnoredFunction,\n formatOptionsHiddenDefaults,\n normalizeOptions,\n getSupportInfoWithoutPlugins,\n vnopts,\n fastGlob,\n utils: {\n arrayify,\n isNonEmptyArray,\n partition,\n },\n};\n\nconst debugApis = {\n parse: withPlugins(core.parse),\n formatAST: withPlugins(core.formatAst),\n formatDoc: withPlugins(core.formatDoc),\n printToDoc: withPlugins(core.printToDoc),\n printDocToString: withPlugins(core.printDocToString),\n};\n\nexport {\n formatWithCursor,\n format,\n check,\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n getFileInfo,\n getSupportInfo,\n sharedWithCli as __internal,\n debugApis as __debug,\n};\nexport * as util from \"./utils/public.js\";\n<|edits_diff|>\n--- src/index.js\n+++ src/index.js\n@@ -20,6 +20,7 @@\n import arrayify from \"./utils/arrayify.js\";\n import partition from \"./utils/partition.js\";\n import isNonEmptyArray from \"./utils/is-non-empty-array.js\";\n+import omit from \"./utils/object-omit.js\";\n \n /**\n * @param {*} fn\n<|current_version|>\nimport * as core from \"./main/core.js\";\nimport { getSupportInfo as getSupportInfoWithoutPlugins } from \"./main/support.js\";\nimport getFileInfoWithoutPlugins from \"./common/get-file-info.js\";\nimport {\n loadBuiltinPlugins,\n loadPlugins,\n searchPlugins,\n clearCache as clearPluginCache,\n} from \"./main/plugins/index.js\";\nimport {\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n} from \"./config/resolve-config.js\";\nimport * as errors from \"./common/errors.js\";\nimport * as coreOptions from \"./main/core-options.evaluate.js\";\nimport { createIsIgnoredFunction } from \"./utils/ignore.js\";\nimport { formatOptionsHiddenDefaults } from \"./main/normalize-format-options.js\";\nimport normalizeOptions from \"./main/normalize-options.js\";\nimport arrayify from \"./utils/arrayify.js\";\nimport partition from \"./utils/partition.js\";\nimport isNonEmptyArray from \"./utils/is-non-empty-array.js\";\nimport omit from \"./utils/object-omit.js\";\n\n/**\n * @param {*} fn\n * @param {number} [optionsArgumentIndex]\n * @returns {*}\n */\nfunction withPlugins(\n fn,\n optionsArgumentIndex = 1 // Usually `options` is the 2nd argument\n) {\n return async (...args) => {\n const options = args[optionsArgumentIndex] ?? {};\n const { plugins = [], pluginSearchDirs } = options;\n\n args[optionsArgumentIndex] = {\n ...options,\n plugins: (\n await Promise.all([\n loadBuiltinPlugins(),\n // TODO: standalone version allow `plugins` to be `prettierPlugins` which is an object, should allow that too\n loadPlugins(plugins),\n options.pluginSearchDirs === false\n ? []\n : searchPlugins(pluginSearchDirs),\n ])\n ).flat(),\n };\n\n return fn(...args);\n };\n}\n\nconst formatWithCursor = withPlugins(core.formatWithCursor);\n\nasync function format(text, options) {\n const { formatted } = await formatWithCursor(text, {\n ...options,\n cursorOffset: -1,\n });\n return formatted;\n}\n\nasync function check(text, options) {\n return (await format(text, options)) === text;\n}\n\n// eslint-disable-next-line require-await\nasync function clearCache() {\n clearConfigCache();\n clearPluginCache();\n}\n\n/** @type {typeof getFileInfoWithoutPlugins} */\nconst getFileInfo = withPlugins(getFileInfoWithoutPlugins);\n\n/** @type {typeof getSupportInfoWithoutPlugins} */\nconst getSupportInfo = withPlugins(getSupportInfoWithoutPlugins, 0);\n\n// Internal shared with cli\nconst sharedWithCli = {\n errors,\n coreOptions,\n createIsIgnoredFunction,\n formatOptionsHiddenDefaults,\n normalizeOptions,\n getSupportInfoWithoutPlugins,\n vnopts,\n fastGlob,\n utils: {\n arrayify,\n isNonEmptyArray,\n partition,\n },\n};\n\nconst debugApis = {\n parse: withPlugins(core.parse),\n formatAST: withPlugins(core.formatAst),\n formatDoc: withPlugins(core.formatDoc),\n printToDoc: withPlugins(core.printToDoc),\n printDocToString: withPlugins(core.printDocToString),\n};\n\nexport {\n formatWithCursor,\n format,\n check,\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n getFileInfo,\n getSupportInfo,\n sharedWithCli as __internal,\n debugApis as __debug,\n};\nexport * as util from \"./utils/public.js\";\n<|next_version|>\nimport * as core from \"./main/core.js\";\nimport { getSupportInfo as getSupportInfoWithoutPlugins } from \"./main/support.js\";\nimport getFileInfoWithoutPlugins from \"./common/get-file-info.js\";\nimport {\n loadBuiltinPlugins,\n loadPlugins,\n searchPlugins,\n clearCache as clearPluginCache,\n} from \"./main/plugins/index.js\";\nimport {\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n} from \"./config/resolve-config.js\";\nimport * as errors from \"./common/errors.js\";\nimport * as coreOptions from \"./main/core-options.evaluate.js\";\nimport { createIsIgnoredFunction } from \"./utils/ignore.js\";\nimport { formatOptionsHiddenDefaults } from \"./main/normalize-format-options.js\";\nimport normalizeOptions from \"./main/normalize-options.js\";\nimport arrayify from \"./utils/arrayify.js\";\nimport partition from \"./utils/partition.js\";\nimport isNonEmptyArray from \"./utils/is-non-empty-array.js\";\nimport omit from \"./utils/object-omit.js\";\n\n/**\n * @param {*} fn\n * @param {number} [optionsArgumentIndex]\n * @returns {*}\n */\nfunction withPlugins(\n fn,\n optionsArgumentIndex = 1 // Usually `options` is the 2nd argument\n) {\n return async (...args) => {\n const options = args[optionsArgumentIndex] ?? {};\n const { plugins = [], pluginSearchDirs } = options;\n\n args[optionsArgumentIndex] = {\n ...options,\n plugins: (\n await Promise.all([\n loadBuiltinPlugins(),\n // TODO: standalone version allow `plugins` to be `prettierPlugins` which is an object, should allow that too\n loadPlugins(plugins),\n options.pluginSearchDirs === false\n ? []\n : searchPlugins(pluginSearchDirs),\n ])\n ).flat(),\n };\n\n return fn(...args);\n };\n}\n\nconst formatWithCursor = withPlugins(core.formatWithCursor);\n\nasync function format(text, options) {\n const { formatted } = await formatWithCursor(text, {\n ...options,\n cursorOffset: -1,\n });\n return formatted;\n}\n\nasync function check(text, options) {\n return (await format(text, options)) === text;\n}\n\n// eslint-disable-next-line require-await\nasync function clearCache() {\n clearConfigCache();\n clearPluginCache();\n}\n\n/** @type {typeof getFileInfoWithoutPlugins} */\nconst getFileInfo = withPlugins(getFileInfoWithoutPlugins);\n\n/** @type {typeof getSupportInfoWithoutPlugins} */\nconst getSupportInfo = withPlugins(getSupportInfoWithoutPlugins, 0);\n\n// Internal shared with cli\nconst sharedWithCli = {\n errors,\n coreOptions,\n createIsIgnoredFunction,\n formatOptionsHiddenDefaults,\n normalizeOptions,\n getSupportInfoWithoutPlugins,\n vnopts,\n fastGlob,\n utils: {\n arrayify,\n isNonEmptyArray,\n partition,\n omit,\n },\n};\n\nconst debugApis = {\n parse: withPlugins(core.parse),\n formatAST: withPlugins(core.formatAst),\n formatDoc: withPlugins(core.formatDoc),\n printToDoc: withPlugins(core.printToDoc),\n printDocToString: withPlugins(core.printDocToString),\n};\n\nexport {\n formatWithCursor,\n format,\n check,\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n getFileInfo,\n getSupportInfo,\n sharedWithCli as __internal,\n debugApis as __debug,\n};\nexport * as util from \"./utils/public.js\";\n", "current_contents": "import * as core from \"./main/core.js\";\nimport { getSupportInfo as getSupportInfoWithoutPlugins } from \"./main/support.js\";\nimport getFileInfoWithoutPlugins from \"./common/get-file-info.js\";\nimport {\n loadBuiltinPlugins,\n loadPlugins,\n searchPlugins,\n clearCache as clearPluginCache,\n} from \"./main/plugins/index.js\";\nimport {\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n} from \"./config/resolve-config.js\";\nimport * as errors from \"./common/errors.js\";\nimport * as coreOptions from \"./main/core-options.evaluate.js\";\nimport { createIsIgnoredFunction } from \"./utils/ignore.js\";\nimport { formatOptionsHiddenDefaults } from \"./main/normalize-format-options.js\";\nimport normalizeOptions from \"./main/normalize-options.js\";\nimport arrayify from \"./utils/arrayify.js\";\nimport partition from \"./utils/partition.js\";\nimport isNonEmptyArray from \"./utils/is-non-empty-array.js\";\nimport omit from \"./utils/object-omit.js\";\n\n/**\n * @param {*} fn\n * @param {number} [optionsArgumentIndex]\n * @returns {*}\n */\nfunction withPlugins(\n fn,\n optionsArgumentIndex = 1 // Usually `options` is the 2nd argument\n) {\n return async (...args) => {\n const options = args[optionsArgumentIndex] ?? {};\n const { plugins = [], pluginSearchDirs } = options;\n\n args[optionsArgumentIndex] = {\n ...options,\n plugins: (\n await Promise.all([\n loadBuiltinPlugins(),\n // TODO: standalone version allow `plugins` to be `prettierPlugins` which is an object, should allow that too\n loadPlugins(plugins),\n options.pluginSearchDirs === false\n ? []\n : searchPlugins(pluginSearchDirs),\n ])\n ).flat(),\n };\n\n return fn(...args);\n };\n}\n\nconst formatWithCursor = withPlugins(core.formatWithCursor);\n\nasync function format(text, options) {\n const { formatted } = await formatWithCursor(text, {\n ...options,\n cursorOffset: -1,\n });\n return formatted;\n}\n\nasync function check(text, options) {\n return (await format(text, options)) === text;\n}\n\n// eslint-disable-next-line require-await\nasync function clearCache() {\n clearConfigCache();\n clearPluginCache();\n}\n\n/** @type {typeof getFileInfoWithoutPlugins} */\nconst getFileInfo = withPlugins(getFileInfoWithoutPlugins);\n\n/** @type {typeof getSupportInfoWithoutPlugins} */\nconst getSupportInfo = withPlugins(getSupportInfoWithoutPlugins, 0);\n\n// Internal shared with cli\nconst sharedWithCli = {\n errors,\n coreOptions,\n createIsIgnoredFunction,\n formatOptionsHiddenDefaults,\n normalizeOptions,\n getSupportInfoWithoutPlugins,\n vnopts,\n fastGlob,\n utils: {\n arrayify,\n isNonEmptyArray,\n partition,\n },\n};\n\nconst debugApis = {\n parse: withPlugins(core.parse),\n formatAST: withPlugins(core.formatAst),\n formatDoc: withPlugins(core.formatDoc),\n printToDoc: withPlugins(core.printToDoc),\n printDocToString: withPlugins(core.printDocToString),\n};\n\nexport {\n formatWithCursor,\n format,\n check,\n resolveConfig,\n resolveConfigFile,\n clearCache as clearConfigCache,\n getFileInfo,\n getSupportInfo,\n sharedWithCli as __internal,\n debugApis as __debug,\n};\nexport * as util from \"./utils/public.js\";"} {"commit": "20e891544c7e15b323a82d0e5da0a9e16c9c2fc6", "message": "Add `printTypeScriptAccessibilityToken` (#14273)", "old_file": "src/language-js/print/misc.js", "new_file": "src/language-js/print/misc.js", "status": "M", "old_contents": "function printRestSpread(path, print) {\n return [\"...\", print(\"argument\"), printTypeAnnotationProperty(path, print)];\n}\n\nfunction printDirective(rawText, options) {\n const rawContent = rawText.slice(1, -1);\n\n // Check for the alternate quote, to determine if we're allowed to swap\n // the quotes on a DirectiveLiteral.\n if (rawContent.includes('\"') || rawContent.includes(\"'\")) {\n return rawText;\n }\n\n const enclosingQuote = options.singleQuote ? \"'\" : '\"';\n\n // Directives are exact code unit sequences, which means that you can't\n // change the escape sequences they use.\n // See https://github.com/prettier/prettier/issues/1555\n // and https://tc39.github.io/ecma262/#directive-prologue\n return enclosingQuote + rawContent + enclosingQuote;\n}\n\nexport {\n printOptionalToken,\n printDefiniteToken,\n printDeclareToken,\n printFunctionTypeParameters,\n printBindExpressionCallee,\n printRestSpread,\n adjustClause,\n printDirective,\n};\n", "new_contents": "function printRestSpread(path, print) {\n return [\"...\", print(\"argument\"), printTypeAnnotationProperty(path, print)];\n}\n\nfunction printDirective(rawText, options) {\n const rawContent = rawText.slice(1, -1);\n\n // Check for the alternate quote, to determine if we're allowed to swap\n // the quotes on a DirectiveLiteral.\n if (rawContent.includes('\"') || rawContent.includes(\"'\")) {\n return rawText;\n }\n\n const enclosingQuote = options.singleQuote ? \"'\" : '\"';\n\n // Directives are exact code unit sequences, which means that you can't\n // change the escape sequences they use.\n // See https://github.com/prettier/prettier/issues/1555\n // and https://tc39.github.io/ecma262/#directive-prologue\n return enclosingQuote + rawContent + enclosingQuote;\n}\n\nfunction printTypeScriptAccessibilityToken(node) {\n return node.accessibility ? node.accessibility + \" \" : \"\";\n}\n\nexport {\n printOptionalToken,\n printDefiniteToken,\n printDeclareToken,\n printFunctionTypeParameters,\n printBindExpressionCallee,\n printRestSpread,\n adjustClause,\n printDirective,\n printTypeScriptAccessibilityToken,\n};\n", "text": "<|original_code|>\nfunction printRestSpread(path, print) {\n return [\"...\", print(\"argument\"), printTypeAnnotationProperty(path, print)];\n}\n\nfunction printDirective(rawText, options) {\n const rawContent = rawText.slice(1, -1);\n\n // Check for the alternate quote, to determine if we're allowed to swap\n // the quotes on a DirectiveLiteral.\n if (rawContent.includes('\"') || rawContent.includes(\"'\")) {\n return rawText;\n }\n\n const enclosingQuote = options.singleQuote ? \"'\" : '\"';\n\n // Directives are exact code unit sequences, which means that you can't\n // change the escape sequences they use.\n // See https://github.com/prettier/prettier/issues/1555\n // and https://tc39.github.io/ecma262/#directive-prologue\n return enclosingQuote + rawContent + enclosingQuote;\n}\n\nexport {\n printOptionalToken,\n printDefiniteToken,\n printDeclareToken,\n printFunctionTypeParameters,\n printBindExpressionCallee,\n printRestSpread,\n adjustClause,\n printDirective,\n};\n\n<|edits_diff|>\n--- src/language-js/print/misc.js\n+++ src/language-js/print/misc.js\n@@ -20,6 +20,10 @@\n return enclosingQuote + rawContent + enclosingQuote;\n }\n \n+function printTypeScriptAccessibilityToken(node) {\n+ return node.accessibility ? node.accessibility + \" \" : \"\";\n+}\n+\n export {\n printOptionalToken,\n printDefiniteToken,\n<|current_version|>\nfunction printRestSpread(path, print) {\n return [\"...\", print(\"argument\"), printTypeAnnotationProperty(path, print)];\n}\n\nfunction printDirective(rawText, options) {\n const rawContent = rawText.slice(1, -1);\n\n // Check for the alternate quote, to determine if we're allowed to swap\n // the quotes on a DirectiveLiteral.\n if (rawContent.includes('\"') || rawContent.includes(\"'\")) {\n return rawText;\n }\n\n const enclosingQuote = options.singleQuote ? \"'\" : '\"';\n\n // Directives are exact code unit sequences, which means that you can't\n // change the escape sequences they use.\n // See https://github.com/prettier/prettier/issues/1555\n // and https://tc39.github.io/ecma262/#directive-prologue\n return enclosingQuote + rawContent + enclosingQuote;\n}\n\nfunction printTypeScriptAccessibilityToken(node) {\n return node.accessibility ? node.accessibility + \" \" : \"\";\n}\n\nexport {\n printOptionalToken,\n printDefiniteToken,\n printDeclareToken,\n printFunctionTypeParameters,\n printBindExpressionCallee,\n printRestSpread,\n adjustClause,\n printDirective,\n};\n\n<|next_version|>\nfunction printRestSpread(path, print) {\n return [\"...\", print(\"argument\"), printTypeAnnotationProperty(path, print)];\n}\n\nfunction printDirective(rawText, options) {\n const rawContent = rawText.slice(1, -1);\n\n // Check for the alternate quote, to determine if we're allowed to swap\n // the quotes on a DirectiveLiteral.\n if (rawContent.includes('\"') || rawContent.includes(\"'\")) {\n return rawText;\n }\n\n const enclosingQuote = options.singleQuote ? \"'\" : '\"';\n\n // Directives are exact code unit sequences, which means that you can't\n // change the escape sequences they use.\n // See https://github.com/prettier/prettier/issues/1555\n // and https://tc39.github.io/ecma262/#directive-prologue\n return enclosingQuote + rawContent + enclosingQuote;\n}\n\nfunction printTypeScriptAccessibilityToken(node) {\n return node.accessibility ? node.accessibility + \" \" : \"\";\n}\n\nexport {\n printOptionalToken,\n printDefiniteToken,\n printDeclareToken,\n printFunctionTypeParameters,\n printBindExpressionCallee,\n printRestSpread,\n adjustClause,\n printDirective,\n printTypeScriptAccessibilityToken,\n};\n\n", "current_contents": "function printRestSpread(path, print) {\n return [\"...\", print(\"argument\"), printTypeAnnotationProperty(path, print)];\n}\n\nfunction printDirective(rawText, options) {\n const rawContent = rawText.slice(1, -1);\n\n // Check for the alternate quote, to determine if we're allowed to swap\n // the quotes on a DirectiveLiteral.\n if (rawContent.includes('\"') || rawContent.includes(\"'\")) {\n return rawText;\n }\n\n const enclosingQuote = options.singleQuote ? \"'\" : '\"';\n\n // Directives are exact code unit sequences, which means that you can't\n // change the escape sequences they use.\n // See https://github.com/prettier/prettier/issues/1555\n // and https://tc39.github.io/ecma262/#directive-prologue\n return enclosingQuote + rawContent + enclosingQuote;\n}\n\nfunction printTypeScriptAccessibilityToken(node) {\n return node.accessibility ? node.accessibility + \" \" : \"\";\n}\n\nexport {\n printOptionalToken,\n printDefiniteToken,\n printDeclareToken,\n printFunctionTypeParameters,\n printBindExpressionCallee,\n printRestSpread,\n adjustClause,\n printDirective,\n};\n"} {"commit": "d921087d1292e7fff55749f6ff1e57076422e915", "message": "Throw errors when too many 'cursor' found in doc (#13339)", "old_file": "src/document/printer.js", "new_file": "src/document/printer.js", "status": "M", "old_contents": " break;\n }\n }\n return false;\n}\n\nfunction printDocToString(doc, options) {\n /** @type GroupModeMap */\n const groupModeMap = {};\n\n const width = options.printWidth;\n const newLine = convertEndOfLineToChars(options.endOfLine);\n let pos = 0;\n // cmds is basically a stack. We've turned a recursive call into a\n // while loop which is much faster. The while loop below adds new\n // cmds to the array instead of recursively calling `print`.\n /** @type Command[] */\n const cmds = [{ ind: rootIndent(), mode: MODE_BREAK, doc }];\n const out = [];\n let shouldRemeasure = false;\n /** @type Command[] */\n const lineSuffix = [];\n\n while (cmds.length > 0) {\n const { ind, mode, doc } = cmds.pop();\n switch (getDocType(doc)) {\n case DOC_TYPE_STRING: {\n const formatted = newLine !== \"\\n\" ? doc.replace(/\\n/g, newLine) : doc;\n out.push(formatted);\n pos += getStringWidth(formatted);\n break;\n }\n\n case DOC_TYPE_ARRAY: {\n for (let i = doc.length - 1; i >= 0; i--) {\n cmds.push({ ind, mode, doc: doc[i] });\n }\n break;\n }\n\n case DOC_TYPE_CURSOR:\n out.push(CURSOR_PLACEHOLDER);\n break;\n\n case DOC_TYPE_INDENT:\n cmds.push({ ind: makeIndent(ind, options), mode, doc: doc.contents });\n break;\n\n case DOC_TYPE_ALIGN:\n cmds.push({\n ind: makeAlign(ind, doc.n, options),\n mode,\n doc: doc.contents,\n });\n break;\n\n case DOC_TYPE_TRIM:\n pos -= trim(out);\n break;\n\n case DOC_TYPE_GROUP:\n switch (mode) {\n case MODE_FLAT:\n if (!shouldRemeasure) {\n cmds.push({\n ind,", "new_contents": " break;\n }\n }\n return false;\n}\n\nfunction printDocToString(doc, options) {\n /** @type GroupModeMap */\n const groupModeMap = {};\n\n const width = options.printWidth;\n const newLine = convertEndOfLineToChars(options.endOfLine);\n let pos = 0;\n // cmds is basically a stack. We've turned a recursive call into a\n // while loop which is much faster. The while loop below adds new\n // cmds to the array instead of recursively calling `print`.\n /** @type Command[] */\n const cmds = [{ ind: rootIndent(), mode: MODE_BREAK, doc }];\n const out = [];\n let shouldRemeasure = false;\n /** @type Command[] */\n const lineSuffix = [];\n let printedCursorCount = 0;\n\n while (cmds.length > 0) {\n const { ind, mode, doc } = cmds.pop();\n switch (getDocType(doc)) {\n case DOC_TYPE_STRING: {\n const formatted = newLine !== \"\\n\" ? doc.replace(/\\n/g, newLine) : doc;\n out.push(formatted);\n pos += getStringWidth(formatted);\n break;\n }\n\n case DOC_TYPE_ARRAY: {\n for (let i = doc.length - 1; i >= 0; i--) {\n cmds.push({ ind, mode, doc: doc[i] });\n }\n break;\n }\n\n case DOC_TYPE_CURSOR:\n if (printedCursorCount >= 2) {\n throw new Error(\"There are too many 'cursor' in doc.\");\n }\n out.push(CURSOR_PLACEHOLDER);\n printedCursorCount++;\n break;\n\n case DOC_TYPE_INDENT:\n cmds.push({ ind: makeIndent(ind, options), mode, doc: doc.contents });\n break;\n\n case DOC_TYPE_ALIGN:\n cmds.push({\n ind: makeAlign(ind, doc.n, options),\n mode,\n doc: doc.contents,\n });\n break;\n\n case DOC_TYPE_TRIM:\n pos -= trim(out);\n break;\n\n case DOC_TYPE_GROUP:\n switch (mode) {\n case MODE_FLAT:\n if (!shouldRemeasure) {\n cmds.push({\n ind,", "text": "<|original_code|>\n break;\n }\n }\n return false;\n}\n\nfunction printDocToString(doc, options) {\n /** @type GroupModeMap */\n const groupModeMap = {};\n\n const width = options.printWidth;\n const newLine = convertEndOfLineToChars(options.endOfLine);\n let pos = 0;\n // cmds is basically a stack. We've turned a recursive call into a\n // while loop which is much faster. The while loop below adds new\n // cmds to the array instead of recursively calling `print`.\n /** @type Command[] */\n const cmds = [{ ind: rootIndent(), mode: MODE_BREAK, doc }];\n const out = [];\n let shouldRemeasure = false;\n /** @type Command[] */\n const lineSuffix = [];\n\n while (cmds.length > 0) {\n const { ind, mode, doc } = cmds.pop();\n switch (getDocType(doc)) {\n case DOC_TYPE_STRING: {\n const formatted = newLine !== \"\\n\" ? doc.replace(/\\n/g, newLine) : doc;\n out.push(formatted);\n pos += getStringWidth(formatted);\n break;\n }\n\n case DOC_TYPE_ARRAY: {\n for (let i = doc.length - 1; i >= 0; i--) {\n cmds.push({ ind, mode, doc: doc[i] });\n }\n break;\n }\n\n case DOC_TYPE_CURSOR:\n out.push(CURSOR_PLACEHOLDER);\n break;\n\n case DOC_TYPE_INDENT:\n cmds.push({ ind: makeIndent(ind, options), mode, doc: doc.contents });\n break;\n\n case DOC_TYPE_ALIGN:\n cmds.push({\n ind: makeAlign(ind, doc.n, options),\n mode,\n doc: doc.contents,\n });\n break;\n\n case DOC_TYPE_TRIM:\n pos -= trim(out);\n break;\n\n case DOC_TYPE_GROUP:\n switch (mode) {\n case MODE_FLAT:\n if (!shouldRemeasure) {\n cmds.push({\n ind,\n<|edits_diff|>\n--- src/document/printer.js\n+++ src/document/printer.js\n@@ -20,6 +20,7 @@\n let shouldRemeasure = false;\n /** @type Command[] */\n const lineSuffix = [];\n+ let printedCursorCount = 0;\n \n while (cmds.length > 0) {\n const { ind, mode, doc } = cmds.pop();\n@@ -39,6 +40,9 @@\n }\n \n case DOC_TYPE_CURSOR:\n+ if (printedCursorCount >= 2) {\n+ throw new Error(\"There are too many 'cursor' in doc.\");\n+ }\n out.push(CURSOR_PLACEHOLDER);\n break;\n \n<|current_version|>\n break;\n }\n }\n return false;\n}\n\nfunction printDocToString(doc, options) {\n /** @type GroupModeMap */\n const groupModeMap = {};\n\n const width = options.printWidth;\n const newLine = convertEndOfLineToChars(options.endOfLine);\n let pos = 0;\n // cmds is basically a stack. We've turned a recursive call into a\n // while loop which is much faster. The while loop below adds new\n // cmds to the array instead of recursively calling `print`.\n /** @type Command[] */\n const cmds = [{ ind: rootIndent(), mode: MODE_BREAK, doc }];\n const out = [];\n let shouldRemeasure = false;\n /** @type Command[] */\n const lineSuffix = [];\n let printedCursorCount = 0;\n\n while (cmds.length > 0) {\n const { ind, mode, doc } = cmds.pop();\n switch (getDocType(doc)) {\n case DOC_TYPE_STRING: {\n const formatted = newLine !== \"\\n\" ? doc.replace(/\\n/g, newLine) : doc;\n out.push(formatted);\n pos += getStringWidth(formatted);\n break;\n }\n\n case DOC_TYPE_ARRAY: {\n for (let i = doc.length - 1; i >= 0; i--) {\n cmds.push({ ind, mode, doc: doc[i] });\n }\n break;\n }\n\n case DOC_TYPE_CURSOR:\n if (printedCursorCount >= 2) {\n throw new Error(\"There are too many 'cursor' in doc.\");\n }\n out.push(CURSOR_PLACEHOLDER);\n break;\n\n case DOC_TYPE_INDENT:\n cmds.push({ ind: makeIndent(ind, options), mode, doc: doc.contents });\n break;\n\n case DOC_TYPE_ALIGN:\n cmds.push({\n ind: makeAlign(ind, doc.n, options),\n mode,\n doc: doc.contents,\n });\n break;\n\n case DOC_TYPE_TRIM:\n pos -= trim(out);\n break;\n\n case DOC_TYPE_GROUP:\n switch (mode) {\n case MODE_FLAT:\n if (!shouldRemeasure) {\n cmds.push({\n ind,\n<|next_version|>\n break;\n }\n }\n return false;\n}\n\nfunction printDocToString(doc, options) {\n /** @type GroupModeMap */\n const groupModeMap = {};\n\n const width = options.printWidth;\n const newLine = convertEndOfLineToChars(options.endOfLine);\n let pos = 0;\n // cmds is basically a stack. We've turned a recursive call into a\n // while loop which is much faster. The while loop below adds new\n // cmds to the array instead of recursively calling `print`.\n /** @type Command[] */\n const cmds = [{ ind: rootIndent(), mode: MODE_BREAK, doc }];\n const out = [];\n let shouldRemeasure = false;\n /** @type Command[] */\n const lineSuffix = [];\n let printedCursorCount = 0;\n\n while (cmds.length > 0) {\n const { ind, mode, doc } = cmds.pop();\n switch (getDocType(doc)) {\n case DOC_TYPE_STRING: {\n const formatted = newLine !== \"\\n\" ? doc.replace(/\\n/g, newLine) : doc;\n out.push(formatted);\n pos += getStringWidth(formatted);\n break;\n }\n\n case DOC_TYPE_ARRAY: {\n for (let i = doc.length - 1; i >= 0; i--) {\n cmds.push({ ind, mode, doc: doc[i] });\n }\n break;\n }\n\n case DOC_TYPE_CURSOR:\n if (printedCursorCount >= 2) {\n throw new Error(\"There are too many 'cursor' in doc.\");\n }\n out.push(CURSOR_PLACEHOLDER);\n printedCursorCount++;\n break;\n\n case DOC_TYPE_INDENT:\n cmds.push({ ind: makeIndent(ind, options), mode, doc: doc.contents });\n break;\n\n case DOC_TYPE_ALIGN:\n cmds.push({\n ind: makeAlign(ind, doc.n, options),\n mode,\n doc: doc.contents,\n });\n break;\n\n case DOC_TYPE_TRIM:\n pos -= trim(out);\n break;\n\n case DOC_TYPE_GROUP:\n switch (mode) {\n case MODE_FLAT:\n if (!shouldRemeasure) {\n cmds.push({\n ind,\n", "current_contents": " break;\n }\n }\n return false;\n}\n\nfunction printDocToString(doc, options) {\n /** @type GroupModeMap */\n const groupModeMap = {};\n\n const width = options.printWidth;\n const newLine = convertEndOfLineToChars(options.endOfLine);\n let pos = 0;\n // cmds is basically a stack. We've turned a recursive call into a\n // while loop which is much faster. The while loop below adds new\n // cmds to the array instead of recursively calling `print`.\n /** @type Command[] */\n const cmds = [{ ind: rootIndent(), mode: MODE_BREAK, doc }];\n const out = [];\n let shouldRemeasure = false;\n /** @type Command[] */\n const lineSuffix = [];\n let printedCursorCount = 0;\n\n while (cmds.length > 0) {\n const { ind, mode, doc } = cmds.pop();\n switch (getDocType(doc)) {\n case DOC_TYPE_STRING: {\n const formatted = newLine !== \"\\n\" ? doc.replace(/\\n/g, newLine) : doc;\n out.push(formatted);\n pos += getStringWidth(formatted);\n break;\n }\n\n case DOC_TYPE_ARRAY: {\n for (let i = doc.length - 1; i >= 0; i--) {\n cmds.push({ ind, mode, doc: doc[i] });\n }\n break;\n }\n\n case DOC_TYPE_CURSOR:\n if (printedCursorCount >= 2) {\n throw new Error(\"There are too many 'cursor' in doc.\");\n }\n out.push(CURSOR_PLACEHOLDER);\n break;\n\n case DOC_TYPE_INDENT:\n cmds.push({ ind: makeIndent(ind, options), mode, doc: doc.contents });\n break;\n\n case DOC_TYPE_ALIGN:\n cmds.push({\n ind: makeAlign(ind, doc.n, options),\n mode,\n doc: doc.contents,\n });\n break;\n\n case DOC_TYPE_TRIM:\n pos -= trim(out);\n break;\n\n case DOC_TYPE_GROUP:\n switch (mode) {\n case MODE_FLAT:\n if (!shouldRemeasure) {\n cmds.push({\n ind,"} {"commit": "1fa3b1c341562b8eb11d7e055b4579720dbcfe57", "message": "Playground: Allow hide `input` and `output` (#10184)", "old_file": "website/playground/EditorState.js", "new_file": "website/playground/EditorState.js", "status": "M", "old_contents": "import * as React from \"react\";\n\nimport { stateToggler, shallowEqual } from \"./helpers\";\nimport * as storage from \"./storage\";\n\nexport default class extends React.Component {\n constructor() {\n super();\n this.state = {\n showSidebar: window.innerWidth > window.innerHeight,\n showAst: false,\n showDoc: false,\n showComments: false,\n showSecondFormat: false,\n toggleSidebar: () => this.setState(stateToggler(\"showSidebar\")),\n toggleAst: () => this.setState(stateToggler(\"showAst\")),\n toggleDoc: () => this.setState(stateToggler(\"showDoc\")),\n toggleComments: () => this.setState(stateToggler(\"showComments\")),\n toggleSecondFormat: () => this.setState(stateToggler(\"showSecondFormat\")),\n ...storage.get(\"editor_state\"),\n };\n }\n\n componentDidUpdate(_, prevState) {\n if (!shallowEqual(this.state, prevState)) {\n storage.set(\"editor_state\", this.state);\n }\n }\n\n render() {\n return this.props.children(this.state);\n }\n}\n", "new_contents": "import * as React from \"react\";\n\nimport { stateToggler, shallowEqual } from \"./helpers\";\nimport * as storage from \"./storage\";\n\nexport default class extends React.Component {\n constructor() {\n super();\n this.state = {\n showSidebar: window.innerWidth > window.innerHeight,\n showAst: false,\n showDoc: false,\n showComments: false,\n showSecondFormat: false,\n showInput: true,\n showOutput: true,\n toggleSidebar: () => this.setState(stateToggler(\"showSidebar\")),\n toggleAst: () => this.setState(stateToggler(\"showAst\")),\n toggleDoc: () => this.setState(stateToggler(\"showDoc\")),\n toggleComments: () => this.setState(stateToggler(\"showComments\")),\n toggleSecondFormat: () => this.setState(stateToggler(\"showSecondFormat\")),\n toggleInput: () => this.setState(stateToggler(\"showInput\")),\n toggleOutput: () => this.setState(stateToggler(\"showOutput\")),\n ...storage.get(\"editor_state\"),\n };\n }\n\n componentDidUpdate(_, prevState) {\n if (!shallowEqual(this.state, prevState)) {\n storage.set(\"editor_state\", this.state);\n }\n }\n\n render() {\n return this.props.children(this.state);\n }\n}\n", "text": "<|original_code|>\nimport * as React from \"react\";\n\nimport { stateToggler, shallowEqual } from \"./helpers\";\nimport * as storage from \"./storage\";\n\nexport default class extends React.Component {\n constructor() {\n super();\n this.state = {\n showSidebar: window.innerWidth > window.innerHeight,\n showAst: false,\n showDoc: false,\n showComments: false,\n showSecondFormat: false,\n toggleSidebar: () => this.setState(stateToggler(\"showSidebar\")),\n toggleAst: () => this.setState(stateToggler(\"showAst\")),\n toggleDoc: () => this.setState(stateToggler(\"showDoc\")),\n toggleComments: () => this.setState(stateToggler(\"showComments\")),\n toggleSecondFormat: () => this.setState(stateToggler(\"showSecondFormat\")),\n ...storage.get(\"editor_state\"),\n };\n }\n\n componentDidUpdate(_, prevState) {\n if (!shallowEqual(this.state, prevState)) {\n storage.set(\"editor_state\", this.state);\n }\n }\n\n render() {\n return this.props.children(this.state);\n }\n}\n\n<|edits_diff|>\n--- website/playground/EditorState.js\n+++ website/playground/EditorState.js\n@@ -12,6 +12,8 @@\n showDoc: false,\n showComments: false,\n showSecondFormat: false,\n+ showInput: true,\n+ showOutput: true,\n toggleSidebar: () => this.setState(stateToggler(\"showSidebar\")),\n toggleAst: () => this.setState(stateToggler(\"showAst\")),\n toggleDoc: () => this.setState(stateToggler(\"showDoc\")),\n<|current_version|>\nimport * as React from \"react\";\n\nimport { stateToggler, shallowEqual } from \"./helpers\";\nimport * as storage from \"./storage\";\n\nexport default class extends React.Component {\n constructor() {\n super();\n this.state = {\n showSidebar: window.innerWidth > window.innerHeight,\n showAst: false,\n showDoc: false,\n showComments: false,\n showSecondFormat: false,\n showInput: true,\n showOutput: true,\n toggleSidebar: () => this.setState(stateToggler(\"showSidebar\")),\n toggleAst: () => this.setState(stateToggler(\"showAst\")),\n toggleDoc: () => this.setState(stateToggler(\"showDoc\")),\n toggleComments: () => this.setState(stateToggler(\"showComments\")),\n toggleSecondFormat: () => this.setState(stateToggler(\"showSecondFormat\")),\n ...storage.get(\"editor_state\"),\n };\n }\n\n componentDidUpdate(_, prevState) {\n if (!shallowEqual(this.state, prevState)) {\n storage.set(\"editor_state\", this.state);\n }\n }\n\n render() {\n return this.props.children(this.state);\n }\n}\n\n<|next_version|>\nimport * as React from \"react\";\n\nimport { stateToggler, shallowEqual } from \"./helpers\";\nimport * as storage from \"./storage\";\n\nexport default class extends React.Component {\n constructor() {\n super();\n this.state = {\n showSidebar: window.innerWidth > window.innerHeight,\n showAst: false,\n showDoc: false,\n showComments: false,\n showSecondFormat: false,\n showInput: true,\n showOutput: true,\n toggleSidebar: () => this.setState(stateToggler(\"showSidebar\")),\n toggleAst: () => this.setState(stateToggler(\"showAst\")),\n toggleDoc: () => this.setState(stateToggler(\"showDoc\")),\n toggleComments: () => this.setState(stateToggler(\"showComments\")),\n toggleSecondFormat: () => this.setState(stateToggler(\"showSecondFormat\")),\n toggleInput: () => this.setState(stateToggler(\"showInput\")),\n toggleOutput: () => this.setState(stateToggler(\"showOutput\")),\n ...storage.get(\"editor_state\"),\n };\n }\n\n componentDidUpdate(_, prevState) {\n if (!shallowEqual(this.state, prevState)) {\n storage.set(\"editor_state\", this.state);\n }\n }\n\n render() {\n return this.props.children(this.state);\n }\n}\n\n", "current_contents": "import * as React from \"react\";\n\nimport { stateToggler, shallowEqual } from \"./helpers\";\nimport * as storage from \"./storage\";\n\nexport default class extends React.Component {\n constructor() {\n super();\n this.state = {\n showSidebar: window.innerWidth > window.innerHeight,\n showAst: false,\n showDoc: false,\n showComments: false,\n showSecondFormat: false,\n showInput: true,\n showOutput: true,\n toggleSidebar: () => this.setState(stateToggler(\"showSidebar\")),\n toggleAst: () => this.setState(stateToggler(\"showAst\")),\n toggleDoc: () => this.setState(stateToggler(\"showDoc\")),\n toggleComments: () => this.setState(stateToggler(\"showComments\")),\n toggleSecondFormat: () => this.setState(stateToggler(\"showSecondFormat\")),\n ...storage.get(\"editor_state\"),\n };\n }\n\n componentDidUpdate(_, prevState) {\n if (!shallowEqual(this.state, prevState)) {\n storage.set(\"editor_state\", this.state);\n }\n }\n\n render() {\n return this.props.children(this.state);\n }\n}\n"} {"commit": "79d2f4a295c56f637c4d215f78e825bff817f428", "message": "Add CLI flag for debugging comment attachment issues (#10124)", "old_file": "src/main/comments.js", "new_file": "src/main/comments.js", "status": "M", "old_contents": " ) {\n if (locStart(comment) - locStart(ast) <= 0) {\n addLeadingComment(ast, comment);\n continue;\n }\n if (locEnd(comment) - locEnd(ast) >= 0) {\n addTrailingComment(ast, comment);\n continue;\n }\n }\n\n let args;\n if (avoidAstMutation) {\n args = [context];\n } else {\n comment.enclosingNode = enclosingNode;\n comment.precedingNode = precedingNode;\n comment.followingNode = followingNode;\n args = [comment, text, options, ast, isLastComment];\n }\n\n if (isOwnLineComment(text, options, decoratedComments, index)) {\n // If a comment exists on its own line, prefer a leading comment.\n // We also need to check if it's the first line of the file.\n if (handleOwnLineComment(...args)) {\n // We're good\n } else if (followingNode) {\n // Always a leading comment.\n addLeadingComment(followingNode, comment);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else if (isEndOfLineComment(text, options, decoratedComments, index)) {\n if (handleEndOfLineComment(...args)) {\n // We're good\n } else if (precedingNode) {\n // There is content before this comment on the same line, but\n // none after it, so prefer a trailing comment of the previous node.\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else {\n if (handleRemainingComment(...args)) {\n // We're good\n } else if (precedingNode && followingNode) {\n // Otherwise, text exists both before and after the comment on\n // the same line. If there is both a preceding and following\n // node, use a tie-breaking algorithm to determine if it should\n // be attached to the next or previous node. In the last case,\n // simply attach the right node;\n const tieCount = tiesToBreak.length;\n if (tieCount > 0) {\n const lastTie = tiesToBreak[tieCount - 1];\n if (lastTie.followingNode !== followingNode) {\n breakTies(tiesToBreak, text, options);\n }\n }\n tiesToBreak.push(context);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast", "new_contents": " ) {\n if (locStart(comment) - locStart(ast) <= 0) {\n addLeadingComment(ast, comment);\n continue;\n }\n if (locEnd(comment) - locEnd(ast) >= 0) {\n addTrailingComment(ast, comment);\n continue;\n }\n }\n\n let args;\n if (avoidAstMutation) {\n args = [context];\n } else {\n comment.enclosingNode = enclosingNode;\n comment.precedingNode = precedingNode;\n comment.followingNode = followingNode;\n args = [comment, text, options, ast, isLastComment];\n }\n\n if (isOwnLineComment(text, options, decoratedComments, index)) {\n comment.placement = \"ownLine\";\n // If a comment exists on its own line, prefer a leading comment.\n // We also need to check if it's the first line of the file.\n if (handleOwnLineComment(...args)) {\n // We're good\n } else if (followingNode) {\n // Always a leading comment.\n addLeadingComment(followingNode, comment);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else if (isEndOfLineComment(text, options, decoratedComments, index)) {\n comment.placement = \"endOfLine\";\n if (handleEndOfLineComment(...args)) {\n // We're good\n } else if (precedingNode) {\n // There is content before this comment on the same line, but\n // none after it, so prefer a trailing comment of the previous node.\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else {\n comment.placement = \"remaining\";\n if (handleRemainingComment(...args)) {\n // We're good\n } else if (precedingNode && followingNode) {\n // Otherwise, text exists both before and after the comment on\n // the same line. If there is both a preceding and following\n // node, use a tie-breaking algorithm to determine if it should\n // be attached to the next or previous node. In the last case,\n // simply attach the right node;\n const tieCount = tiesToBreak.length;\n if (tieCount > 0) {\n const lastTie = tiesToBreak[tieCount - 1];\n if (lastTie.followingNode !== followingNode) {\n breakTies(tiesToBreak, text, options);\n }\n }\n tiesToBreak.push(context);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast", "text": "<|original_code|>\n ) {\n if (locStart(comment) - locStart(ast) <= 0) {\n addLeadingComment(ast, comment);\n continue;\n }\n if (locEnd(comment) - locEnd(ast) >= 0) {\n addTrailingComment(ast, comment);\n continue;\n }\n }\n\n let args;\n if (avoidAstMutation) {\n args = [context];\n } else {\n comment.enclosingNode = enclosingNode;\n comment.precedingNode = precedingNode;\n comment.followingNode = followingNode;\n args = [comment, text, options, ast, isLastComment];\n }\n\n if (isOwnLineComment(text, options, decoratedComments, index)) {\n // If a comment exists on its own line, prefer a leading comment.\n // We also need to check if it's the first line of the file.\n if (handleOwnLineComment(...args)) {\n // We're good\n } else if (followingNode) {\n // Always a leading comment.\n addLeadingComment(followingNode, comment);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else if (isEndOfLineComment(text, options, decoratedComments, index)) {\n if (handleEndOfLineComment(...args)) {\n // We're good\n } else if (precedingNode) {\n // There is content before this comment on the same line, but\n // none after it, so prefer a trailing comment of the previous node.\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else {\n if (handleRemainingComment(...args)) {\n // We're good\n } else if (precedingNode && followingNode) {\n // Otherwise, text exists both before and after the comment on\n // the same line. If there is both a preceding and following\n // node, use a tie-breaking algorithm to determine if it should\n // be attached to the next or previous node. In the last case,\n // simply attach the right node;\n const tieCount = tiesToBreak.length;\n if (tieCount > 0) {\n const lastTie = tiesToBreak[tieCount - 1];\n if (lastTie.followingNode !== followingNode) {\n breakTies(tiesToBreak, text, options);\n }\n }\n tiesToBreak.push(context);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n<|edits_diff|>\n--- src/main/comments.js\n+++ src/main/comments.js\n@@ -20,6 +20,7 @@\n }\n \n if (isOwnLineComment(text, options, decoratedComments, index)) {\n+ comment.placement = \"ownLine\";\n // If a comment exists on its own line, prefer a leading comment.\n // We also need to check if it's the first line of the file.\n if (handleOwnLineComment(...args)) {\n@@ -37,6 +38,7 @@\n addDanglingComment(ast, comment);\n }\n } else if (isEndOfLineComment(text, options, decoratedComments, index)) {\n+ comment.placement = \"endOfLine\";\n if (handleEndOfLineComment(...args)) {\n // We're good\n } else if (precedingNode) {\n<|current_version|>\n ) {\n if (locStart(comment) - locStart(ast) <= 0) {\n addLeadingComment(ast, comment);\n continue;\n }\n if (locEnd(comment) - locEnd(ast) >= 0) {\n addTrailingComment(ast, comment);\n continue;\n }\n }\n\n let args;\n if (avoidAstMutation) {\n args = [context];\n } else {\n comment.enclosingNode = enclosingNode;\n comment.precedingNode = precedingNode;\n comment.followingNode = followingNode;\n args = [comment, text, options, ast, isLastComment];\n }\n\n if (isOwnLineComment(text, options, decoratedComments, index)) {\n comment.placement = \"ownLine\";\n // If a comment exists on its own line, prefer a leading comment.\n // We also need to check if it's the first line of the file.\n if (handleOwnLineComment(...args)) {\n // We're good\n } else if (followingNode) {\n // Always a leading comment.\n addLeadingComment(followingNode, comment);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else if (isEndOfLineComment(text, options, decoratedComments, index)) {\n comment.placement = \"endOfLine\";\n if (handleEndOfLineComment(...args)) {\n // We're good\n } else if (precedingNode) {\n // There is content before this comment on the same line, but\n // none after it, so prefer a trailing comment of the previous node.\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else {\n if (handleRemainingComment(...args)) {\n // We're good\n } else if (precedingNode && followingNode) {\n // Otherwise, text exists both before and after the comment on\n // the same line. If there is both a preceding and following\n // node, use a tie-breaking algorithm to determine if it should\n // be attached to the next or previous node. In the last case,\n // simply attach the right node;\n const tieCount = tiesToBreak.length;\n if (tieCount > 0) {\n const lastTie = tiesToBreak[tieCount - 1];\n if (lastTie.followingNode !== followingNode) {\n breakTies(tiesToBreak, text, options);\n }\n }\n tiesToBreak.push(context);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n<|next_version|>\n ) {\n if (locStart(comment) - locStart(ast) <= 0) {\n addLeadingComment(ast, comment);\n continue;\n }\n if (locEnd(comment) - locEnd(ast) >= 0) {\n addTrailingComment(ast, comment);\n continue;\n }\n }\n\n let args;\n if (avoidAstMutation) {\n args = [context];\n } else {\n comment.enclosingNode = enclosingNode;\n comment.precedingNode = precedingNode;\n comment.followingNode = followingNode;\n args = [comment, text, options, ast, isLastComment];\n }\n\n if (isOwnLineComment(text, options, decoratedComments, index)) {\n comment.placement = \"ownLine\";\n // If a comment exists on its own line, prefer a leading comment.\n // We also need to check if it's the first line of the file.\n if (handleOwnLineComment(...args)) {\n // We're good\n } else if (followingNode) {\n // Always a leading comment.\n addLeadingComment(followingNode, comment);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else if (isEndOfLineComment(text, options, decoratedComments, index)) {\n comment.placement = \"endOfLine\";\n if (handleEndOfLineComment(...args)) {\n // We're good\n } else if (precedingNode) {\n // There is content before this comment on the same line, but\n // none after it, so prefer a trailing comment of the previous node.\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else {\n comment.placement = \"remaining\";\n if (handleRemainingComment(...args)) {\n // We're good\n } else if (precedingNode && followingNode) {\n // Otherwise, text exists both before and after the comment on\n // the same line. If there is both a preceding and following\n // node, use a tie-breaking algorithm to determine if it should\n // be attached to the next or previous node. In the last case,\n // simply attach the right node;\n const tieCount = tiesToBreak.length;\n if (tieCount > 0) {\n const lastTie = tiesToBreak[tieCount - 1];\n if (lastTie.followingNode !== followingNode) {\n breakTies(tiesToBreak, text, options);\n }\n }\n tiesToBreak.push(context);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n", "current_contents": " ) {\n if (locStart(comment) - locStart(ast) <= 0) {\n addLeadingComment(ast, comment);\n continue;\n }\n if (locEnd(comment) - locEnd(ast) >= 0) {\n addTrailingComment(ast, comment);\n continue;\n }\n }\n\n let args;\n if (avoidAstMutation) {\n args = [context];\n } else {\n comment.enclosingNode = enclosingNode;\n comment.precedingNode = precedingNode;\n comment.followingNode = followingNode;\n args = [comment, text, options, ast, isLastComment];\n }\n\n if (isOwnLineComment(text, options, decoratedComments, index)) {\n comment.placement = \"ownLine\";\n // If a comment exists on its own line, prefer a leading comment.\n // We also need to check if it's the first line of the file.\n if (handleOwnLineComment(...args)) {\n // We're good\n } else if (followingNode) {\n // Always a leading comment.\n addLeadingComment(followingNode, comment);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else if (isEndOfLineComment(text, options, decoratedComments, index)) {\n comment.placement = \"endOfLine\";\n if (handleEndOfLineComment(...args)) {\n // We're good\n } else if (precedingNode) {\n // There is content before this comment on the same line, but\n // none after it, so prefer a trailing comment of the previous node.\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast\n /* istanbul ignore next */\n addDanglingComment(ast, comment);\n }\n } else {\n if (handleRemainingComment(...args)) {\n // We're good\n } else if (precedingNode && followingNode) {\n // Otherwise, text exists both before and after the comment on\n // the same line. If there is both a preceding and following\n // node, use a tie-breaking algorithm to determine if it should\n // be attached to the next or previous node. In the last case,\n // simply attach the right node;\n const tieCount = tiesToBreak.length;\n if (tieCount > 0) {\n const lastTie = tiesToBreak[tieCount - 1];\n if (lastTie.followingNode !== followingNode) {\n breakTies(tiesToBreak, text, options);\n }\n }\n tiesToBreak.push(context);\n } else if (precedingNode) {\n addTrailingComment(precedingNode, comment);\n } else if (followingNode) {\n addLeadingComment(followingNode, comment);\n } else if (enclosingNode) {\n addDanglingComment(enclosingNode, comment);\n } else {\n // There are no nodes, let's attach it to the root of the ast"} {"commit": "73e3976c348d56aba94048874606364b94de9b1a", "message": "Add `espree` parser (#9000)", "old_file": "tests/js/quote-props/jsfmt.spec.js", "new_file": "tests/js/quote-props/jsfmt.spec.js", "status": "M", "old_contents": "run_spec(__dirname, [\"babel\"], {\n quoteProps: \"as-needed\",\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"preserve\",\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n singleQuote: true,\n});\n", "new_contents": "const errors = { espree: [\"classes.js\"] };\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"as-needed\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"preserve\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n singleQuote: true,\n errors,\n});\n", "text": "<|original_code|>\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"as-needed\",\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"preserve\",\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n singleQuote: true,\n});\n\n<|edits_diff|>\n--- tests/js/quote-props/jsfmt.spec.js\n+++ tests/js/quote-props/jsfmt.spec.js\n@@ -1,13 +1,18 @@\n+const errors = { espree: [\"classes.js\"] };\n+\n run_spec(__dirname, [\"babel\"], {\n quoteProps: \"as-needed\",\n+ errors,\n });\n \n run_spec(__dirname, [\"babel\"], {\n quoteProps: \"preserve\",\n+ errors,\n });\n \n run_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n+ errors,\n });\n \n run_spec(__dirname, [\"babel\"], {\n<|current_version|>\nconst errors = { espree: [\"classes.js\"] };\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"as-needed\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"preserve\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n singleQuote: true,\n});\n\n<|next_version|>\nconst errors = { espree: [\"classes.js\"] };\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"as-needed\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"preserve\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n singleQuote: true,\n errors,\n});\n\n", "current_contents": "const errors = { espree: [\"classes.js\"] };\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"as-needed\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"preserve\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n errors,\n});\n\nrun_spec(__dirname, [\"babel\"], {\n quoteProps: \"consistent\",\n singleQuote: true,\n});\n"} {"commit": "ecaeec5b5922634fb0247bb910a90155e0c5f275", "message": "Add feature to test idempotency in playground", "old_file": "website/static/worker.js", "new_file": "website/static/worker.js", "status": "M", "old_contents": " return false;\n }\n};\n// eslint-disable-next-line\nfs = module$1 = module = path = os = crypto = {};\nself.process = { argv: [], env: { PRETTIER_DEBUG: true } };\nself.assert = { ok: function() {}, strictEqual: function() {} };\nself.require = function require(path) {\n return self[path.replace(/.+-/, \"\")];\n};\n\nimportScripts(\"lib/index.js\");\nvar prettier = index; // eslint-disable-line\n\nvar parsersLoaded = {};\n\nself.onmessage = function(message) {\n var options = message.data.options || {};\n options.parser = options.parser || \"babylon\";\n\n delete options.ast;\n delete options.doc;\n\n var formatted = formatCode(message.data.text, options);\n var doc;\n var ast;\n\n if (message.data.ast) {\n var actualAst;\n var errored = false;\n try {\n actualAst = prettier.__debug.parse(message.data.text, options);\n ast = JSON.stringify(actualAst);\n } catch (e) {\n errored = true;\n ast = String(e);\n }\n if (!errored) {\n try {\n ast = formatCode(ast, { parser: \"json\" });\n } catch (e) {\n ast = JSON.stringify(actualAst, null, 2);\n }\n }\n }\n\n if (message.data.doc) {\n lazyLoadParser(\"babylon\");\n try {\n doc = prettier.__debug.formatDoc(\n prettier.__debug.printToDoc(message.data.text, options),\n { parser: \"babylon\" }\n );\n } catch (e) {\n doc = String(e);\n }\n }\n\n self.postMessage({\n formatted: formatted,\n doc: doc,\n ast: ast,\n version: prettier.version\n });\n};\n\nfunction formatCode(text, options) {\n lazyLoadParser(options.parser);\n try {\n return prettier.format(text, options);\n } catch (e) {\n // Multiparser may throw if we haven't loaded the right parser\n // Load it lazily and retry!\n if (e.parser && !parsersLoaded[e.parser]) {\n lazyLoadParser(e.parser);\n return formatCode(text, options);\n }\n return String(e);\n }\n}\n\nfunction lazyLoadParser(parser) {\n var script =\n parser === \"json\" ? \"parser-babylon.js\" : \"parser-\" + parser + \".js\";\n\n if (!parsersLoaded[parser]) {", "new_contents": " return false;\n }\n};\n// eslint-disable-next-line\nfs = module$1 = module = path = os = crypto = {};\nself.process = { argv: [], env: { PRETTIER_DEBUG: true } };\nself.assert = { ok: function() {}, strictEqual: function() {} };\nself.require = function require(path) {\n return self[path.replace(/.+-/, \"\")];\n};\n\nimportScripts(\"lib/index.js\");\nvar prettier = index; // eslint-disable-line\n\nvar parsersLoaded = {};\n\nself.onmessage = function(message) {\n var options = message.data.options || {};\n options.parser = options.parser || \"babylon\";\n\n delete options.ast;\n delete options.doc;\n delete options.output2;\n\n var formatted = formatCode(message.data.text, options);\n var doc;\n var ast;\n var formatted2;\n\n if (message.data.ast) {\n var actualAst;\n var errored = false;\n try {\n actualAst = prettier.__debug.parse(message.data.text, options);\n ast = JSON.stringify(actualAst);\n } catch (e) {\n errored = true;\n ast = String(e);\n }\n if (!errored) {\n try {\n ast = formatCode(ast, { parser: \"json\" });\n } catch (e) {\n ast = JSON.stringify(actualAst, null, 2);\n }\n }\n }\n\n if (message.data.doc) {\n lazyLoadParser(\"babylon\");\n try {\n doc = prettier.__debug.formatDoc(\n prettier.__debug.printToDoc(message.data.text, options),\n { parser: \"babylon\" }\n );\n } catch (e) {\n doc = String(e);\n }\n }\n\n if (message.data.formatted2) {\n formatted2 = formatCode(formatted, options);\n }\n\n self.postMessage({\n formatted: formatted,\n doc: doc,\n ast: ast,\n formatted2: formatted2,\n version: prettier.version\n });\n};\n\nfunction formatCode(text, options) {\n lazyLoadParser(options.parser);\n try {\n return prettier.format(text, options);\n } catch (e) {\n // Multiparser may throw if we haven't loaded the right parser\n // Load it lazily and retry!\n if (e.parser && !parsersLoaded[e.parser]) {\n lazyLoadParser(e.parser);\n return formatCode(text, options);\n }\n return String(e);\n }\n}\n\nfunction lazyLoadParser(parser) {\n var script =\n parser === \"json\" ? \"parser-babylon.js\" : \"parser-\" + parser + \".js\";\n\n if (!parsersLoaded[parser]) {", "text": "<|original_code|>\n return false;\n }\n};\n// eslint-disable-next-line\nfs = module$1 = module = path = os = crypto = {};\nself.process = { argv: [], env: { PRETTIER_DEBUG: true } };\nself.assert = { ok: function() {}, strictEqual: function() {} };\nself.require = function require(path) {\n return self[path.replace(/.+-/, \"\")];\n};\n\nimportScripts(\"lib/index.js\");\nvar prettier = index; // eslint-disable-line\n\nvar parsersLoaded = {};\n\nself.onmessage = function(message) {\n var options = message.data.options || {};\n options.parser = options.parser || \"babylon\";\n\n delete options.ast;\n delete options.doc;\n\n var formatted = formatCode(message.data.text, options);\n var doc;\n var ast;\n\n if (message.data.ast) {\n var actualAst;\n var errored = false;\n try {\n actualAst = prettier.__debug.parse(message.data.text, options);\n ast = JSON.stringify(actualAst);\n } catch (e) {\n errored = true;\n ast = String(e);\n }\n if (!errored) {\n try {\n ast = formatCode(ast, { parser: \"json\" });\n } catch (e) {\n ast = JSON.stringify(actualAst, null, 2);\n }\n }\n }\n\n if (message.data.doc) {\n lazyLoadParser(\"babylon\");\n try {\n doc = prettier.__debug.formatDoc(\n prettier.__debug.printToDoc(message.data.text, options),\n { parser: \"babylon\" }\n );\n } catch (e) {\n doc = String(e);\n }\n }\n\n self.postMessage({\n formatted: formatted,\n doc: doc,\n ast: ast,\n version: prettier.version\n });\n};\n\nfunction formatCode(text, options) {\n lazyLoadParser(options.parser);\n try {\n return prettier.format(text, options);\n } catch (e) {\n // Multiparser may throw if we haven't loaded the right parser\n // Load it lazily and retry!\n if (e.parser && !parsersLoaded[e.parser]) {\n lazyLoadParser(e.parser);\n return formatCode(text, options);\n }\n return String(e);\n }\n}\n\nfunction lazyLoadParser(parser) {\n var script =\n parser === \"json\" ? \"parser-babylon.js\" : \"parser-\" + parser + \".js\";\n\n if (!parsersLoaded[parser]) {\n<|edits_diff|>\n--- website/static/worker.js\n+++ website/static/worker.js\n@@ -20,10 +20,12 @@\n \n delete options.ast;\n delete options.doc;\n+ delete options.output2;\n \n var formatted = formatCode(message.data.text, options);\n var doc;\n var ast;\n+ var formatted2;\n \n if (message.data.ast) {\n var actualAst;\n@@ -56,6 +58,10 @@\n }\n }\n \n+ if (message.data.formatted2) {\n+ formatted2 = formatCode(formatted, options);\n+ }\n+\n self.postMessage({\n formatted: formatted,\n doc: doc,\n<|current_version|>\n return false;\n }\n};\n// eslint-disable-next-line\nfs = module$1 = module = path = os = crypto = {};\nself.process = { argv: [], env: { PRETTIER_DEBUG: true } };\nself.assert = { ok: function() {}, strictEqual: function() {} };\nself.require = function require(path) {\n return self[path.replace(/.+-/, \"\")];\n};\n\nimportScripts(\"lib/index.js\");\nvar prettier = index; // eslint-disable-line\n\nvar parsersLoaded = {};\n\nself.onmessage = function(message) {\n var options = message.data.options || {};\n options.parser = options.parser || \"babylon\";\n\n delete options.ast;\n delete options.doc;\n delete options.output2;\n\n var formatted = formatCode(message.data.text, options);\n var doc;\n var ast;\n var formatted2;\n\n if (message.data.ast) {\n var actualAst;\n var errored = false;\n try {\n actualAst = prettier.__debug.parse(message.data.text, options);\n ast = JSON.stringify(actualAst);\n } catch (e) {\n errored = true;\n ast = String(e);\n }\n if (!errored) {\n try {\n ast = formatCode(ast, { parser: \"json\" });\n } catch (e) {\n ast = JSON.stringify(actualAst, null, 2);\n }\n }\n }\n\n if (message.data.doc) {\n lazyLoadParser(\"babylon\");\n try {\n doc = prettier.__debug.formatDoc(\n prettier.__debug.printToDoc(message.data.text, options),\n { parser: \"babylon\" }\n );\n } catch (e) {\n doc = String(e);\n }\n }\n\n if (message.data.formatted2) {\n formatted2 = formatCode(formatted, options);\n }\n\n self.postMessage({\n formatted: formatted,\n doc: doc,\n ast: ast,\n version: prettier.version\n });\n};\n\nfunction formatCode(text, options) {\n lazyLoadParser(options.parser);\n try {\n return prettier.format(text, options);\n } catch (e) {\n // Multiparser may throw if we haven't loaded the right parser\n // Load it lazily and retry!\n if (e.parser && !parsersLoaded[e.parser]) {\n lazyLoadParser(e.parser);\n return formatCode(text, options);\n }\n return String(e);\n }\n}\n\nfunction lazyLoadParser(parser) {\n var script =\n parser === \"json\" ? \"parser-babylon.js\" : \"parser-\" + parser + \".js\";\n\n if (!parsersLoaded[parser]) {\n<|next_version|>\n return false;\n }\n};\n// eslint-disable-next-line\nfs = module$1 = module = path = os = crypto = {};\nself.process = { argv: [], env: { PRETTIER_DEBUG: true } };\nself.assert = { ok: function() {}, strictEqual: function() {} };\nself.require = function require(path) {\n return self[path.replace(/.+-/, \"\")];\n};\n\nimportScripts(\"lib/index.js\");\nvar prettier = index; // eslint-disable-line\n\nvar parsersLoaded = {};\n\nself.onmessage = function(message) {\n var options = message.data.options || {};\n options.parser = options.parser || \"babylon\";\n\n delete options.ast;\n delete options.doc;\n delete options.output2;\n\n var formatted = formatCode(message.data.text, options);\n var doc;\n var ast;\n var formatted2;\n\n if (message.data.ast) {\n var actualAst;\n var errored = false;\n try {\n actualAst = prettier.__debug.parse(message.data.text, options);\n ast = JSON.stringify(actualAst);\n } catch (e) {\n errored = true;\n ast = String(e);\n }\n if (!errored) {\n try {\n ast = formatCode(ast, { parser: \"json\" });\n } catch (e) {\n ast = JSON.stringify(actualAst, null, 2);\n }\n }\n }\n\n if (message.data.doc) {\n lazyLoadParser(\"babylon\");\n try {\n doc = prettier.__debug.formatDoc(\n prettier.__debug.printToDoc(message.data.text, options),\n { parser: \"babylon\" }\n );\n } catch (e) {\n doc = String(e);\n }\n }\n\n if (message.data.formatted2) {\n formatted2 = formatCode(formatted, options);\n }\n\n self.postMessage({\n formatted: formatted,\n doc: doc,\n ast: ast,\n formatted2: formatted2,\n version: prettier.version\n });\n};\n\nfunction formatCode(text, options) {\n lazyLoadParser(options.parser);\n try {\n return prettier.format(text, options);\n } catch (e) {\n // Multiparser may throw if we haven't loaded the right parser\n // Load it lazily and retry!\n if (e.parser && !parsersLoaded[e.parser]) {\n lazyLoadParser(e.parser);\n return formatCode(text, options);\n }\n return String(e);\n }\n}\n\nfunction lazyLoadParser(parser) {\n var script =\n parser === \"json\" ? \"parser-babylon.js\" : \"parser-\" + parser + \".js\";\n\n if (!parsersLoaded[parser]) {\n", "current_contents": " return false;\n }\n};\n// eslint-disable-next-line\nfs = module$1 = module = path = os = crypto = {};\nself.process = { argv: [], env: { PRETTIER_DEBUG: true } };\nself.assert = { ok: function() {}, strictEqual: function() {} };\nself.require = function require(path) {\n return self[path.replace(/.+-/, \"\")];\n};\n\nimportScripts(\"lib/index.js\");\nvar prettier = index; // eslint-disable-line\n\nvar parsersLoaded = {};\n\nself.onmessage = function(message) {\n var options = message.data.options || {};\n options.parser = options.parser || \"babylon\";\n\n delete options.ast;\n delete options.doc;\n delete options.output2;\n\n var formatted = formatCode(message.data.text, options);\n var doc;\n var ast;\n var formatted2;\n\n if (message.data.ast) {\n var actualAst;\n var errored = false;\n try {\n actualAst = prettier.__debug.parse(message.data.text, options);\n ast = JSON.stringify(actualAst);\n } catch (e) {\n errored = true;\n ast = String(e);\n }\n if (!errored) {\n try {\n ast = formatCode(ast, { parser: \"json\" });\n } catch (e) {\n ast = JSON.stringify(actualAst, null, 2);\n }\n }\n }\n\n if (message.data.doc) {\n lazyLoadParser(\"babylon\");\n try {\n doc = prettier.__debug.formatDoc(\n prettier.__debug.printToDoc(message.data.text, options),\n { parser: \"babylon\" }\n );\n } catch (e) {\n doc = String(e);\n }\n }\n\n if (message.data.formatted2) {\n formatted2 = formatCode(formatted, options);\n }\n\n self.postMessage({\n formatted: formatted,\n doc: doc,\n ast: ast,\n version: prettier.version\n });\n};\n\nfunction formatCode(text, options) {\n lazyLoadParser(options.parser);\n try {\n return prettier.format(text, options);\n } catch (e) {\n // Multiparser may throw if we haven't loaded the right parser\n // Load it lazily and retry!\n if (e.parser && !parsersLoaded[e.parser]) {\n lazyLoadParser(e.parser);\n return formatCode(text, options);\n }\n return String(e);\n }\n}\n\nfunction lazyLoadParser(parser) {\n var script =\n parser === \"json\" ? \"parser-babylon.js\" : \"parser-\" + parser + \".js\";\n\n if (!parsersLoaded[parser]) {"} {"commit": "708ac4cdf5cd0a658d62490a9f4d78d3e1ec6612", "message": "Fix handling very large stacks of sync middleware", "old_file": "lib/router/route.js", "new_file": "lib/router/route.js", "status": "M", "old_contents": "\n // append automatic head\n if (this.methods.get && !this.methods.head) {\n methods.push('head');\n }\n\n for (var i = 0; i < methods.length; i++) {\n // make upper case\n methods[i] = methods[i].toUpperCase();\n }\n\n return methods;\n};\n\n/**\n * dispatch req, res into this route\n * @private\n */\n\nRoute.prototype.dispatch = function dispatch(req, res, done) {\n var idx = 0;\n var stack = this.stack;\n if (stack.length === 0) {\n return done();\n }\n\n var method = req.method.toLowerCase();\n if (method === 'head' && !this.methods['head']) {\n method = 'get';\n }\n\n req.route = this;\n\n next();\n\n function next(err) {\n // signal to exit route\n if (err && err === 'route') {\n return done();\n }\n\n // signal to exit router\n if (err && err === 'router') {\n return done(err)\n }\n\n var layer = stack[idx++];\n if (!layer) {\n return done(err);\n }\n\n if (layer.method && layer.method !== method) {\n return next(err);\n }\n\n if (err) {\n layer.handle_error(err, req, res, next);\n } else {\n layer.handle_request(req, res, next);\n }\n }\n};\n\n/**\n * Add a handler for all HTTP verbs to this route.\n *\n * Behaves just like middleware and can respond or call `next`\n * to continue processing.\n *\n * You can use multiple `.all` call to add multiple handlers.\n *\n * function check_something(req, res, next){\n * next();\n * };\n *\n * function validate_user(req, res, next){\n * next();\n * };\n *\n * route\n * .all(validate_user)\n * .all(check_something)\n * .get(function(req, res, next){\n * res.send('hello world');", "new_contents": "\n // append automatic head\n if (this.methods.get && !this.methods.head) {\n methods.push('head');\n }\n\n for (var i = 0; i < methods.length; i++) {\n // make upper case\n methods[i] = methods[i].toUpperCase();\n }\n\n return methods;\n};\n\n/**\n * dispatch req, res into this route\n * @private\n */\n\nRoute.prototype.dispatch = function dispatch(req, res, done) {\n var idx = 0;\n var stack = this.stack;\n var sync = 0\n\n if (stack.length === 0) {\n return done();\n }\n\n var method = req.method.toLowerCase();\n if (method === 'head' && !this.methods['head']) {\n method = 'get';\n }\n\n req.route = this;\n\n next();\n\n function next(err) {\n // signal to exit route\n if (err && err === 'route') {\n return done();\n }\n\n // signal to exit router\n if (err && err === 'router') {\n return done(err)\n }\n\n var layer = stack[idx++];\n if (!layer) {\n return done(err);\n }\n\n // max sync stack\n if (++sync > 100) {\n return setImmediate(next, err)\n }\n\n if (layer.method && layer.method !== method) {\n return next(err);\n }\n\n if (err) {\n layer.handle_error(err, req, res, next);\n } else {\n layer.handle_request(req, res, next);\n }\n\n sync = 0\n }\n};\n\n/**\n * Add a handler for all HTTP verbs to this route.\n *\n * Behaves just like middleware and can respond or call `next`\n * to continue processing.\n *\n * You can use multiple `.all` call to add multiple handlers.\n *\n * function check_something(req, res, next){\n * next();\n * };\n *\n * function validate_user(req, res, next){\n * next();\n * };\n *\n * route\n * .all(validate_user)\n * .all(check_something)\n * .get(function(req, res, next){\n * res.send('hello world');", "text": "<|original_code|>\n\n // append automatic head\n if (this.methods.get && !this.methods.head) {\n methods.push('head');\n }\n\n for (var i = 0; i < methods.length; i++) {\n // make upper case\n methods[i] = methods[i].toUpperCase();\n }\n\n return methods;\n};\n\n/**\n * dispatch req, res into this route\n * @private\n */\n\nRoute.prototype.dispatch = function dispatch(req, res, done) {\n var idx = 0;\n var stack = this.stack;\n if (stack.length === 0) {\n return done();\n }\n\n var method = req.method.toLowerCase();\n if (method === 'head' && !this.methods['head']) {\n method = 'get';\n }\n\n req.route = this;\n\n next();\n\n function next(err) {\n // signal to exit route\n if (err && err === 'route') {\n return done();\n }\n\n // signal to exit router\n if (err && err === 'router') {\n return done(err)\n }\n\n var layer = stack[idx++];\n if (!layer) {\n return done(err);\n }\n\n if (layer.method && layer.method !== method) {\n return next(err);\n }\n\n if (err) {\n layer.handle_error(err, req, res, next);\n } else {\n layer.handle_request(req, res, next);\n }\n }\n};\n\n/**\n * Add a handler for all HTTP verbs to this route.\n *\n * Behaves just like middleware and can respond or call `next`\n * to continue processing.\n *\n * You can use multiple `.all` call to add multiple handlers.\n *\n * function check_something(req, res, next){\n * next();\n * };\n *\n * function validate_user(req, res, next){\n * next();\n * };\n *\n * route\n * .all(validate_user)\n * .all(check_something)\n * .get(function(req, res, next){\n * res.send('hello world');\n<|edits_diff|>\n--- lib/router/route.js\n+++ lib/router/route.js\n@@ -20,6 +20,8 @@\n Route.prototype.dispatch = function dispatch(req, res, done) {\n var idx = 0;\n var stack = this.stack;\n+ var sync = 0\n+\n if (stack.length === 0) {\n return done();\n }\n@@ -47,6 +49,11 @@\n var layer = stack[idx++];\n if (!layer) {\n return done(err);\n+ }\n+\n+ // max sync stack\n+ if (++sync > 100) {\n+ return setImmediate(next, err)\n }\n \n if (layer.method && layer.method !== method) {\n<|current_version|>\n\n // append automatic head\n if (this.methods.get && !this.methods.head) {\n methods.push('head');\n }\n\n for (var i = 0; i < methods.length; i++) {\n // make upper case\n methods[i] = methods[i].toUpperCase();\n }\n\n return methods;\n};\n\n/**\n * dispatch req, res into this route\n * @private\n */\n\nRoute.prototype.dispatch = function dispatch(req, res, done) {\n var idx = 0;\n var stack = this.stack;\n var sync = 0\n\n if (stack.length === 0) {\n return done();\n }\n\n var method = req.method.toLowerCase();\n if (method === 'head' && !this.methods['head']) {\n method = 'get';\n }\n\n req.route = this;\n\n next();\n\n function next(err) {\n // signal to exit route\n if (err && err === 'route') {\n return done();\n }\n\n // signal to exit router\n if (err && err === 'router') {\n return done(err)\n }\n\n var layer = stack[idx++];\n if (!layer) {\n return done(err);\n }\n\n // max sync stack\n if (++sync > 100) {\n return setImmediate(next, err)\n }\n\n if (layer.method && layer.method !== method) {\n return next(err);\n }\n\n if (err) {\n layer.handle_error(err, req, res, next);\n } else {\n layer.handle_request(req, res, next);\n }\n }\n};\n\n/**\n * Add a handler for all HTTP verbs to this route.\n *\n * Behaves just like middleware and can respond or call `next`\n * to continue processing.\n *\n * You can use multiple `.all` call to add multiple handlers.\n *\n * function check_something(req, res, next){\n * next();\n * };\n *\n * function validate_user(req, res, next){\n * next();\n * };\n *\n * route\n * .all(validate_user)\n * .all(check_something)\n * .get(function(req, res, next){\n * res.send('hello world');\n<|next_version|>\n\n // append automatic head\n if (this.methods.get && !this.methods.head) {\n methods.push('head');\n }\n\n for (var i = 0; i < methods.length; i++) {\n // make upper case\n methods[i] = methods[i].toUpperCase();\n }\n\n return methods;\n};\n\n/**\n * dispatch req, res into this route\n * @private\n */\n\nRoute.prototype.dispatch = function dispatch(req, res, done) {\n var idx = 0;\n var stack = this.stack;\n var sync = 0\n\n if (stack.length === 0) {\n return done();\n }\n\n var method = req.method.toLowerCase();\n if (method === 'head' && !this.methods['head']) {\n method = 'get';\n }\n\n req.route = this;\n\n next();\n\n function next(err) {\n // signal to exit route\n if (err && err === 'route') {\n return done();\n }\n\n // signal to exit router\n if (err && err === 'router') {\n return done(err)\n }\n\n var layer = stack[idx++];\n if (!layer) {\n return done(err);\n }\n\n // max sync stack\n if (++sync > 100) {\n return setImmediate(next, err)\n }\n\n if (layer.method && layer.method !== method) {\n return next(err);\n }\n\n if (err) {\n layer.handle_error(err, req, res, next);\n } else {\n layer.handle_request(req, res, next);\n }\n\n sync = 0\n }\n};\n\n/**\n * Add a handler for all HTTP verbs to this route.\n *\n * Behaves just like middleware and can respond or call `next`\n * to continue processing.\n *\n * You can use multiple `.all` call to add multiple handlers.\n *\n * function check_something(req, res, next){\n * next();\n * };\n *\n * function validate_user(req, res, next){\n * next();\n * };\n *\n * route\n * .all(validate_user)\n * .all(check_something)\n * .get(function(req, res, next){\n * res.send('hello world');\n", "current_contents": "\n // append automatic head\n if (this.methods.get && !this.methods.head) {\n methods.push('head');\n }\n\n for (var i = 0; i < methods.length; i++) {\n // make upper case\n methods[i] = methods[i].toUpperCase();\n }\n\n return methods;\n};\n\n/**\n * dispatch req, res into this route\n * @private\n */\n\nRoute.prototype.dispatch = function dispatch(req, res, done) {\n var idx = 0;\n var stack = this.stack;\n var sync = 0\n\n if (stack.length === 0) {\n return done();\n }\n\n var method = req.method.toLowerCase();\n if (method === 'head' && !this.methods['head']) {\n method = 'get';\n }\n\n req.route = this;\n\n next();\n\n function next(err) {\n // signal to exit route\n if (err && err === 'route') {\n return done();\n }\n\n // signal to exit router\n if (err && err === 'router') {\n return done(err)\n }\n\n var layer = stack[idx++];\n if (!layer) {\n return done(err);\n }\n\n // max sync stack\n if (++sync > 100) {\n return setImmediate(next, err)\n }\n\n if (layer.method && layer.method !== method) {\n return next(err);\n }\n\n if (err) {\n layer.handle_error(err, req, res, next);\n } else {\n layer.handle_request(req, res, next);\n }\n }\n};\n\n/**\n * Add a handler for all HTTP verbs to this route.\n *\n * Behaves just like middleware and can respond or call `next`\n * to continue processing.\n *\n * You can use multiple `.all` call to add multiple handlers.\n *\n * function check_something(req, res, next){\n * next();\n * };\n *\n * function validate_user(req, res, next){\n * next();\n * };\n *\n * route\n * .all(validate_user)\n * .all(check_something)\n * .get(function(req, res, next){\n * res.send('hello world');"} {"commit": "d7dfe3e8123cd54cba24ab9d9d3959448b28d9e7", "message": "expose router", "old_file": "lib/express.js", "new_file": "lib/express.js", "status": "M", "old_contents": "\n/*!\n * Express\n * Copyright(c) 2010 TJ Holowaychuk \n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar http = require('http')\n , connect = require('connect')\n , proto = require('./application')\n , Route = require('./router/route')\n , req = require('./request')\n , res = require('./response')\n , utils = connect.utils;\n\n/**\n * Expose `createApplication()`.\n */\n\nexports = module.exports = createApplication;\n\n/**\n * Framework version.\n */\n\nexports.version = '3.0.0alpha1-pre';\n\n/**\n * Create an express application.\n *\n * @return {Function}\n * @api public\n */\n\nfunction createApplication() {\n var app = connect();\n utils.merge(app, proto);\n app.request = { __proto__: req };\n app.response = { __proto__: res };\n app.init();\n return app;\n}\n\n/**\n * Expose connect.middleware as express.*\n * for example `express.logger` etc. \n */\n\nfor (var key in connect.middleware) {\n Object.defineProperty(\n exports\n , key\n , Object.getOwnPropertyDescriptor(connect.middleware, key));\n}\n\n/**\n * Expose the prototypes.\n */\n\nexports.application = proto;\nexports.request = req;\nexports.response = res;\n\n/**\n * Expose constructors.\n */\n\nexports.Route = Route;\n\n/**\n * Expose HTTP methods.\n */\n\nexports.methods = require('./router/methods');\n\n// Error handler title\n\nexports.errorHandler.title = 'Express';\n\n", "new_contents": "\n/*!\n * Express\n * Copyright(c) 2010 TJ Holowaychuk \n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar http = require('http')\n , connect = require('connect')\n , proto = require('./application')\n , Route = require('./router/route')\n , Router = require('./router')\n , req = require('./request')\n , res = require('./response')\n , utils = connect.utils;\n\n/**\n * Expose `createApplication()`.\n */\n\nexports = module.exports = createApplication;\n\n/**\n * Framework version.\n */\n\nexports.version = '3.0.0alpha1-pre';\n\n/**\n * Create an express application.\n *\n * @return {Function}\n * @api public\n */\n\nfunction createApplication() {\n var app = connect();\n utils.merge(app, proto);\n app.request = { __proto__: req };\n app.response = { __proto__: res };\n app.init();\n return app;\n}\n\n/**\n * Expose connect.middleware as express.*\n * for example `express.logger` etc. \n */\n\nfor (var key in connect.middleware) {\n Object.defineProperty(\n exports\n , key\n , Object.getOwnPropertyDescriptor(connect.middleware, key));\n}\n\n/**\n * Expose the prototypes.\n */\n\nexports.application = proto;\nexports.request = req;\nexports.response = res;\n\n/**\n * Expose constructors.\n */\n\nexports.Route = Route;\nexports.Router = Router;\n\n/**\n * Expose HTTP methods.\n */\n\nexports.methods = require('./router/methods');\n\n// Error handler title\n\nexports.errorHandler.title = 'Express';\n\n", "text": "<|original_code|>\n\n/*!\n * Express\n * Copyright(c) 2010 TJ Holowaychuk \n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar http = require('http')\n , connect = require('connect')\n , proto = require('./application')\n , Route = require('./router/route')\n , req = require('./request')\n , res = require('./response')\n , utils = connect.utils;\n\n/**\n * Expose `createApplication()`.\n */\n\nexports = module.exports = createApplication;\n\n/**\n * Framework version.\n */\n\nexports.version = '3.0.0alpha1-pre';\n\n/**\n * Create an express application.\n *\n * @return {Function}\n * @api public\n */\n\nfunction createApplication() {\n var app = connect();\n utils.merge(app, proto);\n app.request = { __proto__: req };\n app.response = { __proto__: res };\n app.init();\n return app;\n}\n\n/**\n * Expose connect.middleware as express.*\n * for example `express.logger` etc. \n */\n\nfor (var key in connect.middleware) {\n Object.defineProperty(\n exports\n , key\n , Object.getOwnPropertyDescriptor(connect.middleware, key));\n}\n\n/**\n * Expose the prototypes.\n */\n\nexports.application = proto;\nexports.request = req;\nexports.response = res;\n\n/**\n * Expose constructors.\n */\n\nexports.Route = Route;\n\n/**\n * Expose HTTP methods.\n */\n\nexports.methods = require('./router/methods');\n\n// Error handler title\n\nexports.errorHandler.title = 'Express';\n\n\n<|edits_diff|>\n--- lib/express.js\n+++ lib/express.js\n@@ -13,6 +13,7 @@\n , connect = require('connect')\n , proto = require('./application')\n , Route = require('./router/route')\n+ , Router = require('./router')\n , req = require('./request')\n , res = require('./response')\n , utils = connect.utils;\n<|current_version|>\n\n/*!\n * Express\n * Copyright(c) 2010 TJ Holowaychuk \n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar http = require('http')\n , connect = require('connect')\n , proto = require('./application')\n , Route = require('./router/route')\n , Router = require('./router')\n , req = require('./request')\n , res = require('./response')\n , utils = connect.utils;\n\n/**\n * Expose `createApplication()`.\n */\n\nexports = module.exports = createApplication;\n\n/**\n * Framework version.\n */\n\nexports.version = '3.0.0alpha1-pre';\n\n/**\n * Create an express application.\n *\n * @return {Function}\n * @api public\n */\n\nfunction createApplication() {\n var app = connect();\n utils.merge(app, proto);\n app.request = { __proto__: req };\n app.response = { __proto__: res };\n app.init();\n return app;\n}\n\n/**\n * Expose connect.middleware as express.*\n * for example `express.logger` etc. \n */\n\nfor (var key in connect.middleware) {\n Object.defineProperty(\n exports\n , key\n , Object.getOwnPropertyDescriptor(connect.middleware, key));\n}\n\n/**\n * Expose the prototypes.\n */\n\nexports.application = proto;\nexports.request = req;\nexports.response = res;\n\n/**\n * Expose constructors.\n */\n\nexports.Route = Route;\n\n/**\n * Expose HTTP methods.\n */\n\nexports.methods = require('./router/methods');\n\n// Error handler title\n\nexports.errorHandler.title = 'Express';\n\n\n<|next_version|>\n\n/*!\n * Express\n * Copyright(c) 2010 TJ Holowaychuk \n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar http = require('http')\n , connect = require('connect')\n , proto = require('./application')\n , Route = require('./router/route')\n , Router = require('./router')\n , req = require('./request')\n , res = require('./response')\n , utils = connect.utils;\n\n/**\n * Expose `createApplication()`.\n */\n\nexports = module.exports = createApplication;\n\n/**\n * Framework version.\n */\n\nexports.version = '3.0.0alpha1-pre';\n\n/**\n * Create an express application.\n *\n * @return {Function}\n * @api public\n */\n\nfunction createApplication() {\n var app = connect();\n utils.merge(app, proto);\n app.request = { __proto__: req };\n app.response = { __proto__: res };\n app.init();\n return app;\n}\n\n/**\n * Expose connect.middleware as express.*\n * for example `express.logger` etc. \n */\n\nfor (var key in connect.middleware) {\n Object.defineProperty(\n exports\n , key\n , Object.getOwnPropertyDescriptor(connect.middleware, key));\n}\n\n/**\n * Expose the prototypes.\n */\n\nexports.application = proto;\nexports.request = req;\nexports.response = res;\n\n/**\n * Expose constructors.\n */\n\nexports.Route = Route;\nexports.Router = Router;\n\n/**\n * Expose HTTP methods.\n */\n\nexports.methods = require('./router/methods');\n\n// Error handler title\n\nexports.errorHandler.title = 'Express';\n\n\n", "current_contents": "\n/*!\n * Express\n * Copyright(c) 2010 TJ Holowaychuk \n * MIT Licensed\n */\n\n/**\n * Module dependencies.\n */\n\nvar http = require('http')\n , connect = require('connect')\n , proto = require('./application')\n , Route = require('./router/route')\n , Router = require('./router')\n , req = require('./request')\n , res = require('./response')\n , utils = connect.utils;\n\n/**\n * Expose `createApplication()`.\n */\n\nexports = module.exports = createApplication;\n\n/**\n * Framework version.\n */\n\nexports.version = '3.0.0alpha1-pre';\n\n/**\n * Create an express application.\n *\n * @return {Function}\n * @api public\n */\n\nfunction createApplication() {\n var app = connect();\n utils.merge(app, proto);\n app.request = { __proto__: req };\n app.response = { __proto__: res };\n app.init();\n return app;\n}\n\n/**\n * Expose connect.middleware as express.*\n * for example `express.logger` etc. \n */\n\nfor (var key in connect.middleware) {\n Object.defineProperty(\n exports\n , key\n , Object.getOwnPropertyDescriptor(connect.middleware, key));\n}\n\n/**\n * Expose the prototypes.\n */\n\nexports.application = proto;\nexports.request = req;\nexports.response = res;\n\n/**\n * Expose constructors.\n */\n\nexports.Route = Route;\n\n/**\n * Expose HTTP methods.\n */\n\nexports.methods = require('./router/methods');\n\n// Error handler title\n\nexports.errorHandler.title = 'Express';\n\n"} {"commit": "ecbc3cae71768ec0192af41f80f305614fa9c826", "message": "res.send() as 204. Closes #419", "old_file": "test/response.test.js", "new_file": "test/response.test.js", "status": "M", "old_contents": " app.get('/json', function(req, res){\n res.header('X-Foo', 'bar');\n res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);\n });\n \n app.get('/text', function(req, res){\n res.header('X-Foo', 'bar');\n res.contentType('.txt');\n res.send('wahoo');\n });\n \n app.get('/status', function(req, res){\n res.send(404);\n });\n \n app.get('/error', function(req, res){\n res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);\n });\n \n app.get('/buffer', function(req, res){\n res.send(new Buffer('wahoo!'));\n });\n\n assert.response(app,\n { url: '/html' },\n { body: '

test

', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});\n assert.response(app,\n { url: '/json' },\n { body: '{\"foo\":\"bar\"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});\n assert.response(app,\n { url: '/text' },\n { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});\n assert.response(app,\n { url: '/status' },\n { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});\n assert.response(app,\n { url: '/error' },\n { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});\n assert.response(app,\n { url: '/buffer' },\n { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});\n },\n \n 'test #contentType()': function(assert){\n var app = express.createServer();\n \n app.get('/html', function(req, res){\n res.contentType('index.html');\n res.writeHead(200, res.headers);\n res.end('

yay

');\n });\n \n assert.response(app,\n { url: '/html' },\n { body: '

yay

', headers: { 'Content-Type': 'text/html; charset=utf-8' }});\n },\n \n 'test #attachment()': function(assert){\n var app = express.createServer();\n \n app.get('/style.css', function(req, res){\n res.attachment();\n res.send('some stylezzz');\n });\n", "new_contents": " app.get('/json', function(req, res){\n res.header('X-Foo', 'bar');\n res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);\n });\n \n app.get('/text', function(req, res){\n res.header('X-Foo', 'bar');\n res.contentType('.txt');\n res.send('wahoo');\n });\n \n app.get('/status', function(req, res){\n res.send(404);\n });\n \n app.get('/error', function(req, res){\n res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);\n });\n \n app.get('/buffer', function(req, res){\n res.send(new Buffer('wahoo!'));\n });\n \n app.get('/noargs', function(req, res, next){\n res.send();\n });\n\n assert.response(app,\n { url: '/html' },\n { body: '

test

', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});\n assert.response(app,\n { url: '/json' },\n { body: '{\"foo\":\"bar\"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});\n assert.response(app,\n { url: '/text' },\n { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});\n assert.response(app,\n { url: '/status' },\n { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});\n assert.response(app,\n { url: '/error' },\n { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});\n assert.response(app,\n { url: '/buffer' },\n { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});\n assert.response(app,\n { url: '/noargs' },\n { status: 204 });\n },\n \n 'test #contentType()': function(assert){\n var app = express.createServer();\n \n app.get('/html', function(req, res){\n res.contentType('index.html');\n res.writeHead(200, res.headers);\n res.end('

yay

');\n });\n \n assert.response(app,\n { url: '/html' },\n { body: '

yay

', headers: { 'Content-Type': 'text/html; charset=utf-8' }});\n },\n \n 'test #attachment()': function(assert){\n var app = express.createServer();\n \n app.get('/style.css', function(req, res){\n res.attachment();\n res.send('some stylezzz');\n });\n", "text": "<|original_code|>\n app.get('/json', function(req, res){\n res.header('X-Foo', 'bar');\n res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);\n });\n \n app.get('/text', function(req, res){\n res.header('X-Foo', 'bar');\n res.contentType('.txt');\n res.send('wahoo');\n });\n \n app.get('/status', function(req, res){\n res.send(404);\n });\n \n app.get('/error', function(req, res){\n res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);\n });\n \n app.get('/buffer', function(req, res){\n res.send(new Buffer('wahoo!'));\n });\n\n assert.response(app,\n { url: '/html' },\n { body: '

test

', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});\n assert.response(app,\n { url: '/json' },\n { body: '{\"foo\":\"bar\"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});\n assert.response(app,\n { url: '/text' },\n { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});\n assert.response(app,\n { url: '/status' },\n { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});\n assert.response(app,\n { url: '/error' },\n { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});\n assert.response(app,\n { url: '/buffer' },\n { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});\n },\n \n 'test #contentType()': function(assert){\n var app = express.createServer();\n \n app.get('/html', function(req, res){\n res.contentType('index.html');\n res.writeHead(200, res.headers);\n res.end('

yay

');\n });\n \n assert.response(app,\n { url: '/html' },\n { body: '

yay

', headers: { 'Content-Type': 'text/html; charset=utf-8' }});\n },\n \n 'test #attachment()': function(assert){\n var app = express.createServer();\n \n app.get('/style.css', function(req, res){\n res.attachment();\n res.send('some stylezzz');\n });\n\n<|edits_diff|>\n--- test/response.test.js\n+++ test/response.test.js\n@@ -19,6 +19,10 @@\n \n app.get('/buffer', function(req, res){\n res.send(new Buffer('wahoo!'));\n+ });\n+ \n+ app.get('/noargs', function(req, res, next){\n+ res.send();\n });\n \n assert.response(app,\n<|current_version|>\n app.get('/json', function(req, res){\n res.header('X-Foo', 'bar');\n res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);\n });\n \n app.get('/text', function(req, res){\n res.header('X-Foo', 'bar');\n res.contentType('.txt');\n res.send('wahoo');\n });\n \n app.get('/status', function(req, res){\n res.send(404);\n });\n \n app.get('/error', function(req, res){\n res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);\n });\n \n app.get('/buffer', function(req, res){\n res.send(new Buffer('wahoo!'));\n });\n \n app.get('/noargs', function(req, res, next){\n res.send();\n });\n\n assert.response(app,\n { url: '/html' },\n { body: '

test

', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});\n assert.response(app,\n { url: '/json' },\n { body: '{\"foo\":\"bar\"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});\n assert.response(app,\n { url: '/text' },\n { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});\n assert.response(app,\n { url: '/status' },\n { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});\n assert.response(app,\n { url: '/error' },\n { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});\n assert.response(app,\n { url: '/buffer' },\n { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});\n },\n \n 'test #contentType()': function(assert){\n var app = express.createServer();\n \n app.get('/html', function(req, res){\n res.contentType('index.html');\n res.writeHead(200, res.headers);\n res.end('

yay

');\n });\n \n assert.response(app,\n { url: '/html' },\n { body: '

yay

', headers: { 'Content-Type': 'text/html; charset=utf-8' }});\n },\n \n 'test #attachment()': function(assert){\n var app = express.createServer();\n \n app.get('/style.css', function(req, res){\n res.attachment();\n res.send('some stylezzz');\n });\n\n<|next_version|>\n app.get('/json', function(req, res){\n res.header('X-Foo', 'bar');\n res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);\n });\n \n app.get('/text', function(req, res){\n res.header('X-Foo', 'bar');\n res.contentType('.txt');\n res.send('wahoo');\n });\n \n app.get('/status', function(req, res){\n res.send(404);\n });\n \n app.get('/error', function(req, res){\n res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);\n });\n \n app.get('/buffer', function(req, res){\n res.send(new Buffer('wahoo!'));\n });\n \n app.get('/noargs', function(req, res, next){\n res.send();\n });\n\n assert.response(app,\n { url: '/html' },\n { body: '

test

', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});\n assert.response(app,\n { url: '/json' },\n { body: '{\"foo\":\"bar\"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});\n assert.response(app,\n { url: '/text' },\n { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});\n assert.response(app,\n { url: '/status' },\n { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});\n assert.response(app,\n { url: '/error' },\n { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});\n assert.response(app,\n { url: '/buffer' },\n { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});\n assert.response(app,\n { url: '/noargs' },\n { status: 204 });\n },\n \n 'test #contentType()': function(assert){\n var app = express.createServer();\n \n app.get('/html', function(req, res){\n res.contentType('index.html');\n res.writeHead(200, res.headers);\n res.end('

yay

');\n });\n \n assert.response(app,\n { url: '/html' },\n { body: '

yay

', headers: { 'Content-Type': 'text/html; charset=utf-8' }});\n },\n \n 'test #attachment()': function(assert){\n var app = express.createServer();\n \n app.get('/style.css', function(req, res){\n res.attachment();\n res.send('some stylezzz');\n });\n\n", "current_contents": " app.get('/json', function(req, res){\n res.header('X-Foo', 'bar');\n res.send({ foo: 'bar' }, { 'X-Foo': 'baz' }, 201);\n });\n \n app.get('/text', function(req, res){\n res.header('X-Foo', 'bar');\n res.contentType('.txt');\n res.send('wahoo');\n });\n \n app.get('/status', function(req, res){\n res.send(404);\n });\n \n app.get('/error', function(req, res){\n res.send('Oh shit!', { 'Content-Type': 'text/plain' }, 500);\n });\n \n app.get('/buffer', function(req, res){\n res.send(new Buffer('wahoo!'));\n });\n \n app.get('/noargs', function(req, res, next){\n res.send();\n });\n\n assert.response(app,\n { url: '/html' },\n { body: '

test

', headers: { 'Content-Language': 'en', 'Content-Type': 'text/html; charset=utf-8' }});\n assert.response(app,\n { url: '/json' },\n { body: '{\"foo\":\"bar\"}', status: 201, headers: { 'Content-Type': 'application/json', 'X-Foo': 'baz' }});\n assert.response(app,\n { url: '/text' },\n { body: 'wahoo', headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Foo': 'bar' }});\n assert.response(app,\n { url: '/status' },\n { body: 'Not Found', status: 404, headers: { 'Content-Type': 'text/plain; charset=utf-8' }});\n assert.response(app,\n { url: '/error' },\n { body: 'Oh shit!', status: 500, headers: { 'Content-Type': 'text/plain' }});\n assert.response(app,\n { url: '/buffer' },\n { body: 'wahoo!', headers: { 'Content-Type': 'application/octet-stream' }});\n },\n \n 'test #contentType()': function(assert){\n var app = express.createServer();\n \n app.get('/html', function(req, res){\n res.contentType('index.html');\n res.writeHead(200, res.headers);\n res.end('

yay

');\n });\n \n assert.response(app,\n { url: '/html' },\n { body: '

yay

', headers: { 'Content-Type': 'text/html; charset=utf-8' }});\n },\n \n 'test #attachment()': function(assert){\n var app = express.createServer();\n \n app.get('/style.css', function(req, res){\n res.attachment();\n res.send('some stylezzz');\n });\n"} {"commit": "637ac18381d52f3b482cadfa4d8d7ceb886a29c5", "message": "Added mockRequest() and mockResponse()", "old_file": "spec/spec.node.js", "new_file": "spec/spec.node.js", "status": "M", "old_contents": " var promise = node.fs.cat(path, \"utf8\")\n promise.addErrback(function(){ throw \"failed to read file `\" + path + \"'\" })\n promise.addCallback(function(contents){\n setTimeout(function(){\n if (__loading__[0] == path)\n __loading__.shift(), callback(contents)\n else\n setTimeout(arguments.callee, 50)\n }, 50)\n }) \n}\n\nload = function(path) {\n readFile(path, function(contents){\n eval(contents)\n })\n}\n\nload('/Users/tjholowaychuk/scripts/gems/JSpec/lib/jspec.js')\nload('lib/express.core.js')\nload('lib/express.mime.js')\nload('lib/express.view.js')\n\nsetTimeout(function(){\n JSpec\n .exec('spec/spec.core.js')\n .exec('spec/spec.routing.js')\n .exec('spec/spec.mime.js')\n .exec('spec/spec.view.js')\n setTimeout(function(){ \n JSpec.run({ formatter : JSpec.formatters.Terminal, failuresOnly : true })\n setTimeout(function() {\n JSpec.report()\n }, __loadDelay__ / 3)\n }, __loadDelay__ / 3)\n}, __loadDelay__ / 3)\n\n", "new_contents": " var promise = node.fs.cat(path, \"utf8\")\n promise.addErrback(function(){ throw \"failed to read file `\" + path + \"'\" })\n promise.addCallback(function(contents){\n setTimeout(function(){\n if (__loading__[0] == path)\n __loading__.shift(), callback(contents)\n else\n setTimeout(arguments.callee, 50)\n }, 50)\n }) \n}\n\nload = function(path) {\n readFile(path, function(contents){\n eval(contents)\n })\n}\n\nload('/Users/tjholowaychuk/scripts/gems/JSpec/lib/jspec.js')\nload('lib/express.core.js')\nload('lib/express.mime.js')\nload('lib/express.view.js')\nload('lib/express.spec.helpers.js')\n\nsetTimeout(function(){\n JSpec\n .exec('spec/spec.core.js')\n .exec('spec/spec.routing.js')\n .exec('spec/spec.mime.js')\n .exec('spec/spec.view.js')\n .exec('spec/spec.spec.helpers.js')\n setTimeout(function(){ \n JSpec.run({ formatter : JSpec.formatters.Terminal, failuresOnly : true })\n setTimeout(function() {\n JSpec.report()\n }, __loadDelay__ / 3)\n }, __loadDelay__ / 3)\n}, __loadDelay__ / 3)\n\n", "text": "<|original_code|>\n var promise = node.fs.cat(path, \"utf8\")\n promise.addErrback(function(){ throw \"failed to read file `\" + path + \"'\" })\n promise.addCallback(function(contents){\n setTimeout(function(){\n if (__loading__[0] == path)\n __loading__.shift(), callback(contents)\n else\n setTimeout(arguments.callee, 50)\n }, 50)\n }) \n}\n\nload = function(path) {\n readFile(path, function(contents){\n eval(contents)\n })\n}\n\nload('/Users/tjholowaychuk/scripts/gems/JSpec/lib/jspec.js')\nload('lib/express.core.js')\nload('lib/express.mime.js')\nload('lib/express.view.js')\n\nsetTimeout(function(){\n JSpec\n .exec('spec/spec.core.js')\n .exec('spec/spec.routing.js')\n .exec('spec/spec.mime.js')\n .exec('spec/spec.view.js')\n setTimeout(function(){ \n JSpec.run({ formatter : JSpec.formatters.Terminal, failuresOnly : true })\n setTimeout(function() {\n JSpec.report()\n }, __loadDelay__ / 3)\n }, __loadDelay__ / 3)\n}, __loadDelay__ / 3)\n\n\n<|edits_diff|>\n--- spec/spec.node.js\n+++ spec/spec.node.js\n@@ -20,6 +20,7 @@\n load('lib/express.core.js')\n load('lib/express.mime.js')\n load('lib/express.view.js')\n+load('lib/express.spec.helpers.js')\n \n setTimeout(function(){\n JSpec\n<|current_version|>\n var promise = node.fs.cat(path, \"utf8\")\n promise.addErrback(function(){ throw \"failed to read file `\" + path + \"'\" })\n promise.addCallback(function(contents){\n setTimeout(function(){\n if (__loading__[0] == path)\n __loading__.shift(), callback(contents)\n else\n setTimeout(arguments.callee, 50)\n }, 50)\n }) \n}\n\nload = function(path) {\n readFile(path, function(contents){\n eval(contents)\n })\n}\n\nload('/Users/tjholowaychuk/scripts/gems/JSpec/lib/jspec.js')\nload('lib/express.core.js')\nload('lib/express.mime.js')\nload('lib/express.view.js')\nload('lib/express.spec.helpers.js')\n\nsetTimeout(function(){\n JSpec\n .exec('spec/spec.core.js')\n .exec('spec/spec.routing.js')\n .exec('spec/spec.mime.js')\n .exec('spec/spec.view.js')\n setTimeout(function(){ \n JSpec.run({ formatter : JSpec.formatters.Terminal, failuresOnly : true })\n setTimeout(function() {\n JSpec.report()\n }, __loadDelay__ / 3)\n }, __loadDelay__ / 3)\n}, __loadDelay__ / 3)\n\n\n<|next_version|>\n var promise = node.fs.cat(path, \"utf8\")\n promise.addErrback(function(){ throw \"failed to read file `\" + path + \"'\" })\n promise.addCallback(function(contents){\n setTimeout(function(){\n if (__loading__[0] == path)\n __loading__.shift(), callback(contents)\n else\n setTimeout(arguments.callee, 50)\n }, 50)\n }) \n}\n\nload = function(path) {\n readFile(path, function(contents){\n eval(contents)\n })\n}\n\nload('/Users/tjholowaychuk/scripts/gems/JSpec/lib/jspec.js')\nload('lib/express.core.js')\nload('lib/express.mime.js')\nload('lib/express.view.js')\nload('lib/express.spec.helpers.js')\n\nsetTimeout(function(){\n JSpec\n .exec('spec/spec.core.js')\n .exec('spec/spec.routing.js')\n .exec('spec/spec.mime.js')\n .exec('spec/spec.view.js')\n .exec('spec/spec.spec.helpers.js')\n setTimeout(function(){ \n JSpec.run({ formatter : JSpec.formatters.Terminal, failuresOnly : true })\n setTimeout(function() {\n JSpec.report()\n }, __loadDelay__ / 3)\n }, __loadDelay__ / 3)\n}, __loadDelay__ / 3)\n\n\n", "current_contents": " var promise = node.fs.cat(path, \"utf8\")\n promise.addErrback(function(){ throw \"failed to read file `\" + path + \"'\" })\n promise.addCallback(function(contents){\n setTimeout(function(){\n if (__loading__[0] == path)\n __loading__.shift(), callback(contents)\n else\n setTimeout(arguments.callee, 50)\n }, 50)\n }) \n}\n\nload = function(path) {\n readFile(path, function(contents){\n eval(contents)\n })\n}\n\nload('/Users/tjholowaychuk/scripts/gems/JSpec/lib/jspec.js')\nload('lib/express.core.js')\nload('lib/express.mime.js')\nload('lib/express.view.js')\nload('lib/express.spec.helpers.js')\n\nsetTimeout(function(){\n JSpec\n .exec('spec/spec.core.js')\n .exec('spec/spec.routing.js')\n .exec('spec/spec.mime.js')\n .exec('spec/spec.view.js')\n setTimeout(function(){ \n JSpec.run({ formatter : JSpec.formatters.Terminal, failuresOnly : true })\n setTimeout(function() {\n JSpec.report()\n }, __loadDelay__ / 3)\n }, __loadDelay__ / 3)\n}, __loadDelay__ / 3)\n\n"} {"commit": "a73b92b58e8970031664286263a623f272886a42", "message": "Avoid using the values toString method in _.invert if it’s not a function. [closes #3260]", "old_file": "lodash.js", "new_file": "lodash.js", "status": "M", "old_contents": " return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]", "new_contents": " return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]", "text": "<|original_code|>\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n<|edits_diff|>\n--- lodash.js\n+++ lodash.js\n@@ -20,6 +20,11 @@\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n+ if (value != null &&\n+ typeof value.toString != 'function') {\n+ value = nativeObjectToString.call(value);\n+ }\n+\n result[value] = key;\n }, constant(identity));\n \n<|current_version|>\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n<|next_version|>\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n", "current_contents": " return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]"} {"commit": "d216106b88ceab200d9c422bc24a1b5d4d605b24", "message": "Add private tag to unexposed functions. [ci skip]", "old_file": "lib/fp/build-doc.js", "new_file": "lib/fp/build-doc.js", "status": "M", "old_contents": " fs = require('fs-extra'),\n path = require('path');\n\nvar file = require('../common/file'),\n mapping = require('../common/mapping'),\n util = require('../common/util');\n\nvar templatePath = path.join(__dirname, 'template/doc'),\n template = file.globTemplate(path.join(templatePath, '*.jst'));\n\nvar argNames = ['a', 'b', 'c', 'd'];\n\nvar templateData = {\n 'mapping': mapping,\n 'toArgOrder': toArgOrder,\n 'toFuncList': toFuncList\n};\n\n/**\n * Converts arranged argument `indexes` into a named argument string\n * representation of their order.\n *\n * @param {number[]} indexes The arranged argument indexes.\n * @returns {string} Returns the named argument string.\n */\nfunction toArgOrder(indexes) {\n var reordered = [];\n _.each(indexes, function(newIndex, index) {\n reordered[newIndex] = argNames[index];\n });\n return '`(' + reordered.join(', ') + ')`';\n}\n\n/**\n * Converts `funcNames` into a chunked list string representation.\n *\n * @param {string[]} funcNames The function names.\n * @returns {string} Returns the function list string.\n */\nfunction toFuncList(funcNames) {\n var chunks = _.chunk(funcNames.slice().sort(), 5),\n lastChunk = _.last(chunks),\n last = lastChunk ? lastChunk.pop() : undefined;\n\n chunks = _.reject(chunks, _.isEmpty);\n lastChunk = _.last(chunks);\n\n var result = '`' + _.map(chunks, function(chunk) {\n return chunk.join('`, `') + '`';\n }).join(',\\n`');\n\n if (last == null) {\n return result;\n }\n if (_.size(chunks) > 1 || _.size(lastChunk) > 1) {\n result += ',';\n }\n result += ' &';\n result += _.size(lastChunk) < 5 ? ' ' : '\\n';\n return result + '`' + last + '`';\n}\n\n/*----------------------------------------------------------------------------*/\n\n/**\n * Creates the FP-Guide wiki at the `target` path.\n *\n * @param {string} target The output file path.\n */\nfunction build(target) {\n target = path.resolve(target);\n fs.writeFile(target, template.wiki(templateData), util.pitch);\n}\n\nbuild(_.last(process.argv));\n", "new_contents": " fs = require('fs-extra'),\n path = require('path');\n\nvar file = require('../common/file'),\n mapping = require('../common/mapping'),\n util = require('../common/util');\n\nvar templatePath = path.join(__dirname, 'template/doc'),\n template = file.globTemplate(path.join(templatePath, '*.jst'));\n\nvar argNames = ['a', 'b', 'c', 'd'];\n\nvar templateData = {\n 'mapping': mapping,\n 'toArgOrder': toArgOrder,\n 'toFuncList': toFuncList\n};\n\n/**\n * Converts arranged argument `indexes` into a named argument string\n * representation of their order.\n *\n * @private\n * @param {number[]} indexes The arranged argument indexes.\n * @returns {string} Returns the named argument string.\n */\nfunction toArgOrder(indexes) {\n var reordered = [];\n _.each(indexes, function(newIndex, index) {\n reordered[newIndex] = argNames[index];\n });\n return '`(' + reordered.join(', ') + ')`';\n}\n\n/**\n * Converts `funcNames` into a chunked list string representation.\n *\n * @private\n * @param {string[]} funcNames The function names.\n * @returns {string} Returns the function list string.\n */\nfunction toFuncList(funcNames) {\n var chunks = _.chunk(funcNames.slice().sort(), 5),\n lastChunk = _.last(chunks),\n last = lastChunk ? lastChunk.pop() : undefined;\n\n chunks = _.reject(chunks, _.isEmpty);\n lastChunk = _.last(chunks);\n\n var result = '`' + _.map(chunks, function(chunk) {\n return chunk.join('`, `') + '`';\n }).join(',\\n`');\n\n if (last == null) {\n return result;\n }\n if (_.size(chunks) > 1 || _.size(lastChunk) > 1) {\n result += ',';\n }\n result += ' &';\n result += _.size(lastChunk) < 5 ? ' ' : '\\n';\n return result + '`' + last + '`';\n}\n\n/*----------------------------------------------------------------------------*/\n\n/**\n * Creates the FP-Guide wiki at the `target` path.\n *\n * @private\n * @param {string} target The output file path.\n */\nfunction build(target) {\n target = path.resolve(target);\n fs.writeFile(target, template.wiki(templateData), util.pitch);\n}\n\nbuild(_.last(process.argv));\n", "text": "<|original_code|>\n fs = require('fs-extra'),\n path = require('path');\n\nvar file = require('../common/file'),\n mapping = require('../common/mapping'),\n util = require('../common/util');\n\nvar templatePath = path.join(__dirname, 'template/doc'),\n template = file.globTemplate(path.join(templatePath, '*.jst'));\n\nvar argNames = ['a', 'b', 'c', 'd'];\n\nvar templateData = {\n 'mapping': mapping,\n 'toArgOrder': toArgOrder,\n 'toFuncList': toFuncList\n};\n\n/**\n * Converts arranged argument `indexes` into a named argument string\n * representation of their order.\n *\n * @param {number[]} indexes The arranged argument indexes.\n * @returns {string} Returns the named argument string.\n */\nfunction toArgOrder(indexes) {\n var reordered = [];\n _.each(indexes, function(newIndex, index) {\n reordered[newIndex] = argNames[index];\n });\n return '`(' + reordered.join(', ') + ')`';\n}\n\n/**\n * Converts `funcNames` into a chunked list string representation.\n *\n * @param {string[]} funcNames The function names.\n * @returns {string} Returns the function list string.\n */\nfunction toFuncList(funcNames) {\n var chunks = _.chunk(funcNames.slice().sort(), 5),\n lastChunk = _.last(chunks),\n last = lastChunk ? lastChunk.pop() : undefined;\n\n chunks = _.reject(chunks, _.isEmpty);\n lastChunk = _.last(chunks);\n\n var result = '`' + _.map(chunks, function(chunk) {\n return chunk.join('`, `') + '`';\n }).join(',\\n`');\n\n if (last == null) {\n return result;\n }\n if (_.size(chunks) > 1 || _.size(lastChunk) > 1) {\n result += ',';\n }\n result += ' &';\n result += _.size(lastChunk) < 5 ? ' ' : '\\n';\n return result + '`' + last + '`';\n}\n\n/*----------------------------------------------------------------------------*/\n\n/**\n * Creates the FP-Guide wiki at the `target` path.\n *\n * @param {string} target The output file path.\n */\nfunction build(target) {\n target = path.resolve(target);\n fs.writeFile(target, template.wiki(templateData), util.pitch);\n}\n\nbuild(_.last(process.argv));\n\n<|edits_diff|>\n--- lib/fp/build-doc.js\n+++ lib/fp/build-doc.js\n@@ -20,6 +20,7 @@\n * Converts arranged argument `indexes` into a named argument string\n * representation of their order.\n *\n+ * @private\n * @param {number[]} indexes The arranged argument indexes.\n * @returns {string} Returns the named argument string.\n */\n@@ -34,6 +35,7 @@\n /**\n * Converts `funcNames` into a chunked list string representation.\n *\n+ * @private\n * @param {string[]} funcNames The function names.\n * @returns {string} Returns the function list string.\n */\n<|current_version|>\n fs = require('fs-extra'),\n path = require('path');\n\nvar file = require('../common/file'),\n mapping = require('../common/mapping'),\n util = require('../common/util');\n\nvar templatePath = path.join(__dirname, 'template/doc'),\n template = file.globTemplate(path.join(templatePath, '*.jst'));\n\nvar argNames = ['a', 'b', 'c', 'd'];\n\nvar templateData = {\n 'mapping': mapping,\n 'toArgOrder': toArgOrder,\n 'toFuncList': toFuncList\n};\n\n/**\n * Converts arranged argument `indexes` into a named argument string\n * representation of their order.\n *\n * @private\n * @param {number[]} indexes The arranged argument indexes.\n * @returns {string} Returns the named argument string.\n */\nfunction toArgOrder(indexes) {\n var reordered = [];\n _.each(indexes, function(newIndex, index) {\n reordered[newIndex] = argNames[index];\n });\n return '`(' + reordered.join(', ') + ')`';\n}\n\n/**\n * Converts `funcNames` into a chunked list string representation.\n *\n * @private\n * @param {string[]} funcNames The function names.\n * @returns {string} Returns the function list string.\n */\nfunction toFuncList(funcNames) {\n var chunks = _.chunk(funcNames.slice().sort(), 5),\n lastChunk = _.last(chunks),\n last = lastChunk ? lastChunk.pop() : undefined;\n\n chunks = _.reject(chunks, _.isEmpty);\n lastChunk = _.last(chunks);\n\n var result = '`' + _.map(chunks, function(chunk) {\n return chunk.join('`, `') + '`';\n }).join(',\\n`');\n\n if (last == null) {\n return result;\n }\n if (_.size(chunks) > 1 || _.size(lastChunk) > 1) {\n result += ',';\n }\n result += ' &';\n result += _.size(lastChunk) < 5 ? ' ' : '\\n';\n return result + '`' + last + '`';\n}\n\n/*----------------------------------------------------------------------------*/\n\n/**\n * Creates the FP-Guide wiki at the `target` path.\n *\n * @param {string} target The output file path.\n */\nfunction build(target) {\n target = path.resolve(target);\n fs.writeFile(target, template.wiki(templateData), util.pitch);\n}\n\nbuild(_.last(process.argv));\n\n<|next_version|>\n fs = require('fs-extra'),\n path = require('path');\n\nvar file = require('../common/file'),\n mapping = require('../common/mapping'),\n util = require('../common/util');\n\nvar templatePath = path.join(__dirname, 'template/doc'),\n template = file.globTemplate(path.join(templatePath, '*.jst'));\n\nvar argNames = ['a', 'b', 'c', 'd'];\n\nvar templateData = {\n 'mapping': mapping,\n 'toArgOrder': toArgOrder,\n 'toFuncList': toFuncList\n};\n\n/**\n * Converts arranged argument `indexes` into a named argument string\n * representation of their order.\n *\n * @private\n * @param {number[]} indexes The arranged argument indexes.\n * @returns {string} Returns the named argument string.\n */\nfunction toArgOrder(indexes) {\n var reordered = [];\n _.each(indexes, function(newIndex, index) {\n reordered[newIndex] = argNames[index];\n });\n return '`(' + reordered.join(', ') + ')`';\n}\n\n/**\n * Converts `funcNames` into a chunked list string representation.\n *\n * @private\n * @param {string[]} funcNames The function names.\n * @returns {string} Returns the function list string.\n */\nfunction toFuncList(funcNames) {\n var chunks = _.chunk(funcNames.slice().sort(), 5),\n lastChunk = _.last(chunks),\n last = lastChunk ? lastChunk.pop() : undefined;\n\n chunks = _.reject(chunks, _.isEmpty);\n lastChunk = _.last(chunks);\n\n var result = '`' + _.map(chunks, function(chunk) {\n return chunk.join('`, `') + '`';\n }).join(',\\n`');\n\n if (last == null) {\n return result;\n }\n if (_.size(chunks) > 1 || _.size(lastChunk) > 1) {\n result += ',';\n }\n result += ' &';\n result += _.size(lastChunk) < 5 ? ' ' : '\\n';\n return result + '`' + last + '`';\n}\n\n/*----------------------------------------------------------------------------*/\n\n/**\n * Creates the FP-Guide wiki at the `target` path.\n *\n * @private\n * @param {string} target The output file path.\n */\nfunction build(target) {\n target = path.resolve(target);\n fs.writeFile(target, template.wiki(templateData), util.pitch);\n}\n\nbuild(_.last(process.argv));\n\n", "current_contents": " fs = require('fs-extra'),\n path = require('path');\n\nvar file = require('../common/file'),\n mapping = require('../common/mapping'),\n util = require('../common/util');\n\nvar templatePath = path.join(__dirname, 'template/doc'),\n template = file.globTemplate(path.join(templatePath, '*.jst'));\n\nvar argNames = ['a', 'b', 'c', 'd'];\n\nvar templateData = {\n 'mapping': mapping,\n 'toArgOrder': toArgOrder,\n 'toFuncList': toFuncList\n};\n\n/**\n * Converts arranged argument `indexes` into a named argument string\n * representation of their order.\n *\n * @private\n * @param {number[]} indexes The arranged argument indexes.\n * @returns {string} Returns the named argument string.\n */\nfunction toArgOrder(indexes) {\n var reordered = [];\n _.each(indexes, function(newIndex, index) {\n reordered[newIndex] = argNames[index];\n });\n return '`(' + reordered.join(', ') + ')`';\n}\n\n/**\n * Converts `funcNames` into a chunked list string representation.\n *\n * @private\n * @param {string[]} funcNames The function names.\n * @returns {string} Returns the function list string.\n */\nfunction toFuncList(funcNames) {\n var chunks = _.chunk(funcNames.slice().sort(), 5),\n lastChunk = _.last(chunks),\n last = lastChunk ? lastChunk.pop() : undefined;\n\n chunks = _.reject(chunks, _.isEmpty);\n lastChunk = _.last(chunks);\n\n var result = '`' + _.map(chunks, function(chunk) {\n return chunk.join('`, `') + '`';\n }).join(',\\n`');\n\n if (last == null) {\n return result;\n }\n if (_.size(chunks) > 1 || _.size(lastChunk) > 1) {\n result += ',';\n }\n result += ' &';\n result += _.size(lastChunk) < 5 ? ' ' : '\\n';\n return result + '`' + last + '`';\n}\n\n/*----------------------------------------------------------------------------*/\n\n/**\n * Creates the FP-Guide wiki at the `target` path.\n *\n * @param {string} target The output file path.\n */\nfunction build(target) {\n target = path.resolve(target);\n fs.writeFile(target, template.wiki(templateData), util.pitch);\n}\n\nbuild(_.last(process.argv));\n"} {"commit": "6eeac45d23ea1197123b78733e562fd5d0f9e652", "message": "Update vendors.", "old_file": "vendor/underscore/test/arrays.js", "new_file": "vendor/underscore/test/arrays.js", "status": "M", "old_contents": "(function() {\n var _ = typeof require == 'function' ? require('..') : window._;\n\n QUnit.module('Arrays');\n\n QUnit.test('first', function(assert) {\n assert.equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array');\n assert.equal(_([1, 2, 3]).first(), 1, 'can perform OO-style \"first()\"');\n assert.deepEqual(_.first([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.first([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can fetch the first n elements');\n assert.deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _.first(arguments); }(4, 3, 2, 1));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.first);\n assert.deepEqual(result, [1, 1], 'works well with _.map');\n assert.equal(_.first(null), void 0, 'returns undefined when called on null');\n });\n\n QUnit.test('head', function(assert) {\n assert.strictEqual(_.head, _.first, 'is an alias for first');\n });\n\n QUnit.test('take', function(assert) {\n assert.strictEqual(_.take, _.first, 'is an alias for first');\n });\n\n QUnit.test('rest', function(assert) {\n var numbers = [1, 2, 3, 4];\n assert.deepEqual(_.rest(numbers), [2, 3, 4], 'fetches all but the first element');\n assert.deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'returns the whole array when index is 0');\n assert.deepEqual(_.rest(numbers, 2), [3, 4], 'returns elements starting at the given index');\n var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));\n assert.deepEqual(result, [2, 3, 4], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.rest);\n assert.deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map');\n });\n\n QUnit.test('tail', function(assert) {\n assert.strictEqual(_.tail, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('drop', function(assert) {\n assert.strictEqual(_.drop, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('initial', function(assert) {\n assert.deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'returns all but the last element');\n assert.deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'returns all but the last n elements');\n assert.deepEqual(_.initial([1, 2, 3, 4], 6), [], 'returns an empty array when n > length');\n var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.initial);\n assert.deepEqual(_.flatten(result), [1, 2, 1, 2], 'works well with _.map');\n });\n\n QUnit.test('last', function(assert) {\n assert.equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array');\n assert.equal(_([1, 2, 3]).last(), 3, 'can perform OO-style \"last()\"');\n assert.deepEqual(_.last([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.last([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can fetch the last n elements');\n assert.deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.last);\n assert.deepEqual(result, [3, 3], 'works well with _.map');\n assert.equal(_.last(null), void 0, 'returns undefined when called on null');\n });\n\n QUnit.test('compact', function(assert) {\n assert.deepEqual(_.compact([1, false, null, 0, '', void 0, NaN, 2]), [1, 2], 'removes all falsy values');\n var result = (function(){ return _.compact(arguments); }(0, 1, false, 2, false, 3));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, false, false], [false, false, 3]], _.compact);\n assert.deepEqual(result, [[1], [3]], 'works well with _.map');\n });\n\n QUnit.test('flatten', function(assert) {\n assert.deepEqual(_.flatten(null), [], 'supports null');\n assert.deepEqual(_.flatten(void 0), [], 'supports undefined');\n\n assert.deepEqual(_.flatten([[], [[]], []]), [], 'supports empty arrays');\n assert.deepEqual(_.flatten([[], [[]], []], true), [[]], 'can shallowly flatten empty arrays');\n\n var list = [1, [2], [3, [[[4]]]]];\n assert.deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');\n var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]]));\n assert.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');\n list = [[1], [2], [3], [[4]]];\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');", "new_contents": "(function() {\n var _ = typeof require == 'function' ? require('..') : window._;\n\n QUnit.module('Arrays');\n\n QUnit.test('first', function(assert) {\n assert.equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array');\n assert.equal(_([1, 2, 3]).first(), 1, 'can perform OO-style \"first()\"');\n assert.deepEqual(_.first([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.first([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can fetch the first n elements');\n assert.deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _.first(arguments); }(4, 3, 2, 1));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.first);\n assert.deepEqual(result, [1, 1], 'works well with _.map');\n assert.equal(_.first(null), void 0, 'returns undefined when called on null');\n\n Array.prototype[0] = 'boo';\n assert.equal(_.first([]), void 0, 'return undefined when called on a empty array');\n delete Array.prototype[0];\n });\n\n QUnit.test('head', function(assert) {\n assert.strictEqual(_.head, _.first, 'is an alias for first');\n });\n\n QUnit.test('take', function(assert) {\n assert.strictEqual(_.take, _.first, 'is an alias for first');\n });\n\n QUnit.test('rest', function(assert) {\n var numbers = [1, 2, 3, 4];\n assert.deepEqual(_.rest(numbers), [2, 3, 4], 'fetches all but the first element');\n assert.deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'returns the whole array when index is 0');\n assert.deepEqual(_.rest(numbers, 2), [3, 4], 'returns elements starting at the given index');\n var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));\n assert.deepEqual(result, [2, 3, 4], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.rest);\n assert.deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map');\n });\n\n QUnit.test('tail', function(assert) {\n assert.strictEqual(_.tail, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('drop', function(assert) {\n assert.strictEqual(_.drop, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('initial', function(assert) {\n assert.deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'returns all but the last element');\n assert.deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'returns all but the last n elements');\n assert.deepEqual(_.initial([1, 2, 3, 4], 6), [], 'returns an empty array when n > length');\n var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.initial);\n assert.deepEqual(_.flatten(result), [1, 2, 1, 2], 'works well with _.map');\n });\n\n QUnit.test('last', function(assert) {\n assert.equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array');\n assert.equal(_([1, 2, 3]).last(), 3, 'can perform OO-style \"last()\"');\n assert.deepEqual(_.last([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.last([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can fetch the last n elements');\n assert.deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.last);\n assert.deepEqual(result, [3, 3], 'works well with _.map');\n assert.equal(_.last(null), void 0, 'returns undefined when called on null');\n\n var arr = [];\n arr[-1] = 'boo';\n assert.equal(_.last(arr), void 0, 'return undefined when called on a empty array');\n });\n\n QUnit.test('compact', function(assert) {\n assert.deepEqual(_.compact([1, false, null, 0, '', void 0, NaN, 2]), [1, 2], 'removes all falsy values');\n var result = (function(){ return _.compact(arguments); }(0, 1, false, 2, false, 3));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, false, false], [false, false, 3]], _.compact);\n assert.deepEqual(result, [[1], [3]], 'works well with _.map');\n });\n\n QUnit.test('flatten', function(assert) {\n assert.deepEqual(_.flatten(null), [], 'supports null');\n assert.deepEqual(_.flatten(void 0), [], 'supports undefined');\n\n assert.deepEqual(_.flatten([[], [[]], []]), [], 'supports empty arrays');\n assert.deepEqual(_.flatten([[], [[]], []], true), [[]], 'can shallowly flatten empty arrays');\n\n var list = [1, [2], [3, [[[4]]]]];\n assert.deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');\n var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]]));\n assert.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');\n list = [[1], [2], [3], [[4]]];\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');", "text": "<|original_code|>\n(function() {\n var _ = typeof require == 'function' ? require('..') : window._;\n\n QUnit.module('Arrays');\n\n QUnit.test('first', function(assert) {\n assert.equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array');\n assert.equal(_([1, 2, 3]).first(), 1, 'can perform OO-style \"first()\"');\n assert.deepEqual(_.first([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.first([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can fetch the first n elements');\n assert.deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _.first(arguments); }(4, 3, 2, 1));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.first);\n assert.deepEqual(result, [1, 1], 'works well with _.map');\n assert.equal(_.first(null), void 0, 'returns undefined when called on null');\n });\n\n QUnit.test('head', function(assert) {\n assert.strictEqual(_.head, _.first, 'is an alias for first');\n });\n\n QUnit.test('take', function(assert) {\n assert.strictEqual(_.take, _.first, 'is an alias for first');\n });\n\n QUnit.test('rest', function(assert) {\n var numbers = [1, 2, 3, 4];\n assert.deepEqual(_.rest(numbers), [2, 3, 4], 'fetches all but the first element');\n assert.deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'returns the whole array when index is 0');\n assert.deepEqual(_.rest(numbers, 2), [3, 4], 'returns elements starting at the given index');\n var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));\n assert.deepEqual(result, [2, 3, 4], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.rest);\n assert.deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map');\n });\n\n QUnit.test('tail', function(assert) {\n assert.strictEqual(_.tail, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('drop', function(assert) {\n assert.strictEqual(_.drop, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('initial', function(assert) {\n assert.deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'returns all but the last element');\n assert.deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'returns all but the last n elements');\n assert.deepEqual(_.initial([1, 2, 3, 4], 6), [], 'returns an empty array when n > length');\n var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.initial);\n assert.deepEqual(_.flatten(result), [1, 2, 1, 2], 'works well with _.map');\n });\n\n QUnit.test('last', function(assert) {\n assert.equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array');\n assert.equal(_([1, 2, 3]).last(), 3, 'can perform OO-style \"last()\"');\n assert.deepEqual(_.last([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.last([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can fetch the last n elements');\n assert.deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.last);\n assert.deepEqual(result, [3, 3], 'works well with _.map');\n assert.equal(_.last(null), void 0, 'returns undefined when called on null');\n });\n\n QUnit.test('compact', function(assert) {\n assert.deepEqual(_.compact([1, false, null, 0, '', void 0, NaN, 2]), [1, 2], 'removes all falsy values');\n var result = (function(){ return _.compact(arguments); }(0, 1, false, 2, false, 3));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, false, false], [false, false, 3]], _.compact);\n assert.deepEqual(result, [[1], [3]], 'works well with _.map');\n });\n\n QUnit.test('flatten', function(assert) {\n assert.deepEqual(_.flatten(null), [], 'supports null');\n assert.deepEqual(_.flatten(void 0), [], 'supports undefined');\n\n assert.deepEqual(_.flatten([[], [[]], []]), [], 'supports empty arrays');\n assert.deepEqual(_.flatten([[], [[]], []], true), [[]], 'can shallowly flatten empty arrays');\n\n var list = [1, [2], [3, [[[4]]]]];\n assert.deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');\n var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]]));\n assert.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');\n list = [[1], [2], [3], [[4]]];\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');\n<|edits_diff|>\n--- vendor/underscore/test/arrays.js\n+++ vendor/underscore/test/arrays.js\n@@ -15,6 +15,10 @@\n result = _.map([[1, 2, 3], [1, 2, 3]], _.first);\n assert.deepEqual(result, [1, 1], 'works well with _.map');\n assert.equal(_.first(null), void 0, 'returns undefined when called on null');\n+\n+ Array.prototype[0] = 'boo';\n+ assert.equal(_.first([]), void 0, 'return undefined when called on a empty array');\n+ delete Array.prototype[0];\n });\n \n QUnit.test('head', function(assert) {\n<|current_version|>\n(function() {\n var _ = typeof require == 'function' ? require('..') : window._;\n\n QUnit.module('Arrays');\n\n QUnit.test('first', function(assert) {\n assert.equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array');\n assert.equal(_([1, 2, 3]).first(), 1, 'can perform OO-style \"first()\"');\n assert.deepEqual(_.first([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.first([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can fetch the first n elements');\n assert.deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _.first(arguments); }(4, 3, 2, 1));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.first);\n assert.deepEqual(result, [1, 1], 'works well with _.map');\n assert.equal(_.first(null), void 0, 'returns undefined when called on null');\n\n Array.prototype[0] = 'boo';\n assert.equal(_.first([]), void 0, 'return undefined when called on a empty array');\n delete Array.prototype[0];\n });\n\n QUnit.test('head', function(assert) {\n assert.strictEqual(_.head, _.first, 'is an alias for first');\n });\n\n QUnit.test('take', function(assert) {\n assert.strictEqual(_.take, _.first, 'is an alias for first');\n });\n\n QUnit.test('rest', function(assert) {\n var numbers = [1, 2, 3, 4];\n assert.deepEqual(_.rest(numbers), [2, 3, 4], 'fetches all but the first element');\n assert.deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'returns the whole array when index is 0');\n assert.deepEqual(_.rest(numbers, 2), [3, 4], 'returns elements starting at the given index');\n var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));\n assert.deepEqual(result, [2, 3, 4], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.rest);\n assert.deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map');\n });\n\n QUnit.test('tail', function(assert) {\n assert.strictEqual(_.tail, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('drop', function(assert) {\n assert.strictEqual(_.drop, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('initial', function(assert) {\n assert.deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'returns all but the last element');\n assert.deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'returns all but the last n elements');\n assert.deepEqual(_.initial([1, 2, 3, 4], 6), [], 'returns an empty array when n > length');\n var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.initial);\n assert.deepEqual(_.flatten(result), [1, 2, 1, 2], 'works well with _.map');\n });\n\n QUnit.test('last', function(assert) {\n assert.equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array');\n assert.equal(_([1, 2, 3]).last(), 3, 'can perform OO-style \"last()\"');\n assert.deepEqual(_.last([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.last([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can fetch the last n elements');\n assert.deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.last);\n assert.deepEqual(result, [3, 3], 'works well with _.map');\n assert.equal(_.last(null), void 0, 'returns undefined when called on null');\n });\n\n QUnit.test('compact', function(assert) {\n assert.deepEqual(_.compact([1, false, null, 0, '', void 0, NaN, 2]), [1, 2], 'removes all falsy values');\n var result = (function(){ return _.compact(arguments); }(0, 1, false, 2, false, 3));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, false, false], [false, false, 3]], _.compact);\n assert.deepEqual(result, [[1], [3]], 'works well with _.map');\n });\n\n QUnit.test('flatten', function(assert) {\n assert.deepEqual(_.flatten(null), [], 'supports null');\n assert.deepEqual(_.flatten(void 0), [], 'supports undefined');\n\n assert.deepEqual(_.flatten([[], [[]], []]), [], 'supports empty arrays');\n assert.deepEqual(_.flatten([[], [[]], []], true), [[]], 'can shallowly flatten empty arrays');\n\n var list = [1, [2], [3, [[[4]]]]];\n assert.deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');\n var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]]));\n assert.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');\n list = [[1], [2], [3], [[4]]];\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');\n<|next_version|>\n(function() {\n var _ = typeof require == 'function' ? require('..') : window._;\n\n QUnit.module('Arrays');\n\n QUnit.test('first', function(assert) {\n assert.equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array');\n assert.equal(_([1, 2, 3]).first(), 1, 'can perform OO-style \"first()\"');\n assert.deepEqual(_.first([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.first([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can fetch the first n elements');\n assert.deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _.first(arguments); }(4, 3, 2, 1));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.first);\n assert.deepEqual(result, [1, 1], 'works well with _.map');\n assert.equal(_.first(null), void 0, 'returns undefined when called on null');\n\n Array.prototype[0] = 'boo';\n assert.equal(_.first([]), void 0, 'return undefined when called on a empty array');\n delete Array.prototype[0];\n });\n\n QUnit.test('head', function(assert) {\n assert.strictEqual(_.head, _.first, 'is an alias for first');\n });\n\n QUnit.test('take', function(assert) {\n assert.strictEqual(_.take, _.first, 'is an alias for first');\n });\n\n QUnit.test('rest', function(assert) {\n var numbers = [1, 2, 3, 4];\n assert.deepEqual(_.rest(numbers), [2, 3, 4], 'fetches all but the first element');\n assert.deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'returns the whole array when index is 0');\n assert.deepEqual(_.rest(numbers, 2), [3, 4], 'returns elements starting at the given index');\n var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));\n assert.deepEqual(result, [2, 3, 4], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.rest);\n assert.deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map');\n });\n\n QUnit.test('tail', function(assert) {\n assert.strictEqual(_.tail, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('drop', function(assert) {\n assert.strictEqual(_.drop, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('initial', function(assert) {\n assert.deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'returns all but the last element');\n assert.deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'returns all but the last n elements');\n assert.deepEqual(_.initial([1, 2, 3, 4], 6), [], 'returns an empty array when n > length');\n var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.initial);\n assert.deepEqual(_.flatten(result), [1, 2, 1, 2], 'works well with _.map');\n });\n\n QUnit.test('last', function(assert) {\n assert.equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array');\n assert.equal(_([1, 2, 3]).last(), 3, 'can perform OO-style \"last()\"');\n assert.deepEqual(_.last([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.last([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can fetch the last n elements');\n assert.deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.last);\n assert.deepEqual(result, [3, 3], 'works well with _.map');\n assert.equal(_.last(null), void 0, 'returns undefined when called on null');\n\n var arr = [];\n arr[-1] = 'boo';\n assert.equal(_.last(arr), void 0, 'return undefined when called on a empty array');\n });\n\n QUnit.test('compact', function(assert) {\n assert.deepEqual(_.compact([1, false, null, 0, '', void 0, NaN, 2]), [1, 2], 'removes all falsy values');\n var result = (function(){ return _.compact(arguments); }(0, 1, false, 2, false, 3));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, false, false], [false, false, 3]], _.compact);\n assert.deepEqual(result, [[1], [3]], 'works well with _.map');\n });\n\n QUnit.test('flatten', function(assert) {\n assert.deepEqual(_.flatten(null), [], 'supports null');\n assert.deepEqual(_.flatten(void 0), [], 'supports undefined');\n\n assert.deepEqual(_.flatten([[], [[]], []]), [], 'supports empty arrays');\n assert.deepEqual(_.flatten([[], [[]], []], true), [[]], 'can shallowly flatten empty arrays');\n\n var list = [1, [2], [3, [[[4]]]]];\n assert.deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');\n var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]]));\n assert.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');\n list = [[1], [2], [3], [[4]]];\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');\n", "current_contents": "(function() {\n var _ = typeof require == 'function' ? require('..') : window._;\n\n QUnit.module('Arrays');\n\n QUnit.test('first', function(assert) {\n assert.equal(_.first([1, 2, 3]), 1, 'can pull out the first element of an array');\n assert.equal(_([1, 2, 3]).first(), 1, 'can perform OO-style \"first()\"');\n assert.deepEqual(_.first([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.first([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.first([1, 2, 3], 2), [1, 2], 'can fetch the first n elements');\n assert.deepEqual(_.first([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _.first(arguments); }(4, 3, 2, 1));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.first);\n assert.deepEqual(result, [1, 1], 'works well with _.map');\n assert.equal(_.first(null), void 0, 'returns undefined when called on null');\n\n Array.prototype[0] = 'boo';\n assert.equal(_.first([]), void 0, 'return undefined when called on a empty array');\n delete Array.prototype[0];\n });\n\n QUnit.test('head', function(assert) {\n assert.strictEqual(_.head, _.first, 'is an alias for first');\n });\n\n QUnit.test('take', function(assert) {\n assert.strictEqual(_.take, _.first, 'is an alias for first');\n });\n\n QUnit.test('rest', function(assert) {\n var numbers = [1, 2, 3, 4];\n assert.deepEqual(_.rest(numbers), [2, 3, 4], 'fetches all but the first element');\n assert.deepEqual(_.rest(numbers, 0), [1, 2, 3, 4], 'returns the whole array when index is 0');\n assert.deepEqual(_.rest(numbers, 2), [3, 4], 'returns elements starting at the given index');\n var result = (function(){ return _(arguments).rest(); }(1, 2, 3, 4));\n assert.deepEqual(result, [2, 3, 4], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.rest);\n assert.deepEqual(_.flatten(result), [2, 3, 2, 3], 'works well with _.map');\n });\n\n QUnit.test('tail', function(assert) {\n assert.strictEqual(_.tail, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('drop', function(assert) {\n assert.strictEqual(_.drop, _.rest, 'is an alias for rest');\n });\n\n QUnit.test('initial', function(assert) {\n assert.deepEqual(_.initial([1, 2, 3, 4, 5]), [1, 2, 3, 4], 'returns all but the last element');\n assert.deepEqual(_.initial([1, 2, 3, 4], 2), [1, 2], 'returns all but the last n elements');\n assert.deepEqual(_.initial([1, 2, 3, 4], 6), [], 'returns an empty array when n > length');\n var result = (function(){ return _(arguments).initial(); }(1, 2, 3, 4));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.initial);\n assert.deepEqual(_.flatten(result), [1, 2, 1, 2], 'works well with _.map');\n });\n\n QUnit.test('last', function(assert) {\n assert.equal(_.last([1, 2, 3]), 3, 'can pull out the last element of an array');\n assert.equal(_([1, 2, 3]).last(), 3, 'can perform OO-style \"last()\"');\n assert.deepEqual(_.last([1, 2, 3], 0), [], 'returns an empty array when n <= 0 (0 case)');\n assert.deepEqual(_.last([1, 2, 3], -1), [], 'returns an empty array when n <= 0 (negative case)');\n assert.deepEqual(_.last([1, 2, 3], 2), [2, 3], 'can fetch the last n elements');\n assert.deepEqual(_.last([1, 2, 3], 5), [1, 2, 3], 'returns the whole array if n > length');\n var result = (function(){ return _(arguments).last(); }(1, 2, 3, 4));\n assert.equal(result, 4, 'works on an arguments object');\n result = _.map([[1, 2, 3], [1, 2, 3]], _.last);\n assert.deepEqual(result, [3, 3], 'works well with _.map');\n assert.equal(_.last(null), void 0, 'returns undefined when called on null');\n });\n\n QUnit.test('compact', function(assert) {\n assert.deepEqual(_.compact([1, false, null, 0, '', void 0, NaN, 2]), [1, 2], 'removes all falsy values');\n var result = (function(){ return _.compact(arguments); }(0, 1, false, 2, false, 3));\n assert.deepEqual(result, [1, 2, 3], 'works on an arguments object');\n result = _.map([[1, false, false], [false, false, 3]], _.compact);\n assert.deepEqual(result, [[1], [3]], 'works well with _.map');\n });\n\n QUnit.test('flatten', function(assert) {\n assert.deepEqual(_.flatten(null), [], 'supports null');\n assert.deepEqual(_.flatten(void 0), [], 'supports undefined');\n\n assert.deepEqual(_.flatten([[], [[]], []]), [], 'supports empty arrays');\n assert.deepEqual(_.flatten([[], [[]], []], true), [[]], 'can shallowly flatten empty arrays');\n\n var list = [1, [2], [3, [[[4]]]]];\n assert.deepEqual(_.flatten(list), [1, 2, 3, 4], 'can flatten nested arrays');\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [[[4]]]], 'can shallowly flatten nested arrays');\n var result = (function(){ return _.flatten(arguments); }(1, [2], [3, [[[4]]]]));\n assert.deepEqual(result, [1, 2, 3, 4], 'works on an arguments object');\n list = [[1], [2], [3], [[4]]];\n assert.deepEqual(_.flatten(list, true), [1, 2, 3, [4]], 'can shallowly flatten arrays containing only other arrays');"} {"commit": "ee2153364d2f1cd72e9c74f65c085e0cc0f37977", "message": "Add bizarro Promise test.", "old_file": "test/test.js", "new_file": "test/test.js", "status": "M", "old_contents": " name = caller ? caller.name : '';\n\n if (!(name == 'runInContext' || name.length == 1 || /\\b_\\.isBuffer\\b/.test(caller))) {\n return Buffer;\n }\n }\n });\n }\n if (Map) {\n setProperty(root, 'Map', (function() {\n var count = 0;\n return function() {\n if (count++) {\n return new Map;\n }\n setProperty(root, 'Map', Map);\n return {};\n };\n }()));\n\n setProperty(root.Map, 'toString', createToString('Map'));\n }\n setProperty(root, 'Set', noop);\n setProperty(root, 'Symbol', undefined);\n setProperty(root, 'WeakMap', noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(Object, 'create', create);\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n setProperty(root, 'Buffer', Buffer);\n\n if (getSymbols) {\n Object.getOwnPropertySymbols = getSymbols;\n } else {\n delete Object.getOwnPropertySymbols;\n }\n if (Map) {\n setProperty(root, 'Map', Map);\n } else {\n delete root.Map;\n }\n if (Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (Symbol) {\n setProperty(root, 'Symbol', Symbol);\n } else {\n delete root.Symbol;\n }\n if (WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n lodashStable.attempt(function() {\n lodashStable.assign(realm, require('vm').runInNewContext([\n '(function() {',", "new_contents": " name = caller ? caller.name : '';\n\n if (!(name == 'runInContext' || name.length == 1 || /\\b_\\.isBuffer\\b/.test(caller))) {\n return Buffer;\n }\n }\n });\n }\n if (Map) {\n setProperty(root, 'Map', (function() {\n var count = 0;\n return function() {\n if (count++) {\n return new Map;\n }\n setProperty(root, 'Map', Map);\n return {};\n };\n }()));\n\n setProperty(root.Map, 'toString', createToString('Map'));\n }\n setProperty(root, 'Promise', noop);\n setProperty(root, 'Set', noop);\n setProperty(root, 'Symbol', undefined);\n setProperty(root, 'WeakMap', noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(Object, 'create', create);\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n setProperty(root, 'Buffer', Buffer);\n\n if (getSymbols) {\n Object.getOwnPropertySymbols = getSymbols;\n } else {\n delete Object.getOwnPropertySymbols;\n }\n if (Map) {\n setProperty(root, 'Map', Map);\n } else {\n delete root.Map;\n }\n if (Promise) {\n setProperty(root, 'Promise', Promise);\n } else {\n delete root.Promise;\n }\n if (Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (Symbol) {\n setProperty(root, 'Symbol', Symbol);\n } else {\n delete root.Symbol;\n }\n if (WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n lodashStable.attempt(function() {\n lodashStable.assign(realm, require('vm').runInNewContext([\n '(function() {',", "text": "<|original_code|>\n name = caller ? caller.name : '';\n\n if (!(name == 'runInContext' || name.length == 1 || /\\b_\\.isBuffer\\b/.test(caller))) {\n return Buffer;\n }\n }\n });\n }\n if (Map) {\n setProperty(root, 'Map', (function() {\n var count = 0;\n return function() {\n if (count++) {\n return new Map;\n }\n setProperty(root, 'Map', Map);\n return {};\n };\n }()));\n\n setProperty(root.Map, 'toString', createToString('Map'));\n }\n setProperty(root, 'Set', noop);\n setProperty(root, 'Symbol', undefined);\n setProperty(root, 'WeakMap', noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(Object, 'create', create);\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n setProperty(root, 'Buffer', Buffer);\n\n if (getSymbols) {\n Object.getOwnPropertySymbols = getSymbols;\n } else {\n delete Object.getOwnPropertySymbols;\n }\n if (Map) {\n setProperty(root, 'Map', Map);\n } else {\n delete root.Map;\n }\n if (Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (Symbol) {\n setProperty(root, 'Symbol', Symbol);\n } else {\n delete root.Symbol;\n }\n if (WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n lodashStable.attempt(function() {\n lodashStable.assign(realm, require('vm').runInNewContext([\n '(function() {',\n<|edits_diff|>\n--- test/test.js\n+++ test/test.js\n@@ -20,6 +20,7 @@\n \n setProperty(root.Map, 'toString', createToString('Map'));\n }\n+ setProperty(root, 'Promise', noop);\n setProperty(root, 'Set', noop);\n setProperty(root, 'Symbol', undefined);\n setProperty(root, 'WeakMap', noop);\n<|current_version|>\n name = caller ? caller.name : '';\n\n if (!(name == 'runInContext' || name.length == 1 || /\\b_\\.isBuffer\\b/.test(caller))) {\n return Buffer;\n }\n }\n });\n }\n if (Map) {\n setProperty(root, 'Map', (function() {\n var count = 0;\n return function() {\n if (count++) {\n return new Map;\n }\n setProperty(root, 'Map', Map);\n return {};\n };\n }()));\n\n setProperty(root.Map, 'toString', createToString('Map'));\n }\n setProperty(root, 'Promise', noop);\n setProperty(root, 'Set', noop);\n setProperty(root, 'Symbol', undefined);\n setProperty(root, 'WeakMap', noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(Object, 'create', create);\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n setProperty(root, 'Buffer', Buffer);\n\n if (getSymbols) {\n Object.getOwnPropertySymbols = getSymbols;\n } else {\n delete Object.getOwnPropertySymbols;\n }\n if (Map) {\n setProperty(root, 'Map', Map);\n } else {\n delete root.Map;\n }\n if (Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (Symbol) {\n setProperty(root, 'Symbol', Symbol);\n } else {\n delete root.Symbol;\n }\n if (WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n lodashStable.attempt(function() {\n lodashStable.assign(realm, require('vm').runInNewContext([\n '(function() {',\n<|next_version|>\n name = caller ? caller.name : '';\n\n if (!(name == 'runInContext' || name.length == 1 || /\\b_\\.isBuffer\\b/.test(caller))) {\n return Buffer;\n }\n }\n });\n }\n if (Map) {\n setProperty(root, 'Map', (function() {\n var count = 0;\n return function() {\n if (count++) {\n return new Map;\n }\n setProperty(root, 'Map', Map);\n return {};\n };\n }()));\n\n setProperty(root.Map, 'toString', createToString('Map'));\n }\n setProperty(root, 'Promise', noop);\n setProperty(root, 'Set', noop);\n setProperty(root, 'Symbol', undefined);\n setProperty(root, 'WeakMap', noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(Object, 'create', create);\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n setProperty(root, 'Buffer', Buffer);\n\n if (getSymbols) {\n Object.getOwnPropertySymbols = getSymbols;\n } else {\n delete Object.getOwnPropertySymbols;\n }\n if (Map) {\n setProperty(root, 'Map', Map);\n } else {\n delete root.Map;\n }\n if (Promise) {\n setProperty(root, 'Promise', Promise);\n } else {\n delete root.Promise;\n }\n if (Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (Symbol) {\n setProperty(root, 'Symbol', Symbol);\n } else {\n delete root.Symbol;\n }\n if (WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n lodashStable.attempt(function() {\n lodashStable.assign(realm, require('vm').runInNewContext([\n '(function() {',\n", "current_contents": " name = caller ? caller.name : '';\n\n if (!(name == 'runInContext' || name.length == 1 || /\\b_\\.isBuffer\\b/.test(caller))) {\n return Buffer;\n }\n }\n });\n }\n if (Map) {\n setProperty(root, 'Map', (function() {\n var count = 0;\n return function() {\n if (count++) {\n return new Map;\n }\n setProperty(root, 'Map', Map);\n return {};\n };\n }()));\n\n setProperty(root.Map, 'toString', createToString('Map'));\n }\n setProperty(root, 'Promise', noop);\n setProperty(root, 'Set', noop);\n setProperty(root, 'Symbol', undefined);\n setProperty(root, 'WeakMap', noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(Object, 'create', create);\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n setProperty(root, 'Buffer', Buffer);\n\n if (getSymbols) {\n Object.getOwnPropertySymbols = getSymbols;\n } else {\n delete Object.getOwnPropertySymbols;\n }\n if (Map) {\n setProperty(root, 'Map', Map);\n } else {\n delete root.Map;\n }\n if (Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (Symbol) {\n setProperty(root, 'Symbol', Symbol);\n } else {\n delete root.Symbol;\n }\n if (WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n lodashStable.attempt(function() {\n lodashStable.assign(realm, require('vm').runInNewContext([\n '(function() {',"} {"commit": "02bea6534c10494b6a199fffb8407cd8cd01adef", "message": "fp docs - Remove notes about mutation in description.", "old_file": "lib/doc/apply-fp-mapping/index.js", "new_file": "lib/doc/apply-fp-mapping/index.js", "status": "M", "old_contents": "var Entry = require('docdown/lib/entry'),\n getReorderedParams = require('./parameters'),\n getReorderedExample = require('./example');\n\n/**\n * Updates `docdown` `Entry`'s prototype so that parameters/arguments are reordered according to `mapping`.\n */\nmodule.exports = function applyFPMapping(mapping) {\n Entry.prototype.getParams = getReorderedParams(mapping);\n Entry.prototype.getExample = getReorderedExample(mapping);\n};\n", "new_contents": "var Entry = require('docdown/lib/entry'),\n getUpdatedDesc = require('./description'),\n getReorderedParams = require('./parameters'),\n getReorderedExample = require('./example');\n\n/**\n * Updates `docdown` `Entry`'s prototype so that parameters/arguments are reordered according to `mapping`.\n */\nmodule.exports = function applyFPMapping(mapping) {\n Entry.prototype.getDesc = getUpdatedDesc;\n Entry.prototype.getParams = getReorderedParams(mapping);\n Entry.prototype.getExample = getReorderedExample(mapping);\n};\n", "text": "<|original_code|>\nvar Entry = require('docdown/lib/entry'),\n getReorderedParams = require('./parameters'),\n getReorderedExample = require('./example');\n\n/**\n * Updates `docdown` `Entry`'s prototype so that parameters/arguments are reordered according to `mapping`.\n */\nmodule.exports = function applyFPMapping(mapping) {\n Entry.prototype.getParams = getReorderedParams(mapping);\n Entry.prototype.getExample = getReorderedExample(mapping);\n};\n\n<|edits_diff|>\n--- lib/doc/apply-fp-mapping/index.js\n+++ lib/doc/apply-fp-mapping/index.js\n@@ -1,4 +1,5 @@\n var Entry = require('docdown/lib/entry'),\n+ getUpdatedDesc = require('./description'),\n getReorderedParams = require('./parameters'),\n getReorderedExample = require('./example');\n \n<|current_version|>\nvar Entry = require('docdown/lib/entry'),\n getUpdatedDesc = require('./description'),\n getReorderedParams = require('./parameters'),\n getReorderedExample = require('./example');\n\n/**\n * Updates `docdown` `Entry`'s prototype so that parameters/arguments are reordered according to `mapping`.\n */\nmodule.exports = function applyFPMapping(mapping) {\n Entry.prototype.getParams = getReorderedParams(mapping);\n Entry.prototype.getExample = getReorderedExample(mapping);\n};\n\n<|next_version|>\nvar Entry = require('docdown/lib/entry'),\n getUpdatedDesc = require('./description'),\n getReorderedParams = require('./parameters'),\n getReorderedExample = require('./example');\n\n/**\n * Updates `docdown` `Entry`'s prototype so that parameters/arguments are reordered according to `mapping`.\n */\nmodule.exports = function applyFPMapping(mapping) {\n Entry.prototype.getDesc = getUpdatedDesc;\n Entry.prototype.getParams = getReorderedParams(mapping);\n Entry.prototype.getExample = getReorderedExample(mapping);\n};\n\n", "current_contents": "var Entry = require('docdown/lib/entry'),\n getUpdatedDesc = require('./description'),\n getReorderedParams = require('./parameters'),\n getReorderedExample = require('./example');\n\n/**\n * Updates `docdown` `Entry`'s prototype so that parameters/arguments are reordered according to `mapping`.\n */\nmodule.exports = function applyFPMapping(mapping) {\n Entry.prototype.getParams = getReorderedParams(mapping);\n Entry.prototype.getExample = getReorderedExample(mapping);\n};\n"} {"commit": "bc252228e1efde35d3da7a3068d379e6a25cb5d5", "message": "Add bizarro `Map`.", "old_file": "test/test.js", "new_file": "test/test.js", "status": "M", "old_contents": "\n function createToString(funcName) {\n return _.constant(nativeString.replace(reToString, funcName));\n }\n\n // Allow bypassing native checks.\n setProperty(funcProto, 'toString', function wrapper() {\n setProperty(funcProto, 'toString', fnToString);\n var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this);\n setProperty(funcProto, 'toString', wrapper);\n return result;\n });\n\n // Add prototype extensions.\n funcProto._method = _.noop;\n\n // Set bad shims.\n var _propertyIsEnumerable = objectProto.propertyIsEnumerable;\n setProperty(objectProto, 'propertyIsEnumerable', function(key) {\n return !(key == 'valueOf' && this && this.valueOf === 1) && _propertyIsEnumerable.call(this, key);\n });\n\n var _Set = root.Set;\n setProperty(root, 'Set', _.noop);\n\n var _WeakMap = root.WeakMap;\n setProperty(root, 'WeakMap', _.noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n\n if (_Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (_WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n _.attempt(function() {\n _.extend(realm, require('vm').runInNewContext([\n '(function() {',\n ' var root = this;',\n '',\n ' var object = {',\n \" 'arguments': (function() { return arguments; }(1, 2, 3)),\",\n \" 'array': [1, 2, 3],\",\n \" 'arrayBuffer': new (this.ArrayByffer || Object),\",", "new_contents": "\n function createToString(funcName) {\n return _.constant(nativeString.replace(reToString, funcName));\n }\n\n // Allow bypassing native checks.\n setProperty(funcProto, 'toString', function wrapper() {\n setProperty(funcProto, 'toString', fnToString);\n var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this);\n setProperty(funcProto, 'toString', wrapper);\n return result;\n });\n\n // Add prototype extensions.\n funcProto._method = _.noop;\n\n // Set bad shims.\n var _propertyIsEnumerable = objectProto.propertyIsEnumerable;\n setProperty(objectProto, 'propertyIsEnumerable', function(key) {\n return !(key == 'valueOf' && this && this.valueOf === 1) && _propertyIsEnumerable.call(this, key);\n });\n\n var _Map = root.Map;\n setProperty(root, 'Map', _.noop);\n\n var _Set = root.Set;\n setProperty(root, 'Set', _.noop);\n\n var _WeakMap = root.WeakMap;\n setProperty(root, 'WeakMap', _.noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n\n if (_Map) {\n setProperty(root, 'Map', Map);\n } else {\n delete root.Map;\n }\n if (_Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (_WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n _.attempt(function() {\n _.extend(realm, require('vm').runInNewContext([\n '(function() {',\n ' var root = this;',\n '',\n ' var object = {',\n \" 'arguments': (function() { return arguments; }(1, 2, 3)),\",\n \" 'array': [1, 2, 3],\",\n \" 'arrayBuffer': new (this.ArrayByffer || Object),\",", "text": "<|original_code|>\n\n function createToString(funcName) {\n return _.constant(nativeString.replace(reToString, funcName));\n }\n\n // Allow bypassing native checks.\n setProperty(funcProto, 'toString', function wrapper() {\n setProperty(funcProto, 'toString', fnToString);\n var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this);\n setProperty(funcProto, 'toString', wrapper);\n return result;\n });\n\n // Add prototype extensions.\n funcProto._method = _.noop;\n\n // Set bad shims.\n var _propertyIsEnumerable = objectProto.propertyIsEnumerable;\n setProperty(objectProto, 'propertyIsEnumerable', function(key) {\n return !(key == 'valueOf' && this && this.valueOf === 1) && _propertyIsEnumerable.call(this, key);\n });\n\n var _Set = root.Set;\n setProperty(root, 'Set', _.noop);\n\n var _WeakMap = root.WeakMap;\n setProperty(root, 'WeakMap', _.noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n\n if (_Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (_WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n _.attempt(function() {\n _.extend(realm, require('vm').runInNewContext([\n '(function() {',\n ' var root = this;',\n '',\n ' var object = {',\n \" 'arguments': (function() { return arguments; }(1, 2, 3)),\",\n \" 'array': [1, 2, 3],\",\n \" 'arrayBuffer': new (this.ArrayByffer || Object),\",\n<|edits_diff|>\n--- test/test.js\n+++ test/test.js\n@@ -19,6 +19,9 @@\n setProperty(objectProto, 'propertyIsEnumerable', function(key) {\n return !(key == 'valueOf' && this && this.valueOf === 1) && _propertyIsEnumerable.call(this, key);\n });\n+\n+ var _Map = root.Map;\n+ setProperty(root, 'Map', _.noop);\n \n var _Set = root.Set;\n setProperty(root, 'Set', _.noop);\n<|current_version|>\n\n function createToString(funcName) {\n return _.constant(nativeString.replace(reToString, funcName));\n }\n\n // Allow bypassing native checks.\n setProperty(funcProto, 'toString', function wrapper() {\n setProperty(funcProto, 'toString', fnToString);\n var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this);\n setProperty(funcProto, 'toString', wrapper);\n return result;\n });\n\n // Add prototype extensions.\n funcProto._method = _.noop;\n\n // Set bad shims.\n var _propertyIsEnumerable = objectProto.propertyIsEnumerable;\n setProperty(objectProto, 'propertyIsEnumerable', function(key) {\n return !(key == 'valueOf' && this && this.valueOf === 1) && _propertyIsEnumerable.call(this, key);\n });\n\n var _Map = root.Map;\n setProperty(root, 'Map', _.noop);\n\n var _Set = root.Set;\n setProperty(root, 'Set', _.noop);\n\n var _WeakMap = root.WeakMap;\n setProperty(root, 'WeakMap', _.noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n\n if (_Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (_WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n _.attempt(function() {\n _.extend(realm, require('vm').runInNewContext([\n '(function() {',\n ' var root = this;',\n '',\n ' var object = {',\n \" 'arguments': (function() { return arguments; }(1, 2, 3)),\",\n \" 'array': [1, 2, 3],\",\n \" 'arrayBuffer': new (this.ArrayByffer || Object),\",\n<|next_version|>\n\n function createToString(funcName) {\n return _.constant(nativeString.replace(reToString, funcName));\n }\n\n // Allow bypassing native checks.\n setProperty(funcProto, 'toString', function wrapper() {\n setProperty(funcProto, 'toString', fnToString);\n var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this);\n setProperty(funcProto, 'toString', wrapper);\n return result;\n });\n\n // Add prototype extensions.\n funcProto._method = _.noop;\n\n // Set bad shims.\n var _propertyIsEnumerable = objectProto.propertyIsEnumerable;\n setProperty(objectProto, 'propertyIsEnumerable', function(key) {\n return !(key == 'valueOf' && this && this.valueOf === 1) && _propertyIsEnumerable.call(this, key);\n });\n\n var _Map = root.Map;\n setProperty(root, 'Map', _.noop);\n\n var _Set = root.Set;\n setProperty(root, 'Set', _.noop);\n\n var _WeakMap = root.WeakMap;\n setProperty(root, 'WeakMap', _.noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n\n if (_Map) {\n setProperty(root, 'Map', Map);\n } else {\n delete root.Map;\n }\n if (_Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (_WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n _.attempt(function() {\n _.extend(realm, require('vm').runInNewContext([\n '(function() {',\n ' var root = this;',\n '',\n ' var object = {',\n \" 'arguments': (function() { return arguments; }(1, 2, 3)),\",\n \" 'array': [1, 2, 3],\",\n \" 'arrayBuffer': new (this.ArrayByffer || Object),\",\n", "current_contents": "\n function createToString(funcName) {\n return _.constant(nativeString.replace(reToString, funcName));\n }\n\n // Allow bypassing native checks.\n setProperty(funcProto, 'toString', function wrapper() {\n setProperty(funcProto, 'toString', fnToString);\n var result = _.has(this, 'toString') ? this.toString() : fnToString.call(this);\n setProperty(funcProto, 'toString', wrapper);\n return result;\n });\n\n // Add prototype extensions.\n funcProto._method = _.noop;\n\n // Set bad shims.\n var _propertyIsEnumerable = objectProto.propertyIsEnumerable;\n setProperty(objectProto, 'propertyIsEnumerable', function(key) {\n return !(key == 'valueOf' && this && this.valueOf === 1) && _propertyIsEnumerable.call(this, key);\n });\n\n var _Map = root.Map;\n setProperty(root, 'Map', _.noop);\n\n var _Set = root.Set;\n setProperty(root, 'Set', _.noop);\n\n var _WeakMap = root.WeakMap;\n setProperty(root, 'WeakMap', _.noop);\n\n // Fake `WinRTError`.\n setProperty(root, 'WinRTError', Error);\n\n // Clear cache so lodash can be reloaded.\n emptyObject(require.cache);\n\n // Load lodash and expose it to the bad extensions/shims.\n lodashBizarro = (lodashBizarro = require(filePath))._ || lodashBizarro['default'] || lodashBizarro;\n root._ = oldDash;\n\n // Restore built-in methods.\n setProperty(objectProto, 'propertyIsEnumerable', _propertyIsEnumerable);\n\n if (_Set) {\n setProperty(root, 'Set', Set);\n } else {\n delete root.Set;\n }\n if (_WeakMap) {\n setProperty(root, 'WeakMap', WeakMap);\n } else {\n delete root.WeakMap;\n }\n delete root.WinRTError;\n delete funcProto._method;\n }());\n\n // Add other realm values from the `vm` module.\n _.attempt(function() {\n _.extend(realm, require('vm').runInNewContext([\n '(function() {',\n ' var root = this;',\n '',\n ' var object = {',\n \" 'arguments': (function() { return arguments; }(1, 2, 3)),\",\n \" 'array': [1, 2, 3],\",\n \" 'arrayBuffer': new (this.ArrayByffer || Object),\","} {"commit": "4c9f3aee7422d0d26c6bcb8c5d1b21dd63c87996", "message": "Make `baseSortedIndex` handle `NaN` correctly when comparing numbers.", "old_file": "lodash.js", "new_file": "lodash.js", "status": "M", "old_contents": " });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` without\n * support for callback shorthands and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iterator The function called per iteration.\n * @param {boolean} [retHighest=false] Specify returning the highest, instead\n * of the lowest, index at which a value should be inserted into `array`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, iterator, retHighest) {\n var low = 0,\n high = array ? array.length : low;\n\n value = iterator(value);\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = iterator(array[mid]);\n\n if (retHighest ? computed <= value : computed < value) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n\n /**\n * The base implementation of `_.uniq` without support for callback shorthands\n * and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iterator] The function called per iteration.\n * @returns {Array} Returns the new duplicate-value-free array.\n */\n function baseUniq(array, iterator) {\n var index = -1,\n indexOf = getIndexOf(),\n length = array.length,\n prereq = indexOf == baseIndexOf,\n isLarge = prereq && createCache && length >= 200,", "new_contents": " });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` without\n * support for callback shorthands and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iterator The function called per iteration.\n * @param {boolean} [retHighest=false] Specify returning the highest, instead\n * of the lowest, index at which a value should be inserted into `array`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, iterator, retHighest) {\n var low = 0,\n high = array ? array.length : low;\n\n value = iterator(value);\n var hintNum = typeof value == 'number' ||\n (value != null && isFunction(value.valueOf) && typeof value.valueOf() == 'number');\n\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = iterator(array[mid]);\n\n if (hintNum && typeof computed != 'undefined') {\n computed = +computed || 0;\n }\n if (retHighest ? computed <= value : computed < value) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n\n /**\n * The base implementation of `_.uniq` without support for callback shorthands\n * and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iterator] The function called per iteration.\n * @returns {Array} Returns the new duplicate-value-free array.\n */\n function baseUniq(array, iterator) {\n var index = -1,\n indexOf = getIndexOf(),\n length = array.length,\n prereq = indexOf == baseIndexOf,\n isLarge = prereq && createCache && length >= 200,", "text": "<|original_code|>\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` without\n * support for callback shorthands and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iterator The function called per iteration.\n * @param {boolean} [retHighest=false] Specify returning the highest, instead\n * of the lowest, index at which a value should be inserted into `array`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, iterator, retHighest) {\n var low = 0,\n high = array ? array.length : low;\n\n value = iterator(value);\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = iterator(array[mid]);\n\n if (retHighest ? computed <= value : computed < value) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n\n /**\n * The base implementation of `_.uniq` without support for callback shorthands\n * and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iterator] The function called per iteration.\n * @returns {Array} Returns the new duplicate-value-free array.\n */\n function baseUniq(array, iterator) {\n var index = -1,\n indexOf = getIndexOf(),\n length = array.length,\n prereq = indexOf == baseIndexOf,\n isLarge = prereq && createCache && length >= 200,\n<|edits_diff|>\n--- lodash.js\n+++ lodash.js\n@@ -20,6 +20,9 @@\n high = array ? array.length : low;\n \n value = iterator(value);\n+ var hintNum = typeof value == 'number' ||\n+ (value != null && isFunction(value.valueOf) && typeof value.valueOf() == 'number');\n+\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = iterator(array[mid]);\n<|current_version|>\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` without\n * support for callback shorthands and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iterator The function called per iteration.\n * @param {boolean} [retHighest=false] Specify returning the highest, instead\n * of the lowest, index at which a value should be inserted into `array`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, iterator, retHighest) {\n var low = 0,\n high = array ? array.length : low;\n\n value = iterator(value);\n var hintNum = typeof value == 'number' ||\n (value != null && isFunction(value.valueOf) && typeof value.valueOf() == 'number');\n\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = iterator(array[mid]);\n\n if (retHighest ? computed <= value : computed < value) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n\n /**\n * The base implementation of `_.uniq` without support for callback shorthands\n * and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iterator] The function called per iteration.\n * @returns {Array} Returns the new duplicate-value-free array.\n */\n function baseUniq(array, iterator) {\n var index = -1,\n indexOf = getIndexOf(),\n length = array.length,\n prereq = indexOf == baseIndexOf,\n isLarge = prereq && createCache && length >= 200,\n<|next_version|>\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` without\n * support for callback shorthands and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iterator The function called per iteration.\n * @param {boolean} [retHighest=false] Specify returning the highest, instead\n * of the lowest, index at which a value should be inserted into `array`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, iterator, retHighest) {\n var low = 0,\n high = array ? array.length : low;\n\n value = iterator(value);\n var hintNum = typeof value == 'number' ||\n (value != null && isFunction(value.valueOf) && typeof value.valueOf() == 'number');\n\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = iterator(array[mid]);\n\n if (hintNum && typeof computed != 'undefined') {\n computed = +computed || 0;\n }\n if (retHighest ? computed <= value : computed < value) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n\n /**\n * The base implementation of `_.uniq` without support for callback shorthands\n * and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iterator] The function called per iteration.\n * @returns {Array} Returns the new duplicate-value-free array.\n */\n function baseUniq(array, iterator) {\n var index = -1,\n indexOf = getIndexOf(),\n length = array.length,\n prereq = indexOf == baseIndexOf,\n isLarge = prereq && createCache && length >= 200,\n", "current_contents": " });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` without\n * support for callback shorthands and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iterator The function called per iteration.\n * @param {boolean} [retHighest=false] Specify returning the highest, instead\n * of the lowest, index at which a value should be inserted into `array`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, iterator, retHighest) {\n var low = 0,\n high = array ? array.length : low;\n\n value = iterator(value);\n var hintNum = typeof value == 'number' ||\n (value != null && isFunction(value.valueOf) && typeof value.valueOf() == 'number');\n\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = iterator(array[mid]);\n\n if (retHighest ? computed <= value : computed < value) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n\n /**\n * The base implementation of `_.uniq` without support for callback shorthands\n * and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iterator] The function called per iteration.\n * @returns {Array} Returns the new duplicate-value-free array.\n */\n function baseUniq(array, iterator) {\n var index = -1,\n indexOf = getIndexOf(),\n length = array.length,\n prereq = indexOf == baseIndexOf,\n isLarge = prereq && createCache && length >= 200,"} {"commit": "88d5f5d76c711dbf5c939ab3d00d2bb3919e1f9a", "message": "Update Backbone tests to 1.1.1.", "old_file": "vendor/backbone/test/environment.js", "new_file": "vendor/backbone/test/environment.js", "status": "M", "old_contents": "(function() {\n\n var sync = Backbone.sync;\n var ajax = Backbone.ajax;\n var emulateHTTP = Backbone.emulateHTTP;\n var emulateJSON = Backbone.emulateJSON;\n\n QUnit.testStart(function() {\n var env = this.config.current.testEnvironment;\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n sync.apply(this, arguments);\n };\n\n });\n\n QUnit.testDone(function() {\n Backbone.sync = sync;\n Backbone.ajax = ajax;\n Backbone.emulateHTTP = emulateHTTP;\n Backbone.emulateJSON = emulateJSON;\n });\n\n})();\n", "new_contents": "(function() {\n\n var sync = Backbone.sync;\n var ajax = Backbone.ajax;\n var emulateHTTP = Backbone.emulateHTTP;\n var emulateJSON = Backbone.emulateJSON;\n var history = window.history;\n var pushState = history.pushState;\n var replaceState = history.replaceState;\n\n QUnit.testStart(function() {\n var env = this.config.current.testEnvironment;\n\n // We never want to actually call these during tests.\n history.pushState = history.replaceState = function(){};\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n sync.apply(this, arguments);\n };\n\n });\n\n QUnit.testDone(function() {\n Backbone.sync = sync;\n Backbone.ajax = ajax;\n Backbone.emulateHTTP = emulateHTTP;\n Backbone.emulateJSON = emulateJSON;\n history.pushState = pushState;\n history.replaceState = replaceState;\n });\n\n})();\n", "text": "<|original_code|>\n(function() {\n\n var sync = Backbone.sync;\n var ajax = Backbone.ajax;\n var emulateHTTP = Backbone.emulateHTTP;\n var emulateJSON = Backbone.emulateJSON;\n\n QUnit.testStart(function() {\n var env = this.config.current.testEnvironment;\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n sync.apply(this, arguments);\n };\n\n });\n\n QUnit.testDone(function() {\n Backbone.sync = sync;\n Backbone.ajax = ajax;\n Backbone.emulateHTTP = emulateHTTP;\n Backbone.emulateJSON = emulateJSON;\n });\n\n})();\n\n<|edits_diff|>\n--- vendor/backbone/test/environment.js\n+++ vendor/backbone/test/environment.js\n@@ -4,9 +4,15 @@\n var ajax = Backbone.ajax;\n var emulateHTTP = Backbone.emulateHTTP;\n var emulateJSON = Backbone.emulateJSON;\n+ var history = window.history;\n+ var pushState = history.pushState;\n+ var replaceState = history.replaceState;\n \n QUnit.testStart(function() {\n var env = this.config.current.testEnvironment;\n+\n+ // We never want to actually call these during tests.\n+ history.pushState = history.replaceState = function(){};\n \n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n<|current_version|>\n(function() {\n\n var sync = Backbone.sync;\n var ajax = Backbone.ajax;\n var emulateHTTP = Backbone.emulateHTTP;\n var emulateJSON = Backbone.emulateJSON;\n var history = window.history;\n var pushState = history.pushState;\n var replaceState = history.replaceState;\n\n QUnit.testStart(function() {\n var env = this.config.current.testEnvironment;\n\n // We never want to actually call these during tests.\n history.pushState = history.replaceState = function(){};\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n sync.apply(this, arguments);\n };\n\n });\n\n QUnit.testDone(function() {\n Backbone.sync = sync;\n Backbone.ajax = ajax;\n Backbone.emulateHTTP = emulateHTTP;\n Backbone.emulateJSON = emulateJSON;\n });\n\n})();\n\n<|next_version|>\n(function() {\n\n var sync = Backbone.sync;\n var ajax = Backbone.ajax;\n var emulateHTTP = Backbone.emulateHTTP;\n var emulateJSON = Backbone.emulateJSON;\n var history = window.history;\n var pushState = history.pushState;\n var replaceState = history.replaceState;\n\n QUnit.testStart(function() {\n var env = this.config.current.testEnvironment;\n\n // We never want to actually call these during tests.\n history.pushState = history.replaceState = function(){};\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n sync.apply(this, arguments);\n };\n\n });\n\n QUnit.testDone(function() {\n Backbone.sync = sync;\n Backbone.ajax = ajax;\n Backbone.emulateHTTP = emulateHTTP;\n Backbone.emulateJSON = emulateJSON;\n history.pushState = pushState;\n history.replaceState = replaceState;\n });\n\n})();\n\n", "current_contents": "(function() {\n\n var sync = Backbone.sync;\n var ajax = Backbone.ajax;\n var emulateHTTP = Backbone.emulateHTTP;\n var emulateJSON = Backbone.emulateJSON;\n var history = window.history;\n var pushState = history.pushState;\n var replaceState = history.replaceState;\n\n QUnit.testStart(function() {\n var env = this.config.current.testEnvironment;\n\n // We never want to actually call these during tests.\n history.pushState = history.replaceState = function(){};\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n sync.apply(this, arguments);\n };\n\n });\n\n QUnit.testDone(function() {\n Backbone.sync = sync;\n Backbone.ajax = ajax;\n Backbone.emulateHTTP = emulateHTTP;\n Backbone.emulateJSON = emulateJSON;\n });\n\n})();\n"} {"commit": "84d0664112181608c848b32fabc4f22b1c2c20ff", "message": "Fixed memory leak with debounce/throttle arguments and context", "old_file": "lodash.js", "new_file": "lodash.js", "status": "M", "old_contents": " throw new TypeError;\n }\n wait = nativeMax(0, wait) || 0;\n if (options === true) {\n var leading = true;\n trailing = false;\n } else if (isObject(options)) {\n leading = options.leading;\n maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);\n trailing = 'trailing' in options ? options.trailing : trailing;\n }\n var delayed = function() {\n var remaining = wait - (now() - stamp);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n clearTimeout(maxTimeoutId);\n }\n var isCalled = trailingCall;\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (isCalled) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n }\n } else {\n timeoutId = setTimeout(delayed, remaining);\n }\n };\n\n var maxDelayed = function() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (trailing || (maxWait !== wait)) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n }\n };\n\n return function() {\n args = arguments;\n stamp = now();\n thisArg = this;\n trailingCall = trailing && (timeoutId || !leading);\n\n if (maxWait === false) {\n var leadingCall = leading && !timeoutId;\n } else {\n if (!maxTimeoutId && !leading) {\n lastCalled = stamp;\n }\n var remaining = maxWait - (stamp - lastCalled);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n maxTimeoutId = clearTimeout(maxTimeoutId);\n }\n lastCalled = stamp;\n result = func.apply(thisArg, args);\n }\n else if (!maxTimeoutId) {\n maxTimeoutId = setTimeout(maxDelayed, remaining);\n }\n }\n if (!timeoutId && wait !== maxWait) {\n timeoutId = setTimeout(delayed, wait);\n }\n if (leadingCall) {\n result = func.apply(thisArg, args);\n }\n return result;\n };\n }\n\n /**\n * Defers executing the `func` function until the current call stack has cleared.\n * Additional arguments will be provided to `func` when it is invoked.\n *\n * @static\n * @memberOf _\n * @category Functions\n * @param {Function} func The function to defer.\n * @param {...*} [arg] Arguments to invoke the function with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function() { console.log('deferred'); });\n * // returns from the function before 'deferred' is logged\n */\n function defer(func) {\n if (!isFunction(func)) {\n throw new TypeError;\n }", "new_contents": " throw new TypeError;\n }\n wait = nativeMax(0, wait) || 0;\n if (options === true) {\n var leading = true;\n trailing = false;\n } else if (isObject(options)) {\n leading = options.leading;\n maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);\n trailing = 'trailing' in options ? options.trailing : trailing;\n }\n var delayed = function() {\n var remaining = wait - (now() - stamp);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n clearTimeout(maxTimeoutId);\n }\n var isCalled = trailingCall;\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (isCalled) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n } else {\n timeoutId = setTimeout(delayed, remaining);\n }\n };\n\n var maxDelayed = function() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (trailing || (maxWait !== wait)) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n };\n\n return function() {\n args = arguments;\n stamp = now();\n thisArg = this;\n trailingCall = trailing && (timeoutId || !leading);\n\n if (maxWait === false) {\n var leadingCall = leading && !timeoutId;\n } else {\n if (!maxTimeoutId && !leading) {\n lastCalled = stamp;\n }\n var remaining = maxWait - (stamp - lastCalled);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n maxTimeoutId = clearTimeout(maxTimeoutId);\n }\n lastCalled = stamp;\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n else if (!maxTimeoutId) {\n maxTimeoutId = setTimeout(maxDelayed, remaining);\n }\n }\n if (!timeoutId && wait !== maxWait) {\n timeoutId = setTimeout(delayed, wait);\n }\n if (leadingCall) {\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n return result;\n };\n }\n\n /**\n * Defers executing the `func` function until the current call stack has cleared.\n * Additional arguments will be provided to `func` when it is invoked.\n *\n * @static\n * @memberOf _\n * @category Functions\n * @param {Function} func The function to defer.\n * @param {...*} [arg] Arguments to invoke the function with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function() { console.log('deferred'); });\n * // returns from the function before 'deferred' is logged\n */\n function defer(func) {\n if (!isFunction(func)) {\n throw new TypeError;\n }", "text": "<|original_code|>\n throw new TypeError;\n }\n wait = nativeMax(0, wait) || 0;\n if (options === true) {\n var leading = true;\n trailing = false;\n } else if (isObject(options)) {\n leading = options.leading;\n maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);\n trailing = 'trailing' in options ? options.trailing : trailing;\n }\n var delayed = function() {\n var remaining = wait - (now() - stamp);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n clearTimeout(maxTimeoutId);\n }\n var isCalled = trailingCall;\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (isCalled) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n }\n } else {\n timeoutId = setTimeout(delayed, remaining);\n }\n };\n\n var maxDelayed = function() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (trailing || (maxWait !== wait)) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n }\n };\n\n return function() {\n args = arguments;\n stamp = now();\n thisArg = this;\n trailingCall = trailing && (timeoutId || !leading);\n\n if (maxWait === false) {\n var leadingCall = leading && !timeoutId;\n } else {\n if (!maxTimeoutId && !leading) {\n lastCalled = stamp;\n }\n var remaining = maxWait - (stamp - lastCalled);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n maxTimeoutId = clearTimeout(maxTimeoutId);\n }\n lastCalled = stamp;\n result = func.apply(thisArg, args);\n }\n else if (!maxTimeoutId) {\n maxTimeoutId = setTimeout(maxDelayed, remaining);\n }\n }\n if (!timeoutId && wait !== maxWait) {\n timeoutId = setTimeout(delayed, wait);\n }\n if (leadingCall) {\n result = func.apply(thisArg, args);\n }\n return result;\n };\n }\n\n /**\n * Defers executing the `func` function until the current call stack has cleared.\n * Additional arguments will be provided to `func` when it is invoked.\n *\n * @static\n * @memberOf _\n * @category Functions\n * @param {Function} func The function to defer.\n * @param {...*} [arg] Arguments to invoke the function with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function() { console.log('deferred'); });\n * // returns from the function before 'deferred' is logged\n */\n function defer(func) {\n if (!isFunction(func)) {\n throw new TypeError;\n }\n<|edits_diff|>\n--- lodash.js\n+++ lodash.js\n@@ -20,6 +20,7 @@\n if (isCalled) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n+ args = thisArg = null;\n }\n } else {\n timeoutId = setTimeout(delayed, remaining);\n@@ -34,6 +35,7 @@\n if (trailing || (maxWait !== wait)) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n+ args = thisArg = null;\n }\n };\n \n@@ -56,6 +58,7 @@\n }\n lastCalled = stamp;\n result = func.apply(thisArg, args);\n+ args = thisArg = null;\n }\n else if (!maxTimeoutId) {\n maxTimeoutId = setTimeout(maxDelayed, remaining);\n<|current_version|>\n throw new TypeError;\n }\n wait = nativeMax(0, wait) || 0;\n if (options === true) {\n var leading = true;\n trailing = false;\n } else if (isObject(options)) {\n leading = options.leading;\n maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);\n trailing = 'trailing' in options ? options.trailing : trailing;\n }\n var delayed = function() {\n var remaining = wait - (now() - stamp);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n clearTimeout(maxTimeoutId);\n }\n var isCalled = trailingCall;\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (isCalled) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n } else {\n timeoutId = setTimeout(delayed, remaining);\n }\n };\n\n var maxDelayed = function() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (trailing || (maxWait !== wait)) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n };\n\n return function() {\n args = arguments;\n stamp = now();\n thisArg = this;\n trailingCall = trailing && (timeoutId || !leading);\n\n if (maxWait === false) {\n var leadingCall = leading && !timeoutId;\n } else {\n if (!maxTimeoutId && !leading) {\n lastCalled = stamp;\n }\n var remaining = maxWait - (stamp - lastCalled);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n maxTimeoutId = clearTimeout(maxTimeoutId);\n }\n lastCalled = stamp;\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n else if (!maxTimeoutId) {\n maxTimeoutId = setTimeout(maxDelayed, remaining);\n }\n }\n if (!timeoutId && wait !== maxWait) {\n timeoutId = setTimeout(delayed, wait);\n }\n if (leadingCall) {\n result = func.apply(thisArg, args);\n }\n return result;\n };\n }\n\n /**\n * Defers executing the `func` function until the current call stack has cleared.\n * Additional arguments will be provided to `func` when it is invoked.\n *\n * @static\n * @memberOf _\n * @category Functions\n * @param {Function} func The function to defer.\n * @param {...*} [arg] Arguments to invoke the function with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function() { console.log('deferred'); });\n * // returns from the function before 'deferred' is logged\n */\n function defer(func) {\n if (!isFunction(func)) {\n throw new TypeError;\n }\n<|next_version|>\n throw new TypeError;\n }\n wait = nativeMax(0, wait) || 0;\n if (options === true) {\n var leading = true;\n trailing = false;\n } else if (isObject(options)) {\n leading = options.leading;\n maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);\n trailing = 'trailing' in options ? options.trailing : trailing;\n }\n var delayed = function() {\n var remaining = wait - (now() - stamp);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n clearTimeout(maxTimeoutId);\n }\n var isCalled = trailingCall;\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (isCalled) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n } else {\n timeoutId = setTimeout(delayed, remaining);\n }\n };\n\n var maxDelayed = function() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (trailing || (maxWait !== wait)) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n };\n\n return function() {\n args = arguments;\n stamp = now();\n thisArg = this;\n trailingCall = trailing && (timeoutId || !leading);\n\n if (maxWait === false) {\n var leadingCall = leading && !timeoutId;\n } else {\n if (!maxTimeoutId && !leading) {\n lastCalled = stamp;\n }\n var remaining = maxWait - (stamp - lastCalled);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n maxTimeoutId = clearTimeout(maxTimeoutId);\n }\n lastCalled = stamp;\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n else if (!maxTimeoutId) {\n maxTimeoutId = setTimeout(maxDelayed, remaining);\n }\n }\n if (!timeoutId && wait !== maxWait) {\n timeoutId = setTimeout(delayed, wait);\n }\n if (leadingCall) {\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n return result;\n };\n }\n\n /**\n * Defers executing the `func` function until the current call stack has cleared.\n * Additional arguments will be provided to `func` when it is invoked.\n *\n * @static\n * @memberOf _\n * @category Functions\n * @param {Function} func The function to defer.\n * @param {...*} [arg] Arguments to invoke the function with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function() { console.log('deferred'); });\n * // returns from the function before 'deferred' is logged\n */\n function defer(func) {\n if (!isFunction(func)) {\n throw new TypeError;\n }\n", "current_contents": " throw new TypeError;\n }\n wait = nativeMax(0, wait) || 0;\n if (options === true) {\n var leading = true;\n trailing = false;\n } else if (isObject(options)) {\n leading = options.leading;\n maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0);\n trailing = 'trailing' in options ? options.trailing : trailing;\n }\n var delayed = function() {\n var remaining = wait - (now() - stamp);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n clearTimeout(maxTimeoutId);\n }\n var isCalled = trailingCall;\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (isCalled) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n } else {\n timeoutId = setTimeout(delayed, remaining);\n }\n };\n\n var maxDelayed = function() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (trailing || (maxWait !== wait)) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n };\n\n return function() {\n args = arguments;\n stamp = now();\n thisArg = this;\n trailingCall = trailing && (timeoutId || !leading);\n\n if (maxWait === false) {\n var leadingCall = leading && !timeoutId;\n } else {\n if (!maxTimeoutId && !leading) {\n lastCalled = stamp;\n }\n var remaining = maxWait - (stamp - lastCalled);\n if (remaining <= 0) {\n if (maxTimeoutId) {\n maxTimeoutId = clearTimeout(maxTimeoutId);\n }\n lastCalled = stamp;\n result = func.apply(thisArg, args);\n args = thisArg = null;\n }\n else if (!maxTimeoutId) {\n maxTimeoutId = setTimeout(maxDelayed, remaining);\n }\n }\n if (!timeoutId && wait !== maxWait) {\n timeoutId = setTimeout(delayed, wait);\n }\n if (leadingCall) {\n result = func.apply(thisArg, args);\n }\n return result;\n };\n }\n\n /**\n * Defers executing the `func` function until the current call stack has cleared.\n * Additional arguments will be provided to `func` when it is invoked.\n *\n * @static\n * @memberOf _\n * @category Functions\n * @param {Function} func The function to defer.\n * @param {...*} [arg] Arguments to invoke the function with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function() { console.log('deferred'); });\n * // returns from the function before 'deferred' is logged\n */\n function defer(func) {\n if (!isFunction(func)) {\n throw new TypeError;\n }"} {"commit": "2639cc61385f387933cc5fc4f7735768c3c99aaf", "message": "Update vendors.", "old_file": "vendor/underscore/test/collections.js", "new_file": "vendor/underscore/test/collections.js", "status": "M", "old_contents": " test('groupBy', function() {\n var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });\n ok('0' in parity && '1' in parity, 'created a group for each value');\n equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.groupBy(list, 'length');\n equal(grouped['3'].join(' '), 'one two six ten');\n equal(grouped['4'].join(' '), 'four five nine');\n equal(grouped['5'].join(' '), 'three seven eight');\n\n var context = {};\n _.groupBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor.length, 1);\n equal(grouped.hasOwnProperty.length, 2);\n\n var array = [{}];\n _.groupBy(array, function(value, index, obj){ ok(obj === array); });\n });\n\n test('countBy', function() {\n var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });\n equal(parity['true'], 2);\n equal(parity['false'], 3);\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.countBy(list, 'length');\n equal(grouped['3'], 4);\n equal(grouped['4'], 3);\n equal(grouped['5'], 3);\n\n var context = {};\n _.countBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.countBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor, 1);\n equal(grouped.hasOwnProperty, 2);\n\n var array = [{}];\n _.countBy(array, function(value, index, obj){ ok(obj === array); });\n });\n\n test('sortedIndex', function() {\n var numbers = [10, 20, 30, 40, 50], num = 35;\n var indexForNum = _.sortedIndex(numbers, num);\n equal(indexForNum, 3, '35 should be inserted at index 3');\n\n var indexFor30 = _.sortedIndex(numbers, 30);\n equal(indexFor30, 2, '30 should be inserted at index 2');\n\n var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];\n var iterator = function(obj){ return obj.x; };\n strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);\n strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);\n\n var context = {1: 2, 2: 3, 3: 4};\n iterator = function(obj){ return this[obj]; };\n strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);\n });\n\n test('shuffle', function() {\n var numbers = _.range(10);\n var shuffled = _.shuffle(numbers).sort();\n notStrictEqual(numbers, shuffled, 'original object is unmodified');", "new_contents": " test('groupBy', function() {\n var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });\n ok('0' in parity && '1' in parity, 'created a group for each value');\n equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.groupBy(list, 'length');\n equal(grouped['3'].join(' '), 'one two six ten');\n equal(grouped['4'].join(' '), 'four five nine');\n equal(grouped['5'].join(' '), 'three seven eight');\n\n var context = {};\n _.groupBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor.length, 1);\n equal(grouped.hasOwnProperty.length, 2);\n\n var array = [{}];\n _.groupBy(array, function(value, index, obj){ ok(obj === array); });\n\n var array = [1, 2, 1, 2, 3];\n var grouped = _.groupBy(array);\n equal(grouped['1'].length, 2);\n equal(grouped['3'].length, 1);\n });\n\n test('countBy', function() {\n var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });\n equal(parity['true'], 2);\n equal(parity['false'], 3);\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.countBy(list, 'length');\n equal(grouped['3'], 4);\n equal(grouped['4'], 3);\n equal(grouped['5'], 3);\n\n var context = {};\n _.countBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.countBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor, 1);\n equal(grouped.hasOwnProperty, 2);\n\n var array = [{}];\n _.countBy(array, function(value, index, obj){ ok(obj === array); });\n\n var array = [1, 2, 1, 2, 3];\n var grouped = _.countBy(array);\n equal(grouped['1'], 2);\n equal(grouped['3'], 1);\n });\n\n test('sortedIndex', function() {\n var numbers = [10, 20, 30, 40, 50], num = 35;\n var indexForNum = _.sortedIndex(numbers, num);\n equal(indexForNum, 3, '35 should be inserted at index 3');\n\n var indexFor30 = _.sortedIndex(numbers, 30);\n equal(indexFor30, 2, '30 should be inserted at index 2');\n\n var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];\n var iterator = function(obj){ return obj.x; };\n strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);\n strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);\n\n var context = {1: 2, 2: 3, 3: 4};\n iterator = function(obj){ return this[obj]; };\n strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);\n });\n\n test('shuffle', function() {\n var numbers = _.range(10);\n var shuffled = _.shuffle(numbers).sort();\n notStrictEqual(numbers, shuffled, 'original object is unmodified');", "text": "<|original_code|>\n test('groupBy', function() {\n var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });\n ok('0' in parity && '1' in parity, 'created a group for each value');\n equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.groupBy(list, 'length');\n equal(grouped['3'].join(' '), 'one two six ten');\n equal(grouped['4'].join(' '), 'four five nine');\n equal(grouped['5'].join(' '), 'three seven eight');\n\n var context = {};\n _.groupBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor.length, 1);\n equal(grouped.hasOwnProperty.length, 2);\n\n var array = [{}];\n _.groupBy(array, function(value, index, obj){ ok(obj === array); });\n });\n\n test('countBy', function() {\n var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });\n equal(parity['true'], 2);\n equal(parity['false'], 3);\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.countBy(list, 'length');\n equal(grouped['3'], 4);\n equal(grouped['4'], 3);\n equal(grouped['5'], 3);\n\n var context = {};\n _.countBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.countBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor, 1);\n equal(grouped.hasOwnProperty, 2);\n\n var array = [{}];\n _.countBy(array, function(value, index, obj){ ok(obj === array); });\n });\n\n test('sortedIndex', function() {\n var numbers = [10, 20, 30, 40, 50], num = 35;\n var indexForNum = _.sortedIndex(numbers, num);\n equal(indexForNum, 3, '35 should be inserted at index 3');\n\n var indexFor30 = _.sortedIndex(numbers, 30);\n equal(indexFor30, 2, '30 should be inserted at index 2');\n\n var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];\n var iterator = function(obj){ return obj.x; };\n strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);\n strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);\n\n var context = {1: 2, 2: 3, 3: 4};\n iterator = function(obj){ return this[obj]; };\n strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);\n });\n\n test('shuffle', function() {\n var numbers = _.range(10);\n var shuffled = _.shuffle(numbers).sort();\n notStrictEqual(numbers, shuffled, 'original object is unmodified');\n<|edits_diff|>\n--- vendor/underscore/test/collections.js\n+++ vendor/underscore/test/collections.js\n@@ -20,6 +20,11 @@\n \n var array = [{}];\n _.groupBy(array, function(value, index, obj){ ok(obj === array); });\n+\n+ var array = [1, 2, 1, 2, 3];\n+ var grouped = _.groupBy(array);\n+ equal(grouped['1'].length, 2);\n+ equal(grouped['3'].length, 1);\n });\n \n test('countBy', function() {\n<|current_version|>\n test('groupBy', function() {\n var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });\n ok('0' in parity && '1' in parity, 'created a group for each value');\n equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.groupBy(list, 'length');\n equal(grouped['3'].join(' '), 'one two six ten');\n equal(grouped['4'].join(' '), 'four five nine');\n equal(grouped['5'].join(' '), 'three seven eight');\n\n var context = {};\n _.groupBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor.length, 1);\n equal(grouped.hasOwnProperty.length, 2);\n\n var array = [{}];\n _.groupBy(array, function(value, index, obj){ ok(obj === array); });\n\n var array = [1, 2, 1, 2, 3];\n var grouped = _.groupBy(array);\n equal(grouped['1'].length, 2);\n equal(grouped['3'].length, 1);\n });\n\n test('countBy', function() {\n var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });\n equal(parity['true'], 2);\n equal(parity['false'], 3);\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.countBy(list, 'length');\n equal(grouped['3'], 4);\n equal(grouped['4'], 3);\n equal(grouped['5'], 3);\n\n var context = {};\n _.countBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.countBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor, 1);\n equal(grouped.hasOwnProperty, 2);\n\n var array = [{}];\n _.countBy(array, function(value, index, obj){ ok(obj === array); });\n });\n\n test('sortedIndex', function() {\n var numbers = [10, 20, 30, 40, 50], num = 35;\n var indexForNum = _.sortedIndex(numbers, num);\n equal(indexForNum, 3, '35 should be inserted at index 3');\n\n var indexFor30 = _.sortedIndex(numbers, 30);\n equal(indexFor30, 2, '30 should be inserted at index 2');\n\n var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];\n var iterator = function(obj){ return obj.x; };\n strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);\n strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);\n\n var context = {1: 2, 2: 3, 3: 4};\n iterator = function(obj){ return this[obj]; };\n strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);\n });\n\n test('shuffle', function() {\n var numbers = _.range(10);\n var shuffled = _.shuffle(numbers).sort();\n notStrictEqual(numbers, shuffled, 'original object is unmodified');\n<|next_version|>\n test('groupBy', function() {\n var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });\n ok('0' in parity && '1' in parity, 'created a group for each value');\n equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.groupBy(list, 'length');\n equal(grouped['3'].join(' '), 'one two six ten');\n equal(grouped['4'].join(' '), 'four five nine');\n equal(grouped['5'].join(' '), 'three seven eight');\n\n var context = {};\n _.groupBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor.length, 1);\n equal(grouped.hasOwnProperty.length, 2);\n\n var array = [{}];\n _.groupBy(array, function(value, index, obj){ ok(obj === array); });\n\n var array = [1, 2, 1, 2, 3];\n var grouped = _.groupBy(array);\n equal(grouped['1'].length, 2);\n equal(grouped['3'].length, 1);\n });\n\n test('countBy', function() {\n var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });\n equal(parity['true'], 2);\n equal(parity['false'], 3);\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.countBy(list, 'length');\n equal(grouped['3'], 4);\n equal(grouped['4'], 3);\n equal(grouped['5'], 3);\n\n var context = {};\n _.countBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.countBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor, 1);\n equal(grouped.hasOwnProperty, 2);\n\n var array = [{}];\n _.countBy(array, function(value, index, obj){ ok(obj === array); });\n\n var array = [1, 2, 1, 2, 3];\n var grouped = _.countBy(array);\n equal(grouped['1'], 2);\n equal(grouped['3'], 1);\n });\n\n test('sortedIndex', function() {\n var numbers = [10, 20, 30, 40, 50], num = 35;\n var indexForNum = _.sortedIndex(numbers, num);\n equal(indexForNum, 3, '35 should be inserted at index 3');\n\n var indexFor30 = _.sortedIndex(numbers, 30);\n equal(indexFor30, 2, '30 should be inserted at index 2');\n\n var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];\n var iterator = function(obj){ return obj.x; };\n strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);\n strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);\n\n var context = {1: 2, 2: 3, 3: 4};\n iterator = function(obj){ return this[obj]; };\n strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);\n });\n\n test('shuffle', function() {\n var numbers = _.range(10);\n var shuffled = _.shuffle(numbers).sort();\n notStrictEqual(numbers, shuffled, 'original object is unmodified');\n", "current_contents": " test('groupBy', function() {\n var parity = _.groupBy([1, 2, 3, 4, 5, 6], function(num){ return num % 2; });\n ok('0' in parity && '1' in parity, 'created a group for each value');\n equal(parity[0].join(', '), '2, 4, 6', 'put each even number in the right group');\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.groupBy(list, 'length');\n equal(grouped['3'].join(' '), 'one two six ten');\n equal(grouped['4'].join(' '), 'four five nine');\n equal(grouped['5'].join(' '), 'three seven eight');\n\n var context = {};\n _.groupBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.groupBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor.length, 1);\n equal(grouped.hasOwnProperty.length, 2);\n\n var array = [{}];\n _.groupBy(array, function(value, index, obj){ ok(obj === array); });\n\n var array = [1, 2, 1, 2, 3];\n var grouped = _.groupBy(array);\n equal(grouped['1'].length, 2);\n equal(grouped['3'].length, 1);\n });\n\n test('countBy', function() {\n var parity = _.countBy([1, 2, 3, 4, 5], function(num){ return num % 2 == 0; });\n equal(parity['true'], 2);\n equal(parity['false'], 3);\n\n var list = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\"];\n var grouped = _.countBy(list, 'length');\n equal(grouped['3'], 4);\n equal(grouped['4'], 3);\n equal(grouped['5'], 3);\n\n var context = {};\n _.countBy([{}], function(){ ok(this === context); }, context);\n\n grouped = _.countBy([4.2, 6.1, 6.4], function(num) {\n return Math.floor(num) > 4 ? 'hasOwnProperty' : 'constructor';\n });\n equal(grouped.constructor, 1);\n equal(grouped.hasOwnProperty, 2);\n\n var array = [{}];\n _.countBy(array, function(value, index, obj){ ok(obj === array); });\n });\n\n test('sortedIndex', function() {\n var numbers = [10, 20, 30, 40, 50], num = 35;\n var indexForNum = _.sortedIndex(numbers, num);\n equal(indexForNum, 3, '35 should be inserted at index 3');\n\n var indexFor30 = _.sortedIndex(numbers, 30);\n equal(indexFor30, 2, '30 should be inserted at index 2');\n\n var objects = [{x: 10}, {x: 20}, {x: 30}, {x: 40}];\n var iterator = function(obj){ return obj.x; };\n strictEqual(_.sortedIndex(objects, {x: 25}, iterator), 2);\n strictEqual(_.sortedIndex(objects, {x: 35}, 'x'), 3);\n\n var context = {1: 2, 2: 3, 3: 4};\n iterator = function(obj){ return this[obj]; };\n strictEqual(_.sortedIndex([1, 3], 2, iterator, context), 1);\n });\n\n test('shuffle', function() {\n var numbers = _.range(10);\n var shuffled = _.shuffle(numbers).sort();\n notStrictEqual(numbers, shuffled, 'original object is unmodified');"} {"commit": "6c8e19a3212e5bbc6f94ad377dc2fd6d7d8fff8d", "message": "Update vendor/backbone.", "old_file": "vendor/backbone/test/environment.js", "new_file": "vendor/backbone/test/environment.js", "status": "M", "old_contents": "(function() {\n\n var Environment = this.Environment = function(){};\n\n _.extend(Environment.prototype, {\n\n ajax: Backbone.ajax,\n\n sync: Backbone.sync,\n\n setup: function() {\n var env = this;\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n env.sync.apply(this, arguments);\n };\n },\n\n teardown: function() {\n this.syncArgs = null;\n this.ajaxSettings = null;\n Backbone.sync = this.sync;\n Backbone.ajax = this.ajax;\n }\n\n });\n\n})();\n", "new_contents": "(function() {\n\n var Environment = this.Environment = function(){};\n\n _.extend(Environment.prototype, {\n\n ajax: Backbone.ajax,\n\n sync: Backbone.sync,\n\n emulateHTTP: Backbone.emulateHTTP,\n\n emulateJSON: Backbone.emulateJSON,\n\n setup: function() {\n var env = this;\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n env.sync.apply(this, arguments);\n };\n },\n\n teardown: function() {\n this.syncArgs = null;\n this.ajaxSettings = null;\n Backbone.sync = this.sync;\n Backbone.ajax = this.ajax;\n Backbone.emulateHTTP = this.emulateHTTP;\n Backbone.emulateJSON = this.emulateJSON;\n }\n\n });\n\n})();\n", "text": "<|original_code|>\n(function() {\n\n var Environment = this.Environment = function(){};\n\n _.extend(Environment.prototype, {\n\n ajax: Backbone.ajax,\n\n sync: Backbone.sync,\n\n setup: function() {\n var env = this;\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n env.sync.apply(this, arguments);\n };\n },\n\n teardown: function() {\n this.syncArgs = null;\n this.ajaxSettings = null;\n Backbone.sync = this.sync;\n Backbone.ajax = this.ajax;\n }\n\n });\n\n})();\n\n<|edits_diff|>\n--- vendor/backbone/test/environment.js\n+++ vendor/backbone/test/environment.js\n@@ -7,6 +7,10 @@\n ajax: Backbone.ajax,\n \n sync: Backbone.sync,\n+\n+ emulateHTTP: Backbone.emulateHTTP,\n+\n+ emulateJSON: Backbone.emulateJSON,\n \n setup: function() {\n var env = this;\n<|current_version|>\n(function() {\n\n var Environment = this.Environment = function(){};\n\n _.extend(Environment.prototype, {\n\n ajax: Backbone.ajax,\n\n sync: Backbone.sync,\n\n emulateHTTP: Backbone.emulateHTTP,\n\n emulateJSON: Backbone.emulateJSON,\n\n setup: function() {\n var env = this;\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n env.sync.apply(this, arguments);\n };\n },\n\n teardown: function() {\n this.syncArgs = null;\n this.ajaxSettings = null;\n Backbone.sync = this.sync;\n Backbone.ajax = this.ajax;\n }\n\n });\n\n})();\n\n<|next_version|>\n(function() {\n\n var Environment = this.Environment = function(){};\n\n _.extend(Environment.prototype, {\n\n ajax: Backbone.ajax,\n\n sync: Backbone.sync,\n\n emulateHTTP: Backbone.emulateHTTP,\n\n emulateJSON: Backbone.emulateJSON,\n\n setup: function() {\n var env = this;\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n env.sync.apply(this, arguments);\n };\n },\n\n teardown: function() {\n this.syncArgs = null;\n this.ajaxSettings = null;\n Backbone.sync = this.sync;\n Backbone.ajax = this.ajax;\n Backbone.emulateHTTP = this.emulateHTTP;\n Backbone.emulateJSON = this.emulateJSON;\n }\n\n });\n\n})();\n\n", "current_contents": "(function() {\n\n var Environment = this.Environment = function(){};\n\n _.extend(Environment.prototype, {\n\n ajax: Backbone.ajax,\n\n sync: Backbone.sync,\n\n emulateHTTP: Backbone.emulateHTTP,\n\n emulateJSON: Backbone.emulateJSON,\n\n setup: function() {\n var env = this;\n\n // Capture ajax settings for comparison.\n Backbone.ajax = function(settings) {\n env.ajaxSettings = settings;\n };\n\n // Capture the arguments to Backbone.sync for comparison.\n Backbone.sync = function(method, model, options) {\n env.syncArgs = {\n method: method,\n model: model,\n options: options\n };\n env.sync.apply(this, arguments);\n };\n },\n\n teardown: function() {\n this.syncArgs = null;\n this.ajaxSettings = null;\n Backbone.sync = this.sync;\n Backbone.ajax = this.ajax;\n }\n\n });\n\n})();\n"} {"commit": "348c93515cf56263828c683ebab055e6c800b63b", "message": "Issue #272 ... min and max of empty objects.", "old_file": "underscore.js", "new_file": "underscore.js", "status": "M", "old_contents": " any(obj, function(value) {\n if (found = value === target) return true;\n });\n return found;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n return _.map(obj, function(value) {\n return (method.call ? method || value : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, function(value){ return value[key]; });\n };\n\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);\n var result = {computed : -Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed >= result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);\n var result = {computed : Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed < result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Shuffle an array.\n _.shuffle = function(obj) {\n var shuffled = [], rand;\n each(obj, function(value, index, list) {\n if (index == 0) {\n shuffled[0] = value;\n } else {\n rand = Math.floor(Math.random() * (index + 1));\n shuffled[index] = shuffled[rand];\n shuffled[rand] = value;\n }\n });\n return shuffled;\n };\n\n // Sort the object's values by a criterion produced by an iterator.", "new_contents": " any(obj, function(value) {\n if (found = value === target) return true;\n });\n return found;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n return _.map(obj, function(value) {\n return (method.call ? method || value : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, function(value){ return value[key]; });\n };\n\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return -Infinity;\n var result = {computed : -Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed >= result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return Infinity;\n var result = {computed : Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed < result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Shuffle an array.\n _.shuffle = function(obj) {\n var shuffled = [], rand;\n each(obj, function(value, index, list) {\n if (index == 0) {\n shuffled[0] = value;\n } else {\n rand = Math.floor(Math.random() * (index + 1));\n shuffled[index] = shuffled[rand];\n shuffled[rand] = value;\n }\n });\n return shuffled;\n };\n\n // Sort the object's values by a criterion produced by an iterator.", "text": "<|original_code|>\n any(obj, function(value) {\n if (found = value === target) return true;\n });\n return found;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n return _.map(obj, function(value) {\n return (method.call ? method || value : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, function(value){ return value[key]; });\n };\n\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);\n var result = {computed : -Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed >= result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);\n var result = {computed : Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed < result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Shuffle an array.\n _.shuffle = function(obj) {\n var shuffled = [], rand;\n each(obj, function(value, index, list) {\n if (index == 0) {\n shuffled[0] = value;\n } else {\n rand = Math.floor(Math.random() * (index + 1));\n shuffled[index] = shuffled[rand];\n shuffled[rand] = value;\n }\n });\n return shuffled;\n };\n\n // Sort the object's values by a criterion produced by an iterator.\n<|edits_diff|>\n--- underscore.js\n+++ underscore.js\n@@ -20,6 +20,7 @@\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);\n+ if (!iterator && _.isEmpty(obj)) return -Infinity;\n var result = {computed : -Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n<|current_version|>\n any(obj, function(value) {\n if (found = value === target) return true;\n });\n return found;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n return _.map(obj, function(value) {\n return (method.call ? method || value : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, function(value){ return value[key]; });\n };\n\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return -Infinity;\n var result = {computed : -Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed >= result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);\n var result = {computed : Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed < result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Shuffle an array.\n _.shuffle = function(obj) {\n var shuffled = [], rand;\n each(obj, function(value, index, list) {\n if (index == 0) {\n shuffled[0] = value;\n } else {\n rand = Math.floor(Math.random() * (index + 1));\n shuffled[index] = shuffled[rand];\n shuffled[rand] = value;\n }\n });\n return shuffled;\n };\n\n // Sort the object's values by a criterion produced by an iterator.\n<|next_version|>\n any(obj, function(value) {\n if (found = value === target) return true;\n });\n return found;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n return _.map(obj, function(value) {\n return (method.call ? method || value : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, function(value){ return value[key]; });\n };\n\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return -Infinity;\n var result = {computed : -Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed >= result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return Infinity;\n var result = {computed : Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed < result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Shuffle an array.\n _.shuffle = function(obj) {\n var shuffled = [], rand;\n each(obj, function(value, index, list) {\n if (index == 0) {\n shuffled[0] = value;\n } else {\n rand = Math.floor(Math.random() * (index + 1));\n shuffled[index] = shuffled[rand];\n shuffled[rand] = value;\n }\n });\n return shuffled;\n };\n\n // Sort the object's values by a criterion produced by an iterator.\n", "current_contents": " any(obj, function(value) {\n if (found = value === target) return true;\n });\n return found;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n return _.map(obj, function(value) {\n return (method.call ? method || value : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, function(value){ return value[key]; });\n };\n\n // Return the maximum element or (element-based computation).\n _.max = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);\n if (!iterator && _.isEmpty(obj)) return -Infinity;\n var result = {computed : -Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed >= result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iterator, context) {\n if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);\n var result = {computed : Infinity};\n each(obj, function(value, index, list) {\n var computed = iterator ? iterator.call(context, value, index, list) : value;\n computed < result.computed && (result = {value : value, computed : computed});\n });\n return result.value;\n };\n\n // Shuffle an array.\n _.shuffle = function(obj) {\n var shuffled = [], rand;\n each(obj, function(value, index, list) {\n if (index == 0) {\n shuffled[0] = value;\n } else {\n rand = Math.floor(Math.random() * (index + 1));\n shuffled[index] = shuffled[rand];\n shuffled[rand] = value;\n }\n });\n return shuffled;\n };\n\n // Sort the object's values by a criterion produced by an iterator."} {"commit": "40af1652ebb1b07ae1dc7e754e9872b1db5a5a5f", "message": "Modified any/some test case to demonstrate issue #177 Fixed any/some formatting to be consistent with the rest of underscore.js", "old_file": "test/collections.js", "new_file": "test/collections.js", "status": "M", "old_contents": " var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'selected each even number');\n\n evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'aliased as \"filter\"');\n });\n\n test('collections: reject', function() {\n var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(odds.join(', '), '1, 3, 5', 'rejected each even number');\n });\n\n test('collections: all', function() {\n ok(_.all([], _.identity), 'the empty set');\n ok(_.all([true, true, true], _.identity), 'all true values');\n ok(!_.all([true, false, true], _.identity), 'one false value');\n ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');\n ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');\n ok(_.every([true, true, true], _.identity), 'aliased as \"every\"');\n });\n\n test('collections: any', function() {\n ok(!_.any([]), 'the empty set');\n ok(!_.any([false, false, false]), 'all false values');\n ok(_.any([false, false, true]), 'one true value');\n ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');\n ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');\n ok(_.some([false, false, true]), 'aliased as \"some\"');\n });\n\n test('collections: include', function() {\n ok(_.include([1,2,3], 2), 'two is in the array');\n ok(!_.include([1,3,9], 2), 'two is not in the array');\n ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');\n ok(_([1,2,3]).include(2), 'OO-style include');\n });\n\n test('collections: invoke', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, 'sort');\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: invoke w/ function reference', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, Array.prototype.sort);\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: pluck', function() {", "new_contents": " var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'selected each even number');\n\n evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'aliased as \"filter\"');\n });\n\n test('collections: reject', function() {\n var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(odds.join(', '), '1, 3, 5', 'rejected each even number');\n });\n\n test('collections: all', function() {\n ok(_.all([], _.identity), 'the empty set');\n ok(_.all([true, true, true], _.identity), 'all true values');\n ok(!_.all([true, false, true], _.identity), 'one false value');\n ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');\n ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');\n ok(_.every([true, true, true], _.identity), 'aliased as \"every\"');\n });\n\n test('collections: any', function() {\n var nativeSome = Array.prototype.some;\n Array.prototype.some = null;\n ok(!_.any([]), 'the empty set');\n ok(!_.any([false, false, false]), 'all false values');\n ok(_.any([false, false, true]), 'one true value');\n ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');\n ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');\n ok(_.some([false, false, true]), 'aliased as \"some\"');\n Array.prototype.some = nativeSome;\n });\n\n test('collections: include', function() {\n ok(_.include([1,2,3], 2), 'two is in the array');\n ok(!_.include([1,3,9], 2), 'two is not in the array');\n ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');\n ok(_([1,2,3]).include(2), 'OO-style include');\n });\n\n test('collections: invoke', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, 'sort');\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: invoke w/ function reference', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, Array.prototype.sort);\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: pluck', function() {", "text": "<|original_code|>\n var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'selected each even number');\n\n evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'aliased as \"filter\"');\n });\n\n test('collections: reject', function() {\n var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(odds.join(', '), '1, 3, 5', 'rejected each even number');\n });\n\n test('collections: all', function() {\n ok(_.all([], _.identity), 'the empty set');\n ok(_.all([true, true, true], _.identity), 'all true values');\n ok(!_.all([true, false, true], _.identity), 'one false value');\n ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');\n ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');\n ok(_.every([true, true, true], _.identity), 'aliased as \"every\"');\n });\n\n test('collections: any', function() {\n ok(!_.any([]), 'the empty set');\n ok(!_.any([false, false, false]), 'all false values');\n ok(_.any([false, false, true]), 'one true value');\n ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');\n ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');\n ok(_.some([false, false, true]), 'aliased as \"some\"');\n });\n\n test('collections: include', function() {\n ok(_.include([1,2,3], 2), 'two is in the array');\n ok(!_.include([1,3,9], 2), 'two is not in the array');\n ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');\n ok(_([1,2,3]).include(2), 'OO-style include');\n });\n\n test('collections: invoke', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, 'sort');\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: invoke w/ function reference', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, Array.prototype.sort);\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: pluck', function() {\n<|edits_diff|>\n--- test/collections.js\n+++ test/collections.js\n@@ -20,6 +20,8 @@\n });\n \n test('collections: any', function() {\n+ var nativeSome = Array.prototype.some;\n+ Array.prototype.some = null;\n ok(!_.any([]), 'the empty set');\n ok(!_.any([false, false, false]), 'all false values');\n ok(_.any([false, false, true]), 'one true value');\n<|current_version|>\n var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'selected each even number');\n\n evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'aliased as \"filter\"');\n });\n\n test('collections: reject', function() {\n var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(odds.join(', '), '1, 3, 5', 'rejected each even number');\n });\n\n test('collections: all', function() {\n ok(_.all([], _.identity), 'the empty set');\n ok(_.all([true, true, true], _.identity), 'all true values');\n ok(!_.all([true, false, true], _.identity), 'one false value');\n ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');\n ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');\n ok(_.every([true, true, true], _.identity), 'aliased as \"every\"');\n });\n\n test('collections: any', function() {\n var nativeSome = Array.prototype.some;\n Array.prototype.some = null;\n ok(!_.any([]), 'the empty set');\n ok(!_.any([false, false, false]), 'all false values');\n ok(_.any([false, false, true]), 'one true value');\n ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');\n ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');\n ok(_.some([false, false, true]), 'aliased as \"some\"');\n });\n\n test('collections: include', function() {\n ok(_.include([1,2,3], 2), 'two is in the array');\n ok(!_.include([1,3,9], 2), 'two is not in the array');\n ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');\n ok(_([1,2,3]).include(2), 'OO-style include');\n });\n\n test('collections: invoke', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, 'sort');\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: invoke w/ function reference', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, Array.prototype.sort);\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: pluck', function() {\n<|next_version|>\n var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'selected each even number');\n\n evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'aliased as \"filter\"');\n });\n\n test('collections: reject', function() {\n var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(odds.join(', '), '1, 3, 5', 'rejected each even number');\n });\n\n test('collections: all', function() {\n ok(_.all([], _.identity), 'the empty set');\n ok(_.all([true, true, true], _.identity), 'all true values');\n ok(!_.all([true, false, true], _.identity), 'one false value');\n ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');\n ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');\n ok(_.every([true, true, true], _.identity), 'aliased as \"every\"');\n });\n\n test('collections: any', function() {\n var nativeSome = Array.prototype.some;\n Array.prototype.some = null;\n ok(!_.any([]), 'the empty set');\n ok(!_.any([false, false, false]), 'all false values');\n ok(_.any([false, false, true]), 'one true value');\n ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');\n ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');\n ok(_.some([false, false, true]), 'aliased as \"some\"');\n Array.prototype.some = nativeSome;\n });\n\n test('collections: include', function() {\n ok(_.include([1,2,3], 2), 'two is in the array');\n ok(!_.include([1,3,9], 2), 'two is not in the array');\n ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');\n ok(_([1,2,3]).include(2), 'OO-style include');\n });\n\n test('collections: invoke', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, 'sort');\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: invoke w/ function reference', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, Array.prototype.sort);\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: pluck', function() {\n", "current_contents": " var evens = _.select([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'selected each even number');\n\n evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(evens.join(', '), '2, 4, 6', 'aliased as \"filter\"');\n });\n\n test('collections: reject', function() {\n var odds = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });\n equals(odds.join(', '), '1, 3, 5', 'rejected each even number');\n });\n\n test('collections: all', function() {\n ok(_.all([], _.identity), 'the empty set');\n ok(_.all([true, true, true], _.identity), 'all true values');\n ok(!_.all([true, false, true], _.identity), 'one false value');\n ok(_.all([0, 10, 28], function(num){ return num % 2 == 0; }), 'even numbers');\n ok(!_.all([0, 11, 28], function(num){ return num % 2 == 0; }), 'an odd number');\n ok(_.every([true, true, true], _.identity), 'aliased as \"every\"');\n });\n\n test('collections: any', function() {\n var nativeSome = Array.prototype.some;\n Array.prototype.some = null;\n ok(!_.any([]), 'the empty set');\n ok(!_.any([false, false, false]), 'all false values');\n ok(_.any([false, false, true]), 'one true value');\n ok(!_.any([1, 11, 29], function(num){ return num % 2 == 0; }), 'all odd numbers');\n ok(_.any([1, 10, 29], function(num){ return num % 2 == 0; }), 'an even number');\n ok(_.some([false, false, true]), 'aliased as \"some\"');\n });\n\n test('collections: include', function() {\n ok(_.include([1,2,3], 2), 'two is in the array');\n ok(!_.include([1,3,9], 2), 'two is not in the array');\n ok(_.contains({moe:1, larry:3, curly:9}, 3) === true, '_.include on objects checks their values');\n ok(_([1,2,3]).include(2), 'OO-style include');\n });\n\n test('collections: invoke', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, 'sort');\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: invoke w/ function reference', function() {\n var list = [[5, 1, 7], [3, 2, 1]];\n var result = _.invoke(list, Array.prototype.sort);\n equals(result[0].join(', '), '1, 5, 7', 'first array sorted');\n equals(result[1].join(', '), '1, 2, 3', 'second array sorted');\n });\n\n test('collections: pluck', function() {"} {"commit": "fe7156e4ea6d26894f1270563c8bf290364e1bed", "message": "first round of tests...", "old_file": "underscore.js", "new_file": "underscore.js", "status": "M", "old_contents": " } else if (obj._each) {\n obj._each(function(value) {\n iterator.call(context, value, index++);\n });\n } else {\n var i = 0;\n for (var key in obj) {\n var value = obj[key], pair = [key, value];\n pair.key = key;\n pair.value = value;\n iterator.call(context, pair, i++);\n }\n }\n } catch(e) {\n if (e != '__break__') throw e;\n }\n return obj;\n },\n \n // Determine whether all of the elements match a truth test. Delegate to\n // Javascript 1.6's every(), if it is present.\n all : function(obj, iterator, context) {\n if (obj.every) return obj.every(iterator, context);\n var result = true;\n _.each(obj, function(value, index) {\n result = result && !!iterator.call(context, value, index);\n if (!result) throw '__break__';\n });\n return result;\n },\n \n // Determine if at least one element in the object matches a truth test. Use\n // Javascript 1.6's some(), if it exists.\n any : function(obj, iterator, context) {\n if (obj.some) return obj.some(iterator, context);\n var result = false;\n _.each(obj, function(value, index) {\n if (result = !!iterator.call(context, value, index)) throw '__break__';\n });\n return result;\n },\n \n // Return the results of applying the iterator to each element. Use Javascript\n // 1.6's version of map, if possible.\n map : function(obj, iterator, context) {\n if (obj.map) return obj.map(iterator, context);\n var results = [];\n _.each(obj, function(value, index) {\n results.push(iterator.call(context, value, index));\n });\n return results;\n },\n \n // Return the first value which passes a truth test.\n detect : function(obj, iterator, context) {\n var result;\n _.each(obj, function(value, index) {\n if (iterator.call(context, value, index)) {", "new_contents": " } else if (obj._each) {\n obj._each(function(value) {\n iterator.call(context, value, index++);\n });\n } else {\n var i = 0;\n for (var key in obj) {\n var value = obj[key], pair = [key, value];\n pair.key = key;\n pair.value = value;\n iterator.call(context, pair, i++);\n }\n }\n } catch(e) {\n if (e != '__break__') throw e;\n }\n return obj;\n },\n \n // Determine whether all of the elements match a truth test. Delegate to\n // Javascript 1.6's every(), if it is present.\n all : function(obj, iterator, context) {\n iterator = iterator || function(v){ return v; };\n if (obj.every) return obj.every(iterator, context);\n var result = true;\n _.each(obj, function(value, index) {\n result = result && !!iterator.call(context, value, index);\n if (!result) throw '__break__';\n });\n return result;\n },\n \n // Determine if at least one element in the object matches a truth test. Use\n // Javascript 1.6's some(), if it exists.\n any : function(obj, iterator, context) {\n iterator = iterator || function(v) { return v; };\n if (obj.some) return obj.some(iterator, context);\n var result = false;\n _.each(obj, function(value, index) {\n if (result = !!iterator.call(context, value, index)) throw '__break__';\n });\n return result;\n },\n \n // Return the results of applying the iterator to each element. Use Javascript\n // 1.6's version of map, if possible.\n map : function(obj, iterator, context) {\n if (obj.map) return obj.map(iterator, context);\n var results = [];\n _.each(obj, function(value, index) {\n results.push(iterator.call(context, value, index));\n });\n return results;\n },\n \n // Return the first value which passes a truth test.\n detect : function(obj, iterator, context) {\n var result;\n _.each(obj, function(value, index) {\n if (iterator.call(context, value, index)) {", "text": "<|original_code|>\n } else if (obj._each) {\n obj._each(function(value) {\n iterator.call(context, value, index++);\n });\n } else {\n var i = 0;\n for (var key in obj) {\n var value = obj[key], pair = [key, value];\n pair.key = key;\n pair.value = value;\n iterator.call(context, pair, i++);\n }\n }\n } catch(e) {\n if (e != '__break__') throw e;\n }\n return obj;\n },\n \n // Determine whether all of the elements match a truth test. Delegate to\n // Javascript 1.6's every(), if it is present.\n all : function(obj, iterator, context) {\n if (obj.every) return obj.every(iterator, context);\n var result = true;\n _.each(obj, function(value, index) {\n result = result && !!iterator.call(context, value, index);\n if (!result) throw '__break__';\n });\n return result;\n },\n \n // Determine if at least one element in the object matches a truth test. Use\n // Javascript 1.6's some(), if it exists.\n any : function(obj, iterator, context) {\n if (obj.some) return obj.some(iterator, context);\n var result = false;\n _.each(obj, function(value, index) {\n if (result = !!iterator.call(context, value, index)) throw '__break__';\n });\n return result;\n },\n \n // Return the results of applying the iterator to each element. Use Javascript\n // 1.6's version of map, if possible.\n map : function(obj, iterator, context) {\n if (obj.map) return obj.map(iterator, context);\n var results = [];\n _.each(obj, function(value, index) {\n results.push(iterator.call(context, value, index));\n });\n return results;\n },\n \n // Return the first value which passes a truth test.\n detect : function(obj, iterator, context) {\n var result;\n _.each(obj, function(value, index) {\n if (iterator.call(context, value, index)) {\n<|edits_diff|>\n--- underscore.js\n+++ underscore.js\n@@ -20,6 +20,7 @@\n // Determine whether all of the elements match a truth test. Delegate to\n // Javascript 1.6's every(), if it is present.\n all : function(obj, iterator, context) {\n+ iterator = iterator || function(v){ return v; };\n if (obj.every) return obj.every(iterator, context);\n var result = true;\n _.each(obj, function(value, index) {\n<|current_version|>\n } else if (obj._each) {\n obj._each(function(value) {\n iterator.call(context, value, index++);\n });\n } else {\n var i = 0;\n for (var key in obj) {\n var value = obj[key], pair = [key, value];\n pair.key = key;\n pair.value = value;\n iterator.call(context, pair, i++);\n }\n }\n } catch(e) {\n if (e != '__break__') throw e;\n }\n return obj;\n },\n \n // Determine whether all of the elements match a truth test. Delegate to\n // Javascript 1.6's every(), if it is present.\n all : function(obj, iterator, context) {\n iterator = iterator || function(v){ return v; };\n if (obj.every) return obj.every(iterator, context);\n var result = true;\n _.each(obj, function(value, index) {\n result = result && !!iterator.call(context, value, index);\n if (!result) throw '__break__';\n });\n return result;\n },\n \n // Determine if at least one element in the object matches a truth test. Use\n // Javascript 1.6's some(), if it exists.\n any : function(obj, iterator, context) {\n if (obj.some) return obj.some(iterator, context);\n var result = false;\n _.each(obj, function(value, index) {\n if (result = !!iterator.call(context, value, index)) throw '__break__';\n });\n return result;\n },\n \n // Return the results of applying the iterator to each element. Use Javascript\n // 1.6's version of map, if possible.\n map : function(obj, iterator, context) {\n if (obj.map) return obj.map(iterator, context);\n var results = [];\n _.each(obj, function(value, index) {\n results.push(iterator.call(context, value, index));\n });\n return results;\n },\n \n // Return the first value which passes a truth test.\n detect : function(obj, iterator, context) {\n var result;\n _.each(obj, function(value, index) {\n if (iterator.call(context, value, index)) {\n<|next_version|>\n } else if (obj._each) {\n obj._each(function(value) {\n iterator.call(context, value, index++);\n });\n } else {\n var i = 0;\n for (var key in obj) {\n var value = obj[key], pair = [key, value];\n pair.key = key;\n pair.value = value;\n iterator.call(context, pair, i++);\n }\n }\n } catch(e) {\n if (e != '__break__') throw e;\n }\n return obj;\n },\n \n // Determine whether all of the elements match a truth test. Delegate to\n // Javascript 1.6's every(), if it is present.\n all : function(obj, iterator, context) {\n iterator = iterator || function(v){ return v; };\n if (obj.every) return obj.every(iterator, context);\n var result = true;\n _.each(obj, function(value, index) {\n result = result && !!iterator.call(context, value, index);\n if (!result) throw '__break__';\n });\n return result;\n },\n \n // Determine if at least one element in the object matches a truth test. Use\n // Javascript 1.6's some(), if it exists.\n any : function(obj, iterator, context) {\n iterator = iterator || function(v) { return v; };\n if (obj.some) return obj.some(iterator, context);\n var result = false;\n _.each(obj, function(value, index) {\n if (result = !!iterator.call(context, value, index)) throw '__break__';\n });\n return result;\n },\n \n // Return the results of applying the iterator to each element. Use Javascript\n // 1.6's version of map, if possible.\n map : function(obj, iterator, context) {\n if (obj.map) return obj.map(iterator, context);\n var results = [];\n _.each(obj, function(value, index) {\n results.push(iterator.call(context, value, index));\n });\n return results;\n },\n \n // Return the first value which passes a truth test.\n detect : function(obj, iterator, context) {\n var result;\n _.each(obj, function(value, index) {\n if (iterator.call(context, value, index)) {\n", "current_contents": " } else if (obj._each) {\n obj._each(function(value) {\n iterator.call(context, value, index++);\n });\n } else {\n var i = 0;\n for (var key in obj) {\n var value = obj[key], pair = [key, value];\n pair.key = key;\n pair.value = value;\n iterator.call(context, pair, i++);\n }\n }\n } catch(e) {\n if (e != '__break__') throw e;\n }\n return obj;\n },\n \n // Determine whether all of the elements match a truth test. Delegate to\n // Javascript 1.6's every(), if it is present.\n all : function(obj, iterator, context) {\n iterator = iterator || function(v){ return v; };\n if (obj.every) return obj.every(iterator, context);\n var result = true;\n _.each(obj, function(value, index) {\n result = result && !!iterator.call(context, value, index);\n if (!result) throw '__break__';\n });\n return result;\n },\n \n // Determine if at least one element in the object matches a truth test. Use\n // Javascript 1.6's some(), if it exists.\n any : function(obj, iterator, context) {\n if (obj.some) return obj.some(iterator, context);\n var result = false;\n _.each(obj, function(value, index) {\n if (result = !!iterator.call(context, value, index)) throw '__break__';\n });\n return result;\n },\n \n // Return the results of applying the iterator to each element. Use Javascript\n // 1.6's version of map, if possible.\n map : function(obj, iterator, context) {\n if (obj.map) return obj.map(iterator, context);\n var results = [];\n _.each(obj, function(value, index) {\n results.push(iterator.call(context, value, index));\n });\n return results;\n },\n \n // Return the first value which passes a truth test.\n detect : function(obj, iterator, context) {\n var result;\n _.each(obj, function(value, index) {\n if (iterator.call(context, value, index)) {"} {"commit": "8fb2f70414b91175464676ed0158b14a8f2d4ade", "message": "fix: scrollbar rendering and improve dragging (#9417)", "old_file": "packages/excalidraw/scene/types.ts", "new_file": "packages/excalidraw/scene/types.ts", "status": "M", "old_contents": " appState: AppState;\n renderConfig: StaticCanvasRenderConfig;\n};\n\nexport type SceneScroll = {\n scrollX: number;\n scrollY: number;\n};\n\nexport type ExportType =\n | \"png\"\n | \"clipboard\"\n | \"clipboard-svg\"\n | \"backend\"\n | \"svg\";\n\nexport type ScrollBars = {\n horizontal: {\n x: number;\n y: number;\n width: number;\n height: number;\n } | null;\n vertical: {\n x: number;\n y: number;\n width: number;\n height: number;\n } | null;\n};\n\nexport type ElementShape = Drawable | Drawable[] | null;\n\nexport type ElementShapes = {\n rectangle: Drawable;\n ellipse: Drawable;\n diamond: Drawable;\n iframe: Drawable;\n embeddable: Drawable;\n freedraw: Drawable | null;\n arrow: Drawable[];\n line: Drawable[];\n text: null;\n image: null;\n frame: null;\n magicframe: null;\n};\n", "new_contents": " appState: AppState;\n renderConfig: StaticCanvasRenderConfig;\n};\n\nexport type SceneScroll = {\n scrollX: number;\n scrollY: number;\n};\n\nexport type ExportType =\n | \"png\"\n | \"clipboard\"\n | \"clipboard-svg\"\n | \"backend\"\n | \"svg\";\n\nexport type ScrollBars = {\n horizontal: {\n x: number;\n y: number;\n width: number;\n height: number;\n deltaMultiplier: number;\n } | null;\n vertical: {\n x: number;\n y: number;\n width: number;\n height: number;\n deltaMultiplier: number;\n } | null;\n};\n\nexport type ElementShape = Drawable | Drawable[] | null;\n\nexport type ElementShapes = {\n rectangle: Drawable;\n ellipse: Drawable;\n diamond: Drawable;\n iframe: Drawable;\n embeddable: Drawable;\n freedraw: Drawable | null;\n arrow: Drawable[];\n line: Drawable[];\n text: null;\n image: null;\n frame: null;\n magicframe: null;\n};\n", "text": "<|original_code|>\n appState: AppState;\n renderConfig: StaticCanvasRenderConfig;\n};\n\nexport type SceneScroll = {\n scrollX: number;\n scrollY: number;\n};\n\nexport type ExportType =\n | \"png\"\n | \"clipboard\"\n | \"clipboard-svg\"\n | \"backend\"\n | \"svg\";\n\nexport type ScrollBars = {\n horizontal: {\n x: number;\n y: number;\n width: number;\n height: number;\n } | null;\n vertical: {\n x: number;\n y: number;\n width: number;\n height: number;\n } | null;\n};\n\nexport type ElementShape = Drawable | Drawable[] | null;\n\nexport type ElementShapes = {\n rectangle: Drawable;\n ellipse: Drawable;\n diamond: Drawable;\n iframe: Drawable;\n embeddable: Drawable;\n freedraw: Drawable | null;\n arrow: Drawable[];\n line: Drawable[];\n text: null;\n image: null;\n frame: null;\n magicframe: null;\n};\n\n<|edits_diff|>\n--- packages/excalidraw/scene/types.ts\n+++ packages/excalidraw/scene/types.ts\n@@ -20,6 +20,7 @@\n y: number;\n width: number;\n height: number;\n+ deltaMultiplier: number;\n } | null;\n vertical: {\n x: number;\n<|current_version|>\n appState: AppState;\n renderConfig: StaticCanvasRenderConfig;\n};\n\nexport type SceneScroll = {\n scrollX: number;\n scrollY: number;\n};\n\nexport type ExportType =\n | \"png\"\n | \"clipboard\"\n | \"clipboard-svg\"\n | \"backend\"\n | \"svg\";\n\nexport type ScrollBars = {\n horizontal: {\n x: number;\n y: number;\n width: number;\n height: number;\n deltaMultiplier: number;\n } | null;\n vertical: {\n x: number;\n y: number;\n width: number;\n height: number;\n } | null;\n};\n\nexport type ElementShape = Drawable | Drawable[] | null;\n\nexport type ElementShapes = {\n rectangle: Drawable;\n ellipse: Drawable;\n diamond: Drawable;\n iframe: Drawable;\n embeddable: Drawable;\n freedraw: Drawable | null;\n arrow: Drawable[];\n line: Drawable[];\n text: null;\n image: null;\n frame: null;\n magicframe: null;\n};\n\n<|next_version|>\n appState: AppState;\n renderConfig: StaticCanvasRenderConfig;\n};\n\nexport type SceneScroll = {\n scrollX: number;\n scrollY: number;\n};\n\nexport type ExportType =\n | \"png\"\n | \"clipboard\"\n | \"clipboard-svg\"\n | \"backend\"\n | \"svg\";\n\nexport type ScrollBars = {\n horizontal: {\n x: number;\n y: number;\n width: number;\n height: number;\n deltaMultiplier: number;\n } | null;\n vertical: {\n x: number;\n y: number;\n width: number;\n height: number;\n deltaMultiplier: number;\n } | null;\n};\n\nexport type ElementShape = Drawable | Drawable[] | null;\n\nexport type ElementShapes = {\n rectangle: Drawable;\n ellipse: Drawable;\n diamond: Drawable;\n iframe: Drawable;\n embeddable: Drawable;\n freedraw: Drawable | null;\n arrow: Drawable[];\n line: Drawable[];\n text: null;\n image: null;\n frame: null;\n magicframe: null;\n};\n\n", "current_contents": " appState: AppState;\n renderConfig: StaticCanvasRenderConfig;\n};\n\nexport type SceneScroll = {\n scrollX: number;\n scrollY: number;\n};\n\nexport type ExportType =\n | \"png\"\n | \"clipboard\"\n | \"clipboard-svg\"\n | \"backend\"\n | \"svg\";\n\nexport type ScrollBars = {\n horizontal: {\n x: number;\n y: number;\n width: number;\n height: number;\n deltaMultiplier: number;\n } | null;\n vertical: {\n x: number;\n y: number;\n width: number;\n height: number;\n } | null;\n};\n\nexport type ElementShape = Drawable | Drawable[] | null;\n\nexport type ElementShapes = {\n rectangle: Drawable;\n ellipse: Drawable;\n diamond: Drawable;\n iframe: Drawable;\n embeddable: Drawable;\n freedraw: Drawable | null;\n arrow: Drawable[];\n line: Drawable[];\n text: null;\n image: null;\n frame: null;\n magicframe: null;\n};\n"} {"commit": "f9815b8b4f612ec1ed4cf2484a61e4ac0befc187", "message": "fix: image cropping svg + compat mode (#8710)", "old_file": "packages/utils/export.ts", "new_file": "packages/utils/export.ts", "status": "M", "old_contents": " opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n", "new_contents": " opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n reuseImages,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n reuseImages?: boolean;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n reuseImages,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n", "text": "<|original_code|>\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n<|edits_diff|>\n--- packages/utils/export.ts\n+++ packages/utils/export.ts\n@@ -20,10 +20,12 @@\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n+ reuseImages,\n }: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n+ reuseImages?: boolean;\n }): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n<|current_version|>\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n reuseImages,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n reuseImages?: boolean;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n<|next_version|>\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n reuseImages,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n reuseImages?: boolean;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n reuseImages,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n", "current_contents": " opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n reuseImages,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n reuseImages?: boolean;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n"} {"commit": "e957c8e9ee5264698eb946317780e80e6a2388df", "message": "feat: image cropping (#8613)", "old_file": "packages/excalidraw/element/newElement.ts", "new_file": "packages/excalidraw/element/newElement.ts", "status": "M", "old_contents": " points?: ExcalidrawArrowElement[\"points\"];\n elbowed?: boolean;\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(opts.type, opts),\n points: opts.points || [],\n lastCommittedPoint: null,\n startBinding: null,\n endBinding: null,\n startArrowhead: opts.startArrowhead || null,\n endArrowhead: opts.endArrowhead || null,\n elbowed: opts.elbowed || false,\n };\n};\n\nexport const newImageElement = (\n opts: {\n type: ExcalidrawImageElement[\"type\"];\n status?: ExcalidrawImageElement[\"status\"];\n fileId?: ExcalidrawImageElement[\"fileId\"];\n scale?: ExcalidrawImageElement[\"scale\"];\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(\"image\", opts),\n // in the future we'll support changing stroke color for some SVG elements,\n // and `transparent` will likely mean \"use original colors of the image\"\n strokeColor: \"transparent\",\n status: opts.status ?? \"pending\",\n fileId: opts.fileId ?? null,\n scale: opts.scale ?? [1, 1],\n };\n};\n\n// Simplified deep clone for the purpose of cloning ExcalidrawElement.\n//\n// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,\n// Typed arrays and other non-null objects.\n//\n// Adapted from https://github.com/lukeed/klona\n//\n// The reason for `deepCopyElement()` wrapper is type safety (only allow\n// passing ExcalidrawElement as the top-level argument).\nconst _deepCopyElement = (val: any, depth: number = 0) => {\n // only clone non-primitives\n if (val == null || typeof val !== \"object\") {\n return val;\n }\n\n const objectType = Object.prototype.toString.call(val);\n\n if (objectType === \"[object Object]\") {\n const tmp =\n typeof val.constructor === \"function\"\n ? Object.create(Object.getPrototypeOf(val))", "new_contents": " points?: ExcalidrawArrowElement[\"points\"];\n elbowed?: boolean;\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(opts.type, opts),\n points: opts.points || [],\n lastCommittedPoint: null,\n startBinding: null,\n endBinding: null,\n startArrowhead: opts.startArrowhead || null,\n endArrowhead: opts.endArrowhead || null,\n elbowed: opts.elbowed || false,\n };\n};\n\nexport const newImageElement = (\n opts: {\n type: ExcalidrawImageElement[\"type\"];\n status?: ExcalidrawImageElement[\"status\"];\n fileId?: ExcalidrawImageElement[\"fileId\"];\n scale?: ExcalidrawImageElement[\"scale\"];\n crop?: ExcalidrawImageElement[\"crop\"];\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(\"image\", opts),\n // in the future we'll support changing stroke color for some SVG elements,\n // and `transparent` will likely mean \"use original colors of the image\"\n strokeColor: \"transparent\",\n status: opts.status ?? \"pending\",\n fileId: opts.fileId ?? null,\n scale: opts.scale ?? [1, 1],\n crop: opts.crop ?? null,\n };\n};\n\n// Simplified deep clone for the purpose of cloning ExcalidrawElement.\n//\n// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,\n// Typed arrays and other non-null objects.\n//\n// Adapted from https://github.com/lukeed/klona\n//\n// The reason for `deepCopyElement()` wrapper is type safety (only allow\n// passing ExcalidrawElement as the top-level argument).\nconst _deepCopyElement = (val: any, depth: number = 0) => {\n // only clone non-primitives\n if (val == null || typeof val !== \"object\") {\n return val;\n }\n\n const objectType = Object.prototype.toString.call(val);\n\n if (objectType === \"[object Object]\") {\n const tmp =\n typeof val.constructor === \"function\"\n ? Object.create(Object.getPrototypeOf(val))", "text": "<|original_code|>\n points?: ExcalidrawArrowElement[\"points\"];\n elbowed?: boolean;\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(opts.type, opts),\n points: opts.points || [],\n lastCommittedPoint: null,\n startBinding: null,\n endBinding: null,\n startArrowhead: opts.startArrowhead || null,\n endArrowhead: opts.endArrowhead || null,\n elbowed: opts.elbowed || false,\n };\n};\n\nexport const newImageElement = (\n opts: {\n type: ExcalidrawImageElement[\"type\"];\n status?: ExcalidrawImageElement[\"status\"];\n fileId?: ExcalidrawImageElement[\"fileId\"];\n scale?: ExcalidrawImageElement[\"scale\"];\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(\"image\", opts),\n // in the future we'll support changing stroke color for some SVG elements,\n // and `transparent` will likely mean \"use original colors of the image\"\n strokeColor: \"transparent\",\n status: opts.status ?? \"pending\",\n fileId: opts.fileId ?? null,\n scale: opts.scale ?? [1, 1],\n };\n};\n\n// Simplified deep clone for the purpose of cloning ExcalidrawElement.\n//\n// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,\n// Typed arrays and other non-null objects.\n//\n// Adapted from https://github.com/lukeed/klona\n//\n// The reason for `deepCopyElement()` wrapper is type safety (only allow\n// passing ExcalidrawElement as the top-level argument).\nconst _deepCopyElement = (val: any, depth: number = 0) => {\n // only clone non-primitives\n if (val == null || typeof val !== \"object\") {\n return val;\n }\n\n const objectType = Object.prototype.toString.call(val);\n\n if (objectType === \"[object Object]\") {\n const tmp =\n typeof val.constructor === \"function\"\n ? Object.create(Object.getPrototypeOf(val))\n<|edits_diff|>\n--- packages/excalidraw/element/newElement.ts\n+++ packages/excalidraw/element/newElement.ts\n@@ -20,6 +20,7 @@\n status?: ExcalidrawImageElement[\"status\"];\n fileId?: ExcalidrawImageElement[\"fileId\"];\n scale?: ExcalidrawImageElement[\"scale\"];\n+ crop?: ExcalidrawImageElement[\"crop\"];\n } & ElementConstructorOpts,\n ): NonDeleted => {\n return {\n<|current_version|>\n points?: ExcalidrawArrowElement[\"points\"];\n elbowed?: boolean;\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(opts.type, opts),\n points: opts.points || [],\n lastCommittedPoint: null,\n startBinding: null,\n endBinding: null,\n startArrowhead: opts.startArrowhead || null,\n endArrowhead: opts.endArrowhead || null,\n elbowed: opts.elbowed || false,\n };\n};\n\nexport const newImageElement = (\n opts: {\n type: ExcalidrawImageElement[\"type\"];\n status?: ExcalidrawImageElement[\"status\"];\n fileId?: ExcalidrawImageElement[\"fileId\"];\n scale?: ExcalidrawImageElement[\"scale\"];\n crop?: ExcalidrawImageElement[\"crop\"];\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(\"image\", opts),\n // in the future we'll support changing stroke color for some SVG elements,\n // and `transparent` will likely mean \"use original colors of the image\"\n strokeColor: \"transparent\",\n status: opts.status ?? \"pending\",\n fileId: opts.fileId ?? null,\n scale: opts.scale ?? [1, 1],\n };\n};\n\n// Simplified deep clone for the purpose of cloning ExcalidrawElement.\n//\n// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,\n// Typed arrays and other non-null objects.\n//\n// Adapted from https://github.com/lukeed/klona\n//\n// The reason for `deepCopyElement()` wrapper is type safety (only allow\n// passing ExcalidrawElement as the top-level argument).\nconst _deepCopyElement = (val: any, depth: number = 0) => {\n // only clone non-primitives\n if (val == null || typeof val !== \"object\") {\n return val;\n }\n\n const objectType = Object.prototype.toString.call(val);\n\n if (objectType === \"[object Object]\") {\n const tmp =\n typeof val.constructor === \"function\"\n ? Object.create(Object.getPrototypeOf(val))\n<|next_version|>\n points?: ExcalidrawArrowElement[\"points\"];\n elbowed?: boolean;\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(opts.type, opts),\n points: opts.points || [],\n lastCommittedPoint: null,\n startBinding: null,\n endBinding: null,\n startArrowhead: opts.startArrowhead || null,\n endArrowhead: opts.endArrowhead || null,\n elbowed: opts.elbowed || false,\n };\n};\n\nexport const newImageElement = (\n opts: {\n type: ExcalidrawImageElement[\"type\"];\n status?: ExcalidrawImageElement[\"status\"];\n fileId?: ExcalidrawImageElement[\"fileId\"];\n scale?: ExcalidrawImageElement[\"scale\"];\n crop?: ExcalidrawImageElement[\"crop\"];\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(\"image\", opts),\n // in the future we'll support changing stroke color for some SVG elements,\n // and `transparent` will likely mean \"use original colors of the image\"\n strokeColor: \"transparent\",\n status: opts.status ?? \"pending\",\n fileId: opts.fileId ?? null,\n scale: opts.scale ?? [1, 1],\n crop: opts.crop ?? null,\n };\n};\n\n// Simplified deep clone for the purpose of cloning ExcalidrawElement.\n//\n// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,\n// Typed arrays and other non-null objects.\n//\n// Adapted from https://github.com/lukeed/klona\n//\n// The reason for `deepCopyElement()` wrapper is type safety (only allow\n// passing ExcalidrawElement as the top-level argument).\nconst _deepCopyElement = (val: any, depth: number = 0) => {\n // only clone non-primitives\n if (val == null || typeof val !== \"object\") {\n return val;\n }\n\n const objectType = Object.prototype.toString.call(val);\n\n if (objectType === \"[object Object]\") {\n const tmp =\n typeof val.constructor === \"function\"\n ? Object.create(Object.getPrototypeOf(val))\n", "current_contents": " points?: ExcalidrawArrowElement[\"points\"];\n elbowed?: boolean;\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(opts.type, opts),\n points: opts.points || [],\n lastCommittedPoint: null,\n startBinding: null,\n endBinding: null,\n startArrowhead: opts.startArrowhead || null,\n endArrowhead: opts.endArrowhead || null,\n elbowed: opts.elbowed || false,\n };\n};\n\nexport const newImageElement = (\n opts: {\n type: ExcalidrawImageElement[\"type\"];\n status?: ExcalidrawImageElement[\"status\"];\n fileId?: ExcalidrawImageElement[\"fileId\"];\n scale?: ExcalidrawImageElement[\"scale\"];\n crop?: ExcalidrawImageElement[\"crop\"];\n } & ElementConstructorOpts,\n): NonDeleted => {\n return {\n ..._newElementBase(\"image\", opts),\n // in the future we'll support changing stroke color for some SVG elements,\n // and `transparent` will likely mean \"use original colors of the image\"\n strokeColor: \"transparent\",\n status: opts.status ?? \"pending\",\n fileId: opts.fileId ?? null,\n scale: opts.scale ?? [1, 1],\n };\n};\n\n// Simplified deep clone for the purpose of cloning ExcalidrawElement.\n//\n// Only clones plain objects and arrays. Doesn't clone Date, RegExp, Map, Set,\n// Typed arrays and other non-null objects.\n//\n// Adapted from https://github.com/lukeed/klona\n//\n// The reason for `deepCopyElement()` wrapper is type safety (only allow\n// passing ExcalidrawElement as the top-level argument).\nconst _deepCopyElement = (val: any, depth: number = 0) => {\n // only clone non-primitives\n if (val == null || typeof val !== \"object\") {\n return val;\n }\n\n const objectType = Object.prototype.toString.call(val);\n\n if (objectType === \"[object Object]\") {\n const tmp =\n typeof val.constructor === \"function\"\n ? Object.create(Object.getPrototypeOf(val))"} {"commit": "84d89b9a8a59155f6d31880488bc4d25c5ebacd1", "message": "fix: throttle fractional indices validation (#8306)", "old_file": "packages/excalidraw/tests/fractionalIndex.test.ts", "new_file": "packages/excalidraw/tests/fractionalIndex.test.ts", "status": "M", "old_contents": " const movedMap = arrayToMap(movedElementsIds || []);\n const movedElements = movedElementsIds\n ? arrayToMap(elements.filter((x) => movedMap.has(x.id)))\n : undefined;\n\n return [elements, movedElements];\n}\n\nfunction test(\n name: string,\n elements: ExcalidrawElement[],\n movedElements: Map | undefined,\n expectUnchangedElements: Map,\n expectValidInput?: boolean,\n) {\n it(name, () => {\n // ensure the input is invalid (unless the flag is on)\n if (!expectValidInput) {\n expect(() =>\n validateFractionalIndices(elements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n }),\n ).toThrowError(InvalidFractionalIndexError);\n }\n\n // clone due to mutation\n const clonedElements = elements.map((x) => deepCopyElement(x));\n\n // act\n const syncedElements = movedElements\n ? syncMovedIndices(clonedElements, movedElements)\n : syncInvalidIndices(clonedElements);\n\n expect(syncedElements.length).toBe(elements.length);\n expect(() =>\n validateFractionalIndices(syncedElements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n }),\n ).not.toThrowError(InvalidFractionalIndexError);\n\n syncedElements.forEach((synced, index) => {\n const element = elements[index];\n // ensure the order hasn't changed\n expect(synced.id).toBe(element.id);\n\n if (expectUnchangedElements.has(synced.id)) {\n // ensure we didn't mutate where we didn't want to mutate\n expect(synced.index).toBe(elements[index].index);\n expect(synced.version).toBe(elements[index].version);\n } else {\n expect(synced.index).not.toBe(elements[index].index);\n // ensure we mutated just once, even with fallback triggered\n expect(synced.version).toBe(elements[index].version + 1);\n }\n });\n });\n}\n", "new_contents": " const movedMap = arrayToMap(movedElementsIds || []);\n const movedElements = movedElementsIds\n ? arrayToMap(elements.filter((x) => movedMap.has(x.id)))\n : undefined;\n\n return [elements, movedElements];\n}\n\nfunction test(\n name: string,\n elements: ExcalidrawElement[],\n movedElements: Map | undefined,\n expectUnchangedElements: Map,\n expectValidInput?: boolean,\n) {\n it(name, () => {\n // ensure the input is invalid (unless the flag is on)\n if (!expectValidInput) {\n expect(() =>\n validateFractionalIndices(elements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n ignoreLogs: true,\n }),\n ).toThrowError(InvalidFractionalIndexError);\n }\n\n // clone due to mutation\n const clonedElements = elements.map((x) => deepCopyElement(x));\n\n // act\n const syncedElements = movedElements\n ? syncMovedIndices(clonedElements, movedElements)\n : syncInvalidIndices(clonedElements);\n\n expect(syncedElements.length).toBe(elements.length);\n expect(() =>\n validateFractionalIndices(syncedElements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n ignoreLogs: true,\n }),\n ).not.toThrowError(InvalidFractionalIndexError);\n\n syncedElements.forEach((synced, index) => {\n const element = elements[index];\n // ensure the order hasn't changed\n expect(synced.id).toBe(element.id);\n\n if (expectUnchangedElements.has(synced.id)) {\n // ensure we didn't mutate where we didn't want to mutate\n expect(synced.index).toBe(elements[index].index);\n expect(synced.version).toBe(elements[index].version);\n } else {\n expect(synced.index).not.toBe(elements[index].index);\n // ensure we mutated just once, even with fallback triggered\n expect(synced.version).toBe(elements[index].version + 1);\n }\n });\n });\n}\n", "text": "<|original_code|>\n const movedMap = arrayToMap(movedElementsIds || []);\n const movedElements = movedElementsIds\n ? arrayToMap(elements.filter((x) => movedMap.has(x.id)))\n : undefined;\n\n return [elements, movedElements];\n}\n\nfunction test(\n name: string,\n elements: ExcalidrawElement[],\n movedElements: Map | undefined,\n expectUnchangedElements: Map,\n expectValidInput?: boolean,\n) {\n it(name, () => {\n // ensure the input is invalid (unless the flag is on)\n if (!expectValidInput) {\n expect(() =>\n validateFractionalIndices(elements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n }),\n ).toThrowError(InvalidFractionalIndexError);\n }\n\n // clone due to mutation\n const clonedElements = elements.map((x) => deepCopyElement(x));\n\n // act\n const syncedElements = movedElements\n ? syncMovedIndices(clonedElements, movedElements)\n : syncInvalidIndices(clonedElements);\n\n expect(syncedElements.length).toBe(elements.length);\n expect(() =>\n validateFractionalIndices(syncedElements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n }),\n ).not.toThrowError(InvalidFractionalIndexError);\n\n syncedElements.forEach((synced, index) => {\n const element = elements[index];\n // ensure the order hasn't changed\n expect(synced.id).toBe(element.id);\n\n if (expectUnchangedElements.has(synced.id)) {\n // ensure we didn't mutate where we didn't want to mutate\n expect(synced.index).toBe(elements[index].index);\n expect(synced.version).toBe(elements[index].version);\n } else {\n expect(synced.index).not.toBe(elements[index].index);\n // ensure we mutated just once, even with fallback triggered\n expect(synced.version).toBe(elements[index].version + 1);\n }\n });\n });\n}\n\n<|edits_diff|>\n--- packages/excalidraw/tests/fractionalIndex.test.ts\n+++ packages/excalidraw/tests/fractionalIndex.test.ts\n@@ -20,6 +20,7 @@\n validateFractionalIndices(elements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n+ ignoreLogs: true,\n }),\n ).toThrowError(InvalidFractionalIndexError);\n }\n<|current_version|>\n const movedMap = arrayToMap(movedElementsIds || []);\n const movedElements = movedElementsIds\n ? arrayToMap(elements.filter((x) => movedMap.has(x.id)))\n : undefined;\n\n return [elements, movedElements];\n}\n\nfunction test(\n name: string,\n elements: ExcalidrawElement[],\n movedElements: Map | undefined,\n expectUnchangedElements: Map,\n expectValidInput?: boolean,\n) {\n it(name, () => {\n // ensure the input is invalid (unless the flag is on)\n if (!expectValidInput) {\n expect(() =>\n validateFractionalIndices(elements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n ignoreLogs: true,\n }),\n ).toThrowError(InvalidFractionalIndexError);\n }\n\n // clone due to mutation\n const clonedElements = elements.map((x) => deepCopyElement(x));\n\n // act\n const syncedElements = movedElements\n ? syncMovedIndices(clonedElements, movedElements)\n : syncInvalidIndices(clonedElements);\n\n expect(syncedElements.length).toBe(elements.length);\n expect(() =>\n validateFractionalIndices(syncedElements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n }),\n ).not.toThrowError(InvalidFractionalIndexError);\n\n syncedElements.forEach((synced, index) => {\n const element = elements[index];\n // ensure the order hasn't changed\n expect(synced.id).toBe(element.id);\n\n if (expectUnchangedElements.has(synced.id)) {\n // ensure we didn't mutate where we didn't want to mutate\n expect(synced.index).toBe(elements[index].index);\n expect(synced.version).toBe(elements[index].version);\n } else {\n expect(synced.index).not.toBe(elements[index].index);\n // ensure we mutated just once, even with fallback triggered\n expect(synced.version).toBe(elements[index].version + 1);\n }\n });\n });\n}\n\n<|next_version|>\n const movedMap = arrayToMap(movedElementsIds || []);\n const movedElements = movedElementsIds\n ? arrayToMap(elements.filter((x) => movedMap.has(x.id)))\n : undefined;\n\n return [elements, movedElements];\n}\n\nfunction test(\n name: string,\n elements: ExcalidrawElement[],\n movedElements: Map | undefined,\n expectUnchangedElements: Map,\n expectValidInput?: boolean,\n) {\n it(name, () => {\n // ensure the input is invalid (unless the flag is on)\n if (!expectValidInput) {\n expect(() =>\n validateFractionalIndices(elements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n ignoreLogs: true,\n }),\n ).toThrowError(InvalidFractionalIndexError);\n }\n\n // clone due to mutation\n const clonedElements = elements.map((x) => deepCopyElement(x));\n\n // act\n const syncedElements = movedElements\n ? syncMovedIndices(clonedElements, movedElements)\n : syncInvalidIndices(clonedElements);\n\n expect(syncedElements.length).toBe(elements.length);\n expect(() =>\n validateFractionalIndices(syncedElements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n ignoreLogs: true,\n }),\n ).not.toThrowError(InvalidFractionalIndexError);\n\n syncedElements.forEach((synced, index) => {\n const element = elements[index];\n // ensure the order hasn't changed\n expect(synced.id).toBe(element.id);\n\n if (expectUnchangedElements.has(synced.id)) {\n // ensure we didn't mutate where we didn't want to mutate\n expect(synced.index).toBe(elements[index].index);\n expect(synced.version).toBe(elements[index].version);\n } else {\n expect(synced.index).not.toBe(elements[index].index);\n // ensure we mutated just once, even with fallback triggered\n expect(synced.version).toBe(elements[index].version + 1);\n }\n });\n });\n}\n\n", "current_contents": " const movedMap = arrayToMap(movedElementsIds || []);\n const movedElements = movedElementsIds\n ? arrayToMap(elements.filter((x) => movedMap.has(x.id)))\n : undefined;\n\n return [elements, movedElements];\n}\n\nfunction test(\n name: string,\n elements: ExcalidrawElement[],\n movedElements: Map | undefined,\n expectUnchangedElements: Map,\n expectValidInput?: boolean,\n) {\n it(name, () => {\n // ensure the input is invalid (unless the flag is on)\n if (!expectValidInput) {\n expect(() =>\n validateFractionalIndices(elements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n ignoreLogs: true,\n }),\n ).toThrowError(InvalidFractionalIndexError);\n }\n\n // clone due to mutation\n const clonedElements = elements.map((x) => deepCopyElement(x));\n\n // act\n const syncedElements = movedElements\n ? syncMovedIndices(clonedElements, movedElements)\n : syncInvalidIndices(clonedElements);\n\n expect(syncedElements.length).toBe(elements.length);\n expect(() =>\n validateFractionalIndices(syncedElements, {\n shouldThrow: true,\n includeBoundTextValidation: true,\n }),\n ).not.toThrowError(InvalidFractionalIndexError);\n\n syncedElements.forEach((synced, index) => {\n const element = elements[index];\n // ensure the order hasn't changed\n expect(synced.id).toBe(element.id);\n\n if (expectUnchangedElements.has(synced.id)) {\n // ensure we didn't mutate where we didn't want to mutate\n expect(synced.index).toBe(elements[index].index);\n expect(synced.version).toBe(elements[index].version);\n } else {\n expect(synced.index).not.toBe(elements[index].index);\n // ensure we mutated just once, even with fallback triggered\n expect(synced.version).toBe(elements[index].version + 1);\n }\n });\n });\n}\n"} {"commit": "62228e0bbb780d1070a8cf206caa32132d22f19e", "message": "feat: introduce font picker (#8012)", "old_file": "packages/utils/export.ts", "new_file": "packages/utils/export.ts", "status": "M", "old_contents": " opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n", "new_contents": " opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n", "text": "<|original_code|>\n opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n<|edits_diff|>\n--- packages/utils/export.ts\n+++ packages/utils/export.ts\n@@ -20,9 +20,11 @@\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n+ skipInliningFonts,\n }: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n+ skipInliningFonts?: true;\n }): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n<|current_version|>\n opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n<|next_version|>\n opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n", "current_contents": " opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n"} {"commit": "14845a343bdc59b1304d02d90457a372b0b909ca", "message": "feat: text-to-diagram (#7325)", "old_file": "src/context/tunnels.ts", "new_file": "src/context/tunnels.ts", "status": "M", "old_contents": "import React from \"react\";\nimport tunnel from \"tunnel-rat\";\n\nexport type Tunnel = ReturnType;\n\ntype TunnelsContextValue = {\n MainMenuTunnel: Tunnel;\n WelcomeScreenMenuHintTunnel: Tunnel;\n WelcomeScreenToolbarHintTunnel: Tunnel;\n WelcomeScreenHelpHintTunnel: Tunnel;\n WelcomeScreenCenterTunnel: Tunnel;\n FooterCenterTunnel: Tunnel;\n DefaultSidebarTriggerTunnel: Tunnel;\n DefaultSidebarTabTriggersTunnel: Tunnel;\n OverwriteConfirmDialogTunnel: Tunnel;\n jotaiScope: symbol;\n};\n\nexport const TunnelsContext = React.createContext(null!);\n\nexport const useTunnels = () => React.useContext(TunnelsContext);\n\nexport const useInitializeTunnels = () => {\n return React.useMemo((): TunnelsContextValue => {\n return {\n MainMenuTunnel: tunnel(),\n WelcomeScreenMenuHintTunnel: tunnel(),\n WelcomeScreenToolbarHintTunnel: tunnel(),\n WelcomeScreenHelpHintTunnel: tunnel(),\n WelcomeScreenCenterTunnel: tunnel(),\n FooterCenterTunnel: tunnel(),\n DefaultSidebarTriggerTunnel: tunnel(),\n DefaultSidebarTabTriggersTunnel: tunnel(),\n OverwriteConfirmDialogTunnel: tunnel(),\n jotaiScope: Symbol(),\n };\n }, []);\n};\n", "new_contents": "import React from \"react\";\nimport tunnel from \"tunnel-rat\";\n\nexport type Tunnel = ReturnType;\n\ntype TunnelsContextValue = {\n MainMenuTunnel: Tunnel;\n WelcomeScreenMenuHintTunnel: Tunnel;\n WelcomeScreenToolbarHintTunnel: Tunnel;\n WelcomeScreenHelpHintTunnel: Tunnel;\n WelcomeScreenCenterTunnel: Tunnel;\n FooterCenterTunnel: Tunnel;\n DefaultSidebarTriggerTunnel: Tunnel;\n DefaultSidebarTabTriggersTunnel: Tunnel;\n OverwriteConfirmDialogTunnel: Tunnel;\n TTDDialogTriggerTunnel: Tunnel;\n jotaiScope: symbol;\n};\n\nexport const TunnelsContext = React.createContext(null!);\n\nexport const useTunnels = () => React.useContext(TunnelsContext);\n\nexport const useInitializeTunnels = () => {\n return React.useMemo((): TunnelsContextValue => {\n return {\n MainMenuTunnel: tunnel(),\n WelcomeScreenMenuHintTunnel: tunnel(),\n WelcomeScreenToolbarHintTunnel: tunnel(),\n WelcomeScreenHelpHintTunnel: tunnel(),\n WelcomeScreenCenterTunnel: tunnel(),\n FooterCenterTunnel: tunnel(),\n DefaultSidebarTriggerTunnel: tunnel(),\n DefaultSidebarTabTriggersTunnel: tunnel(),\n OverwriteConfirmDialogTunnel: tunnel(),\n TTDDialogTriggerTunnel: tunnel(),\n jotaiScope: Symbol(),\n };\n }, []);\n};\n", "text": "<|original_code|>\nimport React from \"react\";\nimport tunnel from \"tunnel-rat\";\n\nexport type Tunnel = ReturnType;\n\ntype TunnelsContextValue = {\n MainMenuTunnel: Tunnel;\n WelcomeScreenMenuHintTunnel: Tunnel;\n WelcomeScreenToolbarHintTunnel: Tunnel;\n WelcomeScreenHelpHintTunnel: Tunnel;\n WelcomeScreenCenterTunnel: Tunnel;\n FooterCenterTunnel: Tunnel;\n DefaultSidebarTriggerTunnel: Tunnel;\n DefaultSidebarTabTriggersTunnel: Tunnel;\n OverwriteConfirmDialogTunnel: Tunnel;\n jotaiScope: symbol;\n};\n\nexport const TunnelsContext = React.createContext(null!);\n\nexport const useTunnels = () => React.useContext(TunnelsContext);\n\nexport const useInitializeTunnels = () => {\n return React.useMemo((): TunnelsContextValue => {\n return {\n MainMenuTunnel: tunnel(),\n WelcomeScreenMenuHintTunnel: tunnel(),\n WelcomeScreenToolbarHintTunnel: tunnel(),\n WelcomeScreenHelpHintTunnel: tunnel(),\n WelcomeScreenCenterTunnel: tunnel(),\n FooterCenterTunnel: tunnel(),\n DefaultSidebarTriggerTunnel: tunnel(),\n DefaultSidebarTabTriggersTunnel: tunnel(),\n OverwriteConfirmDialogTunnel: tunnel(),\n jotaiScope: Symbol(),\n };\n }, []);\n};\n\n<|edits_diff|>\n--- src/context/tunnels.ts\n+++ src/context/tunnels.ts\n@@ -13,6 +13,7 @@\n DefaultSidebarTriggerTunnel: Tunnel;\n DefaultSidebarTabTriggersTunnel: Tunnel;\n OverwriteConfirmDialogTunnel: Tunnel;\n+ TTDDialogTriggerTunnel: Tunnel;\n jotaiScope: symbol;\n };\n \n<|current_version|>\nimport React from \"react\";\nimport tunnel from \"tunnel-rat\";\n\nexport type Tunnel = ReturnType;\n\ntype TunnelsContextValue = {\n MainMenuTunnel: Tunnel;\n WelcomeScreenMenuHintTunnel: Tunnel;\n WelcomeScreenToolbarHintTunnel: Tunnel;\n WelcomeScreenHelpHintTunnel: Tunnel;\n WelcomeScreenCenterTunnel: Tunnel;\n FooterCenterTunnel: Tunnel;\n DefaultSidebarTriggerTunnel: Tunnel;\n DefaultSidebarTabTriggersTunnel: Tunnel;\n OverwriteConfirmDialogTunnel: Tunnel;\n TTDDialogTriggerTunnel: Tunnel;\n jotaiScope: symbol;\n};\n\nexport const TunnelsContext = React.createContext(null!);\n\nexport const useTunnels = () => React.useContext(TunnelsContext);\n\nexport const useInitializeTunnels = () => {\n return React.useMemo((): TunnelsContextValue => {\n return {\n MainMenuTunnel: tunnel(),\n WelcomeScreenMenuHintTunnel: tunnel(),\n WelcomeScreenToolbarHintTunnel: tunnel(),\n WelcomeScreenHelpHintTunnel: tunnel(),\n WelcomeScreenCenterTunnel: tunnel(),\n FooterCenterTunnel: tunnel(),\n DefaultSidebarTriggerTunnel: tunnel(),\n DefaultSidebarTabTriggersTunnel: tunnel(),\n OverwriteConfirmDialogTunnel: tunnel(),\n jotaiScope: Symbol(),\n };\n }, []);\n};\n\n<|next_version|>\nimport React from \"react\";\nimport tunnel from \"tunnel-rat\";\n\nexport type Tunnel = ReturnType;\n\ntype TunnelsContextValue = {\n MainMenuTunnel: Tunnel;\n WelcomeScreenMenuHintTunnel: Tunnel;\n WelcomeScreenToolbarHintTunnel: Tunnel;\n WelcomeScreenHelpHintTunnel: Tunnel;\n WelcomeScreenCenterTunnel: Tunnel;\n FooterCenterTunnel: Tunnel;\n DefaultSidebarTriggerTunnel: Tunnel;\n DefaultSidebarTabTriggersTunnel: Tunnel;\n OverwriteConfirmDialogTunnel: Tunnel;\n TTDDialogTriggerTunnel: Tunnel;\n jotaiScope: symbol;\n};\n\nexport const TunnelsContext = React.createContext(null!);\n\nexport const useTunnels = () => React.useContext(TunnelsContext);\n\nexport const useInitializeTunnels = () => {\n return React.useMemo((): TunnelsContextValue => {\n return {\n MainMenuTunnel: tunnel(),\n WelcomeScreenMenuHintTunnel: tunnel(),\n WelcomeScreenToolbarHintTunnel: tunnel(),\n WelcomeScreenHelpHintTunnel: tunnel(),\n WelcomeScreenCenterTunnel: tunnel(),\n FooterCenterTunnel: tunnel(),\n DefaultSidebarTriggerTunnel: tunnel(),\n DefaultSidebarTabTriggersTunnel: tunnel(),\n OverwriteConfirmDialogTunnel: tunnel(),\n TTDDialogTriggerTunnel: tunnel(),\n jotaiScope: Symbol(),\n };\n }, []);\n};\n\n", "current_contents": "import React from \"react\";\nimport tunnel from \"tunnel-rat\";\n\nexport type Tunnel = ReturnType;\n\ntype TunnelsContextValue = {\n MainMenuTunnel: Tunnel;\n WelcomeScreenMenuHintTunnel: Tunnel;\n WelcomeScreenToolbarHintTunnel: Tunnel;\n WelcomeScreenHelpHintTunnel: Tunnel;\n WelcomeScreenCenterTunnel: Tunnel;\n FooterCenterTunnel: Tunnel;\n DefaultSidebarTriggerTunnel: Tunnel;\n DefaultSidebarTabTriggersTunnel: Tunnel;\n OverwriteConfirmDialogTunnel: Tunnel;\n TTDDialogTriggerTunnel: Tunnel;\n jotaiScope: symbol;\n};\n\nexport const TunnelsContext = React.createContext(null!);\n\nexport const useTunnels = () => React.useContext(TunnelsContext);\n\nexport const useInitializeTunnels = () => {\n return React.useMemo((): TunnelsContextValue => {\n return {\n MainMenuTunnel: tunnel(),\n WelcomeScreenMenuHintTunnel: tunnel(),\n WelcomeScreenToolbarHintTunnel: tunnel(),\n WelcomeScreenHelpHintTunnel: tunnel(),\n WelcomeScreenCenterTunnel: tunnel(),\n FooterCenterTunnel: tunnel(),\n DefaultSidebarTriggerTunnel: tunnel(),\n DefaultSidebarTabTriggersTunnel: tunnel(),\n OverwriteConfirmDialogTunnel: tunnel(),\n jotaiScope: Symbol(),\n };\n }, []);\n};\n"} {"commit": "74d2fc6406c930df2f5823de0318346c10a8c7a5", "message": "fix: collab username style fixes (#6668)", "old_file": "src/renderer/roundRect.ts", "new_file": "src/renderer/roundRect.ts", "status": "M", "old_contents": "/**\n * https://stackoverflow.com/a/3368118\n * Draws a rounded rectangle using the current state of the canvas.\n * @param {CanvasRenderingContext2D} context\n * @param {Number} x The top left x coordinate\n * @param {Number} y The top left y coordinate\n * @param {Number} width The width of the rectangle\n * @param {Number} height The height of the rectangle\n * @param {Number} radius The corner radius\n */\nexport const roundRect = (\n context: CanvasRenderingContext2D,\n x: number,\n y: number,\n width: number,\n height: number,\n radius: number,\n) => {\n context.beginPath();\n context.moveTo(x + radius, y);\n context.lineTo(x + width - radius, y);\n context.quadraticCurveTo(x + width, y, x + width, y + radius);\n context.lineTo(x + width, y + height - radius);\n context.quadraticCurveTo(\n x + width,\n y + height,\n x + width - radius,\n y + height,\n );\n context.lineTo(x + radius, y + height);\n context.quadraticCurveTo(x, y + height, x, y + height - radius);\n context.lineTo(x, y + radius);\n context.quadraticCurveTo(x, y, x + radius, y);\n context.closePath();\n context.fill();\n context.stroke();\n};\n", "new_contents": "/**\n * https://stackoverflow.com/a/3368118\n * Draws a rounded rectangle using the current state of the canvas.\n * @param {CanvasRenderingContext2D} context\n * @param {Number} x The top left x coordinate\n * @param {Number} y The top left y coordinate\n * @param {Number} width The width of the rectangle\n * @param {Number} height The height of the rectangle\n * @param {Number} radius The corner radius\n */\nexport const roundRect = (\n context: CanvasRenderingContext2D,\n x: number,\n y: number,\n width: number,\n height: number,\n radius: number,\n strokeColor?: string,\n) => {\n context.beginPath();\n context.moveTo(x + radius, y);\n context.lineTo(x + width - radius, y);\n context.quadraticCurveTo(x + width, y, x + width, y + radius);\n context.lineTo(x + width, y + height - radius);\n context.quadraticCurveTo(\n x + width,\n y + height,\n x + width - radius,\n y + height,\n );\n context.lineTo(x + radius, y + height);\n context.quadraticCurveTo(x, y + height, x, y + height - radius);\n context.lineTo(x, y + radius);\n context.quadraticCurveTo(x, y, x + radius, y);\n context.closePath();\n context.fill();\n if (strokeColor) {\n context.strokeStyle = strokeColor;\n }\n context.stroke();\n};\n", "text": "<|original_code|>\n/**\n * https://stackoverflow.com/a/3368118\n * Draws a rounded rectangle using the current state of the canvas.\n * @param {CanvasRenderingContext2D} context\n * @param {Number} x The top left x coordinate\n * @param {Number} y The top left y coordinate\n * @param {Number} width The width of the rectangle\n * @param {Number} height The height of the rectangle\n * @param {Number} radius The corner radius\n */\nexport const roundRect = (\n context: CanvasRenderingContext2D,\n x: number,\n y: number,\n width: number,\n height: number,\n radius: number,\n) => {\n context.beginPath();\n context.moveTo(x + radius, y);\n context.lineTo(x + width - radius, y);\n context.quadraticCurveTo(x + width, y, x + width, y + radius);\n context.lineTo(x + width, y + height - radius);\n context.quadraticCurveTo(\n x + width,\n y + height,\n x + width - radius,\n y + height,\n );\n context.lineTo(x + radius, y + height);\n context.quadraticCurveTo(x, y + height, x, y + height - radius);\n context.lineTo(x, y + radius);\n context.quadraticCurveTo(x, y, x + radius, y);\n context.closePath();\n context.fill();\n context.stroke();\n};\n\n<|edits_diff|>\n--- src/renderer/roundRect.ts\n+++ src/renderer/roundRect.ts\n@@ -15,6 +15,7 @@\n width: number,\n height: number,\n radius: number,\n+ strokeColor?: string,\n ) => {\n context.beginPath();\n context.moveTo(x + radius, y);\n<|current_version|>\n/**\n * https://stackoverflow.com/a/3368118\n * Draws a rounded rectangle using the current state of the canvas.\n * @param {CanvasRenderingContext2D} context\n * @param {Number} x The top left x coordinate\n * @param {Number} y The top left y coordinate\n * @param {Number} width The width of the rectangle\n * @param {Number} height The height of the rectangle\n * @param {Number} radius The corner radius\n */\nexport const roundRect = (\n context: CanvasRenderingContext2D,\n x: number,\n y: number,\n width: number,\n height: number,\n radius: number,\n strokeColor?: string,\n) => {\n context.beginPath();\n context.moveTo(x + radius, y);\n context.lineTo(x + width - radius, y);\n context.quadraticCurveTo(x + width, y, x + width, y + radius);\n context.lineTo(x + width, y + height - radius);\n context.quadraticCurveTo(\n x + width,\n y + height,\n x + width - radius,\n y + height,\n );\n context.lineTo(x + radius, y + height);\n context.quadraticCurveTo(x, y + height, x, y + height - radius);\n context.lineTo(x, y + radius);\n context.quadraticCurveTo(x, y, x + radius, y);\n context.closePath();\n context.fill();\n context.stroke();\n};\n\n<|next_version|>\n/**\n * https://stackoverflow.com/a/3368118\n * Draws a rounded rectangle using the current state of the canvas.\n * @param {CanvasRenderingContext2D} context\n * @param {Number} x The top left x coordinate\n * @param {Number} y The top left y coordinate\n * @param {Number} width The width of the rectangle\n * @param {Number} height The height of the rectangle\n * @param {Number} radius The corner radius\n */\nexport const roundRect = (\n context: CanvasRenderingContext2D,\n x: number,\n y: number,\n width: number,\n height: number,\n radius: number,\n strokeColor?: string,\n) => {\n context.beginPath();\n context.moveTo(x + radius, y);\n context.lineTo(x + width - radius, y);\n context.quadraticCurveTo(x + width, y, x + width, y + radius);\n context.lineTo(x + width, y + height - radius);\n context.quadraticCurveTo(\n x + width,\n y + height,\n x + width - radius,\n y + height,\n );\n context.lineTo(x + radius, y + height);\n context.quadraticCurveTo(x, y + height, x, y + height - radius);\n context.lineTo(x, y + radius);\n context.quadraticCurveTo(x, y, x + radius, y);\n context.closePath();\n context.fill();\n if (strokeColor) {\n context.strokeStyle = strokeColor;\n }\n context.stroke();\n};\n\n", "current_contents": "/**\n * https://stackoverflow.com/a/3368118\n * Draws a rounded rectangle using the current state of the canvas.\n * @param {CanvasRenderingContext2D} context\n * @param {Number} x The top left x coordinate\n * @param {Number} y The top left y coordinate\n * @param {Number} width The width of the rectangle\n * @param {Number} height The height of the rectangle\n * @param {Number} radius The corner radius\n */\nexport const roundRect = (\n context: CanvasRenderingContext2D,\n x: number,\n y: number,\n width: number,\n height: number,\n radius: number,\n strokeColor?: string,\n) => {\n context.beginPath();\n context.moveTo(x + radius, y);\n context.lineTo(x + width - radius, y);\n context.quadraticCurveTo(x + width, y, x + width, y + radius);\n context.lineTo(x + width, y + height - radius);\n context.quadraticCurveTo(\n x + width,\n y + height,\n x + width - radius,\n y + height,\n );\n context.lineTo(x + radius, y + height);\n context.quadraticCurveTo(x, y + height, x, y + height - radius);\n context.lineTo(x, y + radius);\n context.quadraticCurveTo(x, y, x + radius, y);\n context.closePath();\n context.fill();\n context.stroke();\n};\n"} {"commit": "51a8ab65f3cb1a1c60392474d7b6b1fbde8a431e", "message": "Group / ungroup should not always be present in the context menu (#1890)", "old_file": "src/actions/actionGroup.ts", "new_file": "src/actions/actionGroup.ts", "status": "M", "old_contents": " .slice(0, lastGroupElementIndex)\n .filter(\n (updatedElement) => !isElementInGroup(updatedElement, newGroupId),\n );\n const updatedElementsInOrder = [\n ...elementsBeforeGroup,\n ...elementsInGroup,\n ...elementsAfterGroup,\n ];\n\n return {\n appState: selectGroup(\n newGroupId,\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(updatedElementsInOrder),\n ),\n elements: updatedElementsInOrder,\n commitToHistory: true,\n };\n },\n contextMenuOrder: 4,\n contextItemLabel: \"labels.group\",\n keyTest: (event) => {\n return (\n !event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n});\n\nexport const actionUngroup = register({\n name: \"ungroup\",\n perform: (elements, appState) => {\n const groupIds = getSelectedGroupIds(appState);\n if (groupIds.length === 0) {\n return { appState, elements, commitToHistory: false };\n }\n const nextElements = elements.map((element) => {\n const nextGroupIds = removeFromSelectedGroups(\n element.groupIds,\n appState.selectedGroupIds,\n );\n if (nextGroupIds.length === element.groupIds.length) {\n return element;\n }\n return newElementWith(element, {\n groupIds: nextGroupIds,\n });\n });\n return {\n appState: selectGroupsForSelectedElements(\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(nextElements),\n ),\n elements: nextElements,\n commitToHistory: true,\n };\n },\n keyTest: (event) => {\n return (\n event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n contextMenuOrder: 5,\n contextItemLabel: \"labels.ungroup\",\n});\n", "new_contents": " .slice(0, lastGroupElementIndex)\n .filter(\n (updatedElement) => !isElementInGroup(updatedElement, newGroupId),\n );\n const updatedElementsInOrder = [\n ...elementsBeforeGroup,\n ...elementsInGroup,\n ...elementsAfterGroup,\n ];\n\n return {\n appState: selectGroup(\n newGroupId,\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(updatedElementsInOrder),\n ),\n elements: updatedElementsInOrder,\n commitToHistory: true,\n };\n },\n contextMenuOrder: 4,\n contextItemLabel: \"labels.group\",\n contextItemPredicate: (elements, appState) =>\n getSelectedElements(getNonDeletedElements(elements), appState).length > 1,\n keyTest: (event) => {\n return (\n !event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n});\n\nexport const actionUngroup = register({\n name: \"ungroup\",\n perform: (elements, appState) => {\n const groupIds = getSelectedGroupIds(appState);\n if (groupIds.length === 0) {\n return { appState, elements, commitToHistory: false };\n }\n const nextElements = elements.map((element) => {\n const nextGroupIds = removeFromSelectedGroups(\n element.groupIds,\n appState.selectedGroupIds,\n );\n if (nextGroupIds.length === element.groupIds.length) {\n return element;\n }\n return newElementWith(element, {\n groupIds: nextGroupIds,\n });\n });\n return {\n appState: selectGroupsForSelectedElements(\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(nextElements),\n ),\n elements: nextElements,\n commitToHistory: true,\n };\n },\n keyTest: (event) => {\n return (\n event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n contextMenuOrder: 5,\n contextItemLabel: \"labels.ungroup\",\n contextItemPredicate: (elements, appState) =>\n getSelectedGroupIds(appState).length > 0,\n});\n", "text": "<|original_code|>\n .slice(0, lastGroupElementIndex)\n .filter(\n (updatedElement) => !isElementInGroup(updatedElement, newGroupId),\n );\n const updatedElementsInOrder = [\n ...elementsBeforeGroup,\n ...elementsInGroup,\n ...elementsAfterGroup,\n ];\n\n return {\n appState: selectGroup(\n newGroupId,\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(updatedElementsInOrder),\n ),\n elements: updatedElementsInOrder,\n commitToHistory: true,\n };\n },\n contextMenuOrder: 4,\n contextItemLabel: \"labels.group\",\n keyTest: (event) => {\n return (\n !event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n});\n\nexport const actionUngroup = register({\n name: \"ungroup\",\n perform: (elements, appState) => {\n const groupIds = getSelectedGroupIds(appState);\n if (groupIds.length === 0) {\n return { appState, elements, commitToHistory: false };\n }\n const nextElements = elements.map((element) => {\n const nextGroupIds = removeFromSelectedGroups(\n element.groupIds,\n appState.selectedGroupIds,\n );\n if (nextGroupIds.length === element.groupIds.length) {\n return element;\n }\n return newElementWith(element, {\n groupIds: nextGroupIds,\n });\n });\n return {\n appState: selectGroupsForSelectedElements(\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(nextElements),\n ),\n elements: nextElements,\n commitToHistory: true,\n };\n },\n keyTest: (event) => {\n return (\n event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n contextMenuOrder: 5,\n contextItemLabel: \"labels.ungroup\",\n});\n\n<|edits_diff|>\n--- src/actions/actionGroup.ts\n+++ src/actions/actionGroup.ts\n@@ -20,6 +20,8 @@\n },\n contextMenuOrder: 4,\n contextItemLabel: \"labels.group\",\n+ contextItemPredicate: (elements, appState) =>\n+ getSelectedElements(getNonDeletedElements(elements), appState).length > 1,\n keyTest: (event) => {\n return (\n !event.shiftKey &&\n<|current_version|>\n .slice(0, lastGroupElementIndex)\n .filter(\n (updatedElement) => !isElementInGroup(updatedElement, newGroupId),\n );\n const updatedElementsInOrder = [\n ...elementsBeforeGroup,\n ...elementsInGroup,\n ...elementsAfterGroup,\n ];\n\n return {\n appState: selectGroup(\n newGroupId,\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(updatedElementsInOrder),\n ),\n elements: updatedElementsInOrder,\n commitToHistory: true,\n };\n },\n contextMenuOrder: 4,\n contextItemLabel: \"labels.group\",\n contextItemPredicate: (elements, appState) =>\n getSelectedElements(getNonDeletedElements(elements), appState).length > 1,\n keyTest: (event) => {\n return (\n !event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n});\n\nexport const actionUngroup = register({\n name: \"ungroup\",\n perform: (elements, appState) => {\n const groupIds = getSelectedGroupIds(appState);\n if (groupIds.length === 0) {\n return { appState, elements, commitToHistory: false };\n }\n const nextElements = elements.map((element) => {\n const nextGroupIds = removeFromSelectedGroups(\n element.groupIds,\n appState.selectedGroupIds,\n );\n if (nextGroupIds.length === element.groupIds.length) {\n return element;\n }\n return newElementWith(element, {\n groupIds: nextGroupIds,\n });\n });\n return {\n appState: selectGroupsForSelectedElements(\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(nextElements),\n ),\n elements: nextElements,\n commitToHistory: true,\n };\n },\n keyTest: (event) => {\n return (\n event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n contextMenuOrder: 5,\n contextItemLabel: \"labels.ungroup\",\n});\n\n<|next_version|>\n .slice(0, lastGroupElementIndex)\n .filter(\n (updatedElement) => !isElementInGroup(updatedElement, newGroupId),\n );\n const updatedElementsInOrder = [\n ...elementsBeforeGroup,\n ...elementsInGroup,\n ...elementsAfterGroup,\n ];\n\n return {\n appState: selectGroup(\n newGroupId,\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(updatedElementsInOrder),\n ),\n elements: updatedElementsInOrder,\n commitToHistory: true,\n };\n },\n contextMenuOrder: 4,\n contextItemLabel: \"labels.group\",\n contextItemPredicate: (elements, appState) =>\n getSelectedElements(getNonDeletedElements(elements), appState).length > 1,\n keyTest: (event) => {\n return (\n !event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n});\n\nexport const actionUngroup = register({\n name: \"ungroup\",\n perform: (elements, appState) => {\n const groupIds = getSelectedGroupIds(appState);\n if (groupIds.length === 0) {\n return { appState, elements, commitToHistory: false };\n }\n const nextElements = elements.map((element) => {\n const nextGroupIds = removeFromSelectedGroups(\n element.groupIds,\n appState.selectedGroupIds,\n );\n if (nextGroupIds.length === element.groupIds.length) {\n return element;\n }\n return newElementWith(element, {\n groupIds: nextGroupIds,\n });\n });\n return {\n appState: selectGroupsForSelectedElements(\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(nextElements),\n ),\n elements: nextElements,\n commitToHistory: true,\n };\n },\n keyTest: (event) => {\n return (\n event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n contextMenuOrder: 5,\n contextItemLabel: \"labels.ungroup\",\n contextItemPredicate: (elements, appState) =>\n getSelectedGroupIds(appState).length > 0,\n});\n\n", "current_contents": " .slice(0, lastGroupElementIndex)\n .filter(\n (updatedElement) => !isElementInGroup(updatedElement, newGroupId),\n );\n const updatedElementsInOrder = [\n ...elementsBeforeGroup,\n ...elementsInGroup,\n ...elementsAfterGroup,\n ];\n\n return {\n appState: selectGroup(\n newGroupId,\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(updatedElementsInOrder),\n ),\n elements: updatedElementsInOrder,\n commitToHistory: true,\n };\n },\n contextMenuOrder: 4,\n contextItemLabel: \"labels.group\",\n contextItemPredicate: (elements, appState) =>\n getSelectedElements(getNonDeletedElements(elements), appState).length > 1,\n keyTest: (event) => {\n return (\n !event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n});\n\nexport const actionUngroup = register({\n name: \"ungroup\",\n perform: (elements, appState) => {\n const groupIds = getSelectedGroupIds(appState);\n if (groupIds.length === 0) {\n return { appState, elements, commitToHistory: false };\n }\n const nextElements = elements.map((element) => {\n const nextGroupIds = removeFromSelectedGroups(\n element.groupIds,\n appState.selectedGroupIds,\n );\n if (nextGroupIds.length === element.groupIds.length) {\n return element;\n }\n return newElementWith(element, {\n groupIds: nextGroupIds,\n });\n });\n return {\n appState: selectGroupsForSelectedElements(\n { ...appState, selectedGroupIds: {} },\n getNonDeletedElements(nextElements),\n ),\n elements: nextElements,\n commitToHistory: true,\n };\n },\n keyTest: (event) => {\n return (\n event.shiftKey &&\n event[KEYS.CTRL_OR_CMD] &&\n event.keyCode === KEYS.G_KEY_CODE\n );\n },\n contextMenuOrder: 5,\n contextItemLabel: \"labels.ungroup\",\n});\n"} {"commit": "62228e0bbb780d1070a8cf206caa32132d22f19e", "message": "feat: introduce font picker (#8012)", "old_file": "packages/utils/export.ts", "new_file": "packages/utils/export.ts", "status": "M", "old_contents": " opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n", "new_contents": " opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n", "text": "<|original_code|>\n opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n<|edits_diff|>\n--- packages/utils/export.ts\n+++ packages/utils/export.ts\n@@ -20,9 +20,11 @@\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n+ skipInliningFonts,\n }: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n+ skipInliningFonts?: true;\n }): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n<|current_version|>\n opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n<|next_version|>\n opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n skipInliningFonts,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n\n", "current_contents": " opts.elements,\n opts.appState,\n opts.files || {},\n \"local\",\n ),\n });\n }\n resolve(blob);\n },\n mimeType,\n quality,\n );\n });\n};\n\nexport const exportToSvg = async ({\n elements,\n appState = getDefaultAppState(),\n files = {},\n exportPadding,\n renderEmbeddables,\n exportingFrame,\n skipInliningFonts,\n}: Omit & {\n exportPadding?: number;\n renderEmbeddables?: boolean;\n skipInliningFonts?: true;\n}): Promise => {\n const { elements: restoredElements, appState: restoredAppState } = restore(\n { elements, appState },\n null,\n null,\n );\n\n const exportAppState = {\n ...restoredAppState,\n exportPadding,\n };\n\n return _exportToSvg(restoredElements, exportAppState, files, {\n exportingFrame,\n renderEmbeddables,\n });\n};\n\nexport const exportToClipboard = async (\n opts: ExportOpts & {\n mimeType?: string;\n quality?: number;\n type: \"png\" | \"svg\" | \"json\";\n },\n) => {\n if (opts.type === \"svg\") {\n const svg = await exportToSvg(opts);\n await copyTextToSystemClipboard(svg.outerHTML);\n } else if (opts.type === \"png\") {\n await copyBlobToClipboardAsPng(exportToBlob(opts));\n } else if (opts.type === \"json\") {\n await copyToClipboard(opts.elements, opts.files);\n } else {\n throw new Error(\"Invalid export type\");\n }\n};\n"} {"commit": "b6ef953dc919060ac56f6ccfdc7b37e93514ea26", "message": "fix: SVG export in dark mode with embedded bitmap image (#4285)", "old_file": "src/renderer/renderScene.ts", "new_file": "src/renderer/renderScene.ts", "status": "M", "old_contents": " clientY: viewTransformations.offsetTop + canvasHeight,\n },\n viewTransformations,\n );\n\n return (\n topLeftSceneCoords.x <= x2 &&\n topLeftSceneCoords.y <= y2 &&\n bottomRightSceneCoords.x >= x1 &&\n bottomRightSceneCoords.y >= y1\n );\n};\n\n// This should be only called for exporting purposes\nexport const renderSceneToSvg = (\n elements: readonly NonDeletedExcalidrawElement[],\n rsvg: RoughSVG,\n svgRoot: SVGElement,\n files: BinaryFiles,\n {\n offsetX = 0,\n offsetY = 0,\n }: {\n offsetX?: number;\n offsetY?: number;\n } = {},\n) => {\n if (!svgRoot) {\n return;\n }\n // render elements\n elements.forEach((element) => {\n if (!element.isDeleted) {\n try {\n renderElementToSvg(\n element,\n rsvg,\n svgRoot,\n files,\n element.x + offsetX,\n element.y + offsetY,\n );\n } catch (error: any) {\n console.error(error);\n }\n }\n });\n};\n", "new_contents": " clientY: viewTransformations.offsetTop + canvasHeight,\n },\n viewTransformations,\n );\n\n return (\n topLeftSceneCoords.x <= x2 &&\n topLeftSceneCoords.y <= y2 &&\n bottomRightSceneCoords.x >= x1 &&\n bottomRightSceneCoords.y >= y1\n );\n};\n\n// This should be only called for exporting purposes\nexport const renderSceneToSvg = (\n elements: readonly NonDeletedExcalidrawElement[],\n rsvg: RoughSVG,\n svgRoot: SVGElement,\n files: BinaryFiles,\n {\n offsetX = 0,\n offsetY = 0,\n exportWithDarkMode = false,\n }: {\n offsetX?: number;\n offsetY?: number;\n exportWithDarkMode?: boolean;\n } = {},\n) => {\n if (!svgRoot) {\n return;\n }\n // render elements\n elements.forEach((element) => {\n if (!element.isDeleted) {\n try {\n renderElementToSvg(\n element,\n rsvg,\n svgRoot,\n files,\n element.x + offsetX,\n element.y + offsetY,\n exportWithDarkMode,\n );\n } catch (error: any) {\n console.error(error);\n }\n }\n });\n};\n", "text": "<|original_code|>\n clientY: viewTransformations.offsetTop + canvasHeight,\n },\n viewTransformations,\n );\n\n return (\n topLeftSceneCoords.x <= x2 &&\n topLeftSceneCoords.y <= y2 &&\n bottomRightSceneCoords.x >= x1 &&\n bottomRightSceneCoords.y >= y1\n );\n};\n\n// This should be only called for exporting purposes\nexport const renderSceneToSvg = (\n elements: readonly NonDeletedExcalidrawElement[],\n rsvg: RoughSVG,\n svgRoot: SVGElement,\n files: BinaryFiles,\n {\n offsetX = 0,\n offsetY = 0,\n }: {\n offsetX?: number;\n offsetY?: number;\n } = {},\n) => {\n if (!svgRoot) {\n return;\n }\n // render elements\n elements.forEach((element) => {\n if (!element.isDeleted) {\n try {\n renderElementToSvg(\n element,\n rsvg,\n svgRoot,\n files,\n element.x + offsetX,\n element.y + offsetY,\n );\n } catch (error: any) {\n console.error(error);\n }\n }\n });\n};\n\n<|edits_diff|>\n--- src/renderer/renderScene.ts\n+++ src/renderer/renderScene.ts\n@@ -20,9 +20,11 @@\n {\n offsetX = 0,\n offsetY = 0,\n+ exportWithDarkMode = false,\n }: {\n offsetX?: number;\n offsetY?: number;\n+ exportWithDarkMode?: boolean;\n } = {},\n ) => {\n if (!svgRoot) {\n<|current_version|>\n clientY: viewTransformations.offsetTop + canvasHeight,\n },\n viewTransformations,\n );\n\n return (\n topLeftSceneCoords.x <= x2 &&\n topLeftSceneCoords.y <= y2 &&\n bottomRightSceneCoords.x >= x1 &&\n bottomRightSceneCoords.y >= y1\n );\n};\n\n// This should be only called for exporting purposes\nexport const renderSceneToSvg = (\n elements: readonly NonDeletedExcalidrawElement[],\n rsvg: RoughSVG,\n svgRoot: SVGElement,\n files: BinaryFiles,\n {\n offsetX = 0,\n offsetY = 0,\n exportWithDarkMode = false,\n }: {\n offsetX?: number;\n offsetY?: number;\n exportWithDarkMode?: boolean;\n } = {},\n) => {\n if (!svgRoot) {\n return;\n }\n // render elements\n elements.forEach((element) => {\n if (!element.isDeleted) {\n try {\n renderElementToSvg(\n element,\n rsvg,\n svgRoot,\n files,\n element.x + offsetX,\n element.y + offsetY,\n );\n } catch (error: any) {\n console.error(error);\n }\n }\n });\n};\n\n<|next_version|>\n clientY: viewTransformations.offsetTop + canvasHeight,\n },\n viewTransformations,\n );\n\n return (\n topLeftSceneCoords.x <= x2 &&\n topLeftSceneCoords.y <= y2 &&\n bottomRightSceneCoords.x >= x1 &&\n bottomRightSceneCoords.y >= y1\n );\n};\n\n// This should be only called for exporting purposes\nexport const renderSceneToSvg = (\n elements: readonly NonDeletedExcalidrawElement[],\n rsvg: RoughSVG,\n svgRoot: SVGElement,\n files: BinaryFiles,\n {\n offsetX = 0,\n offsetY = 0,\n exportWithDarkMode = false,\n }: {\n offsetX?: number;\n offsetY?: number;\n exportWithDarkMode?: boolean;\n } = {},\n) => {\n if (!svgRoot) {\n return;\n }\n // render elements\n elements.forEach((element) => {\n if (!element.isDeleted) {\n try {\n renderElementToSvg(\n element,\n rsvg,\n svgRoot,\n files,\n element.x + offsetX,\n element.y + offsetY,\n exportWithDarkMode,\n );\n } catch (error: any) {\n console.error(error);\n }\n }\n });\n};\n\n", "current_contents": " clientY: viewTransformations.offsetTop + canvasHeight,\n },\n viewTransformations,\n );\n\n return (\n topLeftSceneCoords.x <= x2 &&\n topLeftSceneCoords.y <= y2 &&\n bottomRightSceneCoords.x >= x1 &&\n bottomRightSceneCoords.y >= y1\n );\n};\n\n// This should be only called for exporting purposes\nexport const renderSceneToSvg = (\n elements: readonly NonDeletedExcalidrawElement[],\n rsvg: RoughSVG,\n svgRoot: SVGElement,\n files: BinaryFiles,\n {\n offsetX = 0,\n offsetY = 0,\n exportWithDarkMode = false,\n }: {\n offsetX?: number;\n offsetY?: number;\n exportWithDarkMode?: boolean;\n } = {},\n) => {\n if (!svgRoot) {\n return;\n }\n // render elements\n elements.forEach((element) => {\n if (!element.isDeleted) {\n try {\n renderElementToSvg(\n element,\n rsvg,\n svgRoot,\n files,\n element.x + offsetX,\n element.y + offsetY,\n );\n } catch (error: any) {\n console.error(error);\n }\n }\n });\n};\n"} {"commit": "49430528e519d112332b1012d242afea5b2a1ef8", "message": "refactor: foundational changes to support subdomain based cloud instances (#4704)", "old_file": "packages/hoppscotch-common/src/platform/index.ts", "new_file": "packages/hoppscotch-common/src/platform/index.ts", "status": "M", "old_contents": "import { ServiceClassInstance } from \"dioc\"\nimport { Ref } from \"vue\"\nimport { HoppModule } from \"~/modules\"\nimport { AnalyticsPlatformDef } from \"./analytics\"\nimport { AuthPlatformDef } from \"./auth\"\nimport { CollectionsPlatformDef } from \"./collections\"\nimport { EnvironmentsPlatformDef } from \"./environments\"\nimport { ExperimentsPlatformDef } from \"./experiments\"\nimport { HistoryPlatformDef } from \"./history\"\nimport { InfraPlatformDef } from \"./infra\"\nimport { InspectorsPlatformDef } from \"./inspectors\"\nimport { InterceptorsPlatformDef } from \"./interceptors\"\nimport { IOPlatformDef } from \"./io\"\nimport { LimitsPlatformDef } from \"./limits\"\nimport { SettingsPlatformDef } from \"./settings\"\nimport { SpotlightPlatformDef } from \"./spotlight\"\nimport { UIPlatformDef } from \"./ui\"\n\nexport type PlatformDef = {\n ui?: UIPlatformDef\n addedHoppModules?: HoppModule[]\n addedServices?: Array>\n auth: AuthPlatformDef\n analytics?: AnalyticsPlatformDef\n io: IOPlatformDef\n sync: {\n environments: EnvironmentsPlatformDef\n collections: CollectionsPlatformDef\n settings: SettingsPlatformDef\n history: HistoryPlatformDef\n }\n interceptors: InterceptorsPlatformDef\n additionalInspectors?: InspectorsPlatformDef\n spotlight?: SpotlightPlatformDef\n platformFeatureFlags: {\n exportAsGIST: boolean\n hasTelemetry: boolean\n\n /**\n * Whether the platform supports cookies (affects whether the cookies footer item is shown)\n * If a value is not given, then the value is assumed to be false\n */\n cookiesEnabled?: boolean\n\n /**\n * Whether the platform should prompt the user that cookies are being used.\n * This will result in the user being notified a cookies advisory and is meant for web apps.\n *\n * If a value is not given, then the value is assumed to be true\n */\n promptAsUsingCookies?: boolean\n\n /**\n * Whether to show the A/B testing workspace switcher click login flow or not\n */\n workspaceSwitcherLogin?: Ref\n }\n limits?: LimitsPlatformDef\n infra?: InfraPlatformDef\n experiments?: ExperimentsPlatformDef\n}\n\nexport let platform: PlatformDef\n\nexport function setPlatformDef(def: PlatformDef) {\n platform = def\n}\n", "new_contents": "import { ServiceClassInstance } from \"dioc\"\nimport { Ref } from \"vue\"\nimport { HoppModule } from \"~/modules\"\nimport { AnalyticsPlatformDef } from \"./analytics\"\nimport { AuthPlatformDef } from \"./auth\"\nimport { CollectionsPlatformDef } from \"./collections\"\nimport { EnvironmentsPlatformDef } from \"./environments\"\nimport { ExperimentsPlatformDef } from \"./experiments\"\nimport { HistoryPlatformDef } from \"./history\"\nimport { InfraPlatformDef } from \"./infra\"\nimport { InspectorsPlatformDef } from \"./inspectors\"\nimport { InterceptorsPlatformDef } from \"./interceptors\"\nimport { IOPlatformDef } from \"./io\"\nimport { LimitsPlatformDef } from \"./limits\"\nimport { SettingsPlatformDef } from \"./settings\"\nimport { SpotlightPlatformDef } from \"./spotlight\"\nimport { UIPlatformDef } from \"./ui\"\nimport { BackendPlatformDef } from \"./backend\"\nimport { OrganizationPlatformDef } from \"./organization\"\n\nexport type PlatformDef = {\n ui?: UIPlatformDef\n addedHoppModules?: HoppModule[]\n addedServices?: Array>\n auth: AuthPlatformDef\n analytics?: AnalyticsPlatformDef\n io: IOPlatformDef\n sync: {\n environments: EnvironmentsPlatformDef\n collections: CollectionsPlatformDef\n settings: SettingsPlatformDef\n history: HistoryPlatformDef\n }\n interceptors: InterceptorsPlatformDef\n additionalInspectors?: InspectorsPlatformDef\n spotlight?: SpotlightPlatformDef\n platformFeatureFlags: {\n exportAsGIST: boolean\n hasTelemetry: boolean\n\n /**\n * Whether the platform supports cookies (affects whether the cookies footer item is shown)\n * If a value is not given, then the value is assumed to be false\n */\n cookiesEnabled?: boolean\n\n /**\n * Whether the platform should prompt the user that cookies are being used.\n * This will result in the user being notified a cookies advisory and is meant for web apps.\n *\n * If a value is not given, then the value is assumed to be true\n */\n promptAsUsingCookies?: boolean\n\n /**\n * Whether to show the A/B testing workspace switcher click login flow or not\n */\n workspaceSwitcherLogin?: Ref\n }\n limits?: LimitsPlatformDef\n infra?: InfraPlatformDef\n experiments?: ExperimentsPlatformDef\n backend: BackendPlatformDef\n organization?: OrganizationPlatformDef\n}\n\nexport let platform: PlatformDef\n\nexport function setPlatformDef(def: PlatformDef) {\n platform = def\n}\n", "text": "<|original_code|>\nimport { ServiceClassInstance } from \"dioc\"\nimport { Ref } from \"vue\"\nimport { HoppModule } from \"~/modules\"\nimport { AnalyticsPlatformDef } from \"./analytics\"\nimport { AuthPlatformDef } from \"./auth\"\nimport { CollectionsPlatformDef } from \"./collections\"\nimport { EnvironmentsPlatformDef } from \"./environments\"\nimport { ExperimentsPlatformDef } from \"./experiments\"\nimport { HistoryPlatformDef } from \"./history\"\nimport { InfraPlatformDef } from \"./infra\"\nimport { InspectorsPlatformDef } from \"./inspectors\"\nimport { InterceptorsPlatformDef } from \"./interceptors\"\nimport { IOPlatformDef } from \"./io\"\nimport { LimitsPlatformDef } from \"./limits\"\nimport { SettingsPlatformDef } from \"./settings\"\nimport { SpotlightPlatformDef } from \"./spotlight\"\nimport { UIPlatformDef } from \"./ui\"\n\nexport type PlatformDef = {\n ui?: UIPlatformDef\n addedHoppModules?: HoppModule[]\n addedServices?: Array>\n auth: AuthPlatformDef\n analytics?: AnalyticsPlatformDef\n io: IOPlatformDef\n sync: {\n environments: EnvironmentsPlatformDef\n collections: CollectionsPlatformDef\n settings: SettingsPlatformDef\n history: HistoryPlatformDef\n }\n interceptors: InterceptorsPlatformDef\n additionalInspectors?: InspectorsPlatformDef\n spotlight?: SpotlightPlatformDef\n platformFeatureFlags: {\n exportAsGIST: boolean\n hasTelemetry: boolean\n\n /**\n * Whether the platform supports cookies (affects whether the cookies footer item is shown)\n * If a value is not given, then the value is assumed to be false\n */\n cookiesEnabled?: boolean\n\n /**\n * Whether the platform should prompt the user that cookies are being used.\n * This will result in the user being notified a cookies advisory and is meant for web apps.\n *\n * If a value is not given, then the value is assumed to be true\n */\n promptAsUsingCookies?: boolean\n\n /**\n * Whether to show the A/B testing workspace switcher click login flow or not\n */\n workspaceSwitcherLogin?: Ref\n }\n limits?: LimitsPlatformDef\n infra?: InfraPlatformDef\n experiments?: ExperimentsPlatformDef\n}\n\nexport let platform: PlatformDef\n\nexport function setPlatformDef(def: PlatformDef) {\n platform = def\n}\n\n<|edits_diff|>\n--- packages/hoppscotch-common/src/platform/index.ts\n+++ packages/hoppscotch-common/src/platform/index.ts\n@@ -15,6 +15,8 @@\n import { SettingsPlatformDef } from \"./settings\"\n import { SpotlightPlatformDef } from \"./spotlight\"\n import { UIPlatformDef } from \"./ui\"\n+import { BackendPlatformDef } from \"./backend\"\n+import { OrganizationPlatformDef } from \"./organization\"\n \n export type PlatformDef = {\n ui?: UIPlatformDef\n<|current_version|>\nimport { ServiceClassInstance } from \"dioc\"\nimport { Ref } from \"vue\"\nimport { HoppModule } from \"~/modules\"\nimport { AnalyticsPlatformDef } from \"./analytics\"\nimport { AuthPlatformDef } from \"./auth\"\nimport { CollectionsPlatformDef } from \"./collections\"\nimport { EnvironmentsPlatformDef } from \"./environments\"\nimport { ExperimentsPlatformDef } from \"./experiments\"\nimport { HistoryPlatformDef } from \"./history\"\nimport { InfraPlatformDef } from \"./infra\"\nimport { InspectorsPlatformDef } from \"./inspectors\"\nimport { InterceptorsPlatformDef } from \"./interceptors\"\nimport { IOPlatformDef } from \"./io\"\nimport { LimitsPlatformDef } from \"./limits\"\nimport { SettingsPlatformDef } from \"./settings\"\nimport { SpotlightPlatformDef } from \"./spotlight\"\nimport { UIPlatformDef } from \"./ui\"\nimport { BackendPlatformDef } from \"./backend\"\nimport { OrganizationPlatformDef } from \"./organization\"\n\nexport type PlatformDef = {\n ui?: UIPlatformDef\n addedHoppModules?: HoppModule[]\n addedServices?: Array>\n auth: AuthPlatformDef\n analytics?: AnalyticsPlatformDef\n io: IOPlatformDef\n sync: {\n environments: EnvironmentsPlatformDef\n collections: CollectionsPlatformDef\n settings: SettingsPlatformDef\n history: HistoryPlatformDef\n }\n interceptors: InterceptorsPlatformDef\n additionalInspectors?: InspectorsPlatformDef\n spotlight?: SpotlightPlatformDef\n platformFeatureFlags: {\n exportAsGIST: boolean\n hasTelemetry: boolean\n\n /**\n * Whether the platform supports cookies (affects whether the cookies footer item is shown)\n * If a value is not given, then the value is assumed to be false\n */\n cookiesEnabled?: boolean\n\n /**\n * Whether the platform should prompt the user that cookies are being used.\n * This will result in the user being notified a cookies advisory and is meant for web apps.\n *\n * If a value is not given, then the value is assumed to be true\n */\n promptAsUsingCookies?: boolean\n\n /**\n * Whether to show the A/B testing workspace switcher click login flow or not\n */\n workspaceSwitcherLogin?: Ref\n }\n limits?: LimitsPlatformDef\n infra?: InfraPlatformDef\n experiments?: ExperimentsPlatformDef\n}\n\nexport let platform: PlatformDef\n\nexport function setPlatformDef(def: PlatformDef) {\n platform = def\n}\n\n<|next_version|>\nimport { ServiceClassInstance } from \"dioc\"\nimport { Ref } from \"vue\"\nimport { HoppModule } from \"~/modules\"\nimport { AnalyticsPlatformDef } from \"./analytics\"\nimport { AuthPlatformDef } from \"./auth\"\nimport { CollectionsPlatformDef } from \"./collections\"\nimport { EnvironmentsPlatformDef } from \"./environments\"\nimport { ExperimentsPlatformDef } from \"./experiments\"\nimport { HistoryPlatformDef } from \"./history\"\nimport { InfraPlatformDef } from \"./infra\"\nimport { InspectorsPlatformDef } from \"./inspectors\"\nimport { InterceptorsPlatformDef } from \"./interceptors\"\nimport { IOPlatformDef } from \"./io\"\nimport { LimitsPlatformDef } from \"./limits\"\nimport { SettingsPlatformDef } from \"./settings\"\nimport { SpotlightPlatformDef } from \"./spotlight\"\nimport { UIPlatformDef } from \"./ui\"\nimport { BackendPlatformDef } from \"./backend\"\nimport { OrganizationPlatformDef } from \"./organization\"\n\nexport type PlatformDef = {\n ui?: UIPlatformDef\n addedHoppModules?: HoppModule[]\n addedServices?: Array>\n auth: AuthPlatformDef\n analytics?: AnalyticsPlatformDef\n io: IOPlatformDef\n sync: {\n environments: EnvironmentsPlatformDef\n collections: CollectionsPlatformDef\n settings: SettingsPlatformDef\n history: HistoryPlatformDef\n }\n interceptors: InterceptorsPlatformDef\n additionalInspectors?: InspectorsPlatformDef\n spotlight?: SpotlightPlatformDef\n platformFeatureFlags: {\n exportAsGIST: boolean\n hasTelemetry: boolean\n\n /**\n * Whether the platform supports cookies (affects whether the cookies footer item is shown)\n * If a value is not given, then the value is assumed to be false\n */\n cookiesEnabled?: boolean\n\n /**\n * Whether the platform should prompt the user that cookies are being used.\n * This will result in the user being notified a cookies advisory and is meant for web apps.\n *\n * If a value is not given, then the value is assumed to be true\n */\n promptAsUsingCookies?: boolean\n\n /**\n * Whether to show the A/B testing workspace switcher click login flow or not\n */\n workspaceSwitcherLogin?: Ref\n }\n limits?: LimitsPlatformDef\n infra?: InfraPlatformDef\n experiments?: ExperimentsPlatformDef\n backend: BackendPlatformDef\n organization?: OrganizationPlatformDef\n}\n\nexport let platform: PlatformDef\n\nexport function setPlatformDef(def: PlatformDef) {\n platform = def\n}\n\n", "current_contents": "import { ServiceClassInstance } from \"dioc\"\nimport { Ref } from \"vue\"\nimport { HoppModule } from \"~/modules\"\nimport { AnalyticsPlatformDef } from \"./analytics\"\nimport { AuthPlatformDef } from \"./auth\"\nimport { CollectionsPlatformDef } from \"./collections\"\nimport { EnvironmentsPlatformDef } from \"./environments\"\nimport { ExperimentsPlatformDef } from \"./experiments\"\nimport { HistoryPlatformDef } from \"./history\"\nimport { InfraPlatformDef } from \"./infra\"\nimport { InspectorsPlatformDef } from \"./inspectors\"\nimport { InterceptorsPlatformDef } from \"./interceptors\"\nimport { IOPlatformDef } from \"./io\"\nimport { LimitsPlatformDef } from \"./limits\"\nimport { SettingsPlatformDef } from \"./settings\"\nimport { SpotlightPlatformDef } from \"./spotlight\"\nimport { UIPlatformDef } from \"./ui\"\nimport { BackendPlatformDef } from \"./backend\"\nimport { OrganizationPlatformDef } from \"./organization\"\n\nexport type PlatformDef = {\n ui?: UIPlatformDef\n addedHoppModules?: HoppModule[]\n addedServices?: Array>\n auth: AuthPlatformDef\n analytics?: AnalyticsPlatformDef\n io: IOPlatformDef\n sync: {\n environments: EnvironmentsPlatformDef\n collections: CollectionsPlatformDef\n settings: SettingsPlatformDef\n history: HistoryPlatformDef\n }\n interceptors: InterceptorsPlatformDef\n additionalInspectors?: InspectorsPlatformDef\n spotlight?: SpotlightPlatformDef\n platformFeatureFlags: {\n exportAsGIST: boolean\n hasTelemetry: boolean\n\n /**\n * Whether the platform supports cookies (affects whether the cookies footer item is shown)\n * If a value is not given, then the value is assumed to be false\n */\n cookiesEnabled?: boolean\n\n /**\n * Whether the platform should prompt the user that cookies are being used.\n * This will result in the user being notified a cookies advisory and is meant for web apps.\n *\n * If a value is not given, then the value is assumed to be true\n */\n promptAsUsingCookies?: boolean\n\n /**\n * Whether to show the A/B testing workspace switcher click login flow or not\n */\n workspaceSwitcherLogin?: Ref\n }\n limits?: LimitsPlatformDef\n infra?: InfraPlatformDef\n experiments?: ExperimentsPlatformDef\n}\n\nexport let platform: PlatformDef\n\nexport function setPlatformDef(def: PlatformDef) {\n platform = def\n}\n"} {"commit": "da2597d4dbbcd784a08ad5ed5e1ee9e8ebc0f59d", "message": "feat: updated the hard coded proxy url with the server fetched (#4773)", "old_file": "packages/hoppscotch-common/src/platform/infra.ts", "new_file": "packages/hoppscotch-common/src/platform/infra.ts", "status": "M", "old_contents": "import * as E from \"fp-ts/Either\"\n\nexport type InfraPlatformDef = {\n getIsSMTPEnabled?: () => Promise>\n}\n", "new_contents": "import * as E from \"fp-ts/Either\"\n\ntype ProxyAppUrl = {\n value: string\n name: string\n}\n\nexport type InfraPlatformDef = {\n getIsSMTPEnabled?: () => Promise>\n getProxyAppUrl?: () => Promise>\n}\n", "text": "<|original_code|>\nimport * as E from \"fp-ts/Either\"\n\nexport type InfraPlatformDef = {\n getIsSMTPEnabled?: () => Promise>\n}\n\n<|edits_diff|>\n--- packages/hoppscotch-common/src/platform/infra.ts\n+++ packages/hoppscotch-common/src/platform/infra.ts\n@@ -1,4 +1,9 @@\n import * as E from \"fp-ts/Either\"\n+\n+type ProxyAppUrl = {\n+ value: string\n+ name: string\n+}\n \n export type InfraPlatformDef = {\n getIsSMTPEnabled?: () => Promise>\n<|current_version|>\nimport * as E from \"fp-ts/Either\"\n\ntype ProxyAppUrl = {\n value: string\n name: string\n}\n\nexport type InfraPlatformDef = {\n getIsSMTPEnabled?: () => Promise>\n}\n\n<|next_version|>\nimport * as E from \"fp-ts/Either\"\n\ntype ProxyAppUrl = {\n value: string\n name: string\n}\n\nexport type InfraPlatformDef = {\n getIsSMTPEnabled?: () => Promise>\n getProxyAppUrl?: () => Promise>\n}\n\n", "current_contents": "import * as E from \"fp-ts/Either\"\n\ntype ProxyAppUrl = {\n value: string\n name: string\n}\n\nexport type InfraPlatformDef = {\n getIsSMTPEnabled?: () => Promise>\n}\n"} {"commit": "bd22c8c1a9e8a08b337bbfa2bdfe36b560db8df0", "message": "feat: disable tracking request history (#4607)", "old_file": "packages/hoppscotch-selfhost-web/src/platform/history/history.sync.ts", "new_file": "packages/hoppscotch-selfhost-web/src/platform/history/history.sync.ts", "status": "M", "old_contents": " removeDuplicateRestHistoryEntry,\n removeDuplicateGraphqlHistoryEntry,\n restHistoryStore,\n} from \"@hoppscotch/common/newstore/history\"\nimport {\n getSettingSubject,\n settingsStore,\n} from \"@hoppscotch/common/newstore/settings\"\n\nimport { getSyncInitFunction } from \"../../lib/sync\"\n\nimport * as E from \"fp-ts/Either\"\n\nimport { StoreSyncDefinitionOf } from \"../../lib/sync\"\nimport {\n createUserHistory,\n deleteAllUserHistory,\n removeRequestFromHistory,\n toggleHistoryStarStatus,\n} from \"./history.api\"\nimport { ReqType } from \"../../api/generated/graphql\"\n\nexport const restHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof restHistoryStore\n> = {\n async addEntry({ entry }) {\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.responseMeta),\n ReqType.Rest\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateRestHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n deleteAllUserHistory(ReqType.Rest)\n },\n}\n\nexport const gqlHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof graphqlHistoryStore\n> = {\n async addEntry({ entry }) {\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.response),\n ReqType.Gql\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateGraphqlHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {", "new_contents": " removeDuplicateRestHistoryEntry,\n removeDuplicateGraphqlHistoryEntry,\n restHistoryStore,\n} from \"@hoppscotch/common/newstore/history\"\nimport {\n getSettingSubject,\n settingsStore,\n} from \"@hoppscotch/common/newstore/settings\"\n\nimport { getSyncInitFunction } from \"../../lib/sync\"\n\nimport * as E from \"fp-ts/Either\"\n\nimport { StoreSyncDefinitionOf } from \"../../lib/sync\"\nimport {\n createUserHistory,\n deleteAllUserHistory,\n removeRequestFromHistory,\n toggleHistoryStarStatus,\n} from \"./history.api\"\nimport { ReqType } from \"../../api/generated/graphql\"\n\nimport { isHistoryStoreEnabled } from \"./history.platform\"\n\nexport const restHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof restHistoryStore\n> = {\n async addEntry({ entry }) {\n if (!isHistoryStoreEnabled.value) {\n return\n }\n\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.responseMeta),\n ReqType.Rest\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateRestHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n deleteAllUserHistory(ReqType.Rest)\n },\n}\n\nexport const gqlHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof graphqlHistoryStore\n> = {\n async addEntry({ entry }) {\n if (!isHistoryStoreEnabled.value) {\n return\n }\n\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.response),\n ReqType.Gql\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateGraphqlHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {", "text": "<|original_code|>\n removeDuplicateRestHistoryEntry,\n removeDuplicateGraphqlHistoryEntry,\n restHistoryStore,\n} from \"@hoppscotch/common/newstore/history\"\nimport {\n getSettingSubject,\n settingsStore,\n} from \"@hoppscotch/common/newstore/settings\"\n\nimport { getSyncInitFunction } from \"../../lib/sync\"\n\nimport * as E from \"fp-ts/Either\"\n\nimport { StoreSyncDefinitionOf } from \"../../lib/sync\"\nimport {\n createUserHistory,\n deleteAllUserHistory,\n removeRequestFromHistory,\n toggleHistoryStarStatus,\n} from \"./history.api\"\nimport { ReqType } from \"../../api/generated/graphql\"\n\nexport const restHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof restHistoryStore\n> = {\n async addEntry({ entry }) {\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.responseMeta),\n ReqType.Rest\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateRestHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n deleteAllUserHistory(ReqType.Rest)\n },\n}\n\nexport const gqlHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof graphqlHistoryStore\n> = {\n async addEntry({ entry }) {\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.response),\n ReqType.Gql\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateGraphqlHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n<|edits_diff|>\n--- packages/hoppscotch-selfhost-web/src/platform/history/history.sync.ts\n+++ packages/hoppscotch-selfhost-web/src/platform/history/history.sync.ts\n@@ -20,10 +20,16 @@\n } from \"./history.api\"\n import { ReqType } from \"../../api/generated/graphql\"\n \n+import { isHistoryStoreEnabled } from \"./history.platform\"\n+\n export const restHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof restHistoryStore\n > = {\n async addEntry({ entry }) {\n+ if (!isHistoryStoreEnabled.value) {\n+ return\n+ }\n+\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.responseMeta),\n<|current_version|>\n removeDuplicateRestHistoryEntry,\n removeDuplicateGraphqlHistoryEntry,\n restHistoryStore,\n} from \"@hoppscotch/common/newstore/history\"\nimport {\n getSettingSubject,\n settingsStore,\n} from \"@hoppscotch/common/newstore/settings\"\n\nimport { getSyncInitFunction } from \"../../lib/sync\"\n\nimport * as E from \"fp-ts/Either\"\n\nimport { StoreSyncDefinitionOf } from \"../../lib/sync\"\nimport {\n createUserHistory,\n deleteAllUserHistory,\n removeRequestFromHistory,\n toggleHistoryStarStatus,\n} from \"./history.api\"\nimport { ReqType } from \"../../api/generated/graphql\"\n\nimport { isHistoryStoreEnabled } from \"./history.platform\"\n\nexport const restHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof restHistoryStore\n> = {\n async addEntry({ entry }) {\n if (!isHistoryStoreEnabled.value) {\n return\n }\n\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.responseMeta),\n ReqType.Rest\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateRestHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n deleteAllUserHistory(ReqType.Rest)\n },\n}\n\nexport const gqlHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof graphqlHistoryStore\n> = {\n async addEntry({ entry }) {\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.response),\n ReqType.Gql\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateGraphqlHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n<|next_version|>\n removeDuplicateRestHistoryEntry,\n removeDuplicateGraphqlHistoryEntry,\n restHistoryStore,\n} from \"@hoppscotch/common/newstore/history\"\nimport {\n getSettingSubject,\n settingsStore,\n} from \"@hoppscotch/common/newstore/settings\"\n\nimport { getSyncInitFunction } from \"../../lib/sync\"\n\nimport * as E from \"fp-ts/Either\"\n\nimport { StoreSyncDefinitionOf } from \"../../lib/sync\"\nimport {\n createUserHistory,\n deleteAllUserHistory,\n removeRequestFromHistory,\n toggleHistoryStarStatus,\n} from \"./history.api\"\nimport { ReqType } from \"../../api/generated/graphql\"\n\nimport { isHistoryStoreEnabled } from \"./history.platform\"\n\nexport const restHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof restHistoryStore\n> = {\n async addEntry({ entry }) {\n if (!isHistoryStoreEnabled.value) {\n return\n }\n\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.responseMeta),\n ReqType.Rest\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateRestHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n deleteAllUserHistory(ReqType.Rest)\n },\n}\n\nexport const gqlHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof graphqlHistoryStore\n> = {\n async addEntry({ entry }) {\n if (!isHistoryStoreEnabled.value) {\n return\n }\n\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.response),\n ReqType.Gql\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateGraphqlHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n", "current_contents": " removeDuplicateRestHistoryEntry,\n removeDuplicateGraphqlHistoryEntry,\n restHistoryStore,\n} from \"@hoppscotch/common/newstore/history\"\nimport {\n getSettingSubject,\n settingsStore,\n} from \"@hoppscotch/common/newstore/settings\"\n\nimport { getSyncInitFunction } from \"../../lib/sync\"\n\nimport * as E from \"fp-ts/Either\"\n\nimport { StoreSyncDefinitionOf } from \"../../lib/sync\"\nimport {\n createUserHistory,\n deleteAllUserHistory,\n removeRequestFromHistory,\n toggleHistoryStarStatus,\n} from \"./history.api\"\nimport { ReqType } from \"../../api/generated/graphql\"\n\nimport { isHistoryStoreEnabled } from \"./history.platform\"\n\nexport const restHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof restHistoryStore\n> = {\n async addEntry({ entry }) {\n if (!isHistoryStoreEnabled.value) {\n return\n }\n\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.responseMeta),\n ReqType.Rest\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateRestHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {\n deleteAllUserHistory(ReqType.Rest)\n },\n}\n\nexport const gqlHistoryStoreSyncDefinition: StoreSyncDefinitionOf<\n typeof graphqlHistoryStore\n> = {\n async addEntry({ entry }) {\n const res = await createUserHistory(\n JSON.stringify(entry.request),\n JSON.stringify(entry.response),\n ReqType.Gql\n )\n\n if (E.isRight(res)) {\n entry.id = res.right.createUserHistory.id\n\n // preventing double insertion from here and subscription\n removeDuplicateGraphqlHistoryEntry(entry.id)\n }\n },\n deleteEntry({ entry }) {\n if (entry.id) {\n removeRequestFromHistory(entry.id)\n }\n },\n toggleStar({ entry }) {\n if (entry.id) {\n toggleHistoryStarStatus(entry.id)\n }\n },\n clearHistory() {"} {"commit": "e30a6c9db5a6d683bc8ee0eeccfe5e6108d9f18f", "message": "feat(backend): add the ability to disable tracking request history (#4594)", "old_file": "packages/hoppscotch-backend/src/admin/admin.module.ts", "new_file": "packages/hoppscotch-backend/src/admin/admin.module.ts", "status": "M", "old_contents": "import { Module } from '@nestjs/common';\nimport { AdminResolver } from './admin.resolver';\nimport { AdminService } from './admin.service';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { UserModule } from '../user/user.module';\nimport { TeamModule } from '../team/team.module';\nimport { TeamInvitationModule } from '../team-invitation/team-invitation.module';\nimport { TeamEnvironmentsModule } from '../team-environments/team-environments.module';\nimport { TeamCollectionModule } from '../team-collection/team-collection.module';\nimport { TeamRequestModule } from '../team-request/team-request.module';\nimport { InfraResolver } from './infra.resolver';\nimport { ShortcodeModule } from 'src/shortcode/shortcode.module';\nimport { InfraConfigModule } from 'src/infra-config/infra-config.module';\n\n@Module({\n imports: [\n PrismaModule,\n PubSubModule,\n UserModule,\n TeamModule,\n TeamInvitationModule,\n TeamEnvironmentsModule,\n TeamCollectionModule,\n TeamRequestModule,\n ShortcodeModule,\n InfraConfigModule,\n ],\n providers: [InfraResolver, AdminResolver, AdminService],\n exports: [AdminService],\n})\nexport class AdminModule {}\n", "new_contents": "import { Module } from '@nestjs/common';\nimport { AdminResolver } from './admin.resolver';\nimport { AdminService } from './admin.service';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { UserModule } from '../user/user.module';\nimport { TeamModule } from '../team/team.module';\nimport { TeamInvitationModule } from '../team-invitation/team-invitation.module';\nimport { TeamEnvironmentsModule } from '../team-environments/team-environments.module';\nimport { TeamCollectionModule } from '../team-collection/team-collection.module';\nimport { TeamRequestModule } from '../team-request/team-request.module';\nimport { InfraResolver } from './infra.resolver';\nimport { ShortcodeModule } from 'src/shortcode/shortcode.module';\nimport { InfraConfigModule } from 'src/infra-config/infra-config.module';\nimport { UserHistoryModule } from 'src/user-history/user-history.module';\n\n@Module({\n imports: [\n PrismaModule,\n PubSubModule,\n UserModule,\n TeamModule,\n TeamInvitationModule,\n TeamEnvironmentsModule,\n TeamCollectionModule,\n TeamRequestModule,\n ShortcodeModule,\n InfraConfigModule,\n UserHistoryModule,\n ],\n providers: [InfraResolver, AdminResolver, AdminService],\n exports: [AdminService],\n})\nexport class AdminModule {}\n", "text": "<|original_code|>\nimport { Module } from '@nestjs/common';\nimport { AdminResolver } from './admin.resolver';\nimport { AdminService } from './admin.service';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { UserModule } from '../user/user.module';\nimport { TeamModule } from '../team/team.module';\nimport { TeamInvitationModule } from '../team-invitation/team-invitation.module';\nimport { TeamEnvironmentsModule } from '../team-environments/team-environments.module';\nimport { TeamCollectionModule } from '../team-collection/team-collection.module';\nimport { TeamRequestModule } from '../team-request/team-request.module';\nimport { InfraResolver } from './infra.resolver';\nimport { ShortcodeModule } from 'src/shortcode/shortcode.module';\nimport { InfraConfigModule } from 'src/infra-config/infra-config.module';\n\n@Module({\n imports: [\n PrismaModule,\n PubSubModule,\n UserModule,\n TeamModule,\n TeamInvitationModule,\n TeamEnvironmentsModule,\n TeamCollectionModule,\n TeamRequestModule,\n ShortcodeModule,\n InfraConfigModule,\n ],\n providers: [InfraResolver, AdminResolver, AdminService],\n exports: [AdminService],\n})\nexport class AdminModule {}\n\n<|edits_diff|>\n--- packages/hoppscotch-backend/src/admin/admin.module.ts\n+++ packages/hoppscotch-backend/src/admin/admin.module.ts\n@@ -12,6 +12,7 @@\n import { InfraResolver } from './infra.resolver';\n import { ShortcodeModule } from 'src/shortcode/shortcode.module';\n import { InfraConfigModule } from 'src/infra-config/infra-config.module';\n+import { UserHistoryModule } from 'src/user-history/user-history.module';\n \n @Module({\n imports: [\n<|current_version|>\nimport { Module } from '@nestjs/common';\nimport { AdminResolver } from './admin.resolver';\nimport { AdminService } from './admin.service';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { UserModule } from '../user/user.module';\nimport { TeamModule } from '../team/team.module';\nimport { TeamInvitationModule } from '../team-invitation/team-invitation.module';\nimport { TeamEnvironmentsModule } from '../team-environments/team-environments.module';\nimport { TeamCollectionModule } from '../team-collection/team-collection.module';\nimport { TeamRequestModule } from '../team-request/team-request.module';\nimport { InfraResolver } from './infra.resolver';\nimport { ShortcodeModule } from 'src/shortcode/shortcode.module';\nimport { InfraConfigModule } from 'src/infra-config/infra-config.module';\nimport { UserHistoryModule } from 'src/user-history/user-history.module';\n\n@Module({\n imports: [\n PrismaModule,\n PubSubModule,\n UserModule,\n TeamModule,\n TeamInvitationModule,\n TeamEnvironmentsModule,\n TeamCollectionModule,\n TeamRequestModule,\n ShortcodeModule,\n InfraConfigModule,\n ],\n providers: [InfraResolver, AdminResolver, AdminService],\n exports: [AdminService],\n})\nexport class AdminModule {}\n\n<|next_version|>\nimport { Module } from '@nestjs/common';\nimport { AdminResolver } from './admin.resolver';\nimport { AdminService } from './admin.service';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { UserModule } from '../user/user.module';\nimport { TeamModule } from '../team/team.module';\nimport { TeamInvitationModule } from '../team-invitation/team-invitation.module';\nimport { TeamEnvironmentsModule } from '../team-environments/team-environments.module';\nimport { TeamCollectionModule } from '../team-collection/team-collection.module';\nimport { TeamRequestModule } from '../team-request/team-request.module';\nimport { InfraResolver } from './infra.resolver';\nimport { ShortcodeModule } from 'src/shortcode/shortcode.module';\nimport { InfraConfigModule } from 'src/infra-config/infra-config.module';\nimport { UserHistoryModule } from 'src/user-history/user-history.module';\n\n@Module({\n imports: [\n PrismaModule,\n PubSubModule,\n UserModule,\n TeamModule,\n TeamInvitationModule,\n TeamEnvironmentsModule,\n TeamCollectionModule,\n TeamRequestModule,\n ShortcodeModule,\n InfraConfigModule,\n UserHistoryModule,\n ],\n providers: [InfraResolver, AdminResolver, AdminService],\n exports: [AdminService],\n})\nexport class AdminModule {}\n\n", "current_contents": "import { Module } from '@nestjs/common';\nimport { AdminResolver } from './admin.resolver';\nimport { AdminService } from './admin.service';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { UserModule } from '../user/user.module';\nimport { TeamModule } from '../team/team.module';\nimport { TeamInvitationModule } from '../team-invitation/team-invitation.module';\nimport { TeamEnvironmentsModule } from '../team-environments/team-environments.module';\nimport { TeamCollectionModule } from '../team-collection/team-collection.module';\nimport { TeamRequestModule } from '../team-request/team-request.module';\nimport { InfraResolver } from './infra.resolver';\nimport { ShortcodeModule } from 'src/shortcode/shortcode.module';\nimport { InfraConfigModule } from 'src/infra-config/infra-config.module';\nimport { UserHistoryModule } from 'src/user-history/user-history.module';\n\n@Module({\n imports: [\n PrismaModule,\n PubSubModule,\n UserModule,\n TeamModule,\n TeamInvitationModule,\n TeamEnvironmentsModule,\n TeamCollectionModule,\n TeamRequestModule,\n ShortcodeModule,\n InfraConfigModule,\n ],\n providers: [InfraResolver, AdminResolver, AdminService],\n exports: [AdminService],\n})\nexport class AdminModule {}\n"} {"commit": "b706a43d2ee0427f1b7e61d22ca96e25d265a442", "message": "feat: collection import summaries (#4489)", "old_file": "packages/hoppscotch-common/src/helpers/import-export/import/import-sources/FileSource.ts", "new_file": "packages/hoppscotch-common/src/helpers/import-export/import/import-sources/FileSource.ts", "status": "M", "old_contents": "import FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n loading: metadata.isLoading?.value,\n }))\n}\n", "new_contents": "import FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n description?: string\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n loading: metadata.isLoading?.value,\n description: metadata.description,\n }))\n}\n", "text": "<|original_code|>\nimport FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n loading: metadata.isLoading?.value,\n }))\n}\n\n<|edits_diff|>\n--- packages/hoppscotch-common/src/helpers/import-export/import/import-sources/FileSource.ts\n+++ packages/hoppscotch-common/src/helpers/import-export/import/import-sources/FileSource.ts\n@@ -9,6 +9,7 @@\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n+ description?: string\n }) {\n const stepID = uuidv4()\n \n<|current_version|>\nimport FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n description?: string\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n loading: metadata.isLoading?.value,\n }))\n}\n\n<|next_version|>\nimport FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n description?: string\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n loading: metadata.isLoading?.value,\n description: metadata.description,\n }))\n}\n\n", "current_contents": "import FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n description?: string\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n loading: metadata.isLoading?.value,\n }))\n}\n"} {"commit": "1701961335b443d777c0d1d2336f02e075575d8d", "message": "feat: add loading state for import actions (#4217)", "old_file": "packages/hoppscotch-common/src/helpers/import-export/import/import-sources/FileSource.ts", "new_file": "packages/hoppscotch-common/src/helpers/import-export/import/import-sources/FileSource.ts", "status": "M", "old_contents": "import FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n }))\n}\n", "new_contents": "import FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n loading: metadata.isLoading?.value,\n }))\n}\n", "text": "<|original_code|>\nimport FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n }))\n}\n\n<|edits_diff|>\n--- packages/hoppscotch-common/src/helpers/import-export/import/import-sources/FileSource.ts\n+++ packages/hoppscotch-common/src/helpers/import-export/import/import-sources/FileSource.ts\n@@ -2,11 +2,13 @@\n import { defineStep } from \"~/composables/step-components\"\n \n import { v4 as uuidv4 } from \"uuid\"\n+import { Ref } from \"vue\"\n \n export function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n+ isLoading?: Ref\n }) {\n const stepID = uuidv4()\n \n<|current_version|>\nimport FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n }))\n}\n\n<|next_version|>\nimport FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n loading: metadata.isLoading?.value,\n }))\n}\n\n", "current_contents": "import FileImportVue from \"~/components/importExport/ImportExportSteps/FileImport.vue\"\nimport { defineStep } from \"~/composables/step-components\"\n\nimport { v4 as uuidv4 } from \"uuid\"\nimport { Ref } from \"vue\"\n\nexport function FileSource(metadata: {\n acceptedFileTypes: string\n caption: string\n onImportFromFile: (content: string[]) => any | Promise\n isLoading?: Ref\n}) {\n const stepID = uuidv4()\n\n return defineStep(stepID, FileImportVue, () => ({\n acceptedFileTypes: metadata.acceptedFileTypes,\n caption: metadata.caption,\n onImportFromFile: metadata.onImportFromFile,\n }))\n}\n"} {"commit": "783d911f8d64e43850265e217fb601bc6cfbc562", "message": "HSB-462 feat: infra token module and sh apis (#4191)", "old_file": "packages/hoppscotch-backend/src/types/input-types.args.ts", "new_file": "packages/hoppscotch-backend/src/types/input-types.args.ts", "status": "M", "old_contents": "import { ArgsType, Field, ID, InputType } from '@nestjs/graphql';\n\n@ArgsType()\n@InputType()\nexport class PaginationArgs {\n @Field(() => ID, {\n nullable: true,\n defaultValue: undefined,\n description: 'Cursor for pagination, ID of the last item in the list',\n })\n cursor: string;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n@ArgsType()\n@InputType()\nexport class OffsetPaginationArgs {\n @Field({\n nullable: true,\n defaultValue: 0,\n description: 'Number of items to skip',\n })\n skip: number;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n", "new_contents": "import { ArgsType, Field, ID, InputType } from '@nestjs/graphql';\nimport { ApiPropertyOptional } from '@nestjs/swagger';\nimport { Type } from 'class-transformer';\nimport { IsNotEmpty, IsOptional } from 'class-validator';\n\n@ArgsType()\n@InputType()\nexport class PaginationArgs {\n @Field(() => ID, {\n nullable: true,\n defaultValue: undefined,\n description: 'Cursor for pagination, ID of the last item in the list',\n })\n cursor: string;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n@ArgsType()\n@InputType()\nexport class OffsetPaginationArgs {\n @IsOptional()\n @IsNotEmpty()\n @Type(() => Number)\n @ApiPropertyOptional()\n @Field({\n nullable: true,\n defaultValue: 0,\n description: 'Number of items to skip',\n })\n skip: number;\n\n @IsOptional()\n @IsNotEmpty()\n @Type(() => Number)\n @ApiPropertyOptional()\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n", "text": "<|original_code|>\nimport { ArgsType, Field, ID, InputType } from '@nestjs/graphql';\n\n@ArgsType()\n@InputType()\nexport class PaginationArgs {\n @Field(() => ID, {\n nullable: true,\n defaultValue: undefined,\n description: 'Cursor for pagination, ID of the last item in the list',\n })\n cursor: string;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n@ArgsType()\n@InputType()\nexport class OffsetPaginationArgs {\n @Field({\n nullable: true,\n defaultValue: 0,\n description: 'Number of items to skip',\n })\n skip: number;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n<|edits_diff|>\n--- packages/hoppscotch-backend/src/types/input-types.args.ts\n+++ packages/hoppscotch-backend/src/types/input-types.args.ts\n@@ -1,4 +1,7 @@\n import { ArgsType, Field, ID, InputType } from '@nestjs/graphql';\n+import { ApiPropertyOptional } from '@nestjs/swagger';\n+import { Type } from 'class-transformer';\n+import { IsNotEmpty, IsOptional } from 'class-validator';\n \n @ArgsType()\n @InputType()\n@@ -21,6 +24,10 @@\n @ArgsType()\n @InputType()\n export class OffsetPaginationArgs {\n+ @IsOptional()\n+ @IsNotEmpty()\n+ @Type(() => Number)\n+ @ApiPropertyOptional()\n @Field({\n nullable: true,\n defaultValue: 0,\n<|current_version|>\nimport { ArgsType, Field, ID, InputType } from '@nestjs/graphql';\nimport { ApiPropertyOptional } from '@nestjs/swagger';\nimport { Type } from 'class-transformer';\nimport { IsNotEmpty, IsOptional } from 'class-validator';\n\n@ArgsType()\n@InputType()\nexport class PaginationArgs {\n @Field(() => ID, {\n nullable: true,\n defaultValue: undefined,\n description: 'Cursor for pagination, ID of the last item in the list',\n })\n cursor: string;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n@ArgsType()\n@InputType()\nexport class OffsetPaginationArgs {\n @IsOptional()\n @IsNotEmpty()\n @Type(() => Number)\n @ApiPropertyOptional()\n @Field({\n nullable: true,\n defaultValue: 0,\n description: 'Number of items to skip',\n })\n skip: number;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n<|next_version|>\nimport { ArgsType, Field, ID, InputType } from '@nestjs/graphql';\nimport { ApiPropertyOptional } from '@nestjs/swagger';\nimport { Type } from 'class-transformer';\nimport { IsNotEmpty, IsOptional } from 'class-validator';\n\n@ArgsType()\n@InputType()\nexport class PaginationArgs {\n @Field(() => ID, {\n nullable: true,\n defaultValue: undefined,\n description: 'Cursor for pagination, ID of the last item in the list',\n })\n cursor: string;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n@ArgsType()\n@InputType()\nexport class OffsetPaginationArgs {\n @IsOptional()\n @IsNotEmpty()\n @Type(() => Number)\n @ApiPropertyOptional()\n @Field({\n nullable: true,\n defaultValue: 0,\n description: 'Number of items to skip',\n })\n skip: number;\n\n @IsOptional()\n @IsNotEmpty()\n @Type(() => Number)\n @ApiPropertyOptional()\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n", "current_contents": "import { ArgsType, Field, ID, InputType } from '@nestjs/graphql';\nimport { ApiPropertyOptional } from '@nestjs/swagger';\nimport { Type } from 'class-transformer';\nimport { IsNotEmpty, IsOptional } from 'class-validator';\n\n@ArgsType()\n@InputType()\nexport class PaginationArgs {\n @Field(() => ID, {\n nullable: true,\n defaultValue: undefined,\n description: 'Cursor for pagination, ID of the last item in the list',\n })\n cursor: string;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n\n@ArgsType()\n@InputType()\nexport class OffsetPaginationArgs {\n @IsOptional()\n @IsNotEmpty()\n @Type(() => Number)\n @ApiPropertyOptional()\n @Field({\n nullable: true,\n defaultValue: 0,\n description: 'Number of items to skip',\n })\n skip: number;\n\n @Field({\n nullable: true,\n defaultValue: 10,\n description: 'Number of items to fetch',\n })\n take: number;\n}\n"} {"commit": "a0c6b22641190bf742ff7a7c7f9431576ceeca5a", "message": "feat: full text search for `TeamCollections` and `TeamRequests` (#3857)", "old_file": "packages/hoppscotch-backend/src/team-collection/team-collection.module.ts", "new_file": "packages/hoppscotch-backend/src/team-collection/team-collection.module.ts", "status": "M", "old_contents": "import { Module } from '@nestjs/common';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { TeamCollectionService } from './team-collection.service';\nimport { TeamCollectionResolver } from './team-collection.resolver';\nimport { GqlCollectionTeamMemberGuard } from './guards/gql-collection-team-member.guard';\nimport { TeamModule } from '../team/team.module';\nimport { UserModule } from '../user/user.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\n\n@Module({\n imports: [PrismaModule, TeamModule, UserModule, PubSubModule],\n providers: [\n TeamCollectionService,\n TeamCollectionResolver,\n GqlCollectionTeamMemberGuard,\n ],\n exports: [TeamCollectionService, GqlCollectionTeamMemberGuard],\n})\nexport class TeamCollectionModule {}\n", "new_contents": "import { Module } from '@nestjs/common';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { TeamCollectionService } from './team-collection.service';\nimport { TeamCollectionResolver } from './team-collection.resolver';\nimport { GqlCollectionTeamMemberGuard } from './guards/gql-collection-team-member.guard';\nimport { TeamModule } from '../team/team.module';\nimport { UserModule } from '../user/user.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { TeamCollectionController } from './team-collection.controller';\n\n@Module({\n imports: [PrismaModule, TeamModule, UserModule, PubSubModule],\n providers: [\n TeamCollectionService,\n TeamCollectionResolver,\n GqlCollectionTeamMemberGuard,\n ],\n exports: [TeamCollectionService, GqlCollectionTeamMemberGuard],\n controllers: [TeamCollectionController],\n})\nexport class TeamCollectionModule {}\n", "text": "<|original_code|>\nimport { Module } from '@nestjs/common';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { TeamCollectionService } from './team-collection.service';\nimport { TeamCollectionResolver } from './team-collection.resolver';\nimport { GqlCollectionTeamMemberGuard } from './guards/gql-collection-team-member.guard';\nimport { TeamModule } from '../team/team.module';\nimport { UserModule } from '../user/user.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\n\n@Module({\n imports: [PrismaModule, TeamModule, UserModule, PubSubModule],\n providers: [\n TeamCollectionService,\n TeamCollectionResolver,\n GqlCollectionTeamMemberGuard,\n ],\n exports: [TeamCollectionService, GqlCollectionTeamMemberGuard],\n})\nexport class TeamCollectionModule {}\n\n<|edits_diff|>\n--- packages/hoppscotch-backend/src/team-collection/team-collection.module.ts\n+++ packages/hoppscotch-backend/src/team-collection/team-collection.module.ts\n@@ -6,6 +6,7 @@\n import { TeamModule } from '../team/team.module';\n import { UserModule } from '../user/user.module';\n import { PubSubModule } from '../pubsub/pubsub.module';\n+import { TeamCollectionController } from './team-collection.controller';\n \n @Module({\n imports: [PrismaModule, TeamModule, UserModule, PubSubModule],\n<|current_version|>\nimport { Module } from '@nestjs/common';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { TeamCollectionService } from './team-collection.service';\nimport { TeamCollectionResolver } from './team-collection.resolver';\nimport { GqlCollectionTeamMemberGuard } from './guards/gql-collection-team-member.guard';\nimport { TeamModule } from '../team/team.module';\nimport { UserModule } from '../user/user.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { TeamCollectionController } from './team-collection.controller';\n\n@Module({\n imports: [PrismaModule, TeamModule, UserModule, PubSubModule],\n providers: [\n TeamCollectionService,\n TeamCollectionResolver,\n GqlCollectionTeamMemberGuard,\n ],\n exports: [TeamCollectionService, GqlCollectionTeamMemberGuard],\n})\nexport class TeamCollectionModule {}\n\n<|next_version|>\nimport { Module } from '@nestjs/common';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { TeamCollectionService } from './team-collection.service';\nimport { TeamCollectionResolver } from './team-collection.resolver';\nimport { GqlCollectionTeamMemberGuard } from './guards/gql-collection-team-member.guard';\nimport { TeamModule } from '../team/team.module';\nimport { UserModule } from '../user/user.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { TeamCollectionController } from './team-collection.controller';\n\n@Module({\n imports: [PrismaModule, TeamModule, UserModule, PubSubModule],\n providers: [\n TeamCollectionService,\n TeamCollectionResolver,\n GqlCollectionTeamMemberGuard,\n ],\n exports: [TeamCollectionService, GqlCollectionTeamMemberGuard],\n controllers: [TeamCollectionController],\n})\nexport class TeamCollectionModule {}\n\n", "current_contents": "import { Module } from '@nestjs/common';\nimport { PrismaModule } from '../prisma/prisma.module';\nimport { TeamCollectionService } from './team-collection.service';\nimport { TeamCollectionResolver } from './team-collection.resolver';\nimport { GqlCollectionTeamMemberGuard } from './guards/gql-collection-team-member.guard';\nimport { TeamModule } from '../team/team.module';\nimport { UserModule } from '../user/user.module';\nimport { PubSubModule } from '../pubsub/pubsub.module';\nimport { TeamCollectionController } from './team-collection.controller';\n\n@Module({\n imports: [PrismaModule, TeamModule, UserModule, PubSubModule],\n providers: [\n TeamCollectionService,\n TeamCollectionResolver,\n GqlCollectionTeamMemberGuard,\n ],\n exports: [TeamCollectionService, GqlCollectionTeamMemberGuard],\n})\nexport class TeamCollectionModule {}\n"} {"commit": "defece95fc5f2fa3f6c961bdabd399b1c4fbf749", "message": "feat: rest revamp (#2918)", "old_file": "packages/hoppscotch-web/src/main.ts", "new_file": "packages/hoppscotch-web/src/main.ts", "status": "M", "old_contents": "import { createHoppApp } from \"@hoppscotch/common\"\nimport { def as authDef } from \"./firebase/auth\"\nimport { def as envDef } from \"./environments\"\nimport { def as collectionsDef } from \"./collections\"\nimport { def as settingsDef } from \"./settings\"\nimport { def as historyDef } from \"./history\"\n\ncreateHoppApp(\"#app\", {\n auth: authDef,\n sync: {\n environments: envDef,\n collections: collectionsDef,\n settings: settingsDef,\n history: historyDef,\n },\n})\n", "new_contents": "import { createHoppApp } from \"@hoppscotch/common\"\nimport { def as authDef } from \"./firebase/auth\"\nimport { def as envDef } from \"./environments\"\nimport { def as collectionsDef } from \"./collections\"\nimport { def as settingsDef } from \"./settings\"\nimport { def as historyDef } from \"./history\"\nimport { def as tabStateDef } from \"./tab\"\n\ncreateHoppApp(\"#app\", {\n auth: authDef,\n sync: {\n environments: envDef,\n collections: collectionsDef,\n settings: settingsDef,\n history: historyDef,\n tabState: tabStateDef,\n },\n})\n", "text": "<|original_code|>\nimport { createHoppApp } from \"@hoppscotch/common\"\nimport { def as authDef } from \"./firebase/auth\"\nimport { def as envDef } from \"./environments\"\nimport { def as collectionsDef } from \"./collections\"\nimport { def as settingsDef } from \"./settings\"\nimport { def as historyDef } from \"./history\"\n\ncreateHoppApp(\"#app\", {\n auth: authDef,\n sync: {\n environments: envDef,\n collections: collectionsDef,\n settings: settingsDef,\n history: historyDef,\n },\n})\n\n<|edits_diff|>\n--- packages/hoppscotch-web/src/main.ts\n+++ packages/hoppscotch-web/src/main.ts\n@@ -4,6 +4,7 @@\n import { def as collectionsDef } from \"./collections\"\n import { def as settingsDef } from \"./settings\"\n import { def as historyDef } from \"./history\"\n+import { def as tabStateDef } from \"./tab\"\n \n createHoppApp(\"#app\", {\n auth: authDef,\n<|current_version|>\nimport { createHoppApp } from \"@hoppscotch/common\"\nimport { def as authDef } from \"./firebase/auth\"\nimport { def as envDef } from \"./environments\"\nimport { def as collectionsDef } from \"./collections\"\nimport { def as settingsDef } from \"./settings\"\nimport { def as historyDef } from \"./history\"\nimport { def as tabStateDef } from \"./tab\"\n\ncreateHoppApp(\"#app\", {\n auth: authDef,\n sync: {\n environments: envDef,\n collections: collectionsDef,\n settings: settingsDef,\n history: historyDef,\n },\n})\n\n<|next_version|>\nimport { createHoppApp } from \"@hoppscotch/common\"\nimport { def as authDef } from \"./firebase/auth\"\nimport { def as envDef } from \"./environments\"\nimport { def as collectionsDef } from \"./collections\"\nimport { def as settingsDef } from \"./settings\"\nimport { def as historyDef } from \"./history\"\nimport { def as tabStateDef } from \"./tab\"\n\ncreateHoppApp(\"#app\", {\n auth: authDef,\n sync: {\n environments: envDef,\n collections: collectionsDef,\n settings: settingsDef,\n history: historyDef,\n tabState: tabStateDef,\n },\n})\n\n", "current_contents": "import { createHoppApp } from \"@hoppscotch/common\"\nimport { def as authDef } from \"./firebase/auth\"\nimport { def as envDef } from \"./environments\"\nimport { def as collectionsDef } from \"./collections\"\nimport { def as settingsDef } from \"./settings\"\nimport { def as historyDef } from \"./history\"\nimport { def as tabStateDef } from \"./tab\"\n\ncreateHoppApp(\"#app\", {\n auth: authDef,\n sync: {\n environments: envDef,\n collections: collectionsDef,\n settings: settingsDef,\n history: historyDef,\n },\n})\n"} {"commit": "7e686a8882c1f97ca7ae04edf1e3941688752891", "message": "feat: global workspace selector (#2922)", "old_file": "packages/hoppscotch-common/src/helpers/teams/TeamListAdapter.ts", "new_file": "packages/hoppscotch-common/src/helpers/teams/TeamListAdapter.ts", "status": "M", "old_contents": "import * as E from \"fp-ts/Either\"\nimport { BehaviorSubject } from \"rxjs\"\nimport { GQLError, runGQLQuery } from \"../backend/GQLClient\"\nimport { GetMyTeamsDocument, GetMyTeamsQuery } from \"../backend/graphql\"\nimport { platform } from \"~/platform\"\n\nconst BACKEND_PAGE_SIZE = 10\nconst POLL_DURATION = 10000\n\nexport default class TeamListAdapter {\n error$: BehaviorSubject | null>\n loading$: BehaviorSubject\n teamList$: BehaviorSubject\n\n private timeoutHandle: ReturnType | null\n private isDispose: boolean\n\n constructor(deferInit = false) {\n this.error$ = new BehaviorSubject | null>(null)\n this.loading$ = new BehaviorSubject(false)\n this.teamList$ = new BehaviorSubject([])\n this.timeoutHandle = null\n this.isDispose = false\n\n if (!deferInit) this.initialize()\n }\n\n initialize() {\n if (this.timeoutHandle) throw new Error(`Adapter already initialized`)\n if (this.isDispose) throw new Error(`Adapter has been disposed`)\n\n const func = async () => {\n await this.fetchList()\n\n if (!this.isDispose) {\n this.timeoutHandle = setTimeout(() => func(), POLL_DURATION)\n }\n }\n\n func()\n }\n\n public dispose() {\n this.isDispose = true\n clearTimeout(this.timeoutHandle as any)\n this.timeoutHandle = null\n }\n\n async fetchList() {\n const currentUser = platform.auth.getCurrentUser()\n\n // if the authIdToken is not present, don't fetch the teams list, as it will fail anyway\n if (!currentUser) return\n\n this.loading$.next(true)\n\n const results: GetMyTeamsQuery[\"myTeams\"] = []\n\n while (true) {\n const result = await runGQLQuery({\n query: GetMyTeamsDocument,\n variables: {\n cursor:\n results.length > 0 ? results[results.length - 1].id : undefined,\n },\n })\n\n if (E.isLeft(result)) {\n this.error$.next(result.left)\n throw new Error(", "new_contents": "import * as E from \"fp-ts/Either\"\nimport { BehaviorSubject } from \"rxjs\"\nimport { GQLError, runGQLQuery } from \"../backend/GQLClient\"\nimport { GetMyTeamsDocument, GetMyTeamsQuery } from \"../backend/graphql\"\nimport { platform } from \"~/platform\"\n\nconst BACKEND_PAGE_SIZE = 10\nconst POLL_DURATION = 10000\n\nexport default class TeamListAdapter {\n error$: BehaviorSubject | null>\n loading$: BehaviorSubject\n teamList$: BehaviorSubject\n\n private timeoutHandle: ReturnType | null\n private isDispose: boolean\n\n public isInitialized: boolean\n\n constructor(deferInit = false) {\n this.error$ = new BehaviorSubject | null>(null)\n this.loading$ = new BehaviorSubject(false)\n this.teamList$ = new BehaviorSubject([])\n this.timeoutHandle = null\n this.isDispose = false\n\n this.isInitialized = false\n\n if (!deferInit) this.initialize()\n }\n\n initialize() {\n if (this.timeoutHandle) throw new Error(`Adapter already initialized`)\n if (this.isDispose) throw new Error(`Adapter has been disposed`)\n\n this.isInitialized = true\n\n const func = async () => {\n await this.fetchList()\n\n if (!this.isDispose) {\n this.timeoutHandle = setTimeout(() => func(), POLL_DURATION)\n }\n }\n\n func()\n }\n\n public dispose() {\n this.isDispose = true\n clearTimeout(this.timeoutHandle as any)\n this.timeoutHandle = null\n this.isInitialized = false\n }\n\n async fetchList() {\n const currentUser = platform.auth.getCurrentUser()\n\n // if the authIdToken is not present, don't fetch the teams list, as it will fail anyway\n if (!currentUser) return\n\n this.loading$.next(true)\n\n const results: GetMyTeamsQuery[\"myTeams\"] = []\n\n while (true) {\n const result = await runGQLQuery({\n query: GetMyTeamsDocument,\n variables: {\n cursor:\n results.length > 0 ? results[results.length - 1].id : undefined,\n },\n })\n\n if (E.isLeft(result)) {\n this.error$.next(result.left)\n throw new Error(", "text": "<|original_code|>\nimport * as E from \"fp-ts/Either\"\nimport { BehaviorSubject } from \"rxjs\"\nimport { GQLError, runGQLQuery } from \"../backend/GQLClient\"\nimport { GetMyTeamsDocument, GetMyTeamsQuery } from \"../backend/graphql\"\nimport { platform } from \"~/platform\"\n\nconst BACKEND_PAGE_SIZE = 10\nconst POLL_DURATION = 10000\n\nexport default class TeamListAdapter {\n error$: BehaviorSubject | null>\n loading$: BehaviorSubject\n teamList$: BehaviorSubject\n\n private timeoutHandle: ReturnType | null\n private isDispose: boolean\n\n constructor(deferInit = false) {\n this.error$ = new BehaviorSubject | null>(null)\n this.loading$ = new BehaviorSubject(false)\n this.teamList$ = new BehaviorSubject([])\n this.timeoutHandle = null\n this.isDispose = false\n\n if (!deferInit) this.initialize()\n }\n\n initialize() {\n if (this.timeoutHandle) throw new Error(`Adapter already initialized`)\n if (this.isDispose) throw new Error(`Adapter has been disposed`)\n\n const func = async () => {\n await this.fetchList()\n\n if (!this.isDispose) {\n this.timeoutHandle = setTimeout(() => func(), POLL_DURATION)\n }\n }\n\n func()\n }\n\n public dispose() {\n this.isDispose = true\n clearTimeout(this.timeoutHandle as any)\n this.timeoutHandle = null\n }\n\n async fetchList() {\n const currentUser = platform.auth.getCurrentUser()\n\n // if the authIdToken is not present, don't fetch the teams list, as it will fail anyway\n if (!currentUser) return\n\n this.loading$.next(true)\n\n const results: GetMyTeamsQuery[\"myTeams\"] = []\n\n while (true) {\n const result = await runGQLQuery({\n query: GetMyTeamsDocument,\n variables: {\n cursor:\n results.length > 0 ? results[results.length - 1].id : undefined,\n },\n })\n\n if (E.isLeft(result)) {\n this.error$.next(result.left)\n throw new Error(\n<|edits_diff|>\n--- packages/hoppscotch-common/src/helpers/teams/TeamListAdapter.ts\n+++ packages/hoppscotch-common/src/helpers/teams/TeamListAdapter.ts\n@@ -15,6 +15,8 @@\n private timeoutHandle: ReturnType | null\n private isDispose: boolean\n \n+ public isInitialized: boolean\n+\n constructor(deferInit = false) {\n this.error$ = new BehaviorSubject | null>(null)\n this.loading$ = new BehaviorSubject(false)\n@@ -22,12 +24,16 @@\n this.timeoutHandle = null\n this.isDispose = false\n \n+ this.isInitialized = false\n+\n if (!deferInit) this.initialize()\n }\n \n initialize() {\n if (this.timeoutHandle) throw new Error(`Adapter already initialized`)\n if (this.isDispose) throw new Error(`Adapter has been disposed`)\n+\n+ this.isInitialized = true\n \n const func = async () => {\n await this.fetchList()\n<|current_version|>\nimport * as E from \"fp-ts/Either\"\nimport { BehaviorSubject } from \"rxjs\"\nimport { GQLError, runGQLQuery } from \"../backend/GQLClient\"\nimport { GetMyTeamsDocument, GetMyTeamsQuery } from \"../backend/graphql\"\nimport { platform } from \"~/platform\"\n\nconst BACKEND_PAGE_SIZE = 10\nconst POLL_DURATION = 10000\n\nexport default class TeamListAdapter {\n error$: BehaviorSubject | null>\n loading$: BehaviorSubject\n teamList$: BehaviorSubject\n\n private timeoutHandle: ReturnType | null\n private isDispose: boolean\n\n public isInitialized: boolean\n\n constructor(deferInit = false) {\n this.error$ = new BehaviorSubject | null>(null)\n this.loading$ = new BehaviorSubject(false)\n this.teamList$ = new BehaviorSubject([])\n this.timeoutHandle = null\n this.isDispose = false\n\n this.isInitialized = false\n\n if (!deferInit) this.initialize()\n }\n\n initialize() {\n if (this.timeoutHandle) throw new Error(`Adapter already initialized`)\n if (this.isDispose) throw new Error(`Adapter has been disposed`)\n\n this.isInitialized = true\n\n const func = async () => {\n await this.fetchList()\n\n if (!this.isDispose) {\n this.timeoutHandle = setTimeout(() => func(), POLL_DURATION)\n }\n }\n\n func()\n }\n\n public dispose() {\n this.isDispose = true\n clearTimeout(this.timeoutHandle as any)\n this.timeoutHandle = null\n }\n\n async fetchList() {\n const currentUser = platform.auth.getCurrentUser()\n\n // if the authIdToken is not present, don't fetch the teams list, as it will fail anyway\n if (!currentUser) return\n\n this.loading$.next(true)\n\n const results: GetMyTeamsQuery[\"myTeams\"] = []\n\n while (true) {\n const result = await runGQLQuery({\n query: GetMyTeamsDocument,\n variables: {\n cursor:\n results.length > 0 ? results[results.length - 1].id : undefined,\n },\n })\n\n if (E.isLeft(result)) {\n this.error$.next(result.left)\n throw new Error(\n<|next_version|>\nimport * as E from \"fp-ts/Either\"\nimport { BehaviorSubject } from \"rxjs\"\nimport { GQLError, runGQLQuery } from \"../backend/GQLClient\"\nimport { GetMyTeamsDocument, GetMyTeamsQuery } from \"../backend/graphql\"\nimport { platform } from \"~/platform\"\n\nconst BACKEND_PAGE_SIZE = 10\nconst POLL_DURATION = 10000\n\nexport default class TeamListAdapter {\n error$: BehaviorSubject | null>\n loading$: BehaviorSubject\n teamList$: BehaviorSubject\n\n private timeoutHandle: ReturnType | null\n private isDispose: boolean\n\n public isInitialized: boolean\n\n constructor(deferInit = false) {\n this.error$ = new BehaviorSubject | null>(null)\n this.loading$ = new BehaviorSubject(false)\n this.teamList$ = new BehaviorSubject([])\n this.timeoutHandle = null\n this.isDispose = false\n\n this.isInitialized = false\n\n if (!deferInit) this.initialize()\n }\n\n initialize() {\n if (this.timeoutHandle) throw new Error(`Adapter already initialized`)\n if (this.isDispose) throw new Error(`Adapter has been disposed`)\n\n this.isInitialized = true\n\n const func = async () => {\n await this.fetchList()\n\n if (!this.isDispose) {\n this.timeoutHandle = setTimeout(() => func(), POLL_DURATION)\n }\n }\n\n func()\n }\n\n public dispose() {\n this.isDispose = true\n clearTimeout(this.timeoutHandle as any)\n this.timeoutHandle = null\n this.isInitialized = false\n }\n\n async fetchList() {\n const currentUser = platform.auth.getCurrentUser()\n\n // if the authIdToken is not present, don't fetch the teams list, as it will fail anyway\n if (!currentUser) return\n\n this.loading$.next(true)\n\n const results: GetMyTeamsQuery[\"myTeams\"] = []\n\n while (true) {\n const result = await runGQLQuery({\n query: GetMyTeamsDocument,\n variables: {\n cursor:\n results.length > 0 ? results[results.length - 1].id : undefined,\n },\n })\n\n if (E.isLeft(result)) {\n this.error$.next(result.left)\n throw new Error(\n", "current_contents": "import * as E from \"fp-ts/Either\"\nimport { BehaviorSubject } from \"rxjs\"\nimport { GQLError, runGQLQuery } from \"../backend/GQLClient\"\nimport { GetMyTeamsDocument, GetMyTeamsQuery } from \"../backend/graphql\"\nimport { platform } from \"~/platform\"\n\nconst BACKEND_PAGE_SIZE = 10\nconst POLL_DURATION = 10000\n\nexport default class TeamListAdapter {\n error$: BehaviorSubject | null>\n loading$: BehaviorSubject\n teamList$: BehaviorSubject\n\n private timeoutHandle: ReturnType | null\n private isDispose: boolean\n\n public isInitialized: boolean\n\n constructor(deferInit = false) {\n this.error$ = new BehaviorSubject | null>(null)\n this.loading$ = new BehaviorSubject(false)\n this.teamList$ = new BehaviorSubject([])\n this.timeoutHandle = null\n this.isDispose = false\n\n this.isInitialized = false\n\n if (!deferInit) this.initialize()\n }\n\n initialize() {\n if (this.timeoutHandle) throw new Error(`Adapter already initialized`)\n if (this.isDispose) throw new Error(`Adapter has been disposed`)\n\n this.isInitialized = true\n\n const func = async () => {\n await this.fetchList()\n\n if (!this.isDispose) {\n this.timeoutHandle = setTimeout(() => func(), POLL_DURATION)\n }\n }\n\n func()\n }\n\n public dispose() {\n this.isDispose = true\n clearTimeout(this.timeoutHandle as any)\n this.timeoutHandle = null\n }\n\n async fetchList() {\n const currentUser = platform.auth.getCurrentUser()\n\n // if the authIdToken is not present, don't fetch the teams list, as it will fail anyway\n if (!currentUser) return\n\n this.loading$.next(true)\n\n const results: GetMyTeamsQuery[\"myTeams\"] = []\n\n while (true) {\n const result = await runGQLQuery({\n query: GetMyTeamsDocument,\n variables: {\n cursor:\n results.length > 0 ? results[results.length - 1].id : undefined,\n },\n })\n\n if (E.isLeft(result)) {\n this.error$.next(result.left)\n throw new Error("} {"commit": "a8d50223aabe0e75e6c0f7ccd77305df0837ac09", "message": "refactor: changed auth module to work with signed cookies", "old_file": "packages/hoppscotch-backend/src/utils.ts", "new_file": "packages/hoppscotch-backend/src/utils.ts", "status": "M", "old_contents": "export const authCookieHandler = (\n res: Response,\n authTokens: AuthTokens,\n redirect: boolean,\n) => {\n const currentTime = DateTime.now();\n const accessTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY),\n })\n .toMillis();\n const refreshTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY),\n })\n .toMillis();\n\n res.cookie('access_token', authTokens.access_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: accessTokenValidity,\n });\n res.cookie('refresh_token', authTokens.refresh_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: refreshTokenValidity,\n });\n if (redirect) {\n res.status(HttpStatus.OK).redirect(process.env.REDIRECT_URL);\n } else res.status(HttpStatus.OK).send();\n};\n\n/*\n * String to JSON parser\n * @param {str} str The string to parse\n * @returns {E.Right | E.Left<\"json_invalid\">} An Either of the parsed JSON\n */\nexport function stringToJson(\n str: string,\n): E.Right | E.Left {\n try {\n return E.right(JSON.parse(str));\n } catch (err) {\n return E.left(JSON_INVALID);\n }\n}\n", "new_contents": "export const authCookieHandler = (\n res: Response,\n authTokens: AuthTokens,\n redirect: boolean,\n) => {\n const currentTime = DateTime.now();\n const accessTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY),\n })\n .toMillis();\n const refreshTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY),\n })\n .toMillis();\n\n res.cookie('access_token', authTokens.access_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: accessTokenValidity,\n signed: true,\n });\n res.cookie('refresh_token', authTokens.refresh_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: refreshTokenValidity,\n signed: true,\n });\n if (redirect) {\n res.status(HttpStatus.OK).redirect(process.env.REDIRECT_URL);\n } else res.status(HttpStatus.OK).send();\n};\n\n/*\n * String to JSON parser\n * @param {str} str The string to parse\n * @returns {E.Right | E.Left<\"json_invalid\">} An Either of the parsed JSON\n */\nexport function stringToJson(\n str: string,\n): E.Right | E.Left {\n try {\n return E.right(JSON.parse(str));\n } catch (err) {\n return E.left(JSON_INVALID);\n }\n}\n", "text": "<|original_code|>\nexport const authCookieHandler = (\n res: Response,\n authTokens: AuthTokens,\n redirect: boolean,\n) => {\n const currentTime = DateTime.now();\n const accessTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY),\n })\n .toMillis();\n const refreshTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY),\n })\n .toMillis();\n\n res.cookie('access_token', authTokens.access_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: accessTokenValidity,\n });\n res.cookie('refresh_token', authTokens.refresh_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: refreshTokenValidity,\n });\n if (redirect) {\n res.status(HttpStatus.OK).redirect(process.env.REDIRECT_URL);\n } else res.status(HttpStatus.OK).send();\n};\n\n/*\n * String to JSON parser\n * @param {str} str The string to parse\n * @returns {E.Right | E.Left<\"json_invalid\">} An Either of the parsed JSON\n */\nexport function stringToJson(\n str: string,\n): E.Right | E.Left {\n try {\n return E.right(JSON.parse(str));\n } catch (err) {\n return E.left(JSON_INVALID);\n }\n}\n\n<|edits_diff|>\n--- packages/hoppscotch-backend/src/utils.ts\n+++ packages/hoppscotch-backend/src/utils.ts\n@@ -20,6 +20,7 @@\n secure: true,\n sameSite: 'lax',\n maxAge: accessTokenValidity,\n+ signed: true,\n });\n res.cookie('refresh_token', authTokens.refresh_token, {\n httpOnly: true,\n<|current_version|>\nexport const authCookieHandler = (\n res: Response,\n authTokens: AuthTokens,\n redirect: boolean,\n) => {\n const currentTime = DateTime.now();\n const accessTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY),\n })\n .toMillis();\n const refreshTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY),\n })\n .toMillis();\n\n res.cookie('access_token', authTokens.access_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: accessTokenValidity,\n signed: true,\n });\n res.cookie('refresh_token', authTokens.refresh_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: refreshTokenValidity,\n });\n if (redirect) {\n res.status(HttpStatus.OK).redirect(process.env.REDIRECT_URL);\n } else res.status(HttpStatus.OK).send();\n};\n\n/*\n * String to JSON parser\n * @param {str} str The string to parse\n * @returns {E.Right | E.Left<\"json_invalid\">} An Either of the parsed JSON\n */\nexport function stringToJson(\n str: string,\n): E.Right | E.Left {\n try {\n return E.right(JSON.parse(str));\n } catch (err) {\n return E.left(JSON_INVALID);\n }\n}\n\n<|next_version|>\nexport const authCookieHandler = (\n res: Response,\n authTokens: AuthTokens,\n redirect: boolean,\n) => {\n const currentTime = DateTime.now();\n const accessTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY),\n })\n .toMillis();\n const refreshTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY),\n })\n .toMillis();\n\n res.cookie('access_token', authTokens.access_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: accessTokenValidity,\n signed: true,\n });\n res.cookie('refresh_token', authTokens.refresh_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: refreshTokenValidity,\n signed: true,\n });\n if (redirect) {\n res.status(HttpStatus.OK).redirect(process.env.REDIRECT_URL);\n } else res.status(HttpStatus.OK).send();\n};\n\n/*\n * String to JSON parser\n * @param {str} str The string to parse\n * @returns {E.Right | E.Left<\"json_invalid\">} An Either of the parsed JSON\n */\nexport function stringToJson(\n str: string,\n): E.Right | E.Left {\n try {\n return E.right(JSON.parse(str));\n } catch (err) {\n return E.left(JSON_INVALID);\n }\n}\n\n", "current_contents": "export const authCookieHandler = (\n res: Response,\n authTokens: AuthTokens,\n redirect: boolean,\n) => {\n const currentTime = DateTime.now();\n const accessTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.ACCESS_TOKEN_VALIDITY),\n })\n .toMillis();\n const refreshTokenValidity = currentTime\n .plus({\n milliseconds: parseInt(process.env.REFRESH_TOKEN_VALIDITY),\n })\n .toMillis();\n\n res.cookie('access_token', authTokens.access_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: accessTokenValidity,\n signed: true,\n });\n res.cookie('refresh_token', authTokens.refresh_token, {\n httpOnly: true,\n secure: true,\n sameSite: 'lax',\n maxAge: refreshTokenValidity,\n });\n if (redirect) {\n res.status(HttpStatus.OK).redirect(process.env.REDIRECT_URL);\n } else res.status(HttpStatus.OK).send();\n};\n\n/*\n * String to JSON parser\n * @param {str} str The string to parse\n * @returns {E.Right | E.Left<\"json_invalid\">} An Either of the parsed JSON\n */\nexport function stringToJson(\n str: string,\n): E.Right | E.Left {\n try {\n return E.right(JSON.parse(str));\n } catch (err) {\n return E.left(JSON_INVALID);\n }\n}\n"} {"commit": "6627514e88844e342225ab33b1bbdd4fb5a8831e", "message": "chore: pulled from main", "old_file": "packages/hoppscotch-backend/src/app.module.ts", "new_file": "packages/hoppscotch-backend/src/app.module.ts", "status": "M", "old_contents": "import { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';\nimport { UserModule } from './user/user.module';\nimport { GQLComplexityPlugin } from './plugins/GQLComplexityPlugin';\nimport { UserEnvironmentsModule } from './user-environment/user-environments.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: process.env.PRODUCTION !== 'true',\n debug: process.env.PRODUCTION !== 'true',\n autoSchemaFile: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'subscriptions-transport-ws': {\n path: '/graphql',\n onConnect: (connectionParams: any) => {\n return {\n reqHeaders: Object.fromEntries(\n Object.entries(connectionParams).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n },\n },\n },\n context: async ({ req, connection }) => {\n if (req) {\n return { reqHeaders: req.headers };\n } else {\n return {\n // Lowercase the keys\n reqHeaders: Object.fromEntries(\n Object.entries(connection.context).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n }\n },\n driver: ApolloDriver,\n }),\n UserModule,\n UserEnvironmentsModule,\n ],\n providers: [GQLComplexityPlugin],\n})\nexport class AppModule {}\n", "new_contents": "import { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';\nimport { UserModule } from './user/user.module';\nimport { GQLComplexityPlugin } from './plugins/GQLComplexityPlugin';\nimport { UserSettingsModule } from './user-settings/user-settings.module';\nimport { UserEnvironmentsModule } from './user-environment/user-environments.module';\nimport { UserHistoryModule } from './user-history/user-history.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: process.env.PRODUCTION !== 'true',\n debug: process.env.PRODUCTION !== 'true',\n autoSchemaFile: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'subscriptions-transport-ws': {\n path: '/graphql',\n onConnect: (connectionParams: any) => {\n return {\n reqHeaders: Object.fromEntries(\n Object.entries(connectionParams).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n },\n },\n },\n context: async ({ req, connection }) => {\n if (req) {\n return { reqHeaders: req.headers };\n } else {\n return {\n // Lowercase the keys\n reqHeaders: Object.fromEntries(\n Object.entries(connection.context).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n }\n },\n driver: ApolloDriver,\n }),\n UserModule,\n UserSettingsModule,\n UserEnvironmentsModule,\n UserHistoryModule,\n ],\n providers: [GQLComplexityPlugin],\n})\nexport class AppModule {}\n", "text": "<|original_code|>\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';\nimport { UserModule } from './user/user.module';\nimport { GQLComplexityPlugin } from './plugins/GQLComplexityPlugin';\nimport { UserEnvironmentsModule } from './user-environment/user-environments.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: process.env.PRODUCTION !== 'true',\n debug: process.env.PRODUCTION !== 'true',\n autoSchemaFile: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'subscriptions-transport-ws': {\n path: '/graphql',\n onConnect: (connectionParams: any) => {\n return {\n reqHeaders: Object.fromEntries(\n Object.entries(connectionParams).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n },\n },\n },\n context: async ({ req, connection }) => {\n if (req) {\n return { reqHeaders: req.headers };\n } else {\n return {\n // Lowercase the keys\n reqHeaders: Object.fromEntries(\n Object.entries(connection.context).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n }\n },\n driver: ApolloDriver,\n }),\n UserModule,\n UserEnvironmentsModule,\n ],\n providers: [GQLComplexityPlugin],\n})\nexport class AppModule {}\n\n<|edits_diff|>\n--- packages/hoppscotch-backend/src/app.module.ts\n+++ packages/hoppscotch-backend/src/app.module.ts\n@@ -3,7 +3,9 @@\n import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';\n import { UserModule } from './user/user.module';\n import { GQLComplexityPlugin } from './plugins/GQLComplexityPlugin';\n+import { UserSettingsModule } from './user-settings/user-settings.module';\n import { UserEnvironmentsModule } from './user-environment/user-environments.module';\n+import { UserHistoryModule } from './user-history/user-history.module';\n \n @Module({\n imports: [\n@@ -45,6 +47,7 @@\n driver: ApolloDriver,\n }),\n UserModule,\n+ UserSettingsModule,\n UserEnvironmentsModule,\n ],\n providers: [GQLComplexityPlugin],\n<|current_version|>\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';\nimport { UserModule } from './user/user.module';\nimport { GQLComplexityPlugin } from './plugins/GQLComplexityPlugin';\nimport { UserSettingsModule } from './user-settings/user-settings.module';\nimport { UserEnvironmentsModule } from './user-environment/user-environments.module';\nimport { UserHistoryModule } from './user-history/user-history.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: process.env.PRODUCTION !== 'true',\n debug: process.env.PRODUCTION !== 'true',\n autoSchemaFile: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'subscriptions-transport-ws': {\n path: '/graphql',\n onConnect: (connectionParams: any) => {\n return {\n reqHeaders: Object.fromEntries(\n Object.entries(connectionParams).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n },\n },\n },\n context: async ({ req, connection }) => {\n if (req) {\n return { reqHeaders: req.headers };\n } else {\n return {\n // Lowercase the keys\n reqHeaders: Object.fromEntries(\n Object.entries(connection.context).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n }\n },\n driver: ApolloDriver,\n }),\n UserModule,\n UserSettingsModule,\n UserEnvironmentsModule,\n ],\n providers: [GQLComplexityPlugin],\n})\nexport class AppModule {}\n\n<|next_version|>\nimport { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';\nimport { UserModule } from './user/user.module';\nimport { GQLComplexityPlugin } from './plugins/GQLComplexityPlugin';\nimport { UserSettingsModule } from './user-settings/user-settings.module';\nimport { UserEnvironmentsModule } from './user-environment/user-environments.module';\nimport { UserHistoryModule } from './user-history/user-history.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: process.env.PRODUCTION !== 'true',\n debug: process.env.PRODUCTION !== 'true',\n autoSchemaFile: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'subscriptions-transport-ws': {\n path: '/graphql',\n onConnect: (connectionParams: any) => {\n return {\n reqHeaders: Object.fromEntries(\n Object.entries(connectionParams).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n },\n },\n },\n context: async ({ req, connection }) => {\n if (req) {\n return { reqHeaders: req.headers };\n } else {\n return {\n // Lowercase the keys\n reqHeaders: Object.fromEntries(\n Object.entries(connection.context).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n }\n },\n driver: ApolloDriver,\n }),\n UserModule,\n UserSettingsModule,\n UserEnvironmentsModule,\n UserHistoryModule,\n ],\n providers: [GQLComplexityPlugin],\n})\nexport class AppModule {}\n\n", "current_contents": "import { Module } from '@nestjs/common';\nimport { GraphQLModule } from '@nestjs/graphql';\nimport { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';\nimport { UserModule } from './user/user.module';\nimport { GQLComplexityPlugin } from './plugins/GQLComplexityPlugin';\nimport { UserSettingsModule } from './user-settings/user-settings.module';\nimport { UserEnvironmentsModule } from './user-environment/user-environments.module';\nimport { UserHistoryModule } from './user-history/user-history.module';\n\n@Module({\n imports: [\n GraphQLModule.forRoot({\n playground: process.env.PRODUCTION !== 'true',\n debug: process.env.PRODUCTION !== 'true',\n autoSchemaFile: true,\n installSubscriptionHandlers: true,\n subscriptions: {\n 'subscriptions-transport-ws': {\n path: '/graphql',\n onConnect: (connectionParams: any) => {\n return {\n reqHeaders: Object.fromEntries(\n Object.entries(connectionParams).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n },\n },\n },\n context: async ({ req, connection }) => {\n if (req) {\n return { reqHeaders: req.headers };\n } else {\n return {\n // Lowercase the keys\n reqHeaders: Object.fromEntries(\n Object.entries(connection.context).map(([k, v]) => [\n k.toLowerCase(),\n v,\n ]),\n ),\n };\n }\n },\n driver: ApolloDriver,\n }),\n UserModule,\n UserSettingsModule,\n UserEnvironmentsModule,\n ],\n providers: [GQLComplexityPlugin],\n})\nexport class AppModule {}\n"} {"commit": "81cb0d43d78e41a3ce1e82260a10fa9baedfbc64", "message": "fix: added scope for github strategy in auth module", "old_file": "packages/hoppscotch-backend/src/auth/auth.module.ts", "new_file": "packages/hoppscotch-backend/src/auth/auth.module.ts", "status": "M", "old_contents": "import { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { UserModule } from 'src/user/user.module';\nimport { MailerModule } from 'src/mailer/mailer.module';\nimport { PrismaModule } from 'src/prisma/prisma.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt/dist';\nimport { JwtStrategy } from './strategies/jwt.strategy';\nimport { RTJwtStrategy } from './strategies/rt-jwt.strategy';\nimport { GoogleStrategy } from './strategies/google.strategy';\nimport { GithubStrategy } from './strategies/github.strategy';\n\n@Module({\n imports: [\n PrismaModule,\n UserModule,\n MailerModule,\n PassportModule,\n JwtModule.register({\n secret: process.env.JWT_SECRET,\n }),\n ],\n providers: [\n AuthService,\n JwtStrategy,\n RTJwtStrategy,\n GoogleStrategy,\n GithubStrategy,\n ],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n", "new_contents": "import { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { UserModule } from 'src/user/user.module';\nimport { MailerModule } from 'src/mailer/mailer.module';\nimport { PrismaModule } from 'src/prisma/prisma.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt/dist';\nimport { JwtStrategy } from './strategies/jwt.strategy';\nimport { RTJwtStrategy } from './strategies/rt-jwt.strategy';\nimport { GoogleStrategy } from './strategies/google.strategy';\nimport { GithubStrategy } from './strategies/github.strategy';\nimport { MicrosoftStrategy } from './strategies/microsoft.strategy';\n\n@Module({\n imports: [\n PrismaModule,\n UserModule,\n MailerModule,\n PassportModule,\n JwtModule.register({\n secret: process.env.JWT_SECRET,\n }),\n ],\n providers: [\n AuthService,\n JwtStrategy,\n RTJwtStrategy,\n GoogleStrategy,\n GithubStrategy,\n MicrosoftStrategy,\n ],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n", "text": "<|original_code|>\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { UserModule } from 'src/user/user.module';\nimport { MailerModule } from 'src/mailer/mailer.module';\nimport { PrismaModule } from 'src/prisma/prisma.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt/dist';\nimport { JwtStrategy } from './strategies/jwt.strategy';\nimport { RTJwtStrategy } from './strategies/rt-jwt.strategy';\nimport { GoogleStrategy } from './strategies/google.strategy';\nimport { GithubStrategy } from './strategies/github.strategy';\n\n@Module({\n imports: [\n PrismaModule,\n UserModule,\n MailerModule,\n PassportModule,\n JwtModule.register({\n secret: process.env.JWT_SECRET,\n }),\n ],\n providers: [\n AuthService,\n JwtStrategy,\n RTJwtStrategy,\n GoogleStrategy,\n GithubStrategy,\n ],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n\n<|edits_diff|>\n--- packages/hoppscotch-backend/src/auth/auth.module.ts\n+++ packages/hoppscotch-backend/src/auth/auth.module.ts\n@@ -10,6 +10,7 @@\n import { RTJwtStrategy } from './strategies/rt-jwt.strategy';\n import { GoogleStrategy } from './strategies/google.strategy';\n import { GithubStrategy } from './strategies/github.strategy';\n+import { MicrosoftStrategy } from './strategies/microsoft.strategy';\n \n @Module({\n imports: [\n<|current_version|>\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { UserModule } from 'src/user/user.module';\nimport { MailerModule } from 'src/mailer/mailer.module';\nimport { PrismaModule } from 'src/prisma/prisma.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt/dist';\nimport { JwtStrategy } from './strategies/jwt.strategy';\nimport { RTJwtStrategy } from './strategies/rt-jwt.strategy';\nimport { GoogleStrategy } from './strategies/google.strategy';\nimport { GithubStrategy } from './strategies/github.strategy';\nimport { MicrosoftStrategy } from './strategies/microsoft.strategy';\n\n@Module({\n imports: [\n PrismaModule,\n UserModule,\n MailerModule,\n PassportModule,\n JwtModule.register({\n secret: process.env.JWT_SECRET,\n }),\n ],\n providers: [\n AuthService,\n JwtStrategy,\n RTJwtStrategy,\n GoogleStrategy,\n GithubStrategy,\n ],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n\n<|next_version|>\nimport { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { UserModule } from 'src/user/user.module';\nimport { MailerModule } from 'src/mailer/mailer.module';\nimport { PrismaModule } from 'src/prisma/prisma.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt/dist';\nimport { JwtStrategy } from './strategies/jwt.strategy';\nimport { RTJwtStrategy } from './strategies/rt-jwt.strategy';\nimport { GoogleStrategy } from './strategies/google.strategy';\nimport { GithubStrategy } from './strategies/github.strategy';\nimport { MicrosoftStrategy } from './strategies/microsoft.strategy';\n\n@Module({\n imports: [\n PrismaModule,\n UserModule,\n MailerModule,\n PassportModule,\n JwtModule.register({\n secret: process.env.JWT_SECRET,\n }),\n ],\n providers: [\n AuthService,\n JwtStrategy,\n RTJwtStrategy,\n GoogleStrategy,\n GithubStrategy,\n MicrosoftStrategy,\n ],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n\n", "current_contents": "import { Module } from '@nestjs/common';\nimport { AuthService } from './auth.service';\nimport { AuthController } from './auth.controller';\nimport { UserModule } from 'src/user/user.module';\nimport { MailerModule } from 'src/mailer/mailer.module';\nimport { PrismaModule } from 'src/prisma/prisma.module';\nimport { PassportModule } from '@nestjs/passport';\nimport { JwtModule } from '@nestjs/jwt/dist';\nimport { JwtStrategy } from './strategies/jwt.strategy';\nimport { RTJwtStrategy } from './strategies/rt-jwt.strategy';\nimport { GoogleStrategy } from './strategies/google.strategy';\nimport { GithubStrategy } from './strategies/github.strategy';\nimport { MicrosoftStrategy } from './strategies/microsoft.strategy';\n\n@Module({\n imports: [\n PrismaModule,\n UserModule,\n MailerModule,\n PassportModule,\n JwtModule.register({\n secret: process.env.JWT_SECRET,\n }),\n ],\n providers: [\n AuthService,\n JwtStrategy,\n RTJwtStrategy,\n GoogleStrategy,\n GithubStrategy,\n ],\n controllers: [AuthController],\n})\nexport class AuthModule {}\n"} {"commit": "5c032e84be7cbac62d3e7c90db2d0d8cfa8618cb", "message": "fix: null value checked on user_settings.properties", "old_file": "packages/hoppscotch-backend/src/user-settings/user-settings.service.ts", "new_file": "packages/hoppscotch-backend/src/user-settings/user-settings.service.ts", "status": "M", "old_contents": "import { Injectable } from '@nestjs/common';\nimport { PrismaService } from 'src/prisma/prisma.service';\nimport { PubSubService } from 'src/pubsub/pubsub.service';\nimport { User } from 'src/user/user.model';\nimport * as E from 'fp-ts/Either';\nimport { stringToJson } from 'src/utils';\nimport { UserSettings } from './user-settings.model';\nimport {\n USER_SETTINGS_NOT_FOUND,\n USER_SETTINGS_UPDATE_FAILED,\n} from 'src/errors';\n\n@Injectable()\nexport class UserSettingsService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly pubsub: PubSubService,\n ) {}\n\n async fetchUserSettings(user: User) {\n try {\n const dbUserSettings = await this.prisma.userSettings.findUnique({\n where: { userUid: user.uid },\n rejectOnNotFound: true,\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties: JSON.stringify(dbUserSettings.properties),\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n } catch (e) {\n return E.left(USER_SETTINGS_NOT_FOUND);\n }\n }\n\n async createUserSettings(user: User, properties: string) {\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n const dbUserSettings = await this.prisma.userSettings.create({\n data: {\n properties: jsonProperties.right,\n userUid: user.uid,\n },\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties,\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n }\n\n async updateUserSettings(user: User, properties: string) {\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n try {\n const dbUpdatedUserSettings = await this.prisma.userSettings.update({\n where: { userUid: user.uid },\n data: {\n properties: jsonProperties.right,\n },\n });\n\n const updatedUserSettings: UserSettings = {\n id: dbUpdatedUserSettings.id,\n userUid: dbUpdatedUserSettings.userUid,\n properties,\n updatedOn: dbUpdatedUserSettings.updatedOn,\n };\n\n // Publish subscription for environment creation\n await this.pubsub.publish(\n `user_settings/${user.uid}/updated`,\n updatedUserSettings,\n );\n", "new_contents": "import { Injectable } from '@nestjs/common';\nimport { PrismaService } from 'src/prisma/prisma.service';\nimport { PubSubService } from 'src/pubsub/pubsub.service';\nimport { User } from 'src/user/user.model';\nimport * as E from 'fp-ts/Either';\nimport { stringToJson } from 'src/utils';\nimport { UserSettings } from './user-settings.model';\nimport {\n USER_SETTINGS_INVALID_PROPERTIES,\n USER_SETTINGS_NOT_FOUND,\n USER_SETTINGS_UPDATE_FAILED,\n} from 'src/errors';\n\n@Injectable()\nexport class UserSettingsService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly pubsub: PubSubService,\n ) {}\n\n async fetchUserSettings(user: User) {\n try {\n const dbUserSettings = await this.prisma.userSettings.findUnique({\n where: { userUid: user.uid },\n rejectOnNotFound: true,\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties: JSON.stringify(dbUserSettings.properties),\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n } catch (e) {\n return E.left(USER_SETTINGS_NOT_FOUND);\n }\n }\n\n async createUserSettings(user: User, properties: string) {\n if (!properties) return E.left(USER_SETTINGS_INVALID_PROPERTIES);\n\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n const dbUserSettings = await this.prisma.userSettings.create({\n data: {\n properties: jsonProperties.right,\n userUid: user.uid,\n },\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties,\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n }\n\n async updateUserSettings(user: User, properties: string) {\n if (!properties) return E.left(USER_SETTINGS_INVALID_PROPERTIES);\n\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n try {\n const dbUpdatedUserSettings = await this.prisma.userSettings.update({\n where: { userUid: user.uid },\n data: {\n properties: jsonProperties.right,\n },\n });\n\n const updatedUserSettings: UserSettings = {\n id: dbUpdatedUserSettings.id,\n userUid: dbUpdatedUserSettings.userUid,\n properties,\n updatedOn: dbUpdatedUserSettings.updatedOn,\n };\n\n // Publish subscription for environment creation\n await this.pubsub.publish(\n `user_settings/${user.uid}/updated`,\n updatedUserSettings,\n );\n", "text": "<|original_code|>\nimport { Injectable } from '@nestjs/common';\nimport { PrismaService } from 'src/prisma/prisma.service';\nimport { PubSubService } from 'src/pubsub/pubsub.service';\nimport { User } from 'src/user/user.model';\nimport * as E from 'fp-ts/Either';\nimport { stringToJson } from 'src/utils';\nimport { UserSettings } from './user-settings.model';\nimport {\n USER_SETTINGS_NOT_FOUND,\n USER_SETTINGS_UPDATE_FAILED,\n} from 'src/errors';\n\n@Injectable()\nexport class UserSettingsService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly pubsub: PubSubService,\n ) {}\n\n async fetchUserSettings(user: User) {\n try {\n const dbUserSettings = await this.prisma.userSettings.findUnique({\n where: { userUid: user.uid },\n rejectOnNotFound: true,\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties: JSON.stringify(dbUserSettings.properties),\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n } catch (e) {\n return E.left(USER_SETTINGS_NOT_FOUND);\n }\n }\n\n async createUserSettings(user: User, properties: string) {\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n const dbUserSettings = await this.prisma.userSettings.create({\n data: {\n properties: jsonProperties.right,\n userUid: user.uid,\n },\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties,\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n }\n\n async updateUserSettings(user: User, properties: string) {\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n try {\n const dbUpdatedUserSettings = await this.prisma.userSettings.update({\n where: { userUid: user.uid },\n data: {\n properties: jsonProperties.right,\n },\n });\n\n const updatedUserSettings: UserSettings = {\n id: dbUpdatedUserSettings.id,\n userUid: dbUpdatedUserSettings.userUid,\n properties,\n updatedOn: dbUpdatedUserSettings.updatedOn,\n };\n\n // Publish subscription for environment creation\n await this.pubsub.publish(\n `user_settings/${user.uid}/updated`,\n updatedUserSettings,\n );\n\n<|edits_diff|>\n--- packages/hoppscotch-backend/src/user-settings/user-settings.service.ts\n+++ packages/hoppscotch-backend/src/user-settings/user-settings.service.ts\n@@ -6,6 +6,7 @@\n import { stringToJson } from 'src/utils';\n import { UserSettings } from './user-settings.model';\n import {\n+ USER_SETTINGS_INVALID_PROPERTIES,\n USER_SETTINGS_NOT_FOUND,\n USER_SETTINGS_UPDATE_FAILED,\n } from 'src/errors';\n@@ -38,6 +39,8 @@\n }\n \n async createUserSettings(user: User, properties: string) {\n+ if (!properties) return E.left(USER_SETTINGS_INVALID_PROPERTIES);\n+\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n \n<|current_version|>\nimport { Injectable } from '@nestjs/common';\nimport { PrismaService } from 'src/prisma/prisma.service';\nimport { PubSubService } from 'src/pubsub/pubsub.service';\nimport { User } from 'src/user/user.model';\nimport * as E from 'fp-ts/Either';\nimport { stringToJson } from 'src/utils';\nimport { UserSettings } from './user-settings.model';\nimport {\n USER_SETTINGS_INVALID_PROPERTIES,\n USER_SETTINGS_NOT_FOUND,\n USER_SETTINGS_UPDATE_FAILED,\n} from 'src/errors';\n\n@Injectable()\nexport class UserSettingsService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly pubsub: PubSubService,\n ) {}\n\n async fetchUserSettings(user: User) {\n try {\n const dbUserSettings = await this.prisma.userSettings.findUnique({\n where: { userUid: user.uid },\n rejectOnNotFound: true,\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties: JSON.stringify(dbUserSettings.properties),\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n } catch (e) {\n return E.left(USER_SETTINGS_NOT_FOUND);\n }\n }\n\n async createUserSettings(user: User, properties: string) {\n if (!properties) return E.left(USER_SETTINGS_INVALID_PROPERTIES);\n\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n const dbUserSettings = await this.prisma.userSettings.create({\n data: {\n properties: jsonProperties.right,\n userUid: user.uid,\n },\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties,\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n }\n\n async updateUserSettings(user: User, properties: string) {\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n try {\n const dbUpdatedUserSettings = await this.prisma.userSettings.update({\n where: { userUid: user.uid },\n data: {\n properties: jsonProperties.right,\n },\n });\n\n const updatedUserSettings: UserSettings = {\n id: dbUpdatedUserSettings.id,\n userUid: dbUpdatedUserSettings.userUid,\n properties,\n updatedOn: dbUpdatedUserSettings.updatedOn,\n };\n\n // Publish subscription for environment creation\n await this.pubsub.publish(\n `user_settings/${user.uid}/updated`,\n updatedUserSettings,\n );\n\n<|next_version|>\nimport { Injectable } from '@nestjs/common';\nimport { PrismaService } from 'src/prisma/prisma.service';\nimport { PubSubService } from 'src/pubsub/pubsub.service';\nimport { User } from 'src/user/user.model';\nimport * as E from 'fp-ts/Either';\nimport { stringToJson } from 'src/utils';\nimport { UserSettings } from './user-settings.model';\nimport {\n USER_SETTINGS_INVALID_PROPERTIES,\n USER_SETTINGS_NOT_FOUND,\n USER_SETTINGS_UPDATE_FAILED,\n} from 'src/errors';\n\n@Injectable()\nexport class UserSettingsService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly pubsub: PubSubService,\n ) {}\n\n async fetchUserSettings(user: User) {\n try {\n const dbUserSettings = await this.prisma.userSettings.findUnique({\n where: { userUid: user.uid },\n rejectOnNotFound: true,\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties: JSON.stringify(dbUserSettings.properties),\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n } catch (e) {\n return E.left(USER_SETTINGS_NOT_FOUND);\n }\n }\n\n async createUserSettings(user: User, properties: string) {\n if (!properties) return E.left(USER_SETTINGS_INVALID_PROPERTIES);\n\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n const dbUserSettings = await this.prisma.userSettings.create({\n data: {\n properties: jsonProperties.right,\n userUid: user.uid,\n },\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties,\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n }\n\n async updateUserSettings(user: User, properties: string) {\n if (!properties) return E.left(USER_SETTINGS_INVALID_PROPERTIES);\n\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n try {\n const dbUpdatedUserSettings = await this.prisma.userSettings.update({\n where: { userUid: user.uid },\n data: {\n properties: jsonProperties.right,\n },\n });\n\n const updatedUserSettings: UserSettings = {\n id: dbUpdatedUserSettings.id,\n userUid: dbUpdatedUserSettings.userUid,\n properties,\n updatedOn: dbUpdatedUserSettings.updatedOn,\n };\n\n // Publish subscription for environment creation\n await this.pubsub.publish(\n `user_settings/${user.uid}/updated`,\n updatedUserSettings,\n );\n\n", "current_contents": "import { Injectable } from '@nestjs/common';\nimport { PrismaService } from 'src/prisma/prisma.service';\nimport { PubSubService } from 'src/pubsub/pubsub.service';\nimport { User } from 'src/user/user.model';\nimport * as E from 'fp-ts/Either';\nimport { stringToJson } from 'src/utils';\nimport { UserSettings } from './user-settings.model';\nimport {\n USER_SETTINGS_INVALID_PROPERTIES,\n USER_SETTINGS_NOT_FOUND,\n USER_SETTINGS_UPDATE_FAILED,\n} from 'src/errors';\n\n@Injectable()\nexport class UserSettingsService {\n constructor(\n private readonly prisma: PrismaService,\n private readonly pubsub: PubSubService,\n ) {}\n\n async fetchUserSettings(user: User) {\n try {\n const dbUserSettings = await this.prisma.userSettings.findUnique({\n where: { userUid: user.uid },\n rejectOnNotFound: true,\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties: JSON.stringify(dbUserSettings.properties),\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n } catch (e) {\n return E.left(USER_SETTINGS_NOT_FOUND);\n }\n }\n\n async createUserSettings(user: User, properties: string) {\n if (!properties) return E.left(USER_SETTINGS_INVALID_PROPERTIES);\n\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n const dbUserSettings = await this.prisma.userSettings.create({\n data: {\n properties: jsonProperties.right,\n userUid: user.uid,\n },\n });\n\n const userSettings: UserSettings = {\n id: dbUserSettings.id,\n userUid: dbUserSettings.userUid,\n properties,\n updatedOn: dbUserSettings.updatedOn,\n };\n\n return E.right(userSettings);\n }\n\n async updateUserSettings(user: User, properties: string) {\n const jsonProperties = stringToJson(properties);\n if (E.isLeft(jsonProperties)) return E.left(jsonProperties.left);\n\n try {\n const dbUpdatedUserSettings = await this.prisma.userSettings.update({\n where: { userUid: user.uid },\n data: {\n properties: jsonProperties.right,\n },\n });\n\n const updatedUserSettings: UserSettings = {\n id: dbUpdatedUserSettings.id,\n userUid: dbUpdatedUserSettings.userUid,\n properties,\n updatedOn: dbUpdatedUserSettings.updatedOn,\n };\n\n // Publish subscription for environment creation\n await this.pubsub.publish(\n `user_settings/${user.uid}/updated`,\n updatedUserSettings,\n );\n"} {"commit": "56b22bb1d38cb9a9408fe5dcf71eeb3c7407c4c0", "message": "Add support for source maps (#17775)", "old_file": "packages/@tailwindcss-browser/src/index.ts", "new_file": "packages/@tailwindcss-browser/src/index.ts", "status": "M", "old_contents": "\n lastCss = css\n\n I.start('Compile CSS')\n try {\n compiler = await tailwindcss.compile(css, {\n base: '/',\n loadStylesheet,\n loadModule,\n })\n } finally {\n I.end('Compile CSS')\n I.end(`Create compiler`)\n }\n\n classes.clear()\n}\n\nasync function loadStylesheet(id: string, base: string) {\n function load() {\n if (id === 'tailwindcss') {\n return {\n base,\n content: assets.css.index,\n }\n } else if (\n id === 'tailwindcss/preflight' ||\n id === 'tailwindcss/preflight.css' ||\n id === './preflight.css'\n ) {\n return {\n base,\n content: assets.css.preflight,\n }\n } else if (\n id === 'tailwindcss/theme' ||\n id === 'tailwindcss/theme.css' ||\n id === './theme.css'\n ) {\n return {\n base,\n content: assets.css.theme,\n }\n } else if (\n id === 'tailwindcss/utilities' ||\n id === 'tailwindcss/utilities.css' ||\n id === './utilities.css'\n ) {\n return {\n base,\n content: assets.css.utilities,\n }\n }\n\n throw new Error(`The browser build does not support @import for \"${id}\"`)\n }\n\n try {\n let sheet = load()\n\n I.hit(`Loaded stylesheet`, {\n id,\n base,\n size: sheet.content.length,\n })\n\n return sheet\n } catch (err) {\n I.hit(`Failed to load stylesheet`, {\n id,\n base,\n error: (err as Error).message ?? err,\n })", "new_contents": "\n lastCss = css\n\n I.start('Compile CSS')\n try {\n compiler = await tailwindcss.compile(css, {\n base: '/',\n loadStylesheet,\n loadModule,\n })\n } finally {\n I.end('Compile CSS')\n I.end(`Create compiler`)\n }\n\n classes.clear()\n}\n\nasync function loadStylesheet(id: string, base: string) {\n function load() {\n if (id === 'tailwindcss') {\n return {\n path: 'virtual:tailwindcss/index.css',\n base,\n content: assets.css.index,\n }\n } else if (\n id === 'tailwindcss/preflight' ||\n id === 'tailwindcss/preflight.css' ||\n id === './preflight.css'\n ) {\n return {\n path: 'virtual:tailwindcss/preflight.css',\n base,\n content: assets.css.preflight,\n }\n } else if (\n id === 'tailwindcss/theme' ||\n id === 'tailwindcss/theme.css' ||\n id === './theme.css'\n ) {\n return {\n path: 'virtual:tailwindcss/theme.css',\n base,\n content: assets.css.theme,\n }\n } else if (\n id === 'tailwindcss/utilities' ||\n id === 'tailwindcss/utilities.css' ||\n id === './utilities.css'\n ) {\n return {\n path: 'virtual:tailwindcss/utilities.css',\n base,\n content: assets.css.utilities,\n }\n }\n\n throw new Error(`The browser build does not support @import for \"${id}\"`)\n }\n\n try {\n let sheet = load()\n\n I.hit(`Loaded stylesheet`, {\n id,\n base,\n size: sheet.content.length,\n })\n\n return sheet\n } catch (err) {\n I.hit(`Failed to load stylesheet`, {\n id,\n base,\n error: (err as Error).message ?? err,\n })", "text": "<|original_code|>\n\n lastCss = css\n\n I.start('Compile CSS')\n try {\n compiler = await tailwindcss.compile(css, {\n base: '/',\n loadStylesheet,\n loadModule,\n })\n } finally {\n I.end('Compile CSS')\n I.end(`Create compiler`)\n }\n\n classes.clear()\n}\n\nasync function loadStylesheet(id: string, base: string) {\n function load() {\n if (id === 'tailwindcss') {\n return {\n base,\n content: assets.css.index,\n }\n } else if (\n id === 'tailwindcss/preflight' ||\n id === 'tailwindcss/preflight.css' ||\n id === './preflight.css'\n ) {\n return {\n base,\n content: assets.css.preflight,\n }\n } else if (\n id === 'tailwindcss/theme' ||\n id === 'tailwindcss/theme.css' ||\n id === './theme.css'\n ) {\n return {\n base,\n content: assets.css.theme,\n }\n } else if (\n id === 'tailwindcss/utilities' ||\n id === 'tailwindcss/utilities.css' ||\n id === './utilities.css'\n ) {\n return {\n base,\n content: assets.css.utilities,\n }\n }\n\n throw new Error(`The browser build does not support @import for \"${id}\"`)\n }\n\n try {\n let sheet = load()\n\n I.hit(`Loaded stylesheet`, {\n id,\n base,\n size: sheet.content.length,\n })\n\n return sheet\n } catch (err) {\n I.hit(`Failed to load stylesheet`, {\n id,\n base,\n error: (err as Error).message ?? err,\n })\n<|edits_diff|>\n--- packages/@tailwindcss-browser/src/index.ts\n+++ packages/@tailwindcss-browser/src/index.ts\n@@ -20,6 +20,7 @@\n function load() {\n if (id === 'tailwindcss') {\n return {\n+ path: 'virtual:tailwindcss/index.css',\n base,\n content: assets.css.index,\n }\n@@ -29,6 +30,7 @@\n id === './preflight.css'\n ) {\n return {\n+ path: 'virtual:tailwindcss/preflight.css',\n base,\n content: assets.css.preflight,\n }\n@@ -38,6 +40,7 @@\n id === './theme.css'\n ) {\n return {\n+ path: 'virtual:tailwindcss/theme.css',\n base,\n content: assets.css.theme,\n }\n<|current_version|>\n\n lastCss = css\n\n I.start('Compile CSS')\n try {\n compiler = await tailwindcss.compile(css, {\n base: '/',\n loadStylesheet,\n loadModule,\n })\n } finally {\n I.end('Compile CSS')\n I.end(`Create compiler`)\n }\n\n classes.clear()\n}\n\nasync function loadStylesheet(id: string, base: string) {\n function load() {\n if (id === 'tailwindcss') {\n return {\n path: 'virtual:tailwindcss/index.css',\n base,\n content: assets.css.index,\n }\n } else if (\n id === 'tailwindcss/preflight' ||\n id === 'tailwindcss/preflight.css' ||\n id === './preflight.css'\n ) {\n return {\n path: 'virtual:tailwindcss/preflight.css',\n base,\n content: assets.css.preflight,\n }\n } else if (\n id === 'tailwindcss/theme' ||\n id === 'tailwindcss/theme.css' ||\n id === './theme.css'\n ) {\n return {\n path: 'virtual:tailwindcss/theme.css',\n base,\n content: assets.css.theme,\n }\n } else if (\n id === 'tailwindcss/utilities' ||\n id === 'tailwindcss/utilities.css' ||\n id === './utilities.css'\n ) {\n return {\n base,\n content: assets.css.utilities,\n }\n }\n\n throw new Error(`The browser build does not support @import for \"${id}\"`)\n }\n\n try {\n let sheet = load()\n\n I.hit(`Loaded stylesheet`, {\n id,\n base,\n size: sheet.content.length,\n })\n\n return sheet\n } catch (err) {\n I.hit(`Failed to load stylesheet`, {\n id,\n base,\n error: (err as Error).message ?? err,\n })\n<|next_version|>\n\n lastCss = css\n\n I.start('Compile CSS')\n try {\n compiler = await tailwindcss.compile(css, {\n base: '/',\n loadStylesheet,\n loadModule,\n })\n } finally {\n I.end('Compile CSS')\n I.end(`Create compiler`)\n }\n\n classes.clear()\n}\n\nasync function loadStylesheet(id: string, base: string) {\n function load() {\n if (id === 'tailwindcss') {\n return {\n path: 'virtual:tailwindcss/index.css',\n base,\n content: assets.css.index,\n }\n } else if (\n id === 'tailwindcss/preflight' ||\n id === 'tailwindcss/preflight.css' ||\n id === './preflight.css'\n ) {\n return {\n path: 'virtual:tailwindcss/preflight.css',\n base,\n content: assets.css.preflight,\n }\n } else if (\n id === 'tailwindcss/theme' ||\n id === 'tailwindcss/theme.css' ||\n id === './theme.css'\n ) {\n return {\n path: 'virtual:tailwindcss/theme.css',\n base,\n content: assets.css.theme,\n }\n } else if (\n id === 'tailwindcss/utilities' ||\n id === 'tailwindcss/utilities.css' ||\n id === './utilities.css'\n ) {\n return {\n path: 'virtual:tailwindcss/utilities.css',\n base,\n content: assets.css.utilities,\n }\n }\n\n throw new Error(`The browser build does not support @import for \"${id}\"`)\n }\n\n try {\n let sheet = load()\n\n I.hit(`Loaded stylesheet`, {\n id,\n base,\n size: sheet.content.length,\n })\n\n return sheet\n } catch (err) {\n I.hit(`Failed to load stylesheet`, {\n id,\n base,\n error: (err as Error).message ?? err,\n })\n", "current_contents": "\n lastCss = css\n\n I.start('Compile CSS')\n try {\n compiler = await tailwindcss.compile(css, {\n base: '/',\n loadStylesheet,\n loadModule,\n })\n } finally {\n I.end('Compile CSS')\n I.end(`Create compiler`)\n }\n\n classes.clear()\n}\n\nasync function loadStylesheet(id: string, base: string) {\n function load() {\n if (id === 'tailwindcss') {\n return {\n path: 'virtual:tailwindcss/index.css',\n base,\n content: assets.css.index,\n }\n } else if (\n id === 'tailwindcss/preflight' ||\n id === 'tailwindcss/preflight.css' ||\n id === './preflight.css'\n ) {\n return {\n path: 'virtual:tailwindcss/preflight.css',\n base,\n content: assets.css.preflight,\n }\n } else if (\n id === 'tailwindcss/theme' ||\n id === 'tailwindcss/theme.css' ||\n id === './theme.css'\n ) {\n return {\n path: 'virtual:tailwindcss/theme.css',\n base,\n content: assets.css.theme,\n }\n } else if (\n id === 'tailwindcss/utilities' ||\n id === 'tailwindcss/utilities.css' ||\n id === './utilities.css'\n ) {\n return {\n base,\n content: assets.css.utilities,\n }\n }\n\n throw new Error(`The browser build does not support @import for \"${id}\"`)\n }\n\n try {\n let sheet = load()\n\n I.hit(`Loaded stylesheet`, {\n id,\n base,\n size: sheet.content.length,\n })\n\n return sheet\n } catch (err) {\n I.hit(`Failed to load stylesheet`, {\n id,\n base,\n error: (err as Error).message ?? err,\n })"} {"commit": "55d7a65cfcdc08c4b54d509aef29ffba376b1326", "message": "Add `self-baseline-last` (#17476)", "old_file": "packages/tailwindcss/src/utilities.test.ts", "new_file": "packages/tailwindcss/src/utilities.test.ts", "status": "M", "old_contents": " '-place-self-center',\n '-place-self-stretch',\n 'place-self-auto/foo',\n 'place-self-start/foo',\n 'place-self-end/foo',\n 'place-self-center/foo',\n 'place-self-stretch/foo',\n ]),\n ).toEqual('')\n})\n\ntest('self', async () => {\n expect(\n await run([\n 'self-auto',\n 'self-start',\n 'self-end',\n 'self-end-safe',\n 'self-center',\n 'self-center-safe',\n 'self-stretch',\n 'self-baseline',\n ]),\n ).toMatchInlineSnapshot(`\n \".self-auto {\n align-self: auto;\n }\n\n .self-baseline {\n align-self: baseline;\n }\n\n .self-center {\n align-self: center;\n }\n\n .self-center-safe {\n align-self: safe center;\n }\n\n .self-end {\n align-self: flex-end;\n }\n\n .self-end-safe {\n align-self: safe flex-end;\n }\n\n .self-start {\n align-self: flex-start;\n }\n\n .self-stretch {\n align-self: stretch;", "new_contents": " '-place-self-center',\n '-place-self-stretch',\n 'place-self-auto/foo',\n 'place-self-start/foo',\n 'place-self-end/foo',\n 'place-self-center/foo',\n 'place-self-stretch/foo',\n ]),\n ).toEqual('')\n})\n\ntest('self', async () => {\n expect(\n await run([\n 'self-auto',\n 'self-start',\n 'self-end',\n 'self-end-safe',\n 'self-center',\n 'self-center-safe',\n 'self-stretch',\n 'self-baseline',\n 'self-baseline-last',\n ]),\n ).toMatchInlineSnapshot(`\n \".self-auto {\n align-self: auto;\n }\n\n .self-baseline {\n align-self: baseline;\n }\n\n .self-baseline-last {\n align-self: last baseline;\n }\n\n .self-center {\n align-self: center;\n }\n\n .self-center-safe {\n align-self: safe center;\n }\n\n .self-end {\n align-self: flex-end;\n }\n\n .self-end-safe {\n align-self: safe flex-end;\n }\n\n .self-start {\n align-self: flex-start;\n }\n\n .self-stretch {\n align-self: stretch;", "text": "<|original_code|>\n '-place-self-center',\n '-place-self-stretch',\n 'place-self-auto/foo',\n 'place-self-start/foo',\n 'place-self-end/foo',\n 'place-self-center/foo',\n 'place-self-stretch/foo',\n ]),\n ).toEqual('')\n})\n\ntest('self', async () => {\n expect(\n await run([\n 'self-auto',\n 'self-start',\n 'self-end',\n 'self-end-safe',\n 'self-center',\n 'self-center-safe',\n 'self-stretch',\n 'self-baseline',\n ]),\n ).toMatchInlineSnapshot(`\n \".self-auto {\n align-self: auto;\n }\n\n .self-baseline {\n align-self: baseline;\n }\n\n .self-center {\n align-self: center;\n }\n\n .self-center-safe {\n align-self: safe center;\n }\n\n .self-end {\n align-self: flex-end;\n }\n\n .self-end-safe {\n align-self: safe flex-end;\n }\n\n .self-start {\n align-self: flex-start;\n }\n\n .self-stretch {\n align-self: stretch;\n<|edits_diff|>\n--- packages/tailwindcss/src/utilities.test.ts\n+++ packages/tailwindcss/src/utilities.test.ts\n@@ -20,6 +20,7 @@\n 'self-center-safe',\n 'self-stretch',\n 'self-baseline',\n+ 'self-baseline-last',\n ]),\n ).toMatchInlineSnapshot(`\n \".self-auto {\n<|current_version|>\n '-place-self-center',\n '-place-self-stretch',\n 'place-self-auto/foo',\n 'place-self-start/foo',\n 'place-self-end/foo',\n 'place-self-center/foo',\n 'place-self-stretch/foo',\n ]),\n ).toEqual('')\n})\n\ntest('self', async () => {\n expect(\n await run([\n 'self-auto',\n 'self-start',\n 'self-end',\n 'self-end-safe',\n 'self-center',\n 'self-center-safe',\n 'self-stretch',\n 'self-baseline',\n 'self-baseline-last',\n ]),\n ).toMatchInlineSnapshot(`\n \".self-auto {\n align-self: auto;\n }\n\n .self-baseline {\n align-self: baseline;\n }\n\n .self-center {\n align-self: center;\n }\n\n .self-center-safe {\n align-self: safe center;\n }\n\n .self-end {\n align-self: flex-end;\n }\n\n .self-end-safe {\n align-self: safe flex-end;\n }\n\n .self-start {\n align-self: flex-start;\n }\n\n .self-stretch {\n align-self: stretch;\n<|next_version|>\n '-place-self-center',\n '-place-self-stretch',\n 'place-self-auto/foo',\n 'place-self-start/foo',\n 'place-self-end/foo',\n 'place-self-center/foo',\n 'place-self-stretch/foo',\n ]),\n ).toEqual('')\n})\n\ntest('self', async () => {\n expect(\n await run([\n 'self-auto',\n 'self-start',\n 'self-end',\n 'self-end-safe',\n 'self-center',\n 'self-center-safe',\n 'self-stretch',\n 'self-baseline',\n 'self-baseline-last',\n ]),\n ).toMatchInlineSnapshot(`\n \".self-auto {\n align-self: auto;\n }\n\n .self-baseline {\n align-self: baseline;\n }\n\n .self-baseline-last {\n align-self: last baseline;\n }\n\n .self-center {\n align-self: center;\n }\n\n .self-center-safe {\n align-self: safe center;\n }\n\n .self-end {\n align-self: flex-end;\n }\n\n .self-end-safe {\n align-self: safe flex-end;\n }\n\n .self-start {\n align-self: flex-start;\n }\n\n .self-stretch {\n align-self: stretch;\n", "current_contents": " '-place-self-center',\n '-place-self-stretch',\n 'place-self-auto/foo',\n 'place-self-start/foo',\n 'place-self-end/foo',\n 'place-self-center/foo',\n 'place-self-stretch/foo',\n ]),\n ).toEqual('')\n})\n\ntest('self', async () => {\n expect(\n await run([\n 'self-auto',\n 'self-start',\n 'self-end',\n 'self-end-safe',\n 'self-center',\n 'self-center-safe',\n 'self-stretch',\n 'self-baseline',\n 'self-baseline-last',\n ]),\n ).toMatchInlineSnapshot(`\n \".self-auto {\n align-self: auto;\n }\n\n .self-baseline {\n align-self: baseline;\n }\n\n .self-center {\n align-self: center;\n }\n\n .self-center-safe {\n align-self: safe center;\n }\n\n .self-end {\n align-self: flex-end;\n }\n\n .self-end-safe {\n align-self: safe flex-end;\n }\n\n .self-start {\n align-self: flex-start;\n }\n\n .self-stretch {\n align-self: stretch;"} {"commit": "9bbe2e3d08ac7d38c2f6e64cf34eb0fc931ba07f", "message": "Revert: Only expose used CSS variables (#16403)", "old_file": "packages/tailwindcss/tsup.config.ts", "new_file": "packages/tailwindcss/tsup.config.ts", "status": "M", "old_contents": "import { defineConfig } from 'tsup'\n\nexport default defineConfig([\n {\n format: ['esm'],\n minify: true,\n dts: true,\n entry: {\n lib: 'src/index.ts',\n plugin: 'src/plugin.ts',\n colors: 'src/compat/colors.ts',\n 'default-theme': 'src/compat/default-theme.ts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.ts',\n },\n },\n {\n format: ['cjs'],\n minify: true,\n dts: true,\n entry: {\n plugin: 'src/plugin.cts',\n lib: 'src/index.cts',\n colors: 'src/compat/colors.cts',\n 'default-theme': 'src/compat/default-theme.cts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.cts',\n },\n },\n])\n", "new_contents": "import { defineConfig } from 'tsup'\n\nexport default defineConfig([\n {\n format: ['esm'],\n minify: true,\n dts: true,\n entry: {\n lib: 'src/index.ts',\n plugin: 'src/plugin.ts',\n colors: 'src/compat/colors.ts',\n 'default-theme': 'src/compat/default-theme.ts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.ts',\n },\n define: {\n 'process.env.FEATURES_ENV': JSON.stringify(process.env.FEATURES_ENV ?? 'insiders'),\n },\n },\n {\n format: ['cjs'],\n minify: true,\n dts: true,\n entry: {\n plugin: 'src/plugin.cts',\n lib: 'src/index.cts',\n colors: 'src/compat/colors.cts',\n 'default-theme': 'src/compat/default-theme.cts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.cts',\n },\n define: {\n 'process.env.FEATURES_ENV': JSON.stringify(process.env.FEATURES_ENV ?? 'insiders'),\n },\n },\n])\n", "text": "<|original_code|>\nimport { defineConfig } from 'tsup'\n\nexport default defineConfig([\n {\n format: ['esm'],\n minify: true,\n dts: true,\n entry: {\n lib: 'src/index.ts',\n plugin: 'src/plugin.ts',\n colors: 'src/compat/colors.ts',\n 'default-theme': 'src/compat/default-theme.ts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.ts',\n },\n },\n {\n format: ['cjs'],\n minify: true,\n dts: true,\n entry: {\n plugin: 'src/plugin.cts',\n lib: 'src/index.cts',\n colors: 'src/compat/colors.cts',\n 'default-theme': 'src/compat/default-theme.cts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.cts',\n },\n },\n])\n\n<|edits_diff|>\n--- packages/tailwindcss/tsup.config.ts\n+++ packages/tailwindcss/tsup.config.ts\n@@ -11,6 +11,9 @@\n colors: 'src/compat/colors.ts',\n 'default-theme': 'src/compat/default-theme.ts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.ts',\n+ },\n+ define: {\n+ 'process.env.FEATURES_ENV': JSON.stringify(process.env.FEATURES_ENV ?? 'insiders'),\n },\n },\n {\n<|current_version|>\nimport { defineConfig } from 'tsup'\n\nexport default defineConfig([\n {\n format: ['esm'],\n minify: true,\n dts: true,\n entry: {\n lib: 'src/index.ts',\n plugin: 'src/plugin.ts',\n colors: 'src/compat/colors.ts',\n 'default-theme': 'src/compat/default-theme.ts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.ts',\n },\n define: {\n 'process.env.FEATURES_ENV': JSON.stringify(process.env.FEATURES_ENV ?? 'insiders'),\n },\n },\n {\n format: ['cjs'],\n minify: true,\n dts: true,\n entry: {\n plugin: 'src/plugin.cts',\n lib: 'src/index.cts',\n colors: 'src/compat/colors.cts',\n 'default-theme': 'src/compat/default-theme.cts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.cts',\n },\n },\n])\n\n<|next_version|>\nimport { defineConfig } from 'tsup'\n\nexport default defineConfig([\n {\n format: ['esm'],\n minify: true,\n dts: true,\n entry: {\n lib: 'src/index.ts',\n plugin: 'src/plugin.ts',\n colors: 'src/compat/colors.ts',\n 'default-theme': 'src/compat/default-theme.ts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.ts',\n },\n define: {\n 'process.env.FEATURES_ENV': JSON.stringify(process.env.FEATURES_ENV ?? 'insiders'),\n },\n },\n {\n format: ['cjs'],\n minify: true,\n dts: true,\n entry: {\n plugin: 'src/plugin.cts',\n lib: 'src/index.cts',\n colors: 'src/compat/colors.cts',\n 'default-theme': 'src/compat/default-theme.cts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.cts',\n },\n define: {\n 'process.env.FEATURES_ENV': JSON.stringify(process.env.FEATURES_ENV ?? 'insiders'),\n },\n },\n])\n\n", "current_contents": "import { defineConfig } from 'tsup'\n\nexport default defineConfig([\n {\n format: ['esm'],\n minify: true,\n dts: true,\n entry: {\n lib: 'src/index.ts',\n plugin: 'src/plugin.ts',\n colors: 'src/compat/colors.ts',\n 'default-theme': 'src/compat/default-theme.ts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.ts',\n },\n define: {\n 'process.env.FEATURES_ENV': JSON.stringify(process.env.FEATURES_ENV ?? 'insiders'),\n },\n },\n {\n format: ['cjs'],\n minify: true,\n dts: true,\n entry: {\n plugin: 'src/plugin.cts',\n lib: 'src/index.cts',\n colors: 'src/compat/colors.cts',\n 'default-theme': 'src/compat/default-theme.cts',\n 'flatten-color-palette': 'src/compat/flatten-color-palette.cts',\n },\n },\n])\n"} {"commit": "3f8e7647b6a47b944b363ab4af2a8cddd30d2e4a", "message": "Take `NODE_PATH` into account when resolving modules (#16274)", "old_file": "packages/@tailwindcss-node/src/compile.ts", "new_file": "packages/@tailwindcss-node/src/compile.ts", "status": "M", "old_contents": "}\n\n// Attempts to import the module using the native `import()` function. If this\n// fails, it sets up `jiti` and attempts to import this way so that `.ts` files\n// can be resolved properly.\nlet jiti: null | Jiti = null\nasync function importModule(path: string): Promise {\n if (typeof globalThis.__tw_load === 'function') {\n let module = await globalThis.__tw_load(path)\n if (module) {\n return module\n }\n }\n\n try {\n return await import(path)\n } catch (error) {\n jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false })\n return await jiti.import(path)\n }\n}\n\nconst cssResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.css'],\n mainFields: ['style'],\n conditionNames: ['style'],\n})\nasync function resolveCssId(\n id: string,\n base: string,\n customCssResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customCssResolver) {\n let customResolution = await customCssResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(cssResolver, id, base)\n}\n\nconst esmResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'import'],\n})\n\nconst cjsResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'require'],\n})\n\nasync function resolveJsId(\n id: string,\n base: string,\n customJsResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customJsResolver) {\n let customResolution = await customJsResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(esmResolver, id, base).catch(() => runResolver(cjsResolver, id, base))\n}\n", "new_contents": "}\n\n// Attempts to import the module using the native `import()` function. If this\n// fails, it sets up `jiti` and attempts to import this way so that `.ts` files\n// can be resolved properly.\nlet jiti: null | Jiti = null\nasync function importModule(path: string): Promise {\n if (typeof globalThis.__tw_load === 'function') {\n let module = await globalThis.__tw_load(path)\n if (module) {\n return module\n }\n }\n\n try {\n return await import(path)\n } catch (error) {\n jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false })\n return await jiti.import(path)\n }\n}\n\nconst modules = ['node_modules', ...(process.env.NODE_PATH ? [process.env.NODE_PATH] : [])]\n\nconst cssResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.css'],\n mainFields: ['style'],\n conditionNames: ['style'],\n modules,\n})\nasync function resolveCssId(\n id: string,\n base: string,\n customCssResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customCssResolver) {\n let customResolution = await customCssResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(cssResolver, id, base)\n}\n\nconst esmResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'import'],\n modules,\n})\n\nconst cjsResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'require'],\n modules,\n})\n\nasync function resolveJsId(\n id: string,\n base: string,\n customJsResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customJsResolver) {\n let customResolution = await customJsResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(esmResolver, id, base).catch(() => runResolver(cjsResolver, id, base))\n}\n", "text": "<|original_code|>\n}\n\n// Attempts to import the module using the native `import()` function. If this\n// fails, it sets up `jiti` and attempts to import this way so that `.ts` files\n// can be resolved properly.\nlet jiti: null | Jiti = null\nasync function importModule(path: string): Promise {\n if (typeof globalThis.__tw_load === 'function') {\n let module = await globalThis.__tw_load(path)\n if (module) {\n return module\n }\n }\n\n try {\n return await import(path)\n } catch (error) {\n jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false })\n return await jiti.import(path)\n }\n}\n\nconst cssResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.css'],\n mainFields: ['style'],\n conditionNames: ['style'],\n})\nasync function resolveCssId(\n id: string,\n base: string,\n customCssResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customCssResolver) {\n let customResolution = await customCssResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(cssResolver, id, base)\n}\n\nconst esmResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'import'],\n})\n\nconst cjsResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'require'],\n})\n\nasync function resolveJsId(\n id: string,\n base: string,\n customJsResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customJsResolver) {\n let customResolution = await customJsResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(esmResolver, id, base).catch(() => runResolver(cjsResolver, id, base))\n}\n\n<|edits_diff|>\n--- packages/@tailwindcss-node/src/compile.ts\n+++ packages/@tailwindcss-node/src/compile.ts\n@@ -20,12 +20,15 @@\n }\n }\n \n+const modules = ['node_modules', ...(process.env.NODE_PATH ? [process.env.NODE_PATH] : [])]\n+\n const cssResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.css'],\n mainFields: ['style'],\n conditionNames: ['style'],\n+ modules,\n })\n async function resolveCssId(\n id: string,\n@@ -54,6 +57,7 @@\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'import'],\n+ modules,\n })\n \n const cjsResolver = EnhancedResolve.ResolverFactory.createResolver({\n<|current_version|>\n}\n\n// Attempts to import the module using the native `import()` function. If this\n// fails, it sets up `jiti` and attempts to import this way so that `.ts` files\n// can be resolved properly.\nlet jiti: null | Jiti = null\nasync function importModule(path: string): Promise {\n if (typeof globalThis.__tw_load === 'function') {\n let module = await globalThis.__tw_load(path)\n if (module) {\n return module\n }\n }\n\n try {\n return await import(path)\n } catch (error) {\n jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false })\n return await jiti.import(path)\n }\n}\n\nconst modules = ['node_modules', ...(process.env.NODE_PATH ? [process.env.NODE_PATH] : [])]\n\nconst cssResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.css'],\n mainFields: ['style'],\n conditionNames: ['style'],\n modules,\n})\nasync function resolveCssId(\n id: string,\n base: string,\n customCssResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customCssResolver) {\n let customResolution = await customCssResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(cssResolver, id, base)\n}\n\nconst esmResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'import'],\n modules,\n})\n\nconst cjsResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'require'],\n})\n\nasync function resolveJsId(\n id: string,\n base: string,\n customJsResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customJsResolver) {\n let customResolution = await customJsResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(esmResolver, id, base).catch(() => runResolver(cjsResolver, id, base))\n}\n\n<|next_version|>\n}\n\n// Attempts to import the module using the native `import()` function. If this\n// fails, it sets up `jiti` and attempts to import this way so that `.ts` files\n// can be resolved properly.\nlet jiti: null | Jiti = null\nasync function importModule(path: string): Promise {\n if (typeof globalThis.__tw_load === 'function') {\n let module = await globalThis.__tw_load(path)\n if (module) {\n return module\n }\n }\n\n try {\n return await import(path)\n } catch (error) {\n jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false })\n return await jiti.import(path)\n }\n}\n\nconst modules = ['node_modules', ...(process.env.NODE_PATH ? [process.env.NODE_PATH] : [])]\n\nconst cssResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.css'],\n mainFields: ['style'],\n conditionNames: ['style'],\n modules,\n})\nasync function resolveCssId(\n id: string,\n base: string,\n customCssResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customCssResolver) {\n let customResolution = await customCssResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(cssResolver, id, base)\n}\n\nconst esmResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'import'],\n modules,\n})\n\nconst cjsResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'require'],\n modules,\n})\n\nasync function resolveJsId(\n id: string,\n base: string,\n customJsResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customJsResolver) {\n let customResolution = await customJsResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(esmResolver, id, base).catch(() => runResolver(cjsResolver, id, base))\n}\n\n", "current_contents": "}\n\n// Attempts to import the module using the native `import()` function. If this\n// fails, it sets up `jiti` and attempts to import this way so that `.ts` files\n// can be resolved properly.\nlet jiti: null | Jiti = null\nasync function importModule(path: string): Promise {\n if (typeof globalThis.__tw_load === 'function') {\n let module = await globalThis.__tw_load(path)\n if (module) {\n return module\n }\n }\n\n try {\n return await import(path)\n } catch (error) {\n jiti ??= createJiti(import.meta.url, { moduleCache: false, fsCache: false })\n return await jiti.import(path)\n }\n}\n\nconst modules = ['node_modules', ...(process.env.NODE_PATH ? [process.env.NODE_PATH] : [])]\n\nconst cssResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.css'],\n mainFields: ['style'],\n conditionNames: ['style'],\n modules,\n})\nasync function resolveCssId(\n id: string,\n base: string,\n customCssResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customCssResolver) {\n let customResolution = await customCssResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(cssResolver, id, base)\n}\n\nconst esmResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'import'],\n modules,\n})\n\nconst cjsResolver = EnhancedResolve.ResolverFactory.createResolver({\n fileSystem: new EnhancedResolve.CachedInputFileSystem(fs, 4000),\n useSyncFileSystemCalls: true,\n extensions: ['.js', '.json', '.node', '.ts'],\n conditionNames: ['node', 'require'],\n})\n\nasync function resolveJsId(\n id: string,\n base: string,\n customJsResolver?: Resolver,\n): Promise {\n if (typeof globalThis.__tw_resolve === 'function') {\n let resolved = globalThis.__tw_resolve(id, base)\n if (resolved) {\n return Promise.resolve(resolved)\n }\n }\n\n if (customJsResolver) {\n let customResolution = await customJsResolver(id, base)\n if (customResolution) {\n return customResolution\n }\n }\n\n return runResolver(esmResolver, id, base).catch(() => runResolver(cjsResolver, id, base))\n}\n"} {"commit": "af15e1bdc00119a7eb93e7d74ffb4f0c12b76e6b", "message": "Add support for `important` in v4 (#14448)", "old_file": "packages/tailwindcss/src/compat/config/resolve-config.ts", "new_file": "packages/tailwindcss/src/compat/config/resolve-config.ts", "status": "M", "old_contents": " type UserConfig,\n} from './types'\n\nexport interface ConfigFile {\n path?: string\n base: string\n config: UserConfig\n}\n\ninterface ResolutionContext {\n design: DesignSystem\n configs: UserConfig[]\n plugins: PluginWithConfig[]\n content: ResolvedContentConfig\n theme: Record\n extend: Record\n result: ResolvedConfig\n}\n\nlet minimal: ResolvedConfig = {\n blocklist: [],\n prefix: '',\n darkMode: null,\n theme: {},\n plugins: [],\n content: {\n files: [],\n },\n}\n\nexport function resolveConfig(design: DesignSystem, files: ConfigFile[]): ResolvedConfig {\n let ctx: ResolutionContext = {\n design,\n configs: [],\n plugins: [],\n content: {\n files: [],\n },\n theme: {},\n extend: {},\n\n // Start with a minimal valid, but empty config\n result: structuredClone(minimal),\n }\n\n for (let file of files) {\n extractConfigs(ctx, file)\n }\n\n // Merge top level keys\n for (let config of ctx.configs) {\n if ('darkMode' in config && config.darkMode !== undefined) {\n ctx.result.darkMode = config.darkMode ?? null\n }\n\n if ('prefix' in config && config.prefix !== undefined) {\n ctx.result.prefix = config.prefix ?? ''\n }\n\n if ('blocklist' in config && config.blocklist !== undefined) {\n ctx.result.blocklist = config.blocklist ?? []\n }\n }\n\n // Merge themes\n mergeTheme(ctx)\n\n return {\n ...ctx.result,\n content: ctx.content,\n theme: ctx.theme as ResolvedConfig['theme'],\n plugins: ctx.plugins,\n }\n}\n\nfunction mergeThemeExtension(\n themeValue: ThemeValue | ThemeValue[],\n extensionValue: ThemeValue | ThemeValue[],\n) {\n // When we have an array of objects, we do want to merge it\n if (Array.isArray(themeValue) && isPlainObject(themeValue[0])) {\n return themeValue.concat(extensionValue)\n }\n\n // When the incoming value is an array, and the existing config is an object,", "new_contents": " type UserConfig,\n} from './types'\n\nexport interface ConfigFile {\n path?: string\n base: string\n config: UserConfig\n}\n\ninterface ResolutionContext {\n design: DesignSystem\n configs: UserConfig[]\n plugins: PluginWithConfig[]\n content: ResolvedContentConfig\n theme: Record\n extend: Record\n result: ResolvedConfig\n}\n\nlet minimal: ResolvedConfig = {\n blocklist: [],\n prefix: '',\n important: false,\n darkMode: null,\n theme: {},\n plugins: [],\n content: {\n files: [],\n },\n}\n\nexport function resolveConfig(design: DesignSystem, files: ConfigFile[]): ResolvedConfig {\n let ctx: ResolutionContext = {\n design,\n configs: [],\n plugins: [],\n content: {\n files: [],\n },\n theme: {},\n extend: {},\n\n // Start with a minimal valid, but empty config\n result: structuredClone(minimal),\n }\n\n for (let file of files) {\n extractConfigs(ctx, file)\n }\n\n // Merge top level keys\n for (let config of ctx.configs) {\n if ('darkMode' in config && config.darkMode !== undefined) {\n ctx.result.darkMode = config.darkMode ?? null\n }\n\n if ('prefix' in config && config.prefix !== undefined) {\n ctx.result.prefix = config.prefix ?? ''\n }\n\n if ('blocklist' in config && config.blocklist !== undefined) {\n ctx.result.blocklist = config.blocklist ?? []\n }\n\n if ('important' in config && config.important !== undefined) {\n ctx.result.important = config.important ?? false\n }\n }\n\n // Merge themes\n mergeTheme(ctx)\n\n return {\n ...ctx.result,\n content: ctx.content,\n theme: ctx.theme as ResolvedConfig['theme'],\n plugins: ctx.plugins,\n }\n}\n\nfunction mergeThemeExtension(\n themeValue: ThemeValue | ThemeValue[],\n extensionValue: ThemeValue | ThemeValue[],\n) {\n // When we have an array of objects, we do want to merge it\n if (Array.isArray(themeValue) && isPlainObject(themeValue[0])) {\n return themeValue.concat(extensionValue)\n }\n\n // When the incoming value is an array, and the existing config is an object,", "text": "<|original_code|>\n type UserConfig,\n} from './types'\n\nexport interface ConfigFile {\n path?: string\n base: string\n config: UserConfig\n}\n\ninterface ResolutionContext {\n design: DesignSystem\n configs: UserConfig[]\n plugins: PluginWithConfig[]\n content: ResolvedContentConfig\n theme: Record\n extend: Record\n result: ResolvedConfig\n}\n\nlet minimal: ResolvedConfig = {\n blocklist: [],\n prefix: '',\n darkMode: null,\n theme: {},\n plugins: [],\n content: {\n files: [],\n },\n}\n\nexport function resolveConfig(design: DesignSystem, files: ConfigFile[]): ResolvedConfig {\n let ctx: ResolutionContext = {\n design,\n configs: [],\n plugins: [],\n content: {\n files: [],\n },\n theme: {},\n extend: {},\n\n // Start with a minimal valid, but empty config\n result: structuredClone(minimal),\n }\n\n for (let file of files) {\n extractConfigs(ctx, file)\n }\n\n // Merge top level keys\n for (let config of ctx.configs) {\n if ('darkMode' in config && config.darkMode !== undefined) {\n ctx.result.darkMode = config.darkMode ?? null\n }\n\n if ('prefix' in config && config.prefix !== undefined) {\n ctx.result.prefix = config.prefix ?? ''\n }\n\n if ('blocklist' in config && config.blocklist !== undefined) {\n ctx.result.blocklist = config.blocklist ?? []\n }\n }\n\n // Merge themes\n mergeTheme(ctx)\n\n return {\n ...ctx.result,\n content: ctx.content,\n theme: ctx.theme as ResolvedConfig['theme'],\n plugins: ctx.plugins,\n }\n}\n\nfunction mergeThemeExtension(\n themeValue: ThemeValue | ThemeValue[],\n extensionValue: ThemeValue | ThemeValue[],\n) {\n // When we have an array of objects, we do want to merge it\n if (Array.isArray(themeValue) && isPlainObject(themeValue[0])) {\n return themeValue.concat(extensionValue)\n }\n\n // When the incoming value is an array, and the existing config is an object,\n<|edits_diff|>\n--- packages/tailwindcss/src/compat/config/resolve-config.ts\n+++ packages/tailwindcss/src/compat/config/resolve-config.ts\n@@ -20,6 +20,7 @@\n let minimal: ResolvedConfig = {\n blocklist: [],\n prefix: '',\n+ important: false,\n darkMode: null,\n theme: {},\n plugins: [],\n<|current_version|>\n type UserConfig,\n} from './types'\n\nexport interface ConfigFile {\n path?: string\n base: string\n config: UserConfig\n}\n\ninterface ResolutionContext {\n design: DesignSystem\n configs: UserConfig[]\n plugins: PluginWithConfig[]\n content: ResolvedContentConfig\n theme: Record\n extend: Record\n result: ResolvedConfig\n}\n\nlet minimal: ResolvedConfig = {\n blocklist: [],\n prefix: '',\n important: false,\n darkMode: null,\n theme: {},\n plugins: [],\n content: {\n files: [],\n },\n}\n\nexport function resolveConfig(design: DesignSystem, files: ConfigFile[]): ResolvedConfig {\n let ctx: ResolutionContext = {\n design,\n configs: [],\n plugins: [],\n content: {\n files: [],\n },\n theme: {},\n extend: {},\n\n // Start with a minimal valid, but empty config\n result: structuredClone(minimal),\n }\n\n for (let file of files) {\n extractConfigs(ctx, file)\n }\n\n // Merge top level keys\n for (let config of ctx.configs) {\n if ('darkMode' in config && config.darkMode !== undefined) {\n ctx.result.darkMode = config.darkMode ?? null\n }\n\n if ('prefix' in config && config.prefix !== undefined) {\n ctx.result.prefix = config.prefix ?? ''\n }\n\n if ('blocklist' in config && config.blocklist !== undefined) {\n ctx.result.blocklist = config.blocklist ?? []\n }\n }\n\n // Merge themes\n mergeTheme(ctx)\n\n return {\n ...ctx.result,\n content: ctx.content,\n theme: ctx.theme as ResolvedConfig['theme'],\n plugins: ctx.plugins,\n }\n}\n\nfunction mergeThemeExtension(\n themeValue: ThemeValue | ThemeValue[],\n extensionValue: ThemeValue | ThemeValue[],\n) {\n // When we have an array of objects, we do want to merge it\n if (Array.isArray(themeValue) && isPlainObject(themeValue[0])) {\n return themeValue.concat(extensionValue)\n }\n\n // When the incoming value is an array, and the existing config is an object,\n<|next_version|>\n type UserConfig,\n} from './types'\n\nexport interface ConfigFile {\n path?: string\n base: string\n config: UserConfig\n}\n\ninterface ResolutionContext {\n design: DesignSystem\n configs: UserConfig[]\n plugins: PluginWithConfig[]\n content: ResolvedContentConfig\n theme: Record\n extend: Record\n result: ResolvedConfig\n}\n\nlet minimal: ResolvedConfig = {\n blocklist: [],\n prefix: '',\n important: false,\n darkMode: null,\n theme: {},\n plugins: [],\n content: {\n files: [],\n },\n}\n\nexport function resolveConfig(design: DesignSystem, files: ConfigFile[]): ResolvedConfig {\n let ctx: ResolutionContext = {\n design,\n configs: [],\n plugins: [],\n content: {\n files: [],\n },\n theme: {},\n extend: {},\n\n // Start with a minimal valid, but empty config\n result: structuredClone(minimal),\n }\n\n for (let file of files) {\n extractConfigs(ctx, file)\n }\n\n // Merge top level keys\n for (let config of ctx.configs) {\n if ('darkMode' in config && config.darkMode !== undefined) {\n ctx.result.darkMode = config.darkMode ?? null\n }\n\n if ('prefix' in config && config.prefix !== undefined) {\n ctx.result.prefix = config.prefix ?? ''\n }\n\n if ('blocklist' in config && config.blocklist !== undefined) {\n ctx.result.blocklist = config.blocklist ?? []\n }\n\n if ('important' in config && config.important !== undefined) {\n ctx.result.important = config.important ?? false\n }\n }\n\n // Merge themes\n mergeTheme(ctx)\n\n return {\n ...ctx.result,\n content: ctx.content,\n theme: ctx.theme as ResolvedConfig['theme'],\n plugins: ctx.plugins,\n }\n}\n\nfunction mergeThemeExtension(\n themeValue: ThemeValue | ThemeValue[],\n extensionValue: ThemeValue | ThemeValue[],\n) {\n // When we have an array of objects, we do want to merge it\n if (Array.isArray(themeValue) && isPlainObject(themeValue[0])) {\n return themeValue.concat(extensionValue)\n }\n\n // When the incoming value is an array, and the existing config is an object,\n", "current_contents": " type UserConfig,\n} from './types'\n\nexport interface ConfigFile {\n path?: string\n base: string\n config: UserConfig\n}\n\ninterface ResolutionContext {\n design: DesignSystem\n configs: UserConfig[]\n plugins: PluginWithConfig[]\n content: ResolvedContentConfig\n theme: Record\n extend: Record\n result: ResolvedConfig\n}\n\nlet minimal: ResolvedConfig = {\n blocklist: [],\n prefix: '',\n important: false,\n darkMode: null,\n theme: {},\n plugins: [],\n content: {\n files: [],\n },\n}\n\nexport function resolveConfig(design: DesignSystem, files: ConfigFile[]): ResolvedConfig {\n let ctx: ResolutionContext = {\n design,\n configs: [],\n plugins: [],\n content: {\n files: [],\n },\n theme: {},\n extend: {},\n\n // Start with a minimal valid, but empty config\n result: structuredClone(minimal),\n }\n\n for (let file of files) {\n extractConfigs(ctx, file)\n }\n\n // Merge top level keys\n for (let config of ctx.configs) {\n if ('darkMode' in config && config.darkMode !== undefined) {\n ctx.result.darkMode = config.darkMode ?? null\n }\n\n if ('prefix' in config && config.prefix !== undefined) {\n ctx.result.prefix = config.prefix ?? ''\n }\n\n if ('blocklist' in config && config.blocklist !== undefined) {\n ctx.result.blocklist = config.blocklist ?? []\n }\n }\n\n // Merge themes\n mergeTheme(ctx)\n\n return {\n ...ctx.result,\n content: ctx.content,\n theme: ctx.theme as ResolvedConfig['theme'],\n plugins: ctx.plugins,\n }\n}\n\nfunction mergeThemeExtension(\n themeValue: ThemeValue | ThemeValue[],\n extensionValue: ThemeValue | ThemeValue[],\n) {\n // When we have an array of objects, we do want to merge it\n if (Array.isArray(themeValue) && isPlainObject(themeValue[0])) {\n return themeValue.concat(extensionValue)\n }\n\n // When the incoming value is an array, and the existing config is an object,"} {"commit": "bc88958855051c44a95b782a0a6f41f4ba4d8812", "message": "Add support for the CSS `theme()` function (#14177)", "old_file": "packages/tailwindcss/src/theme.ts", "new_file": "packages/tailwindcss/src/theme.ts", "status": "M", "old_contents": " let themeKey = this.#resolveKey(candidateValue, themeKeys)\n\n if (!themeKey) return null\n\n let extra = {} as Record\n for (let name of nestedKeys) {\n let nestedValue = this.#var(`${themeKey}${name}`)\n if (nestedValue) {\n extra[name] = nestedValue\n }\n }\n\n return [this.#var(themeKey)!, extra]\n }\n\n namespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.value)\n }\n }\n\n return values\n }\n\n resolveNamespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.isInline ? value.value : this.#var(key)!)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.isInline ? value.value : this.#var(key)!)\n }\n }\n\n return values\n }\n}\n\nexport type ThemeKey =\n | '--accent-color'\n | '--animate'\n | '--aspect-ratio'\n | '--backdrop-blur'\n | '--backdrop-brightness'\n | '--backdrop-contrast'\n | '--backdrop-grayscale'\n | '--backdrop-hue-rotate'\n | '--backdrop-invert'\n | '--backdrop-opacity'\n | '--backdrop-saturate'\n | '--backdrop-sepia'\n | '--background-color'\n | '--background-image'", "new_contents": " let themeKey = this.#resolveKey(candidateValue, themeKeys)\n\n if (!themeKey) return null\n\n let extra = {} as Record\n for (let name of nestedKeys) {\n let nestedValue = this.#var(`${themeKey}${name}`)\n if (nestedValue) {\n extra[name] = nestedValue\n }\n }\n\n return [this.#var(themeKey)!, extra]\n }\n\n namespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.value)\n } else if (key.startsWith(`${prefix}-`)) {\n // Preserve `--` prefix for sub-variables\n // e.g. `--font-size-sm--line-height`\n values.set(key.slice(namespace.length), value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.value)\n }\n }\n\n return values\n }\n\n resolveNamespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.isInline ? value.value : this.#var(key)!)\n } else if (key.startsWith(`${prefix}-`)) {\n // Preserve `--` prefix for sub-variables\n // e.g. `--font-size-sm--line-height`\n values.set(key.slice(namespace.length), value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.isInline ? value.value : this.#var(key)!)\n }\n }\n\n return values\n }\n}\n\nexport type ThemeKey =\n | '--accent-color'\n | '--animate'\n | '--aspect-ratio'\n | '--backdrop-blur'\n | '--backdrop-brightness'\n | '--backdrop-contrast'\n | '--backdrop-grayscale'\n | '--backdrop-hue-rotate'\n | '--backdrop-invert'\n | '--backdrop-opacity'\n | '--backdrop-saturate'\n | '--backdrop-sepia'\n | '--background-color'\n | '--background-image'", "text": "<|original_code|>\n let themeKey = this.#resolveKey(candidateValue, themeKeys)\n\n if (!themeKey) return null\n\n let extra = {} as Record\n for (let name of nestedKeys) {\n let nestedValue = this.#var(`${themeKey}${name}`)\n if (nestedValue) {\n extra[name] = nestedValue\n }\n }\n\n return [this.#var(themeKey)!, extra]\n }\n\n namespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.value)\n }\n }\n\n return values\n }\n\n resolveNamespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.isInline ? value.value : this.#var(key)!)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.isInline ? value.value : this.#var(key)!)\n }\n }\n\n return values\n }\n}\n\nexport type ThemeKey =\n | '--accent-color'\n | '--animate'\n | '--aspect-ratio'\n | '--backdrop-blur'\n | '--backdrop-brightness'\n | '--backdrop-contrast'\n | '--backdrop-grayscale'\n | '--backdrop-hue-rotate'\n | '--backdrop-invert'\n | '--backdrop-opacity'\n | '--backdrop-saturate'\n | '--backdrop-sepia'\n | '--background-color'\n | '--background-image'\n<|edits_diff|>\n--- packages/tailwindcss/src/theme.ts\n+++ packages/tailwindcss/src/theme.ts\n@@ -20,6 +20,10 @@\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.value)\n+ } else if (key.startsWith(`${prefix}-`)) {\n+ // Preserve `--` prefix for sub-variables\n+ // e.g. `--font-size-sm--line-height`\n+ values.set(key.slice(namespace.length), value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.value)\n }\n<|current_version|>\n let themeKey = this.#resolveKey(candidateValue, themeKeys)\n\n if (!themeKey) return null\n\n let extra = {} as Record\n for (let name of nestedKeys) {\n let nestedValue = this.#var(`${themeKey}${name}`)\n if (nestedValue) {\n extra[name] = nestedValue\n }\n }\n\n return [this.#var(themeKey)!, extra]\n }\n\n namespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.value)\n } else if (key.startsWith(`${prefix}-`)) {\n // Preserve `--` prefix for sub-variables\n // e.g. `--font-size-sm--line-height`\n values.set(key.slice(namespace.length), value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.value)\n }\n }\n\n return values\n }\n\n resolveNamespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.isInline ? value.value : this.#var(key)!)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.isInline ? value.value : this.#var(key)!)\n }\n }\n\n return values\n }\n}\n\nexport type ThemeKey =\n | '--accent-color'\n | '--animate'\n | '--aspect-ratio'\n | '--backdrop-blur'\n | '--backdrop-brightness'\n | '--backdrop-contrast'\n | '--backdrop-grayscale'\n | '--backdrop-hue-rotate'\n | '--backdrop-invert'\n | '--backdrop-opacity'\n | '--backdrop-saturate'\n | '--backdrop-sepia'\n | '--background-color'\n | '--background-image'\n<|next_version|>\n let themeKey = this.#resolveKey(candidateValue, themeKeys)\n\n if (!themeKey) return null\n\n let extra = {} as Record\n for (let name of nestedKeys) {\n let nestedValue = this.#var(`${themeKey}${name}`)\n if (nestedValue) {\n extra[name] = nestedValue\n }\n }\n\n return [this.#var(themeKey)!, extra]\n }\n\n namespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.value)\n } else if (key.startsWith(`${prefix}-`)) {\n // Preserve `--` prefix for sub-variables\n // e.g. `--font-size-sm--line-height`\n values.set(key.slice(namespace.length), value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.value)\n }\n }\n\n return values\n }\n\n resolveNamespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.isInline ? value.value : this.#var(key)!)\n } else if (key.startsWith(`${prefix}-`)) {\n // Preserve `--` prefix for sub-variables\n // e.g. `--font-size-sm--line-height`\n values.set(key.slice(namespace.length), value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.isInline ? value.value : this.#var(key)!)\n }\n }\n\n return values\n }\n}\n\nexport type ThemeKey =\n | '--accent-color'\n | '--animate'\n | '--aspect-ratio'\n | '--backdrop-blur'\n | '--backdrop-brightness'\n | '--backdrop-contrast'\n | '--backdrop-grayscale'\n | '--backdrop-hue-rotate'\n | '--backdrop-invert'\n | '--backdrop-opacity'\n | '--backdrop-saturate'\n | '--backdrop-sepia'\n | '--background-color'\n | '--background-image'\n", "current_contents": " let themeKey = this.#resolveKey(candidateValue, themeKeys)\n\n if (!themeKey) return null\n\n let extra = {} as Record\n for (let name of nestedKeys) {\n let nestedValue = this.#var(`${themeKey}${name}`)\n if (nestedValue) {\n extra[name] = nestedValue\n }\n }\n\n return [this.#var(themeKey)!, extra]\n }\n\n namespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.value)\n } else if (key.startsWith(`${prefix}-`)) {\n // Preserve `--` prefix for sub-variables\n // e.g. `--font-size-sm--line-height`\n values.set(key.slice(namespace.length), value.value)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.value)\n }\n }\n\n return values\n }\n\n resolveNamespace(namespace: string) {\n let values = new Map()\n let prefix = `${namespace}-`\n\n for (let [key, value] of this.values) {\n if (key === namespace) {\n values.set(null, value.isInline ? value.value : this.#var(key)!)\n } else if (key.startsWith(prefix)) {\n values.set(key.slice(prefix.length), value.isInline ? value.value : this.#var(key)!)\n }\n }\n\n return values\n }\n}\n\nexport type ThemeKey =\n | '--accent-color'\n | '--animate'\n | '--aspect-ratio'\n | '--backdrop-blur'\n | '--backdrop-brightness'\n | '--backdrop-contrast'\n | '--backdrop-grayscale'\n | '--backdrop-hue-rotate'\n | '--backdrop-invert'\n | '--backdrop-opacity'\n | '--backdrop-saturate'\n | '--backdrop-sepia'\n | '--background-color'\n | '--background-image'"}