text:
angular.module('Storyboard').directive('modal', function(){
	return {
		restrict: 'E',
		transclude: true,
		templateUrl: 'templates/modal.html',
		scope: {
			title: '@',
			modalid: '@'
		},
		link: function(scope, element, attrs){
			scope.title = attrs.title;
			scope.modalId = attrs.modalid;
		}
	};
});


text:
package org.apache.camel.component.as2.api.util;

import org.apache.camel.component.as2.api.AS2CompressionAlgorithm;
import org.bouncycastle.cms.CMSCompressedDataGenerator;
import org.bouncycastle.operator.OutputCompressor;

public final class CompressionUtils {

    private CompressionUtils() {
    }

    public static CMSCompressedDataGenerator createCompressedDataGenerator() {
        return new CMSCompressedDataGenerator();
    }

    public static OutputCompressor createCompressor(AS2CompressionAlgorithm compressionAlgorithm) {
        return compressionAlgorithm.getOutputCompressor();
    }

}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <version>0.1.0</version>
    <packaging>jar</packaging>
    <artifactId>rating-microservice</artifactId>

    <parent>
        <groupId>org.kbastani</groupId>
        <artifactId>spring-cloud-microservice-example-parent</artifactId>
        <version>0.1.0-SNAPSHOT</version>
    </parent>

    <properties>
        <docker.image.prefix>kbastani</docker.image.prefix>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-neo4j</artifactId>
            <version>3.4.0.RC1</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-neo4j-rest</artifactId>
            <version>3.3.0.M1</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>com.spotify</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.2.3</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>build</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <imageName>${docker.image.prefix}/${project.artifactId}</imageName>
                    <dockerDirectory>${project.basedir}/src/main/docker</dockerDirectory>
                    <resources>
                        <resource>
                            <targetPath>/</targetPath>
                            <directory>${project.build.directory}</directory>
                            <include>${project.build.finalName}.jar</include>
                        </resource>
                    </resources>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>http://repo.spring.io/libs-release-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>http://repo.spring.io/libs-snapshot-local</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>http://repo.spring.io/libs-milestone-local</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
</project>


text:
#import "ABKInAppMessageViewController.h"
#import "ABKInAppMessageUIButton.h"

// Customize this to set the font for the in-app message header.
#define HeaderLabelDefaultFont [UIFont boldSystemFontOfSize:20.0]

NS_ASSUME_NONNULL_BEGIN
@interface ABKInAppMessageImmersiveViewController : ABKInAppMessageViewController

/*!
 * The UILabel for the in-app message header.
 */
@property (weak, nonatomic) IBOutlet UILabel *inAppMessageHeaderLabel;

/*!
 * The UIImageView for the in-app message image.
 */
@property (weak, nonatomic, nullable) IBOutlet UIImageView *graphicImageView;

/*!
 * The NSLayoutConstraint that specifies the space between the header and rest of the in-app message.
 */
@property (nonatomic) IBOutlet NSLayoutConstraint *headerBodySpaceConstraint;

/*!
 * The UIButton on the left of the in-app message.
 * When there is only one button in the in-app message, this left button is the one that is used.
 */
@property (retain, nonatomic, nullable) IBOutlet ABKInAppMessageUIButton *leftInAppMessageButton;

/*!
 * The UIButton on the right of the in-app message.
 */
@property (retain, nonatomic, nullable) IBOutlet ABKInAppMessageUIButton *rightInAppMessageButton;

/*!
 * The UIScrollView for the message of the in-app message.
 */
@property (nonatomic, nullable) IBOutlet UIScrollView *textsView;

/*!
 * @discussion This method is used for setting up the layout for ABKInAppMessageGraphic image style.
 *
 * For customization, please use a subclass or category to override this method.
 */
- (void)setupLayoutForGraphic;

/*!
 * @discussion This method is used for setting up the layout for ABKInAppMessageTopImage image style.
 *
 * For customization, please use a subclass or category to override this method.
 */
- (void)setupLayoutForTopImage;

/*!
 * @discussion This method is used for setting the color of the close button.
 *
 * For customization, please use a subclass or category to override this method.
 */
- (void)changeCloseButtonColor;

/*!
 * @discussion The touch up inside action for the close button. The default behavior is to close the
 *             in-app message.
 *
 * For customization, please use a subclass or category to override this method.
 */
- (IBAction)dismissInAppMessage:(id)sender;

/*!
 * @discussion The touch up inside action for the in-app message buttons.
 *
 * For customization, please use a subclass or category to override this method.
 */
- (IBAction)buttonClicked:(ABKInAppMessageUIButton *)button;

@end
NS_ASSUME_NONNULL_END


text:
#ifndef XSIMD_BASE_CONSTANT_HPP
#define XSIMD_BASE_CONSTANT_HPP

namespace xsimd
{
    template <class X>
    class simd_base;

    template <class T, bool... Values>
    struct batch_bool_constant
    {
        static constexpr std::size_t size = sizeof...(Values);
        using value_type = bool;
        using batch_type =
            typename simd_batch_traits<batch<T, size>>::batch_bool_type;

        batch_type operator()() const { return *this; }

        operator batch_type() const { return {Values...}; }

        bool operator[](size_t i) const
        {
            return std::array<value_type, size>{{Values...}}[i];
        }
        static constexpr int mask()
        {
            return mask_helper(0, static_cast<int>(Values)...);
        }

      private:
        static constexpr int mask_helper(int acc) { return acc; }
        template <class... Tys>
        static constexpr int mask_helper(int acc, int mask, Tys... masks)
        {
            return mask_helper(acc | mask, (masks << 1)...);
        }
    };

    template <class T, T... Values>
    struct batch_constant
    {
        static constexpr std::size_t size = sizeof...(Values);
        using value_type = T;
        using batch_type = batch<T, size>;

        batch_type operator()() const { return *this; }

        operator batch_type() const { return {Values...}; }

        constexpr T operator[](size_t i) const
        {
            return std::array<value_type, size>{Values...}[i];
        }
    };

    namespace detail
    {
        template <class G, std::size_t... Is>
        constexpr auto make_batch_constant(detail::index_sequence<Is...>)
            -> batch_constant<decltype(G::get(0, 0)),
                              G::get(Is, sizeof...(Is))...>
        {
            return {};
        }
        template <class T, class G, std::size_t... Is>
        constexpr auto make_batch_bool_constant(detail::index_sequence<Is...>)
            -> batch_bool_constant<T, G::get(Is, sizeof...(Is))...>
        {
            return {};
        }
        template <class T, T value, std::size_t... Is>
        constexpr auto make_batch_constant(detail::index_sequence<Is...>)
            -> batch_constant<T, (Is, value)...>
        {
            return {};
        }
        template <class T, T value, std::size_t... Is>
        constexpr auto make_batch_bool_constant(detail::index_sequence<Is...>)
            -> batch_bool_constant<T, (Is, value)...>
        {
            return {};
        }
    } // namespace detail

