text:
package com.wegas.core.security.ejb;

import com.wegas.core.Helper;
import com.wegas.core.ejb.BaseFacade;
import com.wegas.core.ejb.GameFacade;
import com.wegas.core.ejb.GameModelFacade;
import com.wegas.core.ejb.PlayerFacade;
import com.wegas.core.exception.client.WegasConflictException;
import com.wegas.core.exception.client.WegasErrorMessage;
import com.wegas.core.exception.client.WegasNotFoundException;
import com.wegas.core.exception.internal.WegasNoResultException;
import com.wegas.core.persistence.game.Game;
import com.wegas.core.persistence.game.GameModel;
import com.wegas.core.persistence.game.Player;
import com.wegas.core.persistence.game.Team;
import com.wegas.core.rest.util.Email;
import com.wegas.core.security.aai.AaiAccount;
import com.wegas.core.security.guest.GuestJpaAccount;
import com.wegas.core.security.guest.GuestToken;
import com.wegas.core.security.jparealm.JpaAccount;
import com.wegas.core.security.persistence.AbstractAccount;
import com.wegas.core.security.persistence.AccountDetails;
import com.wegas.core.security.persistence.Permission;
import com.wegas.core.security.persistence.Role;
import com.wegas.core.security.persistence.Shadow;
import com.wegas.core.security.persistence.User;
import com.wegas.core.security.token.TokenAuthToken;
import com.wegas.core.security.util.AuthenticationInformation;
import com.wegas.core.security.util.AuthenticationMethod;
import com.wegas.core.security.util.HashMethod;
import com.wegas.core.security.util.JpaAuthentication;
import com.wegas.core.security.util.Sudoer;
import com.wegas.core.security.util.TokenInfo;
import com.wegas.messaging.ejb.EMailFacade;
import java.util.*;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.inject.Inject;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import javax.naming.NamingException;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.LoggerFactory;

/**
 * @author Francois-Xavier Aeberhard (fx at red-agent.com)
 */
@Stateless
@LocalBean
public class UserFacade extends BaseFacade<User> {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(UserFacade.class);

    /**
     *
     */
    @Inject
    private AccountFacade accountFacade;

    /**
     *
     */
    @Inject
    private RoleFacade roleFacade;

    /**
     *
     */
    @Inject
    private PlayerFacade playerFacade;

    /**
     *
     */
    @Inject
    private GameFacade gameFacade;

    /**
     *
     */
    @Inject
    private GameModelFacade gameModelFacade;

    /**
     *
     */
    public UserFacade() {
        super(User.class);
    }

    /**
     * Login as guest
     *
     * @return the just logged user
     *
     * @throws WegasErrorMessage when guest not allowed
     */
    public User guestLogin() {
        if (Helper.getWegasProperty("guestallowed").equals("true")) {
            User newUser = new User();
            this.create(newUser);
            //this.setCurrentUser(newUser);

            newUser.addAccount(new GuestJpaAccount());
            this.merge(newUser);

            requestManager.login(new GuestToken(newUser.getMainAccount().getId()));

            return newUser;
        }
        throw WegasErrorMessage.error("Guest log in not allowed on this server");
    }

    /**
     * Check is username is already in use (case-insensitive !)
     *
     * @param username username to check
     *
     * @return true is username is already in use
     */
    public boolean checkExistingUsername(String username) {
        try ( Sudoer root = requestManager.sudoer()) {
            return !accountFacade.findAllByEmailOrUsername(username).isEmpty();
        }
    }

    /**
     * Authenticate with a token
     *
     * @param email
     * @param token
     *
     * @return the just authenticated user
     */
    public User authenticateFromToken(TokenInfo tokenInfo) {
        if (tokenInfo != null) {
            Subject subject = SecurityUtils.getSubject();

            TokenAuthToken at = new TokenAuthToken(
                tokenInfo.getAccountId(),
                tokenInfo.getToken());

            try {
                requestManager.login(subject, at);
                User user = this.getCurrentUser();
                AbstractAccount mainAccount = user.getMainAccount();

                if (mainAccount instanceof JpaAccount) {
                    JpaAccount jpaAccount = (JpaAccount) mainAccount;
                    jpaAccount.setVerified(Boolean.TRUE);
                }

                this.touchLastSeenAt(user);

                return user;
            } catch (AuthenticationException aex) {
                logger.error("Fails to log in with token {}", tokenInfo);
            }
        }
        throw WegasErrorMessage.error("Token not found");
    }

    public JpaAuthentication getDefaultAuthMethod() {
        return new JpaAuthentication(HashMethod.SHA_256, null,
            Helper.generateSalt(), null);
    }

    /**
     * Return the list of hash method the client may use to sign in. Such methods
     *
     *
     * @param authInfo
     *
     * @return
     */
    public List<AuthenticationMethod> getAuthMethods(String username) {
        List<AuthenticationMethod> methods = new ArrayList<>();
        try {
            requestManager.su();

            for (AbstractAccount account : accountFacade.findAllByEmailOrUsernameCaseSensitive(username)) {
                AuthenticationMethod m = account.getAuthenticationMethod();
                if (m != null) {
                    methods.add(m);
                }
            }

        } finally {
            requestManager.releaseSu();
        }
        if (methods.isEmpty()) {
            methods.add(this.getDefaultAuthMethod());
        }

        return methods;
    }

    public User authenticate(AuthenticationInformation authInfo) {
        Subject subject = SecurityUtils.getSubject();

        User guest = null;
        if (Helper.isLoggedIn(subject)) {
            AbstractAccount gAccount = accountFacade.find((Long) subject.getPrincipal());
            if (gAccount instanceof GuestJpaAccount) {
                logger.error("Logged as guest");
                guest = gAccount.getUser();
                requestManager.logout(subject);
            }
        }

        String password = authInfo.getHashes().get(0);
        UsernamePasswordToken token = new UsernamePasswordToken(authInfo.getLogin(), password);
        token.setRememberMe(authInfo.isRemember());
        try {
            requestManager.login(subject, token);

            AbstractAccount account = accountFacade.find((Long) subject.getPrincipal());
            if (account instanceof JpaAccount) {
                JpaAccount jpaAccount = (JpaAccount) account;
                String newHash = null;

                if (jpaAccount.getShadow().getNextHashMethod() != null) {
                    // shadow asks to use a new hash method
                    // initialize newHash to trigger password update
                    newHash = password;
                }

                HashMethod nextAuth = jpaAccount.getNextAuth();
                if (nextAuth != null && authInfo.getHashes().size() > 1) {
                    // client sent extra hashes, let's switch to the new method
                    // migrate to next auth method silently
                    newHash = authInfo.getHashes().get(1);
                    jpaAccount.migrateToNextAuthMethod();
                }

                if (newHash != null) {
                    jpaAccount.getShadow().generateNewSalt();
                    jpaAccount.setPassword(newHash);
                }
            }

            if (authInfo.isAgreed() && account instanceof JpaAccount) { // why JpaAccount only ?
                account.setAgreedTime(new Date());
                ((JpaAccount) account).setAgreedTime(new Date());
            }

            User user = this.getCurrentUser();
            this.touchLastSeenAt(user);

            if (guest != null) {
                this.transferPlayers(guest, user);
            }
            return user;
        } catch (AuthenticationException aex) {
            logger.error("AUTHFAIL: {}", aex);
            throw WegasErrorMessage.error("Email/password combination not found");
        }
    }

    public User signup(JpaAccount account) throws AddressException, WegasConflictException {
        Helper.assertEmailPattern(account.getDeserialisedEmail());

        if (account.getUsername().equals("") || !this.checkExistingUsername(account.getUsername())) {
            User user;
            Subject subject = SecurityUtils.getSubject();

            if (Helper.isLoggedIn(subject)
                && accountFacade.find((Long) subject.getPrincipal()) instanceof GuestJpaAccount) {
                /**
                 * Subject is authenticated as guest but try to sign up with a full account : let's
                 * upgrade
                 */
                GuestJpaAccount from = (GuestJpaAccount) accountFacade.find((Long) subject.getPrincipal());
                requestManager.logout(subject);
                return this.upgradeGuest(from, account);
            } else {
                // Check if e-mail is already taken and if yes return a localized error message:
                try {
                    accountFacade.findByEmail(account.getDeserialisedEmail());
                    throw new WegasConflictException("email");
                } catch (WegasNoResultException e) {
                    // GOTCHA
                    // E-Mail not yet registered -> proceed with account creation
                    user = new User(account);
                    this.create(user);
                    return user;
                } catch (RuntimeException ex) {
                    throw new WegasConflictException("email");
                }
            }
        } else {
            throw new WegasConflictException("username");
        }
    }

    /**
     * logout current user
     */
    public void logout() {
        requestManager.clearPermissions();
        Subject subject = SecurityUtils.getSubject();
        if (subject.isRunAs()) {
            requestManager.releaseRunAs();
        } else {
            this.touchLastSeenAt(requestManager.getCurrentUser());
            // flush to db before logout !
            this.flush();
            requestManager.logout(subject);
        }
    }

    public void touchLastSeenAt(Long userId) {
        touchLastSeenAt(this.find(userId));
    }

    public void touchLastSeenAt(User user) {
        if (user != null) {
            user.setLastSeenAt(new Date());
        }
    }

    /**
     * @return a User entity, based on the shiro login state
     */
    public AbstractAccount getCurrentAccount() {
        final Subject subject = SecurityUtils.getSubject();

        if (Helper.isLoggedIn(subject)) {
            return accountFacade.find((Long) subject.getPrincipal());
        }
        throw new WegasNotFoundException("Unable to find an account");
    }

    /**
     * @return a User entity, based on the shiro login state
     *
     * @throws WegasNotFoundException no current user
     */
    public User getCurrentUser() throws WegasNotFoundException {
        User currentUser = requestManager.getCurrentUser();
        if (currentUser != null) {
            return currentUser;
        } else {
            throw new WegasNotFoundException("Unable to find user");
        }
    }

    /**
     * Same as {@link #getCurrentUser() } but return null rather than throwing an exception
     *
     * @return the current user or null if current subject is not authenticated
     */
    public User getCurrentUserOrNull() {
        return requestManager.getCurrentUser();
    }

    /* private void setCurrentUser(User user) { requestManager.setCurrentUser(user); } */
    /**
     * @param username String representing the username
     *
     * @return a User entity, based on the username
     */
    public User getUserByUsername(String username) {
        User u = null;
        try {
            u = accountFacade.findByUsername(username).getUser();
        } catch (WegasNoResultException e) { // NOPMD
        }
        return u;
    }

