text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using Hpdi.VssLogicalLib;

namespace Hpdi.Vss2Svn
{
    /// <summary>
    /// Replays and commits changesets into a new Git repository.
    /// </summary>
    /// <author>Trevor Robinson</author>
    class GitExporter : Worker
    {
        private const string DefaultComment = "";

        private readonly VssDatabase database;
        private readonly RevisionAnalyzer revisionAnalyzer;
        private readonly ChangesetBuilder changesetBuilder;
        private readonly StreamCopier streamCopier = new StreamCopier();
        private readonly HashSet<string> tagsUsed = new HashSet<string>();

        private string emailDomain = "localhost";
        public string EmailDomain
        {
            get { return emailDomain; }
            set { emailDomain = value; }
        }

        private Encoding commitEncoding = Encoding.UTF8;
        public Encoding CommitEncoding
        {
            get { return commitEncoding; }
            set { commitEncoding = value; }
        }

        private bool forceAnnotatedTags = true;
        public bool ForceAnnotatedTags
        {
            get { return forceAnnotatedTags; }
            set { forceAnnotatedTags = value; }
        }

        public GitExporter(WorkQueue workQueue, Logger logger,
            RevisionAnalyzer revisionAnalyzer, ChangesetBuilder changesetBuilder)
            : base(workQueue, logger)
        {
            this.database = revisionAnalyzer.Database;
            this.revisionAnalyzer = revisionAnalyzer;
            this.changesetBuilder = changesetBuilder;
        }

