text:
"""

    OpenAPI spec version:

    Generated by: https://github.com/swagger-api/swagger-codegen.git

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

from pprint import pformat
from six import iteritems
import re

class V1beta1DeploymentStrategy(object):
    """
    NOTE: This class is auto generated by the swagger code generator program.
    Do not edit the class manually.
    """

    operations = [
    ]

    # The key is attribute name
    # and the value is attribute type.
    swagger_types = {
        'type': 'str',
        'rolling_update': 'V1beta1RollingUpdateDeployment'
    }

    # The key is attribute name
    # and the value is json key in definition.
    attribute_map = {
        'type': 'type',
        'rolling_update': 'rollingUpdate'
    }

    def __init__(self, type=None, rolling_update=None):
        """
        V1beta1DeploymentStrategy - a model defined in Swagger

        """

        self._type = type
        self._rolling_update = rolling_update

    @property
    def type(self):
        """
        Gets the type of this V1beta1DeploymentStrategy.
        Type of deployment. Can be \"Recreate\" or \"RollingUpdate\". Default is RollingUpdate.

        :return: The type of this V1beta1DeploymentStrategy.
        :rtype: str
        """
        return self._type

    @type.setter
    def type(self, type):
        """
        Sets the type of this V1beta1DeploymentStrategy.
        Type of deployment. Can be \"Recreate\" or \"RollingUpdate\". Default is RollingUpdate.

        :param type: The type of this V1beta1DeploymentStrategy.
        :type: str
        """

        self._type = type

    @property
    def rolling_update(self):
        """
        Gets the rolling_update of this V1beta1DeploymentStrategy.
        Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate.

        :return: The rolling_update of this V1beta1DeploymentStrategy.
        :rtype: V1beta1RollingUpdateDeployment
        """
        return self._rolling_update

    @rolling_update.setter
    def rolling_update(self, rolling_update):
        """
        Sets the rolling_update of this V1beta1DeploymentStrategy.
        Rolling update config params. Present only if DeploymentStrategyType = RollingUpdate.

        :param rolling_update: The rolling_update of this V1beta1DeploymentStrategy.
        :type: V1beta1RollingUpdateDeployment
        """

        self._rolling_update = rolling_update

    def to_dict(self):
        """
        Returns the model properties as a dict
        """
        result = {}

        for attr, _ in iteritems(V1beta1DeploymentStrategy.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """
        Returns the string representation of the model
        """
        return pformat(self.to_dict())

    def __repr__(self):
        """
        For `print` and `pprint`
        """
        return self.to_str()

    def __eq__(self, other):
        """
        Returns true if both objects are equal
        """
        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """
        Returns true if both objects are not equal
        """
        return not self == other


text:
"""
RoBERTa: A Robustly Optimized BERT Pretraining Approach.
"""

import logging

import torch
import torch.nn as nn
import torch.nn.functional as F

from fairseq import utils
from fairseq.models import (
    FairseqEncoder,
    FairseqEncoderModel,
    register_model,
    register_model_architecture,
)
from fairseq.models.transformer import DEFAULT_MIN_PARAMS_TO_WRAP, TransformerEncoder
from fairseq.modules import LayerNorm
from fairseq.modules.quant_noise import quant_noise as apply_quant_noise_
from fairseq.modules.transformer_sentence_encoder import init_bert_params
from fairseq.utils import safe_getattr, safe_hasattr

from .hub_interface import RobertaHubInterface

logger = logging.getLogger(__name__)

@register_model("roberta")
class RobertaModel(FairseqEncoderModel):
    @classmethod
    def hub_models(cls):
        return {
            "roberta.base": "http://dl.fbaipublicfiles.com/fairseq/models/roberta.base.tar.gz",
            "roberta.large": "http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.tar.gz",
            "roberta.large.mnli": "http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.mnli.tar.gz",
            "roberta.large.wsc": "http://dl.fbaipublicfiles.com/fairseq/models/roberta.large.wsc.tar.gz",
        }

    def __init__(self, args, encoder):
        super().__init__(encoder)
        self.args = args

        # We follow BERT's random weight initialization
        self.apply(init_bert_params)

        self.classification_heads = nn.ModuleDict()

    @staticmethod
    def add_args(parser):
        """Add model-specific arguments to the parser."""
        parser.add_argument(
            "--encoder-layers", type=int, metavar="L", help="num encoder layers"
        )
        parser.add_argument(
            "--encoder-embed-dim",
            type=int,
            metavar="H",
            help="encoder embedding dimension",
        )
        parser.add_argument(
            "--encoder-ffn-embed-dim",
            type=int,
            metavar="F",
            help="encoder embedding dimension for FFN",
        )
        parser.add_argument(
            "--encoder-attention-heads",
            type=int,
            metavar="A",
            help="num encoder attention heads",
        )
        parser.add_argument(
            "--activation-fn",
            choices=utils.get_available_activation_fns(),
            help="activation function to use",
        )
        parser.add_argument(
            "--pooler-activation-fn",
            choices=utils.get_available_activation_fns(),
            help="activation function to use for pooler layer",
        )
        parser.add_argument(
            "--encoder-normalize-before",
            action="store_true",
            help="apply layernorm before each encoder block",
        )
        parser.add_argument(
            "--layernorm-embedding",
            action="store_true",
            help="add layernorm to embedding",
        )
        parser.add_argument(
            "--dropout", type=float, metavar="D", help="dropout probability"
        )
        parser.add_argument(
            "--attention-dropout",
            type=float,
            metavar="D",
            help="dropout probability for attention weights",
        )
        parser.add_argument(
            "--activation-dropout",
            type=float,
            metavar="D",
            help="dropout probability after activation in FFN",
        )
        parser.add_argument(
            "--pooler-dropout",
            type=float,
            metavar="D",
            help="dropout probability in the masked_lm pooler layers",
        )
        parser.add_argument(
            "--max-positions", type=int, help="number of positional embeddings to learn"
        )
        parser.add_argument(
            "--load-checkpoint-heads",
            action="store_true",
            help="(re-)register and load heads when loading checkpoints",
        )
        parser.add_argument(
            "--untie-weights-roberta",
            action="store_true",
            help="Untie weights between embeddings and classifiers in RoBERTa",
        )
        # args for "Reducing Transformer Depth on Demand with Structured Dropout" (Fan et al., 2019)
        parser.add_argument(
            "--encoder-layerdrop",
            type=float,
            metavar="D",
            default=0,
            help="LayerDrop probability for encoder",
        )
        parser.add_argument(
            "--encoder-layers-to-keep",
            default=None,
            help="which layers to *keep* when pruning as a comma-separated list",
        )
        # args for Training with Quantization Noise for Extreme Model Compression ({Fan*, Stock*} et al., 2020)
        parser.add_argument(
            "--quant-noise-pq",
            type=float,
            metavar="D",
            default=0,
            help="iterative PQ quantization noise at training time",
        )
        parser.add_argument(
            "--quant-noise-pq-block-size",
            type=int,
            metavar="D",
            default=8,
            help="block size of quantization noise at training time",
        )
        parser.add_argument(
            "--quant-noise-scalar",
            type=float,
            metavar="D",
            default=0,
            help="scalar quantization noise and scalar quantization at training time",
        )
        # args for "Better Fine-Tuning by Reducing Representational Collapse" (Aghajanyan et al. 2020)
        parser.add_argument(
            "--spectral-norm-classification-head",
            action="store_true",
            default=False,
            help="Apply spectral normalization on the classification head",
        )
        # args for Fully Sharded Data Parallel (FSDP) training
        parser.add_argument(
            "--min-params-to-wrap",
            type=int,
            metavar="D",
            default=DEFAULT_MIN_PARAMS_TO_WRAP,
            help=(
                "minimum number of params for a layer to be wrapped with FSDP() when "
                "training with --ddp-backend=fully_sharded. Smaller values will "
                "improve memory efficiency, but may make torch.distributed "
                "communication less efficient due to smaller input sizes. This option "
                "is set to 0 (i.e., always wrap) when --checkpoint-activations or "
                "--offload-activations are passed."
            ),
        )
        # args for AdaPruning
        # In short, it adds regularizarion for the multihead attention module and feed forward neural nets
        # For more details, please refer to the paper https://openreview.net/forum?id=_CMSV7FTzGI
        parser.add_argument(
            "--mha-reg-scale-factor",
            type=float,
            metavar="D",
            default=0.0,
            help="scaling factor for regularization term in adptive pruning, recommendation is 0.000375",
        )
        parser.add_argument(
            "--ffn-reg-scale-factor",
            type=float,
            metavar="D",
            default=0.0,
            help="scaling factor for regularization term in adptive pruning, recommendation is 0.000375",
        )
        parser.add_argument(
            "--mha-heads-to-keep",
            type=int,
            metavar="D",
            default=-1,
            help="number of heads to keep in each multi-head attention module, -1 means keeping all heads",
        )
        parser.add_argument(
            "--ffn-blocks-to-remove",
            type=int,
            metavar="D",
            default=-1,
            help="number of feedforward blocks to remove in each transformer layer, -1 means keeping all ffn blocks",
        )

    @classmethod
    def build_model(cls, args, task):
        """Build a new model instance."""

        from omegaconf import OmegaConf

        if OmegaConf.is_config(args):
            OmegaConf.set_struct(args, False)

        # make sure all arguments are present
        base_architecture(args)

        if not safe_hasattr(args, "max_positions"):
            if not safe_hasattr(args, "tokens_per_sample"):
                args.tokens_per_sample = task.max_positions()
            args.max_positions = args.tokens_per_sample

        encoder = RobertaEncoder(args, task.source_dictionary)

        if OmegaConf.is_config(args):
            OmegaConf.set_struct(args, True)

        return cls(args, encoder)

    def forward(
        self,
        src_tokens,
        features_only=False,
        return_all_hiddens=False,
        classification_head_name=None,
        **kwargs,
    ):
        if classification_head_name is not None:
            features_only = True

        x, extra = self.encoder(src_tokens, features_only, return_all_hiddens, **kwargs)

        if classification_head_name is not None:
            x = self.classification_heads[classification_head_name](x)
        return x, extra

    def _get_adaptive_head_loss(self):
        norm_loss = 0
        scaling = float(self.args.mha_reg_scale_factor)
        for layer in self.encoder.sentence_encoder.layers:
            norm_loss_layer = 0
            for i in range(layer.self_attn.num_heads):
                start_idx = i * layer.self_attn.head_dim
                end_idx = (i + 1) * layer.self_attn.head_dim
                norm_loss_layer += scaling * (
                    torch.sum(
                        torch.abs(
                            layer.self_attn.q_proj.weight[
                                start_idx:end_idx,
                            ]
                        )
                    )
                    + torch.sum(
                        torch.abs(layer.self_attn.q_proj.bias[start_idx:end_idx])
                    )
                )
                norm_loss_layer += scaling * (
                    torch.sum(
                        torch.abs(
                            layer.self_attn.k_proj.weight[
                                start_idx:end_idx,
                            ]
                        )
                    )
                    + torch.sum(
                        torch.abs(layer.self_attn.k_proj.bias[start_idx:end_idx])
                    )
                )
                norm_loss_layer += scaling * (
                    torch.sum(
                        torch.abs(
                            layer.self_attn.v_proj.weight[
                                start_idx:end_idx,
                            ]
                        )
                    )
                    + torch.sum(
                        torch.abs(layer.self_attn.v_proj.bias[start_idx:end_idx])
                    )
                )

            norm_loss += norm_loss_layer
        return norm_loss

    def _get_adaptive_ffn_loss(self):
        ffn_scale_factor = float(self.args.ffn_reg_scale_factor)
        filter_loss = 0
        for layer in self.encoder.sentence_encoder.layers:
            filter_loss += torch.sum(
                torch.abs(layer.fc1.weight * ffn_scale_factor)
            ) + torch.sum(torch.abs(layer.fc2.weight * ffn_scale_factor))
            filter_loss += torch.sum(
                torch.abs(layer.fc1.bias * ffn_scale_factor)
            ) + torch.sum(torch.abs(layer.fc2.bias * ffn_scale_factor))
        return filter_loss

    def get_normalized_probs(self, net_output, log_probs, sample=None):
        """Get normalized probabilities (or log probs) from a net's output."""
        logits = net_output[0].float()
        if log_probs:
            return F.log_softmax(logits, dim=-1)
        else:
            return F.softmax(logits, dim=-1)

    def register_classification_head(
        self, name, num_classes=None, inner_dim=None, **kwargs
    ):
        """Register a classification head."""
        if name in self.classification_heads:
            prev_num_classes = self.classification_heads[name].out_proj.out_features
            prev_inner_dim = self.classification_heads[name].dense.out_features
            if num_classes != prev_num_classes or inner_dim != prev_inner_dim:
                logger.warning(
                    're-registering head "{}" with num_classes {} (prev: {}) '
                    "and inner_dim {} (prev: {})".format(
                        name, num_classes, prev_num_classes, inner_dim, prev_inner_dim
                    )
                )
        self.classification_heads[name] = RobertaClassificationHead(
            input_dim=self.args.encoder_embed_dim,
            inner_dim=inner_dim or self.args.encoder_embed_dim,
            num_classes=num_classes,
            activation_fn=self.args.pooler_activation_fn,
            pooler_dropout=self.args.pooler_dropout,
            q_noise=self.args.quant_noise_pq,
            qn_block_size=self.args.quant_noise_pq_block_size,
            do_spectral_norm=self.args.spectral_norm_classification_head,
        )

    @property
    def supported_targets(self):
        return {"self"}

    @classmethod
    def from_pretrained(
        cls,
        model_name_or_path,
        checkpoint_file="model.pt",
        data_name_or_path=".",
        bpe="gpt2",
        **kwargs,
    ):
        from fairseq import hub_utils

        x = hub_utils.from_pretrained(
            model_name_or_path,
            checkpoint_file,
            data_name_or_path,
            archive_map=cls.hub_models(),
            bpe=bpe,
            load_checkpoint_heads=True,
            **kwargs,
        )

        logger.info(x["args"])
        return RobertaHubInterface(x["args"], x["task"], x["models"][0])

    def upgrade_state_dict_named(self, state_dict, name):
        prefix = name + "." if name != "" else ""

        # rename decoder -> encoder before upgrading children modules
        for k in list(state_dict.keys()):
            if k.startswith(prefix + "decoder"):
                new_k = prefix + "encoder" + k[len(prefix + "decoder") :]
                state_dict[new_k] = state_dict[k]
                del state_dict[k]

        # rename emb_layer_norm -> layernorm_embedding
        for k in list(state_dict.keys()):
            if ".emb_layer_norm." in k:
                new_k = k.replace(".emb_layer_norm.", ".layernorm_embedding.")
                state_dict[new_k] = state_dict[k]
                del state_dict[k]

        # upgrade children modules
        super().upgrade_state_dict_named(state_dict, name)

        # Handle new classification heads present in the state dict.
        current_head_names = (
            []
            if not hasattr(self, "classification_heads")
            else self.classification_heads.keys()
        )
        keys_to_delete = []
        for k in state_dict.keys():
            if not k.startswith(prefix + "classification_heads."):
                continue

            head_name = k[len(prefix + "classification_heads.") :].split(".")[0]
            num_classes = state_dict[
                prefix + "classification_heads." + head_name + ".out_proj.weight"
            ].size(0)
            inner_dim = state_dict[
                prefix + "classification_heads." + head_name + ".dense.weight"
            ].size(0)

            if getattr(self.args, "load_checkpoint_heads", False):
                if head_name not in current_head_names:
                    self.register_classification_head(head_name, num_classes, inner_dim)
            else:
                if head_name not in current_head_names:
                    logger.warning(
                        "deleting classification head ({}) from checkpoint "
                        "not present in current model: {}".format(head_name, k)
                    )
                    keys_to_delete.append(k)
                elif (
                    num_classes
                    != self.classification_heads[head_name].out_proj.out_features
                    or inner_dim
                    != self.classification_heads[head_name].dense.out_features
                ):
                    logger.warning(
                        "deleting classification head ({}) from checkpoint "
                        "with different dimensions than current model: {}".format(
                            head_name, k
                        )
                    )
                    keys_to_delete.append(k)
        for k in keys_to_delete:
            del state_dict[k]

        # Copy any newly-added classification heads into the state dict
        # with their current weights.
        if hasattr(self, "classification_heads"):
            cur_state = self.classification_heads.state_dict()
            for k, v in cur_state.items():
                if prefix + "classification_heads." + k not in state_dict:
                    logger.info("Overwriting " + prefix + "classification_heads." + k)
                    state_dict[prefix + "classification_heads." + k] = v

            # adapt data2vec models
            if (
                "encoder._ema" in state_dict
                and "encoder.lm_head.weight" not in state_dict
            ):
                lm_state = self.encoder.lm_head.state_dict()
                for k, v in lm_state.items():
                    state_dict["encoder.lm_head." + k] = v

            for k in list(state_dict.keys()):
                if k.startswith("encoder.regression_head") or k == "encoder._ema":
                    del state_dict[k]