    template <class G, std::size_t N>
    constexpr auto make_batch_constant() -> decltype(
        detail::make_batch_constant<G>(detail::make_index_sequence<N>()))
    {
        return detail::make_batch_constant<G>(detail::make_index_sequence<N>());
    }

    template <class T, class G, std::size_t N>
    constexpr auto make_batch_bool_constant()
        -> decltype(detail::make_batch_bool_constant<T, G>(
            detail::make_index_sequence<N>()))
    {
        return detail::make_batch_bool_constant<T, G>(
            detail::make_index_sequence<N>());
    }

} // namespace xsimd

#endif


text:
package org.dcm4chee.usr.dao;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.ejb.PostActivate;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import net.sf.json.JSONObject;

import org.dcm4chee.usr.entity.User;
import org.dcm4chee.usr.entity.UserRoleAssignment;
import org.dcm4chee.usr.model.AETGroup;
import org.dcm4chee.usr.model.Group;
import org.dcm4chee.usr.model.Role;
import org.jboss.annotation.ejb.LocalBinding;
import org.jboss.system.server.ServerConfigLocator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Robert David <robert.david@agfa.com>
 * @version $Revision$ $Date$
 * @since 19.08.2009
 */
@Stateless
@LocalBinding(jndiBinding=UserAccess.JNDI_NAME)
public class UserAccessBean implements UserAccess {

    private static Logger log = LoggerFactory.getLogger(UserAccessBean.class);

    @PersistenceContext(unitName="dcm4chee-usr")
    private EntityManager em;

    private File rolesMappingFile;
    private File groupsFile;
    private File aetGroupsFile;
    private String userRoleName;
    private String adminRoleName;
    private boolean ensureUserAndAdminRole;