        public void ExportToGit(string repoPath, bool inheritProjectDir)
        {
            workQueue.AddLast(delegate(object work)
            {
                var stopwatch = Stopwatch.StartNew();

                logger.WriteSectionSeparator();
                LogStatus(work, "Initializing Git repository");

                // create repository directory if it does not exist
                if (!Directory.Exists(repoPath))
                {
                    Directory.CreateDirectory(repoPath);
                }

                var git = new GitWrapper(repoPath, logger);
                git.CommitEncoding = commitEncoding;

                while (!git.FindExecutable())
                {
                    var button = MessageBox.Show("Git not found in PATH. " +
                        "If you need to modify your PATH variable, please " +
                        "restart the program for the changes to take effect.",
                        "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                    if (button == DialogResult.Cancel)
                    {
                        workQueue.Abort();
                        return;
                    }
                }

                if (!RetryCancel(delegate { git.Init(); }))
                {
                    return;
                }

                if (commitEncoding.WebName != "utf-8")
                {
                    AbortRetryIgnore(delegate
                    {
                        git.SetConfig("i18n.commitencoding", commitEncoding.WebName);
                    });
                }

                var pathMapper = new VssPathMapper();

                // create mappings for root projects
                foreach (var rootProject in revisionAnalyzer.RootProjects)
                {
                    var rootPath = inheritProjectDir?VssPathMapper.GetWorkingPath(repoPath, rootProject.Path):repoPath;
                    pathMapper.SetProjectPath(rootProject.PhysicalName, rootPath, rootProject.Path);
                }

                // replay each changeset
                var changesetId = 1;
                var changesets = changesetBuilder.Changesets;
                var commitCount = 0;
                var tagCount = 0;
                var replayStopwatch = new Stopwatch();
                var labels = new LinkedList<Revision>();
                tagsUsed.Clear();
                foreach (var changeset in changesets)
                {
                    var changesetDesc = string.Format(CultureInfo.InvariantCulture,
                        "changeset {0} from {1}", changesetId, changeset.DateTime);

                    // replay each revision in changeset
                    LogStatus(work, "Replaying " + changesetDesc);
                    labels.Clear();
                    replayStopwatch.Start();
                    bool needCommit;
                    try
                    {
                        needCommit = ReplayChangeset(pathMapper, changeset, git, labels);
                    }
                    finally
                    {
                        replayStopwatch.Stop();
                    }

                    if (workQueue.IsAborting)
                    {
                        return;
                    }

                    // commit changes
                    if (needCommit)
                    {
                        LogStatus(work, "Committing " + changesetDesc);
                        if (CommitChangeset(git, changeset))
                        {
                            ++commitCount;
                        }
                    }

                    if (workQueue.IsAborting)
                    {
                        return;
                    }

                    // create tags for any labels in the changeset
                    if (labels.Count > 0)
                    {
                        foreach (Revision label in labels)
                        {
                            var labelName = ((VssLabelAction)label.Action).Label;
                            if (string.IsNullOrEmpty(labelName))
                            {
                                logger.WriteLine("NOTE: Ignoring empty label");
                            }
                            else if (commitCount == 0)
                            {
                                logger.WriteLine("NOTE: Ignoring label '{0}' before initial commit", labelName);
                            }
                            else
                            {
                                var tagName = GetTagFromLabel(labelName);

                                var tagMessage = "Creating tag " + tagName;
                                if (tagName != labelName)
                                {
                                    tagMessage += " for label '" + labelName + "'";
                                }
                                LogStatus(work, tagMessage);

                                // annotated tags require (and are implied by) a tag message;
                                // tools like Mercurial's git converter only import annotated tags
                                var tagComment = label.Comment;
                                if (string.IsNullOrEmpty(tagComment) && forceAnnotatedTags)
                                {
                                    // use the original VSS label as the tag message if none was provided
                                    tagComment = labelName;
                                }

                                if (AbortRetryIgnore(
                                    delegate
                                    {
                                        git.Tag(tagName, label.User, GetEmail(label.User),
                                            tagComment, label.DateTime);
                                    }))
                                {
                                    ++tagCount;
                                }
                            }
                        }
                    }

                    ++changesetId;
                }

                stopwatch.Stop();

                logger.WriteSectionSeparator();
                logger.WriteLine("Git export complete in {0:HH:mm:ss}", new DateTime(stopwatch.ElapsedTicks));
                logger.WriteLine("Replay time: {0:HH:mm:ss}", new DateTime(replayStopwatch.ElapsedTicks));
                logger.WriteLine("Git time: {0:HH:mm:ss}", new DateTime(git.ElapsedTime.Ticks));
                logger.WriteLine("Git commits: {0}", commitCount);
                logger.WriteLine("Git tags: {0}", tagCount);
            });
        }

        private bool ReplayChangeset(VssPathMapper pathMapper, Changeset changeset,
            GitWrapper git, LinkedList<Revision> labels)
        {
            var needCommit = false;
            foreach (Revision revision in changeset.Revisions)
            {
                if (workQueue.IsAborting)
                {
                    break;
                }

                AbortRetryIgnore(delegate
                {
                    needCommit |= ReplayRevision(pathMapper, revision, git, labels);
                });
            }
            return needCommit;
        }

        private bool ReplayRevision(VssPathMapper pathMapper, Revision revision,
            GitWrapper git, LinkedList<Revision> labels)
        {
            var needCommit = false;
            var actionType = revision.Action.Type;
            if (revision.Item.IsProject)
            {
                // note that project path (and therefore target path) can be
                // null if a project was moved and its original location was
                // subsequently destroyed
                var project = revision.Item;
                var projectName = project.LogicalName;
                var projectPath = pathMapper.GetProjectPath(project.PhysicalName);
                var projectDesc = projectPath;
                if (projectPath == null)
                {
                    projectDesc = revision.Item.ToString();
                    logger.WriteLine("NOTE: {0} is currently unmapped", project);
                }

                VssItemName target = null;
                string targetPath = null;
                var namedAction = revision.Action as VssNamedAction;
                if (namedAction != null)
                {
                    target = namedAction.Name;
                    if (projectPath != null)
                    {
                        targetPath = Path.Combine(projectPath, target.LogicalName);
                    }
                }

                bool isAddAction = false;
                bool writeProject = false;
                bool writeFile = false;
                VssItemInfo itemInfo = null;
                switch (actionType)
                {
                    case VssActionType.Label:
                        // defer tagging until after commit
                        labels.AddLast(revision);
                        break;

                    case VssActionType.Create:
                        // ignored; items are actually created when added to a project
                        break;

                    case VssActionType.Add:
                    case VssActionType.Share:
                        logger.WriteLine("{0}: {1} {2}", projectDesc, actionType, target.LogicalName);
                        itemInfo = pathMapper.AddItem(project, target);
                        isAddAction = true;
                        break;

                    case VssActionType.Recover:
                        logger.WriteLine("{0}: {1} {2}", projectDesc, actionType, target.LogicalName);
                        itemInfo = pathMapper.RecoverItem(project, target);
                        isAddAction = true;
                        break;

                    case VssActionType.Delete:
                    case VssActionType.Destroy:
                        {
                            logger.WriteLine("{0}: {1} {2}", projectDesc, actionType, target.LogicalName);
                            itemInfo = pathMapper.DeleteItem(project, target);
                            if (targetPath != null && !itemInfo.Destroyed)
                            {
                                if (target.IsProject)
                                {
                                    if (Directory.Exists(targetPath))
                                    {
                                        if (((VssProjectInfo)itemInfo).ContainsFiles())
                                        {
                                            git.Remove(targetPath, true);
                                            needCommit = true;
                                        }
                                        else
                                        {
                                            // git doesn't care about directories with no files
                                            Directory.Delete(targetPath, true);
                                        }
                                    }
                                }
                                else
                                {
                                    if (File.Exists(targetPath))
                                    {
                                        // not sure how it can happen, but a project can evidently
                                        // contain another file with the same logical name, so check
                                        // that this is not the case before deleting the file
                                        if (pathMapper.ProjectContainsLogicalName(project, target))
                                        {
                                            logger.WriteLine("NOTE: {0} contains another file named {1}; not deleting file",
                                                projectDesc, target.LogicalName);
                                        }
                                        else
                                        {
                                            File.Delete(targetPath);
                                            needCommit = true;
                                        }
                                    }
                                }
                            }
                        }
                        break;

                    case VssActionType.Rename:
                        {
                            var renameAction = (VssRenameAction)revision.Action;
                            logger.WriteLine("{0}: {1} {2} to {3}",
                                projectDesc, actionType, renameAction.OriginalName, target.LogicalName);
                            itemInfo = pathMapper.RenameItem(target);
                            if (targetPath != null && !itemInfo.Destroyed)
                            {
                                var sourcePath = Path.Combine(projectPath, renameAction.OriginalName);
                                if (target.IsProject ? Directory.Exists(sourcePath) : File.Exists(sourcePath))
                                {
                                    // renaming a file or a project that contains files?
                                    var projectInfo = itemInfo as VssProjectInfo;
                                    if (projectInfo == null || projectInfo.ContainsFiles())
                                    {
                                        CaseSensitiveRename(sourcePath, targetPath, git.Move);
                                        needCommit = true;
                                    }
                                    else
                                    {
                                        // git doesn't care about directories with no files
                                        CaseSensitiveRename(sourcePath, targetPath, Directory.Move);
                                    }
                                }
                                else
                                {
                                    logger.WriteLine("NOTE: Skipping rename because {0} does not exist", sourcePath);
                                }
                            }
                        }
                        break;

                    case VssActionType.MoveFrom:
                        // if both MoveFrom & MoveTo are present (e.g.
                        // one of them has not been destroyed), only one
                        // can succeed, so check that the source exists
                        {
                            var moveFromAction = (VssMoveFromAction)revision.Action;
                            logger.WriteLine("{0}: Move from {1} to {2}",
                                projectDesc, moveFromAction.OriginalProject, targetPath ?? target.LogicalName);
                            var sourcePath = pathMapper.GetProjectPath(target.PhysicalName);
                            var projectInfo = pathMapper.MoveProjectFrom(
                                project, target, moveFromAction.OriginalProject);
                            if (targetPath != null && !projectInfo.Destroyed)
                            {
                                if (sourcePath != null && Directory.Exists(sourcePath))
                                {
                                    if (projectInfo.ContainsFiles())
                                    {
                                        git.Move(sourcePath, targetPath);
                                        needCommit = true;
                                    }
                                    else
                                    {
                                        // git doesn't care about directories with no files
                                        Directory.Move(sourcePath, targetPath);
                                    }
                                }
                                else
                                {
                                    // project was moved from a now-destroyed project
                                    writeProject = true;
                                }
                            }
                        }
                        break;

                    case VssActionType.MoveTo:
                        {
                            // handle actual moves in MoveFrom; this just does cleanup of destroyed projects
                            var moveToAction = (VssMoveToAction)revision.Action;
                            logger.WriteLine("{0}: Move to {1} from {2}",
                                projectDesc, moveToAction.NewProject, targetPath ?? target.LogicalName);
                            var projectInfo = pathMapper.MoveProjectTo(
                                project, target, moveToAction.NewProject);
                            if (projectInfo.Destroyed && targetPath != null && Directory.Exists(targetPath))
                            {
                                // project was moved to a now-destroyed project; remove empty directory
                                Directory.Delete(targetPath, true);
                            }
                        }
                        break;

                    case VssActionType.Pin:
                        {
                            var pinAction = (VssPinAction)revision.Action;
                            if (pinAction.Pinned)
                            {
                                logger.WriteLine("{0}: Pin {1}", projectDesc, target.LogicalName);
                                itemInfo = pathMapper.PinItem(project, target);
                            }
                            else
                            {
                                logger.WriteLine("{0}: Unpin {1}", projectDesc, target.LogicalName);
                                itemInfo = pathMapper.UnpinItem(project, target);
                                writeFile = !itemInfo.Destroyed;
                            }
                        }
                        break;

                    case VssActionType.Branch:
                        {
                            var branchAction = (VssBranchAction)revision.Action;
                            logger.WriteLine("{0}: {1} {2}", projectDesc, actionType, target.LogicalName);
                            itemInfo = pathMapper.BranchFile(project, target, branchAction.Source);
                            // branching within the project might happen after branching of the file
                            writeFile = true;
                        }
                        break;

                    case VssActionType.Archive:
                        // currently ignored
                        {
                            var archiveAction = (VssArchiveAction)revision.Action;
                            logger.WriteLine("{0}: Archive {1} to {2} (ignored)",
                                projectDesc, target.LogicalName, archiveAction.ArchivePath);
                        }
                        break;

                    case VssActionType.Restore:
                        {
                            var restoreAction = (VssRestoreAction)revision.Action;
                            logger.WriteLine("{0}: Restore {1} from archive {2}",
                                projectDesc, target.LogicalName, restoreAction.ArchivePath);
                            itemInfo = pathMapper.AddItem(project, target);
                            isAddAction = true;
                        }
                        break;
                }

                if (targetPath != null)
                {
                    if (isAddAction)
                    {
                        if (revisionAnalyzer.IsDestroyed(target.PhysicalName) &&
                            !database.ItemExists(target.PhysicalName))
                        {
                            logger.WriteLine("NOTE: Skipping destroyed file: {0}", targetPath);
                            itemInfo.Destroyed = true;
                        }
                        else if (target.IsProject)
                        {
                            Directory.CreateDirectory(targetPath);
                            writeProject = true;
                        }
                        else
                        {
                            writeFile = true;
                        }
                    }

                    if (writeProject && pathMapper.IsProjectRooted(target.PhysicalName))
                    {
                        // create all contained subdirectories
                        foreach (var projectInfo in pathMapper.GetAllProjects(target.PhysicalName))
                        {
                            logger.WriteLine("{0}: Creating subdirectory {1}",
                                projectDesc, projectInfo.LogicalName);
                            Directory.CreateDirectory(projectInfo.GetPath());
                        }

                        // write current rev of all contained files
                        foreach (var fileInfo in pathMapper.GetAllFiles(target.PhysicalName))
                        {
                            if (WriteRevision(pathMapper, actionType, fileInfo.PhysicalName,
                                fileInfo.Version, target.PhysicalName, git))
                            {
                                // one or more files were written
                                needCommit = true;
                            }
                        }
                    }
                    else if (writeFile)
                    {
                        // write current rev to working path
                        int version = pathMapper.GetFileVersion(target.PhysicalName);
                        if (WriteRevisionTo(target.PhysicalName, version, targetPath))
                        {
                            // add file explicitly, so it is visible to subsequent git operations
                            git.Add(targetPath);
                            needCommit = true;
                        }
                    }
                }
            }
            // item is a file, not a project
            else if (actionType == VssActionType.Edit || actionType == VssActionType.Branch)
            {
                // if the action is Branch, the following code is necessary only if the item
                // was branched from a file that is not part of the migration subset; it will
                // make sure we start with the correct revision instead of the first revision

                var target = revision.Item;

                // update current rev
                pathMapper.SetFileVersion(target, revision.Version);

                // write current rev to all sharing projects
                WriteRevision(pathMapper, actionType, target.PhysicalName,
                    revision.Version, null, git);
                needCommit = true;
            }
            return needCommit;
        }

        private bool CommitChangeset(GitWrapper git, Changeset changeset)
        {
            var result = false;
            AbortRetryIgnore(delegate
            {
                result = git.AddAll() &&
                    git.Commit(changeset.User, GetEmail(changeset.User),
                    changeset.Comment ?? DefaultComment, changeset.DateTime);
            });
            return result;
        }

        private bool RetryCancel(ThreadStart work)
        {
            return AbortRetryIgnore(work, MessageBoxButtons.RetryCancel);
        }

        private bool AbortRetryIgnore(ThreadStart work)
        {
            return AbortRetryIgnore(work, MessageBoxButtons.AbortRetryIgnore);
        }

        private bool AbortRetryIgnore(ThreadStart work, MessageBoxButtons buttons)
        {
            bool retry;
            do
            {
                try
                {
                    work();
                    return true;
                }
                catch (Exception e)
                {
                    var message = LogException(e);

                    message += "\nSee log file for more information.";

                    var button = MessageBox.Show(message, "Error", buttons, MessageBoxIcon.Error);
                    switch (button)
                    {
                        case DialogResult.Retry:
                            retry = true;
                            break;
                        case DialogResult.Ignore:
                            retry = false;
                            break;
                        default:
                            retry = false;
                            workQueue.Abort();
                            break;
                    }
                }
            } while (retry);
            return false;
        }

        private string GetEmail(string user)
        {
            // TODO: user-defined mapping of user names to email addresses
            return user.ToLower().Replace(' ', '.') + "@" + emailDomain;
        }

        private string GetTagFromLabel(string label)
        {
            // git tag names must be valid filenames, so replace sequences of
            // invalid characters with an underscore
            var baseTag = Regex.Replace(label, "[^A-Za-z0-9_-]+", "_");

            // git tags are global, whereas VSS tags are local, so ensure
            // global uniqueness by appending a number; since the file system
            // may be case-insensitive, ignore case when hashing tags
            var tag = baseTag;
            for (int i = 2; !tagsUsed.Add(tag.ToUpperInvariant()); ++i)
            {
                tag = baseTag + "-" + i;
            }

            return tag;
        }

        private bool WriteRevision(VssPathMapper pathMapper, VssActionType actionType,
            string physicalName, int version, string underProject, GitWrapper git)
        {
            var needCommit = false;
            var paths = pathMapper.GetFilePaths(physicalName, underProject);
            foreach (string path in paths)
            {
                logger.WriteLine("{0}: {1} revision {2}", path, actionType, version);
                if (WriteRevisionTo(physicalName, version, path))
                {
                    // add file explicitly, so it is visible to subsequent git operations
                    git.Add(path);
                    needCommit = true;
                }
            }
            return needCommit;
        }

        private bool WriteRevisionTo(string physical, int version, string destPath)
        {
            VssFile item;
            VssFileRevision revision;
            Stream contents;
            try
            {
                item = (VssFile)database.GetItemPhysical(physical);
                revision = item.GetRevision(version);
                contents = revision.GetContents();
            }
            catch (Exception e)
            {
                // log an error for missing data files or versions, but keep processing
                var message = ExceptionFormatter.Format(e);
                logger.WriteLine("ERROR: {0}", message);
                logger.WriteLine(e);
                return false;
            }

            // propagate exceptions here (e.g. disk full) to abort/retry/ignore
            using (contents)
            {
                WriteStream(contents, destPath);
            }

            // try to use the first revision (for this branch) as the create time,
            // since the item creation time doesn't seem to be meaningful
            var createDateTime = item.Created;
            using (var revEnum = item.Revisions.GetEnumerator())
            {
                if (revEnum.MoveNext())
                {
                    createDateTime = revEnum.Current.DateTime;
                }
            }

            // set file creation and update timestamps
            File.SetCreationTimeUtc(destPath, TimeZoneInfo.ConvertTimeToUtc(createDateTime));
            File.SetLastWriteTimeUtc(destPath, TimeZoneInfo.ConvertTimeToUtc(revision.DateTime));

            return true;
        }

        private void WriteStream(Stream inputStream, string path)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(path));

            using (var outputStream = new FileStream(
                path, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                streamCopier.Copy(inputStream, outputStream);
            }
        }

        private delegate void RenameDelegate(string sourcePath, string destPath);

        private void CaseSensitiveRename(string sourcePath, string destPath, RenameDelegate renamer)
        {
            if (sourcePath.Equals(destPath, StringComparison.OrdinalIgnoreCase))
            {
                // workaround for case-only renames on case-insensitive file systems:

                var sourceDir = Path.GetDirectoryName(sourcePath);
                var sourceFile = Path.GetFileName(sourcePath);
                var destDir = Path.GetDirectoryName(destPath);
                var destFile = Path.GetFileName(destPath);

                if (sourceDir != destDir)
                {
                    // recursively rename containing directories that differ in case
                    CaseSensitiveRename(sourceDir, destDir, renamer);

                    // fix up source path based on renamed directory
                    sourcePath = Path.Combine(destDir, sourceFile);
                }

                if (sourceFile != destFile)
                {
                    // use temporary filename to rename files that differ in case
                    var tempPath = sourcePath + ".mvtmp";
                    CaseSensitiveRename(sourcePath, tempPath, renamer);
                    CaseSensitiveRename(tempPath, destPath, renamer);
                }
            }
            else
            {
                renamer(sourcePath, destPath);
            }
        }
    }
}