class RobertaLMHead(nn.Module):
    """Head for masked language modeling."""

    def __init__(self, embed_dim, output_dim, activation_fn, weight=None):
        super().__init__()
        self.dense = nn.Linear(embed_dim, embed_dim)
        self.activation_fn = utils.get_activation_fn(activation_fn)
        self.layer_norm = LayerNorm(embed_dim)

        if weight is None:
            weight = nn.Linear(embed_dim, output_dim, bias=False).weight
        self.weight = weight
        self.bias = nn.Parameter(torch.zeros(output_dim))

    def forward(self, features, masked_tokens=None, **kwargs):
        # Only project the masked tokens while training,
        # saves both memory and computation
        if masked_tokens is not None:
            features = features[masked_tokens, :]

        x = self.dense(features)
        x = self.activation_fn(x)
        x = self.layer_norm(x)
        # project back to size of vocabulary with bias
        x = F.linear(x, self.weight) + self.bias
        return x

class RobertaClassificationHead(nn.Module):
    """Head for sentence-level classification tasks."""

    def __init__(
        self,
        input_dim,
        inner_dim,
        num_classes,
        activation_fn,
        pooler_dropout,
        q_noise=0,
        qn_block_size=8,
        do_spectral_norm=False,
    ):
        super().__init__()
        self.dense = nn.Linear(input_dim, inner_dim)
        self.activation_fn = utils.get_activation_fn(activation_fn)
        self.dropout = nn.Dropout(p=pooler_dropout)
        self.out_proj = apply_quant_noise_(
            nn.Linear(inner_dim, num_classes), q_noise, qn_block_size
        )
        if do_spectral_norm:
            if q_noise != 0:
                raise NotImplementedError(
                    "Attempting to use Spectral Normalization with Quant Noise. This is not officially supported"
                )
            self.out_proj = torch.nn.utils.spectral_norm(self.out_proj)

    def forward(self, features, **kwargs):
        x = features[:, 0, :]  # take <s> token (equiv. to [CLS])
        x = self.dropout(x)
        x = self.dense(x)
        x = self.activation_fn(x)
        x = self.dropout(x)
        x = self.out_proj(x)
        return x

class RobertaEncoder(FairseqEncoder):
    """RoBERTa encoder."""

    def __init__(self, args, dictionary):
        super().__init__(dictionary)

        # set any missing default values
        base_architecture(args)
        self.args = args

        if args.encoder_layers_to_keep:
            args.encoder_layers = len(args.encoder_layers_to_keep.split(","))

        embed_tokens = self.build_embedding(
            len(dictionary), args.encoder_embed_dim, dictionary.pad()
        )

        self.sentence_encoder = self.build_encoder(args, dictionary, embed_tokens)

        self.lm_head = self.build_lm_head(
            embed_dim=args.encoder_embed_dim,
            output_dim=len(dictionary),
            activation_fn=args.activation_fn,
            weight=(
                self.sentence_encoder.embed_tokens.weight
                if not args.untie_weights_roberta
                else None
            ),
        )

    def build_embedding(self, vocab_size, embedding_dim, padding_idx):
        return nn.Embedding(vocab_size, embedding_dim, padding_idx)

    def build_encoder(self, args, dictionary, embed_tokens):
        encoder = TransformerEncoder(args, dictionary, embed_tokens)
        encoder.apply(init_bert_params)
        return encoder

    def build_lm_head(self, embed_dim, output_dim, activation_fn, weight):
        return RobertaLMHead(embed_dim, output_dim, activation_fn, weight)

    def forward(
        self,
        src_tokens,
        features_only=False,
        return_all_hiddens=False,
        masked_tokens=None,
        **unused,
    ):
        """
        Args:
            src_tokens (LongTensor): input tokens of shape `(batch, src_len)`
            features_only (bool, optional): skip LM head and just return
                features. If True, the output will be of shape
                `(batch, src_len, embed_dim)`.
            return_all_hiddens (bool, optional): also return all of the
                intermediate hidden states (default: False).

        Returns:
            tuple:
                - the LM output of shape `(batch, src_len, vocab)`
                - a dictionary of additional data, where 'inner_states'
                  is a list of hidden states. Note that the hidden
                  states have shape `(src_len, batch, vocab)`.
        """
        x, extra = self.extract_features(
            src_tokens, return_all_hiddens=return_all_hiddens
        )
        if not features_only:
            x = self.output_layer(x, masked_tokens=masked_tokens)
        return x, extra

    def extract_features(self, src_tokens, return_all_hiddens=False, **kwargs):
        encoder_out = self.sentence_encoder(
            src_tokens,
            return_all_hiddens=return_all_hiddens,
            token_embeddings=kwargs.get("token_embeddings", None),
        )
        # T x B x C -> B x T x C
        features = encoder_out["encoder_out"][0].transpose(0, 1)
        inner_states = encoder_out["encoder_states"] if return_all_hiddens else None
        return features, {"inner_states": inner_states}

    def output_layer(self, features, masked_tokens=None, **unused):
        return self.lm_head(features, masked_tokens)

    def max_positions(self):
        """Maximum output length supported by the encoder."""
        return self.args.max_positions