    /**
     * @param persistentId String representing the user
     *
     * @return a User entity, based on the persistentId
     */
    public User getUserByPersistentId(String persistentId) {
        User u = null;
        try {
            u = accountFacade.findByPersistentId(persistentId).getUser();
        } catch (WegasNoResultException e) {
            logger.error("User does not exists");
        }
        return u;
    }

    @Override
    public void create(User user) {
//        AbstractAccount account = user.getMainAccount();
        /*
         * // The following check is now done by caller UserController.signup() try { // @fixme
         * This is only done to have a nice error and not the unparsable
         * ConstraintViolationException if (account instanceof JpaAccount) String mail =
         * ((JpaAccount) account).getEmail(); if (mail != null && !mail.isEmpty()) {
         * accountFacade.findByEmail(mail); throw WegasErrorMessage.error("This email is already
         * associated with an existing account."); } } } catch (WegasNoResultException |
         * InjectTransactionRolledbackException e) { // GOTCHA // E-Mail not yet registered ->
         * proceed }
         */
        // setup shadow storage for each account
        for (AbstractAccount account : user.getAccounts()) {
            if (account.getShadow() == null) {
                account.setShadow(new Shadow());
            }
            if (account.getDetails() == null) {
                account.setDetails(new AccountDetails());
            }
        }

        getEntityManager().persist(user);

        for (AbstractAccount account : user.getAccounts()) {
            if (account != null) {
                if (account instanceof JpaAccount) {
                    JpaAuthentication authMethod = this.getDefaultAuthMethod();
                    JpaAccount jpaAccount = (JpaAccount) account;
                    jpaAccount.shadowPasword();
                    jpaAccount.setCurrentAuth(authMethod.getMandatoryMethod());
                    jpaAccount.setNextAuth(authMethod.getOptionalMethod());
                }

                account.shadowEmail();
            }
        }

        this.touchLastSeenAt(user);
        /*
         * Very strange behaviour: without this flush, RequestManages faild to be injected within
         * others beans...
         */
        this.getEntityManager().flush();
    }

    /**
     * Same as {@link remove(java.lang.Long) } but within a brand new transaction
     *
     * @param gameModelId id of the gameModel to remove
     */
    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public void removeTX(Long userId) {
        logger.info("Remove User #{}", userId);
        this.remove(userId);
        logger.info("  done");
    }

    @Override
    public void remove(User entity) {
        for (Role r : entity.getRoles()) {
            r.removeUser(entity);
        }
        /* ???: Should be cascaded, nope ??? */
        // clone list to avoid CME
        List<AbstractAccount> accounts = new ArrayList<>(entity.getAccounts());
        for (AbstractAccount aa : accounts) {
            accountFacade.remove(aa);
        }

        for (Player player : entity.getPlayers()) {
            player.setUser(null);
        }

        for (Team team : entity.getTeams()) {
            team.setCreatedBy(null);
        }

        getEntityManager().remove(entity);
    }

    /**
     * Get all roles which have some permissions on the given instance..
     * <p>
     * Map is { id : role id, name: role name, permissions: list of permissions related to instance}
     *
     * @param instance
     *
     * @return list of "Role"
     */
    public List<Map> findRolePermissionByInstance(String instance) {
        TypedQuery<Role> findByToken = getEntityManager()
            //@fixme Unable to select role with a like w/ embeddebale
            .createQuery("SELECT DISTINCT roles "
                + "FROM Role roles "
                + "JOIN roles.permissions p "
                + "WHERE p.value LIKE :instance", Role.class);
        // Query findByToken = getEntityManager()
        //.createQuery("SELECT DISTINCT roles FROM Role roles WHERE roles.permissions.value = 'mm'");
        // SELECT DISTINCT roles FROM Role roles WHERE roles.permissions LIKE :gameId
        findByToken.setParameter("instance", "%:" + instance);

        List<Role> res = findByToken.getResultList();
        List<Map> allRoles = new ArrayList<>();
        for (Role unRole : res) {
            Map<String, Object> role = new HashMap<>();
            role.put("id", unRole.getId());
            role.put("name", unRole.getName());
            List<String> permissions = new ArrayList<>();
            role.put("permissions", permissions);

            for (Permission permission : unRole.getPermissions()) {
                String splitedPermission[] = permission.getValue().split(":");
                if (splitedPermission.length >= 3 && splitedPermission[2].equals(instance)) {
                    permissions.add(permission.getValue());
                }
            }
            allRoles.add(role);
        }

        return allRoles;
    }

    /**
     * Create role_permissions
     *
     * @param roleId     id of the role to add permission too
     * @param permission permission to add
     *
     * @return true if the permission has successfully been added
     */
    public boolean addRolePermission(final Long roleId, final String permission) {
        final Role r = roleFacade.find(roleId);
        return r.addPermission(new Permission(permission));
    }

    /**
     *
     * @param userId     id of the user
     * @param permission permission to add
     *
     * @return true if the permission has successfully been added
     */
    public boolean addUserPermission(final Long userId, final String permission) {
        return this.addUserPermission(userId, new Permission(permission));
    }

    /**
     * @param userId id of the user
     * @param p      permission to add
     *
     * @return true if the permission has successfully been added
     */
    public boolean addUserPermission(final Long userId, final Permission p) {
        final User user = this.find(userId);
        return user.addPermission(p);
    }

    /**
     *
     * @param user
     * @param permission
     *
     * @return true if the permission has successfully been added
     */
    public boolean addUserPermission(final User user, final String permission) {
        return user.addPermission(new Permission(permission));
        //return user.addPermission(this.generatePermisssion(permission));
    }

    /**
     * @param instance
     *
     * @return all user which have a permission related to the given instance
     */
    public List<User> findUserByPermissionInstance(String instance) {
        final TypedQuery<User> findByToken = getEntityManager()
            .createNamedQuery("User.findUserPermissions", User.class);
        findByToken.setParameter("instance", "%:" + instance);
        return findByToken.getResultList();
    }

    /**
     * @param instance
     *
     * @return all user which have a permission related to the given instance
     */
    public List<User> findEditors(String instance) {
        String permission;
        if (instance.substring(0, 2).equals("gm")) {
            permission = "GameModel:%Edit%:";
        } else {
            permission = "Game:%Edit%:";
        }

        final TypedQuery<User> findByToken = getEntityManager()
            .createNamedQuery("User.findUserPermissions", User.class);
        findByToken.setParameter("instance", permission + instance);
        return findByToken.getResultList();
    }

    /**
     * Get all users is
     *
     * @param role_id
     *
     * @return all role members
     */
    public List<User> findUsersWithRole(Long role_id) {
        /* Why not using JPA ? return roleFacade.find(role_id).getUsers(); ??????
         */
        final TypedQuery<User> findWithRole = getEntityManager()
            .createNamedQuery("User.findUsersWithRole", User.class);
        findWithRole.setParameter("role_id", role_id);
        return findWithRole.getResultList();
    }

    public void deletePermission(Permission p) {
        if (p.getUser() != null) {
            this.find(p.getUser().getId()).removePermission(p);
        }
        if (p.getRole() != null) {
            roleFacade.find(p.getRole().getId()).removePermission(p);
        }
        this.getEntityManager().remove(p);
    }