    @PostConstruct
    @PostActivate
    private void config() {
        if (this.rolesMappingFile == null) {
            userRoleName = System.getProperty("dcm4chee-usr.cfg.userrole", "+WebUser");
            adminRoleName = System.getProperty("dcm4chee-usr.cfg.adminrole", "+WebAdmin");
            rolesMappingFile = new File(System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3") + "roles.json");
            if (!rolesMappingFile.isAbsolute())
                rolesMappingFile = new File(ServerConfigLocator.locate().getServerHomeDir(), rolesMappingFile.getPath());
            if (log.isDebugEnabled()) {
                log.debug("UserAccess configuration:\nuserRoleName:"+userRoleName);
                log.debug("adminRoleName:"+adminRoleName);
                log.debug("ensureUserAndAdminRole:"+ensureUserAndAdminRole);
                log.debug("mappingFile:"+rolesMappingFile);
            }
            if (!rolesMappingFile.exists()) {
                try {
                    if (rolesMappingFile.getParentFile().mkdirs())
                        log.info("M-WRITE dir:" +rolesMappingFile.getParent());
                    rolesMappingFile.createNewFile();
                } catch (IOException e) {
                    log.error("RolesMapping file doesn't exist and can't be created!", e);
                }
            }
        }
        this.groupsFile = checkFile(this.groupsFile, "groups.json");
        this.aetGroupsFile = checkFile(this.aetGroupsFile, "aet-groups.json");
        List<Role> roles = null;
        if (userRoleName.charAt(0)=='+') {
            userRoleName = userRoleName.substring(1);
            roles = getAllRoles();
            Role userRole = new Role(userRoleName);
            if (!roles.contains(userRole)) {
                addRole(userRole);
                roles.add(userRole);
            }
        }
        if (adminRoleName.charAt(0)=='+') {
            adminRoleName = adminRoleName.substring(1);
            Role adminRole = new Role(adminRoleName);
            if ( roles == null)
                roles = getAllRoles();
            if (!roles.contains(adminRole)) {
                addRole(adminRole);
            }
        }
    }

    private File checkFile(File file, String jsonFilename) {
        if (file == null) {
            file = new File(System.getProperty("dcm4chee-web3.cfg.path", "conf/dcm4chee-web3") + jsonFilename);
            if (!file.isAbsolute())
                file = new File(ServerConfigLocator.locate().getServerHomeDir(), file.getPath());
            if (log.isDebugEnabled()) {
                log.debug(jsonFilename + ":" + file);
            }
            if (!file.exists()) {
                try {
                    if (file.getParentFile().mkdirs())
                        log.info("M-WRITE dir:" + file.getParent());
                    file.createNewFile();
                } catch (IOException e) {
                    log.error(jsonFilename + " file doesn't exist and can't be created!", e);
                }
            }
        }
        return file;
    }

    public String getUserRoleName() {
        return userRoleName;
    }

    public String getAdminRoleName() {
        return adminRoleName;
    }

    // TODO: change this to generic version using JPA 2.0 implementation
    @SuppressWarnings("unchecked")
    public List<User> getAllUsers() {
        return this.em.createQuery("SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles ORDER BY u.userID")
            .getResultList();
    }

    public User getUser(String userId) {
    	return (User)
    			this.em.createQuery("SELECT DISTINCT u FROM User u LEFT JOIN FETCH u.roles r WHERE u.userID = :userID")
                .setParameter("userID", userId)
                .getSingleResult();
    }

    public User getUserIgnoreCase(String userId) {
        return (User)
            this.em.createQuery("SELECT DISTINCT u FROM User u WHERE UPPER(u.userID) = UPPER(:userID)")
            .setParameter("userID", userId)
            .getSingleResult();
    }

    public void createUser(User user) {
        this.em.persist(user);
    }

    public void updateUser(String userId, String password) {
        User managedUser = this.em.find(User.class, userId);
        managedUser.setPassword(password);
    }

    public void deleteUser(String userId) {
        this.em.createQuery("DELETE FROM UserRoleAssignment ura WHERE ura.userID = :userID")
        .setParameter("userID", userId)
        .executeUpdate();
        this.em.createQuery("DELETE FROM User u WHERE u.userID = :userID")
        .setParameter("userID", userId)
        .executeUpdate();
    }

    public Boolean userExists(String username) {
        try {
            this.em.createQuery("SELECT DISTINCT u FROM User u WHERE u.userID = :userID")
            .setParameter("userID", username)
            .getSingleResult();
            return true;
        } catch (NoResultException nre) {
            return false;
        }
    }

    public Boolean hasPassword(String username, String password) {
        try {
            this.em.createQuery("SELECT DISTINCT u FROM User u WHERE u.userID = :userID AND u.password = :password")
            .setParameter("userID", username)
            .setParameter("password", password)
            .getSingleResult();
            return true;
        } catch (NoResultException nre) {
            return false;
        }
    }

    public void assignRole(UserRoleAssignment ura) {
        this.em.persist(ura);
    }

    public void unassignRole(UserRoleAssignment ura) {
        this.em.createQuery("DELETE FROM UserRoleAssignment ura WHERE ura.userID = :userID AND ura.role = :rolename")
        .setParameter("userID", ura.getUserID())
        .setParameter("rolename", ura.getRole())
        .executeUpdate();
    }

    public List<Role> getAllRoles() {
        BufferedReader reader = null;
        try {
            List<Role> roleList = new ArrayList<Role>();
            String line;
            reader = new BufferedReader(new FileReader(rolesMappingFile));
            while ((line = reader.readLine()) != null)
                roleList.add((Role) JSONObject.toBean(JSONObject.fromObject(line), Role.class));

            final List<Group> allGroups = getAllGroups();
            final List<String> groupUuidList = new ArrayList<String>(allGroups.size());
            for (Group group : allGroups)
                groupUuidList.add(group.getUuid());
            Collections.sort(roleList);
            return roleList;
        } catch (Exception e) {
            log.error("Can't get roles from roles mapping file!", e);
            return null;
        } finally {
            close(reader, "mapping file reader");
        }
    }

    public void addRole(Role role) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(rolesMappingFile, true));
            JSONObject jsonObject = JSONObject.fromObject(role);
            writer.write(jsonObject.toString());
            writer.newLine();
        } catch (IOException e) {
            log.error("Can't add role to roles mapping file!", e);
        } finally {
            close(writer, "mapping file reader");
        }
    }

    public void updateRole(Role role) {
        Role oldRole = null;
        List<Role> roles = getAllRoles();
        for(Role current : roles)
            if (role.getUuid().equals(current.getUuid()))
                oldRole = current;
        if (oldRole != null) {
            if (!oldRole.getRolename().equals(role.getRolename())) {
                this.em.createQuery("UPDATE UserRoleAssignment ura SET ura.role = :newRolename WHERE ura.role = :oldRolename")
                .setParameter("oldRolename", oldRole.getRolename())
                .setParameter("newRolename", role.getRolename())
                .executeUpdate();
            }
            roles.set(roles.indexOf(oldRole), role);
            saveRoles(roles);
        } else {
            log.warn("Update Role "+role+" failed! Removed from roles mapping file!");
        }
    }

    public void removeRole(Role role) {
        this.em.createQuery("DELETE FROM StudyPermission sp WHERE sp.role = :rolename")
        .setParameter("rolename", role.getRolename())
        .executeUpdate();
        this.em.createQuery("DELETE FROM UserRoleAssignment ura WHERE ura.role = :rolename")
        .setParameter("rolename", role.getRolename())
        .executeUpdate();
        List<Role> roles = getAllRoles();
        if (roles.remove(role)) {
            saveRoles(roles);
        } else {
            log.warn("Role "+role+" already removed from roles mapping file!");
        }
    }

    private void saveRoles(List<Role> roles) {
        BufferedWriter writer = null;
        try {
            File tmpFile = File.createTempFile(rolesMappingFile.getName(), null, rolesMappingFile.getParentFile());
            writer = new BufferedWriter(new FileWriter(tmpFile, true));
            JSONObject jsonObject;
            for (int i=0,len=roles.size() ; i < len ; i++) {
                jsonObject = JSONObject.fromObject(roles.get(i));
                writer.write(jsonObject.toString());
                writer.newLine();
            }
            if (close(writer, "Temporary mapping file"))
                writer = null;
            rolesMappingFile.delete();
            tmpFile.renameTo(rolesMappingFile);
        } catch (IOException e) {
            log.error("Can't save roles in roles mapping file!", e);
        } finally {
            close(writer, "Temporary mapping file (in finally block)");
        }
    }

    public Boolean roleExists(String rolename) {
        return getAllRoles().contains(new Role(rolename));
    }

    public List<Group> getAllGroups() {
        BufferedReader reader = null;
        try {
            List<Group> groupList = new ArrayList<Group>();
            String line;
            reader = new BufferedReader(new FileReader(groupsFile));
            while ((line = reader.readLine()) != null)
                groupList.add((Group) JSONObject.toBean(JSONObject.fromObject(line), Group.class));
            Collections.sort(groupList);

            int webPos = -1;
            int dicomPos = -1;
            int aetPos = -1;

            for (int i = 0; i < groupList.size(); i++) {
                if (groupList.get(i).getGroupname().equalsIgnoreCase("Web"))
                    webPos = i;
                if (groupList.get(i).getGroupname().equalsIgnoreCase("Dicom"))
                    dicomPos = i;
                if (groupList.get(i).getGroupname().equalsIgnoreCase("AET"))
                    aetPos = i;
            }

            if (aetPos != -1) {
                Group aetGroup = groupList.get(aetPos);
                groupList.remove(aetPos);
                groupList.add(0, aetGroup);
            } else {
                Group group = new Group();
                group.setGroupname("AET");
                addGroup(group);
                groupList.add(0, group);
            }
            if (dicomPos != -1) {
                Group dicomGroup = groupList.get(dicomPos);
                groupList.remove(dicomPos);
                groupList.add(0, dicomGroup);
            } else {
                Group group = new Group();
                group.setGroupname("Dicom");
                addGroup(group);
                groupList.add(0, group);
            }
            if (webPos != -1) {
                Group webGroup = groupList.get(webPos);
                groupList.remove(webPos);
                groupList.add(0, webGroup);
            } else {
                Group group = new Group();
                group.setGroupname("Web");
                addGroup(group);
                groupList.add(0, group);
            }

            return groupList;
        } catch (Exception e) {
            log.error("Can't get groups from groups file!", e);
            return null;
        } finally {
            close(reader, "groups file reader");
        }
    }

    public void addGroup(Group group) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(groupsFile, true));
            JSONObject jsonObject = JSONObject.fromObject(group);
            writer.write(jsonObject.toString());
            writer.newLine();
        } catch (IOException e) {
            log.error("Can't add group to groups file!", e);
        } finally {
            close(writer, "groups file reader");
        }
    }

    public void updateGroup(Group group) {
        Group oldGroup = null;
        List<Group> groups = getAllGroups();
        for(Group current : groups)
            if (group.getUuid().equals(current.getUuid()))
                oldGroup = current;
        if (oldGroup != null) {
            groups.set(groups.indexOf(oldGroup), group);
            saveGroups(groups);
        } else {
            log.warn("Update Group "+group+" failed! Removed from groups file!");
        }
    }

    public void removeGroup(Group group) {
        List<Role> roles = getAllRoles();
        for (Role role : roles)
            if (role.getRoleGroups().contains(role.getUuid()))
                role.getRoleGroups().remove(role.getUuid());
        List<Group> groups = getAllGroups();
        if (groups.remove(group)) {
            saveGroups(groups);
        } else {
            log.warn("Group "+group+" already removed from groups file!");
        }
    }

    private void saveGroups(List<Group> groups) {
        BufferedWriter writer = null;
        try {
            File tmpFile = File.createTempFile(groupsFile.getName(), null, groupsFile.getParentFile());
            writer = new BufferedWriter(new FileWriter(tmpFile, true));
            JSONObject jsonObject;
            for (int i=0,len=groups.size() ; i < len ; i++) {
                jsonObject = JSONObject.fromObject(groups.get(i));
                writer.write(jsonObject.toString());
                writer.newLine();
            }
            if (close(writer, "Temporary groups file"))
                writer = null;
            groupsFile.delete();
            tmpFile.renameTo(groupsFile);
        } catch (IOException e) {
            log.error("Can't save groups in groups file!", e);
        } finally {
            close(writer, "Temporary groups file (in finally block)");
        }
    }

    public List<AETGroup> getAllAETGroups() {
        BufferedReader reader = null;
        try {
            List<AETGroup> aetGroupList = new ArrayList<AETGroup>();
            String line;
            reader = new BufferedReader(new FileReader(aetGroupsFile));
            while ((line = reader.readLine()) != null)
                aetGroupList.add((AETGroup) JSONObject.toBean(JSONObject.fromObject(line), AETGroup.class));
            Collections.sort(aetGroupList);
            return aetGroupList;
        } catch (Exception e) {
            log.error("Can't get aet groups from aet groups file!", e);
            return null;
        } finally {
            close(reader, "aet groups file reader");
        }
    }

    public void addAETGroup(AETGroup aetGroup) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(aetGroupsFile, true));
            JSONObject jsonObject = JSONObject.fromObject(aetGroup);
            writer.write(jsonObject.toString());
            writer.newLine();
        } catch (IOException e) {
            log.error("Can't add aet group to aet groups file!", e);
        } finally {
            close(writer, "aet groups file reader");
        }
    }

    public void updateAETGroup(AETGroup aetGroup) {
        AETGroup oldAetGroup = null;
        List<AETGroup> aetGroups = getAllAETGroups();
        for(AETGroup current : aetGroups)
            if (aetGroup.getUuid().equals(current.getUuid()))
                oldAetGroup = current;
        if (oldAetGroup != null) {
            aetGroups.set(aetGroups.indexOf(oldAetGroup), aetGroup);
            saveAETGroups(aetGroups);
        } else {
            log.warn("Update AET Group "+aetGroup+" failed! Removed from aet groups file!");
        }
    }

    public void removeAETGroup(AETGroup aetGroup) {
        List<Role> roles = getAllRoles();
        for (Role role : roles)
            if (role.getAETGroups().contains(aetGroup.getUuid()))
                role.getAETGroups().remove(aetGroup.getUuid());
        List<AETGroup> aetGroups = getAllAETGroups();
        if (aetGroups.remove(aetGroup)) {
            saveAETGroups(aetGroups);
        } else {
            log.warn("AET Group "+aetGroup+" already removed from aet groups file!");
        }
    }

    public List<AETGroup> getAETGroups(List<String> roles) {
        Set<String> aetGroupUuids = new HashSet<String>();
        for (Role role : getAllRoles())
            if (role.isAETRole() && roles.contains(role.getRolename()))
                aetGroupUuids.addAll(role.getAETGroups());
        List<AETGroup> aetGroups = getAllAETGroups();
        for (int i = 0; i < aetGroups.size(); i++) {
            AETGroup aetGroup = aetGroups.get(i);
            if (!aetGroupUuids.contains(aetGroup.getUuid())) {
                aetGroups.remove(aetGroup);
                i--;
            }
        }
        Collections.sort(aetGroups);
        if (aetGroupUuids.contains("*"))
            aetGroups.add(0, new AETGroup("*"));
        return aetGroups;
    }

    @SuppressWarnings("unchecked")
    public List<String> listAETitles() {
        return em.createQuery("SELECT ae.title FROM AE ae ORDER BY ae.title")
                .getResultList();
    }

    public void updateAETInAETGroups(String oldAET, String newAET) {
        List<AETGroup> aetGroups = getAllAETGroups();
        for (AETGroup aetGroup : aetGroups) {
            if (aetGroup.getAets().remove(oldAET))
                aetGroup.getAets().add(newAET);
        }
        saveAETGroups(aetGroups);
    }

    public void removeAETFromAETGroups(String aet) {
        List<AETGroup> aetGroups = getAllAETGroups();
        for (AETGroup aetGroup : aetGroups)
            aetGroup.getAets().remove(aet);
        saveAETGroups(aetGroups);
    }

    private void saveAETGroups(List<AETGroup> aetGroups) {
        BufferedWriter writer = null;
        try {
            File tmpFile = File.createTempFile(aetGroupsFile.getName(), null, aetGroupsFile.getParentFile());
            writer = new BufferedWriter(new FileWriter(tmpFile, true));
            JSONObject jsonObject;
            for (int i=0,len=aetGroups.size() ; i < len ; i++) {
                jsonObject = JSONObject.fromObject(aetGroups.get(i));
                writer.write(jsonObject.toString());
                writer.newLine();
            }
            if (close(writer, "Temporary aet groups file"))
                writer = null;
            aetGroupsFile.delete();
            tmpFile.renameTo(aetGroupsFile);
        } catch (IOException e) {
            log.error("Can't save aet groups in aet groups file!", e);
        } finally {
            close(writer, "Temporary aet groups file (in finally block)");
        }
    }

    private boolean close(Closeable toClose, String desc) {
        log.debug("Closing ",desc);
        if (toClose != null) {
            try {
                toClose.close();
                return true;
            } catch (IOException ignore) {
                log.warn("Error closing : "+desc, ignore);
            }
        }
        return false;
    }
}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>StringGenJSON | Graphinius</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Graphinius

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"core/GenHierarchies"

					StringGenJSON