@register_model_architecture("roberta", "roberta")
def base_architecture(args):
    args.encoder_layers = safe_getattr(args, "encoder_layers", 12)
    args.encoder_embed_dim = safe_getattr(args, "encoder_embed_dim", 768)
    args.encoder_ffn_embed_dim = safe_getattr(args, "encoder_ffn_embed_dim", 3072)
    args.encoder_attention_heads = safe_getattr(args, "encoder_attention_heads", 12)

    args.dropout = safe_getattr(args, "dropout", 0.1)
    args.attention_dropout = safe_getattr(args, "attention_dropout", 0.1)
    args.activation_dropout = safe_getattr(args, "activation_dropout", 0.0)
    args.pooler_dropout = safe_getattr(args, "pooler_dropout", 0.0)

    args.max_source_positions = safe_getattr(args, "max_positions", 512)
    args.no_token_positional_embeddings = safe_getattr(
        args, "no_token_positional_embeddings", False
    )

    # BERT has a few structural differences compared to the original Transformer
    args.encoder_learned_pos = safe_getattr(args, "encoder_learned_pos", True)
    args.layernorm_embedding = safe_getattr(args, "layernorm_embedding", True)
    args.no_scale_embedding = safe_getattr(args, "no_scale_embedding", True)
    args.activation_fn = safe_getattr(args, "activation_fn", "gelu")
    args.encoder_normalize_before = safe_getattr(
        args, "encoder_normalize_before", False
    )
    args.pooler_activation_fn = safe_getattr(args, "pooler_activation_fn", "tanh")
    args.untie_weights_roberta = safe_getattr(args, "untie_weights_roberta", False)

    # Adaptive input config
    args.adaptive_input = safe_getattr(args, "adaptive_input", False)

    # LayerDrop config
    args.encoder_layerdrop = safe_getattr(args, "encoder_layerdrop", 0.0)
    args.encoder_layers_to_keep = safe_getattr(args, "encoder_layers_to_keep", None)

    # Quantization noise config
    args.quant_noise_pq = safe_getattr(args, "quant_noise_pq", 0)
    args.quant_noise_pq_block_size = safe_getattr(args, "quant_noise_pq_block_size", 8)
    args.quant_noise_scalar = safe_getattr(args, "quant_noise_scalar", 0)

    # R4F config
    args.spectral_norm_classification_head = safe_getattr(
        args, "spectral_norm_classification_head", False
    )

@register_model_architecture("roberta", "roberta_prenorm")
def roberta_prenorm_architecture(args):
    args.layernorm_embedding = safe_getattr(args, "layernorm_embedding", False)
    args.encoder_normalize_before = safe_getattr(args, "encoder_normalize_before", True)
    base_architecture(args)

@register_model_architecture("roberta", "roberta_base")
def roberta_base_architecture(args):
    base_architecture(args)

@register_model_architecture("roberta", "roberta_large")
def roberta_large_architecture(args):
    args.encoder_layers = safe_getattr(args, "encoder_layers", 24)
    args.encoder_embed_dim = safe_getattr(args, "encoder_embed_dim", 1024)
    args.encoder_ffn_embed_dim = safe_getattr(args, "encoder_ffn_embed_dim", 4096)
    args.encoder_attention_heads = safe_getattr(args, "encoder_attention_heads", 16)
    base_architecture(args)

@register_model_architecture("roberta", "xlm")
def xlm_architecture(args):
    args.encoder_layers = safe_getattr(args, "encoder_layers", 16)
    args.encoder_embed_dim = safe_getattr(args, "encoder_embed_dim", 1280)
    args.encoder_ffn_embed_dim = safe_getattr(args, "encoder_ffn_embed_dim", 1280 * 4)
    args.encoder_attention_heads = safe_getattr(args, "encoder_attention_heads", 16)
    base_architecture(args)

redpajama_set_name: RedPajamaGithub


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html

module Stratosphere.ResourceProperties.ElasticLoadBalancingLoadBalancerPolicies where

import Stratosphere.ResourceImports

-- | Full data type definition for ElasticLoadBalancingLoadBalancerPolicies.
-- See 'elasticLoadBalancingLoadBalancerPolicies' for a more convenient
-- constructor.
data ElasticLoadBalancingLoadBalancerPolicies =
  ElasticLoadBalancingLoadBalancerPolicies
  { _elasticLoadBalancingLoadBalancerPoliciesAttributes :: [Object]
  , _elasticLoadBalancingLoadBalancerPoliciesInstancePorts :: Maybe (ValList Text)
  , _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts :: Maybe (ValList Text)
  , _elasticLoadBalancingLoadBalancerPoliciesPolicyName :: Val Text
  , _elasticLoadBalancingLoadBalancerPoliciesPolicyType :: Val Text
  } deriving (Show, Eq)

