text:
+++
title = "Bruna Martins Grellt"
Twitter = ""
linkedin = ""
image = "bruna.jpg"
type = "speaker"
linktitle = "bruna-grellt"
+++

Curiosa e comunicativa por natureza, estudante de Analise em desenvolvimento de sistemas, adoro desafios, principalmente aqueles que me tiram da zona de conforto e com enorme paixão em ajudar e entender a dor do cliente
Profissional na área de TI a aproximadamente 6 anos, exercendo funções de suporte técnico, projetos de implementação de Cloud Hosting, atuando na cultura de Customer Success voltada a fidelização do cliente na plataforma.

Minha meta é ajudar as pessoas a perceberem que são responsáveis por criarem sua própria sorte e oportunidades.


text:
'use strict'
var signMsgCtrl = function($scope, $sce, walletService) {
	walletService.wallet = null;
	$scope.visibility = "signView";
	$scope.$watch(function() {
		if (walletService.wallet == null) return null
		return walletService.wallet.getAddressString()
	}, function() {
		if (walletService.wallet == null) return
		$scope.wallet = walletService.wallet
	});
	$scope.signMsg = {
		message: '',
		dateTime: '',
		status: '',
		signedMsg: ''
	}
	$scope.verifyMsg = {
		signedMsg: '',
		status: ''
	}
	$scope.generateSignedMsg = function() {
		try {
      var thisMsg    = $scope.signMsg.message
      var thisDate   = $scope.signMsg.dateTime
      var thisSpacer = (thisMsg.length > 0 && thisDate.length > 0) ? ' ' : ''
			var thisMessage = thisMsg + thisSpacer + thisDate
			var hash = ethUtil.sha3(thisMessage)
			var signed = ethUtil.ecsign(hash, $scope.wallet.getPrivateKey())
			var combined = Buffer.concat([Buffer.from(signed.r), Buffer.from(signed.s), Buffer.from([signed.v])])
			var combinedHex = combined.toString('hex')
			$scope.signMsg.signedMsg = JSON.stringify({
				address: $scope.wallet.getChecksumAddressString(),
				msg: thisMessage,
				sig: '0x' + combinedHex
			})
		} catch (e) {
			$scope.notifier.danger(e)
		}
	}
	$scope.verifySignedMessage = function() {
		try{
		  var json = JSON.parse($scope.verifyMsg.signedMsg);
          var sig = new Buffer(ethFuncs.getNakedAddress(json.sig),'hex');
          if(sig.length!=65) throw globalFuncs.errorMsgs[12];
          sig[64] = sig[64]==0||sig[64]==1 ? sig[64]+27 : sig[64];
          var hash = ethUtil.sha3(json.msg);
          var pubKey = ethUtil.ecrecover(hash, sig[64], sig.slice(0,32), sig.slice(32,64));
          if(ethFuncs.getNakedAddress(json.address)!=ethUtil.pubToAddress(pubKey).toString('hex')) throw globalFuncs.errorMsgs[12];
          else $scope.notifier.success(globalFuncs.successMsgs[6]);
		} catch (e){
		  $scope.notifier.danger(e);
		}
	}
	$scope.setVisibility = function(str) {
		$scope.visibility = str;
	}
}
module.exports = signMsgCtrl

redpajama_set_name: RedPajamaGithub


text:
// Package user is the result of users and clients ended up having to be split
// apart after all, once adding the SQL backing started falling into place.
// Users are very similar to clients, except that they are unique across the
// whole server and can log in via the web interface, while clients are only
// unique across an organization and cannot log in over the web. Basically,
// users are generally for something you would do, while a client would be
// associated with a specific node.
//
// Note: At this time, organizations are not implemented, so the difference
// between clients and users is a little less stark.
package user

import (
	"bytes"
	"database/sql"
	"encoding/gob"
	"fmt"
	"net/http"

	"github.com/ctdk/chefcrypto"
	"github.com/ctdk/goiardi/config"
	"github.com/ctdk/goiardi/datastore"
	"github.com/ctdk/goiardi/secret"
	"github.com/ctdk/goiardi/util"
	"github.com/tideland/golib/logger"
)

// User is, uh, a user. It's very similar to a Client, but subtly different, as
// explained elsewhere.
type User struct {
	Username string `json:"username"`
	Name     string `json:"name"`
	Email    string `json:"email"`
	Admin    bool   `json:"admin"`
	pubKey   string
	passwd   string
	salt     []byte
}

type privUser struct {
	Username  *string `json:"username"`
	Name      *string `json:"name"`
	Email     *string `json:"email"`
	Admin     *bool   `json:"admin"`
	PublicKey *string `json:"public_key"`
	Passwd    *string `json:"password"`
	Salt      *[]byte `json:"salt"`
}

// New creates a new API user.
func New(name string) (*User, util.Gerror) {
	var found bool
	var err util.Gerror
	if config.UsingDB() {
		var uerr error
		found, uerr = checkForUserSQL(datastore.Dbh, name)
		if uerr != nil {
			err = util.Errorf(uerr.Error())
			err.SetStatus(http.StatusInternalServerError)
			return nil, err
		}
	} else {
		ds := datastore.New()
		_, found = ds.Get("user", name)
	}
	if found {
		err := util.Errorf("User '%s' already exists", name)
		err.SetStatus(http.StatusConflict)
		return nil, err
	}

	if err := validateUserName(name); err != nil {
		return nil, err
	}

	salt, saltErr := chefcrypto.GenerateSalt()
	if saltErr != nil {
		err := util.Errorf(saltErr.Error())
		return nil, err
	}
	user := &User{
		Username: name,
		Name:     name,
		Admin:    false,
		Email:    "",
		pubKey:   "",
		salt:     salt,
	}
	return user, nil
}

// Get a user.
func Get(name string) (*User, util.Gerror) {
	var user *User
	if config.UsingDB() {
		var err error
		user, err = getUserSQL(name)
		if err != nil {
			var gerr util.Gerror
			if err != sql.ErrNoRows {
				gerr = util.Errorf(err.Error())
				gerr.SetStatus(http.StatusInternalServerError)
			} else {
				gerr = util.Errorf("Client %s not found", name)
				gerr.SetStatus(http.StatusNotFound)
			}
			return nil, gerr
		}
	} else {
		ds := datastore.New()
		u, found := ds.Get("user", name)
		if !found {
			err := util.Errorf("User %s not found", name)
			return nil, err
		}
		if u != nil {
			user = u.(*User)
		}
	}
	return user, nil
}

// DoesExist checks if the user in question exists or not
func DoesExist(userName string) (bool, util.Gerror) {
	var found bool
	if config.UsingDB() {
		var cerr error
		found, cerr = checkForUserSQL(datastore.Dbh, userName)
		if cerr != nil {
			err := util.Errorf(cerr.Error())
			err.SetStatus(http.StatusInternalServerError)
			return false, err
		}
	} else {
		ds := datastore.New()
		_, found = ds.Get("user", userName)
	}
	return found, nil
}

// Save the user's current state.
func (u *User) Save() util.Gerror {
	if config.UsingDB() {
		var err util.Gerror
		if config.Config.UseMySQL {
			err = u.saveMySQL()
		} else {
			err = u.savePostgreSQL()
		}
		if err != nil {
			return err
		}
	} else {
		if err := chkInMemClient(u.Username); err != nil {
			gerr := util.Errorf(err.Error())
			gerr.SetStatus(http.StatusConflict)
			return gerr
		}
		ds := datastore.New()
		ds.Set("user", u.Username, u)
	}
	return nil
}

// Delete a user, but will refuse to do so and give an error if it is the last
// administrator user.
func (u *User) Delete() util.Gerror {
	if u.isLastAdmin() {
		err := util.Errorf("Cannot delete the last admin")
		return err
	}
	if config.UsingDB() {
		err := u.deleteSQL()
		if err != nil {
			gerr := util.CastErr(err)
			return gerr
		}
	} else {
		ds := datastore.New()
		ds.Delete("user", u.Username)
	}
	if config.UsingExternalSecrets() {
		err := secret.DeletePublicKey(u)
		if err != nil {
			return util.CastErr(err)
		}
		err = secret.DeletePasswdHash(u)
		if err != nil {
			return util.CastErr(err)
		}
	}
	return nil
}

// Rename a user. Save() must be called after this method is used. Will not
// rename the last administrator user.
func (u *User) Rename(newName string) util.Gerror {
	if err := validateUserName(newName); err != nil {
		return err
	}
	if u.isLastAdmin() {
		err := util.Errorf("Cannot rename the last admin")
		err.SetStatus(http.StatusForbidden)
		return err
	}
	var pk string
	var pw string
	if config.UsingExternalSecrets() {
		pk = u.PublicKey()
		pw = u.Passwd()
		err := secret.DeletePublicKey(u)
		if err != nil {
			return util.CastErr(err)
		}
		err = secret.DeletePasswdHash(u)
		if err != nil {
			return util.CastErr(err)
		}
	}
	if config.UsingDB() {
		if config.Config.UseMySQL {
			if err := u.renameMySQL(newName); err != nil {
				return err
			}
		} else if config.Config.UsePostgreSQL {
			if err := u.renamePostgreSQL(newName); err != nil {
				return err
			}
		}
	} else {
		ds := datastore.New()
		if err := chkInMemClient(newName); err != nil {
			gerr := util.Errorf(err.Error())
			gerr.SetStatus(http.StatusConflict)
			return gerr
		}
		if _, found := ds.Get("user", newName); found {
			err := util.Errorf("User %s already exists, cannot rename %s", newName, u.Username)
			err.SetStatus(http.StatusConflict)
			return err
		}
		ds.Delete("client", u.Username)
	}
	u.Username = newName
	if config.UsingExternalSecrets() {
		err := secret.SetPublicKey(u, pk)
		if err != nil {
			return util.CastErr(err)
		}
		err = secret.SetPasswdHash(u, pw)
		if err != nil {
			return util.CastErr(err)
		}
	}
	return nil
}

// NewFromJSON builds a new user from a JSON object.
func NewFromJSON(jsonUser map[string]interface{}) (*User, util.Gerror) {
	userName, nerr := util.ValidateAsString(jsonUser["name"])
	if nerr != nil {
		return nil, nerr
	}
	user, err := New(userName)
	if err != nil {
		return nil, err
	}
	// check if the password is supplied if this is a user, and fail if
	// it isn't.
	if _, ok := jsonUser["password"]; !ok {
		err := util.Errorf("Field 'password' missing")
		return nil, err
	}
	err = user.UpdateFromJSON(jsonUser)
	if err != nil {
		return nil, err
	}
	return user, nil
}