text:
#include <openssl/rand.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/bio.h>
#include <openssl/rand.h>
#include <openssl_constants.h>
#include <openssl_pkey.h>
#include <axis2_util.h>
#include <oxs_buffer.h>

/**
  * @file openssl_rsa.h
  * @brief For RSA encryption.
  */
#ifndef OPENSSL_RSA_H
#define OPENSSL_RSA_H

#ifdef __cplusplus
extern "C" {
#endif

    /** @defgroup openssl_rsa OpenSSL RSA
     * @ingroup openssl
     * @{
     */

    /**
      * Decrypts data using a private key specified in @pkey
      * @rsa pointer to openssl_rsa struct
      * @env pointer to environment struct
      * @pkey private key for decryption
      * @in input data
      * @out output data
      * @return AXIS2_SUCCESS on success, else AXIS2_FAILURE
      **/
    int AXIS2_CALL
    openssl_rsa_prv_decrypt(
        const axutil_env_t *env,
        const openssl_pkey_t *pkey,
        const axis2_char_t *padding,
        oxs_buffer_t *in,
        oxs_buffer_t *out);

    /**
      * Encrypts data using a public key specified in @pkey
      * @rsa pointer to openssl_rsa struct
      * @env pointer to environment struct
      * @pkey public key for encryption
      * @in input data
      * @out output data
      * @return AXIS2_SUCCESS on success, else AXIS2_FAILURE
      **/
    int AXIS2_CALL
    openssl_rsa_pub_encrypt(
        const axutil_env_t *env,
        const openssl_pkey_t *pkey,
        const axis2_char_t *padding,
        oxs_buffer_t *in,
        oxs_buffer_t *out);

    /**
      * Sign data using a private key specified in @pkey
      * @rsa pointer to openssl_rsa struct
      * @env pointer to environment struct
      * @pkey private key for decryption
      * @in input data
      * @out output data
      * @return AXIS2_SUCCESS on success, else AXIS2_FAILURE
      **/
    int AXIS2_CALL
    openssl_rsa_prv_encrypt(
        const axutil_env_t *env,
        const openssl_pkey_t *pkey,
        const axis2_char_t *padding,
        oxs_buffer_t *in,
        oxs_buffer_t *out);

    /**
      * Verifies data using a public key specified in @pkey
      * @rsa pointer to openssl_rsa struct
      * @env pointer to environment struct
      * @pkey public key for encryption
      * @in input data
      * @out output data
      * @return AXIS2_SUCCESS on success, else AXIS2_FAILURE
      **/
    int AXIS2_CALL
    openssl_rsa_pub_decrypt(
        const axutil_env_t *env,
        const openssl_pkey_t *pkey,
        const axis2_char_t *padding,
        oxs_buffer_t *in,
        oxs_buffer_t *out);

    /** @} */
#ifdef __cplusplus
}
#endif

#endif    /* OPENSSL_RSA_H */

redpajama_set_name: RedPajamaGithub


text:
import sys
import re

class Operators():
    def __init__(self, length):
        self.operatorlist = []
        self.length = length
        for i in range(length):
            self.operatorlist.append('+')
        self.current = length - 1
        self.alphabet = ('+','','+-')

    def create_next_configuration(self):
        operator_list_index = self.current
        if self.current > -1:
            operator = self.operatorlist[operator_list_index]
            alphabet_index = self.alphabet.index(operator)
            next_alph_index = (alphabet_index + 1) % 3
            next_operator = self.alphabet[next_alph_index]
            self.operatorlist[operator_list_index] = next_operator
            if next_operator == '+':
                self.current = operator_list_index - 1
                self.create_next_configuration()

class Sums():
    def __init__(self, digitstring):
        self.generator = digitstring
        self.evaluated_sums_with_count = dict()
        self.combined_current = ''
        self.evaluated_sum = ''

    def evaluate(self):
        separated_sum = self.combined_current.split('+')
        total = 0
        for number in separated_sum:
            total += int(number)
        self.evaluated_sum = total

    def track_count(self):
        total_exists = self.evaluated_sums_with_count.has_key(self.evaluated_sum)
        total = self.evaluated_sum
        if total_exists:
            count_of_total = self.evaluated_sums_with_count.get(total) + 1
            self.evaluated_sums_with_count[total] = count_of_total
        else:
            self.evaluated_sums_with_count[total] = 1

    def combine_operators_with_generator(self, operators):
        operators = operators.operatorlist
        generator = self.generator
        combined = generator[0]
        for i in range(len(generator) - 1):
            combined += operators[i]
            combined += generator[i + 1]
        self.combined_current = combined

def is_ugly(number):
    isugly = False
    single_digit_primes = [2, 3, 5, 7]
    for prime in single_digit_primes:
        if number % prime == 0:
            isugly = True
            break
    return isugly

test_cases = open(sys.argv[1], 'r')

for test in test_cases:
    strippedtest = test.strip('\n')
    zerocountorig = strippedtest.count('0')
    multiplezeroregex = re.compile('00+')
    strippedtest = multiplezeroregex.sub('0', strippedtest)
    zerocountremaining = strippedtest.count('0')
    zeroaccountfor = zerocountorig - zerocountremaining
    if strippedtest:
        totaluglys = 0
        sums = Sums(strippedtest)
        test_length = len(strippedtest)
        remaining_configurations = pow(3, test_length - 1)
        operators = Operators(test_length - 1)
        while remaining_configurations > 0 :
            sums.combine_operators_with_generator(operators)
            sums.evaluate()
            sums.track_count()
            operators.current = operators.length - 1
            operators.create_next_configuration()
            remaining_configurations -= 1
        for evaluated_sum in sums.evaluated_sums_with_count:
            if is_ugly(evaluated_sum):
                totaluglys += sums.evaluated_sums_with_count[evaluated_sum]
        totaluglys = totaluglys * pow(3, zeroaccountfor)
        print totaluglys

test_cases.close()


text:
HumanFaktor::Application.routes.draw do

  ###
  # routes for base
  #

  # NNB: be sure to update the subdomain validator options for account to
  #      include these paths as restricted names

  get "contact", :to => 'home#contact', :as => :home_contact
  get "features", :to => 'home#features', :as => :home_features
  get "subscriptions", :to => 'home#subscriptions', :as => :home_subscriptions
  get "terms", :to => 'home#terms', :as => :home_terms
  get "privacy", :to => 'home#privacy', :as => :home_privacy
  get "partner", :to => 'home#partner', :as => :home_partner
  get "sign_in", :to => 'home#sign_in', :as => :home_sign_in

  get "demo_request", :to => 'demo_requests#new', :as => :new_demo_request
  post "demo_request", :to => 'demo_requests#create', :as => :create_demo_request

  get "registrations/new", :to => 'registrations#new', :as => :new_account_registration
  post "registrations", :to => 'registrations#create', :as => :create_account_registration
  get "registrations/:id", :to => 'registrations#show', :as => :account_registration
  get "registrations/:id/query/:started(.:format)", :to => 'registrations#query', :as => :query_account_registration

  ###
  # routes for tenant administration
  #

  scope 'admin' do

    devise_for :tenant_admins, :path => "" do
      # TODO: additional configuration for devise
    end

    get "impersonate/:id", :to => 'tenant_admin#impersonate', :as => :impersonate
    get ":id", :to => 'tenant_admin#show', :as => :show_account
    get "/", :to => 'tenant_admin#index', :as => :tenant_admin

  end

  ###
  # routes for tenant
  #

  # NOTE: this part of the route is "globbed" and there are some issues
  #       in Rails when there are nested routes, so a `:tenant => current_account.subdomain` option
  #       is required for url helpers when constructing paths
  scope "*tenant" do

    get "setup", :to => "tenant/account_setup#edit", :as => :account_setup
    put "setup", :to => "tenant/account_setup#update", :as => :update_account_setup

    devise_for :employees, :path => "" do
      # TODO: additional configuration for devise
    end

    get "welcome", :to => "tenant/dashboard#welcome", :as => :welcome

    # dashboard
    get "balance", :to => "tenant/dashboard#balance", :as => :balance

    get "staff_balance", :to => "tenant/dashboard#staff_balance", :as => :staff_balance
    post "staff_balance", :to => "tenant/dashboard#staff_balance"

    get "calendar", :to => "tenant/dashboard#calendar", :as => :calendar

    get "staff_calendar", :to => "tenant/dashboard#staff_calendar", :as => :staff_calendar
    post "staff_calendar", :to => "tenant/dashboard#staff_calendar"

    get "heatmap", :to => "tenant/dashboard#heatmap", :as => :heatmap
    post "heatmap", :to => "tenant/dashboard#heatmap"

    get "help", :to => "tenant/dashboard#help", :as => :help

    # profile
    get "activate", :to => "tenant/profile#activate", :as => :activate
    put "activate", :to => "tenant/profile#setactive", :as => :activate

    get "profile", :to => "tenant/profile#edit", :as => :profile
    put "profile", :to => "tenant/profile#update", :as => :update_profile

    # employee leave requests
    get "leave", :to => "tenant/employee_leave_requests#index", :as => :employee_leave_requests
    post "leave", :to => "tenant/employee_leave_requests#index"
    get "leave/new", :to => "tenant/employee_leave_requests#new", :as => :new_employee_leave_request
    post "leave/new", :to => "tenant/employee_leave_requests#create", :as => :create_employee_leave_request

    get "staff_leave_summary", :to => "tenant/dashboard#staff_leave_summary", :as => :staff_leave_summary
    post "staff_leave_summary", :to => "tenant/dashboard#staff_leave_summary"

    # staff leave requests
    get "staff_leave", :to => "tenant/staff_leave_requests#index", :as => :staff_leave_requests
    post "staff_leave", :to => "tenant/staff_leave_requests#index"
    get "staff_leave/new", :to => "tenant/staff_leave_requests#new", :as => :new_staff_leave_request
    post "staff_leave/new", :to => "tenant/staff_leave_requests#create", :as => :create_staff_leave_request

    # both employee and staff leave requests
    resources :leave_requests, :path => '/leave', :module => 'tenant', :except => [:index, :new, :create, :edit, :update, :destroy] do
      member do
        get 'amend'
        put 'confirm'
        put 'approve'
        put 'decline'
        put 'cancel'
        put 'reinstate'
        put 'update_constraints'
        put 'update_document'
        delete 'remove_document'
      end
    end

    get "leave_balance", :to => "tenant/leave_requests#balance", :as => :leave_balance

    # data feeds
    get "calendar_entries_feed(.:format)", :to => "tenant/data_feeds#calendar_entries", :as => :calendar_entries_feed
    get "leave_requests_feed(.:format)", :to => "tenant/data_feeds#leave_requests", :as => :leave_requests_feed

    scope "account" do

      get "edit", :to => "tenant/account#edit", :as => :edit_account
      put "edit", :to => "tenant/account#update", :as => :update_account

      get "policies", :to => "tenant/leave_types#edit", :as => :edit_leave_types
      put "policies", :to => "tenant/leave_types#update", :as => :update_leave_types

      resources :locations, :module => 'tenant'
      resources :departments, :module => 'tenant'

      resources :employees, :module => 'tenant' do
        collection do
          get 'filtered'
          post 'filtered'
        end

        member do
          put 'deactivate'
          put 'reactivate'
        end
      end

      get "employee_balance(.:format)", :to => "tenant/employees#balance", :as => :employee_balance

      resources :bulk_uploads, :module => 'tenant', :except => [:index] do
        member do
          get 'download'
        end
        get 'template', :on => :collection, :as => :template
        get 'records', :to => 'bulk_upload_stages#index', :as => :records
        put 'records', :to => 'bulk_upload_stages#index'
      end

      get "/", :to => "tenant/account#index", :as => :account

    end

    get "/", :to => "tenant/dashboard#index", :as => :dashboard

  end

  root :to => "home#index"