Interface StringGenJSON

Hierarchy

						StringGenJSON

Index

Properties

entries

name

Properties

entries

entries: object

Defined in core/GenHierarchies.ts:44

Type declaration

[key: string]: IStringGHEntry

name

name: string

Defined in core/GenHierarchies.ts:43

						Globals

						"<wbr>SaNGree<wbr>A/SNDistance<wbr>Funcs"

						"<wbr>SaNGree<wbr>A/SaNGree<wbr>A"

						"config/<wbr>SaNGreeAConfig_<wbr>adult"

						"config/<wbr>SaNGreeAConfig_<wbr>house"

						"core/<wbr>Equivalence<wbr>Class"

						"core/<wbr>Gen<wbr>Hierarchies"

						"io/CSVInput"

						"io/CSVOutput"

						Cont<wbr>Gen<wbr>Hierarchy

						String<wbr>Gen<wbr>Hierarchy

						ICont<wbr>Gen<wbr>Hierarchy

						IStringGHEntry

						IString<wbr>Gen<wbr>Hierarchy

						String<wbr>GenJSON

								entries

								name

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
import os
import threading
import logging
import logging.handlers
import eftepede_globals
import pyftpdlib.authorizers
import eftepede_password

class Authorizer(pyftpdlib.authorizers.DummyAuthorizer):

    def __init__(self, config, logger):
        pyftpdlib.authorizers.DummyAuthorizer.__init__(self)
        self.config = config
        self.logger = logger
        self.db = eftepede_globals.Database
        self.user_cache = {}

    def add_user(self, username, password, homedir, perm='elr', msg_login="Login successful.", msg_quit="Goodbye."):
        if self.db.has_user(username):
            raise pyftpdlib.authorizers.AuthorizerError('User "%s" already exists' % (username, ))
        if not os.path.isdir(homedir):
            raise pyftpdlib.authorizers.AuthorizerError('No such directory: "%s"' % (homedir, ))
        homedir = os.path.realpath(homedir)
        self._check_permissions(username, perm)
        self.db.add_user(username, eftepede_password.encode(password), homedir, perm, msg_login, msg_quit)

    def add_anonymous(self, homedir, **kwargs):
        return self.add_user('anonymous', '', homedir, **kwargs)

    def remove_user(self, username):
        self.db.remove_user(username)
        try:
            del self.user_cache[username]
        except KeyError:
            pass

    def validate_authentication(self, username, given_password, handler):
        self.logger.info("validate_authentication(%r, %r, %r) called" % (username, given_password, handler, ))
        # NB: this may be tricky, for the sake of unicode names returned from the database...
        result = self.db.identify(username)
        if result is None:
            self.logger.warn("Warning, validate_authentication(%r) failed: no such user" % (username, ))
            return False

        actual_password, homedir, perm, msg_login, msg_quit = result

        if (username != 'anonymous') and (eftepede_password.encode(given_password) != actual_password):
            self.logger.warn("Warning, validate_authentication(%r) failed: invalid password" % (username, ))
            return False

        if isinstance(homedir, str):
            homedir = homedir.decode("latin-1")

        dic = {'home': homedir,
               'perm': "elradfmwM",
               'operms': {},
               'msg_login': str(msg_login),
               'msg_quit': str(msg_quit)
               }
        self.user_table[username] = dic
        self.logger.info("User %r logged in successfully..." % (username, ))
        return True