// UpdateFromJSON updates a user from a JSON object, carrying out a bunch of
// validations inside.
func (u *User) UpdateFromJSON(jsonUser map[string]interface{}) util.Gerror {
	userName, nerr := util.ValidateAsString(jsonUser["name"])
	if nerr != nil {
		return nerr
	}
	if u.Username != userName {
		err := util.Errorf("User name %s and %s from JSON do not match", u.Username, userName)
		return err
	}

	/* Validations. */
	/* Invalid top level elements */
	validElements := []string{"username", "name", "org_name", "public_key", "private_key", "admin", "password",
		"email", "salt", "chef_type", "display_name", "json_class", "openid"}
ValidElem:
	for k := range jsonUser {
		for _, i := range validElements {
			if k == i {
				continue ValidElem
			}
		}
		err := util.Errorf("Invalid key %s in request body", k)
		return err
	}
	var verr util.Gerror

	// Check the password first. If it's bad, bail before touching anything
	// else.
	if passwd, ok := jsonUser["password"]; ok {
		if passwd != nil {
			passwd, verr = util.ValidateAsString(passwd)
			if verr != nil {
				return verr
			}
			if passwd != "" {
				verr = u.SetPasswd(passwd.(string))
				if verr != nil {
					return verr
				}
			}
		}
	}

	if adminVal, ok := jsonUser["admin"]; ok {
		var ab bool
		if ab, verr = util.ValidateAsBool(adminVal); verr != nil {
			// NOTE: may need to tweak this error message depending
			// if this is a user or a client
			verr = util.Errorf("Field 'admin' invalid")
			return verr
		} else if u.Admin && !ab {
			if u.isLastAdmin() {
				verr = util.Errorf("Cannot remove admin status from the last admin")
				verr.SetStatus(http.StatusForbidden)
				return verr
			}
		}
		u.Admin = ab
	}

	return nil
}

// SetPasswdHash is a utility function to directly set a password hash. Only
// especially useful when importing user data with the -m/--import flags, since
// it's still hashed with the user's salt.
func (u *User) SetPasswdHash(pwhash string) {
	if pwhash != "" {
		if config.UsingExternalSecrets() {
			secret.SetPasswdHash(u, pwhash)
		} else {
			u.passwd = pwhash
		}
	}
}

// GetList returns a list of users.
func GetList() []string {
	var userList []string
	if config.UsingDB() {
		userList = getListSQL()
	} else {
		ds := datastore.New()
		userList = ds.GetList("user")
	}
	return userList
}

// ToJSON converts the user to a JSON object, massaging it as needed to keep
// the chef client happy (be it knife, chef-pedant, etc.) NOTE: There may be a
// more idiomatic way to do this.
func (u *User) ToJSON() map[string]interface{} {
	toJSON := make(map[string]interface{})
	toJSON["name"] = u.Name
	toJSON["admin"] = u.Admin
	toJSON["public_key"] = u.PublicKey()

	return toJSON
}

func (u *User) isLastAdmin() bool {
	if u.Admin {
		numAdmins := 0
		if config.UsingDB() {
			numAdmins = numAdminsSQL()
		} else {
			userList := GetList()
			for _, u := range userList {
				u1, _ := Get(u)
				if u1 != nil && u1.Admin {
					numAdmins++
				}
			}
		}
		if numAdmins == 1 {
			return true
		}
	}
	return false
}

// GenerateKeys generates a new set of RSA keys for the user. The new private
// key is saved with the user object, the public key is given to the user and
// not saved on the server at all.
func (u *User) GenerateKeys() (string, error) {
	privPem, pubPem, err := chefcrypto.GenerateRSAKeys()
	if err != nil {
		return "", err
	}
	u.SetPublicKey(pubPem)
	return privPem, nil
}

// ValidatePublicKey checks that the provided public key is valid. Wrapper
// around chefcrypto.ValidatePublicKey(), but with a different error type.
func ValidatePublicKey(publicKey interface{}) (bool, util.Gerror) {
	ok, pkerr := chefcrypto.ValidatePublicKey(publicKey)
	var err util.Gerror
	if !ok {
		err = util.CastErr(pkerr)
	}
	return ok, err
}

// IsAdmin returns true if the user is an admin. If use-auth is false, this
// always returns true.
func (u *User) IsAdmin() bool {
	if !config.Config.UseAuth {
		return true
	}
	return u.Admin
}

// IsValidator always returns false, since users are never validators. This is
// true even if auth mode is not on.
func (u *User) IsValidator() bool {
	return false
}

// IsSelf returns true if the actor in question s the same client or user as the
// caller. Always returns true if use-auth is false.
func (u *User) IsSelf(other interface{}) bool {
	if !config.Config.UseAuth {
		return true
	}
	if ou, ok := other.(*User); ok {
		if u.Username == ou.Username {
			return true
		}
	}
	return false
}

// IsUser returns true for users.
func (u *User) IsUser() bool {
	return true
}

// IsClient returns false for users.
func (u *User) IsClient() bool {
	return false
}

// PublicKey returns the user's public key. Part of the Actor interface.
func (u *User) PublicKey() string {
	if config.UsingExternalSecrets() {
		pk, err := secret.GetPublicKey(u)
		if err != nil {
			// pubKey's not goign to work very well if we can't get
			// it....
			logger.Errorf(err.Error())
			return ""
		}
		return pk
	}
	return u.pubKey
}

// SetPublicKey does what it says on the tin. Part of the Actor interface.
func (u *User) SetPublicKey(pk interface{}) error {
	switch pk := pk.(type) {
	case string:
		ok, err := ValidatePublicKey(pk)
		if !ok {
			return err
		}
		if config.UsingExternalSecrets() {
			pubErr := secret.SetPublicKey(u, pk)
			if pubErr != nil {
				return pubErr
			}
		} else {
			u.pubKey = pk
		}
	default:
		err := fmt.Errorf("invalid type %T for public key", pk)
		return err
	}
	return nil
}

// CheckPermEdit checks to see if the user is trying to edit admin and
// validator attributes, and if it has permissions to do so.
func (u *User) CheckPermEdit(userData map[string]interface{}, perm string) util.Gerror {
	gerr := util.Errorf("You are not allowed to take this action.")
	gerr.SetStatus(http.StatusForbidden)

	if av, ok := userData[perm]; ok {
		if a, _ := util.ValidateAsBool(av); a {
			return gerr
		}
	}
	return nil
}

// SetPasswd validates and sets the user's password. Will not set a password for
// a client.
func (u *User) SetPasswd(password string) util.Gerror {
	if len(password) < 6 {
		err := util.Errorf("Password must have at least 6 characters")
		return err
	}
	/* If those validations pass, set the password */
	pw, perr := chefcrypto.HashPasswd(password, u.salt)
	if perr != nil {
		err := util.Errorf(perr.Error())
		return err
	}
	if config.UsingExternalSecrets() {
		err := secret.SetPasswdHash(u, pw)
		if err != nil {
			return util.CastErr(err)
		}
	} else {
		u.passwd = pw
	}
	return nil
}

// CheckPasswd checks the provided password to see if it matches the stored
// password hash.
func (u *User) CheckPasswd(password string) util.Gerror {
	h, perr := chefcrypto.HashPasswd(password, u.salt)
	if perr != nil {
		err := util.Errorf(perr.Error())
		return err
	}
	if u.Passwd() != h {
		err := util.Errorf("password did not match")
		return err
	}

	return nil
}

// Passwd returns the password hash, either from the user object or an external
// secret store
func (u *User) Passwd() string {
	if config.UsingExternalSecrets() {
		pw, err := secret.GetPasswdHash(u)
		if err != nil {
			logger.Errorf(err.Error())
		}
		return pw
	}
	return u.passwd
}

func validateUserName(name string) util.Gerror {
	if !util.ValidateUserName(name) {
		err := util.Errorf("Field 'name' invalid")
		return err
	}
	return nil
}

// GetName returns the user's name.
func (u *User) GetName() string {
	return u.Username
}

// URLType returns the base element of a user's URL.
func (u *User) URLType() string {
	return "users"
}

func (u *User) export() *privUser {
	return &privUser{Name: &u.Name, Username: &u.Username, PublicKey: &u.pubKey, Admin: &u.Admin, Email: &u.Email, Passwd: &u.passwd, Salt: &u.salt}
}