    public List<Role> findRoles(User user) {
        if (user != null) {
            TypedQuery<Role> queryRoles = getEntityManager().createNamedQuery("Roles.findByUser", Role.class);
            queryRoles.setParameter("userId", user.getId());
            return queryRoles.getResultList();
        } else {
            return new ArrayList<>();
        }
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public List<Role> findRolesTransactional(Long userId) {
        return this.findRoles(this.find(userId));
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public List<String> findRolesNative(User user) {
        Query queryRoles = getEntityManager().createNamedQuery("Roles.findByUser_native", Role.class);
        queryRoles.setParameter(1, user.getId());
        return queryRoles.getResultList();
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public List<Permission> findAllUserPermissionsTransactional(Long userId) {
        return this.findAllUserPermissions(this.find(userId));
    }

    public List<Permission> findAllUserPermissions(User user) {
        if (user != null) {
            List<Permission> perms = new ArrayList<>();

            for (Role role : this.findRoles(user)) {
                perms.addAll(role.getPermissions());
            }
            perms.addAll(user.getPermissions());

            return perms;
        } else {
            return new ArrayList<>();
        }
    }

    @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
    public List<String> findAllUserPermissionsNativeJpa(User user) {
        Query query = getEntityManager().createNamedQuery("Permission.findByUser_native");
        query.setParameter(1, user.getId());
        return query.getResultList();
    }

    public List<Permission> findAllUserPermissionsJpa(User user) {
        List<Permission> perms = new ArrayList<>();

        for (Role role : this.findRoles(user)) {
            TypedQuery<Permission> queryRolePermission = getEntityManager()
                .createNamedQuery("Permission.findByRole", Permission.class);
            queryRolePermission.setParameter("roleId", role.getId());
            perms.addAll(queryRolePermission.getResultList());
        }

        TypedQuery<Permission> queryUserPermissions = getEntityManager()
            .createNamedQuery("Permission.findByUser", Permission.class);
        queryUserPermissions.setParameter("userId", user.getId());
        perms.addAll(queryUserPermissions.getResultList());

        return perms;
    }

    private List<Permission> findUserPermissions(String permission, User user) {
        TypedQuery<Permission> query = getEntityManager()
            .createNamedQuery("Permission.findByPermissionAndUser", Permission.class);
        query.setParameter("userId", user.getId());
        query.setParameter("permission", permission);

        return query.getResultList();
    }

    public void deletePermissions(User user, String permission) {
        for (Permission p : this.findUserPermissions(permission, user)) {
            this.deletePermission(p);
        }
    }

    public void deletePermissions(Game game) {
        this.deletePermissions("Game:%:g" + game.getId());
    }

    public void deletePermissions(GameModel gameModel) {
        this.deletePermissions("GameModel:%:gm" + gameModel.getId());
    }

    private void deletePermissions(String permission) {
        TypedQuery<Permission> query = getEntityManager()
            .createNamedQuery("Permission.findByPermission", Permission.class);
        query.setParameter("permission", permission);

        for (Permission p : query.getResultList()) {
            this.deletePermission(p);
        }
    }

    /**
     *
     * @param trainerId
     * @param gameId
     */
    public void addTrainerToGame(Long trainerId, Long gameId) {
        // load the game to make sure it exists
        Game game = gameFacade.find(gameId);
        requestManager.assertGameTrainer(game);
        try (Sudoer su = requestManager.sudoer()) {
            if (game != null) {
                User user = this.find(trainerId);
                this.addUserPermission(user, "Game:View,Edit:g" + gameId);
                // make sure to send game too
                requestManager.addUpdatedEntity(game);
            }
        }
    }

    public void removeTrainer(Long gameId, User trainer) {
        // load the game to make sure it exists
        Game game = gameFacade.find(gameId);
        requestManager.assertGameTrainer(game);
        try (Sudoer su = requestManager.sudoer()) {
            if (this.getCurrentUser().equals(trainer)) {
                throw WegasErrorMessage.error("Cannot remove yourself");
            }

            if (this.findEditors("g" + gameId).size() <= 1) {
                throw WegasErrorMessage.error("Cannot remove last trainer");
            } else {
                this.deletePermissions(trainer, "Game:%Edit%:g" + gameId);
            }
        }
    }

    /**
     *
     * @param userId
     * @param gameModelId
     * @param permissions
     */
    public void grantGameModelPermissionToUser(Long userId, Long gameModelId, String permissions) {
        GameModel gm = gameModelFacade.find(gameModelId);
        requestManager.assertUpdateRight(gm);
        try (Sudoer su = requestManager.sudoer()) {
            User user = this.find(userId);

            /*
             * Revoke previous permissions (do not use removeScenarist method since this method
             * prevents to remove one own permissions,
             */
            this.deletePermissions(user, "GameModel:%:gm" + gameModelId);

            // Grant new permission
            this.addUserPermission(user, "GameModel:" + permissions + ":gm" + gameModelId);
            // make sure to send the gameModel too
            requestManager.addUpdatedEntity(gm);
        }
    }

    public void removeScenarist(Long gameModelId, User scenarist) {
        GameModel gm = gameModelFacade.find(gameModelId);
        requestManager.assertUpdateRight(gm);
        try (Sudoer su = requestManager.sudoer()) {
            if (this.getCurrentUser().equals(scenarist)) {
                throw WegasErrorMessage.error("Cannot remove yourself");
            }

            List<User> editors = this.findEditors("gm" + gameModelId);
            if (editors.size() <= 1 && editors.contains(scenarist)) {
                throw WegasErrorMessage.error("Cannot remove last scenarist");
            } else {
                //remove all permission matching  both gameModelId and userId
                this.deletePermissions(scenarist, "GameModel:%:gm" + gameModelId);
            }
        }
    }

    /**
     * Send an e-mail to current user to verify its email address. It's only valid for JPAAccounts
     *
     * @param request http request is required to generate the link to send
     */
    public void requestEmailValidation(HttpServletRequest request) {
        User currentUser = requestManager.getCurrentUser();
        if (currentUser != null) {
            AbstractAccount account = currentUser.getMainAccount();

            if (account instanceof JpaAccount) {
                accountFacade.requestValidationLink((JpaAccount) account, request);
            }
        }
    }

    /**
     * Sends the given email as one separate message per addressee (as a measure against spam
     * filters) and an additional one to the sender to provide him a copy of the message. If an
     * address is invalid (but syntactically correct), it should not prevent from sending to the
     * other addressees.
     */
    public void sendEmail(Email email) /* throws MessagingException */ {
        List<Exception> exceptions = new ArrayList<>();
        EMailFacade emailFacade = new EMailFacade();
        for (Player p : email.getTo()) {
            Player rP = playerFacade.find(p.getId());
            AbstractAccount mainAccount = rP.getUser().getMainAccount();
            if (mainAccount instanceof JpaAccount || mainAccount instanceof AaiAccount) {
                try {
                    emailFacade.send(mainAccount.getDetails().getEmail(),
                        email.getFrom(), email.getReplyTo(),
                        email.getSubject(),
                        email.getBody(),
                        Message.RecipientType.TO, "text/html; charset=utf-8", true);
                } catch (MessagingException e) {
                    exceptions.add(e);
                }
            }
        }
        try {
            // Send a last message directly to the sender as a confirmation copy
            emailFacade.send(email.getReplyTo(),
                email.getFrom(), email.getReplyTo(),
                email.getSubject(),
                email.getBody(), Message.RecipientType.TO, "text/html; charset=utf-8", true);
        } catch (MessagingException e) {
            exceptions.add(e);
        }
        if (!exceptions.isEmpty()) {
            for (Exception e : exceptions) {
                logger.error("saendMail {}", e);
            }
            throw WegasErrorMessage.error(exceptions.size() + " error(s) while sending email");
        }
    }

    /**
     * Is the given playerId identify a player owned by the current user players ?
     *
     * @param playerId
     *
     * @return true if the player is owned by the current user
     */
    public boolean matchCurrentUser(Long playerId) {
        return this.getCurrentUser().equals(playerFacade.find(playerId).getUser());
    }

    /**
     *
     * @param roleNames
     * @param user
     *
     * @return true if user is member of at least one group from the list
     */
    public boolean hasAnyRole(User user, List<String> roleNames) {
        Collection<Role> roles = user.getRoles();
        if (roleNames != null && roles != null) {
            for (Role role : roles) {
                if (roleNames.contains(role.getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Transfer players and permission from one user to another
     *
     * @param from the player to take perm and players from
     * @param to   the whow
     */
    public void transferPlayers(User from, User to) {
        final List<Long> gameIds = new ArrayList<>();
        for (Player player : to.getPlayers()) {
            gameIds.add(player.getGame().getId());
        }
        for (Player p : from.getPlayers()) {
            if (!gameIds.contains(p.getGame().getId())) { // User already has a player in p's game
                // p.setName(to.getName());
                p.setUser(to);
            }
        }
        for (Permission p : from.getPermissions()) {
            p.setUser(to);
        }
    }

    public User upgradeGuest(GuestJpaAccount guest, JpaAccount account) {
        User user = guest.getUser();
        user.addAccount(account);

        if (account.getShadow() == null) {
            account.setShadow(new Shadow());
        }
        if (account.getDetails() == null) {
            account.setDetails(new AccountDetails());
        }

        accountFacade.create(account);

        JpaAuthentication authMethod = this.getDefaultAuthMethod();

        account.shadowPasword();
        account.setCurrentAuth(authMethod.getMandatoryMethod());
        account.setNextAuth(authMethod.getOptionalMethod());
        // Detach and delete account
        accountFacade.remove(guest.getId());

        this.refresh(user);
        /* for (Player p : user.getPlayers()) { p.setName(user.getName()); } */
        return user;
    }

    public void addRole(User u, Role r) {
        u.addRole(r);
        r.addUser(u);
        //this.merge(u);
    }

    public User addRole(Long uId, Long rId) {
        User u = this.find(uId);
        Role r = roleFacade.find(rId);
        this.addRole(u, r);
        return u;
    }

    public void removeRole(User u, Role r) {
        u.removeRole(r);
        r.removeUser(u);
        //this.merge(u);
    }

    public User removeRole(Long uId, Long rId) {
        User u = this.find(uId);
        Role r = roleFacade.find(rId);
        this.removeRole(u, r);
        return u;
    }

    /**
     * Give a permission to the user identified by the given id
     *
     * @param userId     id of the user
     * @param permission the permission
     *
     * @return the newly persisted permission
     */
    public Permission createPermission(Long userId, Permission permission) {
        User user = this.find(userId);
        permission.setUser(user);
        permission.setRole(null);
        user.addPermission(permission);
        this.getEntityManager().persist(permission);

        return permission;
    }

    /**
     * Update a permission
     *
     * @param permission new value
     *
     * @return updated managed permission
     */
    public Permission updatePermission(Permission permission) {
        Long id = permission.getId();
        Permission p = this.getEntityManager().find(Permission.class, id);
        p.setValue(permission.getValue());
        return p;
    }

    /**
     * Delete a permission
     *
     * @param id id of the permission to delete
     *
     * @return just deleted permission
     */
    public Permission deletePermission(Long id) {
        Permission p = this.getEntityManager().find(Permission.class, id);
        this.deletePermission(p);
        return p;
    }

    /**
     * @return Looked-up EJB
     */
    public static UserFacade lookup() {
        try {
            return Helper.lookupBy(UserFacade.class
            );
        } catch (NamingException ex) {
            logger.error("Error retrieving user facade", ex);
            return null;
        }
    }
}


text:
module app.dialogs.dataschemaimport {

    class Runner {

        static $inject = ['EmptyHookService'];

        constructor(emptyHookService:EmptyHookService) {

        }
    }

    angular.module('app.dialogs.empty').run(Runner);
}

redpajama_set_name: RedPajamaGithub


text:
import javabridge

def test_java_bridge():
    javabridge.start_vm(run_headless=True)
    try:
        print(javabridge.run_script('java.lang.String.format("Hello, %s!", name);', dict(name='world')))
    finally:
        javabridge.kill_vm()


text:
package io.netty.channel;

import java.util.Queue;

/**
 * Factory used to create {@link Queue} instances that will be used to store tasks for an {@link EventLoop}.
 *
 * Generally speaking the returned {@link Queue} MUST be thread-safe and depending on the {@link EventLoop}
 * implementation must be of type {@link java.util.concurrent.BlockingQueue}.
 */
public interface EventLoopTaskQueueFactory {

    /**
     * Returns a new {@link Queue} to use.
     * @param maxCapacity the maximum amount of elements that can be stored in the {@link Queue} at a given point
     *                    in time.
     * @return the new queue.
     */
    Queue<Runnable> newTaskQueue(int maxCapacity);
}


text:
/**
 * A Text Word Wrap configuration object as used by the Text Style configuration.
 *
 * @typedef {object} Phaser.Types.GameObjects.Text.TextWordWrap
 * @since 3.0.0
 *
 * @property {number} [width] - The width at which text should be considered for word-wrapping.
 * @property {TextStyleWordWrapCallback} [callback] - Provide a custom callback when word wrapping is enabled.
 * @property {any} [callbackScope] - The context in which the word wrap callback is invoked.
 * @property {boolean} [useAdvancedWrap=false] - Use basic or advanced word wrapping?
 */

/**
 * A custom function that will be responsible for wrapping the text.
 * @callback TextStyleWordWrapCallback
 *
 * @param {string} text - The string to wrap.
 * @param {Phaser.GameObjects.Text} textObject - The Text instance.
 *
 * @return {(string|string[])} Should return the wrapped lines either as an array of lines or as a string with
 * newline characters in place to indicate where breaks should happen.
 */


text:
package com.astro.mobileassessment.models;

import java.util.List;

/**
 * Created by TuanNA on 9/27/17.
 */

public class ChannelMetadataResponse extends BaseResponse {

    List<ChannelMetadata> channel;

    public List<ChannelMetadata> getChannel() {
        return channel;
    }

    public void setChannel(List<ChannelMetadata> channel) {
        this.channel = channel;
    }

    public class ChannelMetadata{
        private int channelId;
        private String channelTitle;
        private String channelLanguage;
        private List<ChannelExtRef> channelExtRef;
        private String channelCategory;

        public String getChannelCategory() {
            return channelCategory;
        }

        public void setChannelCategory(String channelCategory) {
            this.channelCategory = channelCategory;
        }

        public int getChannelId() {
            return channelId;
        }

        public void setChannelId(int channelId) {
            this.channelId = channelId;
        }

        public String getChannelTitle() {
            return channelTitle;
        }

        public void setChannelTitle(String channelTitle) {
            this.channelTitle = channelTitle;
        }

        public String getChannelLanguage() {
            return channelLanguage;
        }

        public void setChannelLanguage(String channelLanguage) {
            this.channelLanguage = channelLanguage;
        }

        public List<ChannelExtRef> getChannelExtRef() {
            return channelExtRef;
        }

        public void setChannelExtRef(List<ChannelExtRef> channelExtRef) {
            this.channelExtRef = channelExtRef;
        }
    }

    public class ChannelExtRef{
        private String system;
        private String subSystem;
        private String value;

        public String getSystem() {
            return system;
        }

        public void setSystem(String system) {
            this.system = system;
        }

        public String getSubSystem() {
            return subSystem;
        }

        public void setSubSystem(String subSystem) {
            this.subSystem = subSystem;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}


text:
/* jshint node: true */
'use strict';

module.exports = {
  name: 'dynamic-dashboard',

  included: function (app) {
      this._super.included(app);

      app.import('vendor/dynamic-dashboard.css');
  }
};


text:
/* Angular init */
var writer = angular.module('writer', ['ui.router', 'angular-loading-bar', 'ngAnalytics', 'ngMap', 'ngFacebook',
'writer.controllers', 'writer.services', 'writer.filters', 'writer.directives', 'writer.interceptors']);

/* Module setup */
angular.module('writer.controllers', []);
angular.module('writer.services', []);
angular.module('writer.filters', []);
angular.module('writer.directives', []);
angular.module('writer.interceptors', []);

/* Moment.js init */
moment.locale('sv');

/* Router setup */
writer.config(function($stateProvider, $locationProvider, $urlRouterProvider,
    $httpProvider, cfpLoadingBarProvider, $urlMatcherFactoryProvider, $facebookProvider) {
        /* Crawler magic */
        $locationProvider.hashPrefix('!');
        $locationProvider.html5Mode(true);

        // Initialize ngFacebook
        $facebookProvider.setAppId('1539788846329411'); // PROD
        // $facebookProvider.setAppId('1606132839695011'); // DEV
        $facebookProvider.setPermissions('publish_actions');

        /* API Base URL */
        $httpProvider.defaults.base_url = '/api';
        // $httpProvider.defaults.base_url = 'http://localhost:3000';

        /* Remove spinner */
        cfpLoadingBarProvider.includeSpinner = false;

        /* Set delay prior to loading bar displayed */
        cfpLoadingBarProvider.latencyThreshold = 500;

        /* Fallback URL */
        $urlRouterProvider.otherwise('/posts');

        /* Interceptors */
        $httpProvider.interceptors.push('UnauthorizedInterceptor');
        $httpProvider.interceptors.push('LoadingInterceptor');

        $stateProvider
        .state('base', {
            templateUrl: 'partials/base.html',
            controller: 'BaseCtrl',
            abstract: true,
            data: { pageTitle: 'Asien 2017' }
        })
        .state('base.posts', {
            url: '/posts',
            templateUrl: 'partials/posts/posts.html',
            controller: 'PostCtrl',
            data: { pageTitle: 'Asien 2017 | Blogg' }
        })
        .state('base.archive', {
            url: '/archive?category&author',
            templateUrl: 'partials/posts/archive.html',
            controller: 'ArchiveCtrl',
            data: { pageTitle: 'Asien 2017 | Arkiv' }
        })
        .state('base.postdetail', {
            url: '/posts/:year/:month/:slug',
            templateUrl: 'partials/posts/posts-detail.html',
            controller: 'PostDetailCtrl',
            data: { pageTitle: 'Asien 2017 | Blogg' }
        })
        .state('base.route', {
            url: '/route',
            templateUrl: 'partials/route.html',
            controller: 'RouteCtrl',
            data: { pageTitle: 'Asien 2017 | Vår rutt' }
        })
        .state('base.about', {
            url: '/about',
            templateUrl: 'partials/about.html',
            controller: 'AboutCtrl',
            data: { pageTitle: 'Asien 2017 | Om oss' }
        })
        /* Admin states */
        .state('base.admin', {
            url: '/admin',
            templateUrl: 'partials/admin/base.html',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Admin' }
        })
        .state('base.admin.login', {
            templateUrl: 'partials/admin/login.html',
            controller: 'LoginCtrl',
            data: { pageTitle: 'Asien 2017 | Logga in' }
        })
        .state('base.admin.dashboard', {
            url: '/dashboard',
            templateUrl: 'partials/admin/dashboard.html',
            controller: 'DashboardCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Dashboard' }
        })
        .state('base.admin.posts', {
            url: '/posts',
            templateUrl: 'partials/admin/posts/posts.html',
            controller: 'AdminPostCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Inlägg' }
        })
        .state('base.admin.posts.new', {
            url: '/new',
            templateUrl: 'partials/admin/posts/posts-new.html',
            controller: 'NewPostCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Nytt inlägg' }
        })
        .state('base.admin.posts.detail', {
            url: '/:id',
            templateUrl: 'partials/admin/posts/posts-detail.html',
            controller: 'AdminPostDetailCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Inlägg' }
        })
        .state('base.admin.categories', {
            url: '/categories',
            templateUrl: 'partials/admin/categories/categories.html',
            controller: 'AdminCategoriesCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Kategorier' }
        })
        .state('base.admin.categories.new', {
            url: '/new',
            templateUrl: 'partials/admin/categories/categories-new.html',
            controller: 'NewCategoryCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Ny kategori' }
        })
        .state('base.admin.categories.detail', {
            url: '/:id',
            templateUrl: 'partials/admin/categories/categories-detail.html',
            controller: 'AdminCategoryDetailCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Kategori' }
        })
        .state('base.admin.users', {
            url: '/users',
            templateUrl: 'partials/admin/users/users.html',
            controller: 'AdminUsersCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Användare' }
        })
        .state('base.admin.users.new', {
            url: '/new',
            templateUrl: 'partials/admin/users/users-new.html',
            controller: 'NewUserCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Ny användare' }
        })
        .state('base.admin.users.detail', {
            url: '/:id',
            templateUrl: 'partials/admin/users/users-detail.html',
            controller: 'AdminUsersDetailCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Användare' }
        })
        .state('base.admin.comments', {
            url: '/comments',
            templateUrl: 'partials/admin/comments/comments.html',
            controller: 'AdminCommentCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Kommentarer' }
        })
        .state('base.admin.comments.detail', {
            url: '/:id',
            templateUrl: 'partials/admin/comments/comments-detail.html',
            controller: 'AdminCommentDetailCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Kommentar' }
        })
        .state('base.admin.profile', {
            url: '/profile',
            templateUrl: 'partials/admin/profile.html',
            controller: 'ProfileCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Min profil' }
        })
        .state('base.admin.settings', {
            url: '/settings',
            templateUrl: 'partials/admin/settings.html',
            controller: 'SettingsCtrl',
            authenticate: true,
            data: { pageTitle: 'Asien 2017 | Inställningar' }
        })
    });

    /* Adding authentication */
    writer.run(function ($rootScope, $state, $window, $location, AuthService, ngAnalyticsService) {
        $rootScope.authenticated = AuthService.isAuthenticated();

        // Load Facebook JS SDK
        (function(){
            // If we've already installed the SDK, we're done
            if (document.getElementById('facebook-jssdk')) {return;}

            // Get the first script element, which we'll use to find the parent node
            var firstScriptElement = document.getElementsByTagName('script')[0];

            // Create a new script element and set its id
            var facebookJS = document.createElement('script');
            facebookJS.id = 'facebook-jssdk';

            // Set the new script's source to the source of the Facebook JS SDK
            facebookJS.src = '//connect.facebook.net/en_US/all.js';

            // Insert the Facebook JS SDK into the DOM
            firstScriptElement.parentNode.insertBefore(facebookJS, firstScriptElement);
        }());

        // Initialize Google Analytics
        $window.ga('create', 'UA-72529449-3', 'auto');
        $window.ga(function(tracker) {
            ngAnalyticsService.setClientId('247299331510-g9jvenk0bcvo406gd2mrdabd49550p7b.apps.googleusercontent.com');
        });

        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (toState.authenticate && !AuthService.isAuthenticated()) {
                $state.transitionTo('base.admin.login');
                event.preventDefault();
            }
        });
        $rootScope.$on('$stateChangeSuccess', function (evt, toState) {
            if (toState.name === 'base.admin') {
                $state.go('base.admin.dashboard');
            }
            $window.ga('send', 'pageview', $location.path());
        });
    });