if __name__ == "__main__":
    import eftepede_server
    eftepede_server.main()


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\User;

/* @var $this yii\web\View */
/* @var $model app\models\User */
/* @var $form yii\widgets\ActiveForm */

$this->title = 'Profile';
$this->params['breadcrumbs'][] = 'Profile';
?>

<?= Html::encode($this->title) ?>

        <?php $form = ActiveForm::begin(); ?>

        <?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>

        <?= $form->field($model, 'password')->passwordInput(['maxlength' => true, 'value' => '']) ?>
        <?= $form->field($model, 'password_repeat')->passwordInput(['maxlength' => true, 'value' => '']) ?>

        <?= $form->field($model, 'user_type')->dropDownList(array_merge([''=>''], User::getUserType()), ['disabled' => 'disabled']) ?>

            <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

        <?php ActiveForm::end(); ?>


text:
TemplatingTools = {
  // This type of error should be thrown during compilation
  CompileError: class CompileError {}
};


text:
package command

import (
	"github.com/mitchellh/cli"
	"strings"
)

type UnloadCommand struct {
	Ui cli.Ui
}

func (c *UnloadCommand) Run(args []string) int {
	// Write your code here
	return 0
}

func (c *UnloadCommand) Synopsis() string {
	return ""
}

func (c *UnloadCommand) Help() string {
	helpText := `

`
	return strings.TrimSpace(helpText)
}


text:
echo "$(date)"
echo "Running shutdown script"

readonly METADATA_URL="http://metadata.google.internal/computeMetadata/v1/instance"
readonly METADATA_HEADERS="Metadata-Flavor: Google"
readonly OUTPUT=$(curl "${METADATA_URL}/attributes/output" -H "${METADATA_HEADERS}")
readonly OPERATION_ID=$(curl "${METADATA_URL}/attributes/operation-id" -H "${METADATA_HEADERS}")
readonly STATUS_LOCAL="/tmp/status-${OPERATION_ID}.txt"

readonly STDOUT=/tmp/stdout-${OPERATION_ID}.txt
readonly STDERR=/tmp/stderr-${OPERATION_ID}.txt

echo "$(date)"
echo "Copying stdout and stderr to Cloud Storage"
CMD="gsutil -m cp ${STDOUT} ${STDERR} ${OUTPUT}/"
echo "${CMD}"
${CMD}

# Typically shutdown will cause a running job to fail and status will be set to FAILED
# In case the status is left as RUNNING, set it to FAILED
STATUS="$(cat ${STATUS_LOCAL})"
echo "Status ${STATUS}"

if [[ "${STATUS}" == "RUNNING" ]]; then
  echo "Setting status to FAILED"
  echo "FAILED" > ${STATUS_LOCAL}
  STATUS_FILE=$(curl "${METADATA_URL}/attributes/status-file" -H "${METADATA_HEADERS}")
  gsutil cp ${STATUS_LOCAL} ${STATUS_FILE}
fi


text:
package hudson.tasks.test;

import hudson.tasks.junit.TestAction;
import hudson.model.AbstractBuild;
import hudson.model.Run;
import hudson.model.Result;

import java.util.Collection;

import static java.util.Collections.emptyList;

/**
 * A class that represents a general concept of a test result, without any
 * language or implementation specifics.
 * Subclasses must add @Exported annotation to the fields they want to export.
 *
 * @sine 1.343
 */
public abstract class TestResult extends TestObject {

    /**
     * If the concept of a parent action is important to a subclass, then it should
     * provide a non-noop implementation of this method.
     * @param action
     */
    public void setParentAction(AbstractTestResultAction action) {
    }

    /**
     * Returns the action that points to the top level test result includes
     * this test result.
     *
     * @return
     */
    public AbstractTestResultAction getParentAction() {
        return getOwner().getTestResultAction();
    }

    /**
     * Request that the result update its counts of its children. Does not
     * require a parent action or owner or siblings. Subclasses should
     * implement this, unless they are *always* in a tallied state.
     */
    public void tally() {
    }

    /**
     * Sets the parent test result
     * @param parent
     */
    public void setParent(TestObject parent) {
    }

    /**
     * Gets the human readable title of this result object.
     */
    public /* abstract */ String getTitle(){
        return "";
    }

    /**
     * Mark a build as unstable if there are failures. Otherwise, leave the
     * build result unchanged.
     *
     * @return {@link Result#UNSTABLE} if there are test failures, null otherwise.
     *
     */
    public Result getBuildResult() {
        if (getFailCount() > 0) {
            return Result.UNSTABLE;
        } else {
            return null;
        }
    }

    /**
     * Time it took to run this test. In seconds.
     */
    public /* abstract */ float getDuration() {
        return 0.0f;
    }

    /**
     * Gets the total number of passed tests.
     */
    public /* abstract */ int getPassCount() {
        return 0;
    }

    /**
     * Gets the total number of failed tests.
     */
    public /* abstract */ int getFailCount() {
        return 0;
    }

    /**
     * Gets the total number of skipped tests.
     */
    public /* abstract */ int getSkipCount() {
        return 0;
    }