func (u *User) GobEncode() ([]byte, error) {
	prv := u.export()
	buf := new(bytes.Buffer)
	decoder := gob.NewEncoder(buf)
	if err := decoder.Encode(prv); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

func (u *User) GobDecode(b []byte) error {
	prv := u.export()
	buf := bytes.NewReader(b)
	encoder := gob.NewDecoder(buf)
	err := encoder.Decode(prv)
	if err != nil {
		return err
	}

	return nil
}

// AllUsers returns all the users on this server.
func AllUsers() []*User {
	var users []*User
	if config.UsingDB() {
		users = allUsersSQL()
	} else {
		userList := GetList()
		for _, u := range userList {
			us, err := Get(u)
			if err != nil {
				continue
			}
			users = append(users, us)
		}
	}
	return users
}

// ExportAllUsers return all users, in a fashion suitable for exporting.
func ExportAllUsers() []interface{} {
	users := AllUsers()
	export := make([]interface{}, len(users))
	for i, u := range users {
		export[i] = u.export()
	}
	return export
}

func chkInMemClient(name string) error {
	var err error
	ds := datastore.New()
	if _, found := ds.Get("client", name); found {
		err = fmt.Errorf("a client named %s was found that would conflict with this user", name)
	}
	return err
}


text:
require("node-opcua-service-secure-channel");
const TimestampsToReturn = require("node-opcua-data-value").TimestampsToReturn;

/*
 * Maximum age of the value to be read in milliseconds. The age of the value is based on the difference between the
 * ServerTimestamp and the time when the Server starts processing the request. For example if the Client specifies a
 * maxAge of 500 milliseconds and it takes 100 milliseconds until the Server starts processing the request, the age of
 * the returned value could be 600 milliseconds prior to the time it was requested.
 * If the Server has one or more values of an Attribute that are within the maximum age, it can return any one of the
 * values or it can read a new value from the data source. The number of values of an Attribute that a Server has
 * depends on the number of MonitoredItems that are defined for the Attribute.
 * In any case, the Client can make no assumption about which copy of the data will be returned.
 * If the Server does not have a value that is within the maximum age, it shall attempt to read a new value from the
 * data source.
 * If the Server cannot meet the requested maxAge, it returns its "best effort" value rather than rejecting the request.
 * This may occur when the time it takes the Server to process and return the new data value after it has been accessed
 * is greater than the specified maximum age.
 * If maxAge is set to 0, the Server shall attempt to read a new value from the data source.
 * If maxAge is set to the max Int32 value or greater, the Server shall attempt to get a cached value.
 * Negative values are invalid for maxAge.
 * @class ReadRequest
 */

const Obsolete_ReadRequest_schema = {
    name: "ReadRequest",
    fields: [
        {   name: "requestHeader" ,               fieldType: "RequestHeader"},

        {   name: "maxAge",                       fieldType: "Duration",
            documentation: "Maximum age of the value to be read in milliseconds"
        },
        {   name: "timestampsToReturn" ,          fieldType: "TimestampsToReturn",
            documentation:"An enumeration that specifies the Timestamps to be returned for each requested Variable Value Attribute.",
            defaultValue: TimestampsToReturn.Invalid
        },
        { name: "nodesToRead", isArray:true,    fieldType: "ReadValueId",
            documentation: "List of Nodes and their Attributes to read. For each entry in this list, a StatusCode is " +
            "returned, and if it indicates success, the Attribute Value is also returned."
        }
    ]
};
exports.ReadRequest_Schema = Obsolete_ReadRequest_schema;


text:
///
/// The MIT License(MIT)
///
/// Copyright(c) 2016 Daniel Lupiañez Casares
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
/// SOFTWARE.
///

using UnityEngine;

/// <summary>
/// A Block component implements the behaviour of a block for the Game.
/// The Block conforms to the PoolableComponent, making it suitable to interact with a GameObjectPool.
/// </summary>
public class Block : MonoBehaviour {

    /// <summary>
    /// The GameObject tag that all Block elements should have.
    /// </summary>
    public static string Tag = "Block";

    /// <summary>
    /// The amount of points this block is worth.
    /// </summary>
    public int points = 100;

    /// <summary>
    /// The main sprite renderer of the Block Game Object.
    /// </summary>
    public SpriteRenderer spriteRenderer { get; private set; }

    void Awake()
    {
        this.spriteRenderer = GetComponent<SpriteRenderer>();
    }

}


text:
module Features
  module SessionHelpers
    def login_as_admin
      Contentr::User.current(Contentr::AdminUser.new)
    end
  end
end


text:
import datetime

import mock
from nose.tools import eq_

import amo.tests
import mkt
import mkt.constants
from mkt.developers.cron import (_flag_rereview_adult, exclude_new_region,
                                 process_iarc_changes, send_new_region_emails)
from mkt.developers.models import ActivityLog
from mkt.webapps.models import IARCInfo, RatingDescriptors, RatingInteractives

class TestSendNewRegionEmails(amo.tests.WebappTestCase):

    @mock.patch('mkt.developers.cron._region_email')
    def test_called(self, _region_email_mock):
        eq_(self.app.enable_new_regions, True)
        send_new_region_emails([mkt.regions.UK])
        eq_(list(_region_email_mock.call_args_list[0][0][0]), [self.app.id])

    @mock.patch('mkt.developers.cron._region_email')
    def test_not_called_with_exclusions(self, _region_email_mock):
        self.app.addonexcludedregion.create(region=mkt.regions.UK.id)
        send_new_region_emails([mkt.regions.UK])
        eq_(list(_region_email_mock.call_args_list[0][0][0]), [])

    @mock.patch('mkt.developers.cron._region_email')
    def test_not_called_with_enable_new_regions_false(self,
                                                      _region_email_mock):
        """Check enable_new_regions is False by default."""
        self.app.update(enable_new_regions=False)
        send_new_region_emails([mkt.regions.UK])
        eq_(list(_region_email_mock.call_args_list[0][0][0]), [])

class TestExcludeNewRegion(amo.tests.WebappTestCase):

    @mock.patch('mkt.developers.cron._region_exclude')
    def test_not_called_enable_new_regions_true(self, _region_exclude_mock):
        eq_(self.app.enable_new_regions, True)
        exclude_new_region([mkt.regions.UK])
        eq_(list(_region_exclude_mock.call_args_list[0][0][0]), [])

    @mock.patch('mkt.developers.cron._region_exclude')
    def test_not_called_with_ordinary_exclusions(self, _region_exclude_mock):
        self.app.addonexcludedregion.create(region=mkt.regions.UK.id)
        exclude_new_region([mkt.regions.UK])
        eq_(list(_region_exclude_mock.call_args_list[0][0][0]), [])

    @mock.patch('mkt.developers.cron._region_exclude')
    def test_called_with_enable_new_regions_false(self, _region_exclude_mock):
        # Check enable_new_regions is False by default.
        self.app.update(enable_new_regions=False)
        exclude_new_region([mkt.regions.UK])
        eq_(list(_region_exclude_mock.call_args_list[0][0][0]), [self.app.id])

class TestIARCChangesCron(amo.tests.TestCase):

    @mock.patch('lib.iarc.utils.render_xml')
    def test_no_date(self, _render):
        process_iarc_changes()
        _render.assert_called_with('get_rating_changes.xml', {
            'date_from': datetime.date.today() - datetime.timedelta(days=1),
            'date_to': datetime.date.today(),
        })

    @mock.patch('lib.iarc.utils.render_xml')
    def test_with_date(self, _render):
        date = datetime.date(2001, 1, 11)
        process_iarc_changes(date.strftime('%Y-%m-%d'))
        _render.assert_called_with('get_rating_changes.xml', {
            'date_from': date - datetime.timedelta(days=1),
            'date_to': date,
        })

    def test_processing(self):
        """
        The mock client always returns the same data. Set up the app so it
        matches the submission ID and verify the data is saved as expected.
        """
        amo.set_user(amo.tests.user_factory())
        app = amo.tests.app_factory()
        IARCInfo.objects.create(addon=app, submission_id=52,
                                security_code='FZ32CU8')
        app.set_descriptors([
            'has_classind_violence',
            'has_esrb_strong_lang',
            'has_pegi_language', 'has_pegi_online',
            'has_usk_lang',
        ])
        app.set_interactives([])
        app.set_content_ratings({
            mkt.ratingsbodies.CLASSIND: mkt.ratingsbodies.CLASSIND_L
        })

        process_iarc_changes()
        app = app.reload()

        # Check ratings. CLASSIND should get updated.
        cr = app.content_ratings.get(
            ratings_body=mkt.ratingsbodies.CLASSIND.id)
        eq_(cr.rating, mkt.ratingsbodies.CLASSIND_14.id)
        cr = app.content_ratings.get(ratings_body=mkt.ratingsbodies.ESRB.id)
        eq_(cr.rating, mkt.ratingsbodies.ESRB_M.id)

        assert ActivityLog.objects.filter(
            action=amo.LOG.CONTENT_RATING_CHANGED.id).count()

        # Check descriptors.
        rd = RatingDescriptors.objects.get(addon=app)
        self.assertSetEqual(rd.to_keys(), [
            'has_esrb_strong_lang',
            'has_classind_lang',
            'has_pegi_lang', 'has_pegi_online',
            'has_usk_lang',
        ])

        # Check interactives.
        ri = RatingInteractives.objects.get(addon=app)
        self.assertSetEqual(ri.to_keys(), [
            'has_shares_info', 'has_shares_location', 'has_digital_purchases',
            'has_users_interact'
        ])

    def test_rereview_flag_adult(self):
        amo.set_user(amo.tests.user_factory())
        app = amo.tests.app_factory()

        app.set_content_ratings({
            mkt.ratingsbodies.ESRB: mkt.ratingsbodies.ESRB_E,
            mkt.ratingsbodies.CLASSIND: mkt.ratingsbodies.CLASSIND_18,
        })
        _flag_rereview_adult(app, mkt.ratingsbodies.ESRB,
                             mkt.ratingsbodies.ESRB_T)
        assert not app.rereviewqueue_set.count()
        assert not ActivityLog.objects.filter(
            action=amo.LOG.CONTENT_RATING_TO_ADULT.id).exists()

        # Adult should get flagged to rereview.
        _flag_rereview_adult(app, mkt.ratingsbodies.ESRB,
                             mkt.ratingsbodies.ESRB_A)
        eq_(app.rereviewqueue_set.count(), 1)
        eq_(ActivityLog.objects.filter(
            action=amo.LOG.CONTENT_RATING_TO_ADULT.id).count(), 1)

        # Test things same same if rating stays the same as adult.
        app.set_content_ratings({
            mkt.ratingsbodies.ESRB: mkt.ratingsbodies.ESRB_A,
        })
        _flag_rereview_adult(app, mkt.ratingsbodies.ESRB,
                             mkt.ratingsbodies.ESRB_A)
        eq_(app.rereviewqueue_set.count(), 1)
        eq_(ActivityLog.objects.filter(
            action=amo.LOG.CONTENT_RATING_TO_ADULT.id).count(), 1)


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:atlassian-scanner="http://www.atlassian.com/schema/atlassian-scanner"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.atlassian.com/schema/atlassian-scanner
        http://www.atlassian.com/schema/atlassian-scanner/atlassian-scanner.xsd">
    <atlassian-scanner:scan-indexes/>
</beans>


text:
package io.flutter.plugin.editing;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;

import android.text.Editable;
import android.text.Selection;
import android.view.View;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import io.flutter.embedding.android.KeyboardManager;
import io.flutter.embedding.engine.systemchannels.TextInputChannel;
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;

@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class ListenableEditingStateTest {
  @Mock KeyboardManager mockKeyboardManager;

  private BaseInputConnection getTestInputConnection(View view, Editable mEditable) {
    new View(RuntimeEnvironment.application);
    return new BaseInputConnection(view, true) {
      @Override
      public Editable getEditable() {
        return mEditable;
      }
    };
  }

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
  }

  // -------- Start: Test BatchEditing   -------
  @Test
  public void testBatchEditing() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));
    final Listener listener = new Listener();
    final View testView = new View(RuntimeEnvironment.application);
    final BaseInputConnection inputConnection = getTestInputConnection(testView, editingState);

    editingState.addEditingStateListener(listener);

    editingState.replace(0, editingState.length(), "update");
    assertTrue(listener.isCalled());
    assertTrue(listener.textChanged);
    assertFalse(listener.selectionChanged);
    assertFalse(listener.composingRegionChanged);

    assertEquals(-1, editingState.getSelectionStart());
    assertEquals(-1, editingState.getSelectionEnd());

    listener.reset();

    // Batch edit depth = 1.
    editingState.beginBatchEdit();
    editingState.replace(0, editingState.length(), "update1");
    assertFalse(listener.isCalled());
    // Batch edit depth = 2.
    editingState.beginBatchEdit();
    editingState.replace(0, editingState.length(), "update2");
    inputConnection.setComposingRegion(0, editingState.length());
    assertFalse(listener.isCalled());
    // Batch edit depth = 1.
    editingState.endBatchEdit();
    assertFalse(listener.isCalled());

    // Batch edit depth = 2.
    editingState.beginBatchEdit();
    assertFalse(listener.isCalled());
    inputConnection.setSelection(0, 0);
    assertFalse(listener.isCalled());
    // Batch edit depth = 1.
    editingState.endBatchEdit();
    assertFalse(listener.isCalled());

    // Remove composing region.
    inputConnection.finishComposingText();

    // Batch edit depth = 0. Last endBatchEdit.
    editingState.endBatchEdit();

    // Now notify the listener.
    assertTrue(listener.isCalled());
    assertTrue(listener.textChanged);
    assertFalse(listener.composingRegionChanged);
  }

  @Test
  public void testBatchingEditing_callEndBeforeBegin() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));
    final Listener listener = new Listener();
    editingState.addEditingStateListener(listener);

    editingState.endBatchEdit();
    assertFalse(listener.isCalled());

    editingState.replace(0, editingState.length(), "text");
    assertTrue(listener.isCalled());
    assertTrue(listener.textChanged);

    listener.reset();
    // Does not disrupt the followup events.
    editingState.beginBatchEdit();
    editingState.replace(0, editingState.length(), "more text");
    assertFalse(listener.isCalled());
    editingState.endBatchEdit();
    assertTrue(listener.isCalled());
  }

  @Test
  public void testBatchingEditing_addListenerDuringBatchEdit() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));
    final Listener listener = new Listener();

    editingState.beginBatchEdit();
    editingState.addEditingStateListener(listener);
    editingState.replace(0, editingState.length(), "update");
    editingState.endBatchEdit();

    assertTrue(listener.isCalled());
    assertTrue(listener.textChanged);
    assertTrue(listener.selectionChanged);
    assertTrue(listener.composingRegionChanged);

    listener.reset();

    // Verifies the listener is officially added.
    editingState.replace(0, editingState.length(), "more updates");
    assertTrue(listener.isCalled());
    assertTrue(listener.textChanged);
    editingState.removeEditingStateListener(listener);

    listener.reset();
    // Now remove before endBatchEdit();
    editingState.beginBatchEdit();
    editingState.addEditingStateListener(listener);
    editingState.replace(0, editingState.length(), "update");
    editingState.removeEditingStateListener(listener);
    editingState.endBatchEdit();

    assertFalse(listener.isCalled());
  }

  @Test
  public void testBatchingEditing_removeListenerDuringBatchEdit() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));
    final Listener listener = new Listener();
    editingState.addEditingStateListener(listener);

    editingState.beginBatchEdit();
    editingState.replace(0, editingState.length(), "update");
    editingState.removeEditingStateListener(listener);
    editingState.endBatchEdit();

    assertFalse(listener.isCalled());
  }

  @Test
  public void testBatchingEditing_listenerCallsReplaceWhenBatchEditEnds() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));

    final Listener listener =
        new Listener() {
          @Override
          public void didChangeEditingState(
              boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) {
            super.didChangeEditingState(textChanged, selectionChanged, composingRegionChanged);
            editingState.replace(
                0, editingState.length(), "one does not simply replace the text in the listener");
          }
        };
    editingState.addEditingStateListener(listener);

    editingState.beginBatchEdit();
    editingState.replace(0, editingState.length(), "update");
    editingState.endBatchEdit();

    assertTrue(listener.isCalled());
    assertEquals(1, listener.timesCalled);
    assertEquals("one does not simply replace the text in the listener", editingState.toString());
  }
  // -------- End: Test BatchEditing   -------

  @Test
  public void testSetComposingRegion() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));
    editingState.replace(0, editingState.length(), "text");

    // (-1, -1) clears the composing region.
    editingState.setComposingRange(-1, -1);
    assertEquals(-1, editingState.getComposingStart());
    assertEquals(-1, editingState.getComposingEnd());

    editingState.setComposingRange(-1, 5);
    assertEquals(-1, editingState.getComposingStart());
    assertEquals(-1, editingState.getComposingEnd());

    editingState.setComposingRange(2, 3);
    assertEquals(2, editingState.getComposingStart());
    assertEquals(3, editingState.getComposingEnd());

    // Empty range is invalid. Clears composing region.
    editingState.setComposingRange(1, 1);
    assertEquals(-1, editingState.getComposingStart());
    assertEquals(-1, editingState.getComposingEnd());

    // Covers everything.
    editingState.setComposingRange(0, editingState.length());
    assertEquals(0, editingState.getComposingStart());
    assertEquals(editingState.length(), editingState.getComposingEnd());
  }

  // -------- Start: Test InputMethods actions   -------
  @Test
  public void inputMethod_batchEditingBeginAndEnd() {
    final ArrayList<String> batchMarkers = new ArrayList<>();
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application)) {
          @Override
          public final void beginBatchEdit() {
            super.beginBatchEdit();
            batchMarkers.add("begin");
          }

          @Override
          public void endBatchEdit() {
            super.endBatchEdit();
            batchMarkers.add("end");
          }
        };

    final Listener listener = new Listener();
    final View testView = new View(RuntimeEnvironment.application);
    final InputConnectionAdaptor inputConnection =
        new InputConnectionAdaptor(
            testView,
            0,
            mock(TextInputChannel.class),
            mockKeyboardManager,
            editingState,
            new EditorInfo());

    // Make sure begin/endBatchEdit is called on the Editable when the input method calls
    // InputConnection#begin/endBatchEdit.
    inputConnection.beginBatchEdit();
    assertEquals(1, batchMarkers.size());
    assertEquals("begin", batchMarkers.get(0));

    inputConnection.endBatchEdit();
    assertEquals(2, batchMarkers.size());
    assertEquals("end", batchMarkers.get(1));
  }

  @Test
  public void inputMethod_testSetSelection() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));
    final Listener listener = new Listener();
    final View testView = new View(RuntimeEnvironment.application);
    final InputConnectionAdaptor inputConnection =
        new InputConnectionAdaptor(
            testView,
            0,
            mock(TextInputChannel.class),
            mockKeyboardManager,
            editingState,
            new EditorInfo());
    editingState.replace(0, editingState.length(), "initial text");

    editingState.addEditingStateListener(listener);

    inputConnection.setSelection(0, 0);

    assertTrue(listener.isCalled());
    assertFalse(listener.textChanged);
    assertTrue(listener.selectionChanged);
    assertFalse(listener.composingRegionChanged);

    listener.reset();

    inputConnection.setSelection(5, 5);

    assertTrue(listener.isCalled());
    assertFalse(listener.textChanged);
    assertTrue(listener.selectionChanged);
    assertFalse(listener.composingRegionChanged);
  }

  @Test
  public void inputMethod_testSetComposition() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));
    final Listener listener = new Listener();
    final View testView = new View(RuntimeEnvironment.application);
    final InputConnectionAdaptor inputConnection =
        new InputConnectionAdaptor(
            testView,
            0,
            mock(TextInputChannel.class),
            mockKeyboardManager,
            editingState,
            new EditorInfo());
    editingState.replace(0, editingState.length(), "initial text");

    editingState.addEditingStateListener(listener);

    // setComposingRegion test.
    inputConnection.setComposingRegion(1, 3);
    assertTrue(listener.isCalled());
    assertFalse(listener.textChanged);
    assertFalse(listener.selectionChanged);
    assertTrue(listener.composingRegionChanged);

    Selection.setSelection(editingState, 0, 0);
    listener.reset();

    // setComposingText test: non-empty text, does not move cursor.
    inputConnection.setComposingText("composing", -1);
    assertTrue(listener.isCalled());
    assertTrue(listener.textChanged);
    assertFalse(listener.selectionChanged);
    assertTrue(listener.composingRegionChanged);

    listener.reset();
    // setComposingText test: non-empty text, moves cursor.
    inputConnection.setComposingText("composing2", 1);
    assertTrue(listener.isCalled());
    assertTrue(listener.textChanged);
    assertTrue(listener.selectionChanged);
    assertTrue(listener.composingRegionChanged);

    listener.reset();
    // setComposingText test: empty text.
    inputConnection.setComposingText("", 1);
    assertTrue(listener.isCalled());
    assertTrue(listener.textChanged);
    assertTrue(listener.selectionChanged);
    assertTrue(listener.composingRegionChanged);

    // finishComposingText test.
    inputConnection.setComposingText("composing text", 1);
    listener.reset();
    inputConnection.finishComposingText();
    assertTrue(listener.isCalled());
    assertFalse(listener.textChanged);
    assertFalse(listener.selectionChanged);
    assertTrue(listener.composingRegionChanged);
  }

  @Test
  public void inputMethod_testCommitText() {
    final ListenableEditingState editingState =
        new ListenableEditingState(null, new View(RuntimeEnvironment.application));
    final Listener listener = new Listener();
    final View testView = new View(RuntimeEnvironment.application);
    final InputConnectionAdaptor inputConnection =
        new InputConnectionAdaptor(
            testView,
            0,
            mock(TextInputChannel.class),
            mockKeyboardManager,
            editingState,
            new EditorInfo());
    editingState.replace(0, editingState.length(), "initial text");

    editingState.addEditingStateListener(listener);
  }
  // -------- End: Test InputMethods actions   -------

  public static class Listener implements ListenableEditingState.EditingStateWatcher {
    public boolean isCalled() {
      return timesCalled > 0;
    }

    int timesCalled = 0;
    boolean textChanged = false;
    boolean selectionChanged = false;
    boolean composingRegionChanged = false;

    @Override
    public void didChangeEditingState(
        boolean textChanged, boolean selectionChanged, boolean composingRegionChanged) {
      timesCalled++;
      this.textChanged = textChanged;
      this.selectionChanged = selectionChanged;
      this.composingRegionChanged = composingRegionChanged;
    }

    public void reset() {
      timesCalled = 0;
      textChanged = false;
      selectionChanged = false;
      composingRegionChanged = false;
    }
  }
}