instance ToJSON ElasticLoadBalancingLoadBalancerPolicies where
  toJSON ElasticLoadBalancingLoadBalancerPolicies{..} =
    object $
    catMaybes
    [ (Just . ("Attributes",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesAttributes
    , fmap (("InstancePorts",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesInstancePorts
    , fmap (("LoadBalancerPorts",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts
    , (Just . ("PolicyName",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesPolicyName
    , (Just . ("PolicyType",) . toJSON) _elasticLoadBalancingLoadBalancerPoliciesPolicyType
    ]

-- | Constructor for 'ElasticLoadBalancingLoadBalancerPolicies' containing
-- required fields as arguments.
elasticLoadBalancingLoadBalancerPolicies
  :: [Object] -- ^ 'elblbpAttributes'
  -> Val Text -- ^ 'elblbpPolicyName'
  -> Val Text -- ^ 'elblbpPolicyType'
  -> ElasticLoadBalancingLoadBalancerPolicies
elasticLoadBalancingLoadBalancerPolicies attributesarg policyNamearg policyTypearg =
  ElasticLoadBalancingLoadBalancerPolicies
  { _elasticLoadBalancingLoadBalancerPoliciesAttributes = attributesarg
  , _elasticLoadBalancingLoadBalancerPoliciesInstancePorts = Nothing
  , _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts = Nothing
  , _elasticLoadBalancingLoadBalancerPoliciesPolicyName = policyNamearg
  , _elasticLoadBalancingLoadBalancerPoliciesPolicyType = policyTypearg
  }

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-attributes
elblbpAttributes :: Lens' ElasticLoadBalancingLoadBalancerPolicies [Object]
elblbpAttributes = lens _elasticLoadBalancingLoadBalancerPoliciesAttributes (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesAttributes = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-instanceports
elblbpInstancePorts :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Maybe (ValList Text))
elblbpInstancePorts = lens _elasticLoadBalancingLoadBalancerPoliciesInstancePorts (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesInstancePorts = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-loadbalancerports
elblbpLoadBalancerPorts :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Maybe (ValList Text))
elblbpLoadBalancerPorts = lens _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesLoadBalancerPorts = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policyname
elblbpPolicyName :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Val Text)
elblbpPolicyName = lens _elasticLoadBalancingLoadBalancerPoliciesPolicyName (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesPolicyName = a })

-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-elb-policy.html#cfn-ec2-elb-policy-policytype
elblbpPolicyType :: Lens' ElasticLoadBalancingLoadBalancerPolicies (Val Text)
elblbpPolicyType = lens _elasticLoadBalancingLoadBalancerPoliciesPolicyType (\s a -> s { _elasticLoadBalancingLoadBalancerPoliciesPolicyType = a })


text:
package com.haulmont.cuba.core.sys.persistence.mapping;

import com.haulmont.chile.core.model.MetaClass;
import com.haulmont.chile.core.model.MetaProperty;
import com.haulmont.cuba.core.global.Metadata;
import com.haulmont.cuba.core.sys.UuidConverter;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.DirectToFieldMapping;
import org.eclipse.persistence.mappings.OneToOneMapping;
import org.eclipse.persistence.platform.database.*;
import org.eclipse.persistence.sessions.Session;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.sql.Types;
import java.util.UUID;

/**
 * Updates entity mappings to add UUID support even for databases that do not support UUID datatype directly.
 */
@Component("cuba_UuidMappingProcessor")
public class UuidMappingProcessor implements MappingProcessor {

    @Inject
    private Metadata metadata;

    @Override
    public void process(MappingProcessorContext context) {
        DatabaseMapping mapping = context.getMapping();
        Session session = context.getSession();

        MetaClass metaClass = metadata.getSession().getClassNN(mapping.getDescriptor().getJavaClass());

        String attributeName = mapping.getAttributeName();
        MetaProperty metaProperty = metaClass.getPropertyNN(attributeName);
        if (metaProperty.getRange().isDatatype()) {
            if (metaProperty.getJavaType().equals(UUID.class)) {
                ((DirectToFieldMapping) mapping).setConverter(UuidConverter.getInstance());
                setDatabaseFieldParameters(session, mapping.getField());
            }
        } else if (metaProperty.getRange().isClass() && !metaProperty.getRange().getCardinality().isMany()) {
            MetaClass refMetaClass = metaProperty.getRange().asClass();
            MetaProperty refPkProperty = metadata.getTools().getPrimaryKeyProperty(refMetaClass);
            if (refPkProperty != null && refPkProperty.getJavaType().equals(UUID.class)) {
                for (DatabaseField field : ((OneToOneMapping) mapping).getForeignKeyFields()) {
                    setDatabaseFieldParameters(session, field);
                }
            }
        }

    }

    private void setDatabaseFieldParameters(Session session, DatabaseField field) {
        if (session.getPlatform() instanceof PostgreSQLPlatform) {
            field.setSqlType(Types.OTHER);
            field.setType(UUID.class);
            field.setColumnDefinition("UUID");
        } else if (session.getPlatform() instanceof MySQLPlatform) {
            field.setSqlType(Types.VARCHAR);
            field.setType(String.class);
            field.setColumnDefinition("varchar(32)");
        } else if (session.getPlatform() instanceof HSQLPlatform) {
            field.setSqlType(Types.VARCHAR);
            field.setType(String.class);
            field.setColumnDefinition("varchar(36)");
        } else if (session.getPlatform() instanceof SQLServerPlatform) {
            field.setSqlType(Types.VARCHAR);
            field.setType(String.class);
            field.setColumnDefinition("uniqueidentifier");
        } else if (session.getPlatform() instanceof OraclePlatform) {
            field.setSqlType(Types.VARCHAR);
            field.setType(String.class);
            field.setColumnDefinition("varchar2(32)");
        } else {
            field.setSqlType(Types.VARCHAR);
            field.setType(String.class);
        }
    }
}


text:
package vpn

/**
* Binding class showing the group that can be bound to vpnurlpolicy.
*/
type Vpnurlpolicygroupbinding struct {
	/**
	* The entity name to which policy is bound
	*/
	Boundto string `json:"boundto,omitempty"`
	Priority uint32 `json:"priority,omitempty"`
	Activepolicy uint32 `json:"activepolicy,omitempty"`
	/**
	* Name for the new urlPolicy.
	*/
	Name string `json:"name,omitempty"`

}


text:
NAME

coqdep - Compute inter-module dependencies for Coq and Caml programs

SYNOPSIS

coqdep [ -w ] [ -I \ directory ] [ -coqlib \ directory ] [ -c ] [ -i ] [ -D ] [ -slash ] filename ... directory ...

DESCRIPTION

coqdep compute inter-module dependencies for Coq and Caml programs, and prints the dependencies on the standard output in a format readable by make. When a directory is given as argument, it is recursively looked at.

Dependencies of Coq modules are computed by looking at Require \& commands (Require, Require Export, Require Import), Declare \&  ML \&  Module \& commands and Load \& commands. Dependencies relative to modules from the Coq library are not printed.

Dependencies of Caml modules are computed by looking at open \& directives and the dot notation module.value \&.

OPTIONS

-c Prints the dependencies of Caml modules. (On Caml modules, the behaviour is exactly the same as ocamldep).

-w Prints a warning if a Coq command Declare \&  ML \&  Module \& is incorrect. (For instance, you wrote `Declare ML Module "A".', but the module A contains #open "B"). The correct command is printed (see option -D). The warning is printed on standard error.

-D This commands looks for every command Declare \&  ML \&  Module \& of each Coq file given as argument and complete (if needed) the list of Caml modules. The new command is printed on the standard output. No dependency is computed with this option.

-slash Prints paths using a slash instead of the OS specific separator. This option is useful when developping under Cygwin.

-I \ directory The files .v .ml .mli of the directory directory \& are taken into account during the calculus of dependencies, but their own dependencies are not printed.

-coqlib \ directory Indicates where is the Coq library. The default value has been determined at installation time, and therefore this option should not be used under normal circumstances.

SEE ALSO

ocamlc (1), coqc (1), make (1).

NOTES

Lexers (for Coq and Caml) correctly handle nested comments and strings.

The treatment of symbolic links is primitive.

If two files have the same name, in two different directories, a warning is printed on standard error.

There is no way to limit the scope of the recursive search for directories.

EXAMPLES

Consider the files (in the same directory):

	A.ml B.ml C.ml D.ml X.v Y.v and Z.v

where

\+  D.ml contains the commands `open A', `open B' and `type t = C.t' ;

\+ Y.v contains the command `Require X' ;

\+ Z.v contains the commands `Require X' and `Declare ML Module "D"'.

To get the dependencies of the Coq files:

 example% coqdep -I . *.v

Z.vo: Z.v ./X.vo ./D.cmo
Y.vo: Y.v ./X.vo
X.vo: X.v

With a warning:

 example% coqdep -w -I . *.v

Z.vo: Z.v ./X.vo ./D.cmo
Y.vo: Y.v ./X.vo
X.vo: X.v
### Warning : In file Z.v, the ML modules declaration should be
### Declare ML Module "A" "B" "C" "D".

To get only the Caml dependencies:

 example% coqdep -c -I . *.ml

D.cmo: D.ml ./A.cmo ./B.cmo ./C.cmo
D.cmx: D.ml ./A.cmx ./B.cmx ./C.cmx
C.cmo: C.ml
C.cmx: C.ml
B.cmo: B.ml
B.cmx: B.ml
A.cmo: A.ml
A.cmx: A.ml

BUGS

Please report any bug to coq-bugs@pauillac.inria.fr


text:
#ifndef IJKPLAYER_ANDROID__IJKPLAYER_H
#define IJKPLAYER_ANDROID__IJKPLAYER_H

#include <stdbool.h>
#include "ff_ffmsg_queue.h"

#include "ijkmeta.h"

#ifndef MPTRACE
#define MPTRACE ALOGD
#endif

typedef struct IjkMediaPlayer IjkMediaPlayer;
struct FFPlayer;
struct SDL_Vout;

/*-
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_IDLE);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_INITIALIZED);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_ASYNC_PREPARING);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_PREPARED);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_STARTED);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_PAUSED);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_COMPLETED);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_STOPPED);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_ERROR);
 MPST_CHECK_NOT_RET(mp->mp_state, MP_STATE_END);
 */

/*-
 * ijkmp_set_data_source()  -> MP_STATE_INITIALIZED
 *
 * ijkmp_reset              -> self
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_IDLE               0

/*-
 * ijkmp_prepare_async()    -> MP_STATE_ASYNC_PREPARING
 *
 * ijkmp_reset              -> MP_STATE_IDLE
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_INITIALIZED        1

/*-
 *                   ...    -> MP_STATE_PREPARED
 *                   ...    -> MP_STATE_ERROR
 *
 * ijkmp_reset              -> MP_STATE_IDLE
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_ASYNC_PREPARING    2

/*-
 * ijkmp_seek_to()          -> self
 * ijkmp_start()            -> MP_STATE_STARTED
 *
 * ijkmp_reset              -> MP_STATE_IDLE
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_PREPARED           3

/*-
 * ijkmp_seek_to()          -> self
 * ijkmp_start()            -> self
 * ijkmp_pause()            -> MP_STATE_PAUSED
 * ijkmp_stop()             -> MP_STATE_STOPPED
 *                   ...    -> MP_STATE_COMPLETED
 *                   ...    -> MP_STATE_ERROR
 *
 * ijkmp_reset              -> MP_STATE_IDLE
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_STARTED            4

/*-
 * ijkmp_seek_to()          -> self
 * ijkmp_start()            -> MP_STATE_STARTED
 * ijkmp_pause()            -> self
 * ijkmp_stop()             -> MP_STATE_STOPPED
 *
 * ijkmp_reset              -> MP_STATE_IDLE
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_PAUSED             5

/*-
 * ijkmp_seek_to()          -> self
 * ijkmp_start()            -> MP_STATE_STARTED (from beginning)
 * ijkmp_pause()            -> self
 * ijkmp_stop()             -> MP_STATE_STOPPED
 *
 * ijkmp_reset              -> MP_STATE_IDLE
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_COMPLETED          6

/*-
 * ijkmp_stop()             -> self
 * ijkmp_prepare_async()    -> MP_STATE_ASYNC_PREPARING
 *
 * ijkmp_reset              -> MP_STATE_IDLE
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_STOPPED            7

/*-
 * ijkmp_reset              -> MP_STATE_IDLE
 * ijkmp_release            -> MP_STATE_END
 */
#define MP_STATE_ERROR              8

/*-
 * ijkmp_release            -> self
 */
#define MP_STATE_END                9

#define IJKMP_IO_STAT_READ 1

#define IJKMP_OPT_CATEGORY_FORMAT FFP_OPT_CATEGORY_FORMAT
#define IJKMP_OPT_CATEGORY_CODEC  FFP_OPT_CATEGORY_CODEC
#define IJKMP_OPT_CATEGORY_SWS    FFP_OPT_CATEGORY_SWS
#define IJKMP_OPT_CATEGORY_PLAYER FFP_OPT_CATEGORY_PLAYER

void            ijkmp_global_init();
void            ijkmp_global_uninit();
void            ijkmp_global_set_log_report(int use_report);
void            ijkmp_global_set_log_level(int log_level);   // log_level = AV_LOG_xxx
void            ijkmp_global_set_inject_callback(ijk_inject_callback cb);
const char     *ijkmp_version_ident();
unsigned int    ijkmp_version_int();
void            ijkmp_io_stat_register(void (*cb)(const char *url, int type, int bytes));
void            ijkmp_io_stat_complete_register(void (*cb)(const char *url,
                                                           int64_t read_bytes, int64_t total_size,
                                                           int64_t elpased_time, int64_t total_duration));

// ref_count is 1 after open
IjkMediaPlayer *ijkmp_create(int (*msg_loop)(void*));
void            ijkmp_set_inject_opaque(IjkMediaPlayer *mp, void *opaque);

void            ijkmp_set_option(IjkMediaPlayer *mp, int opt_category, const char *name, const char *value);
void            ijkmp_set_option_int(IjkMediaPlayer *mp, int opt_category, const char *name, int64_t value);

int             ijkmp_get_video_codec_info(IjkMediaPlayer *mp, char **codec_info);
int             ijkmp_get_audio_codec_info(IjkMediaPlayer *mp, char **codec_info);
void            ijkmp_set_playback_rate(IjkMediaPlayer *mp, float rate);
int             ijkmp_set_stream_selected(IjkMediaPlayer *mp, int stream, int selected);

float           ijkmp_get_property_float(IjkMediaPlayer *mp, int id, float default_value);
void            ijkmp_set_property_float(IjkMediaPlayer *mp, int id, float value);
int64_t         ijkmp_get_property_int64(IjkMediaPlayer *mp, int id, int64_t default_value);
void            ijkmp_set_property_int64(IjkMediaPlayer *mp, int id, int64_t value);

// must be freed with free();
IjkMediaMeta   *ijkmp_get_meta_l(IjkMediaPlayer *mp);

// preferred to be called explicity, can be called multiple times
// NOTE: ijkmp_shutdown may block thread
void            ijkmp_shutdown(IjkMediaPlayer *mp);

void            ijkmp_inc_ref(IjkMediaPlayer *mp);

// call close at last release, also free memory
// NOTE: ijkmp_dec_ref may block thread
void            ijkmp_dec_ref(IjkMediaPlayer *mp);
void            ijkmp_dec_ref_p(IjkMediaPlayer **pmp);

int             ijkmp_set_data_source(IjkMediaPlayer *mp, const char *url);
int             ijkmp_prepare_async(IjkMediaPlayer *mp);
int             ijkmp_start(IjkMediaPlayer *mp);
int             ijkmp_pause(IjkMediaPlayer *mp);
int             ijkmp_stop(IjkMediaPlayer *mp);
int             ijkmp_seek_to(IjkMediaPlayer *mp, long msec);
int             ijkmp_get_state(IjkMediaPlayer *mp);
bool            ijkmp_is_playing(IjkMediaPlayer *mp);
long            ijkmp_get_current_position(IjkMediaPlayer *mp);
long            ijkmp_get_duration(IjkMediaPlayer *mp);
long            ijkmp_get_playable_duration(IjkMediaPlayer *mp);
void            ijkmp_set_loop(IjkMediaPlayer *mp, int loop);
int             ijkmp_get_loop(IjkMediaPlayer *mp);

void           *ijkmp_get_weak_thiz(IjkMediaPlayer *mp);
void           *ijkmp_set_weak_thiz(IjkMediaPlayer *mp, void *weak_thiz);

/* return < 0 if aborted, 0 if no packet and > 0 if packet.  */
int             ijkmp_get_msg(IjkMediaPlayer *mp, AVMessage *msg, int block);

#endif


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Puccinia congregata Ellis & Harkn.

### Remarks
null


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package interaccion;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import pojos.TblRol;

/**
 *
 * @author mario
 */
public class clControlRol {

    public List<TblRol> funListaRoles(){
        List<TblRol> vl_lista = new ArrayList<TblRol>();
        SessionFactory sf = HibernateUtil.getSessionFactory();
        Session sesion = sf.openSession();

        Query q = sesion.createQuery("from TblRol");

        vl_lista = (List<TblRol>) q.list();

        return vl_lista;
    }

    public int funObtenerRol(){
        int rol = 0;

        return rol;
    }

}


text:
<?php
namespace ProdeMundial\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use ProdeMundial\CoreBundle\Entity\Game;
use ProdeMundial\CoreBundle\Entity\TeamsGroup;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Config\FileLocator;

class LoadMatches extends AbstractFixture implements OrderedFixtureInterface, ContainerAwareInterface
{

    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * {@inheritDoc}
     */
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $locator = new FileLocator($this->container->get('kernel')->getBundle('ProdeMundialCoreBundle')->getPath()
            . DIRECTORY_SEPARATOR . "Resources/config/data"
        );
        $fixture = $data = file_get_contents($locator->locate('groups.txt', null, true)); //read the file
        $fixture_lines = explode("\n", $data); //create array separate by new line
        // we parse the lines to search the matches
        $group = null;
        foreach($fixture_lines as $line) {
            // we look for the group
            if (preg_match("/Grupo [A-H]:/", $line)) {
                // if the group already exists, then we persist it
                if ($group instanceof TeamsGroup) {
                    $manager->persist($group);
                }
                // we create the new group
                $group = new TeamsGroup();
                $group->setName(rtrim($line, ':'));
            } else {
                if (!empty($line)) {
                    $matchInfo = explode(" ", preg_replace( '/\s+/', ' ', $line ));
                    // we have a game! add it to the group
                    $game = new Game();
                    $hour = end($matchInfo) == '(UTC-3)' ? (int) $matchInfo['3'] : $matchInfo['3'] + 1;
                    $gameDate = new \DateTime(date('m/d/Y', strtotime(str_replace('/', ' ', $matchInfo[2]))));
                    $gameDate->setTime($hour, 0); //$gameDate->setTimezone(new \DateTimeZone('America/Buenos_Aires'));
                    $game->setDate($gameDate);
                    $game->setHomeTeam($this->getReference($matchInfo[4]));
                    $game->setAwayTeam($this->getReference($matchInfo[6]));
                    $game->setVenue(join(' ', array_splice($matchInfo, 7)));
                    $game->setFifaMatchId(str_replace(array( '(', ')' ), '', $matchInfo[0]));

                    // we add the match to the group
                    $group->addGame($game);
                }
            }
        }

        // we persist the last group
        if ($group instanceof TeamsGroup) {
            $manager->persist($group);
        }

        $manager->flush();
    }

    public function getOrder()
    {
        return 2;
    }
}


text:
from datetime import datetime
from django.utils import timezone

from django.conf import settings
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.utils.encoding import python_2_unicode_compatible

from jsonfield import JSONField

from statsy.descriptors import ValueDescriptor
from statsy.managers import StatsyGroupQuerySet, StatsyEventQuerySet, StatsyQuerySet

@python_2_unicode_compatible
class StatsyCategory(models.Model):
    """ Abstract base model for Group and Event """
    NAME_LENGTH_LIMIT = 100

    name = models.CharField(max_length=NAME_LENGTH_LIMIT, unique=True, verbose_name='name')
    is_active = models.BooleanField(default=True, verbose_name='is active')

    class Meta:
        abstract = True

    def __str__(self):
        return self.name

    @property
    def cache_key(self):
        return self.cache_key_string.format(self.name)

    def activate(self):
        self.is_active = True
        self.save()

    def deactivate(self):
        self.is_active = False
        self.save()

class StatsyGroup(StatsyCategory):
    objects = StatsyGroupQuerySet.as_manager()

    cache_key_string = 'statsy_group_{0}'

    class Meta:
        verbose_name = 'Statsy Group'
        verbose_name_plural = 'Statsy Groups'

class StatsyEvent(StatsyCategory):
    objects = StatsyEventQuerySet.as_manager()

    cache_key_string = 'statsy_event_{0}'

    class Meta:
        verbose_name = 'Statsy Event'
        verbose_name_plural = 'Statsy Events'

@python_2_unicode_compatible
class StatsyObject(models.Model):
    group = models.ForeignKey(
        'StatsyGroup', blank=True, null=True,
        related_name='statsy_object_list', verbose_name='group'
    )
    event = models.ForeignKey(
        'StatsyEvent', blank=True, null=True,
        related_name='statsy_object_list', verbose_name='event'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, blank=True, null=True,
        related_name='statsy_object_list', verbose_name='user'
    )

    label = models.CharField(max_length=255, blank=True, null=True, verbose_name='label')

    content_type = models.ForeignKey(ContentType, blank=True, null=True)
    object_id = models.PositiveIntegerField(blank=True, null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    created_at = models.DateTimeField(blank=True, null=True, db_index=True, verbose_name='created at')

    value_types = ('float', 'text')
    value = ValueDescriptor(value_types=value_types)

    float_value = models.FloatField(blank=True, null=True, verbose_name='float value')
    text_value = models.CharField(max_length=255, blank=True, null=True, verbose_name='text value')

    url = models.URLField(blank=True, null=True, verbose_name='url')
    duration = models.IntegerField(blank=True, null=True, verbose_name='duration')
    extra = JSONField(blank=True, null=True, max_length=1024, verbose_name='extra')

    objects = StatsyQuerySet.as_manager()

    class Meta:
        verbose_name = 'Statsy Object'
        verbose_name_plural = 'Statsy Objects'

        index_together = ['content_type', 'object_id', 'user']
        ordering = ('-created_at',)

        permissions = (
            ('stats_view', 'Can view stats'),
        )

    def __str__(self):
        if self.label:
            return '{0}:{1}:{2} {3}'.format(
                self.group, self.event, self.label,
                self.created_at.strftime('%d/%m/%Y %H:%M')
            )

        return '{0}:{1} {2}'.format(self.group, self.event, self.created_at.strftime('%d/%m/%Y %H:%M'))

    @classmethod
    def create(cls, **kwargs):
        value = kwargs.pop('value', None)

        if 'created_at' not in kwargs:
            kwargs['created_at'] = timezone.now()

        new_object = cls(**kwargs)
        new_object.value = value
        new_object.save()

        return new_object

    def serialize(self):
        if isinstance(self.created_at, str):
            self.created_at = datetime.strptime(self.created_at.rstrip('Z'), '%Y-%m-%dT%H:%M:%S.%f')

        return {
            'id': self.pk,
            'group_id': self.group_id,
            'event_id': self.event_id,
            'user_id': self.user_id,
            'label': self.label,
            'content_type_id': self.content_type_id,
            'object_id': self.object_id,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            'value': self.value,
            'url': self.url,
            'duration': self.duration,
            'extra': self.extra
        }


text: Updating List Item...


text:
package com.wroclawstudio.weddinggame.presenters;

import com.wroclawstudio.weddinggame.fragments.interfaces.MenuFragment;
import com.wroclawstudio.weddinggame.presenters.interfaces.BasePresenter;

public class MenuPresenterImpl extends BasePresenter<MenuFragment> {

    @Override
    public void onResume() {
        getView().startSong();
    }

    @Override
    public void onPause(){
        getView().stopSong();
    }
}


text:
'use strict';
const Code = require('code');
const Constants = require('../../../../../../../client/pages/admin/admins/details/constants');
const Lab = require('lab');
const Store = require('../../../../../../../client/pages/admin/admins/details/store');

const lab = exports.lab = Lab.script();

lab.experiment('Admin Admins Permissions Reducer', () => {

    lab.test('it handles a GET_DETAILS_RESPONSE action (only setting permissions if present)', (done) => {

        Store.dispatch({
            type: Constants.GET_DETAILS_RESPONSE,
            err: null,
            response: {
                _id: 'abcxyz'
            }
        });

        let state = Store.getState().permissions;

        Code.expect(state.adminId).to.equal('abcxyz');
        Code.expect(state.permissions).to.have.length(0);

        Store.dispatch({
            type: Constants.GET_DETAILS_RESPONSE,
            err: null,
            response: {
                _id: 'abcxyz',
                permissions: {
                    FOO: true,
                    BAR: false
                }
            }
        });

        state = Store.getState().permissions;

        Code.expect(state.permissions).to.have.length(2);

        done();
    });

    lab.test('it handles a SAVE_PERMISSIONS action', (done) => {

        Store.dispatch({
            type: Constants.SAVE_PERMISSIONS,
            request: {
                data: {
                    permissions: {
                        FOO: true,
                        BAR: false
                    }
                }
            }
        });

        const state = Store.getState().permissions;

        Code.expect(state.loading).to.be.true();
        Code.expect(state.permissions.FOO).to.be.true();
        Code.expect(state.permissions.BAR).to.be.false();

        done();
    });

    lab.test('it handles a SAVE_PERMISSIONS_RESPONSE action (only setting permissions if present)', (done) => {

        Store.dispatch({
            type: Constants.SAVE_PERMISSIONS_RESPONSE,
            err: null,
            response: {
                permissions: {}
            }
        });

        let state = Store.getState().permissions;

        Code.expect(state.loading).to.be.false();
        Code.expect(state.permissions).to.have.length(0);

        Store.dispatch({
            type: Constants.SAVE_PERMISSIONS_RESPONSE,
            err: null,
            response: {
            }
        });

        state = Store.getState().permissions;

        Code.expect(state.loading).to.be.false();

        done();
    });

    lab.test('it handles a HIDE_PERMISSIONS_SAVE_SUCCESS action', (done) => {

        Store.dispatch({
            type: Constants.HIDE_PERMISSIONS_SAVE_SUCCESS
        });

        const state = Store.getState().permissions;

        Code.expect(state.showSaveSuccess).to.be.false();

        done();
    });
});


text:
<?php
/**
 * Custom template tags for this theme.
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package Pu-ente
 */

if ( ! function_exists( 'the_posts_navigation' ) ) :
/**
 * Display navigation to next/previous set of posts when applicable.
 *
 * @todo Remove this function when WordPress 4.3 is released.
 */
function the_posts_navigation() {
	// Don't print empty markup if there's only one page.
	if ( $GLOBALS['wp_query']->max_num_pages < 2 ) {
		return;
	}
	?>

<?php _e( 'Posts navigation', 'pu-ente' ); ?>

			<?php if ( get_next_posts_link() ) : ?>

<?php next_posts_link( __( 'Older posts', 'pu-ente' ) ); ?>

			<?php endif; ?>

			<?php if ( get_previous_posts_link() ) : ?>

<?php previous_posts_link( __( 'Newer posts', 'pu-ente' ) ); ?>

			<?php endif; ?>

	<?php
}
endif;

if ( ! function_exists( 'the_post_navigation' ) ) :
/**
 * Display navigation to next/previous post when applicable.
 *
 * @todo Remove this function when WordPress 4.3 is released.
 */
function the_post_navigation() {
	// Don't print empty markup if there's nowhere to navigate.
	$previous = ( is_attachment() ) ? get_post( get_post()->post_parent ) : get_adjacent_post( false, '', true );
	$next     = get_adjacent_post( false, '', false );

	if ( ! $next && ! $previous ) {
		return;
	}
	?>

<?php _e( 'Post navigation', 'pu-ente' ); ?>

			<?php
				previous_post_link( '
%link
', '%title' );
				next_post_link( '
%link
', '%title' );
			?>

	<?php
}
endif;

if ( ! function_exists( 'pu_ente_posted_on' ) ) :
/**
 * Prints HTML with meta information for the current post-date/time and author.
 */
function pu_ente_posted_on() {
	$time_string = '<time class="entry-date published updated" datetime="%1$s">%2$s</time>';
	if ( get_the_time( 'U' ) !== get_the_modified_time( 'U' ) ) {
		$time_string = '<time class="entry-date published" datetime="%1$s">%2$s</time><time class="updated" datetime="%3$s">%4$s</time>';
	}

	$time_string = sprintf( $time_string,
		esc_attr( get_the_date( 'c' ) ),
		esc_html( get_the_date() ),
		esc_attr( get_the_modified_date( 'c' ) ),
		esc_html( get_the_modified_date() )
	);

	$posted_on = sprintf(
		_x( 'Posted on %s', 'post date', 'pu-ente' ),
		'' . $time_string . ''
	);

	$byline = sprintf(
		_x( 'by %s', 'post author', 'pu-ente' ),
		'' . esc_html( get_the_author() ) . ''
	);

	echo '' . $posted_on . ' ' . $byline . '';

}
endif;

if ( ! function_exists( 'pu_ente_entry_footer' ) ) :
/**
 * Prints HTML with meta information for the categories, tags and comments.
 */
function pu_ente_entry_footer() {
	// Hide category and tag text for pages.
	if ( 'post' == get_post_type() ) {
		/* translators: used between list items, there is a space after the comma */
		$categories_list = get_the_category_list( __( ', ', 'pu-ente' ) );
		if ( $categories_list && pu_ente_categorized_blog() ) {
			printf( '' . __( 'Posted in %1$s', 'pu-ente' ) . '', $categories_list );
		}

		/* translators: used between list items, there is a space after the comma */
		$tags_list = get_the_tag_list( '', __( ', ', 'pu-ente' ) );
		if ( $tags_list ) {
			printf( '' . __( 'Tagged %1$s', 'pu-ente' ) . '', $tags_list );
		}
	}

	if ( ! is_single() && ! post_password_required() && ( comments_open() || get_comments_number() ) ) {
		echo '';
		comments_popup_link( __( 'Leave a comment', 'pu-ente' ), __( '1 Comment', 'pu-ente' ), __( '% Comments', 'pu-ente' ) );
		echo '';
	}

	edit_post_link( __( 'Edit', 'pu-ente' ), '', '' );
}
endif;

if ( ! function_exists( 'the_archive_title' ) ) :
/**
 * Shim for `the_archive_title()`.
 *
 * Display the archive title based on the queried object.
 *
 * @todo Remove this function when WordPress 4.3 is released.
 *
 * @param string $before Optional. Content to prepend to the title. Default empty.
 * @param string $after  Optional. Content to append to the title. Default empty.
 */
function the_archive_title( $before = '', $after = '' ) {
	if ( is_category() ) {
		$title = sprintf( __( 'Category: %s', 'pu-ente' ), single_cat_title( '', false ) );
	} elseif ( is_tag() ) {
		$title = sprintf( __( 'Tag: %s', 'pu-ente' ), single_tag_title( '', false ) );
	} elseif ( is_author() ) {
		$title = sprintf( __( 'Author: %s', 'pu-ente' ), '' . get_the_author() . '' );
	} elseif ( is_year() ) {
		$title = sprintf( __( 'Year: %s', 'pu-ente' ), get_the_date( _x( 'Y', 'yearly archives date format', 'pu-ente' ) ) );
	} elseif ( is_month() ) {
		$title = sprintf( __( 'Month: %s', 'pu-ente' ), get_the_date( _x( 'F Y', 'monthly archives date format', 'pu-ente' ) ) );
	} elseif ( is_day() ) {
		$title = sprintf( __( 'Day: %s', 'pu-ente' ), get_the_date( _x( 'F j, Y', 'daily archives date format', 'pu-ente' ) ) );
	} elseif ( is_tax( 'post_format' ) ) {
		if ( is_tax( 'post_format', 'post-format-aside' ) ) {
			$title = _x( 'Asides', 'post format archive title', 'pu-ente' );
		} elseif ( is_tax( 'post_format', 'post-format-gallery' ) ) {
			$title = _x( 'Galleries', 'post format archive title', 'pu-ente' );
		} elseif ( is_tax( 'post_format', 'post-format-image' ) ) {
			$title = _x( 'Images', 'post format archive title', 'pu-ente' );
		} elseif ( is_tax( 'post_format', 'post-format-video' ) ) {
			$title = _x( 'Videos', 'post format archive title', 'pu-ente' );
		} elseif ( is_tax( 'post_format', 'post-format-quote' ) ) {
			$title = _x( 'Quotes', 'post format archive title', 'pu-ente' );
		} elseif ( is_tax( 'post_format', 'post-format-link' ) ) {
			$title = _x( 'Links', 'post format archive title', 'pu-ente' );
		} elseif ( is_tax( 'post_format', 'post-format-status' ) ) {
			$title = _x( 'Statuses', 'post format archive title', 'pu-ente' );
		} elseif ( is_tax( 'post_format', 'post-format-audio' ) ) {
			$title = _x( 'Audio', 'post format archive title', 'pu-ente' );
		} elseif ( is_tax( 'post_format', 'post-format-chat' ) ) {
			$title = _x( 'Chats', 'post format archive title', 'pu-ente' );
		}
	} elseif ( is_post_type_archive() ) {
		$title = sprintf( __( 'Archives: %s', 'pu-ente' ), post_type_archive_title( '', false ) );
	} elseif ( is_tax() ) {
		$tax = get_taxonomy( get_queried_object()->taxonomy );
		/* translators: 1: Taxonomy singular name, 2: Current taxonomy term */
		$title = sprintf( __( '%1$s: %2$s', 'pu-ente' ), $tax->labels->singular_name, single_term_title( '', false ) );
	} else {
		$title = __( 'Archives', 'pu-ente' );
	}

	/**
	 * Filter the archive title.
	 *
	 * @param string $title Archive title to be displayed.
	 */
	$title = apply_filters( 'get_the_archive_title', $title );

	if ( ! empty( $title ) ) {
		echo $before . $title . $after;
	}
}
endif;

if ( ! function_exists( 'the_archive_description' ) ) :
/**
 * Shim for `the_archive_description()`.
 *
 * Display category, tag, or term description.
 *
 * @todo Remove this function when WordPress 4.3 is released.
 *
 * @param string $before Optional. Content to prepend to the description. Default empty.
 * @param string $after  Optional. Content to append to the description. Default empty.
 */
function the_archive_description( $before = '', $after = '' ) {
	$description = apply_filters( 'get_the_archive_description', term_description() );

	if ( ! empty( $description ) ) {
		/**
		 * Filter the archive description.
		 *
		 * @see term_description()
		 *
		 * @param string $description Archive description to be displayed.
		 */
		echo $before . $description . $after;
	}
}
endif;

/**
 * Returns true if a blog has more than 1 category.
 *
 * @return bool
 */
function pu_ente_categorized_blog() {
	if ( false === ( $all_the_cool_cats = get_transient( 'pu_ente_categories' ) ) ) {
		// Create an array of all the categories that are attached to posts.
		$all_the_cool_cats = get_categories( array(
			'fields'     => 'ids',
			'hide_empty' => 1,

			// We only need to know if there is more than one category.
			'number'     => 2,
		) );

		// Count the number of categories that are attached to the posts.
		$all_the_cool_cats = count( $all_the_cool_cats );

		set_transient( 'pu_ente_categories', $all_the_cool_cats );
	}

	if ( $all_the_cool_cats > 1 ) {
		// This blog has more than 1 category so pu_ente_categorized_blog should return true.
		return true;
	} else {
		// This blog has only 1 category so pu_ente_categorized_blog should return false.
		return false;
	}
}

/**
 * Flush out the transients used in pu_ente_categorized_blog.
 */
function pu_ente_category_transient_flusher() {
	if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
		return;
	}
	// Like, beat it. Dig?
	delete_transient( 'pu_ente_categories' );
}
add_action( 'edit_category', 'pu_ente_category_transient_flusher' );
add_action( 'save_post',     'pu_ente_category_transient_flusher' );


text:
namespace scm {
namespace gl {

class __scm_export(gl_core) uniform_base
{
public:
    uniform_base(const std::string& n, const int l, const unsigned e, const data_type t);
    virtual ~uniform_base();

    const std::string&      name() const;
    const int               location() const;
    const unsigned          elements() const;
    const data_type         type() const;

    bool                    update_required() const;
    virtual void            apply_value(const render_context& context, const program& p) = 0;

protected:
    std::string             _name;
    int                     _location;
    unsigned                _elements;
    data_type               _type;

    struct {
        bool                _update_required : 1;
        bool                _initialized     : 1;
    }                       _status;

private:
    // declared, never defined
    uniform_base(const uniform_base&);
    const uniform_base& operator=(const uniform_base&);

    friend class scm::gl::program;
}; // class uniform_base

template<typename T, data_type D>
class uniform : public uniform_base
{
public:
    typedef T       value_type;

protected:
    typedef typename boost::call_traits<value_type>::param_type value_param_type;
    typedef std::vector<value_type>                             value_array;

public:
    uniform(const std::string& n, const int l, const unsigned e, const data_type t);
    virtual ~uniform();

    value_param_type        value() const;
    void                    set_value(value_param_type v);

    value_param_type        value(int i) const;
    void                    set_value(int i, value_param_type v);

    void                    apply_value(const render_context& context, const program& p);

protected:
    value_array             _value;

}; // class uniform

template<typename T>
struct uniform_type {
};

template<typename T>
struct uniform_data_type {
};

#define SCM_UNIFORM_TYPE_DECLARE(type_raw, type_id, uniform_type_name)                                  \
    typedef scm::gl::uniform<type_raw, type_id>          uniform_type_name;                             \
    typedef shared_ptr<scm::gl::uniform_type_name>       uniform_type_name##_ptr;                       \
    typedef shared_ptr<scm::gl::uniform_type_name const> uniform_type_name##_cptr;                      \
    template<> struct uniform_type<type_raw>      { typedef uniform_type_name  type; };                 \
    template<> struct uniform_data_type<type_raw> { static const data_type  type = type_id; };

SCM_UNIFORM_TYPE_DECLARE(float,             TYPE_FLOAT,  uniform_1f)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec2f,  TYPE_VEC2F,  uniform_vec2f)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec3f,  TYPE_VEC3F,  uniform_vec3f)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec4f,  TYPE_VEC4F,  uniform_vec4f)
SCM_UNIFORM_TYPE_DECLARE(scm::math::mat2f,  TYPE_MAT2F,  uniform_mat2f)
SCM_UNIFORM_TYPE_DECLARE(scm::math::mat3f,  TYPE_MAT3F,  uniform_mat3f)
SCM_UNIFORM_TYPE_DECLARE(scm::math::mat4f,  TYPE_MAT4F,  uniform_mat4f)

SCM_UNIFORM_TYPE_DECLARE(int,               TYPE_INT,    uniform_1i)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec2i,  TYPE_VEC2I,  uniform_vec2i)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec3i,  TYPE_VEC3I,  uniform_vec3i)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec4i,  TYPE_VEC4I,  uniform_vec4i)

SCM_UNIFORM_TYPE_DECLARE(unsigned,          TYPE_UINT,   uniform_1ui)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec2ui, TYPE_VEC2UI, uniform_vec2ui)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec3ui, TYPE_VEC3UI, uniform_vec3ui)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec4ui, TYPE_VEC4UI, uniform_vec4ui)

#if SCM_GL_CORE_OPENGL_CORE_VERSION >= SCM_GL_CORE_OPENGL_CORE_VERSION_400
SCM_UNIFORM_TYPE_DECLARE(double,            TYPE_DOUBLE, uniform_1d)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec2d,  TYPE_VEC2D,  uniform_vec2d)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec3d,  TYPE_VEC3D,  uniform_vec3d)
SCM_UNIFORM_TYPE_DECLARE(scm::math::vec4d,  TYPE_VEC4D,  uniform_vec4d)
SCM_UNIFORM_TYPE_DECLARE(scm::math::mat2d,  TYPE_MAT2D,  uniform_mat2d)
SCM_UNIFORM_TYPE_DECLARE(scm::math::mat3d,  TYPE_MAT3D,  uniform_mat3d)
SCM_UNIFORM_TYPE_DECLARE(scm::math::mat4d,  TYPE_MAT4D,  uniform_mat4d)
#endif // SCM_GL_CORE_OPENGL_CORE_VERSION >= SCM_GL_CORE_OPENGL_CORE_VERSION_400