text:
import React from 'react'
import Root from '../../app/containers/Root';

class AlwaysOn extends React.Component {
  constructor () {
    super()
  }
  render () {
    return <div>
      <Root />
    </div>
  }
}

window.addEventListener('load', () => {
  React.render(<AlwaysOn />, document.querySelector('#reactApp'));
});


text:
```
# brew 程序本身,Homebrew/Linuxbrew 相同
git -C "$(brew --repo)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git

# 以下针对 mac OS 系统上的 Homebrew
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git
git -C "$(brew --repo homebrew/cask)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git
git -C "$(brew --repo homebrew/cask-fonts)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask-fonts.git
git -C "$(brew --repo homebrew/cask-drivers)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask-drivers.git

# 以下针对 Linux 系统上的 Linuxbrew
git -C "$(brew --repo homebrew/core)" remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/linuxbrew-core.git

# 更换后测试工作是否正常
brew update
```
copy from [Homebrew/Linuxbrew 镜像使用帮助](https://mirrors.tuna.tsinghua.edu.cn/help/homebrew/)

## virtualbox

```
Restart your mac in Recovery mode (cmd + R)

Then open a Terminal and enter : spctl kext-consent add VB5E2TV963

Restart your mac.
```
copy from [Can't Reinstall VirtualBox on Mojave](https://forums.virtualbox.org/viewtopic.php?f=8&t=93246)

## add keyboard shortcuts
see [在Mac中设置Ctrl+C/V进行复制/粘贴](https://support.apple.com/zh-cn/HT201236)

## macosx keyboard shortcuts
see [Mac 键盘快捷键](https://support.apple.com/zh-cn/HT201236)

## change keyboard key position by using Karabiner-Elements

~~## install intel-power-gadget~~

``` shell
brew cask install intel-power-gadget
```
copy from [How I fixed my VirtualBox VMs randomly crashing on macOS](https://angristan.xyz/2020/02/crashes-virtualbox-macos-intel-power-gadget/)

## Remove .DS_Store in macOS

``` shell
defaults write com.apple.desktopservices DSDontWriteNetworkStores true
```
copy from [Remove .DS_Store in macOS](https://wp-mix.com/remove-ds_store-in-macos/)

## install julia

``` shell
brew cask install julia
```

## brew download cache directory

``` shell
~/Library/Caches/Homebrew/downloads
```

## docker desktop

``` shell
https://mirrors.aliyun.com/docker-toolbox/mac/docker-for-mac/stable/Docker.dmg
```

## install IDE

``` shell
brew tap homebrew/cask-versions
brew cask install android-studio visual-studio unity-hub epic-games
```

## Simulator

``` shell
open -a Simulator
```

## android-platform-tools

``` shell
brew cask install android-platform-tools

```

## pandoc

``` shell
brew install pandoc
```

## upgrade

``` shell
brew upgrade
brew upgrade --cask
brew upgrade --cask --greedy
 brew outdated --cask --greedy
```

## install pass

``` shell
brew install pass
```

## find the package download filename

``` shell
brew cache -s package-name
```

## delete ABC input method

``` shell
/usr/libexec/PlistBuddy -c "Delete :AppleEnabledInputSources:1" ~/Library/Preferences/com.apple.HIToolbox.plist
```
copy from [Mac 怎么设置搜狗输入法为默认第一位?](https://www.v2ex.com/amp/t/592752)

## install firefox

``` shell
brew cask install firefox --language=zh
```
copy from [language](https://github.com/Homebrew/homebrew-cask/blob/master/doc/cask_language_reference/stanzas/language.md])

## homebrew usage

``` shell
## Edit this formula
brew edit git

## Print this formula
brew cat git
```

## brew cleanup

``` shell
alias brewski='brew update && brew upgrade && brew cleanup; brew doctor'
```
copy from [别忘了定期执行 brew cleanup 哦](https://www.jianshu.com/p/403140306cb6)

## not mount disk

``` shell
$ sudo diskutil list
$ sudo diskutil info --all | grep "Volume UUID"
$ sudo echo "UUID=3B87FF76-C6DA-49BF-B911-61DE2331E9F5 none ext4 noauto 0 0" >> /etc/fstab

```
The `3B87FF76-C6DA-49BF-B911-61DE2331E9F5` is the disk you don't want to mount automatically.
copy from [MacOS下禁止开机自动挂载分区 [/etc/fstab]](https://blog.csdn.net/qq_38202733/article/details/109631753)

or
``` shell
echo "UUID=791E37B4-82A3-37E7-9F15-3C39359126B4   none  hfs  rw,noauto" >> /etc/fstab
```
copy from [How to Disable USB Auto-mount](https://apple.stackexchange.com/questions/120782/how-to-disable-usb-auto-mount)

use with virtualbox:

``` shell
VBoxManage list usbhost
```
copy from [How to get the UUID of a USB device on a Mac?](https://stackoverflow.com/questions/8305419/how-to-get-the-uuid-of-a-usb-device-on-a-mac/37170840)

## access samba
Finder->Go(前往)->Connete to Server...(连接服务器)(Command+K)
smb://ip/share

copy from [Mac OS X 访问连接SAMBA共享磁盘](https://www.jianshu.com/p/4f785ae6c29c)
also see [Macos 建立Samba服务器](https://blog.csdn.net/qq_38375620/article/details/101699465)

## disable brew auto update

``` shell
echo "export HOMEBREW_NO_INSTALL_UPGRADE=1" >> ~/.zshrc
source ~/.zshrc
```
copy from [HOMEBREW_NO_AUTO_UPDATE=1 environment variable does not work](https://github.com/Homebrew/brew/issues/12114)

## podman

``` shell
brew install podman
podman machine init
podman machine start
export DOCKER_HOST='unix:///Users/gerald/.local/share/containers/podman/machine/podman-machine-default/podman.sock'
podman pull yandex/clickhouse-server:21.3.20.1
podman run -d --name some-clickhouse-server --ulimit nofile=262144:262144 yandex/clickhouse-server:21.3.20.1
```

## Warning: Bottle missing, falling back to the default domain

``` shell
echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.ustc.edu.cn/homebrew-bottles/bottles' >> ~/.zshrc

source ~/.zshrc
```

## reinstall

``` shell
brew reinstall --cask sogouinput
```
copy from [Homebrew - Error: Not upgrading 1 `installer manual` cask](https://www.reddit.com/r/Windscribe/comments/soe5hn/homebrew_error_not_upgrading_1_installer_manual/)


text:
This section contains the following Plugins
* [Aspose .NET AutoMerge](Aspose .NET AutoMerge 1.0.0)
* [Aspose .NET AutoMerge v 2.0](Aspose .NET AutoMerge 2.0.0)
* [Aspose .NET Document Generator](Aspose .NET Document Generator)
* [Aspose .NET Document Merger](Aspose .NET Document Merger)
* [Aspose.DuplicateDocument](Aspose.DuplicateDocument)
* [Aspose .NET Quote Generator](Aspose .NET Quote Generator)


text:
package rhogenwizard.debugger;

import org.eclipse.debug.core.model.IWatchExpressionResult;
import org.eclipse.debug.internal.core.WatchExpression;

@SuppressWarnings("restriction")
public class RhogenWatchExpression extends WatchExpression
{
	public RhogenWatchExpression(String expression)
	{
		super(expression);
	}

	public void evaluate()
	{
		//setPending(true);
		//setResult(this.fResult);
	}

	@Override
	public void setResult(IWatchExpressionResult result)
	{
		super.setResult(result);
	}
}


text:
package org.apache.asterix.runtime.evaluators.accessors;

import java.io.DataOutput;
import java.io.IOException;

import org.apache.asterix.dataflow.data.nontagged.serde.AIntervalSerializerDeserializer;
import org.apache.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import org.apache.asterix.om.base.AMutableTime;
import org.apache.asterix.om.base.ANull;
import org.apache.asterix.om.base.ATime;
import org.apache.asterix.om.functions.AsterixBuiltinFunctions;
import org.apache.asterix.om.functions.IFunctionDescriptor;
import org.apache.asterix.om.functions.IFunctionDescriptorFactory;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.asterix.om.types.EnumDeserializer;
import org.apache.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.data.std.api.IPointable;
import org.apache.hyracks.data.std.primitive.VoidPointable;
import org.apache.hyracks.data.std.util.ArrayBackedValueStorage;
import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference;

public class TemporalIntervalStartTimeAccessor extends AbstractScalarFunctionDynamicDescriptor {

    private static final long serialVersionUID = 1L;
    private static final FunctionIdentifier FID = AsterixBuiltinFunctions.ACCESSOR_TEMPORAL_INTERVAL_START_TIME;
    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {

        @Override
        public IFunctionDescriptor createFunctionDescriptor() {
            return new TemporalIntervalStartTimeAccessor();
        }
    };

    @Override
    public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args)
            throws AlgebricksException {
        return new IScalarEvaluatorFactory() {
            private static final long serialVersionUID = 1L;

            @Override
            public IScalarEvaluator createScalarEvaluator(IHyracksTaskContext ctx) throws AlgebricksException {
                return new IScalarEvaluator() {
                    private final ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage();
                    private final DataOutput out = resultStorage.getDataOutput();
                    private final IPointable argPtr = new VoidPointable();
                    private final IScalarEvaluator eval = args[0].createScalarEvaluator(ctx);

                    // possible output
                    @SuppressWarnings("unchecked")
                    private final ISerializerDeserializer<ATime> timeSerde = AqlSerializerDeserializerProvider.INSTANCE
                            .getSerializerDeserializer(BuiltinType.ATIME);
                    private final AMutableTime aTime = new AMutableTime(0);
                    @SuppressWarnings("unchecked")
                    private final ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
                            .getSerializerDeserializer(BuiltinType.ANULL);

                    @Override
                    public void evaluate(IFrameTupleReference tuple, IPointable result) throws AlgebricksException {
                        eval.evaluate(tuple, argPtr);
                        byte[] bytes = argPtr.getByteArray();
                        int startOffset = argPtr.getStartOffset();

                        resultStorage.reset();
                        try {
                            if (bytes[startOffset] == ATypeTag.SERIALIZED_NULL_TYPE_TAG) {
                                nullSerde.serialize(ANull.NULL, out);
                                result.set(resultStorage);
                                return;
                            } else if (bytes[startOffset] == ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG) {
                                byte timeType = AIntervalSerializerDeserializer.getIntervalTimeType(bytes,
                                        startOffset + 1);
                                long startTime = AIntervalSerializerDeserializer.getIntervalStart(bytes,
                                        startOffset + 1);
                                if (timeType == ATypeTag.SERIALIZED_TIME_TYPE_TAG) {
                                    aTime.setValue((int) (startTime));
                                    timeSerde.serialize(aTime, out);
                                } else {
                                    throw new AlgebricksException(FID.getName()
                                            + ": expects NULL/INTERVAL(of TIME), but got INTERVAL(of "
                                            + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(bytes[startOffset])
                                            + ")");
                                }
                            } else {
                                throw new AlgebricksException(FID.getName() + ": expects NULL/INTERVAL, but got "
                                        + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(bytes[startOffset]));
                            }
                        } catch (IOException e) {
                            throw new AlgebricksException(e);
                        }
                        result.set(resultStorage);
                    }
                };
            }
        };
    }

    /* (non-Javadoc)
     * @see org.apache.asterix.om.functions.AbstractFunctionDescriptor#getIdentifier()
     */
    @Override
    public FunctionIdentifier getIdentifier() {
        return FID;
    }

}


text:
A packaged collection of data meant to be transmitted to another entity. A token could be used for authorized access (an "access token"), or could be used to exchange information about a subject (a "claim token").

-- From UMA spec


text:
<?php

/*
|--------------------------------------------------------------------------
| Validation Language Lines
|--------------------------------------------------------------------------
|
| The following language lines contain the default error messages used by
| the validator class. Some of these rules have multiple versions such
| as the size rules. Feel free to tweak each of these messages here.
|
*/

return [
    'accepted'             => 'Полето :attribute мора да биде прифатено.',
    'accepted_if'          => 'The :attribute must be accepted when :other is :value.',
    'active_url'           => 'Полето :attribute не е валиден URL.',
    'after'                => 'Полето :attribute мора да биде датум после :date.',
    'after_or_equal'       => 'Полето :attribute мора да биде датум кој е после или еднаков на :date.',
    'alpha'                => 'Полето :attribute може да содржи само букви.',
    'alpha_dash'           => 'Полето :attribute може да содржи само букви, броеви, долна црта и тире.',
    'alpha_num'            => 'Полето :attribute може да содржи само букви и броеви.',
    'array'                => 'Полето :attribute мора да биде низа.',
    'before'               => 'Полето :attribute мора да биде датум пред :date.',
    'before_or_equal'      => 'Полето :attribute мора да биде датум пред или еднаков на :date.',
    'between'              => [
        'array'   => 'Полето :attribute мора да има помеѓу :min - :max елементи.',
        'file'    => 'Полето :attribute мора да биде датотека со големина помеѓу :min и :max килобајти.',
        'numeric' => 'Полето :attribute мора да биде број помеѓу :min и :max.',
        'string'  => 'Полето :attribute мора да биде текст со должина помеѓу :min и :max карактери.',
    ],
    'boolean'              => 'Полето :attribute мора да има вредност вистинито (true) или невистинито (false).',
    'confirmed'            => 'Полето :attribute не е потврдено.',
    'current_password'     => 'The password is incorrect.',
    'date'                 => 'Полето :attribute не е валиден датум.',
    'date_equals'          => 'Полето :attribute мора да биде датум еднаков на :date.',
    'date_format'          => 'Полето :attribute не одговара на форматот :format.',
    'declined'             => 'The :attribute must be declined.',
    'declined_if'          => 'The :attribute must be declined when :other is :value.',
    'different'            => 'Полињата :attribute и :other треба да се различни.',
    'digits'               => 'Полето :attribute треба да има :digits цифри.',
    'digits_between'       => 'Полето :attribute треба да има помеѓу :min и :max цифри.',
    'dimensions'           => 'Полето :attribute има невалидни димензии.',
    'distinct'             => 'Полето :attribute има вредност која е дупликат.',
    'email'                => 'Полето :attribute не е во валиден формат.',
    'ends_with'            => 'Полето :attribute мора да завршува со една од следните вредности: :values.',
    'enum'                 => 'The selected :attribute is invalid.',
    'exists'               => 'Полето :attribute има вредност која веќе постои.',
    'file'                 => 'Полето :attribute мора да биде датотека.',
    'filled'               => 'Полето :attribute мора да има вредност.',
    'gt'                   => [
        'array'   => 'Полето :attribute мора да има повеке од :value елементи.',
        'file'    => 'Полето :attribute мора да биде датотека поголема од :value килобајти.',
        'numeric' => 'Полето :attribute мора да биде број поголем од :value.',
        'string'  => 'Полето :attribute мора да биде текст со повеќе од :value карактери.',
    ],
    'gte'                  => [
        'array'   => 'Полето :attribute мора да има :value елементи или повеќе.',
        'file'    => 'Полето :attribute мора да биде датотека поголема или еднаква на :value килобајти.',
        'numeric' => 'Полето :attribute мора да биде број поголем или еднаков на :value.',
        'string'  => 'Полето :attribute мора да биде текст со повеќе или еднаков на :value број на карактери.',
    ],
    'image'                => 'Полето :attribute мора да биде слика.',
    'in'                   => 'Избраното поле :attribute е невалидно.',
    'in_array'             => 'Полето :attribute не содржи вредност која постои во :other.',
    'integer'              => 'Полето :attribute мора да биде цел број.',
    'ip'                   => 'Полето :attribute мора да биде валидна IP адреса.',
    'ipv4'                 => 'Полето :attribute мора да биде валидна IPv4 адреса.',
    'ipv6'                 => 'Полето :attribute мора да биде валидна IPv6 адреса.',
    'json'                 => 'Полето :attribute мора да биде валиден JSON објект.',
    'lt'                   => [
        'array'   => 'Полето :attribute мора да има помалку од :value елементи.',
        'file'    => 'Полето :attribute мора да биде датотека помала од :value килобајти.',
        'numeric' => 'Полето :attribute мора да биде број помал од :value.',
        'string'  => 'Полето :attribute мора да биде текст помал од :value број на карактери.',
    ],
    'lte'                  => [
        'array'   => 'Полето :attribute мора да има :value елементи или помалку.',
        'file'    => 'Полето :attribute мора да биде датотека помала или еднаква на :value килобајти.',
        'numeric' => 'Полето :attribute мора да биде број помал или еднаков на :value.',
        'string'  => 'Полето :attribute мора да биде текст со помалку или еднаков на :value број на карактери.',
    ],
    'mac_address'          => 'The :attribute must be a valid MAC address.',
    'max'                  => [
        'array'   => 'Полето :attribute не може да има повеќе од :max елементи.',
        'file'    => 'Полето :attribute мора да биде датотека не поголема од :max килобајти.',
        'numeric' => 'Полето :attribute мора да биде број не поголем од :max.',
        'string'  => 'Полето :attribute мора да има не повеќе од :max карактери.',
    ],
    'mimes'                => 'Полето :attribute мора да биде датотека од типот: :values.',
    'mimetypes'            => 'Полето :attribute мора да биде датотека од типот: :values.',
    'min'                  => [
        'array'   => 'Полето :attribute мора да има минимум :min елементи.',
        'file'    => 'Полето :attribute мора да биде датотека не помала од :min килобајти.',
        'numeric' => 'Полето :attribute мора да биде број не помал од :min.',
        'string'  => 'Полето :attribute мора да има не помалку од :min карактери.',
    ],
    'multiple_of'          => 'Полето :attribute мора да биде повеќекратна вредност од :value',
    'not_in'               => 'Избраното поле :attribute е невалидно.',
    'not_regex'            => 'Полето :attribute има невалиден формат.',
    'numeric'              => 'Полето :attribute мора да биде број.',
    'password'             => 'Лозинката не е точна.',
    'present'              => 'Полето :attribute мора да биде присутно.',
    'prohibited'           => 'Во :attribute година полето е забрането.',
    'prohibited_if'        => 'На :attribute поле е забрането кога :other е :value.',
    'prohibited_unless'    => 'На :attribute поле е забранета освен ако не :other е во :values.',
    'prohibits'            => 'The :attribute field prohibits :other from being present.',
    'regex'                => 'Полето :attribute има невалиден формат.',
    'required'             => 'Полето :attribute е задолжително.',
    'required_array_keys'  => 'The :attribute field must contain entries for: :values.',
    'required_if'          => 'Полето :attribute е задолжително кога :other е :value.',
    'required_unless'      => 'Полето :attribute е задолжително освен кога :other е во :values.',
    'required_with'        => 'Полето :attribute е задолжително кога е внесено :values.',
    'required_with_all'    => 'Полето :attribute е задолжително кога :values се присутни.',
    'required_without'     => 'Полето :attribute е задолжително кога не е присутно :values.',
    'required_without_all' => 'Полето :attribute е задолжително кога ниту една вредност од следните: :values се присутни.',
    'same'                 => 'Полињата :attribute и :other треба да совпаѓаат.',
    'size'                 => [
        'array'   => 'Полето :attribute мора да биде низа со :size број на елементи.',
        'file'    => 'Полето :attribute мора да биде датотека со големина од :size килобајти.',
        'numeric' => 'Полето :attribute мора да биде број со вредност :size.',
        'string'  => 'Полето :attribute мора да биде текст со должина од :size број на карактери.',
    ],
    'starts_with'          => 'Полето :attribute мора да започнува со една од следните вредности: :values.',
    'string'               => 'Полето :attribute мора да биде текст.',
    'timezone'             => 'Полето :attribute мора да биде валидна временска зона.',
    'unique'               => 'Полето :attribute веќе постои.',
    'uploaded'             => ':attribute не е прикачен.',
    'url'                  => 'Полето :attribute не е во валиден формат.',
    'uuid'                 => 'Полето :attribute мора да биде валиден УУИД.',
    'custom'               => [
        'attribute-name' => [
            'rule-name' => 'custom-message',
        ],
    ],
];


text:
class Fluentd
  module Setting
    class InSyslog
      include Fluentd::Setting::Plugin

      register_plugin("input", "syslog")

      def self.initial_params
        params = {
          parse_type: "syslog",
          parse: {
            "0" => {
              "type" => "syslog"
            }
          }
        }
        super.compact.deep_merge(params)
      end

      def common_options
        [
          :label, :tag, :bind, :port
        ]
      end

      def hidden_options
        [
          :parse,
          :transport,
          :blocking_timeout
        ]
      end
    end
  end
end


text:
require_relative 'model'
require 'csv'

selectorr = Record.where(version: 38)

needles = selectorr

puts "#{selectorr.count} records in total"
selectorr.where(run_time: nil).each do |record|
begin
  record.run_time = record.result.scan(/elapsed time: (.*)$/).first.first.to_f
  record.save!
rescue
  puts record.result
  puts record.command
end
end

selectorr.where(collision_status: nil).each do |record|
#selectorr.each do |record|
  record.collision_status = eval(record.result.scan(/collision status: (.*)$/).first.first)
  record.save!
end

selectorr.where(distance_to_goals: nil).each do |record|
#selectorr.each do |record|
  record.distance_to_goals = eval(record.result.scan(/distance to goals: (.*)$/).first.first)
  record.save!

end

#needles.where(collision_free_cnt: nil).each do |record|
#  record.collision_free_cnt = record.result.scan(/is not in collision/).count
#  record.save!
#end
#
#needles.where(collision_free_dis: nil).each do |record|
#  record.collision_free_dis = record.result.scan(/is not in collision. The distance to goal is (\d+\.\d+)/).map{|x| x.first.to_f}
#  record.save!
#end

#CSV.open("results_30.csv", "w") do |csv|
#  csv << %w[pg_name method separate_planning_first simultaneous_planning average_collision_free_count average_collision_free_distance_to_goal average_run_time]
runtime =[]
succnt= []
dists = []

#needles.pluck(:start_position_error_relax_x).uniq.sort.each do |start_position_error_relax_x|
  needles.pluck(:pg_name).uniq.each do |pg_name|
    [1, 2].each do |method|
      [[0, 1], [1, 0]].each do |separate_planning_first, simultaneous_planning|
        range = {
          pg_name: pg_name,
          method: method,
          separate_planning_first: separate_planning_first,
          simultaneous_planning: simultaneous_planning,
          #start_position_error_relax_x: start_position_error_relax_x,#start_orientation_error_relax: start_orientation_error_relax,
        }
        puts range
        cnt = needles.where(range).count
        puts needles.where(range).pluck(:collision_status).map(&:sum)
        collision_free_cnt = needles.where(range).pluck(:collision_status).map(&:sum).select{|x| x==0}.count#where(converged:true).count
        distance_to_goals = needles.where(range).where(collision_status: [0]).pluck(:distance_to_goals).map(&:sum).sum
        #total_collision_free_cnt = needles.where(range).pluck(:collision_free_cnt).sum
        #total_collision_free_dis = needles.where(range).pluck(:collision_free_dis).flatten(1).sum
        total_run_time = needles.where(range).pluck(:run_time).sum
        #puts "avg collision free cnt: #{total_collision_free_cnt * 1.0 / cnt}"
        #puts "avg collision free dis: #{total_collision_free_dis * 1.0 / total_collision_free_cnt}"
        #puts "avg run time: #{total_run_time * 1.0 / cnt}"
        puts "avg run time: #{(total_run_time*1.0/cnt).round(3)}"
        puts "avg collision free cnt: #{(collision_free_cnt*1.0/cnt).round(3)}"
        puts "avg distance to goals: #{(distance_to_goals*1.0/cnt).round(3)}"
        runtime << (total_run_time*1.0/cnt).round(3)
        succnt << (collision_free_cnt*1.0/cnt).round(3)
        dists << (distance_to_goals*1.0/cnt).round(3)

        #csv << [pg_name, method, separate_planning_first, simultaneous_planning, total_collision_free_cnt * 1.0 / cnt,
        #  total_collision_free_dis * 1.0 / total_collision_free_cnt,
        #  total_run_time * 1.0 / cnt
        #]
      end
    end
  end
puts runtime.join("&")
puts succnt.map{|x| "#{(x*100).round(3)}\\%"}.join("&")
puts dists.join("&")

#  csv << %w[pg_name method separate_planning_first simultaneous_planning converged_percentage average_run_time]
#  channels.pluck(:pg_name).uniq.each do |pg_name|
#    [1, 2].each do |method|
#      [[1, 0]].each do |separate_planning_first, simultaneous_planning|
#        range = {
#          pg_name: pg_name,
#          method: method,
#          separate_planning_first: separate_planning_first,
#          simultaneous_planning: simultaneous_planning,
#        }
#        cnt = channels.where(range).count
#        total_converged_cnt = channels.where(range).where(converged: true).count
#        total_run_time = channels.where(range).pluck(:run_time).sum
#        #puts range.inspect
#        #puts "converged percentage: #{total_converged_cnt * 1.0 / cnt}"
#        #puts "avg run time: #{total_run_time * 1.0 / cnt}"
#        csv << [pg_name, method, separate_planning_first, simultaneous_planning, total_converged_cnt * 1.0 / cnt,
#          total_run_time * 1.0 / cnt
#        ]
#      end
#    end
#  end

#end


text:
layout: post
title: maya2katana
tags: [katana, python, maya]
categories:
- blog
---
# maya2katana
Easily copy shading nodes from [Maya](http://www.autodesk.com/products/maya/overview) to [Katana](https://www.foundry.com/products/katana)

### Currently supported nodes ([Arnold](https://www.solidangle.com/arnold/) with [alShaders](http://www.anderslanglands.com/alshaders/index.html)):
- aiAmbientOcclusion
- aiImage
- aiNoise
- aiStandard
- aiUserDataColor
- aiUserDataFloat
- aiVolumeCollector
- alCellNoise
- alCombineColor
- alCombineFloat
- alCurvature
- alFlake
- alFlowNoise
- alFractal
- alHair
- alInputScalar
- alInputVector
- alJitterColor
- alLayer
- alLayerColor
- alLayerFloat
- alRemapColor
- alRemapFloat
- alSurface
- alSwitchColor
- alSwitchFloat
- alTriplanar
- blendColors
- bump2d
- clamp
- luminance
- ramp
- samplerInfo

### Installation
1. Quit Maya
2. Clone maya2katana repository (or download zip, extract and rename directory from "maya2katana-master" to "maya2katana") and place it to:
```
Windows: \Users\<username>\Documents\maya\scripts
Linux: ~/maya/scripts
```
3. Open Script Editor and paste the following code to Python tab:
```
from maya2katana import clip
reload (clip)
clip.copy()
```
4. To create a shelf button select the code and middle-mouse-drag it to your shelf

### Usage
1. Select a shading network or a single shadingEngine (Shading Group) node
![Maya shading network](https://github.com/ababak/maya2katana/blob/master/doc/maya.jpg)
2. Press the button you've created earlier or execute a script (see installation step)
3. Switch to Katana and paste the nodes
![Resulting Katana shading network](https://github.com/ababak/maya2katana/blob/master/doc/katana.jpg)

 MAYA2KATANA [Github](https://github.com/ababak/maya2katana)


text:
(function(window)
{

	window.dskblogControllers=angular.module('dskblogControllers', []);

}
)(window);


text:
layout: doc_page
---
# Search Queries
A search query returns dimension values that match the search specification.

```json
{
  "queryType": "search",
  "dataSource": "sample_datasource",
  "granularity": "day",
  "searchDimensions": [
    "dim1",
    "dim2"
  ],
  "query": {
    "type": "insensitive_contains",
    "value": "Ke"
  },
  "sort" : {
    "type": "lexicographic"
  },
  "intervals": [
    "2013-01-01T00:00:00.000/2013-01-03T00:00:00.000"
  ]
}
```

There are several main parts to a search query:

|property|description|required?|
|--------|-----------|---------|
|queryType|This String should always be "search"; this is the first thing Druid looks at to figure out how to interpret the query.|yes|
|dataSource|A String defining the data source to query, very similar to a table in a relational database.|yes|
|granularity|Defines the granularity of the query. See [Granularities](Granularities.html).|yes|
|filter|See [Filters](Filters.html).|no|
|intervals|A JSON Object representing ISO-8601 Intervals. This defines the time ranges to run the query over.|yes|
|searchDimensions|The dimensions to run the search over. Excluding this means the search is run over all dimensions.|no|
|query|See [SearchQuerySpec](SearchQuerySpec.html).|yes|
|sort|An object specifying how the results of the search should be sorted. Two possible types here are "lexicographic" (the default sort) and "strlen".|no|
|context|An additional JSON Object which can be used to specify certain flags.|no|

The format of the result is:

```json
[
  {
    "timestamp": "2012-01-01T00:00:00.000Z",
    "result": [
      {
        "dimension": "dim1",
        "value": "Ke$ha"
      },
      {
        "dimension": "dim2",
        "value": "Ke$haForPresident"
      }
    ]
  },
  {
    "timestamp": "2012-01-02T00:00:00.000Z",
    "result": [
      {
        "dimension": "dim1",
        "value": "SomethingThatContainsKe"
      },
      {
        "dimension": "dim2",
        "value": "SomethingElseThatContainsKe"
      }
    ]
  }
]
```


text:
let { Matrix, Vector } = require('../build/matrix');
let { Network } = require('../build/main');

//new Matrix
let a = new Matrix();
let b = new Matrix(2,2,[1,2,3,4]);
console.log('Matrix creation', a, b);

//Error thrown
try {
    let errorMat1 = new Matrix(2,3,[1,2,3,4,5]);
} catch (err){
    console.log('Matrix creation exception', err);
}

//Transpose
let trans = new Matrix(2,3,[1,2,3,4,5,6]);
let transposed = trans.transpose();
console.log('Pretransposed Matrix', trans);
console.log('Transposed Matrix', transposed);

//Dot matrix
let dotMatrix = new Matrix(2,2,[1,2,3,4]);
let resultDotM = dotMatrix.dotMat(dotMatrix);
console.log('Matrix multiplication', resultDotM);

//Add vectors
let vadd1 = new Vector([1,2]);
let vadd2 = new Vector([2,3]);
let addV12 = vadd1.add(vadd2);
console.log('Add vectors', addV12);

//Norm
console.log('Norm of previous vects', vadd1.norm);
console.log('Norm of previous vects', vadd2.norm);
console.log('Norm 1 ', new Vector([1/1.4142, 1/1.4142]).norm);

//dot product
let v1 = new Vector([1,1]);
let cross = v1.dot(v1);
console.log('Dot vectors', cross);

//Hadamard product
let vh1 = new Vector([2,3]);
let vh2 = new Vector([4,5]);
let hadamard = vh1.hadamard(vh2);
console.log('Hadamard vectors', hadamard);

let m1 = new Matrix(2,2,[1,1,1,1]);
cross = m1.dot(v1);
console.log('Dot matrix & vector', cross);

//Build network
let net1 = new Network(2, 3, 3);
let dataFeed = [1,1];
let dataOut = net1.forward(dataFeed);
console.log('Random network out', dataOut);
console.log('chromosome', net1.chromosome);

let net2 = new Network(3, 1, 6, [12, 4]);
let dataFeed2 = [1,1,-3];
let dataOut2 = net2.forward(dataFeed2);
console.log('Random complex network out', dataOut2);
console.log('chromosome', net2.chromosome);

let net3 = new Network(12, 1);
let dataFeed3 = [1, 1, -3,
                0, 4, 5,
                1, -5, 6,
                3, -4, 0];
let dataOut3 = net3.forward(dataFeed3);
console.log('Random single perceptron', dataOut3);
console.log('chromosome', net3.chromosome);

//Rebuild from chromosome
let chrom1 = net1.chromosome;
let net1Bis = new Network(2, 3, 3, [], chrom1);
let dataOut1Bis = net1Bis.forward(dataFeed);
console.log('Reproduce network 1', dataOut1Bis);

//Backpropagate a single sample
let netBack1 = new Network(2, 3, 3);
let backIn = [1,2];
let backOut = [0.5, 0.1, 0.3];
let outBack1 = netBack1.forward(backIn);
let error1 = netBack1.backpropagate(backIn, backOut);
console.log('Backpropagate one sample', outBack1, error1);

//Learn batch
let samples = [
    [[1,0],[0,0,1]],
    [[0,1],[1,0,0]],
    [[-1,-1],[0,1,0]]
];
let netToTrain = new Network(2, 3);
console.log('Net to train\'s chromosomes', netToTrain.chromosome);
console.log('Net to train\'s result on 1', netToTrain.forward([1,0]));
netToTrain.learnBatch(samples, 1, 1000);
console.log('Net to train\'s chromosomes after train', netToTrain.chromosome);
console.log('Net to train\'s result on 1 after train', netToTrain.forward([1,0]));
console.log('Net to train\'s result on 2 after train', netToTrain.forward([0,1]));
console.log('Net to train\'s result on 3 after train', netToTrain.forward([-1,-1]));


text:
namespace NServiceBus.AcceptanceTests.Performance.TimeToBeReceived
{
    using System;
    using System.Threading.Tasks;
    using AcceptanceTesting;
    using EndpointTemplates;
    using Features;
    using NUnit.Framework;

    public class When_TimeToBeReceived_used_with_unobtrusive_mode : NServiceBusAcceptanceTest
    {
        [Test]
        public async Task Message_should_not_be_received()
        {
            var context = await Scenario.Define<Context>()
                .WithEndpoint<Sender>()
                .WithEndpoint<Receiver>()
                .Run(TimeSpan.FromSeconds(10));

            Assert.IsFalse(context.WasCalled);
        }

        public class Context : ScenarioContext
        {
            public bool WasCalled { get; set; }
        }

        class SendMessageWhileStarting : Feature
        {
            protected override void Setup(FeatureConfigurationContext context)
            {
                context.RegisterStartupTask(b => new SendMessageWhileStartingTask());
            }
        }

        class SendMessageWhileStartingTask : FeatureStartupTask
        {
            protected override Task OnStart(IMessageSession session)
            {
                return session.Send(new MyCommand());
            }

            protected override Task OnStop(IMessageSession session)
            {
                return Task.FromResult(0);
            }
        }

        public class Sender : EndpointConfigurationBuilder
        {
            public Sender()
            {
                EndpointSetup<DefaultServer>(c =>
                {
                    c.Conventions()
                    .DefiningCommandsAs(t => t.Namespace != null && t.FullName == typeof(MyCommand).FullName)
                    .DefiningTimeToBeReceivedAs(messageType =>
                    {
                        if (messageType == typeof(MyCommand))
                        {
                            return TimeSpan.FromSeconds(2);
                        }
                        return TimeSpan.MaxValue;
                    });
                    c.EnableFeature<SendMessageWhileStarting>();
                }).AddMapping<MyCommand>(typeof(Receiver))
                .ExcludeType<MyCommand>(); // remove that type from assembly scanning to simulate what would happen with true unobtrusive mode
            }
        }

        class DelayReceiverFromStarting : Feature
        {
            protected override void Setup(FeatureConfigurationContext context)
            {
                context.RegisterStartupTask(b => new DelayReceiverFromStartingTask());
            }
        }

        class DelayReceiverFromStartingTask : FeatureStartupTask
        {
            protected override Task OnStart(IMessageSession session)
            {
                return Task.Delay(TimeSpan.FromSeconds(5));
            }

            protected override Task OnStop(IMessageSession session)
            {
                return Task.FromResult(0);
            }
        }

        public class Receiver : EndpointConfigurationBuilder
        {
            public Receiver()
            {
                EndpointSetup<DefaultServer>(c =>
                {
                    c.Conventions().DefiningCommandsAs(t => t.Namespace != null && t.FullName == typeof(MyCommand).FullName);
                    c.EnableFeature<DelayReceiverFromStarting>();
                });
            }

            public class MyMessageHandler : IHandleMessages<MyCommand>
            {
                public Context Context { get; set; }

                public Task Handle(MyCommand message, IMessageHandlerContext context)
                {
                    Context.WasCalled = true;
                    return Task.FromResult(0);
                }
            }
        }

        public class MyCommand
        {
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <link href='http://fonts.googleapis.com/css?family=Oswald:400,700' rel='stylesheet' type='text/css'>

        <link rel="stylesheet" type="text/css" href="style.css">
        <link rel="icon" type="image/png" href="favicon.png">
        <title>
            Installation
        </title>

                    Welcome to the GCentrix Installation Assistant

                    Press Start in order to initiate the installation process

                    Please enter the database to use with GCentrix

                        Server Address

                    <input type="text" name="Server" value="" />

                        Database Port

                    <input type="text" name="Port" value="" />

                        Database Name

                    <input type="text" name="Database" value="" />

                    please make sure you have PostgreSQL up and running. For the installation it is necessary for you to have one empty database to use exclusively for the GCentrix Database Manager

                    Please enter name and password of the PostgreSQL user

                        User Name

                    <input type="text" name="User" value="" />

                        User Password

                    <input type="password" name="Password" value="" />

                    Keep in mind that this user has to have most privileges in the specified database, because all GCentrix Queries will be sent through this user

                    When you press finish GCentrix will try to create the necessary demo data for your database and create cache files for performance reasons. This should take less than a minute

                <button id="Control" type="Button" id="Previous" class="GreyedOut" disabled>Previous</button>
                <button id="Control" type="Button" id="Next">Start</button>

                <?php
                echo "<button class=\"ProgressBar Active\" id=\"ProgressBar1\">Step 1
";
                for($Counter = 2; $Counter < ($NumberOfInitSteps + 1); $Counter++) {
                    echo "<button class=\"ProgressBar Todo\" id=\"ProgressBar$Counter\">Step $Counter
";
                }
                ?>


text:
dotJEM Angular Routing [![Build Status](https://travis-ci.org/dotJEM/angular-routing.png?branch=master)](https://travis-ci.org/dotJEM/angular-routing)
=========

#### Latest release v0.6.15:
 - Source: [angular-routing.js](https://raw.github.com/dotJEM/angular-routing/v0.6.15/build/angular-routing.js)
 - Minified: [angular-routing.min.js](https://raw.github.com/dotJEM/angular-routing/v0.6.15/build/angular-routing.min.js)
 - Folder: [Build](https://github.com/dotJEM/angular-routing/tree/v0.6.15/build)

#### Latest build (currently not automated, so not 100% the latest always):
 - Source: [angular-routing.js](https://raw.github.com/dotJEM/angular-routing/master/build/angular-routing.js)
 - Minified: [angular-routing.min.js](https://raw.github.com/dotJEM/angular-routing/master/build/angular-routing.min.js)
 - Folder: [Build](https://github.com/dotJEM/angular-routing/tree/master/build)

The samples and api reference are currently a work in progress:
 - **Api Reference:** http://dotjem.github.io/angular-routing/#/docs/api/dotjem.routing
 - **Samples:** http://dotjem.github.io/angular-routing/

# Briefly

Inspired by the UI-Router project by Angular-UI, this project came to life as I wanted
to provide what I believe is more "true states" where the transitions could be
an important part of the implementation.

The UI-Route project can be found here: https://github.com/angular-ui/ui-router

One important note is that this is developed using TypeScript, yet following the
basic style of how Angular modules, services and directives is written.

## Main goal

The goal is to provide a routing concept for Angular that provides a way to
separate views into tiers so that we don't always have to reload the entire main view.

Also I want it to support a variety of page designs, where different types of navigations
take place.

## Features

* `$routeProvider` and `$route` to replace the existing angular routing concept.
* `$stateProvider` and `$state` to manage application states.
* `$stateTransitionProvider` to manage state transitions.
* `$viewProvider` and `$view` to manage view state.
* `jem-view` directive as a replacement for `ng-view`
* `$scroll` and `jem-anchor` directive for scrolling

#### $routeProvider and $route

Through the $routeProvider and $route, backwards compatibility can be obtained
by registering decoraters, this project comes with a module that provides just that.

Aditionally a new concept for parameters is introduced, providing the flexibility to
match and convert parameters only if they are numeric, patterns etc. Furthermore, the ability
to extend on this concept by registering new converters or overwriting existing ones.

By default `num` and `regex` are available.

Also providing the abilty to switch to a case insensitive mode.

#### $stateProvider and $state

Provides the means to define application states with views, controllers and more.

`$stateProvider` will register routes with the `$routeProvider` if a `route` property
is specified on the state, which is really just a short-hand to registering that route
manually.

It can also register specific transitions through the onEnter and onExit properties.

#### $stateTransitionProvider

Allows the configuration of extra behavior or the ability to change the flow of existing states
by registering handlers in great many ways using wildcards, arrays and special `{before, between, after}` handlers
that give a more granulated control over when a handler is called.

Through depending on `$transition`, `$from` and `$to` a transition handler can reject, redirect
or modify what happens during a transition.

#### $viewProvider and $view

`$view` manages the current state of all views and will support different update schemes.

#### Requires

* AngularJS 1.2

## Reporting Issues

When encountering issues and posting them under issues here on github, if possible, it will be much apreciated
if an example is to follow, it would be especially usefull if the issue was recreated using either
http://plnkr.co/ or http://jsfiddle.net/.

Otherwise, try to capture as much detail as possible, the more that is known about the issue and context
the easier it is to help.

Here is a template Plunker that can be used: http://plnkr.co/edit/tpl:Q2P6M278icUckKNmZJ7C


text:
<?php /* Smarty version 2.6.27, created on 2014-04-08 18:56:04
         compiled from sk_admin/index.tpl */ ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<frameset rows="100,*" frameborder="no" border="0" framespacing="0" onkeydown="if(event.keyCode==116) { mainFrame.location.reload();event.returnValue=false; }">
  <frame src="<?php echo $this->_tpl_vars['admin_path']; ?>
/dashboard/top" name="topframe" scrolling="No" id="topframe" title="topframe" />
  <frameset id="mainframeset" cols="205,*" frameborder="no" border="0" framespacing="0">
    <frame src="<?php echo $this->_tpl_vars['admin_path']; ?>
/dashboard/menu" name="leftframe" scrolling="Yes" noresize="noresize" id="leftframe" title="leftframe" />
    <frame src="" name="mainframe" id="mainframe" title="mainframe" />

  </frameset>
</frameset><noframes></noframes>
<noframes>
</head>
<body>
</body>
</html>