text:
namespace XamarinFormsAutofacMvvmStarterKit.UnitTests.Mocks
{
	class MockViewModel : ViewModelBase
	{
		public bool WasOnPushedCalled { get; private set; } = false;
		public bool WasOnPoppedCalled { get; private set; } = false;
		public bool WasOnAppearingCalled { get; private set; } = false;
		public bool WasOnDisappearingCalled { get; private set; } = false;
		public override void OnAppearing()
		{
			base.OnAppearing();
			WasOnAppearingCalled = true;
		}

		public override void OnDisappearing()
		{
			base.OnDisappearing();
			WasOnDisappearingCalled = true;
		}

		public override void OnPushed()
		{
			base.OnPushed();
			WasOnPushedCalled = true;
		}

		public override void OnPopped()
		{
			base.OnPopped();
			WasOnPoppedCalled = true;
		}
	}
}


text:
@interface NSDictionary (KF5)

- (nullable id)kf5_objectForKeyPath:(nonnull NSString *)keyPath;
- (nullable NSString *)kf5_stringForKeyPath:(nonnull NSString *)keyPath;
- (nullable NSNumber *)kf5_numberForKeyPath:(nonnull NSString *)keyPath;
- (nullable NSArray *)kf5_arrayForKeyPath:(nonnull NSString *)keyPath;
- (nullable NSDictionary *)kf5_dictionaryForKeyPath:(nonnull NSString *)keyPath;
- (BOOL)kf5_hasKey:(nonnull NSString *)key;

@end


text:
@protocol MLReorderableCollectionControllerAnimator <NSObject>

@required
- (UIView *)viewPlaceholderFromCollectionViewCell:(UICollectionViewCell *)cell;
- (void)collectionView:(UICollectionView *)collectionView beginsAnimationItemAtIndexPath:(NSIndexPath *)indexPath usingPlaceholder:(UIView *)viewPlaceholder completion:(void(^)(BOOL))completion;
- (void)collectionView:(UICollectionView *)collectionView endsAnimationItemAtIndexPath:(NSIndexPath *)indexPath usingPlaceholder:(UIView *)viewPlaceholder completion:(void(^)(BOOL))completion;
- (void)collectionView:(UICollectionView *)fromCollectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath animatesToCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath usingPlaceholder:(UIView *)viewPlaceholder completion:(void(^)(BOOL))completion;

@end

@protocol MLReorderableCollectionControllerDelegate <NSObject>

@optional
// Dragging delegates
- (void)collectionView:(UICollectionView *)collectionView willBeginDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didBeginDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView willEndDraggingItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didEndDraggingItemAtIndexPath:(NSIndexPath *)indexPath;

// Hover item delegate
- (void)collectionView:(UICollectionView *)collectionView didBeginHoveringItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didEndHoveringItemAtIndexPath:(NSIndexPath *)indexPath;

@end

@protocol MLReorderableCollectionControllerDataSource <NSObject>