end


text:
using HydrantWiki.Forms;
using HydrantWiki.Interfaces;
using HydrantWiki.Managers;
using HydrantWiki.Objects;
using Xamarin.Forms;

namespace HydrantWiki
{
    public class HydrantWikiApp : Application
    {
        public static string DataFolder;
        public static string ImageFolder;
        public static int ScreenWidth;
        public static int ScreenHeight;

        public static User User { get; set; }
        public IPlatformManager m_PlatformManager;

        public HydrantWikiApp(
            IPlatformManager _platformManager)
        {
            m_PlatformManager = _platformManager;

            DataFolder = m_PlatformManager.DataFolder;
            ImageFolder = m_PlatformManager.ImageFolder;

            HWManager manager = HWManager.GetInstance();
            manager.PlatformManager = m_PlatformManager;

            User = manager.SettingManager.GetUser();

            // The root page of your application
            MainPage = new MainForm();
        }

        public IPlatformManager PlatformManager
        {
            get
            {
                return m_PlatformManager;
            }
        }

        protected override void OnStart()
        {

        }

        protected override void OnSleep()
        {

        }

        protected override void OnResume()
        {

        }

    }
}


text:
class FamilyAddTable < ActiveRecord::Migration
  def self.up
    create_table :families do |t|
      t.timestamps
    end
  end

  def self.down
    drop_table :families
  end
end


text:
package org.apache.synapse.message.processor.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.SynapseException;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.core.SynapseEnvironment;
import org.apache.synapse.message.MessageConsumer;
import org.apache.synapse.message.processor.MessageProcessor;

import java.util.Map;

/**
 * Class AbstractMessageProcessor is handles Message processing of the messages
 * in Message Store. Abstract Message Store is assumes that Message processors can be implemented
 * using the quartz scheduler jobs. If in case we user wants a different implementation They can
 * directly use MessageProcessor interface for that implementations
 */
public abstract class AbstractMessageProcessor implements MessageProcessor {
    private static final Log logger = LogFactory.getLog(AbstractMessageProcessor.class.getName());

    /** Message Store associated with Message processor */
    protected String  messageStore;

    protected String description;

    protected String name;

    protected String fileName;

    protected SynapseConfiguration configuration;

    protected MessageConsumer messageConsumer;

    /** This attribute is only need for forwarding message processor. However, it here because
     * then we don't need to implement this in sampling processor with nothing */
    protected String targetEndpoint;

    /**message store parameters */
    protected Map<String, Object> parameters = null;

    public void init(SynapseEnvironment se) {
        configuration = se.getSynapseConfiguration();
    }

    public void setMessageStoreName(String  messageStore) {
        if (messageStore != null) {
            this.messageStore = messageStore;
        } else {
            throw new SynapseException("Error Can't set Message store to null");
        }
    }

    public String getMessageStoreName() {
        return messageStore;
    }

    public void setParameters(Map<String, Object> parameters) {
        this.parameters = parameters;
    }

    public Map<String, Object> getParameters() {
        return parameters;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setDescription(String description) {
        this.description=description;
    }

    public String getDescription() {
        return description;
    }

    public void setFileName(String filename) {
        this.fileName = filename;
    }

    public String getFileName() {
        return fileName;
    }

    public MessageConsumer getMessageConsumer() {
        return messageConsumer;
    }

    public boolean setMessageConsumer(MessageConsumer consumer) {
        if (consumer == null) {
            logger.error("[" + getName() + "] Faulty message consumer.");
            return false;
        }

        if (messageConsumer != null) {
            messageConsumer.cleanup();
        }

        messageConsumer = consumer;

        return true;
    }

    public void setTargetEndpoint(String targetEndpoint) {
        this.targetEndpoint = targetEndpoint;
    }

    public String getTargetEndpoint() {
        return targetEndpoint;
    }
}


text:
'use strict';
const {Botkit} = require('botkit');
const {TurnContext} = require('botbuilder');
const {setTimeoutAsync} = require('./utils');

class BotMock extends Botkit {
	static get defaultFields() {
		return {
			CHANNEL: 'BotMock-default-channel',
			TEAM: 'BotMock-default-channel',
			MESSAGE_TYPE: 'direct_message'
		}
	}

	constructor(config) {
		// try to disable botkit warning if config has no disable_console property
		if(!(config).hasOwnProperty('disable_console')){
			config.disable_console = true;
		}
		// try to disable botkit server if config has no disable_webserver property
		if(!(config).hasOwnProperty('disable_webserver')){
			config.disable_webserver = true;
		}
		super(config);
		this.detailed_answers = {};
		this.adapter._originSendActivities = this.adapter.sendActivities;
		this.adapter.sendActivities = this._sendActivities.bind(this);
	}

	/**
	 * Override of botkit.adapter.sendActivities to track history of sent messages.
	 * The function must be async because original fn botkit.adapter.sendActivities
	 * returns promise.
	 * @param context
	 * @param activities
	 * @returns {Promise<void>}
	 * @private
	 */
	async _sendActivities(context, activities) {
		for (let activity of activities) {
			if (Array.isArray(this.detailed_answers[activity.conversation.id])) {
				this.detailed_answers[activity.conversation.id].push(activity);
			} else {
				this.detailed_answers[activity.conversation.id] = [activity];
			}
		}
	}

	/**
	 * The function interpolate sequence of messages into events for botkit.
	 * @param userSequences
	 * @returns {Promise<void>}
	 */
	async usersInput(userSequences) {
		const {defaultFields} = this.constructor;

		for (let userSequence of userSequences) {
			for (let message of userSequence.messages) {
				// build activity in botkit format
				const activity = {
					id: message.id || null,
					timestamp: new Date(),
					channelId: 'slack',
					conversation: {
						id: message.channel || userSequence.channel || defaultFields.CHANNEL,
						team: message.team || userSequence.team || defaultFields.TEAM,
						thread_ts: message.thread_ts || null
					},
					from: {id: userSequence.user || message.user || null},
					recipient: {id: message.recipient},
					channelData: {
						botkitEventType: message.type || userSequence.type || defaultFields.MESSAGE_TYPE,
						...message
					},
					text: message.text,
					type: 'event'
				};

				const waitBefore = message.timeout || message.waitBefore || 0;
				if (waitBefore > 0) {
					await setTimeoutAsync(waitBefore);
				}

				const context = new TurnContext(this.adapter, activity);
				await this.adapter.runMiddleware(context, this.handleTurn.bind(this));

				const waitAfter = message.waitAfter || 0;
				if (waitAfter > 0) {
					await setTimeoutAsync(waitAfter);
				}

				if (message.isAssertion) {
					const messagesLog = this.detailed_answers[activity.conversation.id];
					let result = {};
					if (messagesLog) {
						const deepIndex = messagesLog.length - 1 - (message.deep || 0);
						result = messagesLog[deepIndex];
					}
					return result;
				}
			}
		}

		throw new Error("isAssert is missed in message sequence");
	}
}

module.exports = BotMock;


text:
#ifndef COGNITOWARE_MATH_PROBABILITY_RANGEDUNIFORM_H_
#define COGNITOWARE_MATH_PROBABILITY_RANGEDUNIFORM_H_

#include "cognitoware/math/data/Vector.h"
#include "cognitoware/math/data/VectorRange.h"
#include "cognitoware/math/probability/RandomDistribution.h"

#include <type_traits>
#include <utility>

namespace cognitoware {
namespace math {
namespace probability {

template<typename X>
class RangedUniform : public RandomDistribution<X> {
public:
  RangedUniform(X min, X max) :
      range_(std::move(min), std::move(max)) {
    static_assert(std::is_base_of<data::Vector, X>::value, "X must derive from Vector");
  }

  ~RangedUniform() override {
  }

  double ProbabilityOf(const X& x) const override {
    if (range_.Contains(x)) return 1.0 / range_.area();
    return 0.0;
  }

  X Sample(std::default_random_engine* generator) const override {
    return range_.Sample(generator);
  }

private:
  data::VectorRange<X> range_;
};

}  // namespace probability
}  // namespace math
}  // namespace cognitoware

#endif /* COGNITOWARE_MATH_PROBABILITY_RANGEDUNIFORM_H_ */


text:
namespace swift {

/// EpilogueARCBlockState - Keep track of whether an epilogue ARC instruction
/// has been found.
struct EpilogueARCBlockState {
  /// Keep track of whether an epilogue release has been found before and after
  /// this basic block.
  bool BBSetIn;
  /// The basic block local SILValue we are interested to find epilogue ARC in.
  SILValue LocalArg;
  /// Constructor, we only compute epilogue ARC instruction for 1 argument at
  /// a time.
  /// Optimistic data flow.
  EpilogueARCBlockState() { BBSetIn = true; LocalArg = SILValue(); }
};

/// EpilogueARCContext - This class implements a data flow with which epilogue
/// retains or releases for a SILValue are found.
///
/// NOTE:
/// In case of release finder, this function assumes the SILArgument has
/// @owned semantic.
/// In case of retain finder, this class assumes Arg is one of the return value
/// of the function.
class EpilogueARCContext {
public:
  enum EpilogueARCKind { Retain = 0, Release = 1 };

private:
  // Are we finding retains or releases.
  EpilogueARCKind Kind;

  // The argument we are looking for epilogue ARC instruction for.
  SILValue Arg;

  /// The allocator we are currently using.
  llvm::SpecificBumpPtrAllocator<EpilogueARCBlockState> BPA;

  /// Current function we are analyzing.
  SILFunction *F;

  /// Current post-order we are using.
  PostOrderFunctionInfo *PO;

  /// Current alias analysis we are using.
  AliasAnalysis *AA;

  /// Current rc-identity we are using.
  RCIdentityFunctionInfo *RCFI;

  /// The epilogue retains or releases.
  llvm::SmallSetVector<SILInstruction *, 1> EpilogueARCInsts;