    /**
     * Gets the counter part of this {@link TestResult} in the previous run.
     *
     * @return null if no such counter part exists.
     */
    public TestResult getPreviousResult() {
        AbstractBuild<?,?> b = getOwner();
        if (b == null) {
            return null;
        }
        while(true) {
            b = b.getPreviousBuild();
            if(b==null)
                return null;
            AbstractTestResultAction r = b.getAction(getParentAction().getClass());
            if(r!=null) {
                TestResult result = r.findCorrespondingResult(this.getId());
                if (result!=null)
                    return result;
            }
        }
    }

    /**
     * Gets the counter part of this {@link TestResult} in the specified run.
     *
     * @return null if no such counter part exists.
     */
    public TestResult getResultInBuild(AbstractBuild<?,?> build) {
        AbstractTestResultAction tra = build.getAction(getParentAction().getClass());
        if (tra == null) {
            tra = build.getAction(AbstractTestResultAction.class);
        }
        return (tra == null) ? null : tra.findCorrespondingResult(this.getId());
    }

    /**
     * Gets the "children" of this test result that failed
     * @return the children of this test result, if any, or an empty collection
     */
    public Collection<? extends TestResult> getFailedTests() {
        return emptyList();
    }

    /**
     * Gets the "children" of this test result that passed
     * @return the children of this test result, if any, or an empty collection
     */
    public Collection<? extends TestResult> getPassedTests() {
        return emptyList();
    }

    /**
     * Gets the "children" of this test result that were skipped
     * @return the children of this test result, if any, or an empty list
     */
    public Collection<? extends TestResult> getSkippedTests() {
        return emptyList();
    }

    /**
     * If this test failed, then return the build number
     * when this test started failing.
     */
    public int getFailedSince() {
        return 0;
    }

    /**
     * If this test failed, then return the run
     * when this test started failing.
     */
    public Run<?,?> getFailedSinceRun() {
        return null;
    }

    /**
     * The stdout of this test.
     */
    public String getStdout() {
        return "";
    }

    /**
     * The stderr of this test.
     */
    public String getStderr() {
        return "";
    }

    /**
     * If there was an error or a failure, this is the stack trace, or otherwise null.
     */
    public String getErrorStackTrace() {
        return "";
    }

    /**
     * If there was an error or a failure, this is the text from the message.
     */
    public String getErrorDetails() {
        return "";
    }

    /**
     * @return true if the test was not skipped and did not fail, false otherwise.
     */
    public boolean isPassed() {
        return ((getSkipCount() == 0) && (getFailCount() == 0));
    }

    public String toPrettyString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("Name: ").append(this.getName()).append(", ");
        sb.append("Result: ").append(this.getBuildResult()).append(",\n");
        sb.append("Total Count: ").append(this.getTotalCount()).append(", ");
        sb.append("Fail: ").append(this.getFailCount()).append(", ");
        sb.append("Skipt: ").append(this.getSkipCount()).append(", ");
        sb.append("Pass: ").append(this.getPassCount()).append(",\n");
        sb.append("Test Result Class: " ).append(this.getClass().getName()).append(" }\n");
        return sb.toString();
    }

    /**
     * Annotate some text -- what does this do?
     * @param text
     * @return
     */
    public String annotate(String text) {
        if (text == null)
                return null;
        text = text.replace("&", "&").replace("<", "<").replaceAll(
                        "\\b(https?://[^\\s)>]+)", "$1");

        for (TestAction action: getTestActions()) {
                text = action.annotate(text);
        }
        return text;
    }
}


text:
"""Splinter plugin for pytest.

Provides easy interface for the browser from your tests providing the `browser` fixture
which is an object of splinter Browser class.
"""
import codecs
import functools  # pragma: no cover
try:
    from httplib import HTTPException
except ImportError:
    from http.client import HTTPException
import mimetypes  # pragma: no cover
import os.path
import re

import pytest  # pragma: no cover
import splinter  # pragma: no cover
from _pytest import junitxml
from _pytest.tmpdir import tmpdir

from selenium.webdriver.support import wait
from selenium.common.exceptions import WebDriverException

from .webdriver_patches import patch_webdriver  # pragma: no cover
from .splinter_patches import patch_webdriverelement  # pragma: no cover
from .decorators import with_fixtures

import logging
LOGGER = logging.getLogger(__name__)

NAME_RE = re.compile(r'[\W]')

def _visit(self, url):
    """Override splinter's visit to avoid unnecessary checks and add wait_until instead."""
    self.driver.get(url)
    self.wait_for_condition(self.visit_condition, timeout=self.visit_condition_timeout)

def _wait_for_condition(self, condition=None, timeout=None, poll_frequency=0.5, ignored_exceptions=None):
    """Wait for given javascript condition."""
    condition = functools.partial(condition or self.visit_condition, self)

    timeout = timeout or self.wait_time

    return wait.WebDriverWait(
        self.driver, timeout, poll_frequency=poll_frequency, ignored_exceptions=ignored_exceptions
    ).until(
        lambda browser: condition()
    )

def Browser(*args, **kwargs):
    """Emulate splinter's Browser."""
    visit_condition = kwargs.pop('visit_condition')
    visit_condition_timeout = kwargs.pop('visit_condition_timeout')
    browser = splinter.Browser(*args, **kwargs)
    browser.wait_for_condition = functools.partial(_wait_for_condition, browser)
    if hasattr(browser, 'driver'):
        browser.visit_condition = visit_condition
        browser.visit_condition_timeout = visit_condition_timeout
        browser.visit = functools.partial(_visit, browser)
    browser.__splinter_browser__ = True
    return browser

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_close_browser():
    """Close browser fixture."""
    return True

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_webdriver(request):
    """Webdriver fixture."""
    return request.config.option.splinter_webdriver

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_remote_url(request):
    """Remote webdriver url.

    :return: URL of remote webdriver.
    """
    return request.config.option.splinter_remote_url

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_selenium_socket_timeout(request):
    """Internal Selenium socket timeout (communication between webdriver and the browser).

    :return: Seconds.
    """
    return request.config.option.splinter_webdriver_socket_timeout

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_selenium_implicit_wait(request):
    """Selenium implicit wait timeout.

    :return: Seconds.
    """
    return request.config.option.splinter_webdriver_implicit_wait

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_wait_time(request):
    """Splinter explicit wait timeout.

    :return: Seconds.
    """
    return request.config.option.splinter_wait_time

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_selenium_speed(request):
    """Selenium speed.

    :return: Seconds.
    """
    return request.config.option.splinter_webdriver_speed

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_browser_load_condition():
    """The condition that has to be `True` to assume that the page is fully loaded.

    One example is to wait for jQuery, then the condition could be::

        @pytest.fixture
        def splinter_browser_load_condition():

            def condition(browser):
                return browser.evaluate_script('typeof $ === "undefined" || !$.active')

            return condition
    """
    return lambda browser: True

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_browser_load_timeout():
    """The timeout in seconds in which the page is expected to be fully loaded."""
    return 10

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_file_download_dir(session_tmpdir):
    """Browser file download directory."""
    return session_tmpdir.ensure('splinter', 'download', dir=True).strpath

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_download_file_types():
    """Browser file types to download. Comma-separated."""
    return ','.join(mimetypes.types_map.values())