@optional
// Reorder data source
- (BOOL)collectionView:(UICollectionView *)collectionView canReorderItemAtIndexPath:(NSIndexPath *)indexPath;
- (BOOL)canReorderContinouslyInCollectionView:(UICollectionView *)collectionView;
- (NSIndexPath *)indexPathForNewItemInCollectionView:(UICollectionView *)collectionView;

// Insert data source
- (BOOL)collectionView:(UICollectionView *)collectionView canInsertItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView willInsertItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didInsertItemAtIndexPath:(NSIndexPath *)indexPath;

// Delete data source
- (BOOL)collectionView:(UICollectionView *)collectionView canDeleteItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView willDeleteItemAtIndexPath:(NSIndexPath *)indexPath;
- (void)collectionView:(UICollectionView *)collectionView didDeleteItemAtIndexPath:(NSIndexPath *)indexPath;

// Replace data source
- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath canReplaceWithIndexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath willReplaceWithIndexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath didReplaceWithIndexPath:(NSIndexPath *)toIndexPath;

// Move data source
- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath canMoveToIndexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath willMoveToIndexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)fromIndexPath didMoveToIndexPath:(NSIndexPath *)toIndexPath;

// Transfer data source
- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath canTransferToCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath willTransferToCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath didTransferToCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;

// Copy data source
- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath canCopyToCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath willCopyToCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath didCopyToCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;

// Replace data source
- (BOOL)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath canReplaceWithCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath willReplaceWithCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;
- (void)collectionView:(UICollectionView *)collectionView itemAtIndexPath:(NSIndexPath *)indexPath didReplaceWithCollectionView:(UICollectionView *)toCollectionView indexPath:(NSIndexPath *)toIndexPath;

@end

@interface MLReorderableCollectionController : NSObject <UIGestureRecognizerDelegate>

@property (nonatomic, readonly, strong) UIView * viewContainer;
@property (nonatomic, readonly, strong) UICollectionView * currentCollectionView;
@property (nonatomic, readonly, strong) UILongPressGestureRecognizer * longPressGesture;
@property (nonatomic, readonly, strong) UIPanGestureRecognizer * panGesture;
@property (nonatomic, readonly, assign, getter=isDragging) BOOL dragging;
@property (nonatomic, readwrite, assign) BOOL shouldReorderContinously;
@property (nonatomic, readwrite, weak) id <MLReorderableCollectionControllerDelegate> delegate;
@property (nonatomic, readwrite, weak) id <MLReorderableCollectionControllerDataSource> dataSource;
@property (nonatomic, readwrite, strong) id <MLReorderableCollectionControllerAnimator> animator;

- (instancetype)initWithViewContainer:(UIView *)viewContainer NS_DESIGNATED_INITIALIZER;

- (BOOL)addCollectionView:(UICollectionView *)collectionView;
- (BOOL)removeCollectionView:(UICollectionView *)collectionView;

@end


text:
package org.apache.sling.jcr.resource.internal.helper.jcr;

import java.util.LinkedList;
import java.util.Map;

import javax.jcr.Item;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.version.VersionHistory;
import javax.jcr.version.VersionManager;

import org.apache.commons.lang.StringUtils;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.jcr.resource.internal.HelperData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JcrItemResourceFactory {

    /** Default logger */
    private static final Logger log = LoggerFactory.getLogger(JcrItemResourceFactory.class);

    private final Session session;

    private final HelperData helper;

    public JcrItemResourceFactory(Session session, HelperData helper) {
        this.helper = helper;
        this.session = session;
    }

    /**
     * Creates a Resource instance for the item found at the
     * given path. If no item exists at that path or the item does not have
     * read-access for the session of this resolver, null is
     * returned.
     *
     * @param resourcePath The absolute path
     * @return The Resource for the item at the given path.
     * @throws RepositoryException If an error occurrs accessing checking the
     *             item in the repository.
     */
    public JcrItemResource<?> createResource(final ResourceResolver resourceResolver, final String resourcePath,
            final Resource parent, final Map<String, String> parameters) throws RepositoryException {
        final String jcrPath = helper.pathMapper.mapResourcePathToJCRPath(resourcePath);
        if (jcrPath == null) {
            log.debug("createResource: {} maps to an empty JCR path", resourcePath);
            return null;
        }

        final String version;
        if (parameters != null && parameters.containsKey("v")) {
            version = parameters.get("v");
        } else {
            version = null;
        }

        Node parentNode = null;
        String parentResourcePath = null;
        if (parent != null) {
            parentNode = parent.adaptTo(Node.class);
            parentResourcePath = parent.getPath();
        }

        Item item;
        if (parentNode != null && resourcePath.startsWith(parentResourcePath)) {
            String subPath = resourcePath.substring(parentResourcePath.length());
            if (!subPath.isEmpty() && subPath.charAt(0) == '/') {
                subPath = subPath.substring(1);
            }
            item = getSubitem(parentNode, subPath);
        } else {
            item = getItemOrNull(jcrPath);
        }

        if (item != null && version != null) {
            item = getHistoricItem(item, version);
        }

        if (item == null) {
            log.debug("createResource: No JCR Item exists at path '{}'", jcrPath);
            return null;
        } else {
            final JcrItemResource<?> resource;
            if (item.isNode()) {
                log.debug("createResource: Found JCR Node Resource at path '{}'", resourcePath);
                resource = new JcrNodeResource(resourceResolver, resourcePath, version, (Node) item, helper);
            } else {
                log.debug("createResource: Found JCR Property Resource at path '{}'", resourcePath);
                resource = new JcrPropertyResource(resourceResolver, resourcePath, version, (Property) item);
            }
            resource.getResourceMetadata().setParameterMap(parameters);
            return resource;
        }
    }

    private Item getHistoricItem(Item item, String versionSpecifier) throws RepositoryException {
        Item currentItem = item;
        LinkedList<String> relPath = new LinkedList<String>();
        Node version = null;
        while (!"/".equals(currentItem.getPath())) {
            if (isVersionable(currentItem)) {
                version = getFrozenNode((Node) currentItem, versionSpecifier);
                break;
            } else {
                relPath.addFirst(currentItem.getName());
                currentItem = currentItem.getParent();
            }
        }
        if (version != null) {
            return getSubitem(version, StringUtils.join(relPath.iterator(), '/'));
        }
        return null;
    }

    private static Item getSubitem(Node node, String relPath) throws RepositoryException {
        try {
            if (relPath.length() == 0) { // not using isEmpty() due to 1.5 compatibility
                return node;
            } else if (node.hasNode(relPath)) {
                return node.getNode(relPath);
            } else if (node.hasProperty(relPath)) {
                return node.getProperty(relPath);
            } else {
                return null;
            }
        } catch(RepositoryException e) {
            log.debug("getSubitem: Can't get subitem {} of {}: {}",
                    new Object[] { relPath, node.toString(), e.toString() });
            return null;
        }
    }

    private Node getFrozenNode(Node node, String versionSpecifier) throws RepositoryException {
        final VersionManager versionManager = session.getWorkspace().getVersionManager();
        final VersionHistory history = versionManager.getVersionHistory(node.getPath());
        if (history.hasVersionLabel(versionSpecifier)) {
            return history.getVersionByLabel(versionSpecifier).getFrozenNode();
        } else if (history.hasNode(versionSpecifier)) {
            return history.getVersion(versionSpecifier).getFrozenNode();
        } else {
            return null;
        }
    }

    private static boolean isVersionable(Item item) throws RepositoryException {
        return item.isNode() && ((Node) item).isNodeType(JcrConstants.MIX_VERSIONABLE);
    }

    Item getItemOrNull(String path) throws RepositoryException {
        // Check first if the path is absolute. If it isn't, then we return null because the previous itemExists method,
        // which was replaced by this method, would have returned null as well (instead of throwing an exception).
        if (path.isEmpty() || path.charAt(0) != '/') {
            return null;
        }

        Item item = null;
        try {
         // Use fast getItemOrNull if session is a JackrabbitSession
            if (session instanceof JackrabbitSession) {
                item = ((JackrabbitSession) session).getItemOrNull(path);
            }
            // Fallback to slower itemExists & getItem pattern
            else if (session.itemExists(path)) {
                item = session.getItem(path);
            }
        } catch (RepositoryException e) {
            log.debug("Unable to access item at " + path + ", possibly invalid path", e);
        }

        return item;
    }

}


text:
from ..metrics import mse, logloss, mae, hinge, binary_crossentropy

categorical_crossentropy = logloss

def get_loss(name):
    """Returns loss function by the name."""

    try:
        return globals()[name]
    except:
        raise ValueError('Invalid metric function.')


text:
module Pointsable
  VERSION = "0.0.1"
end


text:
#ifndef __LIBSTUDIO_BLOCK_HPP__
#define __LIBSTUDIO_BLOCK_HPP__

#include "container.hpp"

namespace studio
{
	class Block : public Container
	{
	public:
		Block(const fixed& width, const fixed& height, const fixed& depth);
		void setMaterialForSide(int, const MaterialPtr&);
	};
}

#endif //__LIBSTUDIO_BLOCK_HPP__


text:
from django.test import TestCase
from django.utils import six

from ..bin.start_cms_project import (Output, git, make_executable, query_yes_no,
                                     configure_apps, main)

import getpass
try:
    from unittest import mock
    from unittest.mock import call
except ImportError:
    import mock
    from mock import call
import os

try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

import sys

