content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Python
Python
add missing ckpt in config docs
3e47d19cfc2f44ce3175b1e73f01db88242c743e
<ide><path>src/transformers/models/albert/configuration_albert.py <ide> class AlbertConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`AlbertModel`] or a [`TFAlbertModel`]. It is used <ide> to instantiate an ALBERT model according to the specified arguments, defining the model architecture. Instantiating <ide> a configuration with the defaults will yield a similar configuration to that of the ALBERT <del> [xxlarge](https://huggingface.co/albert-xxlarge-v2) architecture. <add> [albert-xxlarge-v2](https://huggingface.co/albert-xxlarge-v2) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/beit/configuration_beit.py <ide> logger = logging.get_logger(__name__) <ide> <ide> BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "microsoft/beit-base-patch16-224-in22k": "https://huggingface.co/microsoft/beit-base-patch16-224-in22k/resolve/main/config.json", <add> "microsoft/beit-base-patch16-224-pt22k": "https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json", <ide> # See all BEiT models at https://huggingface.co/models?filter=beit <ide> } <ide> <ide> class BeitConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`BeitModel`]. It is used to instantiate an BEiT <ide> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <ide> defaults will yield a similar configuration to that of the BEiT <del> [microsoft/beit-base-patch16-224-in22k](https://huggingface.co/microsoft/beit-base-patch16-224-in22k) architecture. <add> [microsoft/beit-base-patch16-224-pt22k](https://huggingface.co/microsoft/beit-base-patch16-224-pt22k) architecture. <ide> <ide> Args: <ide> vocab_size (`int`, *optional*, defaults to 8092): <ide> class BeitConfig(PretrainedConfig): <ide> ```python <ide> >>> from transformers import BeitModel, BeitConfig <ide> <del> >>> # Initializing a BEiT beit-base-patch16-224-in22k style configuration <add> >>> # Initializing a BEiT beit-base-patch16-224-pt22k style configuration <ide> >>> configuration = BeitConfig() <ide> <del> >>> # Initializing a model from the beit-base-patch16-224-in22k style configuration <add> >>> # Initializing a model from the beit-base-patch16-224-pt22k style configuration <ide> >>> model = BeitModel(configuration) <ide> <ide> >>> # Accessing the model configuration <ide><path>src/transformers/models/bert_generation/configuration_bert_generation.py <ide> class BertGenerationConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`BertGenerationPreTrainedModel`]. It is used to <ide> instantiate a BertGeneration model according to the specified arguments, defining the model architecture. <add> Instantiating a configuration with the defaults will yield a similar configuration to that of the BertGeneration <add> [google/bert_for_seq_generation_L-24_bbc_encoder](https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder) <add> architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/camembert/configuration_camembert.py <ide> class CamembertConfig(RobertaConfig): <ide> """ <ide> This class overrides [`RobertaConfig`]. Please check the superclass for the appropriate documentation alongside <del> usage examples. <add> usage examples. Instantiating a configuration with the defaults will yield a similar configuration to that of the <add> Camembert [camembert-base](https://huggingface.co/camembert-base) architecture. <ide> """ <ide> <ide> model_type = "camembert" <ide><path>src/transformers/models/deberta_v2/configuration_deberta_v2.py <ide> class DebertaV2Config(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`DebertaV2Model`]. It is used to instantiate a <ide> DeBERTa-v2 model according to the specified arguments, defining the model architecture. Instantiating a <ide> configuration with the defaults will yield a similar configuration to that of the DeBERTa <del> [microsoft/deberta-v2-xlarge](https://huggingface.co/microsoft/deberta-base) architecture. <add> [microsoft/deberta-v2-xlarge](https://huggingface.co/microsoft/deberta-v2-xlarge) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/dpr/configuration_dpr.py <ide> class DPRConfig(PretrainedConfig): <ide> [`DPRConfig`] is the configuration class to store the configuration of a *DPRModel*. <ide> <ide> This is the configuration class to store the configuration of a [`DPRContextEncoder`], [`DPRQuestionEncoder`], or a <del> [`DPRReader`]. It is used to instantiate the components of the DPR model. <add> [`DPRReader`]. It is used to instantiate the components of the DPR model according to the specified arguments, <add> defining the model component architectures. Instantiating a configuration with the defaults will yield a similar <add> configuration to that of the DPRContextEncoder <add> [facebook/dpr-ctx_encoder-single-nq-base](https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base) <add> architecture. <ide> <ide> This class is a subclass of [`BertConfig`]. Please check the superclass for the documentation of all kwargs. <ide> <ide><path>src/transformers/models/flaubert/configuration_flaubert.py <ide> class FlaubertConfig(XLMConfig): <ide> """ <ide> This is the configuration class to store the configuration of a [`FlaubertModel`] or a [`TFFlaubertModel`]. It is <ide> used to instantiate a FlauBERT model according to the specified arguments, defining the model architecture. <add> Instantiating a configuration with the defaults will yield a similar configuration to that of the FlauBERT <add> [flaubert/flaubert_base_uncased](https://huggingface.co/flaubert/flaubert_base_uncased) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/fnet/configuration_fnet.py <ide> class FNetConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`FNetModel`]. It is used to instantiate an FNet <ide> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <ide> defaults will yield a similar configuration to that of the FNet <del> [fnet-base](https://huggingface.co/google/fnet-base) architecture. <add> [google/fnet-base](https://huggingface.co/google/fnet-base) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/fsmt/configuration_fsmt.py <ide> def __init__(self, vocab_size=0, bos_token_id=0): <ide> class FSMTConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`FSMTModel`]. It is used to instantiate a FSMT <del> model according to the specified arguments, defining the model architecture. <add> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <add> defaults will yield a similar configuration to that of the FSMT <add> [facebook/wmt19-en-ru](https://huggingface.co/facebook/wmt19-en-ru) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/glpn/configuration_glpn.py <ide> logger = logging.get_logger(__name__) <ide> <ide> GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "vinvino02/glpn-kitti": "https://huggingface.co/vinvino02/gdpdepth-kitti/resolve/main/config.json", <del> # See all GLPN models at https://huggingface.co/models?filter=gdpdepth <add> "vinvino02/glpn-kitti": "https://huggingface.co/vinvino02/glpn-kitti/resolve/main/config.json", <add> # See all GLPN models at https://huggingface.co/models?filter=glpn <ide> } <ide> <ide> <ide> class GLPNConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`GLPNModel`]. It is used to instantiate an GLPN <ide> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <ide> defaults will yield a similar configuration to that of the GLPN <del> [kaist/gdpdepth-kitti](https://huggingface.co/kaist/gdpdepth-kitti) architecture. <add> [vinvino02/glpn-kitti](https://huggingface.co/vinvino02/glpn-kitti) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide> class GLPNConfig(PretrainedConfig): <ide> ```python <ide> >>> from transformers import GLPNModel, GLPNConfig <ide> <del> >>> # Initializing a GLPN kaist/gdpdepth-kitti style configuration <add> >>> # Initializing a GLPN vinvino02/glpn-kitti style configuration <ide> >>> configuration = GLPNConfig() <ide> <del> >>> # Initializing a model from the kaist/gdpdepth-kitti style configuration <add> >>> # Initializing a model from the vinvino02/glpn-kitti style configuration <ide> >>> model = GLPNModel(configuration) <ide> <ide> >>> # Accessing the model configuration <ide><path>src/transformers/models/gpt2/configuration_gpt2.py <ide> class GPT2Config(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`GPT2Model`] or a [`TFGPT2Model`]. It is used to <ide> instantiate a GPT-2 model according to the specified arguments, defining the model architecture. Instantiating a <ide> configuration with the defaults will yield a similar configuration to that of the GPT-2 <del> [small](https://huggingface.co/gpt2) architecture. <add> [gpt2](https://huggingface.co/gpt2) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/gpt_neo/configuration_gpt_neo.py <ide> class GPTNeoConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`GPTNeoModel`]. It is used to instantiate a GPT <ide> Neo model according to the specified arguments, defining the model architecture. Instantiating a configuration with <ide> the defaults will yield a similar configuration to that of the GPTNeo <del> [gpt-neo-1.3B](https://huggingface.co/EleutherAI/gpt-neo-1.3B) architecture. <add> [EleutherAI/gpt-neo-1.3B](https://huggingface.co/EleutherAI/gpt-neo-1.3B) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/gptj/configuration_gptj.py <ide> class GPTJConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`GPTJModel`]. It is used to instantiate a GPT-J <ide> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <ide> defaults will yield a similar configuration to that of the GPT-J <del> [gpt-j-6B](https://huggingface.co/EleutherAI/gpt-j-6B) architecture. Configuration objects inherit from <add> [EleutherAI/gpt-j-6B](https://huggingface.co/EleutherAI/gpt-j-6B) architecture. Configuration objects inherit from <ide> [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] <ide> for more information. <ide> <ide><path>src/transformers/models/ibert/configuration_ibert.py <ide> class IBertConfig(PretrainedConfig): <ide> """ <ide> This is the configuration class to store the configuration of a [`IBertModel`]. It is used to instantiate a I-BERT <del> model according to the specified arguments, <add> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <add> defaults will yield a similar configuration to that of the IBERT <add> [kssteven/ibert-roberta-base](https://huggingface.co/kssteven/ibert-roberta-base) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/layoutlm/configuration_layoutlm.py <ide> logger = logging.get_logger(__name__) <ide> <ide> LAYOUTLM_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "layoutlm-base-uncased": "https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/config.json", <del> "layoutlm-large-uncased": "https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/config.json", <add> "microsoft/layoutlm-base-uncased": "https://huggingface.co/microsoft/layoutlm-base-uncased/resolve/main/config.json", <add> "microsoft/layoutlm-large-uncased": "https://huggingface.co/microsoft/layoutlm-large-uncased/resolve/main/config.json", <ide> } <ide> <ide> <ide> class LayoutLMConfig(BertConfig): <ide> This is the configuration class to store the configuration of a [`LayoutLMModel`]. It is used to instantiate a <ide> LayoutLM model according to the specified arguments, defining the model architecture. Instantiating a configuration <ide> with the defaults will yield a similar configuration to that of the LayoutLM <del> [layoutlm-base-uncased](https://huggingface.co/microsoft/layoutlm-base-uncased) architecture. <add> [microsoft/layoutlm-base-uncased](https://huggingface.co/microsoft/layoutlm-base-uncased) architecture. <ide> <ide> Configuration objects inherit from [`BertConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`BertConfig`] for more information. <ide><path>src/transformers/models/longformer/configuration_longformer.py <ide> class LongformerConfig(RobertaConfig): <ide> <ide> This is the configuration class to store the configuration of a [`LongformerModel`]. It is used to instantiate an <ide> Longformer model according to the specified arguments, defining the model architecture. Instantiating a <del> configuration with the defaults will yield a similar configuration to that of the RoBERTa <del> [roberta-base](https://huggingface.co/roberta-base) architecture with a sequence length 4,096. <add> configuration with the defaults will yield a similar configuration to that of the LongFormer <add> [allenai/longformer-base-4096](https://huggingface.co/allenai/longformer-base-4096) architecture with a sequence <add> length 4,096. <ide> <ide> The [`LongformerConfig`] class directly inherits [`RobertaConfig`]. It reuses the same defaults. Please check the <ide> parent class for more information. <ide><path>src/transformers/models/luke/configuration_luke.py <ide> class LukeConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`LukeModel`]. It is used to instantiate a LUKE <del> model according to the specified arguments, defining the model architecture. <add> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <add> defaults will yield a similar configuration to that of the LUKE <add> [studio-ousia/luke-base](https://huggingface.co/studio-ousia/luke-base) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/lxmert/configuration_lxmert.py <ide> logger = logging.get_logger(__name__) <ide> <ide> LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "unc-nlp/lxmert-base-uncased": "", <add> "unc-nlp/lxmert-base-uncased": "https://huggingface.co/unc-nlp/lxmert-base-uncased/resolve/main/config.json", <ide> } <ide> <ide> <ide> class LxmertConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`LxmertModel`] or a [`TFLxmertModel`]. It is used <del> to instantiate a LXMERT model according to the specified arguments, defining the model architecture. <add> to instantiate a LXMERT model according to the specified arguments, defining the model architecture. Instantiating <add> a configuration with the defaults will yield a similar configuration to that of the Lxmert <add> [unc-nlp/lxmert-base-uncased](https://huggingface.co/unc-nlp/lxmert-base-uncased) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/m2m_100/configuration_m2m_100.py <ide> class M2M100Config(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`M2M100Model`]. It is used to instantiate an <ide> M2M100 model according to the specified arguments, defining the model architecture. Instantiating a configuration <ide> with the defaults will yield a similar configuration to that of the M2M100 <del> [m2m100_418M](https://huggingface.co/facebook/m2m100_418M) architecture. <add> [facebook/m2m100_418M](https://huggingface.co/facebook/m2m100_418M) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/maskformer/configuration_maskformer.py <ide> class MaskFormerConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`MaskFormerModel`]. It is used to instantiate a <ide> MaskFormer model according to the specified arguments, defining the model architecture. Instantiating a <del> configuration with the defaults will yield a similar configuration to that of the <del> "facebook/maskformer-swin-base-ade" architecture trained on <del> [ADE20k-150](https://huggingface.co/datasets/scene_parse_150). <add> configuration with the defaults will yield a similar configuration to that of the MaskFormer <add> [facebook/maskformer-swin-base-ade](https://huggingface.co/facebook/maskformer-swin-base-ade) architecture trained <add> on [ADE20k-150](https://huggingface.co/datasets/scene_parse_150). <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/megatron_bert/configuration_megatron_bert.py <ide> class MegatronBertConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`MegatronBertModel`]. It is used to instantiate a <ide> MEGATRON_BERT model according to the specified arguments, defining the model architecture. Instantiating a <ide> configuration with the defaults will yield a similar configuration to that of the MEGATRON_BERT <del> [megatron-bert-uncased-345m](https://huggingface.co/nvidia/megatron-bert-uncased-345m) architecture. <add> [nvidia/megatron-bert-uncased-345m](https://huggingface.co/nvidia/megatron-bert-uncased-345m) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/mobilebert/configuration_mobilebert.py <ide> logger = logging.get_logger(__name__) <ide> <ide> MOBILEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/config.json" <add> "google/mobilebert-uncased": "https://huggingface.co/google/mobilebert-uncased/resolve/main/config.json" <ide> } <ide> <ide> <ide> class MobileBertConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`MobileBertModel`] or a [`TFMobileBertModel`]. It <ide> is used to instantiate a MobileBERT model according to the specified arguments, defining the model architecture. <add> Instantiating a configuration with the defaults will yield a similar configuration to that of the MobileBERT <add> [google/mobilebert-uncased](https://huggingface.co/google/mobilebert-uncased) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/mpnet/configuration_mpnet.py <ide> class MPNetConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`MPNetModel`] or a [`TFMPNetModel`]. It is used to <ide> instantiate a MPNet model according to the specified arguments, defining the model architecture. Instantiating a <ide> configuration with the defaults will yield a similar configuration to that of the MPNet <del> [mpnet-base](https://huggingface.co/mpnet-base) architecture. <add> [microsoft/mpnet-base](https://huggingface.co/microsoft/mpnet-base) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/openai/configuration_openai.py <ide> class OpenAIGPTConfig(PretrainedConfig): <ide> """ <ide> This is the configuration class to store the configuration of a [`OpenAIGPTModel`] or a [`TFOpenAIGPTModel`]. It is <ide> used to instantiate a GPT model according to the specified arguments, defining the model architecture. <del> Instantiating a configuration with the defaults will yield a similar configuration to that of the <del> [GPT](https://huggingface.co/openai-gpt) architecture from OpenAI. <add> Instantiating a configuration with the defaults will yield a similar configuration to that of the GPT <add> [openai-gpt](https://huggingface.co/openai-gpt) architecture from OpenAI. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/prophetnet/configuration_prophetnet.py <ide> class ProphetNetConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`ProphetNetModel`]. It is used to instantiate a <del> ProphetNet model according to the specified arguments, defining the model architecture. <add> ProphetNet model according to the specified arguments, defining the model architecture. Instantiating a <add> configuration with the defaults will yield a similar configuration to that of the ProphetNet <add> [microsoft/prophetnet-large-uncased](https://huggingface.co/microsoft/prophetnet-large-uncased) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/realm/configuration_realm.py <ide> class RealmConfig(PretrainedConfig): <ide> <ide> It is used to instantiate an REALM model according to the specified arguments, defining the model architecture. <ide> Instantiating a configuration with the defaults will yield a similar configuration to that of the REALM <del> [realm-cc-news-pretrained](https://huggingface.co/google/realm-cc-news-pretrained-embedder) architecture. <add> [google/realm-cc-news-pretrained-embedder](https://huggingface.co/google/realm-cc-news-pretrained-embedder) <add> architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/reformer/configuration_reformer.py <ide> class ReformerConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`ReformerModel`]. It is used to instantiate a <del> Reformer model according to the specified arguments, defining the model architecture. <add> Reformer model according to the specified arguments, defining the model architecture. Instantiating a configuration <add> with the defaults will yield a similar configuration to that of the ReFormer <add> [google/reformer-crime-and-punishment](https://huggingface.co/google/reformer-crime-and-punishment) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/regnet/configuration_regnet.py <ide> logger = logging.get_logger(__name__) <ide> <ide> REGNET_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "regnety-40": "https://huggingface.co/zuppif/regnety-040/blob/main/config.json", <add> "facebook/regnet-y-040": "https://huggingface.co/facebook/regnet-y-040/blob/main/config.json", <ide> } <ide> <ide> <ide> class RegNetConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`RegNetModel`]. It is used to instantiate a RegNet <ide> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <del> defaults will yield a similar configuration to that of the <del> [facebook/regnet-y-40](https://huggingface.co/facebook/regnet-y-40) architecture. <add> defaults will yield a similar configuration to that of the RegNet <add> [facebook/regnet-y-040](https://huggingface.co/facebook/regnet-y-040) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/rembert/configuration_rembert.py <ide> class RemBertConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`RemBertModel`]. It is used to instantiate an <ide> RemBERT model according to the specified arguments, defining the model architecture. Instantiating a configuration <del> with the defaults will yield a similar configuration to that of the remert-large architecture. <add> with the defaults will yield a similar configuration to that of the RemBERT <add> [google/rembert](https://huggingface.co/google/rembert) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/resnet/configuration_resnet.py <ide> logger = logging.get_logger(__name__) <ide> <ide> RESNET_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", <add> "microsoft/resnet-50": "https://huggingface.co/microsoft/resnet-50/blob/main/config.json", <ide> } <ide> <ide> <ide> class ResNetConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`ResNetModel`]. It is used to instantiate an <ide> ResNet model according to the specified arguments, defining the model architecture. Instantiating a configuration <del> with the defaults will yield a similar configuration to that of the <del> [resnet-50](https://huggingface.co/microsoft/resnet-50) architecture. <add> with the defaults will yield a similar configuration to that of the ResNet <add> [microsoft/resnet-50](https://huggingface.co/microsoft/resnet-50) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/retribert/configuration_retribert.py <ide> <ide> # TODO: upload to AWS <ide> RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "retribert-base-uncased": "https://huggingface.co/distilbert-base-uncased/resolve/main/config.json", <add> "yjernite/retribert-base-uncased": "https://huggingface.co/yjernite/retribert-base-uncased/resolve/main/config.json", <ide> } <ide> <ide> <ide> class RetriBertConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`RetriBertModel`]. It is used to instantiate a <del> RetriBertModel model according to the specified arguments, defining the model architecture. <add> RetriBertModel model according to the specified arguments, defining the model architecture. Instantiating a <add> configuration with the defaults will yield a similar configuration to that of the RetriBERT <add> [yjernite/retribert-base-uncased](https://huggingface.co/yjernite/retribert-base-uncased) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/roberta/configuration_roberta.py <ide> class RobertaConfig(BertConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`RobertaModel`] or a [`TFRobertaModel`]. It is <ide> used to instantiate a RoBERTa model according to the specified arguments, defining the model architecture. <del> <add> Instantiating a configuration with the defaults will yield a similar configuration to that of the RoBERTa <add> [roberta-base](https://huggingface.co/roberta-base) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/speech_to_text_2/configuration_speech_to_text_2.py <ide> logger = logging.get_logger(__name__) <ide> <ide> SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "facebook/s2t-small-librispeech-asr": "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json", <add> "facebook/s2t-wav2vec2-large-en-de": "https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json", <ide> # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2 <ide> } <ide> <ide> class Speech2Text2Config(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`Speech2Text2ForCausalLM`]. It is used to <ide> instantiate an Speech2Text2 model according to the specified arguments, defining the model architecture. <ide> Instantiating a configuration with the defaults will yield a similar configuration to that of the Speech2Text2 <del> [facebook/s2t-small-librispeech-asr](https://huggingface.co/facebook/s2t-small-librispeech-asr) architecture. <add> [facebook/s2t-wav2vec2-large-en-de](https://huggingface.co/facebook/s2t-wav2vec2-large-en-de) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/squeezebert/configuration_squeezebert.py <ide> class SqueezeBertConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`SqueezeBertModel`]. It is used to instantiate a <del> SqueezeBERT model according to the specified arguments, defining the model architecture. <add> SqueezeBERT model according to the specified arguments, defining the model architecture. Instantiating a <add> configuration with the defaults will yield a similar configuration to that of the SqueezeBERT <add> [squeezebert/squeezebert-uncased](https://huggingface.co/squeezebert/squeezebert-uncased) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/tapas/configuration_tapas.py <ide> class TapasConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`TapasModel`]. It is used to instantiate a TAPAS <ide> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <del> defaults will yield a similar configuration to that of the TAPAS *tapas-base-finetuned-sqa* architecture. <add> defaults will yield a similar configuration to that of the TAPAS <add> [google/tapas-base-finetuned-sqa](https://huggingface.co/google/tapas-base-finetuned-sqa) architecture. <add> <ide> Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide> <ide><path>src/transformers/models/transfo_xl/configuration_transfo_xl.py <ide> class TransfoXLConfig(PretrainedConfig): <ide> """ <ide> This is the configuration class to store the configuration of a [`TransfoXLModel`] or a [`TFTransfoXLModel`]. It is <ide> used to instantiate a Transformer-XL model according to the specified arguments, defining the model architecture. <del> Instantiating a configuration with the defaults will yield a similar configuration to that of the [Transformer <del> XL](https://huggingface.co/transfo-xl-wt103) architecture. <add> Instantiating a configuration with the defaults will yield a similar configuration to that of the TransfoXL <add> [transfo-xl-wt103](https://huggingface.co/transfo-xl-wt103) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/trocr/configuration_trocr.py <ide> logger = logging.get_logger(__name__) <ide> <ide> TROCR_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "microsoft/trocr-base": "https://huggingface.co/microsoft/trocr-base/resolve/main/config.json", <add> "microsoft/trocr-base-handwritten": "https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json", <ide> # See all TrOCR models at https://huggingface.co/models?filter=trocr <ide> } <ide> <ide> class TrOCRConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`TrOCRForCausalLM`]. It is used to instantiate an <ide> TrOCR model according to the specified arguments, defining the model architecture. Instantiating a configuration <ide> with the defaults will yield a similar configuration to that of the TrOCR <del> [microsoft/trocr-base](https://huggingface.co/microsoft/trocr-base) architecture. <add> [microsoft/trocr-base-handwritten](https://huggingface.co/microsoft/trocr-base-handwritten) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/unispeech/configuration_unispeech.py <ide> logger = logging.get_logger(__name__) <ide> <ide> UNISPEECH_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "facebook/unispeech-base-960h": "https://huggingface.co/facebook/unispeech-base-960h/resolve/main/config.json", <add> "microsoft/unispeech-large-1500h-cv": "https://huggingface.co/microsoft/unispeech-large-1500h-cv/resolve/main/config.json", <ide> # See all UniSpeech models at https://huggingface.co/models?filter=unispeech <ide> } <ide> <ide> class UniSpeechConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`UniSpeechModel`]. It is used to instantiate an <ide> UniSpeech model according to the specified arguments, defining the model architecture. Instantiating a <ide> configuration with the defaults will yield a similar configuration to that of the UniSpeech <del> [facebook/unispeech-base-960h](https://huggingface.co/facebook/unispeech-base-960h) architecture. <add> [microsoft/unispeech-large-1500h-cv](https://huggingface.co/microsoft/unispeech-large-1500h-cv) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/unispeech_sat/configuration_unispeech_sat.py <ide> logger = logging.get_logger(__name__) <ide> <ide> UNISPEECH_SAT_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "facebook/unispeech_sat-base-960h": "https://huggingface.co/facebook/unispeech_sat-base-960h/resolve/main/config.json", <add> "microsoft/unispeech-sat-base-100h-libri-ft": "https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json", <ide> # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat <ide> } <ide> <ide> class UniSpeechSatConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`UniSpeechSatModel`]. It is used to instantiate an <ide> UniSpeechSat model according to the specified arguments, defining the model architecture. Instantiating a <ide> configuration with the defaults will yield a similar configuration to that of the UniSpeechSat <del> [facebook/unispeech_sat-base-960h](https://huggingface.co/facebook/unispeech_sat-base-960h) architecture. <add> [microsoft/unispeech-sat-base-100h-libri-ft](https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft) <add> architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide> class UniSpeechSatConfig(PretrainedConfig): <ide> ```python <ide> >>> from transformers import UniSpeechSatModel, UniSpeechSatConfig <ide> <del> >>> # Initializing a UniSpeechSat facebook/unispeech_sat-base-960h style configuration <add> >>> # Initializing a UniSpeechSat microsoft/unispeech-sat-base-100h-libri-ft style configuration <ide> >>> configuration = UniSpeechSatConfig() <ide> <del> >>> # Initializing a model from the facebook/unispeech_sat-base-960h style configuration <add> >>> # Initializing a model from the microsoft/unispeech-sat-base-100h-libri-ft style configuration <ide> >>> model = UniSpeechSatModel(configuration) <ide> <ide> >>> # Accessing the model configuration <ide><path>src/transformers/models/unispeech_sat/modeling_unispeech_sat.py <ide> def _set_gradient_checkpointing(self, module, value=False): <ide> <ide> `attention_mask` should only be passed if the corresponding processor has `config.return_attention_mask == <ide> True`. For all models whose processor has `config.return_attention_mask == False`, such as <del> [unispeech_sat-base](https://huggingface.co/facebook/unispeech_sat-base-960h), `attention_mask` should <del> **not** be passed to avoid degraded performance when doing batched inference. For such models <del> `input_values` should simply be padded with 0 and passed without `attention_mask`. Be aware that these <del> models also yield slightly different results depending on whether `input_values` is padded or not. <add> [microsoft/unispeech-sat-base-100h-libri-ft](https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft), <add> `attention_mask` should **not** be passed to avoid degraded performance when doing batched inference. For <add> such models `input_values` should simply be padded with 0 and passed without `attention_mask`. Be aware <add> that these models also yield slightly different results depending on whether `input_values` is padded or <add> not. <ide> <ide> </Tip> <ide> <ide><path>src/transformers/models/van/configuration_van.py <ide> logger = logging.get_logger(__name__) <ide> <ide> VAN_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "van-base": "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json", <add> "Visual-Attention-Network/van-base": "https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json", <ide> } <ide> <ide> <ide> class VanConfig(PretrainedConfig): <ide> r""" <ide> This is the configuration class to store the configuration of a [`VanModel`]. It is used to instantiate a VAN model <ide> according to the specified arguments, defining the model architecture. Instantiating a configuration with the <del> defaults will yield a similar configuration to that of the VAN [van-base](https://huggingface.co/van-base) <del> architecture. <add> defaults will yield a similar configuration to that of the VAN <add> [Visual-Attention-Network/van-base](https://huggingface.co/Visual-Attention-Network/van-base) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/visual_bert/configuration_visual_bert.py <ide> class VisualBertConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`VisualBertModel`]. It is used to instantiate an <ide> VisualBERT model according to the specified arguments, defining the model architecture. Instantiating a <ide> configuration with the defaults will yield a similar configuration to that of the VisualBERT <del> [visualbert-vqa-coco-pre](https://huggingface.co/uclanlp/visualbert-vqa-coco-pre) architecture. <add> [uclanlp/visualbert-vqa-coco-pre](https://huggingface.co/uclanlp/visualbert-vqa-coco-pre) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/wavlm/configuration_wavlm.py <ide> logger = logging.get_logger(__name__) <ide> <ide> WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "facebook/wavlm-base-960h": "https://huggingface.co/facebook/wavlm-base-960h/resolve/main/config.json", <add> "microsoft/wavlm-base": "https://huggingface.co/microsoft/wavlm-base/resolve/main/config.json", <ide> # See all WavLM models at https://huggingface.co/models?filter=wavlm <ide> } <ide> <ide> class WavLMConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`WavLMModel`]. It is used to instantiate an WavLM <ide> model according to the specified arguments, defining the model architecture. Instantiating a configuration with the <ide> defaults will yield a similar configuration to that of the WavLM <del> [facebook/wavlm-base-960h](https://huggingface.co/facebook/wavlm-base-960h) architecture. <add> [microsoft/wavlm-base](https://huggingface.co/microsoft/wavlm-base) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information. <ide><path>src/transformers/models/xlm_prophetnet/configuration_xlm_prophetnet.py <ide> class XLMProphetNetConfig(ProphetNetConfig): <ide> """ <ide> This class overrides [`ProphetNetConfig`]. Please check the superclass for the appropriate documentation alongside <del> usage examples. <add> usage examples. Instantiating a configuration with the defaults will yield a similar configuration to that of the <add> XLMProphetNet <add> [microsoft/xprophetnet-large-wiki100-cased](https://huggingface.co/microsoft/xprophetnet-large-wiki100-cased) <add> architecture. <ide> """ <ide> <ide> model_type = "xlm-prophetnet" <ide><path>src/transformers/models/xlm_roberta/configuration_xlm_roberta.py <ide> class XLMRobertaConfig(RobertaConfig): <ide> """ <ide> This class overrides [`RobertaConfig`]. Please check the superclass for the appropriate documentation alongside <del> usage examples. <add> usage examples. Instantiating a configuration with the defaults will yield a similar configuration to that of the <add> XLMRoBERTa [xlm-roberta-base](https://huggingface.co/xlm-roberta-base) architecture. <ide> """ <ide> <ide> model_type = "xlm-roberta" <ide><path>src/transformers/models/xlm_roberta_xl/configuration_xlm_roberta_xl.py <ide> logger = logging.get_logger(__name__) <ide> <ide> XLM_ROBERTA_XL_PRETRAINED_CONFIG_ARCHIVE_MAP = { <del> "xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", <del> "xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", <add> "facebook/xlm-roberta-xl": "https://huggingface.co/facebook/xlm-roberta-xl/resolve/main/config.json", <add> "facebook/xlm-roberta-xxl": "https://huggingface.co/facebook/xlm-roberta-xxl/resolve/main/config.json", <ide> # See all XLM-RoBERTa-XL models at https://huggingface.co/models?filter=xlm-roberta-xl <ide> } <ide> <ide> class XLMRobertaXLConfig(PretrainedConfig): <ide> This is the configuration class to store the configuration of a [`XLMRobertaXLModel`] or a [`TFXLMRobertaXLModel`]. <ide> It is used to instantiate a XLM_ROBERTA_XL model according to the specified arguments, defining the model <ide> architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the <del> XLM_ROBERTA_XL [bert-base-uncased](https://huggingface.co/bert-base-uncased) architecture. <add> XLM_ROBERTA_XL [facebook/xlm-roberta-xl](https://huggingface.co/facebook/xlm-roberta-xl) architecture. <ide> <ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the <ide> documentation from [`PretrainedConfig`] for more information.
46
Text
Text
fix typo s/higlights/highlights/ [ci skip]
fba75f0ae332636cb46a97474bf682c442b6ee2b
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> class User < ApplicationRecord <ide> end <ide> <ide> user.highlights.attach(filename: "funky.jpg", ...) <del>user.higlights.count # => 1 <add>user.highlights.count # => 1 <ide> <ide> blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg", ...) <ide> user.update!(highlights: [ blob ])
1
Text
Text
add apostrophe to "let's"
25884ade58e3414f92a9a2cfd34f23d35748c35c
<ide><path>guide/english/javascript/scopes/index.md <ide> Before you type the first line of code in your program, a _global scope_ is crea <ide> <ide> In the example above, the variable `foo` is in the global scope of the program, while the variable `bar` is declared inside a function and is therefore **in the local scope of that function**. <ide> <del>Lets break down the example line by line. While you might be confused at this point, I promise you will have a much better understanding by the time you finish reading this. <add>Let's break down the example line by line. While you might be confused at this point, I promise you will have a much better understanding by the time you finish reading this. <ide> <ide> On line 1 we are declaring the variable `foo`. Nothing too fancy here. Lets call this a left-hand size (LHS) reference to `foo`, because we are assigning a value to `foo` and it's on the left-hand side of the `equal` sign. <ide>
1
Python
Python
add some important log in aws athena hook
8cf6dca36b0cfc16763cb1d4c96ab04d1fe5ec14
<ide><path>airflow/providers/amazon/aws/hooks/athena.py <ide> class AthenaHook(AwsBaseHook): <ide> :class:`~airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook` <ide> <ide> :param sleep_time: Time (in seconds) to wait between two consecutive calls to check query status on Athena <add> :param log_query: Whether to log athena query and other execution params when it's executed. <add> Defaults to *True*. <ide> """ <ide> <ide> INTERMEDIATE_STATES = ( <ide> class AthenaHook(AwsBaseHook): <ide> "CANCELLED", <ide> ) <ide> <del> def __init__(self, *args: Any, sleep_time: int = 30, **kwargs: Any) -> None: <add> def __init__(self, *args: Any, sleep_time: int = 30, log_query: bool = True, **kwargs: Any) -> None: <ide> super().__init__(client_type="athena", *args, **kwargs) # type: ignore <ide> self.sleep_time = sleep_time <add> self.log_query = log_query <ide> <ide> def run_query( <ide> self, <ide> def run_query( <ide> } <ide> if client_request_token: <ide> params["ClientRequestToken"] = client_request_token <add> if self.log_query: <add> self.log.info("Running Query with params: %s", params) <ide> response = self.get_conn().start_query_execution(**params) <del> return response["QueryExecutionId"] <add> query_execution_id = response["QueryExecutionId"] <add> self.log.info("Query execution id: %s", query_execution_id) <add> return query_execution_id <ide> <ide> def check_query_status(self, query_execution_id: str) -> str | None: <ide> """ <ide> def check_query_status(self, query_execution_id: str) -> str | None: <ide> state = None <ide> try: <ide> state = response["QueryExecution"]["Status"]["State"] <del> except Exception as ex: <del> self.log.error("Exception while getting query state %s", ex) <add> except Exception: <add> self.log.exception( <add> "Exception while getting query state. Query execution id: %s", query_execution_id <add> ) <ide> finally: <ide> # The error is being absorbed here and is being handled by the caller. <ide> # The error is being absorbed to implement retries. <ide> def get_state_change_reason(self, query_execution_id: str) -> str | None: <ide> reason = None <ide> try: <ide> reason = response["QueryExecution"]["Status"]["StateChangeReason"] <del> except Exception as ex: <del> self.log.error("Exception while getting query state change reason: %s", ex) <add> except Exception: <add> self.log.exception( <add> "Exception while getting query state change reason. Query execution id: %s", <add> query_execution_id, <add> ) <ide> finally: <ide> # The error is being absorbed here and is being handled by the caller. <ide> # The error is being absorbed to implement retries. <ide> def get_query_results( <ide> """ <ide> query_state = self.check_query_status(query_execution_id) <ide> if query_state is None: <del> self.log.error("Invalid Query state") <add> self.log.error("Invalid Query state. Query execution id: %s", query_execution_id) <ide> return None <ide> elif query_state in self.INTERMEDIATE_STATES or query_state in self.FAILURE_STATES: <del> self.log.error('Query is in "%s" state. Cannot fetch results', query_state) <add> self.log.error( <add> 'Query is in "%s" state. Cannot fetch results. Query execution id: %s', <add> query_state, <add> query_execution_id, <add> ) <ide> return None <ide> result_params = {"QueryExecutionId": query_execution_id, "MaxResults": max_results} <ide> if next_token_id: <ide> def get_query_results_paginator( <ide> """ <ide> query_state = self.check_query_status(query_execution_id) <ide> if query_state is None: <del> self.log.error("Invalid Query state (null)") <add> self.log.error("Invalid Query state (null). Query execution id: %s", query_execution_id) <ide> return None <ide> if query_state in self.INTERMEDIATE_STATES or query_state in self.FAILURE_STATES: <del> self.log.error('Query is in "%s" state. Cannot fetch results', query_state) <add> self.log.error( <add> 'Query is in "%s" state. Cannot fetch results, Query execution id: %s', <add> query_state, <add> query_execution_id, <add> ) <ide> return None <ide> result_params = { <ide> "QueryExecutionId": query_execution_id, <ide> def poll_query_status( <ide> while True: <ide> query_state = self.check_query_status(query_execution_id) <ide> if query_state is None: <del> self.log.info("Trial %s: Invalid query state. Retrying again", try_number) <add> self.log.info( <add> "Query execution id: %s, trial %s: Invalid query state. Retrying again", <add> query_execution_id, <add> try_number, <add> ) <ide> elif query_state in self.TERMINAL_STATES: <ide> self.log.info( <del> "Trial %s: Query execution completed. Final state is %s}", try_number, query_state <add> "Query execution id: %s, trial %s: Query execution completed. Final state is %s", <add> query_execution_id, <add> try_number, <add> query_state, <ide> ) <ide> final_query_state = query_state <ide> break <ide> else: <del> self.log.info("Trial %s: Query is still in non-terminal state - %s", try_number, query_state) <add> self.log.info( <add> "Query execution id: %s, trial %s: Query is still in non-terminal state - %s", <add> query_execution_id, <add> try_number, <add> query_state, <add> ) <ide> if ( <ide> max_polling_attempts and try_number >= max_polling_attempts <ide> ): # Break loop if max_polling_attempts reached <ide> def get_output_location(self, query_execution_id: str) -> str: <ide> try: <ide> output_location = response["QueryExecution"]["ResultConfiguration"]["OutputLocation"] <ide> except KeyError: <del> self.log.error("Error retrieving OutputLocation") <add> self.log.error( <add> "Error retrieving OutputLocation. Query execution id: %s", query_execution_id <add> ) <ide> raise <ide> else: <ide> raise <ide> else: <del> raise ValueError("Invalid Query execution id") <add> raise ValueError("Invalid Query execution id. Query execution id: %s", query_execution_id) <ide> <ide> return output_location <ide> <ide> def stop_query(self, query_execution_id: str) -> dict: <ide> :param query_execution_id: Id of submitted athena query <ide> :return: dict <ide> """ <add> self.log.info("Stopping Query with executionId - %s", query_execution_id) <ide> return self.get_conn().stop_query_execution(QueryExecutionId=query_execution_id) <ide><path>airflow/providers/amazon/aws/operators/athena.py <ide> class AthenaOperator(BaseOperator): <ide> :param max_tries: Deprecated - use max_polling_attempts instead. <ide> :param max_polling_attempts: Number of times to poll for query state before function exits <ide> To limit task execution time, use execution_timeout. <add> :param log_query: Whether to log athena query and other execution params when it's executed. <add> Defaults to *True*. <ide> """ <ide> <ide> ui_color = "#44b5e2" <ide> def __init__( <ide> sleep_time: int = 30, <ide> max_tries: int | None = None, <ide> max_polling_attempts: int | None = None, <add> log_query: bool = True, <ide> **kwargs: Any, <ide> ) -> None: <ide> super().__init__(**kwargs) <ide> def __init__( <ide> self.sleep_time = sleep_time <ide> self.max_polling_attempts = max_polling_attempts <ide> self.query_execution_id: str | None = None <add> self.log_query: bool = log_query <ide> <ide> if max_tries: <ide> warnings.warn( <ide> def __init__( <ide> @cached_property <ide> def hook(self) -> AthenaHook: <ide> """Create and return an AthenaHook.""" <del> return AthenaHook(self.aws_conn_id, sleep_time=self.sleep_time) <add> return AthenaHook(self.aws_conn_id, sleep_time=self.sleep_time, log_query=self.log_query) <ide> <ide> def execute(self, context: Context) -> str | None: <ide> """Run Presto Query on Athena""" <ide> def on_kill(self) -> None: <ide> """Cancel the submitted athena query""" <ide> if self.query_execution_id: <ide> self.log.info("Received a kill signal.") <del> self.log.info("Stopping Query with executionId - %s", self.query_execution_id) <ide> response = self.hook.stop_query(self.query_execution_id) <ide> http_status_code = None <ide> try: <ide> http_status_code = response["ResponseMetadata"]["HTTPStatusCode"] <del> except Exception as ex: <del> self.log.error("Exception while cancelling query: %s", ex) <add> except Exception: <add> self.log.exception( <add> "Exception while cancelling query. Query execution id: %s", self.query_execution_id <add> ) <ide> finally: <ide> if http_status_code is None or http_status_code != 200: <ide> self.log.error("Unable to request query cancel on athena. Exiting") <ide><path>tests/providers/amazon/aws/hooks/test_athena.py <ide> def test_hook_run_query_with_token(self, mock_conn): <ide> mock_conn.return_value.start_query_execution.assert_called_with(**expected_call_params) <ide> assert result == MOCK_DATA["query_execution_id"] <ide> <add> @mock.patch.object(AthenaHook, "log") <add> @mock.patch.object(AthenaHook, "get_conn") <add> def test_hook_run_query_log_query(self, mock_conn, log): <add> self.athena.run_query( <add> query=MOCK_DATA["query"], <add> query_context=mock_query_context, <add> result_configuration=mock_result_configuration, <add> ) <add> assert self.athena.log.info.call_count == 2 <add> <add> @mock.patch.object(AthenaHook, "log") <add> @mock.patch.object(AthenaHook, "get_conn") <add> def test_hook_run_query_no_log_query(self, mock_conn, log): <add> athena_hook_no_log_query = AthenaHook(sleep_time=0, log_query=False) <add> athena_hook_no_log_query.run_query( <add> query=MOCK_DATA["query"], <add> query_context=mock_query_context, <add> result_configuration=mock_result_configuration, <add> ) <add> assert athena_hook_no_log_query.log.info.call_count == 1 <add> <ide> @mock.patch.object(AthenaHook, "get_conn") <ide> def test_hook_get_query_results_with_non_succeeded_query(self, mock_conn): <ide> mock_conn.return_value.get_query_execution.return_value = MOCK_RUNNING_QUERY_EXECUTION
3
Javascript
Javascript
add examples at the end of the doc pages
a4a551c5718eb8f6d0e60fe477ac0c69fd571020
<ide><path>website/layout/AutodocsLayout.js <ide> var DocsSidebar = require('DocsSidebar'); <ide> var H = require('Header'); <ide> var Header = require('Header'); <ide> var Marked = require('Marked'); <add>var Prism = require('Prism'); <ide> var React = require('React'); <ide> var Site = require('Site'); <ide> var slugify = require('slugify'); <ide> var Autodocs = React.createClass({ <ide> ); <ide> }, <ide> <add> renderExample: function(docs) { <add> if (!docs.example) { <add> return; <add> } <add> <add> return ( <add> <div> <add> <HeaderWithGithub <add> title="Examples" <add> path={docs.example.path} <add> /> <add> <Prism> <add> {docs.example.content.replace(/^[\s\S]*\*\//, '').trim()} <add> </Prism> <add> </div> <add> ); <add> }, <add> <ide> render: function() { <ide> var metadata = this.props.metadata; <ide> var docs = JSON.parse(this.props.children); <ide> var Autodocs = React.createClass({ <ide> <h1>{metadata.title}</h1> <ide> {content} <ide> {this.renderFullDescription(docs)} <add> {this.renderExample(docs)} <ide> <div className="docs-prevnext"> <ide> {metadata.previous && <a className="docs-prev" href={metadata.previous + '.html#content'}>&larr; Prev</a>} <ide> {metadata.next && <a className="docs-next" href={metadata.next + '.html#content'}>Next &rarr;</a>} <ide><path>website/server/extractDocs.js <ide> function getNameFromPath(filepath) { <ide> return filepath; <ide> } <ide> <add>function getExample(componentName) { <add> var path = '../Examples/UIExplorer/' + componentName + 'Example.js'; <add> if (!fs.existsSync(path)) { <add> return; <add> } <add> return { <add> path: path, <add> content: fs.readFileSync(path).toString(), <add> }; <add>} <add> <ide> function componentsToMarkdown(type, json, filepath, i, styles) { <ide> var componentName = getNameFromPath(filepath); <ide> <ide> function componentsToMarkdown(type, json, filepath, i, styles) { <ide> if (styles) { <ide> json.styles = styles; <ide> } <add> json.example = getExample(componentName); <ide> <ide> var res = [ <ide> '---',
2
PHP
PHP
remove input facade
55785d3514a8149d4858acef40c56a31b6b2ccd1
<ide><path>src/Illuminate/Support/Facades/Input.php <del><?php <del> <del>namespace Illuminate\Support\Facades; <del> <del>/** <del> * @method static bool matchesType(string $actual, string $type) <del> * @method static bool isJson() <del> * @method static bool expectsJson() <del> * @method static bool wantsJson() <del> * @method static bool accepts(string|array $contentTypes) <del> * @method static bool prefers(string|array $contentTypes) <del> * @method static bool acceptsAnyContentType() <del> * @method static bool acceptsJson() <del> * @method static bool acceptsHtml() <del> * @method static string format($default = 'html') <del> * @method static string|array old(string|null $key = null, string|array|null $default = null) <del> * @method static void flash() <del> * @method static void flashOnly(array|mixed $keys) <del> * @method static void flashExcept(array|mixed $keys) <del> * @method static void flush() <del> * @method static string|array|null server(string|null $key = null, string|array|null $default = null) <del> * @method static bool hasHeader(string $key) <del> * @method static string|array|null header(string|null $key = null, string|array|null $default = null) <del> * @method static string|null bearerToken() <del> * @method static bool exists(string|array $key) <del> * @method static bool has(string|array $key) <del> * @method static bool hasAny(string|array $key) <del> * @method static bool filled(string|array $key) <del> * @method static bool anyFilled(string|array $key) <del> * @method static array keys() <del> * @method static array all(array|mixed|null $keys = null) <del> * @method static string|array|null input(string|null $key = null, string|array|null $default = null) <del> * @method static array only(array|mixed $keys) <del> * @method static array except(array|mixed $keys) <del> * @method static string|array|null query(string|null $key = null, string|array|null $default = null) <del> * @method static string|array|null post(string|null $key = null, string|array|null $default = null) <del> * @method static bool hasCookie(string $key) <del> * @method static string|array|null cookie(string|null $key = null, string|array|null $default = null) <del> * @method static array allFiles() <del> * @method static bool hasFile(string $key) <del> * @method static \Illuminate\Http\UploadedFile|\Illuminate\Http\UploadedFile[]|array|null file(string|null $key = null, mixed $default = null) <del> * @method static \Illuminate\Http\Request capture() <del> * @method static \Illuminate\Http\Request instance() <del> * @method static string method() <del> * @method static string root() <del> * @method static string url() <del> * @method static string fullUrl() <del> * @method static string fullUrlWithQuery(array $query) <del> * @method static string path() <del> * @method static string decodedPath() <del> * @method static string|null segment(int $index, string|null $default = null) <del> * @method static array segments() <del> * @method static bool is(mixed ...$patterns) <del> * @method static bool routeIs(mixed ...$patterns) <del> * @method static bool fullUrlIs(mixed ...$patterns) <del> * @method static bool ajax() <del> * @method static bool pjax() <del> * @method static bool prefetch() <del> * @method static bool secure() <del> * @method static string|null ip() <del> * @method static array ips() <del> * @method static string userAgent() <del> * @method static \Illuminate\Http\Request merge(array $input) <del> * @method static \Illuminate\Http\Request replace(array $input) <del> * @method static \Symfony\Component\HttpFoundation\ParameterBag|mixed json(string|null $key = null, mixed $default = null) <del> * @method static \Illuminate\Http\Request createFrom(\Illuminate\Http\Request $from, \Illuminate\Http\Request|null $to = null) <del> * @method static \Illuminate\Http\Request createFromBase(\Symfony\Component\HttpFoundation\Request $request) <del> * @method static \Illuminate\Http\Request duplicate(array|null $query = null, array|null $request = null, array|null $attributes = null, array|null $cookies = null, array|null $files = null, array|null $server = null) <del> * @method static mixed filterFiles(mixed $files) <del> * @method static \Illuminate\Session\Store session() <del> * @method static \Illuminate\Session\Store|null getSession() <del> * @method static void setLaravelSession(\Illuminate\Contracts\Session\Session $session) <del> * @method static mixed user(string|null $guard = null) <del> * @method static \Illuminate\Routing\Route|object|string route(string|null $param = null, string|null $default = null) <del> * @method static string fingerprint() <del> * @method static \Illuminate\Http\Request setJson(\Symfony\Component\HttpFoundation\ParameterBag $json) <del> * @method static \Closure getUserResolver() <del> * @method static \Illuminate\Http\Request setUserResolver(\Closure $callback) <del> * @method static \Closure getRouteResolver() <del> * @method static \Illuminate\Http\Request setRouteResolver(\Closure $callback) <del> * @method static array toArray() <del> * @method static bool offsetExists(string $offset) <del> * @method static mixed offsetGet(string $offset) <del> * @method static void offsetSet(string $offset, mixed $value) <del> * @method static void offsetUnset(string $offset) <del> * <del> * @see \Illuminate\Http\Request <del> */ <del>class Input extends Facade <del>{ <del> /** <del> * Get an item from the input data. <del> * <del> * This method is used for all request verbs (GET, POST, PUT, and DELETE) <del> * <del> * @param string|null $key <del> * @param mixed $default <del> * @return mixed <del> */ <del> public static function get($key = null, $default = null) <del> { <del> return static::$app['request']->input($key, $default); <del> } <del> <del> /** <del> * Get the registered name of the component. <del> * <del> * @return string <del> */ <del> protected static function getFacadeAccessor() <del> { <del> return 'request'; <del> } <del>} <ide><path>src/Illuminate/Support/Facades/Request.php <ide> namespace Illuminate\Support\Facades; <ide> <ide> /** <add> * @method static bool matchesType(string $actual, string $type) <add> * @method static bool isJson() <add> * @method static bool expectsJson() <add> * @method static bool wantsJson() <add> * @method static bool accepts(string|array $contentTypes) <add> * @method static bool prefers(string|array $contentTypes) <add> * @method static bool acceptsAnyContentType() <add> * @method static bool acceptsJson() <add> * @method static bool acceptsHtml() <add> * @method static string format($default = 'html') <add> * @method static string|array old(string|null $key = null, string|array|null $default = null) <add> * @method static void flash() <add> * @method static void flashOnly(array|mixed $keys) <add> * @method static void flashExcept(array|mixed $keys) <add> * @method static void flush() <add> * @method static string|array|null server(string|null $key = null, string|array|null $default = null) <add> * @method static bool hasHeader(string $key) <add> * @method static string|array|null header(string|null $key = null, string|array|null $default = null) <add> * @method static string|null bearerToken() <add> * @method static bool exists(string|array $key) <add> * @method static bool has(string|array $key) <add> * @method static bool hasAny(string|array $key) <add> * @method static bool filled(string|array $key) <add> * @method static bool anyFilled(string|array $key) <add> * @method static array keys() <add> * @method static array all(array|mixed|null $keys = null) <add> * @method static string|array|null input(string|null $key = null, string|array|null $default = null) <add> * @method static array only(array|mixed $keys) <add> * @method static array except(array|mixed $keys) <add> * @method static string|array|null query(string|null $key = null, string|array|null $default = null) <add> * @method static string|array|null post(string|null $key = null, string|array|null $default = null) <add> * @method static bool hasCookie(string $key) <add> * @method static string|array|null cookie(string|null $key = null, string|array|null $default = null) <add> * @method static array allFiles() <add> * @method static bool hasFile(string $key) <add> * @method static \Illuminate\Http\UploadedFile|\Illuminate\Http\UploadedFile[]|array|null file(string|null $key = null, mixed $default = null) <add> * @method static \Illuminate\Http\Request capture() <ide> * @method static \Illuminate\Http\Request instance() <ide> * @method static string method() <ide> * @method static string root() <ide> * @method static string decodedPath() <ide> * @method static string|null segment(int $index, string|null $default = null) <ide> * @method static array segments() <del> * @method static bool is(...$patterns) <del> * @method static bool routeIs(...$patterns) <del> * @method static bool fullUrlIs(...$patterns) <add> * @method static bool is(mixed ...$patterns) <add> * @method static bool routeIs(mixed ...$patterns) <add> * @method static bool fullUrlIs(mixed ...$patterns) <ide> * @method static bool ajax() <ide> * @method static bool pjax() <add> * @method static bool prefetch() <ide> * @method static bool secure() <del> * @method static string ip() <add> * @method static string|null ip() <ide> * @method static array ips() <ide> * @method static string userAgent() <ide> * @method static \Illuminate\Http\Request merge(array $input) <ide> * @method static \Illuminate\Http\Request replace(array $input) <del> * @method static \Symfony\Component\HttpFoundation\ParameterBag|mixed json(string $key = null, $default = null) <add> * @method static \Symfony\Component\HttpFoundation\ParameterBag|mixed json(string|null $key = null, mixed $default = null) <add> * @method static \Illuminate\Http\Request createFrom(\Illuminate\Http\Request $from, \Illuminate\Http\Request|null $to = null) <add> * @method static \Illuminate\Http\Request createFromBase(\Symfony\Component\HttpFoundation\Request $request) <add> * @method static \Illuminate\Http\Request duplicate(array|null $query = null, array|null $request = null, array|null $attributes = null, array|null $cookies = null, array|null $files = null, array|null $server = null) <add> * @method static mixed filterFiles(mixed $files) <ide> * @method static \Illuminate\Session\Store session() <ide> * @method static \Illuminate\Session\Store|null getSession() <ide> * @method static void setLaravelSession(\Illuminate\Contracts\Session\Session $session) <ide> * @method static mixed user(string|null $guard = null) <del> * @method static \Illuminate\Routing\Route|object|string route(string|null $param = null) <add> * @method static \Illuminate\Routing\Route|object|string route(string|null $param = null, string|null $default = null) <ide> * @method static string fingerprint() <ide> * @method static \Illuminate\Http\Request setJson(\Symfony\Component\HttpFoundation\ParameterBag $json) <ide> * @method static \Closure getUserResolver() <ide> * @method static array toArray() <ide> * @method static bool offsetExists(string $offset) <ide> * @method static mixed offsetGet(string $offset) <del> * @method static void offsetSet(string $offset, $value) <add> * @method static void offsetSet(string $offset, mixed $value) <ide> * @method static void offsetUnset(string $offset) <ide> * <ide> * @see \Illuminate\Http\Request
2
Python
Python
add conn_type to fix failing livy tests
e2a909787c044c6960b58d5f864b9ad8b4fc5885
<ide><path>tests/providers/apache/livy/hooks/test_livy.py <ide> class TestLivyHook(unittest.TestCase): <ide> @classmethod <ide> def setUpClass(cls): <del> db.merge_conn(Connection(conn_id='livy_default', host='host', schema='http', port='8998')) <del> db.merge_conn(Connection(conn_id='default_port', host='http://host')) <del> db.merge_conn(Connection(conn_id='default_protocol', host='host')) <del> db.merge_conn(Connection(conn_id='port_set', host='host', port=1234)) <del> db.merge_conn(Connection(conn_id='schema_set', host='host', schema='zzz')) <del> db.merge_conn(Connection(conn_id='dont_override_schema', host='http://host', schema='zzz')) <del> db.merge_conn(Connection(conn_id='missing_host', port=1234)) <del> db.merge_conn(Connection(conn_id='invalid_uri', uri='http://invalid_uri:4321')) <add> db.merge_conn( <add> Connection(conn_id='livy_default', conn_type='http', host='host', schema='http', port='8998')) <add> db.merge_conn(Connection(conn_id='default_port', conn_type='http', host='http://host')) <add> db.merge_conn(Connection(conn_id='default_protocol', conn_type='http', host='host')) <add> db.merge_conn(Connection(conn_id='port_set', host='host', conn_type='http', port=1234)) <add> db.merge_conn(Connection(conn_id='schema_set', host='host', conn_type='http', schema='zzz')) <add> db.merge_conn( <add> Connection(conn_id='dont_override_schema', conn_type='http', host='http://host', schema='zzz')) <add> db.merge_conn(Connection(conn_id='missing_host', conn_type='http', port=1234)) <add> db.merge_conn(Connection(conn_id='invalid_uri', conn_type='http', uri='http://invalid_uri:4321')) <ide> <ide> def test_build_get_hook(self): <ide>
1
Javascript
Javascript
use common/fixtures in fs-symlink test
70a19ae7820b85e8535c7db27151baa3d0705287
<ide><path>test/parallel/test-fs-symlink-dir-junction.js <ide> <ide> 'use strict'; <ide> const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <ide> const assert = require('assert'); <ide> const path = require('path'); <ide> const fs = require('fs'); <ide> <ide> // test creating and reading symbolic link <del>const linkData = path.join(common.fixturesDir, 'cycles/'); <add>const linkData = fixtures.path('cycles/'); <ide> const linkPath = path.join(common.tmpDir, 'cycles_link'); <ide> <ide> common.refreshTmpDir(); <ide> <del>console.log(`linkData: ${linkData}`); <del>console.log(`linkPath: ${linkPath}`); <del> <ide> fs.symlink(linkData, linkPath, 'junction', common.mustCall(function(err) { <ide> assert.ifError(err); <ide>
1
Text
Text
fix broken link
e7c44c90c3fc187e86c6f76296109ecab465bddf
<ide><path>share/doc/homebrew/Brew-Test-Bot.md <ide> by [our Kickstarter in 2013](https://www.kickstarter.com/projects/homebrew/brew- <ide> <ide> It comprises of four Mac Minis running in a data centre in England which host <ide> [a Jenkins instance at http://bot.brew.sh](http://bot.brew.sh) and run the <del>[`brew-test-bot.rb`](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/cmd/test-bot.rb) <add>[`brew test-bot.rb`](https://github.com/Homebrew/brew/blob/master/Library/Homebrew/dev-cmd/test-bot.rb) <ide> Ruby script to perform automated testing of commits to the master branch, pull <ide> requests and custom builds requested by maintainers. <ide>
1
Python
Python
allow specification of terms to fit in legfit
d54e7351aeda804de6e7b5963bb2b9fa5c76d027
<ide><path>numpy/polynomial/legendre.py <ide> def legfit(x, y, deg, rcond=None, full=False, w=None): <ide> y-coordinates of the sample points. Several data sets of sample <ide> points sharing the same x-coordinates can be fitted at once by <ide> passing in a 2D-array that contains one dataset per column. <del> deg : int <del> Degree of the fitting polynomial <add> deg : int or array_like <add> Degree of the fitting polynomial. If `deg` is a single integer <add> all terms up to and including the `deg`'th term are included. <add> `deg` may alternatively be a list or array specifying which <add> terms in the Legendre expansion to include in the fit. <add> <add> .. versionchanged:: 1.11.0 <add> `deg` may be a list specifying which terms to fit <ide> rcond : float, optional <ide> Relative condition number of the fit. Singular values smaller than <ide> this relative to the largest singular value will be ignored. The <ide> def legfit(x, y, deg, rcond=None, full=False, w=None): <ide> Returns <ide> ------- <ide> coef : ndarray, shape (M,) or (M, K) <del> Legendre coefficients ordered from low to high. If `y` was 2-D, <del> the coefficients for the data in column k of `y` are in column <del> `k`. <add> Legendre coefficients ordered from low to high. If `y` was <add> 2-D, the coefficients for the data in column k of `y` are in <add> column `k`. If `deg` is specified as a list, coefficients for <add> terms not included in the fit are set equal to zero in the <add> returned `coef`. <ide> <ide> [residuals, rank, singular_values, rcond] : list <ide> These values are only returned if `full` = True <ide> def legfit(x, y, deg, rcond=None, full=False, w=None): <ide> -------- <ide> <ide> """ <del> order = int(deg) + 1 <ide> x = np.asarray(x) + 0.0 <ide> y = np.asarray(y) + 0.0 <add> deg = np.asarray([deg,], dtype=int).flatten() <ide> <ide> # check arguments. <del> if deg < 0: <add> if deg.size < 1: <add> raise TypeError("expected deg to be one or more integers") <add> if deg.min() < 0: <ide> raise ValueError("expected deg >= 0") <ide> if x.ndim != 1: <ide> raise TypeError("expected 1D vector for x") <ide> def legfit(x, y, deg, rcond=None, full=False, w=None): <ide> if len(x) != len(y): <ide> raise TypeError("expected x and y to have same length") <ide> <add> if deg.size == 1: <add> restricted_fit = False <add> lmax = deg[0] <add> order = lmax + 1 <add> else: <add> restricted_fit = True <add> lmax = deg.max() <add> order = deg.size <add> <ide> # set up the least squares matrices in transposed form <del> lhs = legvander(x, deg).T <add> van = legvander(x, lmax) <add> if restricted_fit: <add> van = van[:, deg] <add> lhs = van.T <ide> rhs = y.T <ide> if w is not None: <ide> w = np.asarray(w) + 0.0 <ide> def legfit(x, y, deg, rcond=None, full=False, w=None): <ide> c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond) <ide> c = (c.T/scl).T <ide> <add> # Expand c to include non-fitted coefficients which are set to zero <add> if restricted_fit: <add> if c.ndim == 2: <add> cc = np.zeros((lmax+1, c.shape[1]), dtype=c.dtype) <add> else: <add> cc = np.zeros(lmax+1, dtype=c.dtype) <add> cc[deg] = c <add> c = cc <add> <ide> # warn on rank reduction <ide> if rank != order and not full: <ide> msg = "The fit may be poorly conditioned"
1
PHP
PHP
allow passing of conditions to where with arrays
491feeb82ac27542c6a5512f26735451a2d9c09f
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function where($column, $operator = null, $value = null, $boolean = 'and' <ide> // and can add them each as a where clause. We will maintain the boolean we <ide> // received when the method was called and pass it into the nested where. <ide> if (is_array($column)) { <del> return $this->whereNested(function ($query) use ($column) { <del> foreach ($column as $key => $value) { <del> $query->where($key, '=', $value); <del> } <del> }, $boolean); <add> return $this->addArrayOfWheres($column, $boolean); <ide> } <ide> <ide> // Here we will make some assumptions about the operator. If only 2 values are <ide> public function where($column, $operator = null, $value = null, $boolean = 'and' <ide> return $this; <ide> } <ide> <add> /** <add> * Add an array of where clauses to the query. <add> * <add> * @param array $column <add> * @param string $boolean <add> * @return $this <add> */ <add> protected function addArrayOfWheres($column, $boolean) <add> { <add> return $this->whereNested(function ($query) use ($column) { <add> foreach ($column as $key => $value) { <add> if (is_numeric($key) && is_array($value)) { <add> call_user_func_array([$query, 'where'], $value); <add> } else { <add> $query->where($key, '=', $value); <add> } <add> } <add> }, $boolean); <add> } <add> <ide> /** <ide> * Add an "or where" clause to the query. <ide> * <ide><path>tests/Database/DatabaseQueryBuilderTest.php <ide> public function testWhereShortcut() <ide> $this->assertEquals([0 => 1, 1 => 'foo'], $builder->getBindings()); <ide> } <ide> <add> public function testWhereWithArrayConditions() <add> { <add> $builder = $this->getBuilder(); <add> $builder->select('*')->from('users')->where([['foo', 1], ['bar', 2]]); <add> $this->assertEquals('select * from "users" where ("foo" = ? and "bar" = ?)', $builder->toSql()); <add> $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings()); <add> <add> $builder = $this->getBuilder(); <add> $builder->select('*')->from('users')->where(['foo' => 1, 'bar' => 2]); <add> $this->assertEquals('select * from "users" where ("foo" = ? and "bar" = ?)', $builder->toSql()); <add> $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings()); <add> <add> $builder = $this->getBuilder(); <add> $builder->select('*')->from('users')->where([['foo', 1], ['bar', '<', 2]]); <add> $this->assertEquals('select * from "users" where ("foo" = ? and "bar" < ?)', $builder->toSql()); <add> $this->assertEquals([0 => 1, 1 => 2], $builder->getBindings()); <add> } <add> <ide> public function testNestedWheres() <ide> { <ide> $builder = $this->getBuilder();
2
Javascript
Javascript
update cache-control for render errors
4881cd346b8155314c02a6996538fb48d324111d
<ide><path>server/render.js <ide> async function doRender (req, res, pathname, query, { <ide> <ide> export async function renderScriptError (req, res, page, error) { <ide> // Asks CDNs and others to not to cache the errored page <del> res.setHeader('Cache-Control', 'no-store, must-revalidate') <add> res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate') <ide> <ide> if (error.code === 'ENOENT' || error.message === 'INVALID_BUILD_ID') { <ide> res.statusCode = 404
1
Text
Text
fix syntax errors in docs example
34901a5ffa6078fd964d5b3acdb222410069230d
<ide><path>docs/api-guide/fields.md <ide> Two examples here are `'input_type'` and `'base_template'`: <ide> <ide> # Use a radio input instead of a select input. <ide> color_channel = serializers.ChoiceField( <del> choices=['red', 'green', 'blue'] <del> style = {'base_template': 'radio.html'} <del> } <add> choices=['red', 'green', 'blue'], <add> style={'base_template': 'radio.html'} <add> ) <ide> <ide> For more details see the [HTML & Forms][html-and-forms] documentation. <ide>
1
Python
Python
add compat function to normalize dict keys
480ef8bfc8b92b2de6c4960070c9269cfa505c4f
<ide><path>spacy/compat.py <ide> import sys <ide> import ujson <ide> <add>import thinc.neural.util <add> <ide> try: <ide> import cPickle as pickle <ide> except ImportError: <ide> CudaStream = CudaStream <ide> cupy = cupy <ide> fix_text = ftfy.fix_text <add>copy_array = thinc.neural.util.copy_array <ide> <ide> is_python2 = six.PY2 <ide> is_python3 = six.PY3 <ide> def is_config(python2=None, python3=None, windows=None, linux=None, osx=None): <ide> (windows == None or windows == is_windows) and <ide> (linux == None or linux == is_linux) and <ide> (osx == None or osx == is_osx)) <add> <add> <add>def normalize_string_keys(old): <add> '''Given a dictionary, make sure keys are unicode strings, not bytes.''' <add> new = {} <add> for key, value in old: <add> if isinstance(key, bytes_): <add> new[key.decode('utf8')] = value <add> else: <add> new[key] = value <add> return new <add> <add>
1
Mixed
Javascript
increase timeouts on arm
7049d7b4746dc5dae82d608ac12dc6e1cf11035e
<ide><path>test/common.js <ide> exports.spawnPwd = function(options) { <ide> } <ide> }; <ide> <add>exports.platformTimeout = function(ms) { <add> if (process.arch !== 'arm') <add> return ms; <add> <add> if (process.config.variables.arm_version === '6') <add> return 6 * ms; // ARMv6 <add> <add> return 2 * ms; // ARMv7 and up. <add>}; <add> <ide> var knownGlobals = [setTimeout, <ide> setInterval, <ide> setImmediate, <ide><path>test/parallel/test-child-process-fork-net2.js <ide> if (process.argv[2] === 'child') { <ide> <ide> server.listen(common.PORT, '127.0.0.1'); <ide> <del> var timeElasped = 0; <add> var timeElapsed = 0; <ide> var closeServer = function() { <ide> console.error('[m] closeServer'); <ide> var startTime = Date.now(); <ide> server.on('close', function() { <ide> console.error('[m] emit(close)'); <del> timeElasped = Date.now() - startTime; <add> timeElapsed = Date.now() - startTime; <ide> }); <ide> <ide> console.error('[m] calling server.close'); <ide> if (process.argv[2] === 'child') { <ide> }, 200); <ide> }; <ide> <add> var min = 190; <add> var max = common.platformTimeout(1500); <ide> process.on('exit', function() { <ide> assert.equal(disconnected, count); <ide> assert.equal(connected, count); <ide> assert.ok(closeEmitted); <del> assert.ok(timeElasped >= 190 && timeElasped <= 1000, <del> 'timeElasped was not between 190 and 1000 ms'); <add> assert.ok(timeElapsed >= min && timeElapsed <= max, <add> `timeElapsed was not between ${min} and ${max} ms:` + <add> `${timeElapsed}`); <ide> }); <ide> } <ide><path>test/parallel/test-debug-signal-cluster.js <ide> function onNoMoreLines() { <ide> <ide> setTimeout(function testTimedOut() { <ide> assert(false, 'test timed out.'); <del>}, 6000).unref(); <add>}, common.platformTimeout(3000)).unref(); <ide> <ide> process.on('exit', function onExit() { <ide> // Kill processes in reverse order to avoid timing problems on Windows where <ide><path>test/parallel/test-fs-empty-readStream.js <ide> fs.open(emptyFile, 'r', function (error, fd) { <ide> <ide> setTimeout(function () { <ide> assert.equal(readEmit, true); <del> }, 50); <add> }, common.platformTimeout(50)); <ide> }); <ide> <ide> fs.open(emptyFile, 'r', function (error, fd) { <ide> fs.open(emptyFile, 'r', function (error, fd) { <ide> <ide> setTimeout(function () { <ide> assert.equal(readEmit, false); <del> }, 50); <add> }, common.platformTimeout(50)); <ide> }); <ide><path>test/parallel/test-http-end-throw-socket-handling.js <ide> server.listen(common.PORT, function() { <ide> setTimeout(function() { <ide> process.removeListener('uncaughtException', catcher); <ide> throw new Error('Taking too long!'); <del>}, 1000).unref(); <add>}, common.platformTimeout(1000)).unref(); <ide> <ide> process.on('uncaughtException', catcher); <ide> var errors = 0; <ide><path>test/parallel/test-repl-timeout-throw.js <ide> child.stdout.once('data', function() { <ide> ' });\n' + <ide> '});"";\n'); <ide> <del> setTimeout(child.stdin.end.bind(child.stdin), 200); <add> setTimeout(child.stdin.end.bind(child.stdin), common.platformTimeout(200)); <ide> } <ide> }); <ide> <ide><path>test/parallel/test-tls-fast-writing.js <ide> var gotDrain = false; <ide> var timer = setTimeout(function() { <ide> console.log('not ok - timed out'); <ide> process.exit(1); <del>}, 500); <add>}, common.platformTimeout(500)); <ide> <ide> function onconnection(conn) { <ide> conn.on('data', function(c) { <ide><path>test/parallel/test-tls-wrap-timeout.js <ide> var server = tls.createServer(options, function(c) { <ide> <ide> server.listen(common.PORT, function() { <ide> var socket = net.connect(common.PORT, function() { <del> socket.setTimeout(240, assert.fail); <add> socket.setTimeout(common.platformTimeout(240), function() { <add> throw new Error('timeout'); <add> }); <ide> <ide> var tsocket = tls.connect({ <ide> socket: socket, <ide><path>test/sequential/test-force-repl.js <ide> var cp = spawn(process.execPath, ['-i']); <ide> var gotToEnd = false; <ide> var timeoutId = setTimeout(function() { <ide> throw new Error('timeout!'); <del>}, 1000); // give node + the repl 1 second to boot up <add>}, common.platformTimeout(1000)); // give node + the repl 1 second to boot up <ide> <ide> cp.stdout.setEncoding('utf8'); <ide> <ide><path>test/sequential/test-net-GH-5504.js <ide> function parent() { <ide> setTimeout(function() { <ide> throw new Error('hang'); <ide> }); <del> }, 4000).unref(); <add> }, common.platformTimeout(2000)).unref(); <ide> <ide> var s = spawn(node, [__filename, 'server'], opt); <ide> var c; <ide><path>tools/test.py <ide> def GetTestStatus(self, context, sections, defs): <ide> 'debug' : ['--enable-slow-asserts', '--debug-code', '--verify-heap'], <ide> 'release' : []} <ide> TIMEOUT_SCALEFACTOR = { <del> 'arm' : { 'debug' : 8, 'release' : 2 }, # The ARM buildbots are slow. <del> 'ia32' : { 'debug' : 4, 'release' : 1 } } <add> 'armv6' : { 'debug' : 12, 'release' : 3 }, # The ARM buildbots are slow. <add> 'arm' : { 'debug' : 8, 'release' : 2 }, <add> 'ia32' : { 'debug' : 4, 'release' : 1 } } <ide> <ide> <ide> class Context(object): <ide><path>tools/utils.py <ide> def GuessOS(): <ide> def GuessArchitecture(): <ide> id = platform.machine() <ide> id = id.lower() # Windows 7 capitalizes 'AMD64'. <del> if id.startswith('arm') or id == 'aarch64': <add> if id.startswith('armv6'): # Can return 'armv6l'. <add> return 'armv6' <add> elif id.startswith('arm') or id == 'aarch64': <ide> return 'arm' <ide> elif (not id) or (not re.match('(x|i[3-6])86$', id) is None): <ide> return 'ia32'
12
Go
Go
improve err message when parsing kernel port range
8e4d9f3cf9669f45b0591eea27c47b6f64d89c2d
<ide><path>daemon/networkdriver/portallocator/portallocator.go <ide> func NewErrPortAlreadyAllocated(ip string, port int) ErrPortAlreadyAllocated { <ide> <ide> func init() { <ide> const portRangeKernelParam = "/proc/sys/net/ipv4/ip_local_port_range" <add> portRangeFallback := fmt.Sprintf("using fallback port range %d-%d", beginPortRange, endPortRange) <ide> <ide> file, err := os.Open(portRangeKernelParam) <ide> if err != nil { <del> log.Warnf("Failed to read %s kernel parameter: %v", portRangeKernelParam, err) <add> log.Warnf("port allocator - %s due to error: %v", portRangeFallback, err) <ide> return <ide> } <ide> var start, end int <ide> func init() { <ide> if err == nil { <ide> err = fmt.Errorf("unexpected count of parsed numbers (%d)", n) <ide> } <del> log.Errorf("Failed to parse port range from %s: %v", portRangeKernelParam, err) <add> log.Errorf("port allocator - failed to parse system ephemeral port range from %s - %s: %v", portRangeKernelParam, portRangeFallback, err) <ide> return <ide> } <ide> beginPortRange = start
1
Python
Python
use a set instead of a dictionary
a8556c1007dbf7eb329caaa3dbffc9cd708359ec
<ide><path>numpy/core/numeric.py <ide> def _setdef(): <ide> <ide> <ide> def extend_all(module): <del> adict = {} <del> for a in __all__: <del> adict[a] = 1 <add> existing = set(__all__) <ide> try: <ide> mall = getattr(module, '__all__') <ide> except AttributeError: <ide> mall = [k for k in module.__dict__.keys() if not k.startswith('_')] <ide> for a in mall: <del> if a not in adict: <add> if a not in existing: <ide> __all__.append(a) <ide> <ide>
1
Javascript
Javascript
update color settings of mmd
86748161b2b9f641d7d4cc9e10b96c172ad88e2a
<ide><path>examples/js/loaders/MMDLoader.js <ide> THREE.MMDLoader.prototype.parsePmd = function ( buffer ) { <ide> p.diffuse = dv.getFloat32Array( 4 ); <ide> p.shininess = dv.getFloat32(); <ide> p.specular = dv.getFloat32Array( 3 ); <del> p.emissive = dv.getFloat32Array( 3 ); <add> p.ambient = dv.getFloat32Array( 3 ); <ide> p.toonIndex = dv.getInt8(); <ide> p.edgeFlag = dv.getUint8(); <ide> p.faceCount = dv.getUint32() / 3; <ide> THREE.MMDLoader.prototype.parsePmx = function ( buffer ) { <ide> p.diffuse = dv.getFloat32Array( 4 ); <ide> p.specular = dv.getFloat32Array( 3 ); <ide> p.shininess = dv.getFloat32(); <del> p.emissive = dv.getFloat32Array( 3 ); <add> p.ambient = dv.getFloat32Array( 3 ); <ide> p.flag = dv.getUint8(); <ide> p.edgeColor = dv.getFloat32Array( 4 ); <ide> p.edgeSize = dv.getFloat32(); <ide> THREE.MMDLoader.prototype.parsePmx = function ( buffer ) { <ide> m.diffuse = dv.getFloat32Array( 4 ); <ide> m.specular = dv.getFloat32Array( 3 ); <ide> m.shininess = dv.getFloat32(); <del> m.emissive = dv.getFloat32Array( 3 ); <add> m.ambient = dv.getFloat32Array( 3 ); <ide> m.edgeColor = dv.getFloat32Array( 4 ); <ide> m.edgeSize = dv.getFloat32(); <ide> m.textureColor = dv.getFloat32Array( 4 ); <ide> THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress <ide> var textures = []; <ide> var textureLoader = new THREE.TextureLoader( this.manager ); <ide> var tgaLoader = new THREE.TGALoader( this.manager ); <del> var color = new THREE.Color(); <ide> var offset = 0; <ide> var materialParams = []; <ide> <ide> THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress <ide> offset += m.faceCount; <ide> <ide> params.name = m.name; <del> params.color = color.fromArray( [ m.diffuse[ 0 ], m.diffuse[ 1 ], m.diffuse[ 2 ] ] ).clone(); <add> <add> /* <add> * Color <add> * <add> * MMD MeshPhongMaterial <add> * diffuse - color <add> * specular - specular <add> * ambient - emissive * a <add> * (a = 1.0 without map texture or 0.2 with map texture) <add> * <add> * MeshPhongMaterial doesn't have ambient. Set it to emissive instead. <add> * It'll be too bright if material has map texture so using coef 0.2. <add> */ <add> params.color = new THREE.Color( m.diffuse[ 0 ], m.diffuse[ 1 ], m.diffuse[ 2 ] ); <ide> params.opacity = m.diffuse[ 3 ]; <del> params.specular = color.fromArray( [ m.specular[ 0 ], m.specular[ 1 ], m.specular[ 2 ] ] ).clone(); <add> params.specular = new THREE.Color( m.specular[ 0 ], m.specular[ 1 ], m.specular[ 2 ] ); <ide> params.shininess = m.shininess; <ide> <ide> if ( params.opacity === 1.0 ) { <ide> THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress <ide> <ide> } <ide> <del> // TODO: check if this logic is right <del> if ( params.map === undefined /* && params.envMap === undefined */ ) { <del> <del> params.emissive = color.fromArray( [ m.emissive[ 0 ], m.emissive[ 1 ], m.emissive[ 2 ] ] ).clone(); <del> <del> } <add> var coef = ( params.map === undefined ) ? 1.0 : 0.2; <add> params.emissive = new THREE.Color( m.ambient[ 0 ] * coef, m.ambient[ 1 ] * coef, m.ambient[ 2 ] * coef ); <ide> <ide> materialParams.push( params ); <ide>
1
PHP
PHP
simplify request isset
23d409b450ae7cc0b236a396003ac7ea15b7538a
<ide><path>src/Illuminate/Http/Request.php <ide> public function offsetUnset($offset) <ide> } <ide> <ide> /** <del> * Get an input element from the request. <add> * Check if an input element is set on the request. <ide> * <ide> * @param string $key <del> * @return mixed <add> * @return bool <ide> */ <del> public function __get($key) <add> public function __isset($key) <ide> { <del> $all = $this->all(); <del> <del> if (array_key_exists($key, $all)) { <del> return $all[$key]; <del> } else { <del> return $this->route($key); <del> } <add> return ! is_null($this->__get($key)); <ide> } <ide> <ide> /** <del> * Check if an input element was set in request. <add> * Get an input element from the request. <ide> * <ide> * @param string $key <del> * @return bool <add> * @return mixed <ide> */ <del> public function __isset($key) <add> public function __get($key) <ide> { <ide> $all = $this->all(); <ide> <ide> if (array_key_exists($key, $all)) { <del> return true; <del> } <del> <del> $route = call_user_func($this->getRouteResolver()); <del> <del> if (is_null($route)) { <del> return false; <add> return $all[$key]; <add> } else { <add> return $this->route($key); <ide> } <del> <del> return array_key_exists($key, $route->parameters()); <ide> } <ide> }
1
Java
Java
simplify assertions within mockmvc internals
50e53343789fe985b09e9be83481005074f716ee
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/result/ContentResultMatchers.java <ide> <ide> import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.springframework.test.util.AssertionErrors.assertEquals; <add>import static org.springframework.test.util.AssertionErrors.assertNotNull; <ide> import static org.springframework.test.util.AssertionErrors.assertTrue; <ide> <ide> /** <ide> public ResultMatcher contentType(String contentType) { <ide> public ResultMatcher contentType(MediaType contentType) { <ide> return result -> { <ide> String actual = result.getResponse().getContentType(); <del> assertTrue("Content type not set", actual != null); <del> if (actual != null) { <del> assertEquals("Content type", contentType, MediaType.parseMediaType(actual)); <del> } <add> assertNotNull("Content type not set", actual); <add> assertEquals("Content type", contentType, MediaType.parseMediaType(actual)); <ide> }; <ide> } <ide> <ide> public ResultMatcher contentTypeCompatibleWith(String contentType) { <ide> public ResultMatcher contentTypeCompatibleWith(MediaType contentType) { <ide> return result -> { <ide> String actual = result.getResponse().getContentType(); <del> assertTrue("Content type not set", actual != null); <del> if (actual != null) { <del> MediaType actualContentType = MediaType.parseMediaType(actual); <del> assertTrue("Content type [" + actual + "] is not compatible with [" + contentType + "]", <del> actualContentType.isCompatibleWith(contentType)); <del> } <add> assertNotNull("Content type not set", actual); <add> MediaType actualContentType = MediaType.parseMediaType(actual); <add> assertTrue("Content type [" + actual + "] is not compatible with [" + contentType + "]", <add> actualContentType.isCompatibleWith(contentType)); <ide> }; <ide> } <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/result/CookieResultMatchers.java <ide> <ide> import org.hamcrest.Matcher; <ide> <del>import org.springframework.test.util.AssertionErrors; <ide> import org.springframework.test.web.servlet.MvcResult; <ide> import org.springframework.test.web.servlet.ResultMatcher; <ide> <ide> import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.springframework.test.util.AssertionErrors.assertEquals; <add>import static org.springframework.test.util.AssertionErrors.assertNotNull; <ide> import static org.springframework.test.util.AssertionErrors.assertTrue; <ide> <ide> /** <ide> public ResultMatcher httpOnly(String name, boolean httpOnly) { <ide> <ide> private static Cookie getCookie(MvcResult result, String name) { <ide> Cookie cookie = result.getResponse().getCookie(name); <del> if (cookie == null) { <del> AssertionErrors.fail("No cookie with name '" + name + "'"); <del> } <add> assertNotNull("No cookie with name '" + name + "'", cookie); <ide> return cookie; <ide> } <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/result/FlashAttributeResultMatchers.java <ide> <ide> import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.springframework.test.util.AssertionErrors.assertEquals; <del>import static org.springframework.test.util.AssertionErrors.assertTrue; <add>import static org.springframework.test.util.AssertionErrors.assertNotNull; <ide> <ide> /** <ide> * Factory for "output" flash attribute assertions. <ide> public <T> ResultMatcher attribute(String name, Object value) { <ide> public <T> ResultMatcher attributeExists(String... names) { <ide> return result -> { <ide> for (String name : names) { <del> assertTrue("Flash attribute '" + name + "' does not exist", result.getFlashMap().get(name) != null); <add> assertNotNull("Flash attribute '" + name + "' does not exist", result.getFlashMap().get(name)); <ide> } <ide> }; <ide> } <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/result/HandlerResultMatchers.java <ide> <ide> import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.springframework.test.util.AssertionErrors.assertEquals; <add>import static org.springframework.test.util.AssertionErrors.assertNotNull; <ide> import static org.springframework.test.util.AssertionErrors.assertTrue; <ide> import static org.springframework.test.util.AssertionErrors.fail; <ide> <ide> protected HandlerResultMatchers() { <ide> public ResultMatcher handlerType(Class<?> type) { <ide> return result -> { <ide> Object handler = result.getHandler(); <del> assertTrue("No handler", handler != null); <add> assertNotNull("No handler", handler); <ide> if (handler != null) { <ide> Class<?> actual = handler.getClass(); <ide> if (HandlerMethod.class.isInstance(handler)) { <ide> public ResultMatcher method(Method method) { <ide> <ide> private static HandlerMethod getHandlerMethod(MvcResult result) { <ide> Object handler = result.getHandler(); <del> assertTrue("No handler", handler != null); <del> if (!(handler instanceof HandlerMethod)) { <del> fail("Not a HandlerMethod: " + handler); <del> } <add> assertTrue("Not a HandlerMethod: " + handler, handler instanceof HandlerMethod); <ide> return (HandlerMethod) handler; <ide> } <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/result/ModelResultMatchers.java <ide> <ide> import static org.hamcrest.MatcherAssert.assertThat; <ide> import static org.springframework.test.util.AssertionErrors.assertEquals; <add>import static org.springframework.test.util.AssertionErrors.assertNotNull; <ide> import static org.springframework.test.util.AssertionErrors.assertTrue; <del>import static org.springframework.test.util.AssertionErrors.fail; <ide> <ide> /** <ide> * Factory for assertions on the model. <ide> * {@link MockMvcResultMatchers#model}. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Sam Brannen <ide> * @since 3.2 <ide> */ <ide> public class ModelResultMatchers { <ide> public ResultMatcher attributeExists(String... names) { <ide> return result -> { <ide> ModelAndView mav = getModelAndView(result); <ide> for (String name : names) { <del> assertTrue("Model attribute '" + name + "' does not exist", mav.getModel().get(name) != null); <add> assertNotNull("Model attribute '" + name + "' does not exist", mav.getModel().get(name)); <ide> } <ide> }; <ide> } <ide> public ResultMatcher attributeHasFieldErrorCode(String name, String fieldName, S <ide> BindingResult result = getBindingResult(mav, name); <ide> assertTrue("No errors for attribute '" + name + "'", result.hasErrors()); <ide> FieldError fieldError = result.getFieldError(fieldName); <del> if (fieldError == null) { <del> fail("No errors for field '" + fieldName + "' of attribute '" + name + "'"); <del> } <add> assertNotNull("No errors for field '" + fieldName + "' of attribute '" + name + "'", fieldError); <ide> String code = fieldError.getCode(); <del> assertTrue("Expected error code '" + error + "' but got '" + code + "'", error.equals(code)); <add> assertEquals("Field error code", error, code); <ide> }; <ide> } <ide> <ide> public <T> ResultMatcher attributeHasFieldErrorCode(String name, String fieldNam <ide> return mvcResult -> { <ide> ModelAndView mav = getModelAndView(mvcResult); <ide> BindingResult result = getBindingResult(mav, name); <del> assertTrue("No errors for attribute: [" + name + "]", result.hasErrors()); <add> assertTrue("No errors for attribute '" + name + "'", result.hasErrors()); <ide> FieldError fieldError = result.getFieldError(fieldName); <del> if (fieldError == null) { <del> fail("No errors for field '" + fieldName + "' of attribute '" + name + "'"); <del> } <add> assertNotNull("No errors for field '" + fieldName + "' of attribute '" + name + "'", fieldError); <ide> String code = fieldError.getCode(); <ide> assertThat("Field name '" + fieldName + "' of attribute '" + name + "'", code, matcher); <ide> }; <ide> public <T> ResultMatcher size(int size) { <ide> <ide> private ModelAndView getModelAndView(MvcResult mvcResult) { <ide> ModelAndView mav = mvcResult.getModelAndView(); <del> if (mav == null) { <del> fail("No ModelAndView found"); <del> } <add> assertNotNull("No ModelAndView found", mav); <ide> return mav; <ide> } <ide> <ide> private BindingResult getBindingResult(ModelAndView mav, String name) { <ide> BindingResult result = (BindingResult) mav.getModel().get(BindingResult.MODEL_KEY_PREFIX + name); <del> if (result == null) { <del> fail("No BindingResult for attribute: " + name); <del> } <add> assertNotNull("No BindingResult for attribute: " + name, result); <ide> return result; <ide> } <ide>
5
Ruby
Ruby
test multiple values with blank value
4774fa0d260c1a403858cba3b54673b845d09cce
<ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def preprocess_order_args(order_args) <ide> end <ide> <ide> def sanitize_order_arguments(order_args) <del> order_args.compact_blank! <ide> order_args.map! do |arg| <ide> klass.sanitize_sql_for_order(arg) <ide> end <ide> order_args.flatten! <del> order_args <add> order_args.compact_blank! <ide> end <ide> <ide> def column_references(order_args) <ide><path>activerecord/test/cases/relations_test.rb <ide> def test_find_by_with_take_memoization <ide> assert_empty authors <ide> end <ide> <add> (ActiveRecord::Relation::MULTI_VALUE_METHODS - [:extending]).each do |method| <add> test "#{method} with blank value" do <add> authors = Author.public_send(method, [""]) <add> assert_empty authors.public_send(:"#{method}_values") <add> end <add> end <add> <ide> private <ide> def custom_post_relation(alias_name = "omg_posts") <ide> table_alias = Post.arel_table.alias(alias_name)
2
Javascript
Javascript
remove empty parts of the parsed uri
6550e8cfa07aab1c410ebb8d5b0676d625f93ea3
<ide><path>src/http.js <ide> node.http.parseUri = function (str) { <ide> } <ide> }); <ide> uri.toString = function () { return str; }; <del> <add> <add> for (var i = o.key.length - 1; i >= 0; i--){ <add> if (uri[o.key[i]] == "") delete uri[o.key[i]]; <add> }; <add> <ide> return uri; <ide> }; <ide>
1
Go
Go
fix network inspect for default networks
f301c5765a0d7f4b6866cedfdface6f87874ff53
<ide><path>api/types/types.go <ide> type ContainerJSON struct { <ide> // NetworkSettings exposes the network settings in the api <ide> type NetworkSettings struct { <ide> NetworkSettingsBase <add> DefaultNetworkSettings <ide> Networks map[string]*network.EndpointSettings <ide> } <ide> <ide> type NetworkSettingsBase struct { <ide> SecondaryIPv6Addresses []network.Address <ide> } <ide> <add>// DefaultNetworkSettings holds network information <add>// during the 2 release deprecation period. <add>// It will be removed in Docker 1.11. <add>type DefaultNetworkSettings struct { <add> EndpointID string <add> Gateway string <add> GlobalIPv6Address string <add> GlobalIPv6PrefixLen int <add> IPAddress string <add> IPPrefixLen int <add> IPv6Gateway string <add> MacAddress string <add>} <add> <ide> // MountPoint represents a mount point configuration inside the container. <ide> type MountPoint struct { <ide> Name string `json:",omitempty"` <ide><path>api/types/versions/v1p20/types.go <ide> type StatsJSON struct { <ide> // NetworkSettings is a backward compatible struct for APIs prior to 1.21 <ide> type NetworkSettings struct { <ide> types.NetworkSettingsBase <del> EndpointID string <del> Gateway string <del> GlobalIPv6Address string <del> GlobalIPv6PrefixLen int <del> IPAddress string <del> IPPrefixLen int <del> IPv6Gateway string <del> MacAddress string <add> types.DefaultNetworkSettings <ide> } <ide><path>daemon/inspect.go <ide> func (daemon *Daemon) ContainerInspect(name string, size bool) (*types.Container <ide> <ide> mountPoints := addMountPoints(container) <ide> networkSettings := &types.NetworkSettings{ <del> types.NetworkSettingsBase{ <add> NetworkSettingsBase: types.NetworkSettingsBase{ <ide> Bridge: container.NetworkSettings.Bridge, <ide> SandboxID: container.NetworkSettings.SandboxID, <ide> HairpinMode: container.NetworkSettings.HairpinMode, <ide> func (daemon *Daemon) ContainerInspect(name string, size bool) (*types.Container <ide> SecondaryIPAddresses: container.NetworkSettings.SecondaryIPAddresses, <ide> SecondaryIPv6Addresses: container.NetworkSettings.SecondaryIPv6Addresses, <ide> }, <del> container.NetworkSettings.Networks, <add> DefaultNetworkSettings: daemon.getDefaultNetworkSettings(container.NetworkSettings.Networks), <add> Networks: container.NetworkSettings.Networks, <ide> } <ide> <ide> return &types.ContainerJSON{base, mountPoints, container.Config, networkSettings}, nil <ide> func (daemon *Daemon) ContainerInspect120(name string) (*v1p20.ContainerJSON, er <ide> container.Config.ExposedPorts, <ide> container.hostConfig.VolumeDriver, <ide> } <del> networkSettings := getBackwardsCompatibleNetworkSettings(container.NetworkSettings) <add> networkSettings := daemon.getBackwardsCompatibleNetworkSettings(container.NetworkSettings) <ide> <ide> return &v1p20.ContainerJSON{base, mountPoints, config, networkSettings}, nil <ide> } <ide> func (daemon *Daemon) VolumeInspect(name string) (*types.Volume, error) { <ide> return volumeToAPIType(v), nil <ide> } <ide> <del>func getBackwardsCompatibleNetworkSettings(settings *network.Settings) *v1p20.NetworkSettings { <add>func (daemon *Daemon) getBackwardsCompatibleNetworkSettings(settings *network.Settings) *v1p20.NetworkSettings { <ide> result := &v1p20.NetworkSettings{ <ide> NetworkSettingsBase: types.NetworkSettingsBase{ <ide> Bridge: settings.Bridge, <ide> func getBackwardsCompatibleNetworkSettings(settings *network.Settings) *v1p20.Ne <ide> SecondaryIPAddresses: settings.SecondaryIPAddresses, <ide> SecondaryIPv6Addresses: settings.SecondaryIPv6Addresses, <ide> }, <add> DefaultNetworkSettings: daemon.getDefaultNetworkSettings(settings.Networks), <ide> } <del> if bridgeSettings := settings.Networks["bridge"]; bridgeSettings != nil { <del> result.EndpointID = bridgeSettings.EndpointID <del> result.Gateway = bridgeSettings.Gateway <del> result.GlobalIPv6Address = bridgeSettings.GlobalIPv6Address <del> result.GlobalIPv6PrefixLen = bridgeSettings.GlobalIPv6PrefixLen <del> result.IPAddress = bridgeSettings.IPAddress <del> result.IPPrefixLen = bridgeSettings.IPPrefixLen <del> result.IPv6Gateway = bridgeSettings.IPv6Gateway <del> result.MacAddress = bridgeSettings.MacAddress <del> } <add> <ide> return result <ide> } <add> <add>// getDefaultNetworkSettings creates the deprecated structure that holds the information <add>// about the bridge network for a container. <add>func (daemon *Daemon) getDefaultNetworkSettings(networks map[string]*network.EndpointSettings) types.DefaultNetworkSettings { <add> var settings types.DefaultNetworkSettings <add> <add> if defaultNetwork, ok := networks["bridge"]; ok { <add> settings.EndpointID = defaultNetwork.EndpointID <add> settings.Gateway = defaultNetwork.Gateway <add> settings.GlobalIPv6Address = defaultNetwork.GlobalIPv6Address <add> settings.GlobalIPv6PrefixLen = defaultNetwork.GlobalIPv6PrefixLen <add> settings.IPAddress = defaultNetwork.IPAddress <add> settings.IPPrefixLen = defaultNetwork.IPPrefixLen <add> settings.IPv6Gateway = defaultNetwork.IPv6Gateway <add> settings.MacAddress = defaultNetwork.MacAddress <add> } <add> return settings <add>} <ide><path>daemon/inspect_unix.go <ide> func (daemon *Daemon) ContainerInspectPre120(name string) (*v1p19.ContainerJSON, <ide> container.hostConfig.CPUShares, <ide> container.hostConfig.CpusetCpus, <ide> } <del> networkSettings := getBackwardsCompatibleNetworkSettings(container.NetworkSettings) <add> networkSettings := daemon.getBackwardsCompatibleNetworkSettings(container.NetworkSettings) <ide> <ide> return &v1p19.ContainerJSON{base, volumes, volumesRW, config, networkSettings}, nil <ide> } <ide><path>integration-cli/docker_api_inspect_test.go <ide> package main <ide> <ide> import ( <ide> "encoding/json" <del> "fmt" <ide> "net/http" <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/versions/v1p20" <add> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/docker/docker/pkg/stringutils" <ide> "github.com/go-check/check" <ide> ) <ide> func (s *DockerSuite) TestInspectApiContainerResponse(c *check.C) { <ide> version string <ide> keys []string <ide> }{ <del> {"1.20", append(keysBase, "Mounts")}, <del> {"1.19", append(keysBase, "Volumes", "VolumesRW")}, <add> {"v1.20", append(keysBase, "Mounts")}, <add> {"v1.19", append(keysBase, "Volumes", "VolumesRW")}, <ide> } <ide> <ide> for _, cs := range cases { <del> endpoint := fmt.Sprintf("/v%s/containers/%s/json", cs.version, cleanedContainerID) <del> <del> status, body, err := sockRequest("GET", endpoint, nil) <del> c.Assert(err, check.IsNil) <del> c.Assert(status, check.Equals, http.StatusOK) <add> body := getInspectBody(c, cs.version, cleanedContainerID) <ide> <ide> var inspectJSON map[string]interface{} <del> if err = json.Unmarshal(body, &inspectJSON); err != nil { <add> if err := json.Unmarshal(body, &inspectJSON); err != nil { <ide> c.Fatalf("unable to unmarshal body for version %s: %v", cs.version, err) <ide> } <ide> <ide> func (s *DockerSuite) TestInspectApiContainerVolumeDriverLegacy(c *check.C) { <ide> <ide> cleanedContainerID := strings.TrimSpace(out) <ide> <del> cases := []string{"1.19", "1.20"} <add> cases := []string{"v1.19", "v1.20"} <ide> for _, version := range cases { <del> endpoint := fmt.Sprintf("/v%s/containers/%s/json", version, cleanedContainerID) <del> status, body, err := sockRequest("GET", endpoint, nil) <del> c.Assert(err, check.IsNil) <del> c.Assert(status, check.Equals, http.StatusOK) <add> body := getInspectBody(c, version, cleanedContainerID) <ide> <ide> var inspectJSON map[string]interface{} <del> if err = json.Unmarshal(body, &inspectJSON); err != nil { <add> if err := json.Unmarshal(body, &inspectJSON); err != nil { <ide> c.Fatalf("unable to unmarshal body for version %s: %v", version, err) <ide> } <ide> <ide> func (s *DockerSuite) TestInspectApiContainerVolumeDriver(c *check.C) { <ide> <ide> cleanedContainerID := strings.TrimSpace(out) <ide> <del> endpoint := fmt.Sprintf("/v1.21/containers/%s/json", cleanedContainerID) <del> status, body, err := sockRequest("GET", endpoint, nil) <del> c.Assert(err, check.IsNil) <del> c.Assert(status, check.Equals, http.StatusOK) <add> body := getInspectBody(c, "v1.21", cleanedContainerID) <ide> <ide> var inspectJSON map[string]interface{} <del> if err = json.Unmarshal(body, &inspectJSON); err != nil { <add> if err := json.Unmarshal(body, &inspectJSON); err != nil { <ide> c.Fatalf("unable to unmarshal body for version 1.21: %v", err) <ide> } <ide> <ide> func (s *DockerSuite) TestInspectApiEmptyFieldsInConfigPre121(c *check.C) { <ide> <ide> cleanedContainerID := strings.TrimSpace(out) <ide> <del> cases := []string{"1.19", "1.20"} <add> cases := []string{"v1.19", "v1.20"} <ide> for _, version := range cases { <del> endpoint := fmt.Sprintf("/v%s/containers/%s/json", version, cleanedContainerID) <del> status, body, err := sockRequest("GET", endpoint, nil) <del> c.Assert(err, check.IsNil) <del> c.Assert(status, check.Equals, http.StatusOK) <add> body := getInspectBody(c, version, cleanedContainerID) <ide> <ide> var inspectJSON map[string]interface{} <del> if err = json.Unmarshal(body, &inspectJSON); err != nil { <add> if err := json.Unmarshal(body, &inspectJSON); err != nil { <ide> c.Fatalf("unable to unmarshal body for version %s: %v", version, err) <ide> } <ide> <ide> func (s *DockerSuite) TestInspectApiEmptyFieldsInConfigPre121(c *check.C) { <ide> } <ide> } <ide> } <add> <add>func (s *DockerSuite) TestInspectApiBridgeNetworkSettings120(c *check.C) { <add> out, _ := dockerCmd(c, "run", "-d", "busybox", "true") <add> <add> cleanedContainerID := strings.TrimSpace(out) <add> body := getInspectBody(c, "v1.20", cleanedContainerID) <add> <add> var inspectJSON v1p20.ContainerJSON <add> err := json.Unmarshal(body, &inspectJSON) <add> c.Assert(err, checker.IsNil) <add> <add> settings := inspectJSON.NetworkSettings <add> c.Assert(settings.IPAddress, checker.Not(checker.HasLen), 0) <add>} <add> <add>func (s *DockerSuite) TestInspectApiBridgeNetworkSettings121(c *check.C) { <add> out, _ := dockerCmd(c, "run", "-d", "busybox", "true") <add> cleanedContainerID := strings.TrimSpace(out) <add> <add> body := getInspectBody(c, "v1.21", cleanedContainerID) <add> <add> var inspectJSON types.ContainerJSON <add> err := json.Unmarshal(body, &inspectJSON) <add> c.Assert(err, checker.IsNil) <add> <add> settings := inspectJSON.NetworkSettings <add> c.Assert(settings.IPAddress, checker.Not(checker.HasLen), 0) <add> c.Assert(settings.Networks["bridge"], checker.Not(checker.IsNil)) <add> c.Assert(settings.IPAddress, checker.Equals, settings.Networks["bridge"].IPAddress) <add>} <ide><path>integration-cli/docker_cli_network_unix_test.go <ide> import ( <ide> "strings" <ide> <ide> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/versions/v1p20" <ide> "github.com/docker/docker/pkg/integration/checker" <ide> "github.com/docker/libnetwork/driverapi" <ide> remoteapi "github.com/docker/libnetwork/drivers/remote/api" <ide> func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) { <ide> c.Assert(err, checker.IsNil) <ide> c.Assert(mac, checker.Equals, "a0:b1:c2:d3:e4:f5") <ide> } <add> <add>func (s *DockerSuite) TestInspectApiMultipeNetworks(c *check.C) { <add> dockerCmd(c, "network", "create", "mybridge1") <add> dockerCmd(c, "network", "create", "mybridge2") <add> out, _ := dockerCmd(c, "run", "-d", "busybox", "top") <add> id := strings.TrimSpace(out) <add> c.Assert(waitRun(id), check.IsNil) <add> <add> dockerCmd(c, "network", "connect", "mybridge1", id) <add> dockerCmd(c, "network", "connect", "mybridge2", id) <add> <add> body := getInspectBody(c, "v1.20", id) <add> var inspect120 v1p20.ContainerJSON <add> err := json.Unmarshal(body, &inspect120) <add> c.Assert(err, checker.IsNil) <add> <add> versionedIP := inspect120.NetworkSettings.IPAddress <add> <add> body = getInspectBody(c, "v1.21", id) <add> var inspect121 types.ContainerJSON <add> err = json.Unmarshal(body, &inspect121) <add> c.Assert(err, checker.IsNil) <add> c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3) <add> <add> bridge := inspect121.NetworkSettings.Networks["bridge"] <add> c.Assert(bridge.IPAddress, checker.Equals, versionedIP) <add> c.Assert(bridge.IPAddress, checker.Equals, inspect121.NetworkSettings.IPAddress) <add>} <ide><path>integration-cli/docker_utils.go <ide> func waitInspect(name, expr, expected string, timeout time.Duration) error { <ide> } <ide> return nil <ide> } <add> <add>func getInspectBody(c *check.C, version, id string) []byte { <add> endpoint := fmt.Sprintf("/%s/containers/%s/json", version, id) <add> status, body, err := sockRequest("GET", endpoint, nil) <add> c.Assert(err, check.IsNil) <add> c.Assert(status, check.Equals, http.StatusOK) <add> return body <add>}
7
Javascript
Javascript
fix version check in models directory [ci skip]
27c5795ea5b036fda98292a6486353ba4dc47ed3
<ide><path>website/src/templates/models.js <ide> function isStableVersion(v) { <ide> function getLatestVersion(modelId, compatibility) { <ide> for (let [version, models] of Object.entries(compatibility)) { <ide> if (isStableVersion(version) && models[modelId]) { <del> return models[modelId][0] <add> const modelVersions = models[modelId] <add> for (let modelVersion of modelVersions) { <add> if (isStableVersion(modelVersion)) { <add> return modelVersion <add> } <add> } <ide> } <ide> } <ide> }
1
Javascript
Javascript
remove unnecessary regex
700c16b0859a8c982869d5501934bed9e51d3662
<ide><path>src/attributes.js <ide> var rclass = /[\n\t\r]/g, <ide> rfocusable = /^(?:button|input|object|select|textarea)$/i, <ide> rclickable = /^a(?:rea)?$/i, <ide> rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, <del> rinvalidChar = /\:|^on/, <ide> nodeHook, boolHook; <ide> <ide> jQuery.fn.extend({
1
Javascript
Javascript
fix typo in test
7f8f8d7136d7392b96cc263ba124ceeb7995a4da
<ide><path>packages/ember-glimmer/tests/integration/components/utils-test.js <ide> moduleFor('Bounds tests', class extends RenderingTest { <ide> <ide> let { parentElement, firstNode, lastNode } = getViewBounds(component); <ide> <del> assert.equal(parentElement, this.element, 'a regular component should have the right parentElement'); <add> assert.equal(parentElement, this.element, 'a tagless component should have the right parentElement'); <ide> assert.equal(firstNode, this.$('#start-node')[0], 'a tagless component should have a range enclosing all of its nodes'); <ide> assert.equal(lastNode, this.$('#before-end-node')[0].nextSibling, 'a tagless component should have a range enclosing all of its nodes'); <ide> }
1
PHP
PHP
apply fixes from styleci
2054da77e02f1eebfd367fbfe903e84aa35e5085
<ide><path>tests/Database/DatabaseSchemaBuilderIntegrationTest.php <ide> public function testDropAllTablesWorksWithForeignKeys() <ide> public function testHasColumnWithTablePrefix() <ide> { <ide> $this->db->connection()->setTablePrefix('test_'); <del> <add> <ide> $this->db->connection()->getSchemaBuilder()->create('table1', function ($table) { <ide> $table->integer('id'); <ide> $table->string('name');
1
Java
Java
optimize pre-allocation of views
16a6e51045cf45d6f9d929f7ad4b2228f7417942
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> import com.facebook.react.fabric.mounting.mountitems.DispatchCommandMountItem; <ide> import com.facebook.react.fabric.mounting.mountitems.InsertMountItem; <ide> import com.facebook.react.fabric.mounting.mountitems.MountItem; <add>import com.facebook.react.fabric.mounting.mountitems.PreAllocateViewMountItem; <ide> import com.facebook.react.fabric.mounting.mountitems.RemoveMountItem; <ide> import com.facebook.react.fabric.mounting.mountitems.UpdateEventEmitterMountItem; <ide> import com.facebook.react.fabric.mounting.mountitems.UpdateLayoutMountItem; <ide> import com.facebook.react.bridge.WritableMap; <ide> import com.facebook.react.common.ReactConstants; <ide> import com.facebook.react.modules.core.ReactChoreographer; <add>import com.facebook.react.uimanager.IllegalViewOperationException; <ide> import com.facebook.react.uimanager.ReactRootViewTagGenerator; <ide> import com.facebook.react.uimanager.ThemedReactContext; <ide> import com.facebook.react.uimanager.ViewManagerPropertyUpdater; <ide> public class FabricUIManager implements UIManager, LifecycleEventListener { <ide> new ConcurrentHashMap<>(); <ide> private final EventBeatManager mEventBeatManager; <ide> private final Object mMountItemsLock = new Object(); <add> private final Object mPreMountItemsLock = new Object(); <ide> <ide> @GuardedBy("mMountItemsLock") <ide> private List<MountItem> mMountItems = new ArrayList<>(); <ide> <add> @GuardedBy("mPreMountItemsLock") <add> private List<MountItem> mPreMountItems = new ArrayList<>(); <add> <ide> @ThreadConfined(UI) <ide> private final DispatchUIFrameCallback mDispatchUIFrameCallback; <ide> <ide> public void onCatalystInstanceDestroy() { <ide> <ide> @DoNotStrip <ide> private void preallocateView(final int rootTag, final String componentName) { <del> UiThreadUtil.runOnUiThread( <del> new GuardedRunnable(mReactApplicationContext) { <del> @Override <del> public void runGuarded() { <del> ThemedReactContext context = <del> Assertions.assertNotNull(mReactContextForRootTag.get(rootTag)); <del> String component = sComponentNames.get(componentName); <del> Assertions.assertNotNull(component); <del> mMountingManager.preallocateView(context, component); <del> } <del> }); <add> synchronized (mPreMountItemsLock) { <add> ThemedReactContext context = <add> Assertions.assertNotNull(mReactContextForRootTag.get(rootTag)); <add> String component = sComponentNames.get(componentName); <add> Assertions.assertNotNull(component); <add> mPreMountItems.add(new PreAllocateViewMountItem(context, rootTag, component)); <add> } <ide> } <ide> <ide> @DoNotStrip <ide> private void flushMountItems() { <ide> } <ide> <ide> try { <add> List<MountItem> preMountItemsToDispatch; <add> synchronized (mPreMountItemsLock) { <add> preMountItemsToDispatch = mPreMountItems; <add> mPreMountItems = new ArrayList<>(); <add> } <add> <ide> List<MountItem> mountItemsToDispatch; <ide> synchronized (mMountItemsLock) { <del> if (mMountItems.isEmpty()) { <del> return; <del> } <ide> mountItemsToDispatch = mMountItems; <ide> mMountItems = new ArrayList<>(); <ide> } <ide> <add> Systrace.beginSection( <add> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <add> "FabricUIManager::premountViews (" + preMountItemsToDispatch.size() + " batches)"); <add> for (MountItem mountItem : preMountItemsToDispatch) { <add> mountItem.execute(mMountingManager); <add> } <add> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <add> <ide> Systrace.beginSection( <ide> Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, <ide> "FabricUIManager::mountViews (" + mountItemsToDispatch.size() + " batches)"); <ide> for (MountItem mountItem : mountItemsToDispatch) { <ide> mountItem.execute(mMountingManager); <ide> } <del> <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } catch (Exception ex) { <del> FLog.i(ReactConstants.TAG, "Exception thrown when executing UIFrameGuarded", ex); <add> FLog.e(ReactConstants.TAG, "Exception thrown when executing UIFrameGuarded", ex); <ide> mIsMountingEnabled = false; <ide> throw ex; <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/BatchMountItem.java <ide> */ <ide> package com.facebook.react.fabric.mounting.mountitems; <ide> <del>import com.facebook.react.fabric.mounting.MountingManager; <ide> import com.facebook.proguard.annotations.DoNotStrip; <add>import com.facebook.react.fabric.mounting.MountingManager; <ide> import com.facebook.systrace.Systrace; <ide> <ide> /** <ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/mounting/mountitems/PreAllocateViewMountItem.java <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> */ <add>package com.facebook.react.fabric.mounting.mountitems; <add> <add>import com.facebook.react.fabric.mounting.MountingManager; <add>import com.facebook.react.uimanager.ThemedReactContext; <add> <add>/** <add> * {@link MountItem} that is used to pre-allocate views for JS components. <add> */ <add>public class PreAllocateViewMountItem implements MountItem { <add> <add> private final String mComponent; <add> private final int mRootTag; <add> private final ThemedReactContext mContext; <add> <add> public PreAllocateViewMountItem(ThemedReactContext context, int rootTag, String component){ <add> mContext = context; <add> mComponent = component; <add> mRootTag = rootTag; <add> } <add> <add> @Override <add> public void execute(MountingManager mountingManager) { <add> mountingManager.preallocateView(mContext, mComponent); <add> } <add> <add> @Override <add> public String toString() { <add> return "[" + mRootTag + "] - Preallocate " + mComponent; <add> } <add>}
3
Text
Text
fix inconsistent formatting
a51554988e615b317e95125f5612a28c3bff8e8a
<ide><path>docs/sources/articles/https.md <ide> it will only connect to servers with a certificate signed by that CA. <ide> <ide> ## Create a CA, server and client keys with OpenSSL <ide> <del>> **Note:** replace all instances of `$HOST` in the following example with the <add>> **Note**: replace all instances of `$HOST` in the following example with the <ide> > DNS name of your Docker daemon's host. <ide> <ide> First generate CA private and public keys: <ide> Now that we have a CA, you can create a server key and certificate <ide> signing request (CSR). Make sure that "Common Name" (i.e., server FQDN or YOUR <ide> name) matches the hostname you will use to connect to Docker: <ide> <del>> **Note:** replace all instances of `$HOST` in the following example with the <add>> **Note**: replace all instances of `$HOST` in the following example with the <ide> > DNS name of your Docker daemon's host. <ide> <ide> $ openssl genrsa -out server-key.pem 2048 <ide> providing a certificate trusted by our CA: <ide> To be able to connect to Docker and validate its certificate, you now <ide> need to provide your client keys, certificates and trusted CA: <ide> <del>> **Note:** replace all instances of `$HOST` in the following example with the <add>> **Note**: replace all instances of `$HOST` in the following example with the <ide> > DNS name of your Docker daemon's host. <ide> <ide> $ docker --tlsverify --tlscacert=ca.pem --tlscert=cert.pem --tlskey=key.pem \
1
Javascript
Javascript
improve getusedname performance
c59df0a54215ad5ba934fe1493c98087a79b0f72
<ide><path>lib/ModuleGraph.js <ide> class ExportsInfo { <ide> if (info === undefined) info = this._otherExportsInfo; <ide> const x = info.getUsedName(name[0]); <ide> if (!x) return false; <add> if (name.length === 1) { <add> if (x === name[0]) return name; <add> return [x]; <add> } <ide> if (info.exportsInfo) { <ide> const nested = info.exportsInfo.getUsedName(name.slice(1)); <ide> if (!nested) return false;
1
Text
Text
embed more videos
0c09f38aa17666da3aa46545bee9992ab70fd88f
<ide><path>docs/Videos.md <ide> next: style <ide> <ide> <iframe width="650" height="315" src="//www.youtube.com/embed/hDviGU-57lU" frameborder="0" allowfullscreen></iframe> <ide> <add><iframe width="650" height="315" src="//www.youtube.com/embed/8N4f4h6SThc" frameborder="0" allowfullscreen></iframe> <add> <add><iframe width="650" height="315" src="//www.youtube.com/embed/-XxSCi8TKuk" frameborder="0" allowfullscreen></iframe> <add> <ide> ### [The Changelog #149](https://thechangelog.com/149/) <ide> With Christopher "vjeux" Chedeau and Spencer Ahrens <ide>
1
PHP
PHP
implement psr7 flavour for method & query data
149c9bae3c50e829173f480232584e098cc67794
<ide><path>src/Network/Request.php <ide> public function header($name) <ide> return $this->env($name); <ide> } <ide> <add> /** <add> * Get the HTTP method used for this request. <add> * <add> * @return string The name of the HTTP method used. <add> * @deprected 3.4.0 This method will be removed in 4.0.0. Use getMethod() instead. <add> */ <add> public function method() <add> { <add> return $this->env('REQUEST_METHOD'); <add> } <add> <ide> /** <ide> * Get the HTTP method used for this request. <ide> * There are a few ways to specify a method. <ide> public function header($name) <ide> * <ide> * @return string The name of the HTTP method used. <ide> */ <del> public function method() <add> public function getMethod() <ide> { <ide> return $this->env('REQUEST_METHOD'); <ide> } <ide> <add> /** <add> * Update the request method and get a new instance. <add> * <add> * @param string $method The HTTP method to use. <add> * @return static A new instance with the updated method. <add> */ <add> public function withMethod($method) <add> { <add> $new = clone $this; <add> $new->_environment['REQUEST_METHOD'] = $method; <add> return $new; <add> } <add> <add> /** <add> * Get all the query parameters. <add> * <add> * @return array <add> */ <add> public function getQueryParams() <add> { <add> return $this->query; <add> } <add> <add> /** <add> * Update the query string data and get a new instance. <add> * <add> * @param array $query The query string data to use <add> * @return static A new instance with the updated query string data. <add> */ <add> public function withQueryParams(array $query) <add> { <add> $new = clone $this; <add> $new->query = $query; <add> return $new; <add> } <add> <ide> /** <ide> * Get the host that the request was handled on. <ide> * <ide><path>tests/TestCase/Network/RequestTest.php <ide> public function testIsAll() <ide> * Test the method() method. <ide> * <ide> * @return void <add> * @deprecated <ide> */ <ide> public function testMethod() <ide> { <ide> public function testMethod() <ide> $this->assertEquals('delete', $request->method()); <ide> } <ide> <add> /** <add> * Test getMethod() <add> * <add> * @return void <add> */ <add> public function testGetMethod() <add> { <add> $request = new Request([ <add> 'environment' => ['REQUEST_METHOD' => 'delete'] <add> ]); <add> $this->assertEquals('delete', $request->getMethod()); <add> } <add> <add> /** <add> * Test withMethod() <add> * <add> * @return void <add> */ <add> public function testWithMethod() <add> { <add> $request = new Request([ <add> 'environment' => ['REQUEST_METHOD' => 'delete'] <add> ]); <add> $new = $request->withMethod('put'); <add> $this->assertEquals('delete', $request->getMethod()); <add> $this->assertEquals('put', $new->getMethod()); <add> } <add> <ide> /** <ide> * Test host retrieval. <ide> * <ide> public function testQueryWithArray() <ide> $this->assertNull($result); <ide> } <ide> <add> /** <add> * Test getQueryParams <add> * <add> * @return void <add> */ <add> public function testGetQueryParams() <add> { <add> $get = [ <add> 'test' => ['foo', 'bar'], <add> 'key' => 'value' <add> ]; <add> <add> $request = new Request([ <add> 'query' => $get <add> ]); <add> $this->assertSame($get, $request->getQueryParams()); <add> } <add> <add> /** <add> * Test withQueryParams and immutability <add> * <add> * @return void <add> */ <add> public function testWithQueryParams() <add> { <add> $get = [ <add> 'test' => ['foo', 'bar'], <add> 'key' => 'value' <add> ]; <add> <add> $request = new Request([ <add> 'query' => $get <add> ]); <add> $new = $request->withQueryParams(['new' => 'data']); <add> $this->assertSame($get, $request->getQueryParams()); <add> $this->assertSame(['new' => 'data'], $new->getQueryParams()); <add> } <add> <ide> /** <ide> * Test using param() <ide> *
2
Python
Python
add deprojectivize to pipeline
5738d373d5b1142cdea1cee4f44d75b454da935a
<ide><path>spacy/language.py <ide> def create_pipeline(cls, nlp=None): <ide> <ide> factories = { <ide> 'make_doc': create_tokenizer, <del> 'token_vectors': lambda nlp, **cfg: TokenVectorEncoder(nlp.vocab, **cfg), <del> 'tags': lambda nlp, **cfg: NeuralTagger(nlp.vocab, **cfg), <del> 'dependencies': lambda nlp, **cfg: NeuralDependencyParser(nlp.vocab, **cfg), <del> 'entities': lambda nlp, **cfg: NeuralEntityRecognizer(nlp.vocab, **cfg), <add> 'token_vectors': lambda nlp, **cfg: [TokenVectorEncoder(nlp.vocab, **cfg)], <add> 'tags': lambda nlp, **cfg: [NeuralTagger(nlp.vocab, **cfg)], <add> 'dependencies': lambda nlp, **cfg: [ <add> NeuralDependencyParser(nlp.vocab, **cfg), <add> PseudoProjectivity.deprojectivize], <add> 'entities': lambda nlp, **cfg: [NeuralEntityRecognizer(nlp.vocab, **cfg)], <ide> } <ide> <ide> token_match = TOKEN_MATCH <ide> def __init__(self, vocab=True, make_doc=True, pipeline=None, meta={}): <ide> self.pipeline[i] = factory(self, **meta.get(entry, {})) <ide> else: <ide> self.pipeline = [] <add> flat_list = [] <add> for pipe in self.pipeline: <add> if isinstance(pipe, list): <add> flat_list.extend(pipe) <add> else: <add> flat_list.append(pipe) <add> self.pipeline = flat_list <ide> <ide> def __call__(self, text, **disabled): <ide> """'Apply the pipeline to some text. The text can span multiple sentences, <ide> def get_grads(W, dW, key=None): <ide> tok2vec = self.pipeline[0] <ide> feats = tok2vec.doc2feats(docs) <ide> for proc in self.pipeline[1:]: <add> if not hasattr(proc, 'update'): <add> continue <ide> grads = {} <ide> tokvecses, bp_tokvecses = tok2vec.model.begin_update(feats, drop=drop) <ide> d_tokvecses = proc.update((docs, tokvecses), golds, sgd=get_grads, drop=drop) <ide> def pipe(self, texts, n_threads=2, batch_size=1000, **disabled): <ide> if hasattr(proc, 'pipe'): <ide> docs = proc.pipe(docs, n_threads=n_threads, batch_size=batch_size) <ide> else: <del> docs = (proc(doc) for doc in docs) <add> # Apply the function, but yield the doc <add> docs = _pipe(proc, docs) <ide> for doc in docs: <ide> yield doc <ide> <ide> def from_bytes(self, bytes_data, **exclude): <ide> if key not in exclude: <ide> setattr(self, key, value) <ide> return self <add> <add>def _pipe(func, docs): <add> for doc in docs: <add> func(doc) <add> yield doc
1
Python
Python
add model2model to __init__
bfb9b540d408fd7f0592f321157fe0371c930c5e
<ide><path>examples/run_seq2seq_finetuning.py <ide> # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <del>""" Finetuning seq2seq models for sequence generation. <del> <del>We use the procedure described in [1] to finetune models for sequence <del>generation. Let S1 and S2 be the source and target sequence respectively; we <del>pack them using the start of sequence [EOS] and end of sequence [EOS] token: <del> <del> [CLS] S1 [EOS] S2 [EOS] <del> <del>We then mask a fixed percentage of token from S2 at random and learn to predict <del>the masked words. [EOS] can be masked during finetuning so the model learns to <del>terminate the generation process. <del> <del>[1] Dong Li, Nan Yang, Wenhui Wang, Furu Wei, Xiaodong Liu, Yu Wang, Jianfeng <del>Gao, Ming Zhou, and Hsiao-Wuen Hon. “Unified Language Model Pre-Training for <del>Natural Language Understanding and Generation.” (May 2019) ArXiv:1905.03197 <del>""" <add>""" Finetuning seq2seq models for sequence generation.""" <ide> <ide> import argparse <ide> from collections import deque <ide> def set_seed(args): <ide> # Load dataset <ide> # ------------ <ide> <add> <ide> class TextDataset(Dataset): <ide> """ Abstracts the dataset used to train seq2seq models. <ide> <ide><path>transformers/__init__.py <ide> from .modeling_distilbert import (DistilBertForMaskedLM, DistilBertModel, <ide> DistilBertForSequenceClassification, DistilBertForQuestionAnswering, <ide> DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP) <add> from .modeling_seq2seq import Model2Model <ide> <ide> # Optimization <ide> from .optimization import (AdamW, ConstantLRSchedule, WarmupConstantSchedule, WarmupCosineSchedule,
2
PHP
PHP
use setexpectedexception() instead of annotations
201851da8aba82ddc5d03f251160cd861c15d8ac
<ide><path>tests/TestCase/I18n/Formatter/IcuFormatterTest.php <ide> public function testNativePluralSelection() <ide> /** <ide> * Tests that passing a message in the wrong format will throw an exception <ide> * <del> * @expectedException Exception <del> * @expectedExceptionMessage msgfmt_create: message formatter <ide> * @return void <ide> */ <ide> public function testBadMessageFormat() <ide> { <del> $this->skipIf(version_compare(PHP_VERSION, '7', '>='), 'Skiped for PHP 7 as MessageFormatter throws a different exception'); <del> $formatter = new IcuFormatter(); <del> $formatter->format('en_US', '{crazy format', ['some', 'vars']); <del> } <add> if (version_compare(PHP_VERSION, '7', '<')) { <add> $this->setExpectedException( <add> 'Exception', <add> 'msgfmt_create: message formatter' <add> ); <add> } else { <add> $this->setExpectedException( <add> 'Exception', <add> 'Constructor failed' <add> ); <add> } <ide> <del> /** <del> * Tests that passing a message in the wrong format will throw an exception <del> * <del> * @expectedException Exception <del> * @expectedExceptionMessage Constructor failed <del> * @return void <del> */ <del> public function testBadMessageFormatPHP7() <del> { <del> $this->skipIf(version_compare(PHP_VERSION, '7', '<'), 'Skiped for PHP 5.x as MessageFormatter throws a different exception'); <ide> $formatter = new IcuFormatter(); <ide> $formatter->format('en_US', '{crazy format', ['some', 'vars']); <ide> }
1
Text
Text
use proper syntax for class method reference
ac568795e71999dacd5cd05fb830050dcf09a4f6
<ide><path>activesupport/CHANGELOG.md <ide> <ide> *Puneet Agarwal* and *Xavier Noria* <ide> <del>* Added `Time#days_in_year` to return the number of days in the given year, or the <add>* Added `Time.days_in_year` to return the number of days in the given year, or the <ide> current year if no argument is provided. <ide> <ide> *Jon Pascoe*
1
Python
Python
apply suggestions from code review
3263cc6ef528cdd48bd72651ab735dd75c3339c2
<ide><path>numpy/core/setup.py <ide> def gl_if_msvc(build_cmd): <ide> we are building the library. <ide> """ <ide> if build_cmd.compiler.compiler_type == 'msvc': <add> # explicitly disable whole-program optimization <ide> return ['/GL-'] <ide> return [] <ide> <ide><path>numpy/random/setup.py <ide> def gl_if_msvc(build_cmd): <ide> distutils build command, so use this deferred calculation to run when <ide> we are building the library. <ide> """ <add> # Keep in sync with numpy/core/setup.py <ide> if build_cmd.compiler.compiler_type == 'msvc': <add> # explicitly disable whole-program optimization <ide> return ['/GL-'] <ide> return [] <ide>
2
Javascript
Javascript
use method name instead of method
2bce92383aecf5405119e1377c02b36c14268292
<ide><path>packages/ember-metal/lib/mixin.js <ide> function applyBeforeObservers(obj, m) { <ide> method = beforeObservers[methodName]; <ide> paths = method.__ember_observesBefore__; <ide> for (i=0, l=paths.length; i<l; i++) { <del> addBeforeObserver(obj, paths[i], obj, method); <add> addBeforeObserver(obj, paths[i], null, methodName); <ide> } <ide> } <ide> <ide> function applyObservers(obj, m) { <ide> method = observers[methodName]; <ide> paths = method.__ember_observes__; <ide> for (i=0, l=paths.length; i<l; i++) { <del> addObserver(obj, paths[i], obj, method); <add> addObserver(obj, paths[i], null, methodName); <ide> } <ide> } <ide> <ide> // mark as applied for future Mixin.apply() <del> m.beforeObservers = {}; <add> m.observers = {}; <ide> } <ide> <ide> function finishPartial(obj, m) { <ide><path>packages/ember-metal/tests/observer_test.js <ide> testBoth('local observers can be removed', function(get, set) { <ide> set(obj, 'bar', 'HI!'); <ide> equal(barObserved, 2, 'precond - observers should be fired'); <ide> <del> Ember.removeObserver(obj, 'bar', obj, obj.foo1); <add> Ember.removeObserver(obj, 'bar', null, 'foo1'); <ide> <ide> barObserved = 0; <ide> set(obj, 'bar', 'HI AGAIN!');
2
Python
Python
add regression test for
635792997cca666be560503e2d95f6e79225c2bf
<ide><path>spacy/tests/regression/test_issue1612.py <add>from __future__ import unicode_literals <add> <add>import pytest <add> <add>from ...lang.en import English <add> <add> <add>def test_issue1612(): <add> nlp = English() <add> doc = nlp('The black cat purrs.') <add> span = doc[1: 3] <add> assert span.orth_ == span.text
1
Java
Java
fix recent javadoc errors
84300b796cbd974b81ff3406502e3a7cd6cf1397
<ide><path>spring-context/src/main/java/org/springframework/context/support/ResourceBundleMessageSource.java <ide> * <p>On the classpath, bundle resources will be read with the locally configured <ide> * {@link #setDefaultEncoding encoding}: by default, ISO-8859-1; consider switching <ide> * this to UTF-8, or to {@code null} for the platform default encoding. On the JDK 9+ <del> * module path where locally provided {@link ResourceBundle.Control} handles are not <add> * module path where locally provided {@code ResourceBundle.Control} handles are not <ide> * supported, this MessageSource always falls back to {@link ResourceBundle#getBundle} <ide> * retrieval with the platform default encoding: UTF-8 with a ISO-8859-1 fallback on <ide> * JDK 9+ (configurable through the "java.util.PropertyResourceBundle.encoding" system <ide> protected ResourceBundle doGetBundle(String basename, Locale locale) throws Miss <ide> * Load a property-based resource bundle from the given reader. <ide> * <p>This will be called in case of a {@link #setDefaultEncoding "defaultEncoding"}, <ide> * including {@link ResourceBundleMessageSource}'s default ISO-8859-1 encoding. <del> * Note that this method can only be called with a {@link ResourceBundle.Control}: <add> * Note that this method can only be called with a {@code ResourceBundle.Control}: <ide> * When running on the JDK 9+ module path where such control handles are not <ide> * supported, any overrides in custom subclasses will effectively get ignored. <ide> * <p>The default implementation returns a {@link PropertyResourceBundle}. <ide> protected ResourceBundle loadBundle(Reader reader) throws IOException { <ide> * set to {@code null}, explicitly enforcing the platform default encoding <ide> * (which is UTF-8 with a ISO-8859-1 fallback on JDK 9+ but configurable <ide> * through the "java.util.PropertyResourceBundle.encoding" system property). <del> * Note that this method can only be called with a {@link ResourceBundle.Control}: <add> * Note that this method can only be called with a {@code ResourceBundle.Control}: <ide> * When running on the JDK 9+ module path where such control handles are not <ide> * supported, any overrides in custom subclasses will effectively get ignored. <ide> * <p>The default implementation returns a {@link PropertyResourceBundle}. <ide> public String toString() { <ide> <ide> <ide> /** <del> * Custom implementation of Java 6's {@code ResourceBundle.Control}, <del> * adding support for custom file encodings, deactivating the fallback to the <del> * system locale and activating ResourceBundle's native cache, if desired. <add> * Custom implementation of {@code ResourceBundle.Control}, adding support <add> * for custom file encodings, deactivating the fallback to the system locale <add> * and activating ResourceBundle's native cache, if desired. <ide> */ <ide> private class MessageSourceControl extends ResourceBundle.Control { <ide> <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/ResultSetWrappingSqlRowSet.java <ide> <ide> /** <ide> * The default implementation of Spring's {@link SqlRowSet} interface, wrapping a <del> * {@link java.sql.ResultSet}, catching any {@link SQLException java.sql.ResultSet}, catching any {@link SQLExceptions} and translating <del> * them to a corresponding Spring {@link InvalidResultSetAccessException}. <add> * {@link java.sql.ResultSet}, catching any {@link SQLException SQLExceptions} and <add> * translating them to a corresponding Spring {@link InvalidResultSetAccessException}. <ide> * <ide> * <p>The passed-in ResultSet should already be disconnected if the SqlRowSet is supposed <ide> * to be usable in a disconnected fashion. This means that you will usually pass in a <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/support/rowset/ResultSetWrappingSqlRowSetMetaData.java <ide> import org.springframework.lang.Nullable; <ide> <ide> /** <del> * The default implementation of Spring's {@link SqlRowSetMetaData} interface, wrapping <del> * a {@link java.sql.ResultSetMetaData} instance, catching any {@link SQLException java.sql.ResultSetMetaData} instance, catching any {@link SQLExceptions} <add> * The default implementation of Spring's {@link SqlRowSetMetaData} interface, wrapping a <add> * {@link java.sql.ResultSetMetaData} instance, catching any {@link SQLException SQLExceptions} <ide> * and translating them to a corresponding Spring {@link InvalidResultSetAccessException}. <ide> * <ide> * <p>Used by {@link ResultSetWrappingSqlRowSet}. <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/ReactorNettyCodec.java <ide> public interface ReactorNettyCodec<P> { <ide> <ide> /** <del> * Decode the input {@link ByteBuf} into one or more {@link Message ByteBuf} into one or more {@link Messages}. <add> * Decode the input {@link ByteBuf} into one or more {@link Message ByteBuf} <add> * into one or more {@link Message} objects. <ide> * @param inputBuffer the input buffer to decode from <ide> * @return 0 or more decoded messages <ide> */ <ide><path>spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequestFactory.java <ide> import org.springframework.lang.Nullable; <ide> <ide> /** <del> * {@link ClientHttpRequestFactory} wrapper with support for {@link ClientHttpRequestInterceptor ClientHttpRequestFactory} wrapper with support for {@link ClientHttpRequestInterceptors}. <add> * {@link ClientHttpRequestFactory} wrapper with support for <add> * {@link ClientHttpRequestInterceptor ClientHttpRequestInterceptors}. <ide> * <ide> * @author Arjen Poutsma <ide> * @since 3.1 <ide><path>spring-web/src/main/java/org/springframework/http/client/OkHttp3ClientHttpRequestFactory.java <ide> public OkHttp3ClientHttpRequestFactory(OkHttpClient client) { <ide> <ide> <ide> /** <del> * Sets the underlying read timeout in milliseconds. <add> * Set the underlying read timeout in milliseconds. <ide> * A value of 0 specifies an infinite timeout. <del> * @see OkHttpClient.Builder#readTimeout(long, TimeUnit) <ide> */ <ide> public void setReadTimeout(int readTimeout) { <ide> this.client = this.client.newBuilder() <ide> public void setReadTimeout(int readTimeout) { <ide> } <ide> <ide> /** <del> * Sets the underlying write timeout in milliseconds. <add> * Set the underlying write timeout in milliseconds. <ide> * A value of 0 specifies an infinite timeout. <del> * @see OkHttpClient.Builder#writeTimeout(long, TimeUnit) <ide> */ <ide> public void setWriteTimeout(int writeTimeout) { <ide> this.client = this.client.newBuilder() <ide> public void setWriteTimeout(int writeTimeout) { <ide> } <ide> <ide> /** <del> * Sets the underlying connect timeout in milliseconds. <add> * Set the underlying connect timeout in milliseconds. <ide> * A value of 0 specifies an infinite timeout. <del> * @see OkHttpClient.Builder#connectTimeout(long, TimeUnit) <ide> */ <ide> public void setConnectTimeout(int connectTimeout) { <ide> this.client = this.client.newBuilder() <ide><path>spring-web/src/main/java/org/springframework/http/converter/protobuf/ProtobufJsonFormatHttpMessageConverter.java <ide> public class ProtobufJsonFormatHttpMessageConverter extends ProtobufHttpMessageC <ide> <ide> /** <ide> * Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with default <del> * {@link JsonFormat.Parser} and {@link JsonFormat.Printer} configuration. <add> * {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration. <ide> */ <ide> public ProtobufJsonFormatHttpMessageConverter() { <ide> this(null, null, (ExtensionRegistry)null); <ide> } <ide> <ide> /** <ide> * Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given <del> * {@link JsonFormat.Parser} and {@link JsonFormat.Printer} configuration. <add> * {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration. <ide> * @param parser the JSON parser configuration <ide> * @param printer the JSON printer configuration <ide> */ <ide> public ProtobufJsonFormatHttpMessageConverter( <ide> <ide> /** <ide> * Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given <del> * {@link JsonFormat.Parser} and {@link JsonFormat.Printer} configuration, also <add> * {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also <ide> * accepting a registry that specifies protocol message extensions. <ide> * @param parser the JSON parser configuration <ide> * @param printer the JSON printer configuration <ide> public ProtobufJsonFormatHttpMessageConverter(@Nullable JsonFormat.Parser parser <ide> <ide> /** <ide> * Construct a new {@code ProtobufJsonFormatHttpMessageConverter} with the given <del> * {@link JsonFormat.Parser} and {@link JsonFormat.Printer} configuration, also <add> * {@code JsonFormat.Parser} and {@code JsonFormat.Printer} configuration, also <ide> * accepting an initializer that allows the registration of message extensions. <ide> * @param parser the JSON parser configuration <ide> * @param printer the JSON printer configuration <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/HttpHandler.java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> * <ide> * <p>Higher-level, but still generic, building blocks for applications such as <ide> * {@code WebFilter}, {@code WebSession}, {@code ServerWebExchange}, and others <del> * are available in the {@link org.springframework.web.server} package. <add> * are available in the {@code org.springframework.web.server} package. <ide> * <ide> * <p>Application level programming models such as annotated controllers and <ide> * functional handlers are available in the {@code spring-webflux} module. <ide> * <ide> * <p>Typically an {@link HttpHandler} represents an entire application with <ide> * higher-level programming models bridged via <del> * {@link org.springframework.web.server.adapter.WebHttpHandlerBuilder <del> * WebHttpHandlerBuilder}. Multiple applications at unique context paths can be <del> * plugged in with the help of the {@link ContextPathCompositeHandler}. <add> * {@link org.springframework.web.server.adapter.WebHttpHandlerBuilder}. <add> * Multiple applications at unique context paths can be plugged in with the <add> * help of the {@link ContextPathCompositeHandler}. <ide> * <ide> * @author Arjen Poutsma <ide> * @author Rossen Stoyanchev <ide><path>spring-web/src/main/java/org/springframework/web/client/DefaultResponseErrorHandler.java <ide> public boolean hasError(ClientHttpResponse response) throws IOException { <ide> /** <ide> * Template method called from {@link #hasError(ClientHttpResponse)}. <ide> * <p>The default implementation checks if the given status code is <del> * {@link HttpStatus.Series#CLIENT_ERROR CLIENT_ERROR} or <del> * {@link HttpStatus.Series#SERVER_ERROR SERVER_ERROR}. <add> * {@code HttpStatus.Series#CLIENT_ERROR CLIENT_ERROR} or <add> * {@code HttpStatus.Series#SERVER_ERROR SERVER_ERROR}. <ide> * Can be overridden in subclasses. <ide> * @param statusCode the HTTP status code <ide> * @return {@code true} if the response has an error; {@code false} otherwise <ide><path>spring-web/src/main/java/org/springframework/web/client/ExtractingResponseErrorHandler.java <ide> * {@linkplain #setSeriesMapping(Map) series mapping}. <ide> * <ide> * <p>If there is no match, this error handler will default to the behavior of <del> * {@link DefaultResponseErrorHandler}. Note that you can override this default behavior by <del> * specifying a {@linkplain #setSeriesMapping(Map) series mapping} from <del> * {@link HttpStatus.Series#CLIENT_ERROR} and/or {@link HttpStatus.Series#SERVER_ERROR} to <del> * {@code null}. <add> * {@link DefaultResponseErrorHandler}. Note that you can override this default behavior <add> * by specifying a {@linkplain #setSeriesMapping(Map) series mapping} from <add> * {@code HttpStatus.Series#CLIENT_ERROR} and/or {@code HttpStatus.Series#SERVER_ERROR} <add> * to {@code null}. <ide> * <ide> * @author Simon Galperin <ide> * @author Arjen Poutsma <ide><path>spring-web/src/main/java/org/springframework/web/client/RestTemplate.java <ide> * support of less frequent cases. <ide> * <ide> * <p><strong>NOTE:</strong> As of 5.0, the non-blocking, reactive <del> * {@link org.springframework.web.reactive.client.WebClient WebClient} offers a <add> * {@code org.springframework.web.reactive.client.WebClient} offers a <ide> * modern alternative to the {@code RestTemplate} with efficient support for <ide> * both sync and async, as well as streaming scenarios. The {@code RestTemplate} <ide> * will be deprecated in a future version and will not have major new features <ide><path>spring-web/src/main/java/org/springframework/web/server/session/CookieWebSessionIdResolver.java <ide> public Duration getCookieMaxAge() { <ide> } <ide> <ide> /** <del> * Add {@link Consumer} for a {@link ResponseCookie.ResponseCookieBuilder <del> * ResponseCookieBuilder} that will be invoked for each cookie being built, <del> * just before the call to <del> * {@link ResponseCookie.ResponseCookieBuilder#build() build()}. <add> * Add {@link Consumer} for a {@code ResponseCookieBuilder} that will be invoked <add> * for each cookie being built, just before the call to {@code build()}. <ide> * @param initializer consumer for a cookie builder <ide> * @since 5.1 <ide> */ <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ServerRequest.java <ide> static Builder from(ServerRequest other) { <ide> interface Headers { <ide> <ide> /** <del> * Return the list of acceptable {@linkplain MediaType media types}, <add> * Return the list of acceptable {@code MediaType media types}, <ide> * as specified by the {@code Accept} header. <ide> * <p>Returns an empty list when the acceptable media types are unspecified. <ide> */ <ide> List<MediaType> accept(); <ide> <ide> /** <del> * Return the list of acceptable {@linkplain Charset charsets}, <add> * Return the list of acceptable {@code Charset charsets}, <ide> * as specified by the {@code Accept-Charset} header. <ide> */ <ide> List<Charset> acceptCharset(); <ide> <ide> /** <del> * Return the list of acceptable {@linkplain Locale.LanguageRange languages}, <add> * Return the list of acceptable {@code Locale.LanguageRange languages}, <ide> * as specified by the {@code Accept-Language} header. <ide> */ <ide> List<Locale.LanguageRange> acceptLanguage(); <ide> interface Headers { <ide> OptionalLong contentLength(); <ide> <ide> /** <del> * Return the {@linkplain MediaType media type} of the body, as specified <add> * Return the {@code MediaType media type} of the body, as specified <ide> * by the {@code Content-Type} header. <ide> */ <ide> Optional<MediaType> contentType(); <ide> interface Builder { <ide> */ <ide> Builder uri(URI uri); <ide> <del> /** <add> /** <ide> * Add the given header value(s) under the given name. <ide> * @param headerName the header name <ide> * @param headerValues the header value(s) <ide> interface Builder { <ide> Builder cookie(String name, String... values); <ide> <ide> /** <del> * Manipulate this request's cookies with the given consumer. The <del> * map provided to the consumer is "live", so that the consumer can be used to <add> * Manipulate this request's cookies with the given consumer. <add> * The map provided to the consumer is "live", so that the consumer can be used to <ide> * {@linkplain MultiValueMap#set(Object, Object) overwrite} existing header values, <ide> * {@linkplain MultiValueMap#remove(Object) remove} values, or use any of the other <ide> * {@link MultiValueMap} methods. <ide> interface Builder { <ide> Builder attribute(String name, Object value); <ide> <ide> /** <del> * Manipulate this request's attributes with the given consumer. The map provided to the <del> * consumer is "live", so that the consumer can be used to <del> * {@linkplain Map#put(Object, Object) overwrite} existing header values, <add> * Manipulate this request's attributes with the given consumer. <add> * The map provided to the consumer is "live", so that the consumer can be used <add> * to {@linkplain Map#put(Object, Object) overwrite} existing header values, <ide> * {@linkplain Map#remove(Object) remove} values, or use any of the other <ide> * {@link Map} methods. <ide> * @param attributesConsumer a function that consumes the attributes map <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/UndertowWebSocketClient.java <ide> public XnioWorker getXnioWorker() { <ide> /** <ide> * Set the {@link io.undertow.connector.ByteBufferPool ByteBufferPool} to pass to <ide> * {@link io.undertow.websockets.client.WebSocketClient#connectionBuilder}. <del> * <p>By default an indirect {@link io.undertow.server.DefaultByteBufferPool} with a buffer size <del> * of {@value #DEFAULT_POOL_BUFFER_SIZE} is used. <add> * <p>By default an indirect {@link io.undertow.server.DefaultByteBufferPool} <add> * with a buffer size of 8192 is used. <ide> * @since 5.0.8 <add> * @see #DEFAULT_POOL_BUFFER_SIZE <ide> */ <ide> public void setByteBufferPool(ByteBufferPool byteBufferPool) { <ide> Assert.notNull(byteBufferPool, "ByteBufferPool must not be null"); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/SubProtocolHandler.java <ide> <ide> /** <ide> * A contract for handling WebSocket messages as part of a higher level protocol, <del> * referred to as "sub-protocol" in the WebSocket RFC specification. Handles both <del> * {@link WebSocketMessage}s from a client as well as {@link Message WebSocketMessage}s from a client as well as {@link Messages} to a client. <add> * referred to as "sub-protocol" in the WebSocket RFC specification. <add> * Handles both {@link WebSocketMessage WebSocketMessages} from a client <add> * as well as {@link Message Messages} to a client. <ide> * <ide> * <p>Implementations of this interface can be configured on a <ide> * {@link SubProtocolWebSocketHandler} which selects a sub-protocol handler to <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java <ide> * A basic implementation of {@link org.springframework.web.socket.sockjs.SockJsService} <ide> * with support for SPI-based transport handling and session management. <ide> * <del> * <p>Based on the {@link TransportHandler} SPI. {@link TransportHandler TransportHandler} SPI. {@link TransportHandlers} may additionally <del> * implement the {@link SockJsSessionFactory} and {@link HandshakeHandler} interfaces. <add> * <p>Based on the {@link TransportHandler} SPI. {@link TransportHandler TransportHandlers} may <add> * additionally implement the {@link SockJsSessionFactory} and {@link HandshakeHandler} interfaces. <ide> * <ide> * <p>See the {@link AbstractSockJsService} base class for important details on request mapping. <ide> *
16
Javascript
Javascript
add uint32 test for -1
e454e9b33f2a3e21d0c36a96d47cf39ce3e42d6c
<ide><path>test/js-native-api/test_number/test.js <ide> testUint32(4294967295); <ide> testUint32(4294967296, 0); <ide> testUint32(4294967297, 1); <ide> testUint32(17 * 4294967296 + 1, 1); <add>testUint32(-1, 0xffffffff); <ide> <ide> // Validate documented behavior when value is retrieved as 32-bit integer with <ide> // `napi_get_value_int32`
1
PHP
PHP
add negative numbers test
767558e7841b4fa37d67db9e6cb3e3ba19db77f7
<ide><path>tests/Support/SupportCollectionTest.php <ide> public function testSort() <ide> $data = (new Collection([5, 3, 1, 2, 4]))->sort(); <ide> $this->assertEquals([1, 2, 3, 4, 5], $data->values()->all()); <ide> <add> $data = (new Collection([-1, -3, -2, -4, -5, 0, 5, 3, 1, 2, 4]))->sort(); <add> $this->assertEquals([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], $data->values()->all()); <add> <ide> $data = (new Collection(['foo', 'bar-10', 'bar-1']))->sort(); <ide> $this->assertEquals(['bar-1', 'bar-10', 'foo'], $data->values()->all()); <ide> }
1
Text
Text
add configuration serialization to readme
20577d8a7cb7dd38d3c5295c6f44bf377435e608
<ide><path>README.md <ide> This package comprises the following classes that can be imported in Python and <ide> - Configuration classes for BERT, OpenAI GPT and Transformer-XL (in the respective [`modeling.py`](./pytorch_pretrained_bert/modeling.py), [`modeling_openai.py`](./pytorch_pretrained_bert/modeling_openai.py), [`modeling_transfo_xl.py`](./pytorch_pretrained_bert/modeling_transfo_xl.py) files): <ide> - `BertConfig` - Configuration class to store the configuration of a `BertModel` with utilities to read and write from JSON configuration files. <ide> - `OpenAIGPTConfig` - Configuration class to store the configuration of a `OpenAIGPTModel` with utilities to read and write from JSON configuration files. <add> - `GPT2Config` - Configuration class to store the configuration of a `GPT2Model` with utilities to read and write from JSON configuration files. <ide> - `TransfoXLConfig` - Configuration class to store the configuration of a `TransfoXLModel` with utilities to read and write from JSON configuration files. <ide> <ide> The repository further comprises: <ide> model = GPT2Model.from_pretrained('gpt2') <ide> <ide> ``` <ide> <add>### Configuration classes <add> <add>Models (BERT, GPT, GPT-2 and Transformer-XL) are defined and build from configuration classes which containes the parameters of the models (number of layers, dimensionalities...) and a few utilities to read and write from JSON configuration files. The respective configuration classes are: <add> <add>- `BertConfig` for `BertModel` and BERT classes instances. <add>- `OpenAIGPTConfig` for `OpenAIGPTModel` and OpenAI GPT classes instances. <add>- `GPT2Config` for `GPT2Model` and OpenAI GPT-2 classes instances. <add>- `TransfoXLConfig` for `TransfoXLModel` and Transformer-XL classes instances. <add> <add>These configuration classes contains a few utilities to load and save configurations: <add> <add>- `from_dict(cls, json_object)`: A class method to construct a configuration from a Python dictionary of parameters. Returns an instance of the configuration class. <add>- `from_json_file(cls, json_file)`: A class method to construct a configuration from a json file of parameters. Returns an instance of the configuration class. <add>- `to_dict()`: Serializes an instance to a Python dictionary. Returns a dictionary. <add>- `to_json_string()`: Serializes an instance to a JSON string. Returns a string. <add>- `to_json_file(json_file_path)`: Save an instance to a json file. <add> <ide> ### PyTorch models <ide> <ide> #### 1. `BertModel`
1
Ruby
Ruby
add proper types to dump() and fix inreplace error
2de6958a36a4ef3172e2269a5ce11f15e94e57e9
<ide><path>Library/Homebrew/build_environment.rb <ide> def env(*settings) <ide> ].freeze <ide> private_constant :KEYS <ide> <del> sig { params(env: T.untyped).returns(T::Array[String]) } <add> sig { params(env: T::Hash[String, T.nilable(T.any(String, Pathname))]).returns(T::Array[String]) } <ide> def self.keys(env) <ide> KEYS & env.keys <ide> end <ide> <del> sig { params(env: T.untyped, f: IO).void } <add> sig { params(env: T::Hash[String, T.nilable(T.any(String, Pathname))], f: IO).void } <ide> def self.dump(env, f = $stdout) <ide> keys = self.keys(env) <ide> keys -= %w[CC CXX OBJC OBJCXX] if env["CC"] == env["HOMEBREW_CC"] <ide> <ide> keys.each do |key| <ide> value = env.fetch(key) <add> <ide> s = +"#{key}: #{value}" <ide> case key <ide> when "CC", "CXX", "LD" <del> s << " => #{Pathname.new(value).realpath}" if File.symlink?(value) <add> s << " => #{Pathname.new(value).realpath}" if value.present? && File.symlink?(value) <ide> end <ide> s.freeze <ide> f.puts s <ide><path>Library/Homebrew/cmd/--env.rb <ide> def __env <ide> if shell.nil? <ide> BuildEnvironment.dump ENV <ide> else <del> BuildEnvironment.keys(ENV).each do |key| <add> BuildEnvironment.keys(ENV.to_h).each do |key| <ide> puts Utils::Shell.export_value(key, ENV.fetch(key), shell) <ide> end <ide> end <ide><path>Library/Homebrew/exceptions.rb <ide> def initialize(formula) <ide> <ide> # Raised when an error occurs during a formula build. <ide> class BuildError < RuntimeError <add> extend T::Sig <add> <ide> attr_reader :cmd, :args, :env <ide> attr_accessor :formula, :options <ide> <add> sig { <add> params( <add> formula: T.nilable(Formula), <add> cmd: T.any(String, Pathname), <add> args: T::Array[T.any(String, Pathname, Integer)], <add> env: T::Hash[String, T.untyped], <add> ).void <add> } <ide> def initialize(formula, cmd, args, env) <ide> @formula = formula <ide> @cmd = cmd <ide> def initialize(formula, cmd, args, env) <ide> super "Failed executing: #{cmd} #{pretty_args}".strip <ide> end <ide> <add> sig { returns(T::Array[T.untyped]) } <ide> def issues <ide> @issues ||= fetch_issues <ide> end <ide> <add> sig { returns(T::Array[T.untyped]) } <ide> def fetch_issues <ide> GitHub.issues_for_formula(formula.name, tap: formula.tap, state: "open") <ide> rescue GitHub::API::RateLimitExceededError => e <ide> opoo e.message <ide> [] <ide> end <ide> <add> sig { params(verbose: T::Boolean).void } <ide> def dump(verbose: false) <ide> puts <ide> <ide><path>Library/Homebrew/formula.rb <ide> def install; end <ide> def inreplace(paths, before = nil, after = nil, audit_result = true) # rubocop:disable Style/OptionalBooleanParameter <ide> super(paths, before, after, audit_result) <ide> rescue Utils::Inreplace::Error <del> raise BuildError.new(self, "inreplace", paths, nil) <add> raise BuildError.new(self, "inreplace", paths, {}) <ide> end <ide> <ide> protected
4
Javascript
Javascript
remove duplicate assignments
e06b5d7af7619e9234bb7eb8a9d66b3c7d245ad9
<ide><path>lib/http.js <ide> ClientRequest.prototype.onSocket = function(socket) { <ide> parser.incoming = null; <ide> req.parser = parser; <ide> <del> parser.socket = socket; <ide> socket.parser = parser; <del> parser.incoming = null; <ide> socket._httpMessage = req; <ide> <ide> // Setup "drain" propogation.
1
Ruby
Ruby
remove dead code
80c6b901d4d87cee610ab0a438ff6e3c6bf118d1
<ide><path>actionpack/lib/action_dispatch/http/response.rb <ide> def initialize(status = 200, header = {}, body = []) <ide> <ide> self.body, self.status = body, status <ide> <del> @blank = false <ide> @cv = new_cond <ide> @committed = false <ide> @sending = false <ide> def write(string) <ide> @stream.write string <ide> end <ide> <del> EMPTY = " " <del> <ide> # Allows you to manually set or override the response body. <ide> def body=(body) <del> @blank = true if body == EMPTY <del> <ide> if body.respond_to?(:to_path) <ide> @stream = body <ide> else
1
Java
Java
clarify requestmappinghandleradapter javadoc
2b3ad218e579591396a50363f04c097d05be3a12
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerAdapter.java <ide> public void setSessionAttributeStore(SessionAttributeStore sessionAttributeStore <ide> <ide> /** <ide> * Cache content produced by {@code @SessionAttributes} annotated handlers <del> * for the given number of seconds. Default is 0, preventing caching completely. <add> * for the given number of seconds. <add> * <p>Possible values are: <add> * <ul> <add> * <li>-1: no generation of cache-related headers</li> <add> * <li>0 (default value): "Cache-Control: no-store" will prevent caching</li> <add> * <li>> 0: "Cache-Control: max-age=seconds" will ask to cache content; not advised when dealing <add> * with session attributes</li> <add> * </ul> <ide> * <p>In contrast to the "cacheSeconds" property which will apply to all general <ide> * handlers (but not to {@code @SessionAttributes} annotated handlers), <ide> * this setting will apply to {@code @SessionAttributes} handlers only. <add> * <ide> * @see #setCacheSeconds <ide> * @see org.springframework.web.bind.annotation.SessionAttributes <ide> */
1
PHP
PHP
simplify file cache
b0a087370c9595efd426506439f52967b1711eaa
<ide><path>src/Illuminate/Filesystem/Cache.php <ide> public function save() <ide> { <ide> $contents = $this->getForStorage(); <ide> <del> if (! is_null($this->expire)) { <del> $this->repository->put($this->key, $contents, $this->expire); <del> } else { <del> $this->repository->forever($this->key, $contents); <del> } <add> $this->repository->put($this->key, $contents, $this->expire); <ide> } <ide> }
1
Javascript
Javascript
remove redundant arg flipping in evented#one
08ff5b991e2a42ab20adaa8d939ec680a3055c67
<ide><path>packages/@ember/-internals/runtime/lib/mixins/evented.js <ide> export default Mixin.create({ <ide> @public <ide> */ <ide> one(name, target, method) { <del> if (!method) { <del> method = target; <del> target = null; <del> } <del> <ide> addListener(this, name, target, method, true); <ide> return this; <ide> },
1
Mixed
Javascript
add code snippets to primitives
13027d48f18fa43f3e93d60c75661cd598965b5b
<ide><path>threejs/lessons/resources/threejs-primitives.js <ide> }, <ide> }, <ide> ParametricBufferGeometry: { <del> create() { <del> /* <del> from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js <add> /* <add> from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js <ide> <del> The MIT License <add> The MIT License <ide> <del> Copyright © 2010-2018 three.js authors <add> Copyright © 2010-2018 three.js authors <ide> <del> Permission is hereby granted, free of charge, to any person obtaining a copy <del> of this software and associated documentation files (the "Software"), to deal <del> in the Software without restriction, including without limitation the rights <del> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <del> copies of the Software, and to permit persons to whom the Software is <del> furnished to do so, subject to the following conditions: <add> Permission is hereby granted, free of charge, to any person obtaining a copy <add> of this software and associated documentation files (the "Software"), to deal <add> in the Software without restriction, including without limitation the rights <add> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <add> copies of the Software, and to permit persons to whom the Software is <add> furnished to do so, subject to the following conditions: <ide> <del> The above copyright notice and this permission notice shall be included in <del> all copies or substantial portions of the Software. <add> The above copyright notice and this permission notice shall be included in <add> all copies or substantial portions of the Software. <ide> <del> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <del> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <del> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <del> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <del> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <del> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <del> THE SOFTWARE. <add> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <add> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <add> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <add> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <add> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <add> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <add> THE SOFTWARE. <ide> <del> */ <add> */ <add> create() { <add> // from: https://github.com/mrdoob/three.js/blob/b8d8a8625465bd634aa68e5846354d69f34d2ff5/examples/js/ParametricGeometries.js <ide> function klein(v, u, target) { <ide> u *= Math.PI; <ide> v *= 2 * Math.PI; <ide> const text = base.innerHTML; <ide> base.innerHTML = ''; <ide> <del> const elem = addDiv(base, 'shape'); <add> const pair = addDiv(base, 'pair'); <add> const elem = addDiv(pair, 'shape'); <ide> <del> const right = addDiv(base, 'desc'); <add> const right = addDiv(pair, 'desc'); <ide> addLink(right, name); <ide> if (info.nonBuffer !== false) { <ide> addElem(right, 'span', '', ', '); <ide> addLink(right, name.replace('Buffer', '')); <ide> } <ide> addDiv(right, '.note').innerHTML = text; <ide> <add> const rawLines = info.create.toString().replace('return new', 'const geometry =').split(/\n/); <add> const createRE = /^( *create\()/; <add> const m = createRE.exec(rawLines[0]); <add> const prefixLen = m[1].length + 1; <add> const trimmedLines = rawLines.slice(1, rawLines.length - 1).map(line => line.substring(prefixLen)); <add> <add> addElem(base, 'pre', 'prettyprint showmods', trimmedLines.join('\n')); <add> <ide> return createLiveImage(elem, info); <ide> } <ide> <ide><path>threejs/lessons/threejs-primitives.md <ide> cover making and loading data from several 3D modeling <ide> programs. For now let's go over some of the available <ide> primitives. <ide> <del><div class="primitives"> <ide> <div data-primitive="BoxBufferGeometry">A Box</div> <ide> <div data-primitive="CircleBufferGeometry">A flat circle</div> <ide> <div data-primitive="ConeBufferGeometry">A Cone</div> <ide> for <code>TextBufferGeometry</code> and <code>TextGeometry</code> respectively.< <ide> <div data-primitive="TubeBufferGeometry">A circle traced down a path</div> <ide> <div data-primitive="EdgesGeometry">A helper object that takes another geometry as input and generates edges only if the angle between faces is greater than some threshold. For example if you look at the box at the top it shows a line going through each face showing every triangle that makes the box. Using an EdgesGeometry instead the middle lines are removed.</div> <ide> <div data-primitive="WireframeGeometry">Generates geometry that contains one line segment (2 points) per edge in the given geometry. With out this you'd often be missing edges or get extra edges since WebGL generally requires 2 points per line segment. For example if all you had was a single triangle there would only be 3 points. If you tried to draw it using a material with <code>wireframe: true</code> you would only get a single line. Passing that triangle geometry to a <code>WireframeGeometry</code> will generate a new Geometry that has 3 lines segments using 6 points..</div> <del></div> <ide> <ide> You might notice of most of them come in pairs of `Geometry` <ide> or `BufferGeometry`. The difference between the 2 types is effectively flexibility <ide> to use it](threejs-scenegraph.html). <ide> <script src="resources/threejs-lesson-utils.js"></script> <ide> <script src="resources/threejs-primitives.js"></script> <ide> <style> <del>.primitives { <add>div[data-primitive] { <add> padding-bottom: 2em; <add> border-bottom: 1px solid #888; <add> margin-bottom: 2em; <ide> } <del>.primitives>div { <add>div[data-primitive] .pair { <ide> display: flex; <ide> align-items: center; <ide> margin-bottom: 1em; <ide> } <del>.primitives .shape { <add>div[data-primitive] .shape { <ide> flex: 0 0 auto; <ide> width: 200px; <ide> height: 200px; <ide> } <del>.primitives .desc { <add>div[data-primitive] .desc { <ide> word-wrap: break-word; <ide> padding: 1em; <ide> min-width: 0; <ide> } <del>.primitives .desc code { <add>div[data-primitive] .desc code { <ide> white-space: normal; <ide> } <ide> @media (max-width: 550px) { <del> .primitives .shape { <add> div[data-primitive] .shape { <ide> width: 120px; <ide> height: 120px; <ide> } <ide> } <del>.primitives .desc { <add>div[data-primitive] .desc { <ide> flex: 1 1 auto; <ide> } <ide> </style>
2
Python
Python
introduce types in airflow.bin.cli
0974aabd31abc6aeadf4f07c9c310b6750e28e2f
<ide><path>airflow/bin/cli.py <ide> import os <ide> import textwrap <ide> from argparse import RawTextHelpFormatter <del>from itertools import filterfalse, tee <del>from typing import Callable <add>from typing import Callable, Dict, Iterable, List, NamedTuple, Set, Union <ide> <ide> from tabulate import tabulate_formats <ide> <ide> from airflow import api, settings <ide> from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException <ide> from airflow.executors.executor_loader import ExecutorLoader <add>from airflow.utils.helpers import partition <ide> from airflow.utils.module_loading import import_string <ide> from airflow.utils.timezone import parse as parsedate <ide> <ide> def __init__(self, flags=None, help=None, action=None, default=None, nargs=None, <ide> ] <ide> <ide> <add>class ActionCommand(NamedTuple): <add> """Single CLI command""" <add> name: str <add> help: str <add> func: Callable <add> args: Iterable[Arg] <add> <add> <add>class GroupCommand(NamedTuple): <add> """ClI command with subcommands""" <add> name: str <add> help: str <add> subcommands: Iterable <add> <add> <add>CLICommand = Union[ActionCommand, GroupCommand] <add> <add> <ide> class CLIFactory: <ide> """ <ide> Factory class which generates command line argument parser and holds information <ide> about all available Airflow commands <ide> """ <ide> DAGS_SUBCOMMANDS = ( <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_list_dags'), <del> 'name': 'list', <del> 'help': "List all the DAGs", <del> 'args': (ARG_SUBDIR, ARG_REPORT), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_list_dag_runs'), <del> 'name': 'list_runs', <del> 'help': "List dag runs given a DAG id. If state option is given, it will only " <del> "search for all the dagruns with the given state. " <del> "If no_backfill option is given, it will filter out " <del> "all backfill dagruns for given dag id. " <del> "If start_date is given, it will filter out " <del> "all the dagruns that were executed before this date. " <del> "If end_date is given, it will filter out " <del> "all the dagruns that were executed after this date. ", <del> 'args': (ARG_DAG_ID_OPT, ARG_NO_BACKFILL, ARG_STATE, ARG_OUTPUT, ARG_START_DATE, ARG_END_DATE), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_list_jobs'), <del> 'name': 'list_jobs', <del> 'help': "List the jobs", <del> 'args': (ARG_DAG_ID_OPT, ARG_STATE, ARG_LIMIT, ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_state'), <del> 'name': 'state', <del> 'help': "Get the status of a dag run", <del> 'args': (ARG_DAG_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_next_execution'), <del> 'name': 'next_execution', <del> 'help': "Get the next execution datetime of a DAG", <del> 'args': (ARG_DAG_ID, ARG_SUBDIR), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_pause'), <del> 'name': 'pause', <del> 'help': 'Pause a DAG', <del> 'args': (ARG_DAG_ID, ARG_SUBDIR), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_unpause'), <del> 'name': 'unpause', <del> 'help': 'Resume a paused DAG', <del> 'args': (ARG_DAG_ID, ARG_SUBDIR), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_trigger'), <del> 'name': 'trigger', <del> 'help': 'Trigger a DAG run', <del> 'args': (ARG_DAG_ID, ARG_SUBDIR, ARG_RUN_ID, ARG_CONF, ARG_EXEC_DATE), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_delete'), <del> 'name': 'delete', <del> 'help': "Delete all DB records related to the specified DAG", <del> 'args': (ARG_DAG_ID, ARG_YES), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_show'), <del> 'name': 'show', <del> 'help': "Displays DAG's tasks with their dependencies", <del> 'args': (ARG_DAG_ID, ARG_SUBDIR, ARG_SAVE, ARG_IMGCAT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.dag_command.dag_backfill'), <del> 'name': 'backfill', <del> 'help': "Run subsections of a DAG for a specified date range. " <del> "If reset_dag_run option is used," <del> " backfill will first prompt users whether airflow " <del> "should clear all the previous dag_run and task_instances " <del> "within the backfill date range. " <del> "If rerun_failed_tasks is used, backfill " <del> "will auto re-run the previous failed task instances" <del> " within the backfill date range", <del> 'args': ( <del> ARG_DAG_ID, ARG_TASK_REGEX, ARG_START_DATE, ARG_END_DATE, <del> ARG_MARK_SUCCESS, ARG_LOCAL, ARG_DONOT_PICKLE, ARG_YES, <del> ARG_BF_IGNORE_DEPENDENCIES, ARG_BF_IGNORE_FIRST_DEPENDS_ON_PAST, <add> ActionCommand( <add> name='list', <add> help="List all the DAGs", <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_list_dags'), <add> args=(ARG_SUBDIR, ARG_REPORT), <add> ), <add> ActionCommand( <add> name='list_runs', <add> help=( <add> "List dag runs given a DAG id. If state option is given, it will only search for all the " <add> "dagruns with the given state. If no_backfill option is given, it will filter out all " <add> "backfill dagruns for given dag id. If start_date is given, it will filter out all the " <add> "dagruns that were executed before this date. If end_date is given, it will filter out " <add> "all the dagruns that were executed after this date. " <add> ), <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_list_dag_runs'), <add> args=(ARG_DAG_ID_OPT, ARG_NO_BACKFILL, ARG_STATE, ARG_OUTPUT, ARG_START_DATE, ARG_END_DATE), <add> ), <add> ActionCommand( <add> name='list_jobs', <add> help="List the jobs", <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_list_jobs'), <add> args=(ARG_DAG_ID_OPT, ARG_STATE, ARG_LIMIT, ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='state', <add> help="Get the status of a dag run", <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_state'), <add> args=(ARG_DAG_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <add> ), <add> ActionCommand( <add> name='next_execution', <add> help="Get the next execution datetime of a DAG", <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_next_execution'), <add> args=(ARG_DAG_ID, ARG_SUBDIR), <add> ), <add> ActionCommand( <add> name='pause', <add> help='Pause a DAG', <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_pause'), <add> args=(ARG_DAG_ID, ARG_SUBDIR), <add> ), <add> ActionCommand( <add> name='unpause', <add> help='Resume a paused DAG', <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_unpause'), <add> args=(ARG_DAG_ID, ARG_SUBDIR), <add> ), <add> ActionCommand( <add> name='trigger', <add> help='Trigger a DAG run', <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_trigger'), <add> args=(ARG_DAG_ID, ARG_SUBDIR, ARG_RUN_ID, ARG_CONF, ARG_EXEC_DATE), <add> ), <add> ActionCommand( <add> name='delete', <add> help="Delete all DB records related to the specified DAG", <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_delete'), <add> args=(ARG_DAG_ID, ARG_YES), <add> ), <add> ActionCommand( <add> name='show', <add> help="Displays DAG's tasks with their dependencies", <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_show'), <add> args=(ARG_DAG_ID, ARG_SUBDIR, ARG_SAVE, ARG_IMGCAT,), <add> ), <add> ActionCommand( <add> name='backfill', <add> help=( <add> "Run subsections of a DAG for a specified date range. If reset_dag_run option is used, " <add> "backfill will first prompt users whether airflow should clear all the previous dag_run and " <add> "task_instances within the backfill date range. If rerun_failed_tasks is used, backfill " <add> "will auto re-run the previous failed task instances within the backfill date range" <add> ), <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_backfill'), <add> args=( <add> ARG_DAG_ID, ARG_TASK_REGEX, ARG_START_DATE, ARG_END_DATE, ARG_MARK_SUCCESS, ARG_LOCAL, <add> ARG_DONOT_PICKLE, ARG_YES, ARG_BF_IGNORE_DEPENDENCIES, ARG_BF_IGNORE_FIRST_DEPENDS_ON_PAST, <ide> ARG_SUBDIR, ARG_POOL, ARG_DELAY_ON_LIMIT, ARG_DRY_RUN, ARG_VERBOSE, ARG_CONF, <ide> ARG_RESET_DAG_RUN, ARG_RERUN_FAILED_TASKS, ARG_RUN_BACKWARDS <ide> ), <del> }, <del> { <del> "func": lazy_load_command('airflow.cli.commands.dag_command.dag_test'), <del> 'name': 'test', <del> 'help': "Execute one run of a DAG", <del> 'args': (ARG_DAG_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <del> }, <add> ), <add> ActionCommand( <add> func=lazy_load_command('airflow.cli.commands.dag_command.dag_test'), <add> name='test', <add> help="Execute one run of a DAG", <add> args=(ARG_DAG_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <add> ), <ide> ) <ide> TASKS_COMMANDS = ( <del> { <del> 'func': lazy_load_command('airflow.cli.commands.task_command.task_list'), <del> 'name': 'list', <del> 'help': "List the tasks within a DAG", <del> 'args': (ARG_DAG_ID, ARG_TREE, ARG_SUBDIR), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.task_command.task_clear'), <del> 'name': 'clear', <del> 'help': "Clear a set of task instance, as if they never ran", <del> 'args': ( <del> ARG_DAG_ID, ARG_TASK_REGEX, ARG_START_DATE, ARG_END_DATE, ARG_SUBDIR, <del> ARG_UPSTREAM, ARG_DOWNSTREAM, ARG_YES, ARG_ONLY_FAILED, <del> ARG_ONLY_RUNNING, ARG_EXCLUDE_SUBDAGS, ARG_EXCLUDE_PARENTDAG, ARG_DAG_REGEX), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.task_command.task_state'), <del> 'name': 'state', <del> 'help': "Get the status of a task instance", <del> 'args': (ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.task_command.task_failed_deps'), <del> 'name': 'failed_deps', <del> 'help': ( <del> "Returns the unmet dependencies for a task instance from the perspective " <del> "of the scheduler. In other words, why a task instance doesn't get " <del> "scheduled and then queued by the scheduler, and then run by an " <del> "executor)"), <del> 'args': (ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.task_command.task_render'), <del> 'name': 'render', <del> 'help': "Render a task instance's template(s)", <del> 'args': (ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.task_command.task_run'), <del> 'name': 'run', <del> 'help': "Run a single task instance", <del> 'args': ( <del> ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR, <del> ARG_MARK_SUCCESS, ARG_FORCE, ARG_POOL, ARG_CFG_PATH, <del> ARG_LOCAL, ARG_RAW, ARG_IGNORE_ALL_DEPENDENCIES, ARG_IGNORE_DEPENDENCIES, <del> ARG_IGNORE_DEPENDS_ON_PAST, ARG_SHIP_DAG, ARG_PICKLE, ARG_JOB_ID, ARG_INTERACTIVE,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.task_command.task_test'), <del> 'name': 'test', <del> 'help': ( <del> "Test a task instance. This will run a task without checking for " <del> "dependencies or recording its state in the database"), <del> 'args': ( <add> ActionCommand( <add> name='list', <add> help="List the tasks within a DAG", <add> func=lazy_load_command('airflow.cli.commands.task_command.task_list'), <add> args=(ARG_DAG_ID, ARG_TREE, ARG_SUBDIR), <add> ), <add> ActionCommand( <add> name='clear', <add> help="Clear a set of task instance, as if they never ran", <add> func=lazy_load_command('airflow.cli.commands.task_command.task_clear'), <add> args=( <add> ARG_DAG_ID, ARG_TASK_REGEX, ARG_START_DATE, ARG_END_DATE, ARG_SUBDIR, ARG_UPSTREAM, <add> ARG_DOWNSTREAM, ARG_YES, ARG_ONLY_FAILED, ARG_ONLY_RUNNING, ARG_EXCLUDE_SUBDAGS, <add> ARG_EXCLUDE_PARENTDAG, ARG_DAG_REGEX <add> ), <add> ), <add> ActionCommand( <add> name='state', <add> help="Get the status of a task instance", <add> func=lazy_load_command('airflow.cli.commands.task_command.task_state'), <add> args=(ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <add> ), <add> ActionCommand( <add> name='failed_deps', <add> help=( <add> "Returns the unmet dependencies for a task instance from the perspective of the scheduler. " <add> "In other words, why a task instance doesn't get scheduled and then queued by the scheduler, " <add> "and then run by an executor." <add> ), <add> func=lazy_load_command('airflow.cli.commands.task_command.task_failed_deps'), <add> args=(ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <add> ), <add> ActionCommand( <add> name='render', <add> help="Render a task instance's template(s)", <add> func=lazy_load_command('airflow.cli.commands.task_command.task_render'), <add> args=(ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR), <add> ), <add> ActionCommand( <add> name='run', <add> help="Run a single task instance", <add> func=lazy_load_command('airflow.cli.commands.task_command.task_run'), <add> args=( <add> ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR, ARG_MARK_SUCCESS, ARG_FORCE, <add> ARG_POOL, ARG_CFG_PATH, ARG_LOCAL, ARG_RAW, ARG_IGNORE_ALL_DEPENDENCIES, <add> ARG_IGNORE_DEPENDENCIES, ARG_IGNORE_DEPENDS_ON_PAST, ARG_SHIP_DAG, ARG_PICKLE, ARG_JOB_ID, <add> ARG_INTERACTIVE, <add> ), <add> ), <add> ActionCommand( <add> name='test', <add> help=( <add> "Test a task instance. This will run a task without checking for dependencies or recording " <add> "its state in the database" <add> ), <add> func=lazy_load_command('airflow.cli.commands.task_command.task_test'), <add> args=( <ide> ARG_DAG_ID, ARG_TASK_ID, ARG_EXECUTION_DATE, ARG_SUBDIR, ARG_DRY_RUN, <del> ARG_TASK_PARAMS, ARG_POST_MORTEM, ARG_ENV_VARS), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.task_command.task_states_for_dag_run'), <del> 'name': 'states_for_dag_run', <del> 'help': "Get the status of all task instances in a dag run", <del> 'args': (ARG_DAG_ID, ARG_EXECUTION_DATE, ARG_OUTPUT), <del> }, <add> ARG_TASK_PARAMS, ARG_POST_MORTEM, ARG_ENV_VARS <add> ), <add> ), <add> ActionCommand( <add> name='states_for_dag_run', <add> help="Get the status of all task instances in a dag run", <add> func=lazy_load_command('airflow.cli.commands.task_command.task_states_for_dag_run'), <add> args=(ARG_DAG_ID, ARG_EXECUTION_DATE, ARG_OUTPUT), <add> ), <ide> ) <ide> POOLS_COMMANDS = ( <del> { <del> 'func': lazy_load_command('airflow.cli.commands.pool_command.pool_list'), <del> 'name': 'list', <del> 'help': 'List pools', <del> 'args': (ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.pool_command.pool_get'), <del> 'name': 'get', <del> 'help': 'Get pool size', <del> 'args': (ARG_POOL_NAME, ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.pool_command.pool_set'), <del> 'name': 'set', <del> 'help': 'Configure pool', <del> 'args': (ARG_POOL_NAME, ARG_POOL_SLOTS, ARG_POOL_DESCRIPTION, ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.pool_command.pool_delete'), <del> 'name': 'delete', <del> 'help': 'Delete pool', <del> 'args': (ARG_POOL_NAME, ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.pool_command.pool_import'), <del> 'name': 'import', <del> 'help': 'Import pools', <del> 'args': (ARG_POOL_IMPORT, ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.pool_command.pool_export'), <del> 'name': 'export', <del> 'help': 'Export all pools', <del> 'args': (ARG_POOL_EXPORT, ARG_OUTPUT,), <del> }, <add> ActionCommand( <add> name='list', <add> help='List pools', <add> func=lazy_load_command('airflow.cli.commands.pool_command.pool_list'), <add> args=(ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='get', <add> help='Get pool size', <add> func=lazy_load_command('airflow.cli.commands.pool_command.pool_get'), <add> args=(ARG_POOL_NAME, ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='set', <add> help='Configure pool', <add> func=lazy_load_command('airflow.cli.commands.pool_command.pool_set'), <add> args=(ARG_POOL_NAME, ARG_POOL_SLOTS, ARG_POOL_DESCRIPTION, ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='delete', <add> help='Delete pool', <add> func=lazy_load_command('airflow.cli.commands.pool_command.pool_delete'), <add> args=(ARG_POOL_NAME, ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='import', <add> help='Import pools', <add> func=lazy_load_command('airflow.cli.commands.pool_command.pool_import'), <add> args=(ARG_POOL_IMPORT, ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='export', <add> help='Export all pools', <add> func=lazy_load_command('airflow.cli.commands.pool_command.pool_export'), <add> args=(ARG_POOL_EXPORT, ARG_OUTPUT,), <add> ), <ide> ) <ide> VARIABLES_COMMANDS = ( <del> { <del> 'func': lazy_load_command('airflow.cli.commands.variable_command.variables_list'), <del> 'name': 'list', <del> 'help': 'List variables', <del> 'args': (), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.variable_command.variables_get'), <del> 'name': 'get', <del> 'help': 'Get variable', <del> 'args': (ARG_VAR, ARG_JSON, ARG_DEFAULT), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.variable_command.variables_set'), <del> 'name': 'set', <del> 'help': 'Set variable', <del> 'args': (ARG_VAR, ARG_VAR_VALUE, ARG_JSON), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.variable_command.variables_delete'), <del> 'name': 'delete', <del> 'help': 'Delete variable', <del> 'args': (ARG_VAR,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.variable_command.variables_import'), <del> 'name': 'import', <del> 'help': 'Import variables', <del> 'args': (ARG_VAR_IMPORT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.variable_command.variables_export'), <del> 'name': 'export', <del> 'help': 'Export all variables', <del> 'args': (ARG_VAR_EXPORT,), <del> }, <add> ActionCommand( <add> name='list', <add> help='List variables', <add> func=lazy_load_command('airflow.cli.commands.variable_command.variables_list'), <add> args=(), <add> ), <add> ActionCommand( <add> name='get', <add> help='Get variable', <add> func=lazy_load_command('airflow.cli.commands.variable_command.variables_get'), <add> args=(ARG_VAR, ARG_JSON, ARG_DEFAULT), <add> ), <add> ActionCommand( <add> name='set', <add> help='Set variable', <add> func=lazy_load_command('airflow.cli.commands.variable_command.variables_set'), <add> args=(ARG_VAR, ARG_VAR_VALUE, ARG_JSON), <add> ), <add> ActionCommand( <add> name='delete', <add> help='Delete variable', <add> func=lazy_load_command('airflow.cli.commands.variable_command.variables_delete'), <add> args=(ARG_VAR,), <add> ), <add> ActionCommand( <add> name='import', <add> help='Import variables', <add> func=lazy_load_command('airflow.cli.commands.variable_command.variables_import'), <add> args=(ARG_VAR_IMPORT,), <add> ), <add> ActionCommand( <add> name='export', <add> help='Export all variables', <add> func=lazy_load_command('airflow.cli.commands.variable_command.variables_export'), <add> args=(ARG_VAR_EXPORT,), <add> ), <ide> ) <ide> DB_COMMANDS = ( <del> { <del> 'func': lazy_load_command('airflow.cli.commands.db_command.initdb'), <del> 'name': 'init', <del> 'help': "Initialize the metadata database", <del> 'args': (), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.db_command.resetdb'), <del> 'name': 'reset', <del> 'help': "Burn down and rebuild the metadata database", <del> 'args': (ARG_YES,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.db_command.upgradedb'), <del> 'name': 'upgrade', <del> 'help': "Upgrade the metadata database to latest version", <del> 'args': (), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.db_command.shell'), <del> 'name': 'shell', <del> 'help': "Runs a shell to access the database", <del> 'args': (), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.db_command.check'), <del> 'name': 'check', <del> 'help': "Check if the database can be reached.", <del> 'args': (), <del> }, <add> ActionCommand( <add> name='init', <add> help="Initialize the metadata database", <add> func=lazy_load_command('airflow.cli.commands.db_command.initdb'), <add> args=(), <add> ), <add> ActionCommand( <add> name='reset', <add> help="Burn down and rebuild the metadata database", <add> func=lazy_load_command('airflow.cli.commands.db_command.resetdb'), <add> args=(ARG_YES,), <add> ), <add> ActionCommand( <add> name='upgrade', <add> help="Upgrade the metadata database to latest version", <add> func=lazy_load_command('airflow.cli.commands.db_command.upgradedb'), <add> args=(), <add> ), <add> ActionCommand( <add> name='shell', <add> help="Runs a shell to access the database", <add> func=lazy_load_command('airflow.cli.commands.db_command.shell'), <add> args=(), <add> ), <add> ActionCommand( <add> name='check', <add> help="Check if the database can be reached.", <add> func=lazy_load_command('airflow.cli.commands.db_command.check'), <add> args=(), <add> ), <ide> ) <ide> CONNECTIONS_COMMANDS = ( <del> { <del> 'func': lazy_load_command('airflow.cli.commands.connection_command.connections_list'), <del> 'name': 'list', <del> 'help': 'List connections', <del> 'args': (ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.connection_command.connections_add'), <del> 'name': 'add', <del> 'help': 'Add a connection', <del> 'args': (ARG_CONN_ID, ARG_CONN_URI, ARG_CONN_EXTRA) + tuple(ALTERNATIVE_CONN_SPECS_ARGS), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.connection_command.connections_delete'), <del> 'name': 'delete', <del> 'help': 'Delete a connection', <del> 'args': (ARG_CONN_ID,), <del> }, <add> ActionCommand( <add> name='list', <add> help='List connections', <add> func=lazy_load_command('airflow.cli.commands.connection_command.connections_list'), <add> args=(ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='add', <add> help='Add a connection', <add> func=lazy_load_command('airflow.cli.commands.connection_command.connections_add'), <add> args=(ARG_CONN_ID, ARG_CONN_URI, ARG_CONN_EXTRA) + tuple(ALTERNATIVE_CONN_SPECS_ARGS), <add> ), <add> ActionCommand( <add> name='delete', <add> help='Delete a connection', <add> func=lazy_load_command('airflow.cli.commands.connection_command.connections_delete'), <add> args=(ARG_CONN_ID,), <add> ), <ide> ) <ide> USERS_COMMANDS = ( <del> { <del> 'func': lazy_load_command('airflow.cli.commands.user_command.users_list'), <del> 'name': 'list', <del> 'help': 'List users', <del> 'args': (ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.user_command.users_create'), <del> 'name': 'create', <del> 'help': 'Create a user', <del> 'args': (ARG_ROLE, ARG_USERNAME, ARG_EMAIL, ARG_FIRSTNAME, ARG_LASTNAME, ARG_PASSWORD, <del> ARG_USE_RANDOM_PASSWORD) <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.user_command.users_delete'), <del> 'name': 'delete', <del> 'help': 'Delete a user', <del> 'args': (ARG_USERNAME,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.user_command.add_role'), <del> 'name': 'add_role', <del> 'help': 'Add role to a user', <del> 'args': (ARG_USERNAME_OPTIONAL, ARG_EMAIL_OPTIONAL, ARG_ROLE), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.user_command.remove_role'), <del> 'name': 'remove_role', <del> 'help': 'Remove role from a user', <del> 'args': (ARG_USERNAME_OPTIONAL, ARG_EMAIL_OPTIONAL, ARG_ROLE), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.user_command.users_import'), <del> 'name': 'import', <del> 'help': 'Import users', <del> 'args': (ARG_USER_IMPORT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.user_command.users_export'), <del> 'name': 'export', <del> 'help': 'Export all users', <del> 'args': (ARG_USER_EXPORT,), <del> }, <add> ActionCommand( <add> name='list', <add> help='List users', <add> func=lazy_load_command('airflow.cli.commands.user_command.users_list'), <add> args=(ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='create', <add> help='Create a user', <add> func=lazy_load_command('airflow.cli.commands.user_command.users_create'), <add> args=( <add> ARG_ROLE, ARG_USERNAME, ARG_EMAIL, ARG_FIRSTNAME, ARG_LASTNAME, ARG_PASSWORD, <add> ARG_USE_RANDOM_PASSWORD <add> ) <add> ), <add> ActionCommand( <add> name='delete', <add> help='Delete a user', <add> func=lazy_load_command('airflow.cli.commands.user_command.users_delete'), <add> args=(ARG_USERNAME,), <add> ), <add> ActionCommand( <add> name='add_role', <add> help='Add role to a user', <add> func=lazy_load_command('airflow.cli.commands.user_command.add_role'), <add> args=(ARG_USERNAME_OPTIONAL, ARG_EMAIL_OPTIONAL, ARG_ROLE), <add> ), <add> ActionCommand( <add> name='remove_role', <add> help='Remove role from a user', <add> func=lazy_load_command('airflow.cli.commands.user_command.remove_role'), <add> args=(ARG_USERNAME_OPTIONAL, ARG_EMAIL_OPTIONAL, ARG_ROLE), <add> ), <add> ActionCommand( <add> name='import', <add> help='Import users', <add> func=lazy_load_command('airflow.cli.commands.user_command.users_import'), <add> args=(ARG_USER_IMPORT,), <add> ), <add> ActionCommand( <add> name='export', <add> help='Export all users', <add> func=lazy_load_command('airflow.cli.commands.user_command.users_export'), <add> args=(ARG_USER_EXPORT,), <add> ), <ide> ) <ide> ROLES_COMMANDS = ( <del> { <del> 'func': lazy_load_command('airflow.cli.commands.role_command.roles_list'), <del> 'name': 'list', <del> 'help': 'List roles', <del> 'args': (ARG_OUTPUT,), <del> }, <del> { <del> 'func': lazy_load_command('airflow.cli.commands.role_command.roles_create'), <del> 'name': 'create', <del> 'help': 'Create role', <del> 'args': (ARG_ROLES,), <del> }, <add> ActionCommand( <add> name='list', <add> help='List roles', <add> func=lazy_load_command('airflow.cli.commands.role_command.roles_list'), <add> args=(ARG_OUTPUT,), <add> ), <add> ActionCommand( <add> name='create', <add> help='Create role', <add> func=lazy_load_command('airflow.cli.commands.role_command.roles_create'), <add> args=(ARG_ROLES,), <add> ), <ide> ) <del> subparsers = [ <del> { <del> 'help': 'List and manage DAGs', <del> 'name': 'dags', <del> 'subcommands': DAGS_SUBCOMMANDS, <del> }, <del> { <del> 'help': 'List and manage tasks', <del> 'name': 'tasks', <del> 'subcommands': TASKS_COMMANDS, <del> }, <del> { <del> 'help': "CRUD operations on pools", <del> 'name': 'pools', <del> 'subcommands': POOLS_COMMANDS, <del> }, <del> { <del> 'help': "CRUD operations on variables", <del> 'name': 'variables', <del> 'subcommands': VARIABLES_COMMANDS, <del> }, <del> { <del> 'help': "Database operations", <del> 'name': 'db', <del> 'subcommands': DB_COMMANDS, <del> }, <del> { <del> 'name': 'kerberos', <del> 'func': lazy_load_command('airflow.cli.commands.kerberos_command.kerberos'), <del> 'help': "Start a kerberos ticket renewer", <del> 'args': (ARG_PRINCIPAL, ARG_KEYTAB, ARG_PID, ARG_DAEMON, ARG_STDOUT, ARG_STDERR, ARG_LOG_FILE), <del> }, <del> { <del> 'name': 'webserver', <del> 'func': lazy_load_command('airflow.cli.commands.webserver_command.webserver'), <del> 'help': "Start a Airflow webserver instance", <del> 'args': (ARG_PORT, ARG_WORKERS, ARG_WORKERCLASS, ARG_WORKER_TIMEOUT, ARG_HOSTNAME, <del> ARG_PID, ARG_DAEMON, ARG_STDOUT, ARG_STDERR, ARG_ACCESS_LOGFILE, <del> ARG_ERROR_LOGFILE, ARG_LOG_FILE, ARG_SSL_CERT, ARG_SSL_KEY, ARG_DEBUG), <del> }, <del> { <del> 'name': 'scheduler', <del> 'func': lazy_load_command('airflow.cli.commands.scheduler_command.scheduler'), <del> 'help': "Start a scheduler instance", <del> 'args': (ARG_DAG_ID_OPT, ARG_SUBDIR, ARG_NUM_RUNS, <del> ARG_DO_PICKLE, ARG_PID, ARG_DAEMON, ARG_STDOUT, ARG_STDERR, <del> ARG_LOG_FILE), <del> }, <del> { <del> 'name': 'version', <del> 'func': lazy_load_command('airflow.cli.commands.version_command.version'), <del> 'help': "Show the version", <del> 'args': (), <del> }, <del> { <del> 'help': "List/Add/Delete connections", <del> 'name': 'connections', <del> 'subcommands': CONNECTIONS_COMMANDS, <del> }, <del> { <del> 'help': "CRUD operations on users", <del> 'name': 'users', <del> 'subcommands': USERS_COMMANDS, <del> }, <del> { <del> 'help': 'Create/List roles', <del> 'name': 'roles', <del> 'subcommands': ROLES_COMMANDS, <del> }, <del> { <del> 'name': 'sync_perm', <del> 'func': lazy_load_command('airflow.cli.commands.sync_perm_command.sync_perm'), <del> 'help': "Update permissions for existing roles and DAGs", <del> 'args': (), <del> }, <del> { <del> 'name': 'rotate_fernet_key', <del> 'func': lazy_load_command('airflow.cli.commands.rotate_fernet_key_command.rotate_fernet_key'), <del> 'help': 'Rotate all encrypted connection credentials and variables; see ' <del> 'https://airflow.readthedocs.io/en/stable/howto/secure-connections.html' <del> '#rotating-encryption-keys', <del> 'args': (), <del> }, <del> { <del> 'name': 'config', <del> 'func': lazy_load_command('airflow.cli.commands.config_command.show_config'), <del> 'help': 'Show current application configuration', <del> 'args': (), <del> }, <add> subparsers: List[CLICommand] = [ <add> GroupCommand( <add> name='dags', <add> help='List and manage DAGs', <add> subcommands=DAGS_SUBCOMMANDS, <add> ), <add> GroupCommand( <add> name='tasks', <add> help='List and manage tasks', <add> subcommands=TASKS_COMMANDS, <add> ), <add> GroupCommand( <add> name='pools', <add> help="CRUD operations on pools", <add> subcommands=POOLS_COMMANDS, <add> ), <add> GroupCommand( <add> name='variables', <add> help="CRUD operations on variables", <add> subcommands=VARIABLES_COMMANDS, <add> ), <add> GroupCommand( <add> name='db', <add> help="Database operations", <add> subcommands=DB_COMMANDS, <add> ), <add> ActionCommand( <add> name='kerberos', <add> help="Start a kerberos ticket renewer", <add> func=lazy_load_command('airflow.cli.commands.kerberos_command.kerberos'), <add> args=(ARG_PRINCIPAL, ARG_KEYTAB, ARG_PID, ARG_DAEMON, ARG_STDOUT, ARG_STDERR, ARG_LOG_FILE), <add> ), <add> ActionCommand( <add> name='webserver', <add> help="Start a Airflow webserver instance", <add> func=lazy_load_command('airflow.cli.commands.webserver_command.webserver'), <add> args=( <add> ARG_PORT, ARG_WORKERS, ARG_WORKERCLASS, ARG_WORKER_TIMEOUT, ARG_HOSTNAME, ARG_PID, <add> ARG_DAEMON, ARG_STDOUT, ARG_STDERR, ARG_ACCESS_LOGFILE, ARG_ERROR_LOGFILE, ARG_LOG_FILE, <add> ARG_SSL_CERT, ARG_SSL_KEY, ARG_DEBUG <add> ), <add> ), <add> ActionCommand( <add> name='scheduler', <add> help="Start a scheduler instance", <add> func=lazy_load_command('airflow.cli.commands.scheduler_command.scheduler'), <add> args=( <add> ARG_DAG_ID_OPT, ARG_SUBDIR, ARG_NUM_RUNS, ARG_DO_PICKLE, ARG_PID, ARG_DAEMON, ARG_STDOUT, <add> ARG_STDERR, ARG_LOG_FILE <add> ), <add> ), <add> ActionCommand( <add> name='version', <add> help="Show the version", <add> func=lazy_load_command('airflow.cli.commands.version_command.version'), <add> args=(), <add> ), <add> GroupCommand( <add> name='connections', <add> help="List/Add/Delete connections", <add> subcommands=CONNECTIONS_COMMANDS, <add> ), <add> GroupCommand( <add> name='users', <add> help="CRUD operations on users", <add> subcommands=USERS_COMMANDS, <add> ), <add> GroupCommand( <add> name='roles', <add> help='Create/List roles', <add> subcommands=ROLES_COMMANDS, <add> ), <add> ActionCommand( <add> name='sync_perm', <add> help="Update permissions for existing roles and DAGs", <add> func=lazy_load_command('airflow.cli.commands.sync_perm_command.sync_perm'), <add> args=(), <add> ), <add> ActionCommand( <add> name='rotate_fernet_key', <add> func=lazy_load_command('airflow.cli.commands.rotate_fernet_key_command.rotate_fernet_key'), <add> help=( <add> 'Rotate all encrypted connection credentials and variables; see ' <add> 'https://airflow.readthedocs.io/en/stable/howto/secure-connections.html' <add> '#rotating-encryption-keys' <add> ), <add> args=(), <add> ), <add> ActionCommand( <add> name='config', <add> help='Show current application configuration', <add> func=lazy_load_command('airflow.cli.commands.config_command.show_config'), <add> args=(), <add> ), <ide> ] <ide> if conf.get("core", "EXECUTOR") == ExecutorLoader.CELERY_EXECUTOR or BUILD_DOCS: <del> subparsers.append({ <del> "help": "Start celery components", <del> "name": "celery", <del> "subcommands": ( <del> { <del> 'name': 'worker', <del> 'func': lazy_load_command('airflow.cli.commands.celery_command.worker'), <del> 'help': "Start a Celery worker node", <del> 'args': ( <add> subparsers.append(GroupCommand( <add> name="celery", <add> help="Start celery components", <add> subcommands=( <add> ActionCommand( <add> name='worker', <add> help="Start a Celery worker node", <add> func=lazy_load_command('airflow.cli.commands.celery_command.worker'), <add> args=( <ide> ARG_DO_PICKLE, ARG_QUEUES, ARG_CONCURRENCY, ARG_CELERY_HOSTNAME, ARG_PID, ARG_DAEMON, <ide> ARG_STDOUT, ARG_STDERR, ARG_LOG_FILE, ARG_AUTOSCALE, ARG_SKIP_SERVE_LOGS <ide> ), <del> }, { <del> 'name': 'flower', <del> 'func': lazy_load_command('airflow.cli.commands.celery_command.flower'), <del> 'help': "Start a Celery Flower", <del> 'args': ( <add> ), <add> ActionCommand( <add> name='flower', <add> help="Start a Celery Flower", <add> func=lazy_load_command('airflow.cli.commands.celery_command.flower'), <add> args=( <ide> ARG_FLOWER_HOSTNAME, ARG_FLOWER_PORT, ARG_FLOWER_CONF, ARG_FLOWER_URL_PREFIX, <ide> ARG_FLOWER_BASIC_AUTH, ARG_BROKER_API, ARG_PID, ARG_DAEMON, ARG_STDOUT, ARG_STDERR, <ide> ARG_LOG_FILE <ide> ), <del> }, <del> { <del> 'name': 'stop', <del> 'func': lazy_load_command('airflow.cli.commands.celery_command.stop_worker'), <del> 'help': "Stop the Celery worker gracefully", <del> 'args': (), <del> } <add> ), <add> ActionCommand( <add> name='stop', <add> help="Stop the Celery worker gracefully", <add> func=lazy_load_command('airflow.cli.commands.celery_command.stop_worker'), <add> args=(), <add> ) <ide> ) <del> }) <del> subparsers_dict = {sp.get('name') or sp['func'].__name__: sp for sp in subparsers} # type: ignore <del> dag_subparsers = ( <del> 'list_tasks', 'backfill', 'test', 'run', 'pause', 'unpause', 'list_dag_runs') <add> )) <add> subparsers_dict: Dict[str, CLICommand] = {sp.name: sp for sp in subparsers} <add> dag_subparsers: Set[str] = { <add> 'list_tasks', 'backfill', 'test', 'run', 'pause', 'unpause', 'list_dag_runs' <add> } <ide> <ide> @classmethod <del> def get_parser(cls, dag_parser=False): <add> def get_parser(cls, dag_parser: bool = False) -> argparse.ArgumentParser: <ide> """Creates and returns command line argument parser""" <ide> class DefaultHelpParser(argparse.ArgumentParser): <ide> """Override argparse.ArgumentParser.error and use print_help instead of print_usage""" <ide> def error(self, message): <ide> subparsers.required = True <ide> <ide> subparser_list = cls.dag_subparsers if dag_parser else cls.subparsers_dict.keys() <del> for sub in sorted(subparser_list): <del> sub = cls.subparsers_dict[sub] <add> sub_name: str <add> for sub_name in sorted(subparser_list): <add> sub: CLICommand = cls.subparsers_dict[sub_name] <ide> cls._add_command(subparsers, sub) <ide> return parser <ide> <ide> @classmethod <del> def sort_args(cls, args: Arg): <add> def sort_args(cls, args: Iterable[Arg]) -> Iterable[Arg]: <ide> """ <ide> Sort subcommand optional args, keep positional args <ide> """ <del> def partition(pred, iterable): <del> """ <del> Use a predicate to partition entries into false entries and true entries <del> """ <del> iter_1, iter_2 = tee(iterable) <del> return filterfalse(pred, iter_1), filter(pred, iter_2) <del> <del> def get_long_option(arg): <add> def get_long_option(arg: Arg): <ide> """ <ide> Get long option from Arg.flags <ide> """ <ide> def get_long_option(arg): <ide> yield from sorted(optional, key=lambda x: get_long_option(x).lower()) <ide> <ide> @classmethod <del> def _add_command(cls, subparsers, sub): <add> def _add_command( <add> cls, <add> subparsers: argparse._SubParsersAction, # pylint: disable=protected-access <add> sub: CLICommand <add> ) -> None: <ide> sub_proc = subparsers.add_parser( <del> sub['name'], help=sub['help'] <add> sub.name, help=sub.help <ide> ) <ide> sub_proc.formatter_class = RawTextHelpFormatter <ide> <del> if 'subcommands' in sub: <add> if isinstance(sub, GroupCommand): <ide> cls._add_group_command(sub, sub_proc) <del> elif 'func' in sub: <add> elif isinstance(sub, ActionCommand): <ide> cls._add_action_command(sub, sub_proc) <ide> else: <ide> raise AirflowException("Invalid command definition.") <ide> <ide> @classmethod <del> def _add_action_command(cls, sub, sub_proc): <del> for arg in cls.sort_args(sub['args']): <add> def _add_action_command(cls, sub: ActionCommand, sub_proc: argparse.ArgumentParser) -> None: <add> for arg in cls.sort_args(sub.args): <ide> kwargs = { <ide> k: v for k, v in vars(arg).items() if k != 'flags' and v <ide> } <ide> sub_proc.add_argument(*arg.flags, **kwargs) <del> sub_proc.set_defaults(func=sub['func']) <add> sub_proc.set_defaults(func=sub.func) <ide> <ide> @classmethod <del> def _add_group_command(cls, sub, sub_proc): <del> subcommands = sub.get('subcommands', []) <add> def _add_group_command(cls, sub: GroupCommand, sub_proc: argparse.ArgumentParser) -> None: <add> subcommands = sub.subcommands <ide> sub_subparsers = sub_proc.add_subparsers(dest="subcommand") <ide> sub_subparsers.required = True <ide> <del> for command in sorted(subcommands, key=lambda x: x['name']): <add> for command in sorted(subcommands, key=lambda x: x.name): <ide> cls._add_command(sub_subparsers, command) <ide> <ide> <del>def get_parser(): <add>def get_parser() -> argparse.ArgumentParser: <ide> """Calls static method inside factory which creates argument parser""" <ide> return CLIFactory.get_parser() <ide><path>airflow/utils/helpers.py <ide> import re <ide> from datetime import datetime <ide> from functools import reduce <del>from typing import Any, Dict, Optional <add>from itertools import filterfalse, tee <add>from typing import Any, Callable, Dict, Iterable, Optional <ide> <ide> from jinja2 import Template <ide> <ide> def merge_dicts(dict1, dict2): <ide> else: <ide> merged[k] = v <ide> return merged <add> <add> <add>def partition(pred: Callable, iterable: Iterable): <add> """ <add> Use a predicate to partition entries into false entries and true entries <add> """ <add> iter_1, iter_2 = tee(iterable) <add> return filterfalse(pred, iter_1), filter(pred, iter_2) <ide><path>tests/bin/test_cli.py <ide> def test_subcommand_conflict(self): <ide> if var.isupper() and "COMMANDS" in var <ide> } <ide> for group_name, sub in subcommand.items(): <del> name = [command['name'].lower() for command in sub] <add> name = [command.name.lower() for command in sub] <ide> self.assertEqual(len(name), len(set(name)), <ide> f"Command group {group_name} have conflict subcommand") <ide> <ide> def test_subcommand_arg_name_conflict(self): <ide> } <ide> for group, command in subcommand.items(): <ide> for com in command: <del> name = com['name'] <del> args = com['args'] <del> conflict_arg = [arg for arg, count in Counter(args).items() if count > 1] <add> conflict_arg = [arg for arg, count in Counter(com.args).items() if count > 1] <ide> self.assertListEqual([], conflict_arg, <del> f"Command group {group} function {name} have " <add> f"Command group {group} function {com.name} have " <ide> f"conflict args name {conflict_arg}") <ide> <ide> def test_subcommand_arg_flag_conflict(self): <ide> def cli_args_flags(arg): <ide> } <ide> for group, command in subcommand.items(): <ide> for com in command: <del> name = com['name'] <ide> position = [ <ide> cli_args_flags(a)[0] <del> for a in com['args'] <add> for a in com.args <ide> if (len(cli_args_flags(a)) == 1 <ide> and not cli_args_flags(a)[0].startswith("-")) <ide> ] <ide> conflict_position = [arg for arg, count in Counter(position).items() if count > 1] <ide> self.assertListEqual([], conflict_position, <del> f"Command group {group} function {name} have conflict " <add> f"Command group {group} function {com.name} have conflict " <ide> f"position flags {conflict_position}") <ide> <ide> long_option = [cli_args_flags(a)[0] <del> for a in com['args'] <add> for a in com.args <ide> if (len(cli_args_flags(a)) == 1 <ide> and cli_args_flags(a)[0].startswith("-"))] + \ <ide> [cli_args_flags(a)[1] <del> for a in com['args'] if len(cli_args_flags(a)) == 2] <add> for a in com.args if len(cli_args_flags(a)) == 2] <ide> conflict_long_option = [arg for arg, count in Counter(long_option).items() if count > 1] <ide> self.assertListEqual([], conflict_long_option, <del> f"Command group {group} function {name} have conflict " <add> f"Command group {group} function {com.name} have conflict " <ide> f"long option flags {conflict_long_option}") <ide> <ide> short_option = [ <ide> cli_args_flags(a)[0] <del> for a in com['args'] if len(cli_args_flags(a)) == 2 <add> for a in com.args if len(cli_args_flags(a)) == 2 <ide> ] <ide> conflict_short_option = [arg for arg, count in Counter(short_option).items() if count > 1] <ide> self.assertEqual([], conflict_short_option, <del> f"Command group {group} function {name} have conflict " <add> f"Command group {group} function {com.name} have conflict " <ide> f"short option flags {conflict_short_option}")
3
Ruby
Ruby
remove unneeded option from resourceroutegenerator
b6c270fb62a3ee7c89200084df7666347b787717
<ide><path>railties/lib/rails/generators/rails/resource_route/resource_route_generator.rb <ide> module Rails <ide> module Generators <ide> class ResourceRouteGenerator < NamedBase # :nodoc: <del> class_option :api, type: :boolean, <del> desc: "Preconfigure smaller stack for API only apps" <del> <ide> # Properly nests namespaces passed into a generator <ide> # <ide> # $ rails generate resource admin/users/products
1
Python
Python
add missing import
cace39af972a595064250a22a6a6feebc89113be
<ide><path>src/transformers/__init__.py <ide> TF_MODEL_FOR_CAUSAL_LM_MAPPING, <ide> TF_MODEL_FOR_MASKED_LM_MAPPING, <ide> TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING, <add> TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING, <ide> TF_MODEL_FOR_PRETRAINING_MAPPING, <ide> TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING, <ide> TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING, <ide><path>src/transformers/utils/dummy_tf_objects.py <ide> def from_pretrained(self, *args, **kwargs): <ide> TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING = None <ide> <ide> <add>TF_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = None <add> <add> <ide> TF_MODEL_FOR_PRETRAINING_MAPPING = None <ide> <ide>
2
Python
Python
add system and uptime to the export module
71ffcef3d0127da4655e1580e5001203b5ce28f7
<ide><path>glances/exports/glances_export.py <ide> def plugins_to_export(self): <ide> 'fs', <ide> 'processcount', <ide> 'ip', <del> 'system'] <add> 'system', <add> 'uptime'] <ide> <ide> def update(self, stats): <ide> """Update stats to a server.
1
Javascript
Javascript
remove the api-caching of annotation-data
9b6d0d994dbe3df5b29b96026958c84f4bc54592
<ide><path>src/display/api.js <ide> class PDFPageProxy { <ide> this.cleanupAfterRender = false; <ide> this.pendingCleanup = false; <ide> this._intentStates = new Map(); <del> this._annotationPromises = new Map(); <ide> this.destroyed = false; <ide> } <ide> <ide> class PDFPageProxy { <ide> getAnnotations({ intent = "display" } = {}) { <ide> const intentArgs = this._transport.getRenderingIntent(intent); <ide> <del> let promise = this._annotationPromises.get(intentArgs.cacheKey); <del> if (!promise) { <del> promise = this._transport.getAnnotations( <del> this._pageIndex, <del> intentArgs.renderingIntent <del> ); <del> this._annotationPromises.set(intentArgs.cacheKey, promise); <del> } <del> return promise; <add> return this._transport.getAnnotations( <add> this._pageIndex, <add> intentArgs.renderingIntent <add> ); <ide> } <ide> <ide> /** <ide> class PDFPageProxy { <ide> bitmap.close(); <ide> } <ide> this._bitmaps.clear(); <del> this._annotationPromises.clear(); <ide> this._jsActionsPromise = null; <ide> this.pendingCleanup = false; <ide> return Promise.all(waitOn); <ide> class PDFPageProxy { <ide> <ide> this._intentStates.clear(); <ide> this.objs.clear(); <del> this._annotationPromises.clear(); <ide> this._jsActionsPromise = null; <ide> if (resetStats && this._stats) { <ide> this._stats = new StatTimer();
1
PHP
PHP
fix signature error
d2dc7e4313be40a7becec0ed8be89931b1435ac5
<ide><path>src/Http/Session/CacheSession.php <ide> public function read($id) <ide> * Helper function called on write for cache sessions. <ide> * <ide> * @param string $id ID that uniquely identifies session in cache. <del> * @param mixed $data The data to be saved. <add> * @param string $data The data to be saved. <ide> * @return bool True for successful write, false otherwise. <ide> */ <ide> public function write($id, $data) <ide><path>src/Http/Session/DatabaseSession.php <ide> public function read($id) <ide> * Helper function called on write for database sessions. <ide> * <ide> * @param string $id ID that uniquely identifies session in database. <del> * @param mixed $data The data to be saved. <add> * @param string $data The data to be saved. <ide> * @return bool True for successful write, false otherwise. <ide> */ <ide> public function write($id, $data)
2
Python
Python
claim python 3.6 support
4b9729fc109b72a67e713433ce82c15134d47e65
<ide><path>setup.py <ide> def run(self): <ide> 'Programming Language :: Python :: 3.3', <ide> 'Programming Language :: Python :: 3.4', <ide> 'Programming Language :: Python :: 3.5', <add> 'Programming Language :: Python :: 3.6', <ide> 'Topic :: System :: Monitoring' <ide> ] <ide> )
1
Ruby
Ruby
swap upcase and to_sym
fb9a39f4fa9a3836eca6e33703691ede17737411
<ide><path>actionpack/lib/action_controller/metal/mime_responds.rb <ide> def initialize(mimes, variant = nil) <ide> @responses = {} <ide> @variant = variant <ide> <del> mimes.each { |mime| @responses[Mime::Type[mime.to_sym.upcase]] = nil } <add> mimes.each { |mime| @responses[Mime::Type[mime.upcase.to_sym]] = nil } <ide> end <ide> <ide> def any(*args, &block)
1
Text
Text
add react 17 changelog
46ed2684718d160b06cf6e4f5f5ecf70c7b8974c
<ide><path>CHANGELOG.md <add>## 17.0.0 (October 20, 2020) <add> <add>### React <add> <add>* Add `react/jsx-runtime` and `react/jsx-dev-runtime` for the [new JSX transform](https://babeljs.io/blog/2020/03/16/7.9.0#a-new-jsx-transform-11154-https-githubcom-babel-babel-pull-11154). ([@lunaruan](https://github.com/lunaruan) in [#18299](https://github.com/facebook/react/pull/18299)) <add>* Build component stacks from native error frames. ([@sebmarkbage](https://github.com/sebmarkbage) in [#18561](https://github.com/facebook/react/pull/18561)) <add>* Allow to specify `displayName` on context for improved stacks. ([@eps1lon](https://github.com/eps1lon) in [#18224](https://github.com/facebook/react/pull/18224)) <add>* Prevent `'use strict'` from leaking in the UMD bundles. ([@koba04](https://github.com/koba04) in [#19614](https://github.com/facebook/react/pull/19614)) <add>* Stop using `fb.me` for redirects. ([@cylim](https://github.com/cylim) in [#19598](https://github.com/facebook/react/pull/19598)) <add> <add>### React DOM <add> <add>* Delegate events to roots instead of `document`. ([@trueadm](https://github.com/trueadm) in [#18195](https://github.com/facebook/react/pull/18195) and [others](https://github.com/facebook/react/pulls?q=is%3Apr+author%3Atrueadm+modern+event+is%3Amerged)) <add>* Clean up all effects before running any next effects. ([@bvaughn](https://github.com/bvaughn) in [#17947](https://github.com/facebook/react/pull/17947)) <add>* Run `useEffect` cleanup functions asynchronously. ([@bvaughn](https://github.com/bvaughn) in [#17925](https://github.com/facebook/react/pull/17925)) <add>* Use browser `focusin` and `focusout` for `onFocus` and `onBlur`. ([@trueadm](https://github.com/trueadm) in [#19186](https://github.com/facebook/react/pull/19186)) <add>* Make all `Capture` events use the browser capture phase. ([@trueadm](https://github.com/trueadm) in [#19221](https://github.com/facebook/react/pull/19221)) <add>* Don't emulate bubbling of the `onScroll` event. ([@gaearon](https://github.com/gaearon) in [#19464](https://github.com/facebook/react/pull/19464)) <add>* Throw if `forwardRef` or `memo` component returns `undefined`. ([@gaearon](https://github.com/gaearon) in [#19550](https://github.com/facebook/react/pull/19550)) <add>* Remove event pooling. ([@trueadm](https://github.com/trueadm) in [#18969](https://github.com/facebook/react/pull/18969)) <add>* Stop exposing internals that won’t be needed by React Native Web. ([@necolas](https://github.com/necolas) in [#18483](https://github.com/facebook/react/pull/18483)) <add>* Attach all known event listeners when the root mounts. ([@gaearon](https://github.com/gaearon) in [#19659](https://github.com/facebook/react/pull/19659)) <add>* Disable `console` in the second render pass of DEV mode double render. ([@sebmarkbage](https://github.com/sebmarkbage) in [#18547](https://github.com/facebook/react/pull/18547)) <add>* Deprecate the undocumented and misleading `ReactTestUtils.SimulateNative` API. ([@gaearon](https://github.com/gaearon) in [#13407](https://github.com/facebook/react/pull/13407)) <add>* Rename private field names used in the internals. ([@gaearon](https://github.com/gaearon) in [#18377](https://github.com/facebook/react/pull/18377)) <add>* Don't call User Timing API in development. ([@gaearon](https://github.com/gaearon) in [#18417](https://github.com/facebook/react/pull/18417)) <add>* Disable console during the repeated render in Strict Mode. ([@sebmarkbage](https://github.com/sebmarkbage) in [#18547](https://github.com/facebook/react/pull/18547)) <add>* In Strict Mode, double-render components without Hooks too. ([@eps1lon](https://github.com/eps1lon) in [#18430](https://github.com/facebook/react/pull/18430)) <add>* Allow calling `ReactDOM.flushSync` during lifecycle methods (but warn). ([@sebmarkbage](https://github.com/sebmarkbage) in [#18759](https://github.com/facebook/react/pull/18759)) <add>* Add the `code` property to the keyboard event objects. ([@bl00mber](https://github.com/bl00mber) in [#18287](https://github.com/facebook/react/pull/18287)) <add>* Add the `disableRemotePlayback` property for `video` elements. ([@tombrowndev](https://github.com/tombrowndev) in [#18619](https://github.com/facebook/react/pull/18619)) <add>* Add the `enterKeyHint` property for `input` elements. ([@eps1lon](https://github.com/eps1lon) in [#18634](https://github.com/facebook/react/pull/18634)) <add>* Warn when no `value` is provided to `<Context.Provider>`. ([@charlie1404](https://github.com/charlie1404) in [#19054](https://github.com/facebook/react/pull/19054)) <add>* Warn when `memo` or `forwardRef` components return `undefined`. ([@bvaughn](https://github.com/bvaughn) in [#19550](https://github.com/facebook/react/pull/19550)) <add>* Improve the error message for invalid updates. ([@JoviDeCroock](https://github.com/JoviDeCroock) in [#18316](https://github.com/facebook/react/pull/18316)) <add>* Exclude forwardRef and memo from stack frames. ([@sebmarkbage](https://github.com/sebmarkbage) in [#18559](https://github.com/facebook/react/pull/18559)) <add>* Improve the error message when switching between controlled and uncontrolled inputs. ([@vcarl](https://github.com/vcarl) in [#17070](https://github.com/facebook/react/pull/17070)) <add>* Keep `onTouchStart`, `onTouchMove`, and `onWheel` passive. ([@gaearon](https://github.com/gaearon) in [#19654](https://github.com/facebook/react/pull/19654)) <add>* Fix `setState` hanging in development inside a closed iframe. ([@gaearon](https://github.com/gaearon) in [#19220](https://github.com/facebook/react/pull/19220)) <add>* Fix rendering bailout for lazy components with `defaultProps`. ([@jddxf](https://github.com/jddxf) in [#18539](https://github.com/facebook/react/pull/18539)) <add>* Fix a false positive warning when `dangerouslySetInnerHTML` is `undefined`. ([@eps1lon](https://github.com/eps1lon) in [#18676](https://github.com/facebook/react/pull/18676)) <add>* Fix Test Utils with non-standard `require` implementation. ([@just-boris](https://github.com/just-boris) in [#18632](https://github.com/facebook/react/pull/18632)) <add>* Fix `onBeforeInput` reporting an incorrect `event.type`. ([@eps1lon](https://github.com/eps1lon) in [#19561](https://github.com/facebook/react/pull/19561)) <add>* Fix `event.relatedTarget` reported as `undefined` in Firefox. ([@claytercek](https://github.com/claytercek) in [#19607](https://github.com/facebook/react/pull/19607)) <add>* Fix "unspecified error" in IE11. ([@hemakshis](https://github.com/hemakshis) in [#19664](https://github.com/facebook/react/pull/19664)) <add>* Fix rendering into a shadow root. ([@Jack-Works](https://github.com/Jack-Works) in [#15894](https://github.com/facebook/react/pull/15894)) <add>* Fix `movementX/Y` polyfill with capture events. ([@gaearon](https://github.com/gaearon) in [#19672](https://github.com/facebook/react/pull/19672)) <add>* Use delegation for `onSubmit` and `onReset` events. ([@gaearon](https://github.com/gaearon) in [#19333](https://github.com/facebook/react/pull/19333)) <add>* Improve memory usage. ([@trueadm](https://github.com/trueadm) in [#18970](https://github.com/facebook/react/pull/18970)) <add> <add>### React DOM Server <add> <add>* Make `useCallback` behavior consistent with `useMemo` for the server renderer. ([@alexmckenley](https://github.com/alexmckenley) in [#18783](https://github.com/facebook/react/pull/18783)) <add>* Fix state leaking when a function component throws. ([@pmaccart](https://github.com/pmaccart) in [#19212](https://github.com/facebook/react/pull/19212)) <add> <add>### React Test Renderer <add> <add>* Improve `findByType` error message. ([@henryqdineen](https://github.com/henryqdineen) in [#17439](https://github.com/facebook/react/pull/17439)) <add> <add>### Concurrent Mode (Experimental) <add> <add>* Revamp the priority batching heuristics. ([@acdlite](https://github.com/acdlite) in [#18796](https://github.com/facebook/react/pull/18796)) <add>* Add the `unstable_` prefix before the experimental APIs. ([@acdlite](https://github.com/acdlite) in [#18825](https://github.com/facebook/react/pull/18825)) <add>* Remove `unstable_discreteUpdates` and `unstable_flushDiscreteUpdates`. ([@trueadm](https://github.com/trueadm) in [#18825](https://github.com/facebook/react/pull/18825)) <add>* Remove the `timeoutMs` argument. ([@acdlite](https://github.com/acdlite) in [#19703](https://github.com/facebook/react/pull/19703)) <add>* Disable `<div hidden />` prerendering in favor of a different future API. ([@acdlite](https://github.com/acdlite) in [#18917](https://github.com/facebook/react/pull/18917)) <add>* Add `unstable_expectedLoadTime` to Suspense for CPU-bound trees. ([@acdlite](https://github.com/acdlite) in [#19936](https://github.com/facebook/react/pull/19936)) <add>* Add an experimental `unstable_useOpaqueIdentifier` Hook. ([@lunaruan](https://github.com/lunaruan) in [#17322](https://github.com/facebook/react/pull/17322)) <add>* Add an experimental `unstable_startTransition` API. ([@rickhanlonii](https://github.com/rickhanlonii) in [#19696](https://github.com/facebook/react/pull/19696)) <add>* Using `act` in the test renderer no longer flushes Suspense fallbacks. ([@acdlite](https://github.com/acdlite) in [#18596](https://github.com/facebook/react/pull/18596)) <add>* Use global render timeout for CPU Suspense. ([@sebmarkbage](https://github.com/sebmarkbage) in [#19643](https://github.com/facebook/react/pull/19643)) <add>* Clear the existing root content before mounting. ([@bvaughn](https://github.com/bvaughn) in [#18730](https://github.com/facebook/react/pull/18730)) <add>* Fix a bug with error boundaries. ([@acdlite](https://github.com/acdlite) in [#18265](https://github.com/facebook/react/pull/18265)) <add>* Fix a bug causing dropped updates in a suspended tree. ([@acdlite](https://github.com/acdlite) in [#18384](https://github.com/facebook/react/pull/18384) and [#18457](https://github.com/facebook/react/pull/18457)) <add>* Fix a bug causing dropped render phase updates. ([@acdlite](https://github.com/acdlite) in [#18537](https://github.com/facebook/react/pull/18537)) <add>* Fix a bug in SuspenseList. ([@sebmarkbage](https://github.com/sebmarkbage) in [#18412](https://github.com/facebook/react/pull/18412)) <add>* Fix a bug causing Suspense fallback to show too early. ([@acdlite](https://github.com/acdlite) in [#18411](https://github.com/facebook/react/pull/18411)) <add>* Fix a bug with class components inside SuspenseList. ([@sebmarkbage](https://github.com/sebmarkbage) in [#18448](https://github.com/facebook/react/pull/18448)) <add>* Fix a bug with inputs that may cause updates to be dropped. ([@jddxf](https://github.com/jddxf) in [#18515](https://github.com/facebook/react/pull/18515) and [@acdlite](https://github.com/acdlite) in [#18535](https://github.com/facebook/react/pull/18535)) <add>* Fix a bug causing Suspense fallback to get stuck. ([@acdlite](https://github.com/acdlite) in [#18663](https://github.com/facebook/react/pull/18663)) <add>* Don't cut off the tail of a SuspenseList if hydrating. ([@sebmarkbage](https://github.com/sebmarkbage) in [#18854](https://github.com/facebook/react/pull/18854)) <add>* Fix a bug in `useMutableSource` that may happen when `getSnapshot` changes. ([@bvaughn](https://github.com/bvaughn) in [#18297](https://github.com/facebook/react/pull/18297)) <add>* Fix a tearing bug in `useMutableSource`. ([@bvaughn](https://github.com/bvaughn) in [#18912](https://github.com/facebook/react/pull/18912)) <add>* Warn if calling setState outside of render but before commit. ([@sebmarkbage](https://github.com/sebmarkbage) in [#18838](https://github.com/facebook/react/pull/18838)) <add> <ide> ## 16.14.0 (October 14, 2020) <ide> <ide> ### React
1
Ruby
Ruby
assign the cookie hash on request allocation
9f09848918e5f499e9d07a734345ee106d0fb9f9
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def self.new_session <ide> def self.create <ide> env = {} <ide> env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application <add> env["rack.request.cookie_hash"] = {}.with_indifferent_access <ide> new(default_env.merge(env), new_session) <ide> end <ide> <ide> def setup_controller_request_and_response <ide> end <ide> <ide> @request = TestRequest.create <del> @request.env["rack.request.cookie_hash"] = {}.with_indifferent_access <ide> @response = build_response @response_klass <ide> @response.request = @request <ide> <ide><path>actionpack/lib/action_dispatch/testing/test_request.rb <ide> class TestRequest < Request <ide> 'HTTP_HOST' => 'test.host', <ide> 'REMOTE_ADDR' => '0.0.0.0', <ide> 'HTTP_USER_AGENT' => 'Rails Testing', <del> "rack.request.cookie_hash" => {}.with_indifferent_access <ide> ) <ide> <ide> # Create a new test request with default `env` values <ide> def self.create(env = {}) <ide> env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application <add> env["rack.request.cookie_hash"] ||= {}.with_indifferent_access <ide> new(default_env.merge(env)) <ide> end <ide>
2
Python
Python
fix a typo in tag addition
2390b2cf6571d469bebc65b9b4d8eaee33706b57
<ide><path>src/transformers/modelcard.py <ide> def from_keras( <ide> tags = ["generated_from_keras_callback"] <ide> elif isinstance(tags, str) and tags != "generated_from_keras_callback": <ide> tags = [tags, "generated_from_keras_callback"] <del> elif "generated_from_trainer" not in tags: <add> elif "generated_from_keras_callback" not in tags: <ide> tags.append("generated_from_keras_callback") <ide> <ide> if keras_history is not None:
1
Mixed
Ruby
replace `immediateexecutor` with nothing
f539be73061a3ef6f2d53237a802e7c082995e87
<ide><path>activerecord/CHANGELOG.md <ide> <ide> Some applications may want one thread pool per database whereas others want to use <ide> a single global thread pool for all queries. By default Rails will set `async_query_executor` <del> to `:immediate` and create a `Concurrent::ImmediateExecutor` object which is essentially a no-op. <add> to `nil` which will not initialize any executor. If `load_async` is called and no executor <add> has been configured, the query will be executed in the foreground. <add> <ide> To create one thread pool for all database connections to use applications can set <ide> `config.active_record.async_query_executor` to `:global_thread_pool` and optionally define <ide> `config.active_record.global_executor_concurrency`. This defaults to 4. For applications that want <ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb <ide> def build_async_executor <ide> ) <ide> when :global_thread_pool <ide> Base.global_thread_pool_async_query_executor <del> else <del> Base.immediate_query_executor <ide> end <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def combine_multi_statements(total_sql) <ide> <ide> # Returns an ActiveRecord::Result instance. <ide> def select(sql, name = nil, binds = [], prepare: false, async: false) <del> if async <add> if async && async_enabled? <ide> if current_transaction.joinable? <ide> raise AsynchronousQueryInsideTransactionError, "Asynchronous queries are not allowed inside transactions" <ide> end <ide> def select(sql, name = nil, binds = [], prepare: false, async: false) <ide> end <ide> return future_result <ide> end <add> <ide> exec_query(sql, name, binds, prepare: prepare) <ide> end <ide> <ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def supports_concurrent_connections? <ide> true <ide> end <ide> <add> def async_enabled? <add> supports_concurrent_connections? && !Base.async_query_executor.nil? <add> end <add> <ide> # This is meant to be implemented by the adapters that support extensions <ide> def disable_extension(name) <ide> end <ide><path>activerecord/lib/active_record/core.rb <ide> def self.configurations <ide> mattr_accessor :application_record_class, instance_accessor: false, default: nil <ide> <ide> # Sets the async_query_executor for an application. By default the thread pool executor <del> # set to +:immediate+. Options are: <add> # set to +nil+ which will not run queries in the background. Applications must configure <add> # a thread pool executor to use this feature. Options are: <ide> # <del> # * :immediate - Initializes a single +Concurrent::ImmediateExecutor+ <add> # * nil - Does not initalize a thread pool executor. Any async calls will be <add> # run in the foreground. <ide> # * :global_thread_pool - Initializes a single +Concurrent::ThreadPoolExecutor+ <ide> # that uses the +async_query_concurrency+ for the +max_threads+ value. <ide> # * :multi_thread_pool - Initializes a +Concurrent::ThreadPoolExecutor+ for each <ide> # database connection. The initializer values are defined in the configuration hash. <del> mattr_accessor :async_query_executor, instance_accessor: false, default: :immediate <del> <del> def self.immediate_query_executor # :nodoc: <del> @@immediate_query_executor ||= Concurrent::ImmediateExecutor.new <del> end <add> mattr_accessor :async_query_executor, instance_accessor: false, default: nil <ide> <ide> def self.global_thread_pool_async_query_executor # :nodoc: <ide> concurrency = global_executor_concurrency || 4 <ide> def self.global_thread_pool_async_query_executor # :nodoc: <ide> # Set the +global_executor_concurrency+. This configuration value can only be used <ide> # with the global thread pool async query executor. <ide> def self.global_executor_concurrency=(global_executor_concurrency) <del> if async_query_executor == :immediate || async_query_executor == :multi_thread_pool <del> raise ArgumentError, "`global_executor_concurrency` cannot be set when using either immediate or multiple thread pools. For multiple thread pools, please set the concurrency in your database configuration. Immediate thread pools are essentially a no-op." <add> if async_query_executor.nil? || async_query_executor == :multi_thread_pool <add> raise ArgumentError, "`global_executor_concurrency` cannot be set when using the executor is nil or set to multi_thead_pool. For multiple thread pools, please set the concurrency in your database configuration." <ide> end <ide> <ide> @@global_executor_concurrency = global_executor_concurrency <ide><path>activerecord/lib/active_record/relation.rb <ide> def delete_by(*args) <ide> # <ide> # Post.where(published: true).load_async # => #<ActiveRecord::Relation> <ide> def load_async <add> return load if !connection.async_enabled? <add> <ide> unless loaded? <ide> result = exec_main_query(async: connection.current_transaction.closed?) <add> <ide> if result.is_a?(Array) <ide> @records = result <ide> else <ide> @future_result = result <ide> end <ide> @loaded = true <ide> end <add> <ide> self <ide> end <ide> <ide><path>activerecord/test/cases/asynchronous_queries_test.rb <ide> module AsynchronousQueriesSharedTests <ide> def test_async_select_failure <ide> ActiveRecord::Base.asynchronous_queries_tracker.start_session <ide> <del> future_result = @connection.select_all "SELECT * FROM does_not_exists", async: true <del> assert_kind_of ActiveRecord::FutureResult, future_result <del> assert_raises ActiveRecord::StatementInvalid do <del> future_result.result <add> if in_memory_db? <add> assert_raises ActiveRecord::StatementInvalid do <add> @connection.select_all "SELECT * FROM does_not_exists", async: true <add> end <add> else <add> future_result = @connection.select_all "SELECT * FROM does_not_exists", async: true <add> assert_kind_of ActiveRecord::FutureResult, future_result <add> assert_raises ActiveRecord::StatementInvalid do <add> future_result.result <add> end <ide> end <ide> ensure <ide> ActiveRecord::Base.asynchronous_queries_tracker.finalize_session <ide> def test_async_query_from_transaction <ide> @connection.select_all "SELECT * FROM posts", async: true <ide> end <ide> <del> @connection.transaction do <del> assert_raises ActiveRecord::AsynchronousQueryInsideTransactionError do <del> @connection.select_all "SELECT * FROM posts", async: true <add> unless in_memory_db? <add> @connection.transaction do <add> assert_raises ActiveRecord::AsynchronousQueryInsideTransactionError do <add> @connection.select_all "SELECT * FROM posts", async: true <add> end <ide> end <ide> end <ide> ensure <ide> def test_async_query_foreground_fallback <ide> end <ide> <ide> @connection.pool.stub(:schedule_query, proc { }) do <del> future_result = @connection.select_all "SELECT * FROM does_not_exists", async: true <del> assert_kind_of ActiveRecord::FutureResult, future_result <del> assert_raises ActiveRecord::StatementInvalid do <del> future_result.result <add> if in_memory_db? <add> assert_raises ActiveRecord::StatementInvalid do <add> @connection.select_all "SELECT * FROM does_not_exists", async: true <add> end <add> else <add> future_result = @connection.select_all "SELECT * FROM does_not_exists", async: true <add> assert_kind_of ActiveRecord::FutureResult, future_result <add> assert_raises ActiveRecord::StatementInvalid do <add> future_result.result <add> end <ide> end <ide> end <ide> <ide> def test_async_select_all <ide> end <ide> <ide> future_result = @connection.select_all "SELECT * FROM posts", async: true <del> assert_kind_of ActiveRecord::FutureResult, future_result <add> <add> if in_memory_db? <add> assert_kind_of ActiveRecord::Result, future_result <add> else <add> assert_kind_of ActiveRecord::FutureResult, future_result <add> end <ide> <ide> monitor.synchronize do <ide> condition.wait_until { status[:executed] } <ide> def setup <ide> end <ide> <ide> class AsynchronousExecutorTypeTest < ActiveRecord::TestCase <del> def test_immediate_configuration_uses_a_single_immediate_executor_by_default <add> def test_null_configuration_uses_a_single_null_executor_by_default <ide> old_value = ActiveRecord::Base.async_query_executor <del> ActiveRecord::Base.async_query_executor = :immediate <add> ActiveRecord::Base.async_query_executor = nil <ide> <ide> handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new <ide> db_config = ActiveRecord::Base.configurations.configs_for(env_name: "arunit", name: "primary") <ide> def test_immediate_configuration_uses_a_single_immediate_executor_by_default <ide> async_pool1 = pool1.instance_variable_get(:@async_executor) <ide> async_pool2 = pool2.instance_variable_get(:@async_executor) <ide> <del> assert async_pool1.is_a?(Concurrent::ImmediateExecutor) <del> assert async_pool2.is_a?(Concurrent::ImmediateExecutor) <add> assert_nil async_pool1 <add> assert_nil async_pool2 <ide> <ide> assert_equal 2, handler.all_connection_pools.count <del> assert_equal async_pool1, async_pool2 <ide> ensure <ide> clean_up_connection_handler <ide> ActiveRecord::Base.async_query_executor = old_value <ide> def test_concurrency_can_be_set_on_global_thread_pool <ide> ActiveRecord::Base.async_query_executor = old_value <ide> end <ide> <del> def test_concurrency_cannot_be_set_with_immediate_or_multi_thread_pool <add> def test_concurrency_cannot_be_set_with_null_executor_or_multi_thread_pool <ide> old_value = ActiveRecord::Base.async_query_executor <del> ActiveRecord::Base.async_query_executor = :immediate <add> ActiveRecord::Base.async_query_executor = nil <ide> <ide> assert_raises ArgumentError do <ide> ActiveRecord::Base.global_executor_concurrency = 8 <ide><path>activerecord/test/cases/relation/load_async_test.rb <ide> class LoadAsyncTest < ActiveRecord::TestCase <ide> <ide> def test_scheduled? <ide> defered_posts = Post.where(author_id: 1).load_async <del> assert_predicate defered_posts, :scheduled? <add> if in_memory_db? <add> assert_not_predicate defered_posts, :scheduled? <add> else <add> assert_predicate defered_posts, :scheduled? <add> end <ide> assert_predicate defered_posts, :loaded? <ide> defered_posts.to_a <ide> assert_not_predicate defered_posts, :scheduled? <ide> end <ide> <ide> def test_reset <ide> defered_posts = Post.where(author_id: 1).load_async <del> assert_predicate defered_posts, :scheduled? <add> if in_memory_db? <add> assert_not_predicate defered_posts, :scheduled? <add> else <add> assert_predicate defered_posts, :scheduled? <add> end <ide> defered_posts.reset <ide> assert_not_predicate defered_posts, :scheduled? <ide> end <ide> def test_load_async_from_transaction <ide> Post.transaction do <ide> Post.where(author_id: 1).update_all(title: "In Transaction") <ide> posts = Post.where(author_id: 1).load_async <del> assert_predicate posts, :scheduled? <add> if in_memory_db? <add> assert_not_predicate posts, :scheduled? <add> else <add> assert_predicate posts, :scheduled? <add> end <ide> assert_predicate posts, :loaded? <ide> raise ActiveRecord::Rollback <ide> end <ide> def test_eager_loading_query <ide> <ide> defered_posts = Post.where(author_id: 1).eager_load(:comments).load_async <ide> <del> assert_predicate defered_posts, :scheduled? <add> if in_memory_db? <add> assert_not_predicate defered_posts, :scheduled? <add> else <add> assert_predicate defered_posts, :scheduled? <add> end <ide> <ide> monitor.synchronize do <ide> condition.wait_until { status[:executed] } <ide> def test_empty? <ide> assert_predicate defered_posts, :loaded? <ide> end <ide> end <add> <add> unless in_memory_db? <add> class LoadAsyncNullExecutorTest < ActiveRecord::TestCase <add> self.use_transactional_tests = false <add> <add> fixtures :posts, :comments <add> <add> def setup <add> @old_config = ActiveRecord::Base.async_query_executor <add> ActiveRecord::Base.async_query_executor = nil <add> ActiveRecord::Base.establish_connection :arunit <add> end <add> <add> def teardown <add> ActiveRecord::Base.async_query_executor = @old_config <add> ActiveRecord::Base.establish_connection :arunit <add> end <add> <add> def test_scheduled? <add> defered_posts = Post.where(author_id: 1).load_async <add> assert_not_predicate defered_posts, :scheduled? <add> assert_predicate defered_posts, :loaded? <add> defered_posts.to_a <add> assert_not_predicate defered_posts, :scheduled? <add> end <add> <add> def test_reset <add> defered_posts = Post.where(author_id: 1).load_async <add> assert_not_predicate defered_posts, :scheduled? <add> defered_posts.reset <add> assert_not_predicate defered_posts, :scheduled? <add> end <add> <add> def test_simple_query <add> expected_records = Post.where(author_id: 1).to_a <add> <add> status = {} <add> monitor = Monitor.new <add> condition = monitor.new_cond <add> <add> subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |event| <add> if event.payload[:name] == "Post Load" <add> status[:executed] = true <add> status[:async] = event.payload[:async] <add> monitor.synchronize { condition.signal } <add> end <add> end <add> <add> defered_posts = Post.where(author_id: 1).load_async <add> <add> monitor.synchronize do <add> condition.wait_until { status[:executed] } <add> end <add> <add> assert_equal expected_records, defered_posts.to_a <add> assert_not_equal Post.connection.supports_concurrent_connections?, status[:async] <add> ensure <add> ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber <add> end <add> <add> def test_load_async_from_transaction <add> posts = nil <add> Post.transaction do <add> Post.where(author_id: 1).update_all(title: "In Transaction") <add> posts = Post.where(author_id: 1).load_async <add> assert_not_predicate posts, :scheduled? <add> assert_predicate posts, :loaded? <add> raise ActiveRecord::Rollback <add> end <add> <add> assert_not_nil posts <add> assert_equal ["In Transaction"], posts.map(&:title).uniq <add> end <add> <add> def test_eager_loading_query <add> expected_records = Post.where(author_id: 1).eager_load(:comments).to_a <add> <add> status = {} <add> monitor = Monitor.new <add> condition = monitor.new_cond <add> <add> subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") do |event| <add> if event.payload[:name] == "SQL" <add> status[:executed] = true <add> status[:async] = event.payload[:async] <add> monitor.synchronize { condition.signal } <add> end <add> end <add> <add> defered_posts = Post.where(author_id: 1).eager_load(:comments).load_async <add> <add> assert_not_predicate defered_posts, :scheduled? <add> <add> monitor.synchronize do <add> condition.wait_until { status[:executed] } <add> end <add> <add> assert_equal expected_records, defered_posts.to_a <add> assert_queries(0) do <add> defered_posts.each(&:comments) <add> end <add> <add> assert_predicate Post.connection, :supports_concurrent_connections? <add> assert_not status[:async], "Expected status[:async] to be false with NullExecutor" <add> ensure <add> ActiveSupport::Notifications.unsubscribe(subscriber) if subscriber <add> end <add> <add> def test_contradiction <add> assert_queries(0) do <add> assert_equal [], Post.where(id: []).load_async.to_a <add> end <add> <add> Post.where(id: []).load_async.reset <add> end <add> <add> def test_pluck <add> titles = Post.where(author_id: 1).pluck(:title) <add> assert_equal titles, Post.where(author_id: 1).load_async.pluck(:title) <add> end <add> <add> def test_size <add> expected_size = Post.where(author_id: 1).size <add> <add> defered_posts = Post.where(author_id: 1).load_async <add> <add> assert_equal expected_size, defered_posts.size <add> assert_predicate defered_posts, :loaded? <add> end <add> <add> def test_empty? <add> defered_posts = Post.where(author_id: 1).load_async <add> <add> assert_equal false, defered_posts.empty? <add> assert_predicate defered_posts, :loaded? <add> end <add> end <add> end <ide> end
8
PHP
PHP
use the time utility instead of \datetime
d68caa6077165425db2bbf774cb3e6215f12cf77
<ide><path>src/Controller/Component/CookieComponent.php <ide> <ide> use Cake\Controller\Component; <ide> use Cake\Controller\ComponentRegistry; <del>use Cake\Controller\Controller; <ide> use Cake\Core\Configure; <ide> use Cake\Error; <ide> use Cake\Event\Event; <ide> use Cake\Network\Request; <ide> use Cake\Network\Response; <ide> use Cake\Utility\Hash; <ide> use Cake\Utility\Security; <add>use Cake\Utility\Time; <ide> <ide> /** <ide> * Cookie Component. <ide> public function delete($key) { <ide> */ <ide> protected function _write($name, $value) { <ide> $config = $this->configKey($name); <del> $expires = new \DateTime($config['expires']); <add> $expires = new Time($config['expires']); <ide> <ide> $this->_response->cookie(array( <ide> 'name' => $name, <ide> protected function _write($name, $value) { <ide> */ <ide> protected function _delete($name) { <ide> $config = $this->configKey($name); <del> $expires = new \DateTime('now'); <add> $expires = new Time('now'); <ide> <ide> $this->_response->cookie(array( <ide> 'name' => $name, <ide><path>tests/TestCase/Controller/Component/CookieComponentTest.php <ide> use Cake\Network\Response; <ide> use Cake\TestSuite\TestCase; <ide> use Cake\Utility\Security; <add>use Cake\Utility\Time; <ide> <ide> /** <ide> * CookieComponentTest class <ide> public function testWriteWithFalseyValue() { <ide> public function testWriteFarFuture() { <ide> $this->Cookie->configKey('Testing', 'expires', '+90 years'); <ide> $this->Cookie->write('Testing', 'value'); <del> $future = new \DateTime('now'); <add> $future = new Time('now'); <ide> $future->modify('+90 years'); <ide> <ide> $expected = array( <ide> public function testWriteHttpOnly() { <ide> $expected = array( <ide> 'name' => 'Testing', <ide> 'value' => 'value', <del> 'expire' => time() + 10, <add> 'expire' => (new Time('+10 seconds'))->format('U'), <ide> 'path' => '/', <ide> 'domain' => '', <ide> 'secure' => false, <ide> public function testDeleteHttpOnly() { <ide> $expected = array( <ide> 'name' => 'Testing', <ide> 'value' => '', <del> 'expire' => time() - 42000, <add> 'expire' => (new Time('now'))->format('U') - 42000, <ide> 'path' => '/', <ide> 'domain' => '', <ide> 'secure' => false, <ide> public function testWriteArrayValues() { <ide> ); <ide> $result = $this->Controller->response->cookie('Testing'); <ide> <del> $this->assertWithinMargin($result['expire'], time() + 10, 1); <add> $time = new Time('now'); <add> $this->assertWithinMargin($result['expire'], $time->format('U') + 10, 1); <ide> unset($result['expire']); <ide> $this->assertEquals($expected, $result); <ide> }
2
Javascript
Javascript
kill global queue in reactmultichild
418ba27485ef55dfbee06a3f9e56f09380e09a30
<ide><path>src/renderers/dom/client/ReactDOMIDOperations.js <ide> var ReactDOMIDOperations = { <ide> * Updates a component's children by processing a series of updates. <ide> * <ide> * @param {array<object>} updates List of update configurations. <del> * @param {array<string>} markup List of markup strings. <ide> * @internal <ide> */ <del> dangerouslyProcessChildrenUpdates: function(updates, markup) { <del> for (var i = 0; i < updates.length; i++) { <del> var update = updates[i]; <del> var node = ReactDOMComponentTree.getNodeFromInstance(update.parentInst); <del> update.parentNode = node; <del> } <del> DOMChildrenOperations.processUpdates(updates, markup); <add> dangerouslyProcessChildrenUpdates: function(parentInst, updates) { <add> var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); <add> DOMChildrenOperations.processUpdates(node, updates); <ide> }, <ide> }; <ide> <ide><path>src/renderers/dom/client/__tests__/ReactDOMIDOperations-test.js <ide> describe('ReactDOMIDOperations', function() { <ide> var html = '\n \t <span> \n testContent \t </span> \n \t'; <ide> <ide> ReactDOMIDOperations.dangerouslyProcessChildrenUpdates( <add> {_nativeNode: stubNode}, <ide> [{ <del> parentInst: {_nativeNode: stubNode}, <del> parentNode: null, <ide> type: ReactMultiChildUpdateTypes.SET_MARKUP, <del> markupIndex: null, <ide> content: html, <ide> fromIndex: null, <ide> toIndex: null, <ide><path>src/renderers/dom/client/utils/DOMChildrenOperations.js <ide> var DOMChildrenOperations = { <ide> * update configurations are each expected to have a `parentNode` property. <ide> * <ide> * @param {array<object>} updates List of update configurations. <del> * @param {array<string>} markupList List of markup strings. <ide> * @internal <ide> */ <del> processUpdates: function(updates, markupList) { <add> processUpdates: function(parentNode, updates) { <ide> var update; <ide> // Mapping from parent IDs to initial child orderings. <ide> var initialChildren = null; <ide> // List of children that will be moved or removed. <ide> var updatedChildren = null; <ide> <add> var markupList = null; <add> <ide> for (var i = 0; i < updates.length; i++) { <ide> update = updates[i]; <ide> if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING || <ide> update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) { <ide> var updatedIndex = update.fromIndex; <del> var updatedChild = update.parentNode.childNodes[updatedIndex]; <del> var parentID = update.parentInst._rootNodeID; <add> var updatedChild = parentNode.childNodes[updatedIndex]; <ide> <ide> invariant( <ide> updatedChild, <del> 'processUpdates(): Unable to find child %s of element. This ' + <add> 'processUpdates(): Unable to find child %s of element %s. This ' + <ide> 'probably means the DOM was unexpectedly mutated (e.g., by the ' + <ide> 'browser), usually due to forgetting a <tbody> when using tables, ' + <ide> 'nesting tags like <form>, <p>, or <a>, or using non-SVG elements ' + <del> 'in an <svg> parent. Try inspecting the child nodes of the element ' + <del> 'with React ID `%s`.', <add> 'in an <svg> parent.', <ide> updatedIndex, <del> parentID <add> parentNode, <ide> ); <ide> <ide> initialChildren = initialChildren || {}; <del> initialChildren[parentID] = initialChildren[parentID] || []; <del> initialChildren[parentID][updatedIndex] = updatedChild; <add> initialChildren[updatedIndex] = updatedChild; <ide> <ide> updatedChildren = updatedChildren || []; <ide> updatedChildren.push(updatedChild); <add> } else if (update.type === ReactMultiChildUpdateTypes.INSERT_MARKUP) { <add> // Replace each HTML string with an index into the markup list <add> if (typeof update.content === 'string') { <add> markupList = markupList || []; <add> update.content = markupList.push(update.markup); <add> } <ide> } <ide> } <ide> <del> // markupList is either a list of markup or just a list of elements <del> var isHTML = markupList.length && typeof markupList[0] === 'string'; <ide> var renderedMarkup; <del> if (isHTML) { <add> if (markupList) { <ide> renderedMarkup = Danger.dangerouslyRenderMarkup(markupList); <del> } else { <del> renderedMarkup = markupList; <ide> } <ide> <ide> // Remove updated children first so that `toIndex` is consistent. <ide> if (updatedChildren) { <ide> for (var j = 0; j < updatedChildren.length; j++) { <del> updatedChildren[j].parentNode.removeChild(updatedChildren[j]); <add> parentNode.removeChild(updatedChildren[j]); <ide> } <ide> } <ide> <ide> for (var k = 0; k < updates.length; k++) { <ide> update = updates[k]; <ide> switch (update.type) { <ide> case ReactMultiChildUpdateTypes.INSERT_MARKUP: <del> if (isHTML) { <add> if (renderedMarkup) { <ide> insertChildAt( <del> update.parentNode, <del> renderedMarkup[update.markupIndex], <add> parentNode, <add> renderedMarkup[update.content], <ide> update.toIndex <ide> ); <ide> } else { <ide> insertLazyTreeChildAt( <del> update.parentNode, <del> renderedMarkup[update.markupIndex], <add> parentNode, <add> update.content, <ide> update.toIndex <ide> ); <ide> } <ide> break; <ide> case ReactMultiChildUpdateTypes.MOVE_EXISTING: <ide> insertChildAt( <del> update.parentNode, <del> initialChildren[update.parentInst._rootNodeID][update.fromIndex], <add> parentNode, <add> initialChildren[update.fromIndex], <ide> update.toIndex <ide> ); <ide> break; <ide> case ReactMultiChildUpdateTypes.SET_MARKUP: <ide> setInnerHTML( <del> update.parentNode, <add> parentNode, <ide> update.content <ide> ); <ide> break; <ide> case ReactMultiChildUpdateTypes.TEXT_CONTENT: <ide> setTextContent( <del> update.parentNode, <add> parentNode, <ide> update.content <ide> ); <ide> break; <ide><path>src/renderers/shared/reconciler/ReactMultiChild.js <ide> var ReactChildReconciler = require('ReactChildReconciler'); <ide> var flattenChildren = require('flattenChildren'); <ide> <ide> /** <del> * Updating children of a component may trigger recursive updates. The depth is <del> * used to batch recursive updates to render markup more efficiently. <add> * Make an update for markup to be rendered and inserted at a supplied index. <ide> * <del> * @type {number} <del> * @private <del> */ <del>var updateDepth = 0; <del> <del>/** <del> * Queue of update configuration objects. <del> * <del> * Each object has a `type` property that is in `ReactMultiChildUpdateTypes`. <del> * <del> * @type {array<object>} <del> * @private <del> */ <del>var updateQueue = []; <del> <del>/** <del> * Queue of markup to be rendered. <del> * <del> * @type {array<string>} <del> * @private <del> */ <del>var markupQueue = []; <del> <del>/** <del> * Enqueues markup to be rendered and inserted at a supplied index. <del> * <del> * @param {object} parentInst parent component. <ide> * @param {string} markup Markup that renders into an element. <ide> * @param {number} toIndex Destination index. <ide> * @private <ide> */ <del>function enqueueInsertMarkup(parentInst, markup, toIndex) { <add>function makeInsertMarkup(markup, toIndex) { <ide> // NOTE: Null values reduce hidden classes. <del> updateQueue.push({ <del> parentInst: parentInst, <del> parentNode: null, <add> return { <ide> type: ReactMultiChildUpdateTypes.INSERT_MARKUP, <del> markupIndex: markupQueue.push(markup) - 1, <del> content: null, <add> content: markup, <ide> fromIndex: null, <ide> toIndex: toIndex, <del> }); <add> }; <ide> } <ide> <ide> /** <del> * Enqueues moving an existing element to another index. <add> * Make an update for moving an existing element to another index. <ide> * <del> * @param {object} parentInst parent component. <ide> * @param {number} fromIndex Source index of the existing element. <ide> * @param {number} toIndex Destination index of the element. <ide> * @private <ide> */ <del>function enqueueMove(parentInst, fromIndex, toIndex) { <add>function makeMove(fromIndex, toIndex) { <ide> // NOTE: Null values reduce hidden classes. <del> updateQueue.push({ <del> parentInst: parentInst, <del> parentNode: null, <add> return { <ide> type: ReactMultiChildUpdateTypes.MOVE_EXISTING, <del> markupIndex: null, <ide> content: null, <ide> fromIndex: fromIndex, <ide> toIndex: toIndex, <del> }); <add> }; <ide> } <ide> <ide> /** <del> * Enqueues removing an element at an index. <add> * Make an update for removing an element at an index. <ide> * <del> * @param {object} parentInst parent component. <ide> * @param {number} fromIndex Index of the element to remove. <ide> * @private <ide> */ <del>function enqueueRemove(parentInst, fromIndex) { <add>function makeRemove(fromIndex) { <ide> // NOTE: Null values reduce hidden classes. <del> updateQueue.push({ <del> parentInst: parentInst, <del> parentNode: null, <add> return { <ide> type: ReactMultiChildUpdateTypes.REMOVE_NODE, <del> markupIndex: null, <ide> content: null, <ide> fromIndex: fromIndex, <ide> toIndex: null, <del> }); <add> }; <ide> } <ide> <ide> /** <del> * Enqueues setting the markup of a node. <add> * Make an update for setting the markup of a node. <ide> * <del> * @param {object} parentInst parent component. <ide> * @param {string} markup Markup that renders into an element. <ide> * @private <ide> */ <del>function enqueueSetMarkup(parentInst, markup) { <add>function makeSetMarkup(markup) { <ide> // NOTE: Null values reduce hidden classes. <del> updateQueue.push({ <del> parentInst: parentInst, <del> parentNode: null, <add> return { <ide> type: ReactMultiChildUpdateTypes.SET_MARKUP, <del> markupIndex: null, <ide> content: markup, <ide> fromIndex: null, <ide> toIndex: null, <del> }); <add> }; <ide> } <ide> <ide> /** <del> * Enqueues setting the text content. <add> * Make an update for setting the text content. <ide> * <del> * @param {object} parentInst parent component. <ide> * @param {string} textContent Text content to set. <ide> * @private <ide> */ <del>function enqueueTextContent(parentInst, textContent) { <add>function makeTextContent(textContent) { <ide> // NOTE: Null values reduce hidden classes. <del> updateQueue.push({ <del> parentInst: parentInst, <del> parentNode: null, <add> return { <ide> type: ReactMultiChildUpdateTypes.TEXT_CONTENT, <del> markupIndex: null, <ide> content: textContent, <ide> fromIndex: null, <ide> toIndex: null, <del> }); <add> }; <ide> } <ide> <ide> /** <del> * Processes any enqueued updates. <del> * <del> * @private <add> * Push an update, if any, onto the queue. Creates a new queue if none is <add> * passed and always returns the queue. Mutative. <ide> */ <del>function processQueue() { <del> if (updateQueue.length) { <del> ReactComponentEnvironment.processChildrenUpdates( <del> updateQueue, <del> markupQueue <del> ); <del> clearQueue(); <add>function enqueue(queue, update) { <add> if (update) { <add> queue = queue || []; <add> queue.push(update); <ide> } <add> return queue; <ide> } <ide> <ide> /** <del> * Clears any enqueued updates. <add> * Processes any enqueued updates. <ide> * <ide> * @private <ide> */ <del>function clearQueue() { <del> updateQueue.length = 0; <del> markupQueue.length = 0; <add>function processQueue(inst, updateQueue) { <add> ReactComponentEnvironment.processChildrenUpdates( <add> inst, <add> updateQueue, <add> ); <ide> } <ide> <ide> /** <ide> var ReactMultiChild = { <ide> * @internal <ide> */ <ide> updateTextContent: function(nextContent) { <del> updateDepth++; <del> var errorThrown = true; <del> try { <del> var prevChildren = this._renderedChildren; <del> // Remove any rendered children. <del> ReactChildReconciler.unmountChildren(prevChildren); <del> // TODO: The setTextContent operation should be enough <del> for (var name in prevChildren) { <del> if (prevChildren.hasOwnProperty(name)) { <del> this._unmountChild(prevChildren[name]); <del> } <del> } <del> // Set new text content. <del> this.setTextContent(nextContent); <del> errorThrown = false; <del> } finally { <del> updateDepth--; <del> if (!updateDepth) { <del> if (errorThrown) { <del> clearQueue(); <del> } else { <del> processQueue(); <del> } <add> var prevChildren = this._renderedChildren; <add> // Remove any rendered children. <add> ReactChildReconciler.unmountChildren(prevChildren); <add> // TODO: The setTextContent operation should be enough <add> var updates = []; <add> for (var name in prevChildren) { <add> if (prevChildren.hasOwnProperty(name)) { <add> updates.push(this._unmountChild(prevChildren[name])); <ide> } <ide> } <add> // Set new text content. <add> updates.push(makeTextContent(nextContent)); <add> processQueue(this, updates); <ide> }, <ide> <ide> /** <ide> var ReactMultiChild = { <ide> * @internal <ide> */ <ide> updateMarkup: function(nextMarkup) { <del> updateDepth++; <del> var errorThrown = true; <del> try { <del> var prevChildren = this._renderedChildren; <del> // Remove any rendered children. <del> ReactChildReconciler.unmountChildren(prevChildren); <del> for (var name in prevChildren) { <del> if (prevChildren.hasOwnProperty(name)) { <del> this._unmountChild(prevChildren[name]); <del> } <del> } <del> this.setMarkup(nextMarkup); <del> errorThrown = false; <del> } finally { <del> updateDepth--; <del> if (!updateDepth) { <del> if (errorThrown) { <del> clearQueue(); <del> } else { <del> processQueue(); <del> } <add> var prevChildren = this._renderedChildren; <add> // Remove any rendered children. <add> ReactChildReconciler.unmountChildren(prevChildren); <add> var updates = []; <add> for (var name in prevChildren) { <add> if (prevChildren.hasOwnProperty(name)) { <add> updates.push(this._unmountChild(prevChildren[name])); <ide> } <ide> } <add> updates.push(makeSetMarkup(nextMarkup)); <add> processQueue(this, updates); <ide> }, <ide> <ide> /** <ide> var ReactMultiChild = { <ide> * @internal <ide> */ <ide> updateChildren: function(nextNestedChildrenElements, transaction, context) { <del> updateDepth++; <del> var errorThrown = true; <del> try { <del> this._updateChildren(nextNestedChildrenElements, transaction, context); <del> errorThrown = false; <del> } finally { <del> updateDepth--; <del> if (!updateDepth) { <del> if (errorThrown) { <del> clearQueue(); <del> } else { <del> processQueue(); <del> } <del> } <del> } <add> // Hook used by React ART <add> this._updateChildren(nextNestedChildrenElements, transaction, context); <ide> }, <ide> <ide> /** <del> * Improve performance by isolating this hot code path from the try/catch <del> * block in `updateChildren`. <del> * <ide> * @param {?object} nextNestedChildrenElements Nested child element maps. <ide> * @param {ReactReconcileTransaction} transaction <ide> * @final <ide> var ReactMultiChild = { <ide> if (!nextChildren && !prevChildren) { <ide> return; <ide> } <add> var updates = null; <ide> var name; <ide> // `nextIndex` will increment for each child in `nextChildren`, but <ide> // `lastIndex` will be the last index visited in `prevChildren`. <ide> var ReactMultiChild = { <ide> var prevChild = prevChildren && prevChildren[name]; <ide> var nextChild = nextChildren[name]; <ide> if (prevChild === nextChild) { <del> this.moveChild(prevChild, nextIndex, lastIndex); <add> updates = enqueue( <add> updates, <add> this.moveChild(prevChild, nextIndex, lastIndex) <add> ); <ide> lastIndex = Math.max(prevChild._mountIndex, lastIndex); <ide> prevChild._mountIndex = nextIndex; <ide> } else { <ide> if (prevChild) { <ide> // Update `lastIndex` before `_mountIndex` gets unset by unmounting. <ide> lastIndex = Math.max(prevChild._mountIndex, lastIndex); <del> this._unmountChild(prevChild); <add> updates = enqueue(updates, this._unmountChild(prevChild)); <ide> } <ide> // The child must be instantiated before it's mounted. <del> this._mountChildAtIndex( <del> nextChild, nextIndex, transaction, context <add> updates = enqueue( <add> updates, <add> this._mountChildAtIndex(nextChild, nextIndex, transaction, context) <ide> ); <ide> } <ide> nextIndex++; <ide> var ReactMultiChild = { <ide> for (name in prevChildren) { <ide> if (prevChildren.hasOwnProperty(name) && <ide> !(nextChildren && nextChildren.hasOwnProperty(name))) { <del> this._unmountChild(prevChildren[name]); <add> updates = enqueue( <add> updates, <add> this._unmountChild(prevChildren[name]) <add> ); <ide> } <ide> } <add> if (updates) { <add> this.prepareToManageChildren(); <add> processQueue(this, updates); <add> } <ide> this._renderedChildren = nextChildren; <ide> }, <ide> <ide> var ReactMultiChild = { <ide> // be moved. Otherwise, we do not need to move it because a child will be <ide> // inserted or moved before `child`. <ide> if (child._mountIndex < lastIndex) { <del> this.prepareToManageChildren(); <del> enqueueMove(this, child._mountIndex, toIndex); <add> return makeMove(child._mountIndex, toIndex); <ide> } <ide> }, <ide> <ide> var ReactMultiChild = { <ide> * @protected <ide> */ <ide> createChild: function(child, mountImage) { <del> this.prepareToManageChildren(); <del> enqueueInsertMarkup(this, mountImage, child._mountIndex); <add> return makeInsertMarkup(mountImage, child._mountIndex); <ide> }, <ide> <ide> /** <ide> var ReactMultiChild = { <ide> * @protected <ide> */ <ide> removeChild: function(child) { <del> this.prepareToManageChildren(); <del> enqueueRemove(this, child._mountIndex); <del> }, <del> <del> /** <del> * Sets this text content string. <del> * <del> * @param {string} textContent Text content to set. <del> * @protected <del> */ <del> setTextContent: function(textContent) { <del> enqueueTextContent(this, textContent); <del> }, <del> <del> /** <del> * Sets this markup string. <del> * <del> * @param {string} markup Markup to set. <del> * @protected <del> */ <del> setMarkup: function(markup) { <del> enqueueSetMarkup(this, markup); <add> return makeRemove(child._mountIndex); <ide> }, <ide> <ide> /** <ide> var ReactMultiChild = { <ide> context <ide> ); <ide> child._mountIndex = index; <del> this.createChild(child, mountImage); <add> return this.createChild(child, mountImage); <ide> }, <ide> <ide> /** <ide> var ReactMultiChild = { <ide> * @private <ide> */ <ide> _unmountChild: function(child) { <del> this.removeChild(child); <add> var update = this.removeChild(child); <ide> child._mountIndex = null; <add> return update; <ide> }, <ide> <ide> }, <ide><path>src/test/ReactDefaultPerf.js <ide> var ReactDefaultPerf = { <ide> ReactDefaultPerf._recordWrite('', fnName, totalTime, args[0]); <ide> } else if (fnName === 'dangerouslyProcessChildrenUpdates') { <ide> // special format <del> args[0].forEach(function(update) { <add> args[1].forEach(function(update) { <ide> var writeArgs = {}; <ide> if (update.fromIndex !== null) { <ide> writeArgs.fromIndex = update.fromIndex; <ide> } <ide> if (update.toIndex !== null) { <ide> writeArgs.toIndex = update.toIndex; <ide> } <del> if (update.textContent !== null) { <del> writeArgs.textContent = update.textContent; <del> } <del> if (update.markupIndex !== null) { <del> writeArgs.markup = args[1][update.markupIndex]; <add> if (update.content !== null) { <add> writeArgs.content = update.content; <ide> } <ide> ReactDefaultPerf._recordWrite( <del> update.parentInst._rootNodeID, <add> args[0]._rootNodeID, <ide> update.type, <ide> totalTime, <ide> writeArgs
5
Python
Python
add volume methods in packet compute driver
d8f140faf4e8d74f72e2c20f608697caed51c751
<ide><path>libcloud/compute/drivers/packet.py <ide> """ <ide> Packet Driver <ide> """ <del>try: <add>try: # Try to use asyncio to perform requests in parallel across projects <ide> import asyncio <del>except ImportError: <add>except ImportError: # If not available will do things serially <ide> asyncio = None <ide> <add>import dateutil.parser <add> <ide> from libcloud.utils.py3 import httplib <ide> <ide> from libcloud.common.base import ConnectionKey, JsonResponse <ide> from libcloud.compute.types import Provider, NodeState, InvalidCredsError <ide> from libcloud.compute.base import NodeDriver, Node <ide> from libcloud.compute.base import NodeImage, NodeSize, NodeLocation <ide> from libcloud.compute.base import KeyPair <add>from libcloud.compute.base import StorageVolume, VolumeSnapshot <ide> <ide> PACKET_ENDPOINT = "api.packet.net" <ide> <ide> def ex_list_projects(self): <ide> def list_nodes(self, ex_project_id=None): <ide> if ex_project_id: <ide> return self.list_nodes_for_project(ex_project_id=ex_project_id) <del> else: <del> # if project has been specified during driver initialization, then <del> # return nodes for this project only <del> if self.project_id: <del> return self.list_nodes_for_project( <del> ex_project_id=self.project_id) <del> <del> # In case of Python2 perform requests serially <del> if asyncio is None: <del> nodes = [] <del> for project in self.projects: <del> nodes.extend( <del> self.list_nodes_for_project(ex_project_id=project.id) <del> ) <del> return nodes <del> <del> # In case of Python3 use asyncio to perform requests in parallel <del> # The _list_nodes function is defined dynamically using exec in <del> # order to prevent a SyntaxError in Python2 due to "yield from". <del> # This cruft can be removed once Python2 support is no longer <del> # required. <del> glob = globals() <del> loc = locals() <del> exec(""" <add> <add> # if project has been specified during driver initialization, then <add> # return nodes for this project only <add> if self.project_id: <add> return self.list_nodes_for_project( <add> ex_project_id=self.project_id) <add> <add> # In case of Python2 perform requests serially <add> if asyncio is None: <add> nodes = [] <add> for project in self.projects: <add> nodes.extend( <add> self.list_nodes_for_project(ex_project_id=project.id) <add> ) <add> return nodes <add> # In case of Python3 use asyncio to perform requests in parallel <add> return self.list_resources_async('nodes') <add> <add> def list_resources_async(self, resource_type): <add> # The _list_nodes function is defined dynamically using exec in <add> # order to prevent a SyntaxError in Python2 due to "yield from". <add> # This cruft can be removed once Python2 support is no longer <add> # required. <add> assert resource_type in ['nodes', 'volumes'] <add> glob = globals() <add> loc = locals() <add> exec(""" <ide> import asyncio <ide> @asyncio.coroutine <del>def _list_nodes(driver): <add>def _list_async(driver): <ide> projects = [project.id for project in driver.projects] <ide> loop = asyncio.get_event_loop() <ide> futures = [ <del> loop.run_in_executor(None, driver.list_nodes_for_project, p) <add> loop.run_in_executor(None, driver.list_%s_for_project, p) <ide> for p in projects <ide> ] <del> nodes = [] <add> retval = [] <ide> for future in futures: <ide> result = yield from future <del> nodes.extend(result) <del> return nodes""", glob, loc) <del> loop = asyncio.get_event_loop() <del> nodes = loop.run_until_complete(loc['_list_nodes'](loc['self'])) <del> return nodes <add> retval.extend(result) <add> return retval""" % resource_type, glob, loc) <add> loop = asyncio.get_event_loop() <add> return loop.run_until_complete(loc['_list_async'](loc['self'])) <ide> <ide> def list_nodes_for_project(self, ex_project_id, include='plan', page=1, <ide> per_page=1000): <ide> def ex_disassociate_address(self, address_uuid, include=None): <ide> path, params=params, method='DELETE').object <ide> return result <ide> <add> def list_volumes(self, ex_project_id=None): <add> if ex_project_id: <add> return self.list_volumes_for_project(ex_project_id=ex_project_id) <add> <add> # if project has been specified during driver initialization, then <add> # return nodes for this project only <add> if self.project_id: <add> return self.list_volumes_for_project( <add> ex_project_id=self.project_id) <add> <add> # In case of Python2 perform requests serially <add> if asyncio is None: <add> nodes = [] <add> for project in self.projects: <add> nodes.extend( <add> self.list_volumes_for_project(ex_project_id=project.id) <add> ) <add> return nodes <add> # In case of Python3 use asyncio to perform requests in parallel <add> return self.list_resources_async('volumes') <add> <add> def list_volumes_for_project(self, ex_project_id, include='plan', page=1, <add> per_page=1000): <add> params = { <add> 'include': include, <add> 'page': page, <add> 'per_page': per_page <add> } <add> data = self.connection.request( <add> '/projects/%s/storage' % (ex_project_id), <add> params=params).object['volumes'] <add> return list(map(self._to_volume, data)) <add> <add> def _to_volume(self, data): <add> return StorageVolume(id=data['id'], name=data['name'], <add> size=data['size'], driver=self, <add> extra=data) <add> <add> def create_volume(self, size, location, plan='storage_1', description='', <add> ex_project_id=None, locked=False, billing_cycle=None, <add> customdata='', snapshot_policies=None): <add> """ <add> Create a new volume. <add> <add> :param size: Size of volume in gigabytes (required) <add> :type size: ``int`` <add> <add> :param name: Name of the volume to be created <add> :type name: ``str`` <add> <add> :param location: Which data center to create a volume in. If <add> empty, undefined behavior will be selected. <add> (optional) <add> :type location: :class:`.NodeLocation` <add> :return: The newly created volume. <add> :rtype: :class:`StorageVolume` <add> """ <add> path = '/projects/%s/storage' % (ex_project_id or self.projects[0].id) <add> params = { <add> 'facility': location.id, <add> 'plan': plan, <add> 'size': size, <add> 'locked': locked <add> } <add> if description: <add> params['description'] = description <add> if customdata: <add> params['customdata'] = customdata <add> if billing_cycle: <add> params['billing_cycle'] = billing_cycle <add> if snapshot_policies: <add> params['snapshot_policies'] = snapshot_policies <add> data = self.connection.request(path, params=params, method='POST').object <add> return self._to_volume(data) <add> <add> def destroy_volume(self, volume): <add> """ <add> Destroys a storage volume. <add> <add> :param volume: Volume to be destroyed <add> :type volume: :class:`StorageVolume` <add> <add> :rtype: ``bool`` <add> """ <add> path = '/storage/%s' % volume.id <add> res = self.connection.request(path, method='DELETE') <add> return res.status == httplib.NO_CONTENT <add> <add> def create_volume_snapshot(self, volume, name=''): <add> """ <add> Create a new volume snapshot. <add> <add> :param volume: Volume to create a snapshot for <add> :type volume: class:`StorageVolume` <add> <add> :return: The newly created volume snapshot. <add> :rtype: :class:`VolumeSnapshot` <add> """ <add> path = '/storage/%s/snapshots' % volume.id <add> res = self.connection.request(path, method='POST') <add> assert res.status == httplib.ACCEPTED <add> return volume.list_snapshots()[-1] <add> <add> def destroy_volume_snapshot(self, snapshot): <add> """ <add> Delete a volume snapshot <add> <add> :param snapshot: volume snapshot to delete <add> :type snapshot: class:`VolumeSnapshot` <add> <add> :rtype: ``bool`` <add> """ <add> volume_id = snapshot.extra['volume']['href'].split('/')[-1] <add> path = '/storage/%s/snapshots/%s' % (volume_id, snapshot.id) <add> res = self.connection.request(path, method='DELETE') <add> return res.status == httplib.NO_CONTENT <add> <add> def list_volume_snapshots(self, volume, include=''): <add> """ <add> List snapshots for a volume. <add> <add> :param volume: Volume to list snapshots for <add> :type volume: class:`StorageVolume` <add> <add> :return: List of volume snapshots. <add> :rtype: ``list`` of :class: `VolumeSnapshot` <add> """ <add> path = '/storage/%s/snapshots' % volume.id <add> params = {} <add> if include: <add> params['include'] = include <add> data = self.connection.request(path, params=params).object['snapshots'] <add> return list(map(self._to_volume_snapshot, data)) <add> <add> def _to_volume_snapshot(self, data): <add> created = dateutil.parser.parse(data['created_at']) <add> return VolumeSnapshot(id=data['id'], <add> name=data['id'], <add> created=created, <add> state=data['status'], <add> driver=self, extra=data) <add> <add> def ex_modify_volume(self, volume, description=None, size=None, <add> locked=None, billing_cycle=None, <add> customdata=None): <add> path = '/storage/%s' % volume.id <add> params = {} <add> if description: <add> params['description'] = description <add> if size: <add> params['size'] = size <add> if locked != None: <add> params['locked'] = locked <add> if billing_cycle: <add> params['billing_cycle'] = billing_cycle <add> res = self.connection.request(path, params=params, method='PUT') <add> return self._to_volume(res.object) <add> <add> def ex_restore_volume(self, snapshot): <add> volume_id = snapshot.extra['volume']['href'].split('/')[-1] <add> ts = snapshot.extra['timestamp'] <add> path = '/storage/%s/restore?restore_point=%s' % (volume_id, ts) <add> res = self.connection.request(path, method='POST') <add> return res.status == httplib.NO_CONTENT <add> <add> def ex_clone_volume(self, volume, snapshot=None): <add> path = '/storage/%s/clone' % volume.id <add> if snapshot: <add> path += '?snapshot_timestamp=%s' % snapshot.extra['timestamp'] <add> res = self.connection.request(path, method='POST') <add> return res.status == httplib.NO_CONTENT <add> <add> def ex_describe_volume(self, volume_id): <add> path = '/storage/%s' % volume_id <add> data = self.connection.request(path).object <add> return self._to_volume(data) <ide> <ide> class Project(object): <ide> def __init__(self, project):
1
Javascript
Javascript
omit untitled editors (at least for now)
08a29df12fc965473b0c9e98e4d87fc84154710e
<ide><path>spec/main-process/atom-application.new.test.js <ide> class LaunchScenario { <ide> <ide> getOpenEditors (window) { <ide> return this.evalInWebContents(window.browserWindow.webContents, reply => { <del> reply(atom.workspace.getTextEditors().map(editor => editor.getPath())) <add> reply(atom.workspace.getTextEditors().map(editor => editor.getPath()).filter(Boolean)) <ide> }) <ide> } <ide>
1
Python
Python
add notes to some deprecations
a27f56069fb883c44dd4986d15e751162d85b621
<ide><path>numpy/core/numeric.py <ide> def correlate(a, v, mode='valid', old_behavior=False): <ide> # the old behavior should be made available under a different name, see thread <ide> # http://thread.gmane.org/gmane.comp.python.numeric.general/12609/focus=12630 <ide> if old_behavior: <del> # 2009-07-18 RemoveMe <add> # 2009-07-18 Cannot remove without replacement function. <ide> warnings.warn(""" <ide> The old behavior of correlate was deprecated for 1.4.0, and will be completely removed <ide> for NumPy 2.0. <ide><path>numpy/lib/npyio.py <ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None, <ide> <ide> # Get the first valid lines after the first skiprows ones .. <ide> if skiprows: <del> # 2011-03-06 RemoveMe <add> # 2011-03-06 Cannot remove is keyword. <ide> warnings.warn( <ide> "The use of `skiprows` is deprecated, it will be removed in " <ide> "numpy 2.0.\nPlease use `skip_header` instead.", <ide> def genfromtxt(fname, dtype=float, comments='#', delimiter=None, <ide> <ide> # Process the deprecated `missing` <ide> if missing != asbytes(''): <del> # 2011-03-06 RemoveMe <add> # 2011-03-06 Cannot remove, is keyword. <ide> warnings.warn( <ide> "The use of `missing` is deprecated, it will be removed in " <ide> "Numpy 2.0.\nPlease use `missing_values` instead.",
2
Mixed
Python
put gaussiannoise in its own module
ab8f7da83fc1e8859df543b386484cfb7e491723
<ide><path>docs/sources/layers/core.md <ide> Apply dropout to the input. Dropout consists in randomly setting a fraction `p` <ide> <ide> --- <ide> <del>## GaussianNoise <del>```python <del>keras.layers.core.GaussianNoise(sigma) <del>``` <del>Apply to the input an additive zero-centred gaussian noise with standard deviation `sigma`. Gaussian Noise (GS) is a natural choise as corruption process for real valued inputs. <del> <del>- __Input shape__: This layer does not assume a specific input shape. <del> <del>- __Output shape__: Same as input. <del> <del>- __Arguments__: <del> <del> - __sigma__: float. <del> <del>--- <ide> <ide> ## Reshape <ide> ```python <ide><path>docs/sources/layers/noise.md <add> <add> <add>## GaussianNoise <add>```python <add>keras.layers.core.GaussianNoise(sigma) <add>``` <add>Apply to the input an additive zero-centred gaussian noise with standard deviation `sigma`. Gaussian Noise (GS) is a natural choise as corruption process for real valued inputs. <add> <add>- __Input shape__: This layer does not assume a specific input shape. <add> <add>- __Output shape__: Same as input. <add> <add>- __Arguments__: <add> <add> - __sigma__: float, standard deviation of the noise distribution. <add> <add>--- <ide>\ No newline at end of file <ide><path>keras/layers/core.py <ide> def get_config(self): <ide> "p":self.p} <ide> <ide> <del>class GaussianNoise(MaskedLayer): <del> ''' <del> Corruption process with GaussianNoise <del> ''' <del> def __init__(self, sigma): <del> super(GaussianNoise, self).__init__() <del> self.sigma = sigma <del> <del> def get_output(self, train=False): <del> X = self.get_input(train) <del> if not train or self.sigma == 0: <del> return X <del> else: <del> return X + srng.normal(size=X.shape, avg=0.0, std=self.sigma, <del> dtype=theano.config.floatX) <del> <del> def get_config(self): <del> return {"name":self.__class__.__name__, <del> "sigma":self.sigma} <del> <del> <ide> class Activation(MaskedLayer): <ide> ''' <ide> Apply an activation function to an output. <ide><path>keras/layers/noise.py <add>from __future__ import absolute_import <add>from .core import srng, MaskedLayer <add>import theano <add> <add>class GaussianNoise(MaskedLayer): <add> ''' <add> Corruption process with GaussianNoise <add> ''' <add> def __init__(self, sigma): <add> super(GaussianNoise, self).__init__() <add> self.sigma = sigma <add> <add> def get_output(self, train=False): <add> X = self.get_input(train) <add> if not train or self.sigma == 0: <add> return X <add> else: <add> return X + srng.normal(size=X.shape, avg=0.0, std=self.sigma, <add> dtype=theano.config.floatX) <add> <add> def get_config(self): <add> return {"name":self.__class__.__name__, <add> "sigma":self.sigma} <ide>\ No newline at end of file
4
Ruby
Ruby
add commands module for path lookup
0bb7fda143f3a609fdfed27e84422ff55f85db02
<ide><path>Library/Homebrew/commands.rb <add>module Commands <add> def self.path(cmd) <add> if File.exist?(HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.sh") <add> HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.sh" <add> elsif File.exist?(HOMEBREW_LIBRARY_PATH/"dev-cmd/#{cmd}.sh") <add> HOMEBREW_LIBRARY_PATH/"dev-cmd/#{cmd}.sh" <add> elsif File.exist?(HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.rb") <add> HOMEBREW_LIBRARY_PATH/"cmd/#{cmd}.rb" <add> elsif File.exist?(HOMEBREW_LIBRARY_PATH/"dev-cmd/#{cmd}.rb") <add> HOMEBREW_LIBRARY_PATH/"dev-cmd/#{cmd}.rb" <add> end <add> end <add>end <ide><path>Library/Homebrew/test/test_commands.rb <ide> def test_external_commands <ide> <ide> def test_internal_command_path <ide> assert_equal HOMEBREW_LIBRARY_PATH/"cmd/rbcmd.rb", <del> Homebrew.send(:internal_command_path, "rbcmd") <add> Commands.path("rbcmd") <ide> assert_equal HOMEBREW_LIBRARY_PATH/"cmd/shcmd.sh", <del> Homebrew.send(:internal_command_path, "shcmd") <del> assert_nil Homebrew.send(:internal_command_path, "idontexist1234") <add> Commands.path("shcmd") <add> assert_nil Commands.path("idontexist1234") <ide> end <ide> <ide> def test_internal_dev_command_path <ide> assert_equal HOMEBREW_LIBRARY_PATH/"dev-cmd/rbdevcmd.rb", <del> Homebrew.send(:internal_command_path, "rbdevcmd") <add> Commands.path("rbdevcmd") <ide> assert_equal HOMEBREW_LIBRARY_PATH/"dev-cmd/shdevcmd.sh", <del> Homebrew.send(:internal_command_path, "shdevcmd") <add> Commands.path("shdevcmd") <ide> end <ide> end
2
Javascript
Javascript
improve asyncresource performance
d3d4e10107a594a758baf2cd5e2c1258671e58c5
<ide><path>lib/async_hooks.js <ide> const { <ide> emitBefore, <ide> emitAfter, <ide> emitDestroy, <add> initHooksExist, <ide> } = internal_async_hooks; <ide> <ide> // Get symbols <ide> class AsyncResource { <ide> throw new ERR_INVALID_ASYNC_ID('triggerAsyncId', triggerAsyncId); <ide> } <ide> <del> this[async_id_symbol] = newAsyncId(); <add> const asyncId = newAsyncId(); <add> this[async_id_symbol] = asyncId; <ide> this[trigger_async_id_symbol] = triggerAsyncId; <add> <ide> // This prop name (destroyed) has to be synchronized with C++ <del> this[destroyedSymbol] = { destroyed: false }; <add> const destroyed = { destroyed: false }; <add> this[destroyedSymbol] = destroyed; <ide> <del> emitInit( <del> this[async_id_symbol], type, this[trigger_async_id_symbol], this <del> ); <add> if (initHooksExist()) { <add> emitInit(asyncId, type, triggerAsyncId, this); <add> } <ide> <ide> if (!opts.requireManualDestroy) { <del> registerDestroyHook(this, this[async_id_symbol], this[destroyedSymbol]); <add> registerDestroyHook(this, asyncId, destroyed); <ide> } <ide> } <ide> <ide> runInAsyncScope(fn, thisArg, ...args) { <del> emitBefore(this[async_id_symbol], this[trigger_async_id_symbol]); <del> let ret; <add> const asyncId = this[async_id_symbol]; <add> emitBefore(asyncId, this[trigger_async_id_symbol]); <ide> try { <del> ret = Reflect.apply(fn, thisArg, args); <add> return Reflect.apply(fn, thisArg, args); <ide> } finally { <del> emitAfter(this[async_id_symbol]); <add> emitAfter(asyncId); <ide> } <del> return ret; <ide> } <ide> <ide> emitDestroy() { <ide><path>lib/internal/async_hooks.js <ide> function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) { <ide> const oldDefaultTriggerAsyncId = async_id_fields[kDefaultTriggerAsyncId]; <ide> async_id_fields[kDefaultTriggerAsyncId] = triggerAsyncId; <ide> <del> let ret; <ide> try { <del> ret = Reflect.apply(block, null, args); <add> return Reflect.apply(block, null, args); <ide> } finally { <ide> async_id_fields[kDefaultTriggerAsyncId] = oldDefaultTriggerAsyncId; <ide> } <del> <del> return ret; <ide> } <ide> <ide>
2
Text
Text
add todomvc instructions
cf37fdf578c107bf81ebc8994603be3f47958c3d
<ide><path>README.md <ide> Atomic Flux with hot reloading. <ide> - [Why another Flux framework?](#why-another-flux-framework) <ide> - [Philosophy & Design Goals](#philosophy--design-goals) <ide> - [Demo](#demo) <add>- [Running TodoMVC](#running-todomvc) <ide> - [What does it look like?](#what-does-it-look-like) <ide> - [Actions](#actions) <ide> - [Stores](#stores) <ide> Read **[The Evolution of Flux Frameworks](https://medium.com/@dan_abramov/the-ev <ide> <ide> <img src='https://s3.amazonaws.com/f.cl.ly/items/2Z2D3U260d2A311k2B0z/Screen%20Recording%202015-06-03%20at%2003.22%20pm.gif' width='500'> <ide> <add>## Running TodoMVC <add> <ide> ``` <ide> git clone https://github.com/gaearon/redux.git redux <add> <ide> cd redux <ide> npm install <add> <add>cd examples/todomvc <add>npm install <ide> npm start <ide> ``` <ide>
1
Ruby
Ruby
install build deps for `--head`
cb78499cd4b96fa00b51d235e0dd2ea61ec20336
<ide><path>Library/Homebrew/formula_installer.rb <ide> def expand_dependencies <ide> <ide> keep_build_test = false <ide> keep_build_test ||= dep.test? && include_test? && @include_test_formulae.include?(dependent.full_name) <del> keep_build_test ||= dep.build? && !install_bottle_for?(dependent, build) && !dependent.latest_version_installed? <add> keep_build_test ||= dep.build? && !install_bottle_for?(dependent, build) && (formula.head? || !dependent.latest_version_installed?) <ide> <ide> if dep.prune_from_option?(build) || ((dep.build? || dep.test?) && !keep_build_test) <ide> Dependency.prune
1
Javascript
Javascript
expose module wrapper to native modules
5342e3e925652fdd52da05f98768ac63b4fe7e7b
<ide><path>src/node.js <ide> <ide> var internalModuleCache = {}; <ide> <add> var moduleWrapper = <add> ['(function (exports, require, module, __filename, __dirname) { ', <add> '\n});']; <add> <add> <ide> // This contains the source code for the files in lib/ <ide> // Like, natives.fs is the contents of lib/fs.js <ide> var natives = process.binding('natives'); <ide> <ide> // Native modules don't need a full require function. So we can bootstrap <ide> // most of the system with this mini-require. <ide> function requireNative(id) { <add> if (id == 'module') return module; <ide> if (internalModuleCache[id]) return internalModuleCache[id].exports; <ide> if (!natives[id]) throw new Error('No such native module ' + id); <ide> <add> var filename = id + '.js'; <add> <ide> var fn = runInThisContext( <del> '(function (module, exports, require) {' + natives[id] + '\n})', <del> id + '.js', <add> moduleWrapper[0] + natives[id] + moduleWrapper[1], <add> filename, <ide> true); <ide> var m = {id: id, exports: {}}; <del> fn(m, m.exports, requireNative); <add> fn(m.exports, requireNative, m, filename); <ide> m.loaded = true; <ide> internalModuleCache[id] = m; <ide> return m.exports; <ide> <ide> } else { <ide> // create wrapper function <del> var wrapper = <del> '(function (exports, require, module, __filename, __dirname) { ' + <del> content + <del> '\n});'; <add> var wrapper = moduleWrapper[0] + content + moduleWrapper[1]; <ide> <ide> var compiledWrapper = runInThisContext(wrapper, filename, true); <ide> if (filename === process.argv[1] && global.v8debug) { <ide> } <ide> }; <ide> <add> exports.wrapper = moduleWrapper; <ide> <ide> // Native extension for .js <ide> extensions['.js'] = function(module, filename) {
1
Ruby
Ruby
fix use of search_tap method
b2a291529d0878a51e3e082c3668c54abdbff6c1
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_formula_name <ide> same_name_tap_formulae = @@local_official_taps_name_map[name] || [] <ide> <ide> if @online <del> @@remote_official_taps ||= OFFICIAL_TAPS - Tap.select(&:official?).map(&:repo) <del> <del> same_name_tap_formulae += @@remote_official_taps.map do |tap| <del> Thread.new { Homebrew.search_tap "homebrew", tap, name } <del> end.flat_map(&:value) <add> Homebrew.search_taps(name).each do |tap_formula_full_name| <add> tap_formula_name = tap_formula_full_name.split("/").last <add> next if tap_formula_name != name <add> same_name_tap_formulae << tap_formula_full_name <add> end <ide> end <ide> <ide> same_name_tap_formulae.delete(full_name)
1
Javascript
Javascript
add a todo
00bacbec2575ccb590ac0433996f1c8bb3adde07
<ide><path>test/hotCases/lazy-compilation/context/index.js <add>// TODO: Why is this giving "No tests exported by test case"? <ide> it("should compile to lazy imported context", done => { <ide> const req = require.context("./modules", /^\.\/.*\.js$/); <ide> const result = req("./demo"); <ide> <del> expect(result).toBe(42); <del> <del> done(); <add> // It's not clear why timeout would be needed now since req is a sync call <add> setTimeout(() => { <add> expect(result).toBe(42); <add> done(); <add> }, 1000); <ide> });
1
Javascript
Javascript
remove unused function argument
ab4b632dbf37024783428c10b0b847d15bc1d75f
<ide><path>src/ngMessages/messages.js <ide> angular.module('ngMessages', []) <ide> }); <ide> } <ide> }, <del> detach: function(now) { <add> detach: function() { <ide> if (element) { <ide> $animate.leave(element); <ide> element = null;
1
PHP
PHP
apply fixes from styleci
a66989e565a88ee4c1a72b5acfb44d95161d98d0
<ide><path>src/Illuminate/Broadcasting/BroadcastManager.php <ide> namespace Illuminate\Broadcasting; <ide> <ide> use Closure; <del>use Illuminate\Contracts\Foundation\CachesRoutes; <ide> use Illuminate\Broadcasting\Broadcasters\LogBroadcaster; <ide> use Illuminate\Broadcasting\Broadcasters\NullBroadcaster; <ide> use Illuminate\Broadcasting\Broadcasters\PusherBroadcaster; <ide> use Illuminate\Broadcasting\Broadcasters\RedisBroadcaster; <ide> use Illuminate\Contracts\Broadcasting\Factory as FactoryContract; <ide> use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow; <add>use Illuminate\Contracts\Foundation\CachesRoutes; <ide> use InvalidArgumentException; <ide> use Psr\Log\LoggerInterface; <ide> use Pusher\Pusher; <ide><path>src/Illuminate/Foundation/Application.php <ide> use Closure; <ide> use Illuminate\Container\Container; <ide> use Illuminate\Contracts\Foundation\Application as ApplicationContract; <add>use Illuminate\Contracts\Foundation\CachesConfiguration; <add>use Illuminate\Contracts\Foundation\CachesRoutes; <ide> use Illuminate\Contracts\Http\Kernel as HttpKernelContract; <ide> use Illuminate\Events\EventServiceProvider; <ide> use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\Foundation\Bootstrap\LoadEnvironmentVariables; <ide> use Illuminate\Http\Request; <ide> use Illuminate\Log\LogServiceProvider; <ide> use Illuminate\Routing\RoutingServiceProvider; <del>use Illuminate\Contracts\Foundation\CachesRoutes; <del>use Illuminate\Contracts\Foundation\CachesConfiguration; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Collection; <ide> use Illuminate\Support\Env; <ide><path>src/Illuminate/Support/ServiceProvider.php <ide> namespace Illuminate\Support; <ide> <ide> use Illuminate\Console\Application as Artisan; <add>use Illuminate\Contracts\Foundation\CachesConfiguration; <ide> use Illuminate\Contracts\Foundation\CachesRoutes; <ide> use Illuminate\Contracts\Support\DeferrableProvider; <del>use Illuminate\Contracts\Foundation\CachesConfiguration; <ide> <ide> abstract class ServiceProvider <ide> { <ide><path>src/Illuminate/Validation/Concerns/ValidatesAttributes.php <ide> namespace Illuminate\Validation\Concerns; <ide> <ide> use Countable; <del>use Exception; <ide> use DateTime; <ide> use DateTimeInterface; <ide> use Egulias\EmailValidator\EmailValidator; <ide> use Egulias\EmailValidator\Validation\NoRFCWarningsValidation; <ide> use Egulias\EmailValidator\Validation\RFCValidation; <ide> use Egulias\EmailValidator\Validation\SpoofCheckValidation; <add>use Exception; <ide> use Illuminate\Support\Arr; <ide> use Illuminate\Support\Carbon; <ide> use Illuminate\Support\Facades\Date;
4
Text
Text
simplify challenge "access props using this.props"
409399c272a92cf47c369c1bce5b04cc5b78d8ce
<ide><path>curriculum/challenges/english/03-front-end-development-libraries/react/access-props-using-this.props.md <ide> Anytime you refer to a class component within itself, you use the `this` keyword <ide> <ide> # --instructions-- <ide> <del>Render an instance of the `ReturnTempPassword` component in the parent component `ResetPassword`. Here, give `ReturnTempPassword` a prop of `tempPassword` and assign it a value of a string that is at least 8 characters long. Within the child, `ReturnTempPassword`, access the `tempPassword` prop within the `strong` tags to make sure the user sees the temporary password. <add>Render an instance of the `Welcome` component in the parent component `App`. Here, give `Welcome` a prop of `name` and assign it a value of a string. Within the child, `Welcome`, access the `name` prop within the `strong` tags. <ide> <ide> # --hints-- <ide> <del>The `ResetPassword` component should return a single `div` element. <add>The `App` component should return a single `div` element. <ide> <ide> ```js <ide> assert( <ide> (function () { <del> const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); <add> const mockedComponent = Enzyme.mount(React.createElement(App)); <ide> return mockedComponent.children().type() === 'div'; <ide> })() <ide> ); <ide> ``` <ide> <del>The fourth child of `ResetPassword` should be the `ReturnTempPassword` component. <add>The child of `App` should be the `Welcome` component. <ide> <ide> ```js <ide> assert( <ide> (function () { <del> const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); <add> const mockedComponent = Enzyme.mount(React.createElement(App)); <ide> return ( <del> mockedComponent.children().childAt(3).name() === 'ReturnTempPassword' <add> mockedComponent.children().childAt(0).name() === 'Welcome' <ide> ); <ide> })() <ide> ); <ide> ``` <ide> <del>The `ReturnTempPassword` component should have a prop called `tempPassword`. <add>The `Welcome` component should have a prop called `name`. <ide> <ide> ```js <ide> assert( <ide> (function () { <del> const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); <del> return mockedComponent.find('ReturnTempPassword').props().tempPassword; <add> const mockedComponent = Enzyme.mount(React.createElement(App)); <add> return mockedComponent.find('Welcome').props().name; <ide> })() <ide> ); <ide> ``` <ide> <del>The `tempPassword` prop of `ReturnTempPassword` should be equal to a string of at least 8 characters. <add>The `Welcome` component should display the string you pass as the `name` prop within `strong` tags. <ide> <ide> ```js <ide> assert( <ide> (function () { <del> const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); <del> const temp = mockedComponent.find('ReturnTempPassword').props() <del> .tempPassword; <del> return typeof temp === 'string' && temp.length >= 8; <del> })() <del>); <del>``` <del> <del>The `ReturnTempPassword` component should display the password you create as the `tempPassword` prop within `strong` tags. <del> <del>```js <del>assert( <del> (function () { <del> const mockedComponent = Enzyme.mount(React.createElement(ResetPassword)); <add> const mockedComponent = Enzyme.mount(React.createElement(App)); <ide> return ( <ide> mockedComponent.find('strong').text() === <del> mockedComponent.find('ReturnTempPassword').props().tempPassword <add> mockedComponent.find('Welcome').props().name <ide> ); <ide> })() <ide> ); <ide> assert( <ide> ## --after-user-code-- <ide> <ide> ```jsx <del>ReactDOM.render(<ResetPassword />, document.getElementById('root')) <add>ReactDOM.render(<App />, document.getElementById('root')) <ide> ``` <ide> <ide> ## --seed-contents-- <ide> <ide> ```jsx <del>class ReturnTempPassword extends React.Component { <add>class App extends React.Component { <ide> constructor(props) { <ide> super(props); <ide> <ide> class ReturnTempPassword extends React.Component { <ide> return ( <ide> <div> <ide> { /* Change code below this line */ } <del> <p>Your temporary password is: <strong></strong></p> <add> <Welcome /> <ide> { /* Change code above this line */ } <ide> </div> <ide> ); <ide> } <ide> }; <ide> <del>class ResetPassword extends React.Component { <add>class Welcome extends React.Component { <ide> constructor(props) { <ide> super(props); <ide> <ide> } <ide> render() { <ide> return ( <ide> <div> <del> <h2>Reset Password</h2> <del> <h3>We've generated a new temporary password for you.</h3> <del> <h3>Please reset this password from your account settings ASAP.</h3> <ide> { /* Change code below this line */ } <del> <add> <p>Hello, <strong></strong>!</p> <ide> { /* Change code above this line */ } <ide> </div> <ide> ); <ide> class ResetPassword extends React.Component { <ide> # --solutions-- <ide> <ide> ```jsx <del>class ReturnTempPassword extends React.Component { <add>class Welcome extends React.Component { <ide> constructor(props) { <ide> super(props); <ide> <ide> } <ide> render() { <ide> return ( <ide> <div> <del> <p>Your temporary password is: <strong>{this.props.tempPassword}</strong></p> <add> { /* Change code below this line */ } <add> <p>Hello, <strong>{this.props.name}</strong>!</p> <add> { /* Change code above this line */ } <ide> </div> <ide> ); <ide> } <ide> }; <ide> <del>class ResetPassword extends React.Component { <add>class App extends React.Component { <ide> constructor(props) { <ide> super(props); <ide> <ide> } <ide> render() { <ide> return ( <ide> <div> <del> <h2>Reset Password</h2> <del> <h3>We've generated a new temporary password for you.</h3> <del> <h3>Please reset this password from your account settings ASAP.</h3> <del> { /* Change code below this line */ } <del> <ReturnTempPassword tempPassword="serrPbqrPnzc" /> <del> { /* Change code above this line */ } <add> { /* Change code below this line */ } <add> <Welcome name="Quincy"/> <add> { /* Change code above this line */ } <ide> </div> <ide> ); <ide> }
1
Text
Text
remove eslint config link
f3659a5f931bec0e619ccabd678ab0cfdcf323ce
<ide><path>docs/basic-features/eslint.md <ide> Recommended rule-sets from the following ESLint plugins are all used within `esl <ide> - [`eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks) <ide> - [`eslint-plugin-next`](https://www.npmjs.com/package/@next/eslint-plugin-next) <ide> <del>You can see the full details of the shareable configuration in the [`eslint-config-next`](https://www.npmjs.com/package/eslint-config-next) package. <del> <ide> This will take precedence over the configuration from `next.config.js`. <ide> <ide> ## ESLint Plugin
1
Javascript
Javascript
drop internal uses of .type on the class
9b36b04d75b59a4e0d155735b9ea60ee5fe00afb
<ide><path>src/core/ReactNativeComponent.js <ide> function createInstanceForTag(tag, props, parentType) { <ide> return new genericComponentClass(tag, props); <ide> } <ide> // Unwrap legacy factories <del> return new componentClass.type(props); <add> return new componentClass(props); <ide> } <ide> <ide> var ReactNativeComponent = { <ide><path>src/core/__tests__/ReactCompositeComponent-test.js <ide> describe('ReactCompositeComponent', function() { <ide> expect(Component.ghi).toBe(null); <ide> expect(instance.constructor.jkl).toBe('mno'); <ide> expect(Component.jkl).toBe('mno'); <del> expect(instance.constructor.pqr()).toBe(Component.type); <del> expect(Component.pqr()).toBe(Component.type); <add> expect(instance.constructor.pqr()).toBe(Component); <add> expect(Component.pqr()).toBe(Component); <ide> }); <ide> <ide> it('should throw if a reserved property is in statics', function() { <ide><path>src/core/__tests__/ReactCompositeComponentMixin-test.js <ide> describe('ReactCompositeComponent-mixin', function() { <ide> }); <ide> <ide> it('should validate prop types via mixins', function() { <del> expect(TestComponent.type.propTypes).toBeDefined(); <del> expect(TestComponent.type.propTypes.value) <add> expect(TestComponent.propTypes).toBeDefined(); <add> expect(TestComponent.propTypes.value) <ide> .toBe(mixinPropValidator); <ide> }); <ide> <ide> it('should override mixin prop types with class prop types', function() { <ide> // Sanity check... <ide> expect(componentPropValidator).toNotBe(mixinPropValidator); <ide> // Actually check... <del> expect(TestComponentWithPropTypes.type.propTypes) <add> expect(TestComponentWithPropTypes.propTypes) <ide> .toBeDefined(); <del> expect(TestComponentWithPropTypes.type.propTypes.value) <add> expect(TestComponentWithPropTypes.propTypes.value) <ide> .toNotBe(mixinPropValidator); <del> expect(TestComponentWithPropTypes.type.propTypes.value) <add> expect(TestComponentWithPropTypes.propTypes.value) <ide> .toBe(componentPropValidator); <ide> }); <ide> }); <ide><path>src/core/__tests__/ReactCompositeComponentSpec-test.js <ide> describe('ReactCompositeComponent-spec', function() { <ide> } <ide> }); <ide> <del> expect(TestComponent.type.displayName) <add> expect(TestComponent.displayName) <ide> .toBe('TestComponent'); <ide> }); <ide> <ide> describe('ReactCompositeComponent-spec', function() { <ide> } <ide> }); <ide> <del> expect(TestComponent.type.propTypes).toBeDefined(); <del> expect(TestComponent.type.propTypes.value) <add> expect(TestComponent.propTypes).toBeDefined(); <add> expect(TestComponent.propTypes.value) <ide> .toBe(propValidator); <ide> }); <ide> }); <ide><path>src/core/__tests__/ReactElement-test.js <ide> describe('ReactElement', function() { <ide> ComponentFactory = React.createClass({ <ide> render: function() { return <div />; } <ide> }); <del> ComponentClass = ComponentFactory.type; <add> ComponentClass = ComponentFactory; <ide> }); <ide> <ide> it('returns a complete element according to spec', function() { <ide> describe('ReactElement', function() { <ide> expect(ReactElement.isValidElement(Component)).toEqual(false); <ide> }); <ide> <del> it('should expose the underlying class from a legacy factory', function() { <del> var Legacy = React.createClass({ render: function() { } }); <del> var factory = React.createFactory(Legacy); <del> expect(factory.type).toBe(Legacy.type); <del> expect(factory().type).toBe(Legacy.type); <del> }); <del> <ide> it('allows the use of PropTypes validators in statics', function() { <ide> var Component = React.createClass({ <ide> render: () => null, <ide><path>src/test/reactComponentExpect.js <ide> assign(reactComponentExpect.prototype, { <ide> <ide> // Matchers ------------------------------------------------------------------ <ide> <del> toBeComponentOfType: function(convenienceConstructor) { <del> var type = typeof convenienceConstructor === 'string' ? <del> convenienceConstructor : <del> convenienceConstructor.type; <add> toBeComponentOfType: function(constructor) { <ide> expect( <del> this.instance()._currentElement.type === type <add> this.instance()._currentElement.type === constructor <ide> ).toBe(true); <ide> return this; <ide> }, <ide> assign(reactComponentExpect.prototype, { <ide> return this; <ide> }, <ide> <del> toBeCompositeComponentWithType: function(convenienceConstructor) { <add> toBeCompositeComponentWithType: function(constructor) { <ide> this.toBeCompositeComponent(); <ide> expect( <del> this.instance()._currentElement.type === convenienceConstructor.type <add> this.instance()._currentElement.type === constructor <ide> ).toBe(true); <ide> return this; <ide> },
6
Go
Go
add buildinfo for buildkit
fda0226a890b9948a754c48fc3ad5f6e02f43f40
<ide><path>builder/builder-next/adapters/containerimage/pull.go <ide> func (p *puller) CacheKey(ctx context.Context, g session.Group, index int) (stri <ide> if err != nil { <ide> return "", "", nil, false, err <ide> } <del> return dgst.String(), dgst.String(), nil, false, nil <add> return dgst.String(), p.desc.Digest.String(), nil, false, nil <ide> } <ide> <ide> if p.config != nil { <ide> func (p *puller) CacheKey(ctx context.Context, g session.Group, index int) (stri <ide> if err != nil { <ide> return "", "", nil, false, err <ide> } <del> return dgst.String(), dgst.String(), nil, false, nil <add> return dgst.String(), p.desc.Digest.String(), nil, false, nil <ide> } <ide> <ide> if len(p.config) == 0 && p.desc.MediaType != images.MediaTypeDockerSchema1Manifest { <ide> func (p *puller) CacheKey(ctx context.Context, g session.Group, index int) (stri <ide> if err != nil { <ide> return "", "", nil, false, err <ide> } <del> return dgst.String(), dgst.String(), nil, true, nil <add> return dgst.String(), p.desc.Digest.String(), nil, true, nil <ide> } <ide> <del> return k, "", nil, true, nil <add> return k, k, nil, true, nil <ide> } <ide> <ide> func (p *puller) getRef(ctx context.Context, diffIDs []layer.DiffID, opts ...cache.RefOption) (cache.ImmutableRef, error) { <ide><path>builder/builder-next/exporter/export.go <ide> import ( <ide> "context" <ide> "encoding/json" <ide> "fmt" <add> "strconv" <ide> "strings" <ide> <ide> distref "github.com/docker/distribution/reference" <ide> import ( <ide> ) <ide> <ide> const ( <del> keyImageName = "name" <add> keyImageName = "name" <add> keyBuildInfo = "buildinfo" <add> keyBuildInfoAttrs = "buildinfo-attrs" <ide> ) <ide> <ide> // Differ can make a moby layer from a snapshot <ide> func New(opt Opt) (exporter.Exporter, error) { <ide> } <ide> <ide> func (e *imageExporter) Resolve(ctx context.Context, opt map[string]string) (exporter.ExporterInstance, error) { <del> i := &imageExporterInstance{imageExporter: e} <add> i := &imageExporterInstance{ <add> imageExporter: e, <add> buildInfo: true, <add> } <ide> for k, v := range opt { <ide> switch k { <ide> case keyImageName: <ide> i.targetName = v <add> case keyBuildInfo: <add> if v == "" { <add> i.buildInfo = true <add> continue <add> } <add> b, err := strconv.ParseBool(v) <add> if err != nil { <add> return nil, errors.Wrapf(err, "non-bool value specified for %s", k) <add> } <add> i.buildInfo = b <add> case keyBuildInfoAttrs: <add> if v == "" { <add> i.buildInfoAttrs = false <add> continue <add> } <add> b, err := strconv.ParseBool(v) <add> if err != nil { <add> return nil, errors.Wrapf(err, "non-bool value specified for %s", k) <add> } <add> i.buildInfoAttrs = b <ide> default: <ide> if i.meta == nil { <ide> i.meta = make(map[string][]byte) <ide> func (e *imageExporter) Resolve(ctx context.Context, opt map[string]string) (exp <ide> <ide> type imageExporterInstance struct { <ide> *imageExporter <del> targetName string <del> meta map[string][]byte <add> targetName string <add> meta map[string][]byte <add> buildInfo bool <add> buildInfoAttrs bool <ide> } <ide> <ide> func (e *imageExporterInstance) Name() string { <ide> func (e *imageExporterInstance) Export(ctx context.Context, inp exporter.Source, <ide> } <ide> <ide> var config []byte <add> var buildInfo []byte <ide> switch len(inp.Refs) { <ide> case 0: <ide> config = inp.Metadata[exptypes.ExporterImageConfigKey] <add> if v, ok := inp.Metadata[exptypes.ExporterBuildInfo]; ok { <add> buildInfo = v <add> } <ide> case 1: <ide> platformsBytes, ok := inp.Metadata[exptypes.ExporterPlatformsKey] <ide> if !ok { <ide> func (e *imageExporterInstance) Export(ctx context.Context, inp exporter.Source, <ide> return nil, errors.Errorf("number of platforms does not match references %d %d", len(p.Platforms), len(inp.Refs)) <ide> } <ide> config = inp.Metadata[fmt.Sprintf("%s/%s", exptypes.ExporterImageConfigKey, p.Platforms[0].ID)] <add> if v, ok := inp.Metadata[fmt.Sprintf("%s/%s", exptypes.ExporterBuildInfo, p.Platforms[0].ID)]; ok { <add> buildInfo = v <add> } <ide> } <ide> <ide> var diffs []digest.Digest <ide> func (e *imageExporterInstance) Export(ctx context.Context, inp exporter.Source, <ide> <ide> diffs, history = normalizeLayersAndHistory(diffs, history, ref) <ide> <del> config, err = patchImageConfig(config, diffs, history, inp.Metadata[exptypes.ExporterInlineCache]) <add> config, err = patchImageConfig(config, diffs, history, inp.Metadata[exptypes.ExporterInlineCache], buildInfo) <ide> if err != nil { <ide> return nil, err <ide> } <ide><path>builder/builder-next/exporter/writer.go <ide> import ( <ide> <ide> "github.com/containerd/containerd/platforms" <ide> "github.com/moby/buildkit/cache" <add> binfotypes "github.com/moby/buildkit/util/buildinfo/types" <ide> "github.com/moby/buildkit/util/progress" <ide> "github.com/moby/buildkit/util/system" <ide> "github.com/opencontainers/go-digest" <ide> func parseHistoryFromConfig(dt []byte) ([]ocispec.History, error) { <ide> return config.History, nil <ide> } <ide> <del>func patchImageConfig(dt []byte, dps []digest.Digest, history []ocispec.History, cache []byte) ([]byte, error) { <add>func patchImageConfig(dt []byte, dps []digest.Digest, history []ocispec.History, cache []byte, buildInfo []byte) ([]byte, error) { <ide> m := map[string]json.RawMessage{} <ide> if err := json.Unmarshal(dt, &m); err != nil { <ide> return nil, errors.Wrap(err, "failed to parse image config for patch") <ide> func patchImageConfig(dt []byte, dps []digest.Digest, history []ocispec.History, <ide> } <ide> <ide> if cache != nil { <del> dt, err = json.Marshal(cache) <add> dt, err := json.Marshal(cache) <ide> if err != nil { <del> return nil, errors.Wrap(err, "failed to marshal cache") <add> return nil, err <ide> } <ide> m["moby.buildkit.cache.v0"] = dt <ide> } <ide> <add> if buildInfo != nil { <add> dt, err := json.Marshal(buildInfo) <add> if err != nil { <add> return nil, err <add> } <add> m[binfotypes.ImageConfigField] = dt <add> } else { <add> delete(m, binfotypes.ImageConfigField) <add> } <add> <ide> dt, err = json.Marshal(m) <ide> return dt, errors.Wrap(err, "failed to marshal config after patch") <ide> }
3
Ruby
Ruby
handle syntax errors in formulae
d3c8e2f9cb78b5b78f95729e8c60fb5ad6daf90d
<ide><path>Library/Contributions/cmd/brew-pull.rb <ide> def tap arg <ide> status, filename = line.split <ide> # Don't try and do anything to removed files. <ide> if (status =~ /A|M/) && (filename =~ %r{Formula/.+\.rb$}) || tap(url) <del> formula = File.basename(filename, '.rb') <del> changed_formulae << Formula.factory(formula) <add> formula_name = File.basename(filename, '.rb') <add> formula = Formula[formula_name] rescue nil <add> next unless formula <add> changed_formulae << formula <ide> end <ide> end <ide>
1
PHP
PHP
add bus alias
a80e5bca0b36e2377b884772c560f7c871d0bf1f
<ide><path>config/app.php <ide> 'Artisan' => Illuminate\Support\Facades\Artisan::class, <ide> 'Auth' => Illuminate\Support\Facades\Auth::class, <ide> 'Blade' => Illuminate\Support\Facades\Blade::class, <add> 'Bus' => Illuminate\Support\Facades\Bus::class, <ide> 'Cache' => Illuminate\Support\Facades\Cache::class, <ide> 'Config' => Illuminate\Support\Facades\Config::class, <ide> 'Cookie' => Illuminate\Support\Facades\Cookie::class,
1
Javascript
Javascript
remove valid hostname check in test-dns.js
a1949e8ad9483609fd450f8cc21cc2dca703259e
<ide><path>test/common.js <ide> exports.hasMultiLocalhost = function hasMultiLocalhost() { <ide> return ret === 0; <ide> }; <ide> <del>exports.isValidHostname = function(str) { <del> // See http://stackoverflow.com/a/3824105 <del> var re = new RegExp( <del> '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])' + <del> '(\\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9]))*$'); <del> <del> return !!str.match(re) && str.length <= 255; <del>}; <del> <ide> exports.fileExists = function(pathname) { <ide> try { <ide> fs.accessSync(pathname); <ide><path>test/internet/test-dns.js <ide> TEST(function test_lookup_all_mixed(done) { <ide> TEST(function test_lookupservice_ip_ipv4(done) { <ide> var req = dns.lookupService('127.0.0.1', 80, function(err, host, service) { <ide> if (err) throw err; <del> assert.ok(common.isValidHostname(host)); <add> assert.equal(typeof host, 'string'); <add> assert(host); <ide> <ide> /* <ide> * Retrieve the actual HTTP service name as setup on the host currently <ide> TEST(function test_lookupservice_ip_ipv4(done) { <ide> TEST(function test_lookupservice_ip_ipv6(done) { <ide> var req = dns.lookupService('::1', 80, function(err, host, service) { <ide> if (err) throw err; <del> assert.ok(common.isValidHostname(host)); <add> assert.equal(typeof host, 'string'); <add> assert(host); <ide> <ide> /* <ide> * Retrieve the actual HTTP service name as setup on the host currently
2
Python
Python
update data url
82af172ffc51a99966dae984ef51dd5e7bffcb66
<ide><path>tutorials/image/cifar10/cifar10.py <ide> # names of the summaries when visualizing a model. <ide> TOWER_NAME = 'tower' <ide> <del>DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz' <add>DATA_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz' <ide> <ide> <ide> def _activation_summary(x):
1
Text
Text
add note about variable naming
b763e9b66d1d578b71397c17888f16e9ac485194
<ide><path>CONTRIBUTING.md <ide> At the time of writing (v1.7), spaCy's serialization and deserialization functio <ide> <ide> Although spaCy uses a lot of classes, inheritance is viewed with some suspicion — it's seen as a mechanism of last resort. You should discuss plans to extend the class hierarchy before implementing. <ide> <add>We have a number of conventions around variable naming that are still being documented, and aren't 100% strict. A general policy is that instances of the class `Doc` should by default be called `doc`, `Token` `token`, `Lexeme` `lex`, `Vocab` `vocab` and `Language` `nlp`. You should avoid naming variables that are of other types these names. For instance, don't name a text string `doc` --- you should usually call this `text`. Two general code style preferences further help with naming. First, lean away from introducing temporary variables, as these clutter your namespace. This is one reason why comprehension expressions are often preferred. Second, keep your functions shortish, so that can work in a smaller scope. Of course, this is a question of trade-offs. <add> <ide> ### Cython conventions <ide> <ide> spaCy's core data structures are implemented as [Cython](http://cython.org/) `cdef` classes. Memory is managed through the `cymem.cymem.Pool` class, which allows you to allocate memory which will be freed when the `Pool` object is garbage collected. This means you usually don't have to worry about freeing memory. You just have to decide which Python object owns the memory, and make it own the `Pool`. When that object goes out of scope, the memory will be freed. You do have to take care that no pointers outlive the object that owns them — but this is generally quite easy.
1
PHP
PHP
update doc block
fc8fb360283df84d57b1be22554d9661b509f362
<ide><path>src/Datasource/EntityInterface.php <ide> public function clean(); <ide> * This method can return null in the case there is no prior information on <ide> * the status of this entity. <ide> * <del> * If called with a boolean it will set the known status of this instance, <del> * true means that the instance is not yet persisted in the database, false <add> * If called with a boolean, this method will set the status of this instance. <add> * Using `true` means that the instance has not been persisted in the database, `false` <ide> * that it already is. <ide> * <del> * @param bool $new true if it is known this instance was persisted <del> * @return bool if it is known whether the entity was already persisted <add> * @param bool|null $new Indicate whether or not this instance has been persisted. <add> * @return bool If it is known whether the entity was already persisted <ide> * null otherwise <ide> */ <ide> public function isNew($new = null);
1
PHP
PHP
use cleaner api for plugin loaded info
23bcb93872d3ad2ee919edbe8c4f43425092c49d
<ide><path>src/Core/Plugin.php <ide> */ <ide> namespace Cake\Core; <ide> <del>use Cake\Core\Exception\MissingPluginException; <add>use ArgumentCountError; <ide> use DirectoryIterator; <ide> <ide> /** <ide> public static function bootstrap(string $name): void <ide> } <ide> <ide> /** <del> * Check whether or not a plugin is loaded. <add> * Returns true if the plugin $plugin is already loaded. <ide> * <del> * @param string $plugin The name of the plugin to check. <add> * @param string $plugin Plugin name. <ide> * @return bool <ide> */ <del> public static function isLoaded($plugin) <add> public static function isLoaded(string $plugin): bool <ide> { <ide> return static::getCollection()->has($plugin); <ide> } <ide> <ide> /** <del> * Return a list of loaded plugins. <add> * Returns a list of all loaded plugins. <ide> * <del> * @return bool|array Boolean true if $plugin is already loaded. <del> * If $plugin is null, returns a list of plugins that have been loaded <add> * @return array <ide> */ <del> public static function loaded() <add> public static function loaded(): array <ide> { <ide> $names = []; <ide> foreach (static::getCollection() as $plugin) {
1
Javascript
Javascript
fix default prop [ci skip]
3379ebcaa405d3c0f9d4a30f3dc3c7bb5c93a50c
<ide><path>website/src/components/search.js <ide> const Search = ({ id, placeholder, settings }) => { <ide> Search.defaultProps = { <ide> id: 'docsearch', <ide> placeholder: 'Search docs', <add> settings: {}, <ide> } <ide> <ide> Search.propTypes = {
1
Text
Text
add further references
026d73bd8b67f973f833eebad2edf61edf440da9
<ide><path>guide/english/bulma/get-started/index.md <ide> For Bulma to work correctly, you need to make your webpage responsive. <ide> <ide> ### Bulma-start <ide> ```bulma-start``` is a tiny ```npm``` package that includes the npm dependencies you need to build your own website with Bulma. <add> <add>### Further References: <add>- [Bulma Documentation](https://bulma.io/documentation) <add>- [Vue.js based on Bulma](https://buefy.github.io/documentation)
1
Ruby
Ruby
add a broadcasting logger so we can split logs
d42b3d4347547b7790d0a716e7548baccf408076
<ide><path>activesupport/lib/active_support/logger.rb <ide> require 'logger' <ide> <ide> module ActiveSupport <add> # Broadcasts logs to multiple loggers <add> class BroadcastLogger < ::Logger # :nodoc: <add> attr_reader :logs <add> <add> def initialize(logs) <add> super(nil) <add> @logs = logs <add> end <add> <add> def add(severity, message = nil, progname = nil, &block) <add> super <add> logs.each { |l| l.add(severity, message, progname, &block) } <add> end <add> <add> def <<(x) <add> logs.each { |l| l << x } <add> end <add> <add> def close <add> logs.each(&:close) <add> end <add> end <add> <ide> class Logger < ::Logger <ide> def initialize(*args) <ide> super <ide><path>activesupport/test/broadcast_logger_test.rb <add>require 'abstract_unit' <add> <add>module ActiveSupport <add> class BroadcastLoggerTest < TestCase <add> def test_debug <add> log1 = FakeLogger.new <add> log2 = FakeLogger.new <add> <add> logger = BroadcastLogger.new [log1, log2] <add> logger.debug "foo" <add> assert_equal 'foo', log1.adds.first[2] <add> assert_equal 'foo', log2.adds.first[2] <add> end <add> <add> def test_close <add> log1 = FakeLogger.new <add> log2 = FakeLogger.new <add> <add> logger = BroadcastLogger.new [log1, log2] <add> logger.close <add> assert log1.closed, 'should be closed' <add> assert log2.closed, 'should be closed' <add> end <add> <add> def test_chevrons <add> log1 = FakeLogger.new <add> log2 = FakeLogger.new <add> <add> logger = BroadcastLogger.new [log1, log2] <add> logger << "foo" <add> assert_equal %w{ foo }, log1.chevrons <add> assert_equal %w{ foo }, log2.chevrons <add> end <add> <add> class FakeLogger <add> attr_reader :adds, :closed, :chevrons <add> <add> def initialize <add> @adds = [] <add> @closed = false <add> @chevrons = [] <add> end <add> <add> def << x <add> @chevrons << x <add> end <add> <add> def add(*args) <add> @adds << args <add> end <add> <add> def close <add> @closed = true <add> end <add> end <add> end <add>end
2
Text
Text
add conditon to use case structure
f3884d0d2b60b661438c757e48cad9237e151e97
<ide><path>guide/chinese/c/switch/index.md <ide> switch语句就像一组`if statements` 。 <ide> 这是一个可能性列表,每个可能性都有一个动作,以及一个可选的默认动作,以防其他任何事情的评估结果为真。 <ide> <ide> 我们`break`从交换机退出。如果在下一个案例开始之前没有达到`break`语句,则执行将通过并在下一种情况下开始执行代码。 <add>注: switch语句只能使用在char或int这两种类型的数据。 <add> <add>switch (数据类型必须 char or int) <ide> <ide> ## 开关语法...案例 <ide> <ide> switch (n) <ide> * if-else更适合布尔值:If-else条件分支对于导致布尔值的变量条件很有用,而switch语句对于固定数据值很有用。 <ide> * 速度:如果提供的案例数量良好,则可以证明switch语句更快。如果只有少数情况,则无论如何都不会影响速度。如果案例数超过5,则更喜欢切换,否则也可以使用if-else。 <ide> * 如果一个开关包含五个以上的项目,则使用查找表或哈希列表实现。这意味着与if:s列表相比,所有项目都获得相同的访问时间,其中最后一个项目需要更长的时间才能到达,因为它必须首先评估每个先前的条件。 <del>* 可读性清晰:当您需要组合案例时,开关看起来更清晰。如果也很容易出错。错过其他声明会让你陷入混乱。使用开关更轻松地添加/删除标签,使您的代码更易于更改和维护。 <ide>\ No newline at end of file <add>* 可读性清晰:当您需要组合案例时,开关看起来更清晰。如果也很容易出错。错过其他声明会让你陷入混乱。使用开关更轻松地添加/删除标签,使您的代码更易于更改和维护。
1
Javascript
Javascript
change docs to mention `setunknownproperty`
30a6eae2518f7e0181d2705d44a02deaa5bad281
<ide><path>packages/ember-metal/lib/property_set.js <ide> var META_KEY = Ember.META_KEY, <ide> /** <ide> Sets the value of a property on an object, respecting computed properties <ide> and notifying observers and other listeners of the change. If the <del> property is not defined but the object implements the `unknownProperty` <add> property is not defined but the object implements the `setUnknownProperty` <ide> method then that will be invoked as well. <ide> <ide> If you plan to run on IE8 and older browsers then you should use this <ide> var META_KEY = Ember.META_KEY, <ide> <ide> On all newer browsers, you only need to use this method to set <ide> properties if the property might not be defined on the object and you want <del> to respect the `unknownProperty` handler. Otherwise you can ignore this <add> to respect the `setUnknownProperty` handler. Otherwise you can ignore this <ide> method. <ide> <ide> @method set <ide><path>packages/ember-metal/tests/accessors/set_test.js <ide> test('should call setUnknownProperty if defined and value is undefined', functio <ide> count: 0, <ide> <ide> unknownProperty: function(key, value) { <del> ok(false, 'should not invoke unknownProperty is setUnknownProperty is defined'); <add> ok(false, 'should not invoke unknownProperty if setUnknownProperty is defined'); <ide> }, <ide> <ide> setUnknownProperty: function(key, value) { <ide><path>packages/ember-runtime/lib/mixins/observable.js <ide> Ember.Observable = Ember.Mixin.create({ <ide> <ide> This method is generally very similar to calling `object[key] = value` or <ide> `object.key = value`, except that it provides support for computed <del> properties, the `unknownProperty()` method and property observers. <add> properties, the `setUnknownProperty()` method and property observers. <ide> <ide> ### Computed Properties <ide> <ide> Ember.Observable = Ember.Mixin.create({ <ide> ### Unknown Properties <ide> <ide> If you try to set a value on a key that is undefined in the target <del> object, then the `unknownProperty()` handler will be called instead. This <add> object, then the `setUnknownProperty()` handler will be called instead. This <ide> gives you an opportunity to implement complex "virtual" properties that <del> are not predefined on the object. If `unknownProperty()` returns <add> are not predefined on the object. If `setUnknownProperty()` returns <ide> undefined, then `set()` will simply set the value on the object. <ide> <ide> ### Property Observers
3
Text
Text
fix typos on `e.g.` abbreviations
7afe6c728e824021dd3f4863e2d8b867d5b12c7f
<ide><path>doc/api/dns.md <ide> will be present on the object: <ide> | `'PTR'` | `value` | <ide> | `'SOA'` | Refer to [`dns.resolveSoa()`][] | <ide> | `'SRV'` | Refer to [`dns.resolveSrv()`][] | <del>| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dns.resolveTxt()`][], eg. `{ entries: ['...'], type: 'TXT' }` | <add>| `'TXT'` | This type of record contains an array property called `entries` which refers to [`dns.resolveTxt()`][], e.g. `{ entries: ['...'], type: 'TXT' }` | <ide> <ide> Here is an example of the `ret` object passed to the callback: <ide> <ide><path>doc/api/fs.md <ide> by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains <ide> a colon, Node.js will open a file system stream, as described by <ide> [this MSDN page][MSDN-Using-Streams]. <ide> <del>Functions based on `fs.open()` exhibit this behavior as well. eg. <add>Functions based on `fs.open()` exhibit this behavior as well: <ide> `fs.writeFile()`, `fs.readFile()`, etc. <ide> <ide> ## fs.openSync(path, flags[, mode])
2
Ruby
Ruby
add `path` class
a16746906d463ce9e4dc129bc5a76b81585ee1dd
<ide><path>Library/Homebrew/PATH.rb <add>class PATH <add> def initialize(*paths) <add> @paths = parse(*paths) <add> end <add> <add> def prepend(*paths) <add> @paths.unshift(*parse(*paths)) <add> self <add> end <add> <add> def append(*paths) <add> @paths.concat(parse(*paths)) <add> self <add> end <add> <add> def to_ary <add> @paths <add> end <add> alias to_a to_ary <add> <add> def to_str <add> @paths.join(File::PATH_SEPARATOR) <add> end <add> alias to_s to_str <add> <add> def eql?(other) <add> if other.respond_to?(:to_ary) <add> return true if to_ary == other.to_ary <add> end <add> <add> if other.respond_to?(:to_str) <add> return true if to_str == other.to_str <add> end <add> <add> false <add> end <add> alias == eql? <add> <add> def empty? <add> @paths.empty? <add> end <add> <add> def inspect <add> "<PATH##{to_str}>" <add> end <add> <add> def validate <add> self.class.new(@paths.select(&File.method(:directory?))) <add> end <add> <add> private <add> <add> def parse(*paths) <add> paths <add> .flatten <add> .flat_map { |p| p.respond_to?(:to_str) ? p.to_str.split(File::PATH_SEPARATOR): p } <add> .compact <add> .map { |p| p.respond_to?(:to_path) ? p.to_path : p.to_str } <add> .uniq <add> end <add>end <ide><path>Library/Homebrew/global.rb <ide> require "extend/pathname" <ide> require "extend/git_repository" <ide> require "extend/ARGV" <add>require "PATH" <ide> require "extend/string" <ide> require "os" <ide> require "utils" <ide><path>Library/Homebrew/test/PATH_spec.rb <add>require "PATH" <add> <add>describe PATH do <add> describe "#initialize" do <add> it "can take multiple arguments" do <add> expect(described_class.new("/path1", "/path2")).to eq("/path1:/path2") <add> end <add> <add> it "can parse a mix of arrays and arguments" do <add> expect(described_class.new(["/path1", "/path2"], "/path3")).to eq("/path1:/path2:/path3") <add> end <add> <add> it "splits an existing PATH" do <add> expect(described_class.new("/path1:/path2")).to eq(["/path1", "/path2"]) <add> end <add> end <add> <add> describe "#to_ary" do <add> it "returns a PATH array" do <add> expect(described_class.new("/path1", "/path2").to_ary).to eq(["/path1", "/path2"]) <add> end <add> end <add> <add> describe "#to_str" do <add> it "returns a PATH string" do <add> expect(described_class.new("/path1", "/path2").to_str).to eq("/path1:/path2") <add> end <add> end <add> <add> describe "#prepend" do <add> it "prepends a path to a PATH" do <add> expect(described_class.new("/path1").prepend("/path2").to_str).to eq("/path2:/path1") <add> end <add> end <add> <add> describe "#append" do <add> it "prepends a path to a PATH" do <add> expect(described_class.new("/path1").append("/path2").to_str).to eq("/path1:/path2") <add> end <add> end <add> <add> describe "#validate" do <add> it "returns a new PATH without non-existent paths" do <add> allow(File).to receive(:directory?).with("/path1").and_return(true) <add> allow(File).to receive(:directory?).with("/path2").and_return(false) <add> <add> path = described_class.new("/path1", "/path2") <add> expect(path.validate.to_ary).to eq(["/path1"]) <add> expect(path.to_ary).to eq(["/path1", "/path2"]) <add> end <add> end <add>end
3
Text
Text
strengthen test for reassigning node reference
f2236983a27d92cf844aad87c1688d7e6269b93d
<ide><path>curriculum/challenges/english/10-coding-interview-prep/data-structures/remove-elements-from-a-linked-list.md <ide> tests: <ide> - text: Your <code>remove</code> method should decrease the <code>length</code> of the linked list by one for every node removed. <ide> testString: assert((function(){var test = new LinkedList(); test.add("cat"); test.add("dog"); test.add("hamster"); test.remove("cat"); test.remove("fish"); return test.size() === 2})()); <ide> - text: Your <code>remove</code> method should reassign the reference of the previous node of the removed node to the removed node&apos;s <code>next</code> reference. <del> testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog');test.add('kitten'); test.remove('dog'); return test.head().next.element === 'kitten'})()); <add> testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog'); test.add('snake'); test.add('kitten'); test.remove('snake'); return test.head().next.next.element === 'kitten'})()); <ide> - text: Your <code>remove</code> method should not change the linked list if the element does not exist in the linked list. <ide> testString: assert((function(){var test = new LinkedList(); test.add('cat'); test.add('dog');test.add('kitten'); test.remove('elephant'); return JSON.stringify(test.head()) === '{"element":"cat","next":{"element":"dog","next":{"element":"kitten","next":null}}}'})()); <ide>
1
Ruby
Ruby
document the controller method for ad's mapper
e5eece41b5ac740f8a137b3228d052273c641099
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def scope(*args) <ide> @scope[:blocks] = recover[:block] <ide> end <ide> <add> # Scopes routes to a specific controller <add> # <add> # Example: <add> # controller "food" do <add> # match "bacon", :action => "bacon" <add> # end <ide> def controller(controller, options={}) <ide> options[:controller] = controller <ide> scope(options) { yield }
1
Javascript
Javascript
name anonymous functions in canvas.js
a7690dea0a162738c9f458156343d45a054ab960
<ide><path>src/canvas.js <ide> var CanvasGraphics = (function canvasGraphics() { <ide> }, <ide> <ide> // Color <del> setStrokeColorSpace: <del> function canvasGraphicsSetStrokeColorSpacefunction(raw) { <add> setStrokeColorSpace: function canvasGraphicsSetStrokeColorSpace(raw) { <ide> this.current.strokeColorSpace = ColorSpace.fromIR(raw); <ide> }, <ide> setFillColorSpace: function canvasGraphicsSetFillColorSpace(raw) { <ide> var CanvasGraphics = (function canvasGraphics() { <ide> var color = cs.getRgb(arguments); <ide> this.setStrokeRGBColor.apply(this, color); <ide> }, <del> getColorN_IR_Pattern: function(IR, cs) { <add> getColorN_IR_Pattern: function canvasGraphicsGetColorN_IR_Pattern(IR, cs) { <ide> if (IR[0] == 'TilingPattern') { <ide> var args = IR[1]; <ide> var base = cs.base; <ide> var CanvasGraphics = (function canvasGraphics() { <ide> error('Should not call beginImageData'); <ide> }, <ide> <del> paintFormXObjectBegin: <del> function canvasGraphicsPaintFormXObject(matrix, bbox) { <add> paintFormXObjectBegin: function canvasGraphicsPaintFormXObjectBegin(matrix, <add> bbox) { <ide> this.save(); <ide> <ide> if (matrix && isArray(matrix) && 6 == matrix.length) <ide> var CanvasGraphics = (function canvasGraphics() { <ide> } <ide> }, <ide> <del> paintFormXObjectEnd: function() { <add> paintFormXObjectEnd: function canvasGraphicsPaintFormXObjectEnd() { <ide> this.restore(); <ide> }, <ide> <del> paintJpegXObject: function(objId, w, h) { <add> paintJpegXObject: function canvasGraphicsPaintJpegXObject(objId, w, h) { <ide> var image = this.objs.get(objId); <ide> if (!image) { <ide> error('Dependent image isn\'t ready yet'); <ide> var CanvasGraphics = (function canvasGraphics() { <ide> this.restore(); <ide> }, <ide> <del> paintImageMaskXObject: function(imgArray, inverseDecode, width, height) { <add> paintImageMaskXObject: function canvasGraphicsPaintImageMaskXObject( <add> imgArray, inverseDecode, width, height) { <ide> function applyStencilMask(buffer, inverseDecode) { <ide> var imgArrayPos = 0; <ide> var i, j, mask, buf; <ide> var CanvasGraphics = (function canvasGraphics() { <ide> this.restore(); <ide> }, <ide> <del> paintImageXObject: function(imgData) { <add> paintImageXObject: function canvasGraphicsPaintImageXObject(imgData) { <ide> this.save(); <ide> var ctx = this.ctx; <ide> var w = imgData.width;
1
Text
Text
add missing metadata for recursive mkdir
77152739fd356c054e148e488936f018563136eb
<ide><path>doc/api/fs.md <ide> Synchronous lstat(2). <ide> <!-- YAML <ide> added: v0.1.8 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21875 <add> description: The second argument can now be an `options` object with <add> `recursive` and `mode` properties. <ide> - version: v10.0.0 <ide> pr-url: https://github.com/nodejs/node/pull/12562 <ide> description: The `callback` parameter is no longer optional. Not passing <ide> See also: mkdir(2). <ide> <!-- YAML <ide> added: v0.1.21 <ide> changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/21875 <add> description: The second argument can now be an `options` object with <add> `recursive` and `mode` properties. <ide> - version: v7.6.0 <ide> pr-url: https://github.com/nodejs/node/pull/10739 <ide> description: The `path` parameter can be a WHATWG `URL` object using `file:`
1
Python
Python
fix text preprocessing
a1161885d5d7a4a37ba58c7df5e7073850c6d1ea
<ide><path>keras/preprocessing/text.py <ide> else: <ide> maketrans = str.maketrans <ide> <add> <ide> def base_filter(): <ide> f = string.punctuation <ide> f = f.replace("'", '') <ide> f += '\t\n' <ide> return f <ide> <add> <ide> def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "): <ide> '''prune: sequence of characters to filter out <ide> ''' <ide> def text_to_word_sequence(text, filters=base_filter(), lower=True, split=" "): <ide> <ide> def one_hot(text, n, filters=base_filter(), lower=True, split=" "): <ide> seq = text_to_word_sequence(text, filters=filters, lower=lower, split=split) <del> return [(abs(hash(w))%(n-1)+1) for w in seq] <add> return [(abs(hash(w)) % (n - 1) + 1) for w in seq] <ide> <ide> <ide> class Tokenizer(object): <ide> def fit_on_texts(self, texts): <ide> self.word_docs[w] = 1 <ide> <ide> wcounts = list(self.word_counts.items()) <del> wcounts.sort(key = lambda x: x[1], reverse=True) <add> wcounts.sort(key=lambda x: x[1], reverse=True) <ide> sorted_voc = [wc[0] for wc in wcounts] <del> self.word_index = dict(list(zip(sorted_voc, list(range(0, len(sorted_voc)))))) <add> self.word_index = dict(list(zip(sorted_voc, list(range(1, len(sorted_voc) + 1))))) <ide> <ide> self.index_docs = {} <ide> for w, c in list(self.word_docs.items()): <ide> self.index_docs[self.word_index[w]] = c <ide> <del> <ide> def fit_on_sequences(self, sequences): <ide> ''' <del> required before using sequences_to_matrix <add> required before using sequences_to_matrix <ide> (if fit_on_texts was never called) <ide> ''' <ide> self.document_count = len(sequences) <ide> def fit_on_sequences(self, sequences): <ide> else: <ide> self.index_docs[i] += 1 <ide> <del> <ide> def texts_to_sequences(self, texts): <ide> ''' <ide> Transform each text in texts in a sequence of integers. <ide> def texts_to_sequences_generator(self, texts): <ide> vect.append(i) <ide> yield vect <ide> <del> <ide> def texts_to_matrix(self, texts, mode="binary"): <ide> ''' <ide> modes: binary, count, tfidf, freq <ide> def sequences_to_matrix(self, sequences, mode="binary"): <ide> ''' <ide> if not self.nb_words: <ide> if self.word_index: <del> nb_words = len(self.word_index) <add> nb_words = len(self.word_index) + 1 <ide> else: <ide> raise Exception("Specify a dimension (nb_words argument), or fit on some text data first") <ide> else: <ide> def sequences_to_matrix(self, sequences, mode="binary"): <ide> if mode == "count": <ide> X[i][j] = c <ide> elif mode == "freq": <del> X[i][j] = c/len(seq) <add> X[i][j] = c / len(seq) <ide> elif mode == "binary": <ide> X[i][j] = 1 <ide> elif mode == "tfidf": <del> tf = np.log(c/len(seq)) <del> df = (1 + np.log(1 + self.index_docs.get(j, 0)/(1 + self.document_count))) <add> tf = np.log(c / len(seq)) <add> df = (1 + np.log(1 + self.index_docs.get(j, 0) / (1 + self.document_count))) <ide> X[i][j] = tf / df <ide> else: <ide> raise Exception("Unknown vectorization mode: " + str(mode)) <ide> return X <del> <del> <del> <del> <del> <del> <del> <del>
1