//SCM_UNIFORM_TYPE_DECLARE(scm::uint64,       TYPE_SAMPLER, uniform_sampler)
//SCM_UNIFORM_TYPE_DECLARE(scm::uint64,       TYPE_IMAGE,   uniform_image)

// convenience
//typedef uniform_1i                                      uniform_sampler;
//typedef shared_ptr<scm::gl::uniform_sampler>            uniform_sampler_ptr;
//typedef shared_ptr<scm::gl::uniform_sampler const>      uniform_sampler_cptr;
//
//typedef uniform_1i                                      uniform_image;
//typedef shared_ptr<scm::gl::uniform_image>              uniform_image_ptr;
//typedef shared_ptr<scm::gl::uniform_image const>        uniform_image_cptr;

template<> struct uniform_type<bool>      { typedef uniform_1i  type; };
template<> struct uniform_data_type<bool> { static const data_type  type = TYPE_INT; };

class uniform_image_sampler_base : public uniform_base
{
public:
    uniform_image_sampler_base(const std::string& n, const int l, const unsigned e, const data_type t);
    virtual ~uniform_image_sampler_base();

    scm::int32              bound_unit() const;
    void                    bound_unit(scm::int32 v);

    scm::uint64             resident_handle();
    void                    resident_handle(scm::uint64 v);