@pytest.fixture(scope='session')
def splinter_firefox_profile_preferences():
    """Firefox profile preferences."""
    return {
        'browser.cache.memory.enable': False,
        'browser.sessionhistory.max_total_viewers': 0,
        'network.http.pipelining': True,
        'network.http.pipelining.maxrequests': 8
    }

@pytest.fixture(scope='session')
def splinter_firefox_profile_directory():
    """Firefox profile directory."""
    return os.path.join(os.path.dirname(__file__), 'profiles', 'firefox')

@pytest.fixture(scope='session')
def splinter_driver_kwargs():
    """Webdriver kwargs."""
    return {}

@pytest.fixture(scope='session')
def splinter_window_size():
    """Browser window size. (width, height)."""
    return (1366, 768)

@pytest.fixture(scope='session')
def splinter_session_scoped_browser(request):
    """Flag to keep single browser per test session."""
    return request.config.option.splinter_session_scoped_browser == 'true'

@pytest.fixture(scope='session')
def splinter_make_screenshot_on_failure(request):
    """Flag to make browser screenshot on test failure."""
    return request.config.option.splinter_make_screenshot_on_failure == 'true'

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_screenshot_dir(request):
    """Browser screenshot directory."""
    return os.path.abspath(request.config.option.splinter_screenshot_dir)

@pytest.fixture(scope='session')  # pragma: no cover
def splinter_screenshot_encoding(request):
    """Browser screenshot html encoding."""
    return 'utf-8'

@pytest.fixture(scope='session')
def splinter_webdriver_executable(request):
    """Webdriver executable directory."""
    executable = request.config.option.splinter_webdriver_executable
    return os.path.abspath(executable) if executable else None

@pytest.fixture(scope='session')
def browser_pool(request, splinter_close_browser):
    """Browser 'pool' to emulate session scope but with possibility to recreate browser."""
    pool = {}

    def fin():
        for browser in pool.values():
            try:
                browser.quit()
            except Exception:  # NOQA
                pass

    if splinter_close_browser:
        request.addfinalizer(fin)

    return pool

@pytest.fixture(scope='session')
def browser_patches():
    """Browser monkey patches."""
    patch_webdriver()
    patch_webdriverelement()

@pytest.fixture(scope='session')
def session_tmpdir(request):
    """pytest tmpdir which is session-scoped."""
    return with_fixtures(tmpdir)(request)

@pytest.fixture(scope='session')
def splinter_browser_class(request):
    """Browser class to use for browser instance creation."""
    return Browser

def get_args(driver=None,
             download_dir=None,
             download_ftypes=None,
             firefox_pref=None,
             firefox_prof_dir=None,
             remote_url=None,
             executable=None,
             driver_kwargs=None):
    """Construct arguments to be passed to webdriver on initialization."""
    kwargs = {}

    if driver == 'firefox':
        kwargs['profile_preferences'] = dict({
            'browser.download.folderList': 2,
            'browser.download.manager.showWhenStarting': False,
            'browser.download.dir': download_dir,
            'browser.helperApps.neverAsk.saveToDisk': download_ftypes,
            'browser.helperApps.alwaysAsk.force': False,
            'pdfjs.disabled': True,  # disable internal ff pdf viewer to allow auto pdf download
        }, **firefox_pref)
        kwargs['profile'] = firefox_prof_dir
    elif driver == 'remote':
        if remote_url:
            kwargs['url'] = remote_url
        kwargs['keep_alive'] = True
    elif driver in ('phantomjs', 'chrome'):
        if executable:
            kwargs['executable_path'] = executable
    if driver_kwargs:
        kwargs.update(driver_kwargs)

    return kwargs

@pytest.fixture(scope='session')
def splinter_screenshot_getter_png():
    """Screenshot getter function: png."""
    def getter(browser, path):
        browser.driver.save_screenshot(path)
    return getter

@pytest.fixture(scope='session')
def splinter_screenshot_getter_html(splinter_screenshot_encoding):
    """Screenshot getter function: html."""
    def getter(browser, path):
        with codecs.open(path, 'w', encoding=splinter_screenshot_encoding) as fd:
            fd.write(browser.html)
    return getter

@pytest.fixture(scope='session')
def browser_instance_getter(
        browser_patches,
        splinter_session_scoped_browser,
        splinter_browser_load_condition,
        splinter_browser_load_timeout,
        splinter_download_file_types,
        splinter_driver_kwargs,
        splinter_file_download_dir,
        splinter_firefox_profile_preferences,
        splinter_firefox_profile_directory,
        splinter_make_screenshot_on_failure,
        splinter_remote_url,
        splinter_screenshot_dir,
        splinter_selenium_implicit_wait,
        splinter_wait_time,
        splinter_selenium_socket_timeout,
        splinter_selenium_speed,
        splinter_webdriver_executable,
        splinter_window_size,
        splinter_browser_class,
        session_tmpdir,
        browser_pool,
):
    """Splinter browser instance getter. To be used for getting of plugin.Browser's instances.

    :return: function(parent). Each time this function will return new instance of plugin.Browser class.
    """
    def get_browser(splinter_webdriver, retry_count=3):
        kwargs = get_args(driver=splinter_webdriver,
                          download_dir=splinter_file_download_dir,
                          download_ftypes=splinter_download_file_types,
                          firefox_pref=splinter_firefox_profile_preferences,
                          firefox_prof_dir=splinter_firefox_profile_directory,
                          remote_url=splinter_remote_url,
                          executable=splinter_webdriver_executable,
                          driver_kwargs=splinter_driver_kwargs)
        try:
            return splinter_browser_class(
                splinter_webdriver, visit_condition=splinter_browser_load_condition,
                visit_condition_timeout=splinter_browser_load_timeout,
                wait_time=splinter_wait_time, **kwargs
            )
        except Exception:  # NOQA
            if retry_count > 1:
                return get_browser(splinter_webdriver, retry_count - 1)
            else:
                raise

    def prepare_browser(request, parent):
        splinter_webdriver = request.getfuncargvalue('splinter_webdriver')
        browser_key = id(parent)
        browser = browser_pool.get(browser_key)
        if not splinter_session_scoped_browser:
            browser = get_browser(splinter_webdriver)
            if splinter_close_browser:
                request.addfinalizer(browser.quit)
        elif not browser:
            browser = browser_pool[browser_key] = get_browser(splinter_webdriver)
        try:
            if splinter_webdriver not in browser.driver_name.lower():
                raise IOError('webdriver does not match')
            if hasattr(browser, 'driver'):
                browser.driver.implicitly_wait(splinter_selenium_implicit_wait)
                browser.driver.set_speed(splinter_selenium_speed)
                browser.driver.command_executor.set_timeout(splinter_selenium_socket_timeout)
                browser.driver.command_executor._conn.timeout = splinter_selenium_socket_timeout
                if splinter_window_size:
                    browser.driver.set_window_size(*splinter_window_size)
            browser.cookies.delete()
            if hasattr(browser, 'driver'):
                browser.visit_condition = splinter_browser_load_condition
                browser.visit_condition_timeout = splinter_browser_load_timeout
                browser.visit('about:blank')
        except (IOError, HTTPException, WebDriverException):
            # we lost browser, try to restore the justice
            try:
                browser.quit()
            except Exception:  # NOQA
                pass
            browser = browser_pool[browser_key] = get_browser(splinter_webdriver)
            prepare_browser(request, parent)

        return browser

    return prepare_browser