class TestStartCMSProject(TestCase):

    def setUp(self):
        # Redirect STDOUT so we can capture the `print`.
        self.orig_stdout = sys.stdout
        self.stdout = StringIO()
        sys.stdout = self.stdout

        self.mock_open_data = '{{ project_name }}\r\n\"usertools\",\r\n"foo.apps.people",\r\n{{ project_name }}\r\n'

    def tearDown(self):
        sys.stdout = self.orig_stdout

    def test_output_info(self):
        Output().info('Foo')
        self.assertEqual(self.stdout.getvalue().strip(), '[\x1b[92mINFO\x1b[0m] Foo')

    def test_output_warn(self):
        # Redirect STDOUT so we can capture the `print`.
        Output().warn('Foo')
        self.assertEqual(self.stdout.getvalue().strip(), '[\x1b[93mWARN\x1b[0m] Foo')

    @mock.patch('cms.bin.start_cms_project.subprocess')
    def test_git(self, mock_subprocess):
        git('status')
        mock_subprocess.check_call.assert_called_with(['git', 'status'])

    @mock.patch('cms.bin.start_cms_project.os')
    def test_make_executable(self, mock_os):
        make_executable('test.png')
        mock_os.stat.assert_called_with('test.png')
        self.assertTrue(mock_os.chmod.called)

    @mock.patch('cms.bin.start_cms_project.sys')
    @mock.patch('{}'.format('__builtin__.raw_input' if six.PY2 else 'builtins.input'), return_value='y')
    def test_query_yes_no(self, mock_raw_input, mock_sys):
        query_yes_no('Foo')
        mock_raw_input.assert_called_with()
        mock_sys.stdout.write.assert_called_with('Foo [Y/n] ')

        query_yes_no('Foo', None)
        mock_raw_input.assert_called_with()
        mock_sys.stdout.write.assert_called_with('Foo [y/n] ')

        query_yes_no('Foo', 'yes')
        mock_raw_input.assert_called_with()
        mock_sys.stdout.write.assert_called_with('Foo [Y/n] ')

        query_yes_no('Foo', 'no')
        mock_raw_input.assert_called_with()
        mock_sys.stdout.write.assert_called_with('Foo [y/N] ')

        with self.assertRaises(ValueError):
            query_yes_no('Foo', 'foo')

        with mock.patch('cms.bin.start_cms_project.sys') as mock_sys:
            with mock.patch('{}'.format('__builtin__.raw_input' if six.PY2 else 'builtins.input'), side_effect=['foo', 'y']) as mock_raw_input:
                query_yes_no('Foo')
                mock_raw_input.assert_called_with()

                self.assertListEqual(mock_sys.stdout.write.call_args_list, [
                    call('Foo [Y/n] '),
                    call("Please respond with 'yes' or 'no' (or 'y' or 'n').\n"),
                    call('Foo [Y/n] ')
                ])

        with mock.patch('{}'.format('__builtin__.raw_input' if six.PY2 else 'builtins.input'), return_value='') as mock_raw_input:
            query_yes_no('Foo', 'no')
            mock_raw_input.assert_called_with()
            mock_sys.stdout.write.assert_called_with('Foo [Y/n] ')

    def test_configure_apps(self):
        def os_paths(*args, **kwargs):
            return '/'.join(args)

        os_walk = [
            ('/tmp/apps/temp/people', ['apps', 'templates'], ['.gitignore']),
            ('/tmp/apps/temp/people/apps', ['people'], []),
            ('/tmp/apps/temp/people/apps/people', ['migrations', 'templatetags', 'tests'], ['__init__.py', 'admin.py', 'models.py', 'urls.py', 'views.py']),
            ('/tmp/apps/temp/people/apps/people/migrations', [], ['0001_initial.py', '__init__.py']),
            ('/tmp/apps/temp/people/apps/people/templatetags', [], ['__init__.py', 'people.py']),
            ('/tmp/apps/temp/people/apps/people/tests', [], ['__init__.py', 'test_models.py']),
            ('/tmp/apps/temp/people/templates', ['people'], []),
            ('/tmp/apps/temp/people/templates/people', ['includes'], ['person_detail.html', 'person_list.html', 'team_detail.html', 'team_list.html']),
            ('/tmp/apps/temp/people/templates/people/includes', [], ['people_list.html'])
        ]

        m = mock.mock_open(read_data=self.mock_open_data)
        with mock.patch('cms.bin.start_cms_project.os'), \
                mock.patch('cms.bin.start_cms_project.os.walk', return_value=os_walk) as mock_os_walk, \
                mock.patch('cms.bin.start_cms_project.os.path.join', side_effect=os_paths) as mock_os_path_join, \
                mock.patch('cms.bin.start_cms_project.subprocess.check_call') as mock_check_call, \
                mock.patch('cms.bin.start_cms_project.shutil.move') as mock_shutil_move, \
                mock.patch('cms.bin.start_cms_project.shutil.rmtree') as mock_shutil_rmtree, \
                mock.patch('{}.open'.format('__builtin__' if six.PY2 else 'builtins'), m) as mock_open:
            configure_apps('/tmp', {'people': True}, 'foo')

        self.assertListEqual(mock_os_walk.call_args_list, [
            call('/tmp/apps/temp/people'),
        ])

        self.assertIn(
            call('/tmp', 'apps', 'temp'),
            mock_os_path_join.call_args_list
        )

        self.assertIn(
            call('/tmp/apps/temp', 'people'),
            mock_os_path_join.call_args_list
        )

        self.assertIn(
            call('/tmp/apps/temp/people', 'apps', 'people'),
            mock_os_path_join.call_args_list
        )

        self.assertIn(
            call('/tmp', 'apps'),
            mock_os_path_join.call_args_list
        )

        self.assertIn(
            call('/tmp', 'apps', 'people', 'models.py'),
            mock_os_path_join.call_args_list
        )

        self.assertIn(
            call('/tmp/apps/temp/people', 'templates', 'people'),
            mock_os_path_join.call_args_list
        )

        self.assertIn(
            call('/tmp', 'apps', 'temp'),
            mock_os_path_join.call_args_list
        )

        self.assertListEqual(mock_check_call.call_args_list, [
            call([
                'git',
                'clone',
                'git://github.com/onespacemedia/cms-people.git',
                '/tmp/apps/temp/people',
                '-q'
            ])
        ])

        self.assertListEqual(mock_shutil_move.call_args_list, [
            call('/tmp/apps/temp/people/apps/people', '/tmp/apps'),
            call('/tmp/apps/temp/people/templates/people', '/tmp/templates')
        ])

        self.assertListEqual(mock_shutil_rmtree.call_args_list, [
            call('/tmp/apps/temp')
        ])

        self.assertIn(
            call('/tmp/apps/people/models.py', 'w'),
            mock_open.call_args_list
        )

        self.assertIn(
            call('/tmp/apps/people/models.py', 'r'),
            mock_open.call_args_list
        )

        self.assertEqual(self.stdout.getvalue().strip(), '[\x1b[92mINFO\x1b[0m] Installed people app')

    def test_configure_apps_2(self):
        # Try to break things.
        self.stdout = StringIO()
        sys.stdout = self.stdout

        def os_paths(*args):
            return '/'.join(args)

        m = mock.mock_open(read_data=self.mock_open_data)
        with mock.patch('cms.bin.start_cms_project.os'), \
                mock.patch('cms.bin.start_cms_project.os.path.join', side_effect=os_paths), \
                mock.patch('cms.bin.start_cms_project.shutil.rmtree'), \
                mock.patch('cms.bin.start_cms_project.subprocess.call', side_effect=Exception), \
                mock.patch('{}.open'.format('__builtin__' if six.PY2 else 'builtins'), m):
            configure_apps('/tmp', {'people': True, 'jobs': False, 'faqs': False}, 'foobar')
            self.assertEqual(self.stdout.getvalue().strip(), 'Error:')

    def _test_main_func(self, with_or_without):
        self.stdout = StringIO()
        sys.stdout = self.stdout

        sys.argv = [
            '',
            'foo',
            '/tmp',
            '--{}-people'.format(with_or_without),
        ]

        m = mock.mock_open(read_data=self.mock_open_data)
        with mock.patch('os.makedirs') as mock_os_makedirs, \
                mock.patch('cms.bin.start_cms_project.management') as mock_django_core_management, \
                mock.patch('cms.bin.start_cms_project.query_yes_no', side_effect=[True, True]) as mock_query_yes_no, \
                mock.patch('cms.bin.start_cms_project.make_executable') as mock_make_executable, \
                mock.patch('cms.bin.start_cms_project.configure_apps') as mock_configure_apps, \
                mock.patch('cms.bin.start_cms_project.subprocess.call') as mock_call, \
                mock.patch('{}.open'.format('__builtin__' if six.PY2 else 'builtins'), m) as mock_open:
            main()

            self.assertListEqual(mock_os_makedirs.call_args_list, [
                call('/tmp'),
                call('/tmp/foo/templates/admin/auth/user')
            ])

            self.assertListEqual(mock_django_core_management.call_args_list, [

            ])

            self.assertIn(
                call('Would you like the FAQs module?'),
                mock_query_yes_no.call_args_list,
            )

            self.assertIn(
                call('Would you like the jobs module?'),
                mock_query_yes_no.call_args_list,
            )

            self.assertEqual(len(mock_query_yes_no.call_args_list), 2)

            if with_or_without == 'with':
                self.assertListEqual(mock_configure_apps.call_args_list, [
                    call('/tmp/foo', {'faqs': True, 'jobs': True, 'people': True}, 'foo')
                ])
            elif with_or_without == 'without':
                self.assertListEqual(mock_configure_apps.call_args_list, [
                    call('/tmp/foo', {'faqs': True, 'jobs': True, 'people': False}, 'foo')
                ])

            self.assertListEqual(mock_make_executable.call_args_list, [
                call('/tmp/manage.py')
            ])

            self.assertListEqual(mock_open.call_args_list, [
                call('/tmp/foo/settings/base.py'),
                call('/tmp/foo/settings/base.py', 'w'),
                call('/tmp/foo/templates/admin/auth/user/change_list.html', 'w'),
                call('/tmp/foo/server.json', 'w'),
                call('/dev/null', 'w')
            ])

            self.assertEqual(
                mock_call.call_args_list[0][0][0],
                ['npm', 'install', '-g', 'bower', 'gulp', 'babel']
            )

            self.assertEqual(
                mock_call.call_args_list[1][0][0],
                ['npm', 'install']
            )

            self.assertEqual(
                mock_call.call_args_list[2][0][0],
                ['gulp', 'styles']
            )

            self.assertEqual(
                self.stdout.getvalue().strip(),
                '[\x1b[93mWARN\x1b[0m] Usertools is not installed\n[\x1b[92mINF'
                'O\x1b[0m] Installing bower, babel and gulp\n[\x1b[92mINFO\x1b[0m] Ins'
                'talling npm dependancies\n[\x1b[92mINFO\x1b[0m] Running gulp\n'
                '[\x1b[92mINFO\x1b[0m] CMS project created'
            )

    def test_main_func(self):
        self._test_main_func('with')
        self._test_main_func('without')

    def test_main_func_exceptions(self):
        # Now test exceptions.
        sys.argv = [
            '',
            'foo',
            '/tmp',
            '--with-people',
            '--without-people'
        ]

        with mock.patch('os.makedirs', side_effect=OSError) as mock_os_makedirs, \
                mock.patch('cms.bin.start_cms_project.query_yes_no', side_effect=[True, True]), \
                mock.patch('cms.bin.start_cms_project.management.call_command') as mock_call_command, \
                self.assertRaises(SystemExit):
            main()

        self.assertListEqual(mock_os_makedirs.call_args_list, [
            call('/tmp')
        ])

        self.assertListEqual(mock_call_command.call_args_list, [
            call(
                'startproject',
                'foo',
                '/tmp',
                extensions=['py', 'txt', 'conf', 'gitignore', 'md', 'css', 'js', 'json'],
                user=getpass.getuser(),
                # Did someone say 'clunky'?
                template=os.path.abspath(os.path.join(os.path.abspath(os.path.dirname(__file__)), '../project_template')),
                project_slug='foo'
            )
        ])

        self.assertEqual(
            self.stdout.getvalue().strip(),
            'You cannot use --with-people and --without-people together.'
        )


text:
<TITLE>GNU.Gettext.GettextResourceSet Class</TITLE>

GNU.Gettext.GettextResourceSet Class

public class GettextResourceSet: System.Resources.ResourceSet

Base Types

System.Resources.ResourceSet

  GettextResourceSet

Library

GNU.Gettext

Summary

Each instance of this class encapsulates a single PO file.

This API of this class is not meant to be used directly; use
GettextResourceManager instead.

See Also

GNU.Gettext Namespace

Members

GettextResourceSet Constructors

GettextResourceSet() Constructor

GettextResourceSet(System.Resources.IResourceReader) Constructor