    void                    apply_value(const render_context& context, const program& p);

protected:
    scm::int32              _bound_unit;
    scm::uint64             _resident_handle;

}; // class uniform_image_sampler_base

typedef uniform_image_sampler_base  uniform_sampler;
typedef shared_ptr<scm::gl::uniform_sampler>            uniform_sampler_ptr;
typedef shared_ptr<scm::gl::uniform_sampler const>      uniform_sampler_cptr;

typedef uniform_image_sampler_base  uniform_image;
typedef shared_ptr<scm::gl::uniform_image>              uniform_image_ptr;
typedef shared_ptr<scm::gl::uniform_image const>        uniform_image_cptr;

#undef SCM_UNIFORM_TYPE_DECLARE

} // namespace gl
} // namespace scm

#include <scm/core/utilities/platform_warning_enable.h>

#endif // SCM_GL_CORE_UNIFORM_H_INCLUDED


text:
package preferences.mappingconfig;

import de.unihamburg.swk.parsing.document.TermMapperManager;

import javax.swing.table.DefaultTableModel;
import java.util.List;
import java.util.Map;

/**
 * Created by Gerrit Greiert on 14.04.17.
 */
public class MappingsTableModel extends DefaultTableModel {

    public static final String TYPE_COLUMN_NAME = "Type";
    public static final String SOURCE_COLUMN_NAME = "Source";
    public static final String TARGET_COLUMN_NAME = "Target";