@pytest.yield_fixture(autouse=True)
def browser_screenshot(
        request, splinter_screenshot_dir, session_tmpdir, splinter_make_screenshot_on_failure,
        splinter_screenshot_encoding, splinter_screenshot_getter_png, splinter_screenshot_getter_html):
    """Make browser screenshot on test failure."""
    yield
    for name, value in request._funcargs.items():
        if hasattr(value, '__splinter_browser__'):
            browser = value
            if splinter_make_screenshot_on_failure and request.node.splinter_failure:
                slaveoutput = getattr(request.config, 'slaveoutput', None)
                names = junitxml.mangle_testnames(request.node.nodeid.split("::"))
                classname = '.'.join(names[:-1])
                screenshot_dir = os.path.join(splinter_screenshot_dir, classname)
                screenshot_file_name_format = '{0}-{1}.{{format}}'.format(
                    names[-1][:128 - len(name) - 5], name)
                screenshot_file_name = screenshot_file_name_format.format(format='png')
                screenshot_html_file_name = screenshot_file_name_format.format(format='html')
                if not slaveoutput:
                    if not os.path.exists(screenshot_dir):
                        os.makedirs(screenshot_dir)
                else:
                    screenshot_dir = session_tmpdir.ensure('screenshots', dir=True).strpath
                screenshot_png_path = os.path.join(screenshot_dir, screenshot_file_name)
                screenshot_html_path = os.path.join(screenshot_dir, screenshot_html_file_name)
                LOGGER.info('Saving screenshot to %s', screenshot_dir)
                try:
                    splinter_screenshot_getter_html(browser, screenshot_html_path)
                    splinter_screenshot_getter_png(browser, screenshot_png_path)
                    if slaveoutput is not None:
                        with codecs.open(screenshot_html_path, encoding=splinter_screenshot_encoding) as html_fd:
                            with open(screenshot_png_path) as fd:
                                slaveoutput.setdefault('screenshots', []).append({
                                    'class_name': classname,
                                    'files': [
                                        {
                                            'file_name': screenshot_file_name,
                                            'content': fd.read(),
                                        },
                                        {
                                            'file_name': screenshot_html_file_name,
                                            'content': html_fd.read(),
                                            'encoding': splinter_screenshot_encoding
                                        }]
                                })
                except Exception as e:  # NOQA
                    request.config.warn('SPL504', "Could not save screenshot: {0}".format(e))

@pytest.mark.tryfirst
def pytest_runtest_makereport(item, call, __multicall__):
    """Assign the report to the item for futher usage."""
    rep = __multicall__.execute()
    if rep.outcome != 'passed':
        item.splinter_failure = rep
    else:
        item.splinter_failure = None
    return rep

@pytest.fixture
def browser(request, browser_instance_getter):
    """Browser fixture."""
    return browser_instance_getter(request, browser)

@pytest.fixture(scope='session')
def session_browser(request, browser_instance_getter):
    """Session scoped browser fixture."""
    return browser_instance_getter(request, session_browser)

class SplinterXdistPlugin(object):

    """Plugin class to defer pytest-xdist hook handler."""

    def pytest_testnodedown(self, node, error):
        """Copy screenshots back from remote nodes to have them on the master."""
        config_screenshot_dir = splinter_screenshot_dir(node)
        for screenshot in getattr(node, 'slaveoutput', {}).get('screenshots', []):
            screenshot_dir = os.path.join(config_screenshot_dir, screenshot['class_name'])
            if not os.path.exists(screenshot_dir):
                os.makedirs(screenshot_dir)
            for fil in screenshot['files']:
                encoding = fil.get('encoding')
                with codecs.open(os.path.join(screenshot_dir, fil['file_name']), 'w',
                                 **dict(encoding=encoding) if encoding else {}) as fd:
                    fd.write(fil['content'])

def pytest_configure(config):
    """Register pytest-splinter's deferred plugin."""
    if config.pluginmanager.getplugin('xdist'):
        config.pluginmanager.register(SplinterXdistPlugin())

def pytest_addoption(parser):  # pragma: no cover
    """Pytest hook to add custom command line option(s)."""
    group = parser.getgroup("splinter", "splinter integration for browser testing")
    group.addoption(
        "--splinter-webdriver",
        help="pytest-splinter webdriver", type="choice", choices=list(splinter.browser._DRIVERS.keys()),
        dest='splinter_webdriver', metavar="DRIVER", default='firefox')
    group.addoption(
        "--splinter-remote-url",
        help="pytest-splinter remote webdriver url ", metavar="URL", dest='splinter_remote_url', default=None)
    group.addoption(
        "--splinter-wait-time",
        help="splinter explicit wait, seconds", type="int",
        dest='splinter_wait_time', metavar="SECONDS", default=5)
    group.addoption(
        "--splinter-implicit-wait",
        help="pytest-splinter selenium implicit wait, seconds", type="int",
        dest='splinter_webdriver_implicit_wait', metavar="SECONDS", default=5)
    group.addoption(
        "--splinter-speed",
        help="pytest-splinter selenium speed, seconds", type="int",
        dest='splinter_webdriver_speed', metavar="SECONDS", default=0)
    group.addoption(
        "--splinter-socket-timeout",
        help="pytest-splinter socket timeout, seconds", type="int",
        dest='splinter_webdriver_socket_timeout', metavar="SECONDS", default=120)
    group.addoption(
        "--splinter-session-scoped-browser",
        help="pytest-splinter should use a single browser instance per test session. Defaults to true.", action="store",
        dest='splinter_session_scoped_browser', metavar="false|true", type="choice", choices=['false', 'true'],
        default='true')
    group.addoption(
        "--splinter-make-screenshot-on-failure",
        help="pytest-splinter should take browser screenshots on test failure. Defaults to true.", action="store",
        dest='splinter_make_screenshot_on_failure', metavar="false|true", type="choice", choices=['false', 'true'],
        default='true')
    group.addoption(
        "--splinter-screenshot-dir",
        help="pytest-splinter browser screenshot directory. Defaults to the current directory.", action="store",
        dest='splinter_screenshot_dir', metavar="DIR", default='.')
    group.addoption(
        "--splinter-webdriver-executable",
        help="pytest-splinter webdrive executable path. Defaults to unspecified in which case it is taken from PATH",
        action="store",
        dest='splinter_webdriver_executable', metavar="DIR", default='')