GettextResourceSet(System.IO.Stream) Constructor

GettextResourceSet(System.String) Constructor

GettextResourceSet Methods

GettextResourceSet.GetPluralString Method

GettextResourceSet.GetString(System.String) Method

GettextResourceSet.GetString(System.String, bool) Method

GettextResourceSet.PluralEval Method

GettextResourceSet Properties

GettextResourceSet.Keys Property

GettextResourceSet() Constructor

protected GettextResourceSet();

Summary

Creates a new message catalog. When using this constructor, you
must override the ReadResources method, in order to initialize
the Table property. The message catalog will support plural
forms only if the ReadResources method installs values of type
String[] and if the PluralEval method is overridden.

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace

GettextResourceSet(System.Resources.IResourceReader) Constructor

public GettextResourceSet(System.Resources.IResourceReader reader);

Summary

Creates a new message catalog, by reading the string/value pairs from
the given reader. The message catalog will support
plural forms only if the reader can produce values of type
String[] and if the PluralEval method is overridden.

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace

GettextResourceSet(System.IO.Stream) Constructor

public GettextResourceSet(System.IO.Stream stream);

Summary

Creates a new message catalog, by reading the string/value pairs from
the given stream, which should have the format of
a .resources file. The message catalog will not support plural
forms.

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace

GettextResourceSet(System.String) Constructor

public GettextResourceSet(System.String fileName);

Summary

Creates a new message catalog, by reading the string/value pairs from
the file with the given fileName. The file should
be in the format of a .resources file. The message catalog will
not support plural forms.

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace

GettextResourceSet.GetPluralString Method

public virtual System.String GetPluralString(System.String msgid, System.String msgidPlural, long n);

Summary

Returns the translation of msgid and
msgidPlural, choosing the right plural form
depending on the number n.

Parameters

msgid

the key string to be translated, an ASCII
                    string

msgidPlural

the English plural of msgid,
                          an ASCII string

n

the number, should be >= 0

Return Value

the translation, or null if none is found

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace

GettextResourceSet.GetString(System.String) Method

public override System.String GetString(System.String msgid);

Summary

Returns the translation of msgid.

Parameters

msgid

the key string to be translated, an ASCII
                    string

Return Value

the translation of msgid, or null if
         none is found

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace

GettextResourceSet.GetString(System.String, bool) Method

public override System.String GetString(System.String msgid, bool ignoreCase);

Summary

Returns the translation of msgid, with possibly
case-insensitive lookup.

Parameters

msgid

the key string to be translated, an ASCII
                    string

Return Value

the translation of msgid, or null if
         none is found

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace

GettextResourceSet.PluralEval Method

protected virtual long PluralEval(long n);

Summary

Returns the index of the plural form to be chosen for a given number.
The default implementation is the Germanic plural formula:
zero for n == 1, one for n != 1.

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace

GettextResourceSet.Keys Property

public virtual System.Collections.ICollection Keys { get; }

Summary

Returns the keys of this resource set, i.e. the strings for which
GetObject() can return a non-null value.

See Also

GNU.Gettext.GettextResourceSet Class, GNU.Gettext Namespace


text:
/**
 * Created with JetBrains WebStorm.
 * User: admin
 * Date: 06/08/2013
 * Time: 22:01
 * To change this template use File | Settings | File Templates.
 */
var superagent = require('superagent');
var utils = require('./utils/TestUtils');

describe('Projects Retrieve', function(){

    var token;  // Admin access token
    var project //
    var name = utils.createProjectName(true);   // Create random project name

    it('should get admin token', function(done){

        superagent.post('https://localhost:8443/api/authentications')
            .send({ email: utils.admin.email , password: utils.admin.password })
            .end(function(e,res){
                token = res.body.data.access_token;
                done();
            });
    });

    it('should fail getting a all projects if access token is invalid', function(done){

        superagent.get('https://localhost:8443/api/projects?access_token=' + 'bjkbjhbfdsjh')
            .send()
            .end(function(e,res){
                utils.checkJSendFormat(res.body);
                expect(res.status).toBe(401);
                expect(res.body.status).toBe('fail');
                expect(res.body.data).toBe('Unauthorized');
                done();
            });
    });

    it('should get a all projects', function(done){

        superagent.get('https://localhost:8443/api/projects?access_token=' + token)
            .send()
            .end(function(e,res){
                utils.checkJSendFormat(res.body);
                expect(res.status).toBe(200);
                expect(res.body.status).toBe('success');
                expect(res.body.data.length).toBeGreaterThan(0);

                var projects  = res.body.data;
                var i = projects.length;
                var p;

                while( --i > -1 ){
                    p = projects[i];
                    expect(p.name).toBeDefined();
                    expect(p.name.length).toBeGreaterThan(1);
                    expect(p.pipes).toBeDefined();
                    expect(p.jobs).toBeDefined();
                    expect(p.collaborators).toBeDefined();
                    expect(p.pipes.length).toBeDefined();
                    expect(p.jobs.length).toBeDefined();
                    expect(p.collaborators.length).toBeDefined();
                    expect(p.modified).toBeDefined();
                }
                project = p;
                done();
            });
    });

    it('should get a projects by ID', function(done){

        superagent.get('https://localhost:8443/api/projects/' + project._id + '?access_token=' + token)
            .send()
            .end(function(e,res){
                utils.checkJSendFormat(res.body);
                expect(res.status).toBe(200);
                expect(res.body.status).toBe('success');
                expect(res.body.data).toBeDefined();
                var p = res.body.data;
                expect(p.name).toBeDefined();
                expect(p.name.length).toBeGreaterThan(1);
                expect(p.pipes).toBeDefined();
                expect(p.jobs).toBeDefined();
                expect(p.collaborators).toBeDefined();
                expect(p.pipes.length).toBeDefined();
                expect(p.jobs.length).toBeDefined();
                expect(p.collaborators.length).toBeDefined();
                expect(p.modified).toBeDefined();
                done();
            });
    });

    it('should fail getting a projects by ID if access token is invalid', function(done){

        superagent.get('https://localhost:8443/api/projects/' + project._id + '?access_token=' + '123455')
            .send()
            .end(function(e,res){
                utils.checkJSendFormat(res.body);
                expect(res.status).toBe(401);
                expect(res.body.status).toBe('fail');
                expect(res.body.data).toBe('Unauthorized');
                done();
            });
    });

    it('should fail getting a projects by ID if ID is non existent', function(done){

        superagent.get('https://localhost:8443/api/projects/' + project._id.substr(4) + '?access_token=' + token)
            .send()
            .end(function(e,res){
                utils.checkJSendFormat(res.body);
                expect(res.status).toBe(404);
                expect(res.body.status).toBe('fail');
                expect(res.body.data).toBe('Not found');
                done();
            });
    });

});


text:
package com.qumasoft.guitools.qwin;

import java.awt.SplashScreen;
import javax.swing.SwingUtilities;

/**
 * Launch the client application. Use this small class so the splash should load faster.
 * @author Jim Voris
 */
public final class AppLauncher {
    /** Loading this statically puts it on the screen pretty quick. The actual resource is specified in the manifest file by the SplashScreen-Image property. */
    private static final SplashScreen SPLASH_SCREEN = SplashScreen.getSplashScreen();

    /** Make this private so no one can use it. */
    private AppLauncher() {
    }