    public static final String TYPE = "Type";
    public static final String VARIABLE = "Variable";
    public static final String FUNCTION = "Method";

    private final TermMapperManager termMapperManager;
    private Map<String, String> types;
    private Map<String, String> variables;
    private Map<String, String> functions;

    public MappingsTableModel(String mappingsFilePath, TermMapperManager mapper){

        termMapperManager = mapper;
        termMapperManager.setData(mappingsFilePath);
        List<Map<String, String>> dataList = termMapperManager.getData();

        types = dataList.get(0);
        variables = dataList.get(1);
        functions = dataList.get(2);

        this.addColumn(TYPE_COLUMN_NAME);
        this.addColumn(SOURCE_COLUMN_NAME);
        this.addColumn(TARGET_COLUMN_NAME);

        for (Map.Entry<String, String> entry: types.entrySet()) {
            this.addRow(new String[]{TYPE, entry.getKey(), entry.getValue()});
        }
        for (Map.Entry<String, String> entry: variables.entrySet()) {
            this.addRow(new String[]{VARIABLE, entry.getKey(), entry.getValue()});
        }
        for (Map.Entry<String, String> entry: functions.entrySet()) {
            this.addRow(new String[]{FUNCTION, entry.getKey(), entry.getValue()});
        }
    }

    public void writeMappings(){

        types.clear();
        variables.clear();
        functions.clear();

        for (int rowIndex = 0; rowIndex < getRowCount(); rowIndex++) {
            String type = (String) getValueAt(rowIndex, 0);
            String source = (String) getValueAt(rowIndex, 1);
            String target = (String) getValueAt(rowIndex, 2);

            if (type.equals(TYPE)){
                types.put(source, target);
            }
            else if (type.equals(VARIABLE)) {
                variables.put(source, target);
            }
            else if (type.equals(FUNCTION)) {
                functions.put(source, target);
            }
            else
                System.out.println("Unknown mapping type");

        }

        termMapperManager.setData(types, functions, variables);
        TermMapperManager.persist();
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

/*
 * This class controls buttons used to change the scene that is being shown (next level, restart, etc)
 */

public class ChangeLevel : MonoBehaviour {

	public Button ChangeSceneButton; //the button used to change the scene
	public int SceneToLoad; //the int value of the scene to load

	void Start () {
		Button btn = ChangeSceneButton.GetComponent<Button>();
		btn.onClick.AddListener(TaskOnClick);
	}

	void TaskOnClick(){
		Time.timeScale = 1; //timeScale is changed to 0 when next "next level panel" appears, this undoes that
		Application.LoadLevel (SceneToLoad);
	}
}


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/**
   File Name:          lexical-054.js
   Corresponds to:     7.8.2-7-n.js
   ECMA Section:       7.8.2 Examples of Automatic Semicolon Insertion
   Description:        compare some specific examples of the automatic
   insertion rules in the EMCA specification.
   Author:             christine@netscape.com
   Date:               15 september 1997
*/

var SECTION = "lexical-054";
var VERSION = "JS1_4";
var TITLE   = "Examples of Automatic Semicolon Insertion";

startTest();
writeHeaderToLog( SECTION + " "+ TITLE);

var result = "Failed";
var exception = "No exception thrown";
var expect = "Passed";

try {
  a=0;
  b=1;
  c=2;
  d=3;
  eval("if (a > b)\nelse c = d");
} catch ( e ) {
  result = expect;
  exception = e.toString();
}

new TestCase(
  SECTION,
  "if (a > b)\nelse c = d" +
  " (threw " + exception +")",
  expect,
  result );

test();


text:
'use strict';

jest.mock('execa');
jest.mock('cross-spawn');
const globalModulesNpmValue = 'test-npm';
jest.setMock('global-modules', globalModulesNpmValue);
jest.setMock('enquirer', {
    prompt: jest.fn(),
});

jest.setMock('../run-command', {
    runCommand: jest.fn(),
});

jest.setMock('../package-exists', {
    packageExists: jest.fn(),
});

jest.setMock('../get-package-manager', jest.fn());

const getPackageManager = require('../get-package-manager');
const { packageExists } = require('../package-exists');
const { promptInstallation } = require('../prompt-installation');
const { runCommand } = require('../run-command');
const { prompt } = require('enquirer');

describe('promptInstallation', () => {
    beforeAll(() => {
        packageExists.mockReturnValue(true);
    });
    beforeEach(() => {
        runCommand.mockClear();
        prompt.mockClear();
    });

    it('should prompt to install using npm if npm is package manager', async () => {
        prompt.mockReturnValue({
            installConfirm: true,
        });
        getPackageManager.mockReturnValue('npm');
        const preMessage = jest.fn();
        const promptResult = await promptInstallation('test-package', preMessage);
        expect(promptResult).toBeTruthy();
        expect(preMessage.mock.calls.length).toEqual(1);
        expect(prompt.mock.calls.length).toEqual(1);
        expect(runCommand.mock.calls.length).toEqual(1);
        expect(prompt.mock.calls[0][0][0].message).toMatch(/Would you like to install test-package\?/);
        // install the package using npm
        expect(runCommand.mock.calls[0][0]).toEqual('npm install -D test-package');
    });

    it('should prompt to install using yarn if yarn is package manager', async () => {
        prompt.mockReturnValue({
            installConfirm: true,
        });
        getPackageManager.mockReturnValue('yarn');

        const promptResult = await promptInstallation('test-package');
        expect(promptResult).toBeTruthy();
        expect(prompt.mock.calls.length).toEqual(1);
        expect(runCommand.mock.calls.length).toEqual(1);
        expect(prompt.mock.calls[0][0][0].message).toMatch(/Would you like to install test-package\?/);
        // install the package using yarn
        expect(runCommand.mock.calls[0][0]).toEqual('yarn add -D test-package');
    });

    it('should not install if install is not confirmed', async () => {
        prompt.mockReturnValue({
            installConfirm: false,
        });

        const promptResult = await promptInstallation('test-package');
        expect(promptResult).toBeUndefined();
        expect(prompt.mock.calls.length).toEqual(1);
        // runCommand should not be called, because the installation is not confirmed
        expect(runCommand.mock.calls.length).toEqual(0);
        expect(prompt.mock.calls[0][0][0].message).toMatch(/Would you like to install test-package\?/);
        expect(process.exitCode).toEqual(2);
    });
});


text:
{% extends "admin/base_site.html" %}
{% load i18n admin_urls admin_static admin_list %}

{% block extrastyle %}
    {{ block.super }}
    <link rel="stylesheet" href="{% static 'organigrammi/jquery-ui/jquery-ui.min.css' %}">
    <link rel="stylesheet" href="{% static 'organigrammi/css/riepilogo_presenze.css' %}">
    <link rel="stylesheet" media="print" href="{% static 'organigrammi/css/print_riepilogo_presenze.css' %}">
{% endblock %}

{% block extrahead %}

{% endblock %}

{% block content %}

        <form id="form_filter" method="get" action="">

                {{ form.as_p }}
                <input type="submit" id="filter" value="Filtra">

        </form>

                    {% for h in table_header %}
                        <th{% if forloop.revcounter <= 3 %} class="presenze"{% endif %}>{{ h|safe }}
                    {% endfor %}

            {% for row in table_rows %}

                    {% for el in row %}
                        {% if forloop.revcounter <= 3 %}
                            {{ el }}
                        {% elif forloop.first %}
                            {{ el.0 }}
                        {% else %}
                            {{ el.0 }}{% if el.0 == 'P' and el.1 > 0 %} ({{el.1}}€){% endif %}
                        {% endif %}
                    {% endfor %}

            {% endfor %}

{% endblock %}


text:
using StreamingClient.Base.Model.OAuth;
using StreamingClient.Base.Util;
using StreamingClient.Base.Web;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace Twitch.Base.Services
{
    /// <summary>
    /// The APIs for OAuth-based services.
    /// </summary>
    public class OAuthService : TwitchServiceBase
    {
        private const string OAuthBaseAddress = "https://id.twitch.tv/";

        /// <summary>
        /// Creates an instance of the OAuthService.
        /// </summary>
        /// <param name="connection">The Twitch connection to use</param>
        public OAuthService(TwitchConnection connection) : base(connection, OAuthBaseAddress) { }

        internal OAuthService() : base(OAuthBaseAddress) { }

        /// <summary>
        /// Creates an OAuth token for authenticating with the Twitch services.
        /// </summary>
        /// <param name="clientID">The id of the client application</param>
        /// <param name="authorizationCode">The authorization code</param>
        /// <param name="redirectUrl">The URL to redirect to after authorization is complete</param>
        /// <returns>The OAuth token</returns>
        public async Task<OAuthTokenModel> GetOAuthTokenModel(string clientID, string authorizationCode, string redirectUrl = null)
        {
            return await this.GetOAuthTokenModel(clientID, null, authorizationCode, redirectUrl);
        }

        /// <summary>
        /// Creates an OAuth token for authenticating with the Twitch services.
        /// </summary>
        /// <param name="clientID">The id of the client application</param>
        /// <param name="clientSecret">The secret key of the client application</param>
        /// <param name="authorizationCode">The authorization code</param>
        /// <param name="redirectUrl">The URL to redirect to after authorization is complete</param>
        /// <returns>The OAuth token</returns>
        public async Task<OAuthTokenModel> GetOAuthTokenModel(string clientID, string clientSecret, string authorizationCode, string redirectUrl = null)
        {
            Validator.ValidateString(clientID, "clientID");
            Validator.ValidateString(authorizationCode, "authorizationCode");

            Dictionary<string, string> parameters = new Dictionary<string, string>()
            {
                { "client_id", clientID },
                { "client_secret", clientSecret },
                { "code", authorizationCode },
                { "grant_type", "authorization_code" },
                { "redirect_uri", redirectUrl },
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(parameters.AsEnumerable());

            OAuthTokenModel token = await this.PostAsync<OAuthTokenModel>("oauth2/token?" + await content.ReadAsStringAsync(), AdvancedHttpClient.CreateContentFromObject(string.Empty), autoRefreshToken: false);
            token.clientID = clientID;
            token.clientSecret = clientSecret;
            token.authorizationCode = authorizationCode;
            return token;
        }

        /// <summary>
        /// Refreshes the specified OAuth token.
        /// </summary>
        /// <param name="token">The token to refresh</param>
        /// <returns>The refreshed token</returns>
        public async Task<OAuthTokenModel> RefreshToken(OAuthTokenModel token)
        {
            Validator.ValidateVariable(token, "token");

            Dictionary<string, string> parameters = new Dictionary<string, string>()
            {
                { "client_id", token.clientID },
                { "client_secret", token.clientSecret },
                { "refresh_token", token.refreshToken },
                { "grant_type", "refresh_token" },
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(parameters.AsEnumerable());

            OAuthTokenModel newToken = await this.PostAsync<OAuthTokenModel>("oauth2/token?" + await content.ReadAsStringAsync(), AdvancedHttpClient.CreateContentFromObject(string.Empty), autoRefreshToken: false);
            newToken.clientID = token.clientID;
            newToken.clientSecret = token.clientSecret;
            newToken.authorizationCode = token.authorizationCode;
            return newToken;
        }
    }
}


text:
#import <Foundation/Foundation.h>

#import <MatrixSDK/MatrixSDK.h>

/**
 Temporary category to help in the transition from synchronous access to room.state
 to asynchronous access.
 */
@interface MXRoom (Sync)

/**
 Get the room state if it has been already loaded else return nil.

 Use this method only where you are sure the room state is already mounted.
 */
@property (nonatomic, readonly) MXRoomState *dangerousSyncState;

@end


text:
package jpaoletti.jpm2.web.converter;

import javax.servlet.http.HttpSession;
import jpaoletti.jpm2.core.exception.ConverterException;
import jpaoletti.jpm2.core.exception.FieldNotFoundException;
import jpaoletti.jpm2.core.exception.IgnoreConvertionException;
import jpaoletti.jpm2.core.model.ContextualEntity;
import jpaoletti.jpm2.core.model.Field;
import jpaoletti.jpm2.util.JPMUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * This file converter do not rely in a disk file but in a session attribute.
 *
 * @author jpaoletti
 */
public class EditFileInMemoryConverter extends BaseEditFileConverter {

    @Autowired
    private HttpSession session;
    private String contentTypeField = null;

    @Override
    protected String getPage(ContextualEntity contextualEntity, Field field, Object object, String instanceId) {
        return "@page:file-converter.jsp?postAction=uploadFileInMemoryConverter&accept=" + getAccept() + "&";
    }

    @Override
    public Object build(ContextualEntity contextualEntity, Field field, Object object, Object newValue) throws ConverterException {
        if (newValue != null && newValue.equals("@current:")) {
            throw new IgnoreConvertionException();
        }
        if (newValue == null || newValue.equals("")) {
            return null;
        }
        byte[] bFile = (byte[]) session.getAttribute(newValue.toString());

        if (bFile == null) {
            JPMUtils.getLogger().error("File not exists in file converter");
            throw new ConverterException("jpm.error.uploading.file");
        }
        try {
            if (getFilenameField() != null) {
                try {
                    final Field f = contextualEntity.getEntity().getFieldById(getFilenameField(), contextualEntity.getContext());
                    JPMUtils.set(object, f.getProperty(), session.getAttribute(newValue + "originalName"));
                    session.removeAttribute(newValue + "originalName");
                } catch (FieldNotFoundException ex) {
                    JPMUtils.getLogger().error("Filename field not exists");
                    throw new ConverterException("jpm.error.uploading.file");
                }
            }
            if (contentTypeField != null) {
                try {
                    final Field f = contextualEntity.getEntity().getFieldById(contentTypeField, contextualEntity.getContext());
                    JPMUtils.set(object, f.getProperty(), session.getAttribute(newValue + "originalContentType"));
                    session.removeAttribute(newValue + "originalContentType");
                } catch (FieldNotFoundException ex) {
                    JPMUtils.getLogger().error("Filename field not exists");
                    throw new ConverterException("jpm.error.uploading.file");
                }
            }
        } finally {
            session.removeAttribute(newValue.toString());
        }
        return bFile;
    }

    public String getContentTypeField() {
        return contentTypeField;
    }

    public void setContentTypeField(String contentTypeField) {
        this.contentTypeField = contentTypeField;
    }

}