  /// All the retain/release block state for all the basic blocks in the function.
  llvm::DenseMap<SILBasicBlock *, EpilogueARCBlockState *> EpilogueARCBlockStates;

  /// The exit blocks of the function.
  llvm::SmallPtrSet<SILBasicBlock *, 2> ExitBlocks;

  /// Return true if this is a function exiting block this epilogue ARC
  /// matcher is interested in.
  bool isInterestedFunctionExitingBlock(SILBasicBlock *BB) {
    if (EpilogueARCKind::Release == Kind)
      return BB->getTerminator()->isFunctionExiting();

    return BB->getTerminator()->isFunctionExiting() &&
           BB->getTerminator()->getTermKind() != TermKind::ThrowInst;
  }

  /// Return true if this is a function exit block.
  bool isExitBlock(SILBasicBlock *BB) {
    return ExitBlocks.count(BB);
  }

  /// Return true if this is a retain instruction.
  bool isRetainInstruction(SILInstruction *II) {
    return isa<RetainValueInst>(II) || isa<StrongRetainInst>(II);
  }

  /// Return true if this is a release instruction.
  bool isReleaseInstruction(SILInstruction *II) {
    return isa<ReleaseValueInst>(II) || isa<StrongReleaseInst>(II);
  }

  SILValue getArg(SILBasicBlock *B) {
    SILValue A = EpilogueARCBlockStates[B]->LocalArg;
    if (A)
      return A;
    return Arg;
  }

public:
  /// Constructor.
  EpilogueARCContext(EpilogueARCKind Kind, SILValue Arg, SILFunction *F,
                     PostOrderFunctionInfo *PO, AliasAnalysis *AA,
                     RCIdentityFunctionInfo *RCFI)
    : Kind(Kind), Arg(Arg), F(F), PO(PO), AA(AA), RCFI(RCFI) {}

  /// Run the data flow to find the epilogue retains or releases.
  bool run() {
    // Initialize the epilogue arc data flow context.
    initializeDataflow();
    // Converge the data flow.
    if (!convergeDataflow())
      return false;
    // Lastly, find the epilogue ARC instructions.
    return computeEpilogueARC();
  }

  /// Reset the epilogue arc instructions.
  void resetEpilogueARCInsts() { EpilogueARCInsts.clear(); }
  llvm::SmallSetVector<SILInstruction *, 1> getEpilogueARCInsts() {
    return EpilogueARCInsts;
  }

  /// Initialize the data flow.
  void initializeDataflow();

  /// Keep iterating until the data flow is converged.
  bool convergeDataflow();

  /// Find the epilogue ARC instructions.
  bool computeEpilogueARC();

  /// This instruction prevents looking further for epilogue retains on the
  /// current path.
  bool mayBlockEpilogueRetain(SILInstruction *II, SILValue Ptr) {
    // reference decrementing instruction prevents any retain to be identified as
    // epilogue retains.
    if (mayDecrementRefCount(II, Ptr, AA))
      return true;
    // Handle self-recursion. A self-recursion can be considered a +1 on the
    // current argument.
    if (ApplyInst *AI = dyn_cast<ApplyInst>(II))
     if (AI->getCalleeFunction() == II->getParent()->getParent())
       return true;
    return false;
  }

  /// This instruction prevents looking further for epilogue releases on the
  /// current path.
  bool mayBlockEpilogueRelease(SILInstruction *II, SILValue Ptr) {
    // Check whether this instruction read reference count, i.e. uniqueness
    // check. Moving release past that may result in additional COW.
   if (II->mayReleaseOrReadRefCount())
      return true;
    return false;
  }

  /// Does this instruction block the interested ARC instruction ?
  bool mayBlockEpilogueARC(SILInstruction *II, SILValue Ptr) {
    if (Kind == EpilogueARCKind::Retain)
      return mayBlockEpilogueRetain(II, Ptr);
    return mayBlockEpilogueRelease(II, Ptr);
  }

  /// This is the type of instructions the data flow is interested in.
  bool isInterestedInstruction(SILInstruction *II) {
    // We are checking for release.
    if (Kind == EpilogueARCKind::Release)
      return isReleaseInstruction(II) &&
             RCFI->getRCIdentityRoot(II->getOperand(0)) ==
             RCFI->getRCIdentityRoot(getArg(II->getParent()));
    // We are checking for retain. If this is a self-recursion. call
    // to the function (which returns an owned value) can be treated as
    // the retain instruction.
    if (ApplyInst *AI = dyn_cast<ApplyInst>(II))
     if (AI->getCalleeFunction() == II->getParent()->getParent())
       return true;
    // Check whether this is a retain instruction and the argument it
    // retains.
    return isRetainInstruction(II) &&
           RCFI->getRCIdentityRoot(II->getOperand(0)) ==
           RCFI->getRCIdentityRoot(getArg(II->getParent()));
  }
};

/// This class is a simple wrapper around an identity cache.
class EpilogueARCFunctionInfo {
  /// Current function we are analyzing.
  SILFunction *F;

  /// Current post-order we are using.
  PostOrderAnalysis *PO;

  /// Current alias analysis we are using.
  AliasAnalysis *AA;

  /// Current rc-identity we are using.
  RCIdentityAnalysis *RC;

  using ARCInstructions = llvm::SmallSetVector<SILInstruction *, 1>;
  /// The epilogue retain cache.
  llvm::DenseMap<SILValue, ARCInstructions> EpilogueRetainInstCache;
  /// The epilogue release cache.
  llvm::DenseMap<SILValue, ARCInstructions> EpilogueReleaseInstCache;

public:
  void handleDeleteNotification(ValueBase *V) {
    // Being conservative and clear everything for now.
    EpilogueRetainInstCache.clear();
    EpilogueReleaseInstCache.clear();
  }

  /// Constructor.
  EpilogueARCFunctionInfo(SILFunction *F, PostOrderAnalysis *PO,
                          AliasAnalysis *AA, RCIdentityAnalysis *RC)
    : F(F), PO(PO), AA(AA), RC(RC) {}

  /// Find the epilogue ARC instruction based on the given \p Kind and given
  /// \p Arg.
  llvm::SmallSetVector<SILInstruction *, 1>
  computeEpilogueARCInstructions(EpilogueARCContext::EpilogueARCKind Kind,
                                 SILValue Arg) {
    auto ARCCache = Kind == EpilogueARCContext::EpilogueARCKind::Retain ?
                 EpilogueRetainInstCache :
                 EpilogueReleaseInstCache;
    auto Iter = ARCCache.find(Arg);
    if (Iter != ARCCache.end())
      return Iter->second;

    EpilogueARCContext CM(Kind, Arg, F, PO->get(F), AA, RC->get(F));
    // Initialize and run the data flow. Clear the epilogue arc instructions if the
    // data flow is aborted in middle.
   if (!CM.run()) {
     CM.resetEpilogueARCInsts();
     return CM.getEpilogueARCInsts();
    }
    return ARCCache[Arg] = CM.getEpilogueARCInsts();
  }
};

class EpilogueARCAnalysis : public FunctionAnalysisBase<EpilogueARCFunctionInfo> {
  /// Current post order analysis we are using.
  PostOrderAnalysis *PO;
  /// Current alias analysis we are using.
  AliasAnalysis *AA;
  /// Current RC Identity analysis we are using.
  RCIdentityAnalysis *RC;

public:
  EpilogueARCAnalysis(SILModule *)
    : FunctionAnalysisBase<EpilogueARCFunctionInfo>(AnalysisKind::EpilogueARC),
      PO(nullptr), AA(nullptr), RC(nullptr) {}

  EpilogueARCAnalysis(const EpilogueARCAnalysis &) = delete;
  EpilogueARCAnalysis &operator=(const EpilogueARCAnalysis &) = delete;

  virtual void handleDeleteNotification(ValueBase *V) override {
    // If the parent function of this instruction was just turned into an
    // external declaration, bail. This happens during SILFunction destruction.
    SILFunction *F = V->getFunction();
    if (F->isExternalDeclaration()) {
      return;
    }
    get(F)->handleDeleteNotification(V);
  }

  virtual bool needsNotifications() override { return true; }

  static bool classof(const SILAnalysis *S) {
    return S->getKind() == AnalysisKind::EpilogueARC;
  }

  virtual void initialize(SILPassManager *PM) override;

  virtual EpilogueARCFunctionInfo *newFunctionAnalysis(SILFunction *F) override {
    return new EpilogueARCFunctionInfo(F, PO, AA, RC);
  }

  virtual bool shouldInvalidate(SILAnalysis::InvalidationKind K) override {
    return true;
  }

 };

} // end swift namespace

#endif


text:
cask :v1test => 'with-conditional-caveats' do
  version '1.2.3'
  sha256 '9203c30951f9aab41ac294bbeb1dcef7bed401ff0b353dcb34d68af32ea51853'

  url TestHelper.local_binary_url('caffeine.zip')
  homepage 'http://example.com/local-caffeine'

  app 'Caffeine.app'
  # a do block may print and use a DSL
  caveats do
    puts 'This caveat is conditional' if false
  end
end


text:
KISSY.add('hilo/util/util', function(S){

/**
 * @language=en
 * @class util method set
 * @static
 * @module hilo/util/util
 */
var util = {
    /**
     * @language=en
     * Simple shallow copy objects.
     * @param {Object} target Target object to copy to.
     * @param {Object} source Source object to copy.
     * @param {Boolean} strict Indicates whether replication is undefined property, default is false, i.e., undefined attributes are not copied.
     * @returns {Object} Object after copying.
     */
    copy: function(target, source, strict){
        for(var key in source){
            if(!strict || target.hasOwnProperty(key) || target[key] !== undefined){
                target[key] = source[key];
            }
        }
        return target;
    }
};

return util;

});


text:
package com.joe.bibi.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.joe.bibi.R;
import com.joe.bibi.application.BBApplication;
import com.joe.bibi.domain.Contacts;
import com.joe.bibi.utils.CharacterParser;
import com.joe.bibi.utils.CommonUtils;
import com.joe.bibi.utils.PinyinComparator;
import com.joe.bibi.utils.PrefUtils;
import com.joe.bibi.utils.ToastUtils;
import com.joe.bibi.view.SideBar;

import org.xutils.x;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bmob.im.BmobUserManager;
import cn.bmob.im.bean.BmobChatUser;
import cn.bmob.v3.listener.UpdateListener;

public class ContactActivity extends AppCompatActivity {