    /**
     * Main entry point for QVCS-Enterprise client application.
     * @param args the command line arguments
     */
    public static void main(final String[] args) {
        QWinFrame.initSplashScreen();

        // Run this on the swing thread.
        Runnable swingTask = new Runnable() {

            @Override
            public void run() {
                QWinFrame qwinFrame = new QWinFrame(args);
                QWinFrame.setQwinFrameSingleton(qwinFrame);
                qwinFrame.initialize();
                qwinFrame.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(swingTask);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>TermFreqIterator (Lucene 4.6.1 API)</title>
<meta name="date" content="2014-01-23">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

org.apache.lucene.search.spell

Interface TermFreqIterator

All Superinterfaces:

BytesRefIterator

All Known Implementing Classes:

BufferingTermFreqIteratorWrapper, SortedTermFreqIteratorWrapper, TermFreqIterator.TermFreqIteratorWrapper

public interface TermFreqIterator
extends BytesRefIterator

Interface for enumerating term,weight pairs.

Nested Class Summary

Nested Classes

Modifier and Type
Interface and Description

static class
TermFreqIterator.TermFreqIteratorWrapper

Wraps a BytesRefIterator as a TermFreqIterator, with all weights
 set to 1

Field Summary

Fields inherited from interface org.apache.lucene.util.BytesRefIterator

EMPTY

Method Summary

Methods

Modifier and Type
Method and Description

long
weight()

A term's weight, higher numbers mean better suggestions.

Methods inherited from interface org.apache.lucene.util.BytesRefIterator

getComparator, next

Method Detail

weight

long weight()

A term's weight, higher numbers mean better suggestions.

Overview

Package

Class

Use

Tree

Deprecated

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

          Copyright © 2000-2014 Apache Software Foundation.  All Rights Reserved.


text:
package java.awt;

/**
 * @author Bryce McKinlay
 * @status believed complete, but untested.
 */
class EventDispatchThread extends Thread
{
  /**
   * The default priority when no property has been set.
   */
  private static final int DEFAULT_PRIORITY = NORM_PRIORITY + 1;

  private static int dispatchThreadNum;

  private EventQueue queue;

  EventDispatchThread(EventQueue queue)
  {
    super();
    setName("AWT-EventQueue-" + ++dispatchThreadNum);
    this.queue = queue;

    int priority = DEFAULT_PRIORITY;
    try
      {
        String priorityString =
          System.getProperty("gnu.awt.dispatchthread.priority");
        if (priorityString != null)
          {
            priority = Integer.parseInt(priorityString);
          }
      }
    catch (NumberFormatException ex)
      {
        // Ignore and use default.
      }
    setPriority(priority);

    // Make sure that an event dispatch thread is never a daemon thread.
    setDaemon(false);
  }

  public void run()
  {
    while (true)
      {
        try
        {
          AWTEvent evt = queue.getNextEvent();
          queue.dispatchEvent(evt);
        }
        catch (ThreadDeath death)
        {
          // If someone wants to kill us, let them.
          return;
        }
        catch (InterruptedException ie)
        {
          // We are interrupted when we should finish executing
          return;
        }
        catch (Throwable x)
        {
          System.err.println("Exception during event dispatch:");
          x.printStackTrace(System.err);
        }
      }
  }
}


text:
<?php

require("functions.php");
session_start();

$linkId = $_GET["linkId"];
$uId = $_SESSION["uId"];

$votes = dbGet($connection, "SELECT votes, userId FROM votes WHERE linkId = '$linkId'");
$voteCount = array_sum(array_column($votes, 'votes'));

// If user has voted up...
if ($_GET["vote"] === "up") {
  // ... first check if user has voted already. If not, insert a +1 vote and add 1 to the voteCount variable
  if(!searchVotes($uId, $votes)) {
    $voteCount ++;
    dbPost($connection, "INSERT INTO votes (userId, linkId, votes) VALUES ('$uId', '$linkId', 1)");
  // A new vote from a user that has already voted resets the users vote
  } else {
    $voteCount = resetVote($uId, $linkId, $connection);
  }
}

// If user has voted down...
if ($_GET["vote"] === "down") {
  // ... first check if user has voted already. If not, insert a -1 vote and subtract 1 from the voteCount variable
  if(!searchVotes($uId, $votes)) {
    $voteCount --;
    dbPost($connection, "INSERT INTO votes (userId, linkId, votes) VALUES ('$uId', '$linkId', -1)");
  // A new vote from a user that has already voted resets the users vote
  } else {
    $voteCount = resetVote($uId, $linkId, $connection);
  }
}

dbPost($connection, "UPDATE links SET voteCount = '$voteCount' WHERE id = '$linkId'");

header("Location: ../");
die();


text:
// Copyright (c) rubicon IT GmbH, www.rubicon.eu
//
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership.  rubicon licenses this file to you 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.
//
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading;
using Remotion.Linq.Parsing.Structure.IntermediateModel;
using Remotion.Linq.Utilities;

namespace Remotion.Linq.Parsing.Structure.NodeTypeProviders
{
  /// <summary>
  /// Maps the <see cref="MethodInfo"/> objects used in <see cref="MethodCallExpression"/> objects to the respective <see cref="IExpressionNode"/>
  /// types. This is used by <see cref="ExpressionTreeParser"/> when a <see cref="MethodCallExpression"/> is encountered to instantiate the
  /// right <see cref="IExpressionNode"/> for the given method.
  /// </summary>
  internal sealed class MethodInfoBasedNodeTypeRegistry : INodeTypeProvider
  {
#if !NET_3_5
    private static readonly Dictionary<MethodInfo, Lazy<ICollection<MethodInfo>>> s_genericMethodDefinitionCandidates =
        new Dictionary<MethodInfo, Lazy<ICollection<MethodInfo>>>();
#endif

    /// <summary>
    /// Creates a <see cref="MethodInfoBasedNodeTypeRegistry"/> and automatically registers all types implementing <see cref="IExpressionNode"/>
    /// from a given type sequence that offer a public static <c>SupportedMethods</c> field.
    /// </summary>
    /// <returns>A <see cref="MethodInfoBasedNodeTypeRegistry"/> with all <see cref="IExpressionNode"/> types with a <c>SupportedMethods</c>
    /// field registered.</returns>
    public static MethodInfoBasedNodeTypeRegistry CreateFromTypes (IEnumerable<Type> searchedTypes)
    {
      ArgumentUtility.CheckNotNull ("searchedTypes", searchedTypes);

      var expressionNodeTypes = from t in searchedTypes
                                where typeof (IExpressionNode).GetTypeInfo().IsAssignableFrom (t.GetTypeInfo())
                                select t;

      var supportedMethodsForTypes =
          from t in expressionNodeTypes
          let supportedMethodsField = t.GetRuntimeField ("SupportedMethods")
          select new
                 {
                     Type = t,
                     Methods =
                         supportedMethodsField != null && supportedMethodsField.IsStatic
                             ? (IEnumerable<MethodInfo>) supportedMethodsField.GetValue (null)
                             : Enumerable.Empty<MethodInfo>()
                 };

      var registry = new MethodInfoBasedNodeTypeRegistry();

      foreach (var methodsForType in supportedMethodsForTypes)
      {
        registry.Register (methodsForType.Methods, methodsForType.Type);
      }

      return registry;
    }

    /// <summary>
    /// Gets the registerable method definition from a given <see cref="MethodInfo"/>. A registerable method is a <see cref="MethodInfo"/> object
    /// that can be registered via a call to <see cref="Register"/>. When the given <paramref name="method"/> is passed to
    /// <see cref="GetNodeType"/> and its corresponding registerable method was registered, the correct node type is returned.
    /// </summary>
    /// <param name="method">The method for which the registerable method should be retrieved. Must not be <see langword="null" />.</param>
    /// <param name="throwOnAmbiguousMatch">
    ///   <see langword="true" /> to throw a <see cref="NotSupportedException"/> if the method cannot be matched to a distinct generic method definition,
    ///   <see langword="false" /> to return <see langword="null" /> if an unambiguous match is not possible.
    /// </param>
    /// <returns>
    /// <para>
    ///   <paramref name="method"/> itself, unless it is a closed generic method or declared in a closed generic type. In the latter cases,
    ///   the corresponding generic method definition respectively the method declared in a generic type definition is returned.
    /// </para><para>
    ///   If no generic method definition could be matched and <paramref name="throwOnAmbiguousMatch"/> was set to <see langword="false" />,
    ///   <see langword="null" /> is returned.
    /// </para>
    /// </returns>
    /// <exception cref="NotSupportedException">
    /// Thrown if <paramref name="throwOnAmbiguousMatch"/> is set to <see langword="true" /> and no distinct generic method definition could be resolved.
    /// </exception>
    public static MethodInfo GetRegisterableMethodDefinition (MethodInfo method, bool throwOnAmbiguousMatch)
    {
      ArgumentUtility.CheckNotNull ("method", method);

      var genericMethodDefinition = method.IsGenericMethod ? method.GetGenericMethodDefinition() : method;
      if (!genericMethodDefinition.DeclaringType.GetTypeInfo().IsGenericType)
        return genericMethodDefinition;

      // Simple, fast solution, not possible in PCL because of missing MethodHandle property on MethodInfo type:
      // var declaringTypeDefinition = genericMethodDefinition.DeclaringType.GetGenericTypeDefinition();
      // return (MethodInfo) MethodBase.GetMethodFromHandle (genericMethodDefinition.MethodHandle, declaringTypeDefinition.TypeHandle);

#if NET_3_5
      var declaringTypeDefinition = genericMethodDefinition.DeclaringType.GetGenericTypeDefinition ();
      return (MethodInfo) MethodBase.GetMethodFromHandle (genericMethodDefinition.MethodHandle, declaringTypeDefinition.TypeHandle);
#else
      Lazy<ICollection<MethodInfo>> candidates;
      lock (s_genericMethodDefinitionCandidates)
      {
        if (!s_genericMethodDefinitionCandidates.TryGetValue (method, out candidates))
        {
          candidates = new Lazy<ICollection<MethodInfo>> (
              () => GetGenericMethodDefinitionCandidates (genericMethodDefinition),
              LazyThreadSafetyMode.ExecutionAndPublication);
          s_genericMethodDefinitionCandidates.Add (method, candidates);
        }
      }

      if (candidates.Value.Count == 1)
        return candidates.Value.Single();

      if (!throwOnAmbiguousMatch)
        return null;

      throw new NotSupportedException (
          string.Format (
              "A generic method definition cannot be resolved for method '{0}' on type '{1}' because a distinct match is not possible. "
              + @"The method can still be registered using the following syntax:

public static readonly NameBasedRegistrationInfo[] SupportedMethodNames =
    new[] {{
        new NameBasedRegistrationInfo (
            ""{2}"",
            mi => /* match rule based on MethodInfo */
        )
    }};",
              method,
              genericMethodDefinition.DeclaringType.GetGenericTypeDefinition(),
              method.Name));
    }

    private static MethodInfo[] GetGenericMethodDefinitionCandidates (MethodInfo referenceMethodDefinition)
    {
      var declaringTypeDefinition = referenceMethodDefinition.DeclaringType.GetGenericTypeDefinition();

      var referenceMethodSignature =
          new[] { new { Name = "returnValue", Type = referenceMethodDefinition.ReturnType } }
              .Concat (referenceMethodDefinition.GetParameters().Select (p => new { Name = p.Name, Type = p.ParameterType }))
              .ToArray();

      var candidates = declaringTypeDefinition.GetRuntimeMethods()
          .Select (
              m => new
                   {
                       Method = m,
                       SignatureNames = new[] { "returnValue" }.Concat (m.GetParameters().Select (p => p.Name)).ToArray(),
                       SignatureTypes = new[] { m.ReturnType }.Concat (m.GetParameters().Select (p => p.ParameterType)).ToArray()
                   })
          .Where (c => c.Method.Name == referenceMethodDefinition.Name && c.SignatureTypes.Length == referenceMethodSignature.Length)
          .ToArray();

      for (int i = 0; i < referenceMethodSignature.Length; i++)
      {
        candidates = candidates
            .Where (c => c.SignatureNames[i] == referenceMethodSignature[i].Name)
            .Where (c => c.SignatureTypes[i] == referenceMethodSignature[i].Type || c.SignatureTypes[i].GetTypeInfo().ContainsGenericParameters)
            .ToArray();
      }

      return candidates.Select (c => c.Method).ToArray();
#endif
    }

    private readonly Dictionary<MethodInfo, Type> _registeredMethodInfoTypes = new Dictionary<MethodInfo, Type>();

    /// <summary>
    /// Returns the count of the registered <see cref="MethodInfo"/>s.
    /// </summary>
    public int RegisteredMethodInfoCount
    {
      get { return _registeredMethodInfoTypes.Count; }
    }

    /// <summary>
    /// Registers the specific <paramref name="methods"/> with the given <paramref name="nodeType"/>. The given methods must either be non-generic
    /// or open generic method definitions. If a method has already been registered before, the later registration overwrites the earlier one.
    /// </summary>
    public void Register (IEnumerable<MethodInfo> methods, Type nodeType)
    {
      ArgumentUtility.CheckNotNull ("methods", methods);
      ArgumentUtility.CheckNotNull ("nodeType", nodeType);
      ArgumentUtility.CheckTypeIsAssignableFrom ("nodeType", nodeType, typeof (IExpressionNode));

      foreach (var method in methods)
      {
        if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
        {
          var message = string.Format (
              "Cannot register closed generic method '{0}', try to register its generic method definition instead.", method.Name);
          throw new InvalidOperationException (message);
        }

        if (method.DeclaringType.GetTypeInfo().IsGenericType && !method.DeclaringType.GetTypeInfo().IsGenericTypeDefinition)
        {
          var message = string.Format (
              "Cannot register method '{0}' in closed generic type '{1}', try to register its equivalent in the generic type definition instead.",
              method.Name,
              method.DeclaringType);
          throw new InvalidOperationException (message);
        }

        _registeredMethodInfoTypes[method] = nodeType;
      }
    }

    /// <summary>
    /// Determines whether the specified method was registered with this <see cref="MethodInfoBasedNodeTypeRegistry"/>.
    /// </summary>
    public bool IsRegistered (MethodInfo method)
    {
      ArgumentUtility.CheckNotNull ("method", method);

      return GetNodeType (method) != null;
    }

    /// <summary>
    /// Gets the type of <see cref="IExpressionNode"/> registered with this <see cref="MethodInfoBasedNodeTypeRegistry"/> instance that
    /// matches the given <paramref name="method"/>, returning <see langword="null" /> if none can be found.
    /// </summary>
    public Type GetNodeType (MethodInfo method)
    {
      ArgumentUtility.CheckNotNull ("method", method);

      var methodDefinition = GetRegisterableMethodDefinition (method, throwOnAmbiguousMatch: false);
      if (methodDefinition == null)
        return null;

      Type result;
      _registeredMethodInfoTypes.TryGetValue (methodDefinition, out result);
      return result;
    }
  }
}