    private ListView mListView;
    private SideBar mSidebar;
    private List<Contacts> mContacts;
    private CharacterParser characterParser;
    private myAdapter adapter;
    private SearchView mSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);
        initView();
    }

    private void initView() {
        ActionBar ab=getSupportActionBar();
        ab.setDisplayHomeAsUpEnabled(true);
        mListView = (ListView) findViewById(R.id.lv_contact);
        mSidebar = (SideBar) findViewById(R.id.sb_contact);
        mSearch = (SearchView) findViewById(R.id.search_contacts);
        initContacts();
    }
    private PinyinComparator pinyinComparator;
    //初始化联系人信息
    private void initContacts() {
        characterParser = new CharacterParser();
        mContacts = new ArrayList<Contacts>();
        pinyinComparator=new PinyinComparator();
        for (BmobChatUser user:BBApplication.getInstance().getContactList()) {
            Contacts c=new Contacts();
            c.setUserName(user.getUsername());
            c.setAvatar(user.getAvatar());
            c.setName(user.getNick());
            c.setId(user.getObjectId());
            String pinyin = characterParser.getSelling(user.getNick());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式,判断首字母是否是英文字母
            if(sortString.matches("[A-Z]")){
                c.setSortLetters(sortString.toUpperCase());
            }else{
                c.setSortLetters("#");
            }
            mContacts.add(c);
        }
        /*//测试
        String[] data=getResources().getStringArray(R.array.date);
        for(int i=0;i<data.length;i++){
            Contacts c=new Contacts();
            c.setAvatar(BBApplication.getInstance().getContactList().get(0).getAvatar());
            c.setName(data[i]);
            String pinyin = characterParser.getSelling(data[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式,判断首字母是否是英文字母
            if(sortString.matches("[A-Z]")){
                c.setSortLetters(sortString.toUpperCase());
            }else{
                c.setSortLetters("#");
            }
            mContacts.add(c);
        }*/
        Collections.sort(mContacts, pinyinComparator);
        initAdapterAndListener();
    }

    private void initAdapterAndListener() {
        adapter = new myAdapter(this,mContacts);
        mListView.setAdapter(adapter);

        mSidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    mListView.setSelection(position);
                }

            }
        });
        mSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                filterData(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                filterData(newText);
                return false;
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(ContactActivity.this, UserActivity.class);
                intent.putExtra("username", adapter.getItem(position).getUserName());
                startActivity(intent);
            }
        });
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                final Contacts c=mContacts.get(position);
                AlertDialog.Builder builder=new AlertDialog.Builder(ContactActivity.this);
                builder.setTitle("删除好友?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //删除会话及聊天记录
                        BmobUserManager.getInstance(ContactActivity.this).deleteContact(c.getId(), new UpdateListener() {
                            @Override
                            public void onSuccess() {
                                ToastUtils.make(ContactActivity.this,"删除成功");
                                BBApplication.getInstance().updateContactList();
                            }

                            @Override
                            public void onFailure(int i, String s) {

                            }
                        });
                        mContacts.remove(position);
                        adapter.update(mContacts);
                        dialog.dismiss();
                        ToastUtils.make(ContactActivity.this, "删除成功");
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();
                return false;
            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                CommonUtils.hideKeyBoard(ContactActivity.this);
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }
    private void filterData(String filterStr){
        List<Contacts> filterDateList = new ArrayList<Contacts>();

        if(TextUtils.isEmpty(filterStr)){
            filterDateList = mContacts;
        }else{
            filterDateList.clear();
            for(Contacts Contacts : mContacts){
                String name = Contacts.getName();
                if(name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())){
                    filterDateList.add(Contacts);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.update(filterDateList);
    }
    class myAdapter extends BaseAdapter implements SectionIndexer{
        private Activity mActivity;
        private List<Contacts> contactsList;
        public myAdapter(Activity activity,List<Contacts> contactsList){
            this.mActivity=activity;
            this.contactsList=contactsList;
        }
        @Override
        public int getCount() {
            return contactsList.size();
        }

        @Override
        public Contacts getItem(int position) {
            return contactsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public void update(List<Contacts> list){
            this.contactsList=list;
            notifyDataSetChanged();
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Contacts contact=contactsList.get(position);
            ViewHolder holder=null;
            View v=convertView;
            if(v==null){
                v=View.inflate(mActivity,R.layout.item_contact,null);
                holder=new ViewHolder();
                holder.name= (TextView) v.findViewById(R.id.tv_nick_contact);
                holder.avatar= (ImageView) v.findViewById(R.id.iv_avatar_contact);
                holder.indicator= (TextView) v.findViewById(R.id.ll_content_contact);
                v.setTag(holder);
            }else{
                holder= (ViewHolder) v.getTag();
            }
            //根据position获取分类的首字母的Char ascii值
            int section = getSectionForPosition(position);
            //如果当前位置等于该分类首字母的Char的位置 ,则认为是第一次出现
            if(position == getPositionForSection(section)){
                holder.indicator.setVisibility(View.VISIBLE);
                holder.indicator.setText(contact.getSortLetters());
            }else{
                holder.indicator.setVisibility(View.GONE);
            }
            x.image().bind(holder.avatar,contact.getAvatar());

            holder.name.setText(contact.getName());
            return v;
        }

        @Override
        public Object[] getSections() {
            return null;
        }

        @Override
        public int getPositionForSection(int sectionIndex) {
            for (int i = 0; i < getCount(); i++) {
                String sortStr = contactsList.get(i).getSortLetters();
                char firstChar = sortStr.toUpperCase().charAt(0);
                if (firstChar == sectionIndex) {
                    return i;
                }
            }

            return -1;
        }

        @Override
        public int getSectionForPosition(int position) {
            return contactsList.get(position).getSortLetters().charAt(0);
        }
    }

    class ViewHolder{
        TextView name;
        ImageView avatar;
        TextView indicator;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==android.R.id.home){
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}


text:
namespace Epigram.Server.Core
{
    public enum Status
    {
        Available,
        Created
    }
}


text:
<?php

namespace Intahwebz\FlickrGuzzle;

//use Guzzle\Service\Command\AbstractCommand;
use Guzzle\Service\Command\OperationCommand;

class KeyValueResponseObjectFactory extends AbstractResponseObjectFactory {

	/**
	 * Creates domain objects from the response.
	 *
	 * @param $className
	 * @param OperationCommand $command
	 */
	public static function fromCommand(OperationCommand $command){
		$className = $command->getOperation()->getResponseClass();
		$data = $command->getRequest()->getResponse()->getBody(TRUE);
		$params = splitParameters($data);
		return $className::createFromJson($params);
	}
}

function splitParameters($string){
	//Taken from
	//https://github.com/dopiaza/DPZFlickr/blob/master/README.md
	//This function is MIT licensed
	$parameters = array();
	$keyValuePairs = explode('&', $string);
	foreach ($keyValuePairs as $kvp)	{
		$pieces = explode('=', $kvp);
		if (count($pieces) == 2)		{
			$parameters[rawurldecode($pieces[0])] = rawurldecode($pieces[1]);
		}
	}
	return $parameters;
}


text:
cask "parallels-client" do
  version "18.1.0,22708"
  sha256 "dea9583c7e1af302c8ad8f4362bac7318022ba5bc3dd7edcc63fa0ae9f956649"

  url "https://download.parallels.com/ras/v#{version.major}/#{version.before_comma.major_minor_patch}.#{version.after_comma}/RasClient-Mac-Notarized-#{version.before_comma.major_minor_patch}-#{version.after_comma}.pkg"
  name "Parallels Client"
  homepage "https://www.parallels.com/products/ras/features/rdp-client/"

  livecheck do
    url "https://download.parallels.com/ras/v18/RAS%20Client%20for%20Mac%20Changelog.txt"
    strategy :page_match do |page|
      match = page.match(/Version\s*(\d+(?:\.\d+)*)\s*\((\d+)\)/i)
      "#{match[1]},#{match[2]}"
    end
  end

  pkg "RasClient-Mac-Notarized-#{version.before_comma.major_minor_patch}-#{version.after_comma}.pkg"

  uninstall pkgutil: "com.2X.Client.Mac",
            quit:    "com.2X.Client.Mac"
end


text:
@interface ImageViewController ()

@property(nonatomic, strong) UIImage *image;

@end

@implementation ImageViewController

- (id)initWithNibName:(NSString *)nibNameOrNil
               bundle:(NSBundle *)nibBundleOrNil
                title:(NSString *)title
                image:(UIImage *)image {
  self = [super initWithNibName:nibNameOrNil
                         bundle:nibBundleOrNil];
  if (self) {
    _image = image;
    self.title = self.screenName = title;
  }
  return self;
}

- (void)viewDidLoad {
  [super viewDidLoad];
  UIImageView *imageView = [[UIImageView alloc] initWithImage:self.image];
  imageView.userInteractionEnabled = YES;
  imageView.contentMode = UIViewContentModeScaleAspectFit;
  [self.view addSubview:imageView];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:
    (UIInterfaceOrientation)interfaceOrientation {
  return YES;
}

@end


text:
<?php

namespace Solution10\SQL;

/**
 * Update
 *
 * Generates an SQL query for an UPDATE operation.
 *
 * @package     Solution10\ORM\SQL
 * @author      Alex Gisby<alex@solution10.com>
 * @license     MIT
 */
class Update extends Query
{
    use TableName;
    use Values;
    use Where;
    use Paginate;

    /**
     * @var     string      The base part of the query
     */
    protected $queryBase = 'UPDATE';

    /**
     * Generates the full SQL statement for this query with all the composite parts.
     *
     * @return  string
     */
    public function sql()
    {
        if ($this->table === null) {
            return '';
        }

        $candidateParts = [
            $this->queryBase,
            $this->dialect->quoteTable($this->table),
            $this->valuesSQL(),
            $this->buildWhereSQL($this->dialect),
            $this->buildPaginateSQL()
        ];

        return implode(' ', $candidateParts);
    }

    /**
     * Returns the values part of a query for an UPDATE statement (so key = value, key = value)
     *
     * @return  string
     */
    protected function valuesSQL()
    {
        $sql = '';
        if (!empty($this->values)) {
            $sql .= 'SET ';
            $parts = [];
            foreach ($this->values as $field => $value) {
                $parts[] = $this->dialect->quoteField($field).' = ?';
            }
            $sql .= implode(', ', $parts);
        }
        return $sql;
    }

    /**
     * Returns all the parameters, in the correct order, to pass into PDO.
     *
     * @return  array
     */
    public function params()
    {
        return array_merge(array_values($this->values), $this->getWhereParams());
    }

    /**
     * Resets the entire query.
     *
     * @return  $this
     */
    public function reset()
    {
        $this->table = null;
        $this->resetValues();
        $this->resetWhere();
        return $this;
    }

    /*
     * ------------------- All Tables ------------------------
     */

    /**
     * Returns all the tables that this query makes mention of, in FROMs and JOINs
     *
     * @return  array
     */
    public function allTablesReferenced()
    {
        if ($this->table()) {
            return [$this->table()];
        }
        return [];
    }
}


text:
require 'spec_helper'

describe WireMockController, :integration do

  it 'has a version number' do
    expect(WireMockController::VERSION).not_to be nil
  end

end


text:
package org.elasticsearch.test.rest.yaml;

import org.apache.http.client.methods.HttpHead;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Response;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * Response obtained from a REST call, eagerly reads the response body into a string for later optional parsing.
 * Supports parsing the response body when needed and returning specific values extracted from it.
 */
public class ClientYamlTestResponse {

    private final Response response;
    private final String body;
    private ObjectPath parsedResponse;

    ClientYamlTestResponse(Response response) throws IOException {
        this.response = response;
        if (response.getEntity() != null) {
            try {
                this.body = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            } catch (IOException e) {
                EntityUtils.consumeQuietly(response.getEntity());
                throw new RuntimeException(e);
            }
        } else {
            this.body = null;
        }
        parseResponseBody();
    }

    private void parseResponseBody() throws IOException {
        if (body != null) {
            String contentType = response.getHeader("Content-Type");
            XContentType xContentType = XContentType.fromMediaTypeOrFormat(contentType);
            //skip parsing if we got text back (e.g. if we called _cat apis)
            if (xContentType == XContentType.JSON || xContentType == XContentType.YAML) {
                this.parsedResponse = ObjectPath.createFromXContent(xContentType.xContent(), body);
            }
        }
    }

    public int getStatusCode() {
        return response.getStatusLine().getStatusCode();
    }

    public String getReasonPhrase() {
        return response.getStatusLine().getReasonPhrase();
    }

    /**
     * Returns the body properly parsed depending on the content type.
     * Might be a string or a json object parsed as a map.
     */
    public Object getBody() throws IOException {
        if (parsedResponse != null) {
            return parsedResponse.evaluate("");
        }
        return body;
    }

    /**
     * Returns the body as a string
     */
    public String getBodyAsString() {
        return body;
    }

    public boolean isError() {
        return response.getStatusLine().getStatusCode() >= 400;
    }

    /**
     * Parses the response body and extracts a specific value from it (identified by the provided path)
     */
    public Object evaluate(String path) throws IOException {
        return evaluate(path, Stash.EMPTY);
    }

    /**
     * Parses the response body and extracts a specific value from it (identified by the provided path)
     */
    public Object evaluate(String path, Stash stash) throws IOException {
        if (response == null) {
            return null;
        }

        if (parsedResponse == null) {
            //special case: api that don't support body (e.g. exists) return true if 200, false if 404, even if no body
            //is_true: '' means the response had no body but the client returned true (caused by 200)
            //is_false: '' means the response had no body but the client returned false (caused by 404)
            if ("".equals(path) && HttpHead.METHOD_NAME.equals(response.getRequestLine().getMethod())) {
                return isError() == false;
            }
            return null;
        }

        return parsedResponse.evaluate(path, stash);
    }
}


text:
The pynikani module is a simple python wrapper for the [wanikani](http://www.wanikani.com) web api.  It
was bread out the annoyance of wrapping the same api calls and grabbing the
same data every time I wanted to write a fun script to do something.

Dependencies: requests


text:
ComputationTimer::ComputationTimer(string _computation) : computation(_computation)  {}
ComputationTimer::~ComputationTimer()  {}


text:
SET(PLATFORM_LIBS)
IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    find_library(IOKIT_FRAMEWORK IOKit)
    find_library(COREFOUNDATION_FRAMEWORK CoreFoundation)
    #find_library(QUARTZCORE QuartzCore)
    find_library(APPKIT_FRAMEWORK AppKit)
    #find_library(QTKIT QTKit)
    find_library(AVFOUNDATION AVFoundation)
    find_library(IOBLUETOOTH IOBluetooth)
    #stdc++ ${QUARTZCORE} ${APPKIT_FRAMEWORK} ${QTKIT} ${AVFOUNDATION}
    list(APPEND PLATFORM_LIBS
        ${COREFOUNDATION_FRAMEWORK}
        ${IOKIT_FRAMEWORK}
        ${APPKIT_FRAMEWORK}
        ${AVFOUNDATION}
        ${IOBLUETOOTH})
ELSEIF(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
    #OpenCV extra dependencies: comctl32 gdi32 ole32 setupapi ws2_32 vfw32
    #hid required for HidD_SetOutputReport() in DualShock4 controller
    #setupapi required by hidapi
    #dinput8 required by libstem_gamepad
    list(APPEND PLATFORM_LIBS bthprops setupapi hid dinput8)
    IF(MINGW)
        #list(APPEND PLATFORM_LIBS stdc++)
    ENDIF(MINGW)
ELSE() #Linux
    list(APPEND PLATFORM_LIBS rt)
ENDIF()

# Eigen3
IF(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
    # TODO: Convert this to ExternalProject_Add
    # Can manually set EIGEN3_INCLUDE_DIR to "${ROOT_DIR}/thirdparty/eigen
    MESSAGE(STATUS "Using Eigen3 in submodule")
    LIST(APPEND CMAKE_MODULE_PATH "${ROOT_DIR}/thirdparty/eigen/cmake")
    SET(ENV{EIGEN3_ROOT} "${ROOT_DIR}/thirdparty/eigen")
    find_package(Eigen3 REQUIRED)
ELSEIF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    MESSAGE(STATUS "Using homebrew Eigen3")
    find_package(Eigen3 REQUIRED CONFIG PATHS /usr/local/opt/eigen/lib/cmake/eigen3)
ELSE()
    LIST(APPEND CMAKE_MODULE_PATH "${ROOT_DIR}/thirdparty/eigen/cmake")
    SET(ENV{EIGEN3_ROOT} "/usr/include/eigen3")
    find_package(Eigen3 REQUIRED)
ENDIF()

# OpenCV
# Override by adding "-DOpenCV_DIR=C:\path\to\opencv\build" to your cmake command
IF(NOT OpenCV_DIR)
    IF(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
        ExternalProject_Add(opencv
          PREFIX ${ROOT_DIR}/deps/opencv
          GIT_REPOSITORY https://github.com/opencv/opencv.git
          GIT_SHALLOW 1
          GIT_TAG 3.1.0
          CMAKE_GENERATOR ${gen}
          CMAKE_ARGS
            -DCMAKE_INSTALL_PREFIX=<INSTALL_DIR>
            -DCMAKE_INCLUDE_PATH=${ROOT_DIR}/deps/local/include
            -DCMAKE_LIBRARY_PATH=${ROOT_DIR}/deps/local/lib
            -DBUILD_WITH_STATIC_CRT:BOOL=ON
            -DBUILD_SHARED_LIBS:BOOL=OFF
            -DBUILD_DOCS:BOOL=OFF
            -DBUILD_EXAMPLES:BOOL=OFF
            -DBUILD_TESTS:BOOL=OFF
            -DBUILD_PERF_TESTS:BOOL=OFF
            #-DCMAKE_BUILD_TYPE:STRING=Release
            -DWITH_FFMPEG:BOOL=OFF
            -DWITH_OPENEXR:BOOL=OFF
            -DWITH_JASPER:BOOL=OFF
            -DWITH_TIFF:BOOL=OFF
            -DWITH_IPP:BOOL=OFF
            -DBUILD_opencv_apps:BOOL=OFF
            -DBUILD_opencv_calib3d:BOOL=ON
            -DBUILD_opencv_flann:BOOL=ON
            -DBUILD_opencv_features2d:BOOL=ON
            -DBUILD_opencv_objdetect:BOOL=ON
            -DBUILD_opencv_photo:BOOL=ON
            -DBUILD_opencv_ts:BOOL=OFF
            -DBUILD_opencv_ml:BOOL=ON
            -DBUILD_opencv_video:BOOL=ON
            -DBUILD_opencv_java:BOOL=OFF
            -DBUILD_opencv_python2:BOOL=OFF
            -DBUILD_opencv_python3:BOOL=OFF
            -DPYTHON2_LIBRARY:STRING=C:/Python27/libs/python27.lib
            -DPYTHON3_LIBRARY:STRING=C:/Python35/libs/python35.lib
          INSTALL_DIR ${ROOT_DIR}/deps/local/
        )

        add_definitions(-DHAS_OPENCV)

        set(OpenCV_DIR ${ROOT_DIR}/deps/local)
        set(OpenCV_INCLUDE_DIRS ${ROOT_DIR}/deps/local/include )
        if (${CMAKE_C_SIZEOF_DATA_PTR} EQUAL 8)
            set(OPENCV_LIBS_DIR ${ROOT_DIR}/deps/local/x64/vc14/staticlib)
        else()
            set(OPENCV_LIBS_DIR ${ROOT_DIR}/deps/local/x86/vc14/staticlib)
        endif()

        foreach(__CVLIB core calib3d features2d flann imgproc imgcodecs ml highgui objdetect video videoio)
            set(OpenCV_${__CVLIB}_LIBRARY debug ${OPENCV_LIBS_DIR}/opencv_${__CVLIB}310d.lib optimized ${OPENCV_LIBS_DIR}/opencv_${__CVLIB}310.lib CACHE STRING "" FORCE)
            set(OpenCV_LIBS ${OpenCV_LIBS} ${OpenCV_${__CVLIB}_LIBRARY})
        endforeach(__CVLIB)

        foreach(__CVLIB libjpeg libpng libwebp zlib)
            set(OpenCV_${__CVLIB}_LIBRARY debug ${OPENCV_LIBS_DIR}/${__CVLIB}d.lib optimized ${OPENCV_LIBS_DIR}/${__CVLIB}.lib CACHE STRING "" FORCE)
            set(OpenCV_LIBS ${OpenCV_LIBS} ${OpenCV_${__CVLIB}_LIBRARY})
        endforeach(__CVLIB)

        LIST(APPEND OpenCV_LIBS vfw32.lib)

    ELSEIF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
        # Location of homebrew opencv3's OpenCVConfig.cmake
        # Alternatively, can do `brew ln opencv3 --force`
        MESSAGE(STATUS "Using homebrew opencv3")
        set(OpenCV_DIR "/usr/local/opt/opencv3/share/OpenCV")
    ELSE()
        set(OpenCV_DIR "/usr/local/share/OpenCV")
    ENDIF()#Windows or Darwin
ENDIF(NOT OpenCV_DIR)
LIST(APPEND CMAKE_MODULE_PATH ${OpenCV_DIR})
set(OpenCV_STATIC ON)
IF(NOT(${CMAKE_SYSTEM_NAME} MATCHES "Windows"))
    FIND_PACKAGE(OpenCV REQUIRED)
ENDIF()

# Boost
IF(MSVC)
    # Default location of pre-compiled Boost for Windows
    # Override by adding "-DBOOST_ROOT=C:\path\to\boost\ -DBOOST_LIBRARYDIR=C:\path\to\boost\lib32-msvc-14.0\" to your cmake command
    IF (NOT BOOST_ROOT)
        SET(BOOST_ROOT "C:/local/boost_1_61_0/")
        SET(BOOST_LIBRARYDIR "C:/local/boost_1_61_0/lib32-msvc-14.0/")
    ENDIF()

    # Disable asio auto linking in date-time and regex
    add_definitions(-DBOOST_DATE_TIME_NO_LIB)
    add_definitions(-DBOOST_REGEX_NO_LIB)
    # fix: fatal error C1128: number of sections exceeded object file format limit
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
ENDIF()
SET(Boost_DEBUG                OFF) #Switch this and next to ON for help debugging Boost problems.
SET(Boost_DETAILED_FAILURE_MSG OFF)
set(Boost_USE_STATIC_LIBS      ON) # only find static libs
set(Boost_USE_MULTITHREADED    ON)
set(Boost_USE_STATIC_RUNTIME   ON) #Not default. Because our app is linking against static runtime (see above).
find_package(Boost REQUIRED)  # Future targets can specify components.

# Protobuf
IF(MSVC)
    set(PROTOBUF_SRC_ROOT_FOLDER ${ROOT_DIR}/thirdparty/protobuf)
    #PROTOBUF_IMPORT_DIRS ?
    # Default location of protobuf for Windows
    #SET(CMAKE_INCLUDE_PATH ${CMAKE_INCLUDE_PATH} "${ROOT_DIR}/thirdparty/protobuf")
ENDIF(MSVC)
set(PROTOBUF_ORIG_FIND_LIBRARY_SUFFIXES "${CMAKE_FIND_LIBRARY_SUFFIXES}") # Store original
set(CMAKE_FIND_LIBRARY_SUFFIXES .a .lib .so .dylib .dll)  # Prefer static libs
find_package(Protobuf REQUIRED)
set(CMAKE_FIND_LIBRARY_SUFFIXES "${PROTOBUF_ORIG_FIND_LIBRARY_SUFFIXES}")  # Restore original
include_directories(${CMAKE_BINARY_DIR}/psmoveprotocol)  # This is where the .proto files are compiled to.
IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    # protobuf current generates many warnings in MacOS:
    #'OSMemoryBarrier' is deprecated: first deprecated in macOS 10.12 - Use std::atomic_thread_fence() from <atomic> instead
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations")
ENDIF()

# SDL and GL
set(SDL_GL_INCLUDE_DIRS)
set(SDL_GL_LIBS)
IF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    find_library(OPENGL_FRAMEWORK OpenGL)
    find_package(SDL2)
    list(APPEND SDL_GL_INCLUDE_DIRS ${SDL2_INCLUDE_DIR})
    list(APPEND SDL_GL_LIBS
        ${SDL2_LIBRARY} ${OPENGL_FRAMEWORK} ${GLUT_FRAMEWORK})
ELSEIF(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
    find_package(SDL2)
    list(APPEND SDL_GL_INCLUDE_DIRS ${SDL2_INCLUDE_DIR})
    list(APPEND SDL_GL_LIBS ${SDL2_LIBRARY} GL)
ELSEIF(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
    SET(ENV{SDL2DIR} ${ROOT_DIR}/thirdparty/SDL2/)
    find_package(SDL2)
    list(APPEND SDL_GL_INCLUDE_DIRS ${SDL2_INCLUDE_DIR})
    list(APPEND SDL_GL_LIBS
        ${SDL2_LIBRARY}
        imm32.lib
        version.lib)
ENDIF()

# For PSEye camera
set(PSEYE_SRC)
set(PSEYE_INCLUDE_DIRS)
set(PSEYE_LIBRARIES)
# PS3EYEDriver - only necessary on Mac and Win64, but can be used in Win32 (I think)
IF (${CMAKE_SYSTEM_NAME} MATCHES "Darwin"
    OR (${CMAKE_SYSTEM_NAME} MATCHES "Windows"))
    #PS3EYEDriver
    list(APPEND PSEYE_INCLUDE_DIRS ${ROOT_DIR}/thirdparty/PS3EYEDriver/src)
    list(APPEND PSEYE_SRC
        ${ROOT_DIR}/thirdparty/PS3EYEDriver/src/ps3eye.h
        ${ROOT_DIR}/thirdparty/PS3EYEDriver/src/ps3eye.cpp)
    #Requires libusb
    find_package(USB1 REQUIRED)
    list(APPEND PSEYE_INCLUDE_DIRS ${LIBUSB_INCLUDE_DIR})
    list(APPEND PSEYE_LIBRARIES ${LIBUSB_LIBRARIES})
    add_definitions(-DHAVE_PS3EYE)
    IF (${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-braced-scalar-init")
    ENDIF()
ENDIF()
# CL EYE - only on Win32
IF(${CMAKE_SYSTEM_NAME} MATCHES "Windows"
    AND NOT(${CMAKE_C_SIZEOF_DATA_PTR} EQUAL 8))
    add_definitions(-DHAVE_CLEYE)
    list(APPEND PSEYE_INCLUDE_DIRS ${ROOT_DIR}/thirdparty/CLEYE)
    list(APPEND PSEYE_LIBRARIES ${ROOT_DIR}/thirdparty/CLEYE/x86/lib/CLEyeMulticam.lib)
    find_path(CL_EYE_SDK_PATH CLEyeMulticam.dll
        HINTS C:/Windows/SysWOW64)
    #The non-Multicam version does not require any libs/dlls/includes
    #Uses OpenCV for video. Uses the registry for settings.
    #But libusb is required for enumerating the devices and checking for the CL Eye Driver.
    # LIBUSB already added above
    #find_package(USB1 REQUIRED)
    #list(APPEND PSEYE_INCLUDE_DIRS ${LIBUSB_INCLUDE_DIR})
    #list(APPEND PSEYE_LIBRARIES ${LIBUSB_LIBRARIES})
ENDIF()

# hidapi
set(HIDAPI_INCLUDE_DIRS ${ROOT_DIR}/thirdparty/hidapi/hidapi)
set(HIDAPI_SRC)
set(HIDAPI_LIBS)
IF(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
    list(APPEND HIDAPI_SRC ${ROOT_DIR}/thirdparty/hidapi/windows/hid.c)
ELSEIF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    list(APPEND HIDAPI_SRC ${ROOT_DIR}/thirdparty/hidapi/mac/hid.c)
ELSE()
    list(APPEND HIDAPI_SRC ${ROOT_DIR}/thirdparty/hidapi/linux/hid.c)
    find_package(PkgConfig REQUIRED)
    pkg_check_modules(UDEV REQUIRED libudev)
    list(APPEND HIDAPI_INCLUDE_DIRS ${UDEV_INCLUDE_DIRS})
    list(APPEND HIDAPI_LIBS ${UDEV_LIBRARIES})
    pkg_check_modules(BLUEZ REQUIRED bluez)
    list(APPEND HIDAPI_INCLUDE_DIRS ${BLUEZ_INCLUDE_DIRS})
    list(APPEND HIDAPI_LIBS ${BLUEZ_LIBRARIES})
ENDIF()

# libstem_gamepad
set(LIBSTEM_GAMEPAD_INCLUDE_DIRS ${ROOT_DIR}/thirdparty/libstem_gamepad/source)
set(LIBSTEM_GAMEPAD_SRC ${ROOT_DIR}/thirdparty/libstem_gamepad/source/gamepad/Gamepad_private.c)
IF(${CMAKE_SYSTEM_NAME} MATCHES "Windows")
    list(APPEND LIBSTEM_GAMEPAD_SRC ${ROOT_DIR}/thirdparty/libstem_gamepad/source/gamepad/Gamepad_windows_dinput.c)
ELSEIF(${CMAKE_SYSTEM_NAME} MATCHES "Darwin")
    list(APPEND LIBSTEM_GAMEPAD_SRC ${ROOT_DIR}/thirdparty/libstem_gamepad/source/gamepad/Gamepad_macosx.c)
ELSE()
    list(APPEND LIBSTEM_GAMEPAD_SRC ${ROOT_DIR}/thirdparty/libstem_gamepad/source/gamepad/Gamepad_linux.c)
ENDIF()


text:
package net.dirtyfilthy.bouncycastle.jce.provider;

import javax.crypto.interfaces.PBEKey;
import javax.crypto.spec.PBEKeySpec;

import net.dirtyfilthy.bouncycastle.asn1.DERObjectIdentifier;
import net.dirtyfilthy.bouncycastle.crypto.CipherParameters;
import net.dirtyfilthy.bouncycastle.crypto.PBEParametersGenerator;
import net.dirtyfilthy.bouncycastle.crypto.params.KeyParameter;
import net.dirtyfilthy.bouncycastle.crypto.params.ParametersWithIV;

public class JCEPBEKey
    implements PBEKey
{
    String              algorithm;
    DERObjectIdentifier oid;
    int                 type;
    int                 digest;
    int                 keySize;
    int                 ivSize;
    CipherParameters    param;
    PBEKeySpec          pbeKeySpec;
    boolean             tryWrong = false;

    /**
     * @param param
     */
    public JCEPBEKey(
        String              algorithm,
        DERObjectIdentifier oid,
        int                 type,
        int                 digest,
        int                 keySize,
        int                 ivSize,
        PBEKeySpec          pbeKeySpec,
        CipherParameters    param)
    {
        this.algorithm = algorithm;
        this.oid = oid;
        this.type = type;
        this.digest = digest;
        this.keySize = keySize;
        this.ivSize = ivSize;
        this.pbeKeySpec = pbeKeySpec;
        this.param = param;
    }

    public String getAlgorithm()
    {
        return algorithm;
    }

    public String getFormat()
    {
        return "RAW";
    }

    public byte[] getEncoded()
    {
        if (param != null)
        {
            KeyParameter    kParam;

            if (param instanceof ParametersWithIV)
            {
                kParam = (KeyParameter)((ParametersWithIV)param).getParameters();
            }
            else
            {
                kParam = (KeyParameter)param;
            }

            return kParam.getKey();
        }
        else
        {
            if (type == PBE.PKCS12)
            {
                return PBEParametersGenerator.PKCS12PasswordToBytes(pbeKeySpec.getPassword());
            }
            else
            {
                return PBEParametersGenerator.PKCS5PasswordToBytes(pbeKeySpec.getPassword());
            }
        }
    }

    int getType()
    {
        return type;
    }

    int getDigest()
    {
        return digest;
    }

    int getKeySize()
    {
        return keySize;
    }

    int getIvSize()
    {
        return ivSize;
    }

    CipherParameters getParam()
    {
        return param;
    }

    /* (non-Javadoc)
     * @see javax.crypto.interfaces.PBEKey#getPassword()
     */
    public char[] getPassword()
    {
        return pbeKeySpec.getPassword();
    }

    /* (non-Javadoc)
     * @see javax.crypto.interfaces.PBEKey#getSalt()
     */
    public byte[] getSalt()
    {
        return pbeKeySpec.getSalt();
    }

    /* (non-Javadoc)
     * @see javax.crypto.interfaces.PBEKey#getIterationCount()
     */
    public int getIterationCount()
    {
        return pbeKeySpec.getIterationCount();
    }

    public DERObjectIdentifier getOID()
    {
        return oid;
    }

    void setTryWrongPKCS12Zero(boolean tryWrong)
    {
        this.tryWrong = tryWrong;
    }

    boolean shouldTryWrongPKCS12()
    {
        return tryWrong;
    }
}