text:
using System.Collections.Generic;
//using System.IO.Packaging;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;

namespace DevTreks.Data.Helpers
{
    public class PackageIO
    {
        /// <summary>
        ///Purpose:		utilites for making ebook packages (openxml, idpf ...)
        ///Author:		www.devtreks.org
        ///Date:		2016, May
        ///References:	www.devtreks.org/helptreks/linkedviews/help/linkedview/HelpFile/148
        ///NOTES
        ///             1. The current version does not organize the ebooks. Some early
        ///             experimentation showed how to do it, but its not considered
        ///             as critical as getting the existing features debugged and performant.
        /// </summary>

        public enum DIGITAL_SIGNATURE_TYPES
        {
            none    = 0,
            all     = 1
        }
        //css and scripts shared by all html files
        public const string HEADERS_KEYNAME = "headers";
        //thes uris are taken from a sdk example
        private const string _openxmPackageRelationshipType = "http://schemas.openxmlformats.org/package/2007/relationships/sdk-samples/htmx/root-html";
        private const string _openXmResourceRelationshipType = "http://schemas.openxmlformats.org/package/2007/relationships/sdk-samples/htmx/required-resource";
        //part name of the signatureOrigin relationship.
        private const string _openxmlDigitalSignatureUri = "/package/services/digital-signature/_rels/origin.psdsor.rels";
        //current directory
        private string CurrentDirectory { get; set; }

        public static string GetPackageContentRoot(string rootPackageDirectory)
        {
            //0.8.7 switched from relative paths to full web paths
            string sContentPackageDirectory = rootPackageDirectory;
            return sContentPackageDirectory;
        }
        public bool PackageFiles(ContentURI uri, string packageFilePathName,
            string packageType, string digitalSignatureType,
            IDictionary<string, string> args)
        {
            bool bIsZipped = false;
            //add the error msg to the uri
            string sErrorMsg = string.Empty;
            ZipIO zipIO = new ZipIO();
            if (packageType == AppHelpers.Resources.PACKAGE_TYPES.plainzip.ToString())
            {
                //160 went to 100% zip until need arises for more
                bIsZipped = zipIO.ZipFiles(uri, packageFilePathName, args);
                //delete those files (don't delete them in the zipIO because of
                //error message about deleting the parent directory contains open files
                string sKey = string.Empty;
                string sValue = string.Empty;
                foreach (KeyValuePair<string, string> kvp in args)
                {
                    sKey = kvp.Key;
                    sValue = kvp.Value;
                    if (Path.IsPathRooted(sKey))
                    {
                        FileIO.DeleteFile(uri, sKey);
                    }
                }
            }
            //else if (packageType == AppHelpers.Resources.PACKAGE_TYPES.openxml.ToString())
            //{
            //    bIsZipped = await PackageOpenXmlFiles(packageFilePathName,
            //        digitalSignatureType, args);
            //}
            //else if (packageType == AppHelpers.Resources.PACKAGE_TYPES.idpf.ToString())
            //{
            //    //create and add the idpf-specific files (add to args for zipping)
            //    EPub epub = new EPub();
            //    sErrorMsg = await epub.PackageIDPFFiles(uri, packageFilePathName,
            //        args);
            //    //zip the package
            //    sErrorMsg = await zipIO.ZipFiles(packageFilePathName,
            //        args);
            //}
            //else if (packageType == AppHelpers.Resources.PACKAGE_TYPES.nimas.ToString())
            //{
            //    PackageNIMASFiles(arrZipArgs, out sErrorMessage);
            //}
            else
            {
                //160 went to 100% zip until need arises for more
                bIsZipped = zipIO.ZipFiles(uri, packageFilePathName, args);
                ////default is idpf
                //PackageIDPFFiles(arrZipArgs, out sErrorMessage);
            }
            return bIsZipped;
        }
        public bool PackageOpenXmlFiles(string packageFilePathName,
            string digitalSignatureType, IDictionary<string, string> args,
            out string errorMsg)
        {
            bool bIsZipped = false;
            errorMsg = string.Empty;
            CheckForPackageFileErrors(packageFilePathName, args, ref errorMsg);
            if (!string.IsNullOrEmpty(errorMsg))
            {
                return bIsZipped;
            }
            //package parts have a value with the filename of packageFilePathName
            string sPackagePartValue = Path.GetFileName(packageFilePathName);
            //files are found in this directory and it's subfolders
            CurrentDirectory = FileStorageIO.GetDirectoryName(packageFilePathName);
            Directory.SetCurrentDirectory(Path.GetDirectoryName(packageFilePathName));
            //using (Package oPack = Package.Open(Path.GetFileName(packageFilePathName),
            //    FileMode.Create))
            //{
            //    //make a collection of std css and script files to relate to html files
            //    List<Uri> colHeaderUris = new List<Uri>();
            //    AddHtmlHeadersToPackage(oPack, args, colHeaderUris,
            //        errorMsg);
            //    string sKey = string.Empty;
            //    string sValue = string.Empty;
            //    //parallel didn't work here
            //    foreach (KeyValuePair<string, string> kvp in args)
            //    {
            //        sKey = kvp.Key;
            //        sValue = kvp.Value;
            //        if (sValue == sPackagePartValue)
            //        {
            //            if (string.IsNullOrEmpty(sKey) == false
            //                && Helpers.FileStorageIO.URIAbsoluteExists(sKey))
            //            {
            //                //these are all package parts
            //                PackagePart oPackPart = null;
            //                bool bIsPackagePart = AddPackagePart(oPack, sKey,
            //                    out oPackPart, errorMsg);
            //                if (bIsPackagePart)
            //                {
            //                    AddPackageRelationship(oPack, oPackPart.Uri);
            //                    //relate to std DevTreks headers
            //                    RelateHtmlHeadersToPart(oPack, oPackPart,
            //                        colHeaderUris, errorMsg);
            //                    //add resources and relationships
            //                    AddandRelateResource(sKey, args, oPack,
            //                        oPackPart, errorMsg);
            //                }
            //            }
            //        }
            //    }
            //    //save all of the content
            //    oPack.Flush();
            //    if (digitalSignatureType == DIGITAL_SIGNATURE_TYPES.all.ToString())
            //    {
            //        //digitally sign all the parts and relationships in the package.
            //        SignAllParts(oPack);
            //    }
            //    bIsZipped = true;
            //}//closes, saves, and disposes of Package
            return bIsZipped;
        }
        public void CheckForPackageFileErrors(string packageFilePathName,
            IDictionary<string, string> args, ref string errorMsg)
        {
            if (args.Count < 2)
                errorMsg = "Please select files or directories to zip";
            if (!packageFilePathName.EndsWith(".zip"))
                errorMsg = "The package file must end with .zip";
        }
        //private bool AddPackagePart(Package pack,
        //    string partFullPath, out PackagePart packPart, string errorMsg)
        //{
        //    bool bIsPackagePart = false;
        //    packPart = null;
        //    //convert system path and file names to Part URIs (they are relative to package root)
        //    //convert the absolute path of partFullPath into a path relative to the package root (getcurrentdirectory)
        //    string sRelPartPath = GeneralHelpers.ConvertAbsPathToRelPath(CurrentDirectory, partFullPath);
        //    //string sRelPartPath = GeneralHelpers.ConvertAbsPathToRelPath(Directory.GetCurrentDirectory(), partFullPath);
        //    Uri uriPart = PackUriHelper.CreatePartUri(new Uri(sRelPartPath, UriKind.Relative));
        //    if (pack.PartExists(uriPart) == false)
        //    {
        //        if (Helpers.FileStorageIO.URIAbsoluteExists(partFullPath))
        //        {
        //            //set the media type used in createpart()
        //            string sMediaType = AppHelpers.Resources.GetMimeTypeFromFileExt(Path.GetExtension(partFullPath).ToLower(), ref errorMsg);
        //            //for now, allow the package to be built skipping over some file types
        //            errorMsg = string.Empty;
        //            // Use normal compression unless the data that has
        //            // already been compressed or is an "octet-stream".
        //            CompressionOption oCompression = CompressionOption.Normal;
        //            if (sMediaType.StartsWith("image")
        //                || sMediaType.StartsWith("video")
        //                || sMediaType.StartsWith("audio")
        //                || sMediaType.StartsWith("application/octet-stream"))
        //                oCompression = CompressionOption.NotCompressed;
        //            //add the document part to the package
        //            packPart = pack.CreatePart(uriPart, sMediaType, oCompression);
        //            //copy the data to the document part
        //            using (FileStream fileStream = new FileStream(partFullPath,
        //                FileMode.Open, FileAccess.Read))
        //            {
        //                FileIO.CopyStream(fileStream, packPart.GetStream());
        //            }
        //            bIsPackagePart = true;
        //        }
        //    }
        //    return bIsPackagePart;
        //}
        //private void AddPackageRelationship(Package pack,
        //    Uri partUri)
        //{
        //    //add a package relationship to the document part
        //    pack.CreateRelationship(partUri, TargetMode.Internal, _openxmPackageRelationshipType);
        //}
        //private static void AddResourceRelationship(Package pack,
        //    Uri partUri, Uri resourceUri)
        //{
        //    //add a resource relationship to the document part at the packlevel?
        //    //resources are always in subfolders
        //    string sNewURI = @".." + resourceUri.ToString();
        //    pack.CreateRelationship(new Uri(sNewURI, UriKind.Relative), TargetMode.Internal,
        //        partUri.ToString());
        //}
        //private static void AddResourceRelationship(PackagePart packPart,
        //    Uri resourceUri)
        //{
        //    //add a resource relationship to the document part at the part level?
        //    //resources are always in subfolders
        //    string sNewURI = @".." + resourceUri.ToString();
        //    packPart.CreateRelationship(new Uri(sNewURI, UriKind.Relative), TargetMode.Internal,
        //        _openXmResourceRelationshipType);
        //}
        //private void AddHtmlHeadersToPackage(Package pack,
        //    IDictionary<string, string> args, List<Uri> headerUris,
        //    string errorMsg)
        //{
        //    string sKey = string.Empty;
        //    string sValue = string.Empty;
        //    bool bIsPackagePart = false;
        //    //parallel didn't work here: Parallel.ForEach(args, kvp =>
        //    foreach (KeyValuePair<string, string> kvp in args)
        //    {
        //        sKey = kvp.Key;
        //        sValue = kvp.Value;
        //        if (sValue == HEADERS_KEYNAME)
        //        {
        //            if (string.IsNullOrEmpty(sKey) == false
        //                && Helpers.FileStorageIO.URIAbsoluteExists(sKey))
        //            {
        //                PackagePart oHeaderPart = null;
        //                //add the headers to the package
        //                bIsPackagePart = AddPackagePart(pack, sKey,
        //                    out oHeaderPart, errorMsg);
        //                if (bIsPackagePart)
        //                {
        //                    headerUris.Add(oHeaderPart.Uri);
        //                }
        //            }
        //        }
        //    }
        //}
        //private void RelateHtmlHeadersToPart(Package pack, PackagePart packPart,
        //    List<Uri> headerUris, string errorMsg)
        //{
        //    //only relate to htm and html files
        //    int iIndex = packPart.Uri.ToString().ToLower().IndexOf(".htm");
        //    if (iIndex > 0)
        //    {
        //        if (headerUris.Count > 0)
        //        {
        //            foreach (Uri uriHeader in headerUris)
        //            {
        //                //relate to the partUri
        //                AddResourceRelationship(packPart, uriHeader);
        //            }
        //        }
        //    }
        //}
        //private void AddandRelateResource(string packagePartFilePath,
        //    IDictionary<string, string> args, Package pack,
        //    PackagePart packPart, string errorMsg)
        //{
        //    string sResourceValue = Path.GetFileName(packagePartFilePath);
        //    string sKey = string.Empty;
        //    string sValue = string.Empty;
        //    bool bIsPackagePart = false;
        //    //parellel didnt' work here: Parallel.ForEach(args, kvp =>
        //    foreach (KeyValuePair<string, string> kvp in args)
        //    {
        //        sKey = kvp.Key;
        //        sValue = kvp.Value;
        //        if (sValue == sResourceValue)
        //        {
        //            if (string.IsNullOrEmpty(sKey) == false
        //                && Helpers.FileStorageIO.URIAbsoluteExists(sKey))
        //            {
        //                PackagePart oResourcePart = null;
        //                //add the resources to the package
        //                bIsPackagePart = AddPackagePart(pack, sKey,
        //                    out oResourcePart, errorMsg);
        //                if (bIsPackagePart)
        //                {
        //                    //relate the resource to the part
        //                    AddResourceRelationship(packPart, oResourcePart.Uri);
        //                }
        //            }
        //        }
        //    }
        //}
        //// ------------------------ ValidateSignatures ------------------------
        ///// <summary>
        /////   Validates all the digital signatures of a given package.</summary>
        ///// <param name="package">
        /////   The package for validating digital signatures.</param>
        ///// <returns>
        /////   true if all digital signatures are valid; otherwise false if the
        /////   package is unsigned or any of the signatures are invalid.</returns>
        //private bool ValidateSignatures(Package package)
        //{
        //    if (package == null)
        //        throw new ArgumentNullException("ValidateSignatures(package)");

        //    // Create a PackageDigitalSignatureManager for the given Package.
        //    PackageDigitalSignatureManager dsm =
        //        new PackageDigitalSignatureManager(package);

        //    // Check to see if the package contains any signatures.
        //    if (!dsm.IsSigned)
        //        return false;   // The package is not signed.

        //    // Verify that all signatures are valid.
        //    VerifyResult result = dsm.VerifySignatures(false);
        //    if (result != VerifyResult.Success)
        //        return false;   // One or more digital signatures are invalid.

        //    // else if (result == VerifyResult.Success)
        //    return true;        // All signatures are valid.

        //}// end:ValidateSignatures()
        //private static void SignAllParts(Package pack)
        //{
        //    if (pack == null)
        //        throw new ArgumentNullException("SignAllParts(pack)");
        //    // Create the DigitalSignature Manager
        //    PackageDigitalSignatureManager dsm =
        //        new PackageDigitalSignatureManager(pack);
        //    dsm.CertificateOption =
        //        CertificateEmbeddingOption.InSignaturePart;
        //    // Create a list of all the part URIs in the pack to sign
        //    // (GetParts() also includes PackageRelationship parts).
        //    System.Collections.Generic.List<Uri> toSign =
        //        new System.Collections.Generic.List<Uri>();
        //    foreach (PackagePart packagePart in pack.GetParts())
        //    {
        //        // Add all package parts to the list for signing.
        //        toSign.Add(packagePart.Uri);
        //    }

        //    // Add the URI for SignatureOrigin PackageRelationship part.
        //    // The SignatureOrigin relationship is created when Sign() is called.
        //    // Signing the SignatureOrigin relationship disables counter-signatures.
        //    Uri uriPartSignatureOriginRelationship = PackUriHelper.CreatePartUri(
        //        new Uri(_openxmlDigitalSignatureUri, UriKind.Relative));
        //    toSign.Add(uriPartSignatureOriginRelationship);
        //    try
        //    {
        //        //use a testing certificate (need certificates for registered users?)
        //        string sCertificateName = "CN=kpboyle";
        //        X509Certificate2 cert = GetCertificate(sCertificateName);
        //        //this signs all parts and
        //        dsm.Sign(toSign, cert);
        //    }

        //    // If there are no certificates or the SmartCard manager is
        //    // not running, catch the exception and show an error message.
        //    catch (CryptographicException ex)
        //    {

        //    }

        //}// end:SignAllParts()
        private static X509Certificate2 GetCertificate(string certificateName)
        {
            X509Certificate2 certForRegisteredUser = null;
            //open the X.509 "Current User" store in read only mode.
            //need to open the registered user store (create one for all registered users?)
            X509Store certStore = new X509Store(StoreLocation.CurrentUser);
            certStore.Open(OpenFlags.ReadOnly);
            //place all certificates in an X509Certificate2Collection object.
            X509Certificate2Collection certCollection = certStore.Certificates;
            //find certificateName in the collection
            foreach (X509Certificate2 cert2 in certCollection)
            {
                if (string.IsNullOrEmpty(certificateName) == false)
                {
                    if (cert2.Subject == certificateName)
                    {
                        certForRegisteredUser = cert2;
                        break;
                    }
                }
                else
                {
                    //use last for testing
                    certForRegisteredUser = cert2;
                }
            }
            if (certForRegisteredUser == null)
            {
                throw new CryptographicException("The X.509 certificate could not be found.");
            }
            //close the certStore.
            certStore.Close();
            //return the certificate
            return certForRegisteredUser;
        }

        public static async Task<bool> CopyResourceToPackageAsync(
            ContentURI uri, string resourceRelFilePaths,
            int arrayPos, string rootDirectory, string newDirectory,
            string parentFileName, IDictionary<string, string> zipArgs)
        {
            bool bHasCopied = false;
            string[] arrResourceParams = resourceRelFilePaths.Split(GeneralHelpers.PARAMETER_DELIMITERS);
            string sResourceParams = string.Empty;
            string sResourceRelURI = string.Empty;
            string sResourceFullURI = string.Empty;
            //refactor: parallel didn't work with this loop - keep testing
            //Parallel.For(0, arrResourceParams.Length, i =>
            for (int i = 0; i < arrResourceParams.Length; i++)
            {
                sResourceParams = arrResourceParams[i];
                if (string.IsNullOrEmpty(sResourceParams) == false)
                {
                    //the array holds relative paths; convert to full path for file.copy and package
                    sResourceRelURI = GeneralHelpers.GetDelimitedSubstring(sResourceParams,
                        GeneralHelpers.STRING_DELIMITERS, arrayPos);
                    //remove the rel directories
                    string sBaseResourceURI = sResourceRelURI.Replace("../", string.Empty);
                    if ((!sBaseResourceURI.StartsWith(GeneralHelpers.WEBFILE_PATH_DELIMITER))
                        && (!rootDirectory.EndsWith(GeneralHelpers.FILE_PATH_DELIMITER)))
                    {
                        sBaseResourceURI = string.Concat(GeneralHelpers.WEBFILE_PATH_DELIMITER,
                            sBaseResourceURI);
                    }
                    FileStorageIO.PLATFORM_TYPES ePlatform
                        = uri.URIDataManager.PlatformType;
                    if (ePlatform == FileStorageIO.PLATFORM_TYPES.webserver)
                    {
                        bHasCopied = await CopyWebServerResourceToPackageAsync(
                            uri, rootDirectory, newDirectory,
                            parentFileName, zipArgs, sBaseResourceURI);
                    }
                    else if (ePlatform == FileStorageIO.PLATFORM_TYPES.azure)
                    {
                        bHasCopied = await CopyAzureResourceToPackageAsync(
                            uri, rootDirectory, newDirectory,
                            parentFileName, zipArgs, sBaseResourceURI);
                    }
                }
            }
            return bHasCopied;
        }
        public static async Task<bool> CopyWebServerResourceToPackageAsync(
            ContentURI uri, string rootDirectory, string newDirectory,
            string parentFileName, IDictionary<string, string> zipArgs, string baseResourceFullURI)
        {
            bool bHasCopied = false;
            string sPackageNewURI = string.Empty;
            //convert the full web uri to an equivalent filepath
            string sFileName = Path.GetFileName(baseResourceFullURI);
            //remove the http:\\www.devtreks.org\resources
            string sWebPath = string.Format("{0}{1}{2}",
                uri.URIDataManager.DefaultRootWebStoragePath,
                uri.URIDataManager.ResourceURIName,
                GeneralHelpers.WEBFILE_PATH_DELIMITER);
            string sResourceFilePath = baseResourceFullURI.Replace(sWebPath, string.Empty);
            sResourceFilePath = sResourceFilePath.Replace(
                GeneralHelpers.WEBFILE_PATH_DELIMITER, GeneralHelpers.FILE_PATH_DELIMITER);
            string sResourceFullURI = string.Concat(rootDirectory,
                uri.URIDataManager.ResourceURIName,
                GeneralHelpers.FILE_PATH_DELIMITER, sResourceFilePath);
            if (!string.IsNullOrEmpty(baseResourceFullURI))
            {
                sPackageNewURI = string.Concat(Path.Combine(newDirectory,
                    uri.URIDataManager.ResourceURIName),
                    GeneralHelpers.FILE_PATH_DELIMITER,
                    sFileName);
                Helpers.FileStorageIO.DirectoryCreate(uri, sPackageNewURI);
                //don't add the same file to the zip args (or the string array becomes out of synch)
                if (Helpers.FileStorageIO.URIAbsoluteExists(uri, sPackageNewURI) == false)
                {
                    await Helpers.FileStorageIO.CopyURIsAsync(uri, sResourceFullURI, sPackageNewURI);
                    //parentFileNameKey tells package how to relate resource to parentfile
                    if (!zipArgs.ContainsKey(sPackageNewURI))
                    {
                        zipArgs.Add(sPackageNewURI, parentFileName);
                    }
                    //using streams to copy: see openxml/Packaging sample (write example)
                }
            }
            return bHasCopied;
        }
        public static async Task<bool> CopyAzureResourceToPackageAsync(
            ContentURI uri, string rootDirectory, string newDirectory,
            string parentFileName, IDictionary<string, string> zipArgs, string baseResourceFullURI)
        {
            bool bHasCopied = false;
            string sPackageNewURI = string.Empty;
            if (!string.IsNullOrEmpty(baseResourceFullURI))
            {
                //get the filename
                string sFileName = Path.GetFileName(baseResourceFullURI);
                sPackageNewURI = string.Concat(Path.Combine(newDirectory,
                    uri.URIDataManager.ResourceURIName),
                    GeneralHelpers.FILE_PATH_DELIMITER,
                    sFileName);
                Helpers.FileStorageIO.DirectoryCreate(uri, sPackageNewURI);
                //don't add the same file to the zip args (or the string array becomes out of synch)
                if (Helpers.FileStorageIO.URIAbsoluteExists(uri, sPackageNewURI) == false)
                {
                    AzureIOAsync azureIO = new AzureIOAsync(uri);
                    string sBlobURIPath = string.Empty;
                    azureIO.SaveCloudFileInFileSystem(baseResourceFullURI,
                        sPackageNewURI);
                    azureIO = null;
                    //parentFileNameKey tells package how to relate resource to parentfile
                    if (!zipArgs.ContainsKey(sPackageNewURI))
                    {
                        zipArgs.Add(sPackageNewURI, parentFileName);
                    }
                }
            }
            return bHasCopied;
        }
        public static string MakeResourcePath(string currentResourceFullURI,
            string newPackageDirectory)
        {
            string sNewPackagePath = string.Empty;
            string sErrorMsg = string.Empty;
            string sMimeType = AppHelpers.Resources.GetMimeTypeFromFileExt(Path.GetExtension(currentResourceFullURI).ToLower(),
                ref sErrorMsg);
            string sPackageSubfolderName = GetPackageSubFolderName(currentResourceFullURI, sMimeType);
            sNewPackagePath = string.Concat(newPackageDirectory,
                GeneralHelpers.FILE_PATH_DELIMITER, sPackageSubfolderName,
                GeneralHelpers.FILE_PATH_DELIMITER,
                Path.GetFileName(currentResourceFullURI), string.Empty);
            return sNewPackagePath;
        }
        private static string GetPackageSubFolderName(string currentResourceFullURI,
            string mimeType)
        {
            string sPackageSubfolderName = "images";
            int iIndex = mimeType.IndexOf("image");
            if (iIndex < 0)
            {
                iIndex = mimeType.IndexOf("video");
                if (iIndex > 0)
                {
                    sPackageSubfolderName = "videos";
                }
                else
                {
                    iIndex = mimeType.IndexOf("audio");
                    if (iIndex > 0)
                    {
                        sPackageSubfolderName = "audios";
                    }
                    else
                    {
                        iIndex = mimeType.IndexOf("audio");
                        if (iIndex > 0)
                        {
                            sPackageSubfolderName = "audios";
                        }
                        else
                        {
                            iIndex = currentResourceFullURI.IndexOf(".xsl");
                            if (iIndex > 0)
                            {
                                sPackageSubfolderName = "stylesheets";
                            }
                            else
                            {
                                sPackageSubfolderName = "misc";
                            }
                        }
                    }
                }
            }
            return sPackageSubfolderName;
        }
        public static async Task<bool> CopyRelatedDataToPackageAsync(
            ContentURI uri, string currentFilePath,
            string packageName, string fileType, string newFilePath,
            bool needsAllRelatedData, IDictionary<string, string> zipArgs)
        {
            bool bHasCopied = false;
            FileStorageIO.PLATFORM_TYPES platform
                = uri.URIDataManager.PlatformType;
            if (platform == FileStorageIO.PLATFORM_TYPES.webserver)
            {
                bHasCopied = await CopyRelatedDataToWebServerPackageAsync(
                    uri, currentFilePath, packageName, fileType, newFilePath,
                    needsAllRelatedData, zipArgs);
            }
            else if (platform == FileStorageIO.PLATFORM_TYPES.azure)
            {
                AzureIOAsync azureIO = new AzureIOAsync(uri);
                bHasCopied = await azureIO.CopyRelatedDataToCloudServerPackageAsync(
                    uri, currentFilePath,
                    packageName, fileType, newFilePath, needsAllRelatedData, zipArgs);
            }
            return bHasCopied;
        }
        public static async Task<bool> CopyRelatedDataToWebServerPackageAsync(
            ContentURI uri, string currentFilePath,
            string packageName, string fileType, string newFilePath,
            bool needsAllRelatedData, IDictionary<string, string> zipArgs)
        {
            bool bHasCopied = false;
            DirectoryInfo oldDir = null;
            if (Path.HasExtension(currentFilePath))
            {
                //if it has an extension it needs the parent directory
                oldDir = new DirectoryInfo(
                    Path.GetDirectoryName(currentFilePath));
            }
            else
            {
                oldDir = new DirectoryInfo(currentFilePath);
            }
            DirectoryInfo newDir = null;
            if (Path.HasExtension(newFilePath))
            {
                //if it has an extension it needs the parent directory
                newDir = new DirectoryInfo(
                    Path.GetDirectoryName(newFilePath));
            }
            else
            {
                newDir = new DirectoryInfo(newFilePath);
            }
            //add siblings for everything
            bHasCopied = await AddSiblingFilesAsync(
                uri, oldDir, currentFilePath, packageName,
                fileType, newDir.FullName, zipArgs);
            if (needsAllRelatedData)
            {
                //copy children subfolder data
                //html subdirectories get put in root path so they can find resources
                bool bNeedsNewSubDirectories =
                    (fileType.EndsWith(AppHelpers.Resources.FILEEXTENSION_TYPES.xml.ToString()))
                    ? true : false;
                bool bHasCopiedDirs
                    = await GeneralHelpers.CopyDirectoriesAsync(
                        uri, currentFilePath,
                    newFilePath, bNeedsNewSubDirectories);
                //add them to zipargs
                bool bHasAdded = await AddChildrenFilesToZipArgsAsync(newDir, packageName, fileType, zipArgs);
            }
            return bHasCopied;
        }

        private static async Task<bool> AddSiblingFilesAsync(
            ContentURI uri, DirectoryInfo folder,
            string currentFilePath, string packageName, string fileType,
            string newFilePath, IDictionary<string, string> zipArgs)
        {
            bool bHasCopied = false;
            string sPackageFilePath = string.Empty;
            if (folder != null)
            {
                string sNoCalcDocExt = string.Concat(Helpers.GeneralHelpers.FILENAME_DELIMITER,
                    Helpers.GeneralHelpers.FILENAME_EXTENSIONS.addin.ToString());
                FileInfo[] files = folder.GetFiles();
                if (files != null)
                {
                    string sFileExtension = string.Empty;
                    foreach (FileInfo file in files)
                    {
                        if (fileType == Helpers.GeneralHelpers.EXTENSION_CSV)
                        {
                            bHasCopied = AddSiblingCSVFilesAsync(
                                uri, file, currentFilePath, sNoCalcDocExt,
                                packageName, fileType, newFilePath, zipArgs);
                        }
                        else
                        {
                            //current file is already in the package
                            if (!file.FullName.Equals(currentFilePath))
                            {
                                //package either all html or all xml files
                                if (Path.GetExtension(file.FullName).Equals(fileType))
                                {
                                    //v174 exclude calcdocs because too much unneeded docs in package
                                    if (!file.Name.Contains(sNoCalcDocExt))
                                    {
                                        sPackageFilePath = Path.Combine(newFilePath, Path.GetFileName(file.FullName));
                                        bHasCopied = await FileStorageIO.CopyURIsAsync(
                                            uri, file.FullName, sPackageFilePath);
                                        if (Helpers.FileStorageIO.URIAbsoluteExists(
                                            uri, sPackageFilePath))
                                        {
                                            if (!zipArgs.ContainsKey(sPackageFilePath))
                                            {
                                                zipArgs.Add(sPackageFilePath, packageName);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return bHasCopied;
        }
        private static bool AddSiblingCSVFilesAsync(
            ContentURI uri, FileInfo file,
            string currentFilePath, string noCalcDocExt, string packageName, string fileType,
            string newFilePath, IDictionary<string, string> zipArgs)
        {
            bool bHasCopied = false;
            string sPackageFilePath = string.Empty;
            //convert xml files
            if (Path.GetExtension(file.FullName).Equals(Helpers.GeneralHelpers.EXTENSION_XML))
            {
                //v174 exclude calcdocs because too much unneeded docs in package
                if (!file.Name.Contains(noCalcDocExt))
                {
                    //to csv
                    string sCSVFileName = Path.GetFileName(file.FullName).Replace(Helpers.GeneralHelpers.EXTENSION_XML,
                        Helpers.GeneralHelpers.EXTENSION_CSV);
                    sPackageFilePath = Path.Combine(newFilePath, sCSVFileName);
                    ContentURI docToCalcURI = new ContentURI();
                    docToCalcURI.URIDataManager.TempDocPath = sPackageFilePath;
                    ObservationTextBuilder csvBuilder = new ObservationTextBuilder();
                    IDictionary<string, string> fileOrFolderPaths = new Dictionary<string, string>();
                    fileOrFolderPaths.Add("1", file.FullName);
                    bHasCopied = csvBuilder.StreamAndSaveObservation(docToCalcURI, fileOrFolderPaths);
                    if (Helpers.FileStorageIO.URIAbsoluteExists(
                        uri, sPackageFilePath))
                    {
                        if (!zipArgs.ContainsKey(sPackageFilePath))
                        {
                            zipArgs.Add(sPackageFilePath, packageName);
                        }
                    }
                }
            }
            return bHasCopied;
        }
        public static async Task<bool> AddChildrenFilesToZipArgsAsync(string newFilePath,
            string packageName, string fileType,
            IDictionary<string, string> zipArgs)
        {
            bool bHasCopied = false;
            DirectoryInfo newDir = null;
            if (Path.HasExtension(newFilePath))
            {
                //if it has an extension it needs the parent directory
                newDir = new DirectoryInfo(
                    Path.GetDirectoryName(newFilePath));
            }
            else
            {
                newDir = new DirectoryInfo(newFilePath);
            }
            bHasCopied = await AddChildrenFilesToZipArgsAsync(newDir, packageName, fileType, zipArgs);
            return bHasCopied;
        }
        public static async Task<bool> AddChildrenFilesToZipArgsAsync(
            DirectoryInfo dir, string packageName, string fileType,
            IDictionary<string, string> zipArgs)
        {
            bool bHasCopied = false;
            //add any new files added to root directory
            foreach (FileInfo file in dir.GetFiles())
            {
                if (!zipArgs.ContainsKey(file.FullName))
                {
                    //package either all html or all xml files
                    if (Path.GetExtension(file.FullName).Equals(fileType))
                    {
                        zipArgs.Add(file.FullName, packageName);
                    }
                }
            }
            //files have alread been copied into
            DirectoryInfo[] dirs = dir.GetDirectories();
            //add any new subfolders added
            foreach (DirectoryInfo folder in dirs)
            {
                if (!folder.FullName.EndsWith("stylesheets")
                    && !folder.FullName.EndsWith("scripts"))
                {
                    FileInfo[] files = folder.GetFiles();
                    foreach (FileInfo file in files)
                    {
                        if (!zipArgs.ContainsKey(file.FullName))
                        {
                            //package either all html or all xml files
                            if (Path.GetExtension(file.FullName).Equals(fileType))
                            {
                                zipArgs.Add(file.FullName, packageName);
                            }
                        }
                    }
                    //check for further subfolders
                    bHasCopied = await AddChildrenFilesToZipArgsAsync(folder, packageName, fileType, zipArgs);
                }
            }
            return bHasCopied;
        }
    }
}


text:
import pytest
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy_utils import cast_if

@pytest.fixture(scope='class')
def base():
    return declarative_base()

@pytest.fixture(scope='class')
def article_cls(base):
    class Article(base):
        __tablename__ = 'article'
        id = sa.Column(sa.Integer, primary_key=True)
        name = sa.Column(sa.String)
        name_synonym = sa.orm.synonym('name')

    return Article

class TestCastIf(object):
    def test_column(self, article_cls):
        expr = article_cls.__table__.c.name
        assert cast_if(expr, sa.String) is expr

    def test_column_property(self, article_cls):
        expr = article_cls.name.property
        assert cast_if(expr, sa.String) is expr

    def test_instrumented_attribute(self, article_cls):
        expr = article_cls.name
        assert cast_if(expr, sa.String) is expr

    def test_synonym(self, article_cls):
        expr = article_cls.name_synonym
        assert cast_if(expr, sa.String) is expr

    def test_scalar_selectable(self, article_cls):
        expr = sa.select([article_cls.id]).as_scalar()
        assert cast_if(expr, sa.Integer) is expr

    def test_scalar(self):
        assert cast_if('something', sa.String) == 'something'

redpajama_set_name: RedPajamaGithub


text:
import MySQLdb

# Open database connection
#mysql -u anonymous -h ensembldb.ensembl.org
db = MySQLdb.connect("ensembldb.ensembl.org","anonymous","","homo_sapiens_core_75_37" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print "Database version : %s " % data

cursor.execute( """ SELECT transcript.stable_id, xref.display_label FROM transcript, object_xref, xref,external_db WHERE transcript.transcript_id = object_xref.ensembl_id AND object_xref.ensembl_object_type = 'Transcript' AND object_xref.xref_id = xref.xref_id AND xref.external_db_id = external_db.external_db_id AND external_db.db_name = 'RefSeq_mRNA'; """ )
cursor.fetchone()

# disconnect from server
db.close()


text:
using CheckSum.Common;
using NUnit.Framework;

namespace checksum.unit.test.Common
{
    [TestFixture]
    public class AlgorithmTest
    {

        [TestFixture]
        public class Md5AlgorithmTest : AlgorithmTest
        {

            [Test]
            public void IsValid_returnsTrue()
            {
                var algorithm = Algorithm.MD5;
                Assert.IsTrue(algorithm.IsValid());
            }

        }

        [TestFixture]
        public class Sha1AlgorithmTest : AlgorithmTest
        {

            [Test]
            public void IsValid_returnsTrue()
            {
                var algorithm = Algorithm.SHA1;
                Assert.IsTrue(algorithm.IsValid());
            }

        }

        [TestFixture]
        public class Sha2AlgorithmTest : AlgorithmTest
        {
            [Test]
            public void IsValid_returnsTrue()
            {
                var algorithm = Algorithm.SHA2;
                Assert.IsTrue(algorithm.IsValid());
            }
        }

        [TestFixture]
        public class UndefinedAlgorithmTest : AlgorithmTest
        {
            [Test]
            public void IsValid_returnsFalse()
            {
                var algorithm = Algorithm.Undefined;
                Assert.IsFalse(algorithm.IsValid());
            }
        }

    }
}


text:
using System.Linq;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using NUnit.Framework;
using XNAControls.Test.Helpers;

namespace XNAControls.Test
{
    [TestFixture]
    public class TextSplitterTest
    {
        private TextSplitter _ts;
        private static TestGameManager _gameManager;
        private static SpriteFont _spriteFont;

        [OneTimeSetUp]
        public static void ClassInitialize()
        {
            _gameManager = new TestGameManager();
            _spriteFont = LoadSpriteFontFromWorkingDirectory();
        }

        [OneTimeTearDown]
        public static void ClassCleanup()
        {
            _gameManager?.Dispose();
        }

        [SetUp]
        public void SetUp()
        {
            _ts = new TextSplitter("", _spriteFont);
        }

        [Test]
        [Timeout(2000)]
        public void GivenShortMessage_WhenSplittingAt200px_NeedProcessingShouldBeFalse()
        {
            _ts.Text = "Test Message";
            _ts.LineLength = 200;

            Assert.IsFalse(_ts.NeedsProcessing);
        }

        [Test]
        [Timeout(2000)]
        public void GivenShortMessage_WhenSplittingAt200px_ShouldBeOneLineOfText()
        {
            _ts.Text = "Test Message";
            _ts.LineLength = 200;

            var result = _ts.SplitIntoLines();

            Assert.AreEqual(1, result.Count);
        }

        [Test]
        [Timeout(2000)]
        public void GivenLongMessageWithLongWords1_WhenSplittingAt200px_ShouldBe3LinesOfText()
        {
            _ts.Text = "Testttttttttttttttttttttttttttttttttttttttttttttttttttt messageeeeeeeeeeeeeeeeeeeeeeeeee oneee";
            _ts.LineLength = 200;

            var result = _ts.SplitIntoLines();

            Assert.AreEqual(3, result.Count);
        }

        [Test]
        [Timeout(2000)]
        public void GivenLongMessageWithLongWords2_WhenSplittingAt200px_ShouldBe5LinesOfText()
        {
            _ts.Text = "Test messageeeeeeeeeeeeeeeeeeeeeeeeee oneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
            _ts.LineLength = 200;

            var result = _ts.SplitIntoLines();

            Assert.AreEqual(4, result.Count);
        }

        [Test]
        [Timeout(2000)]
        public void GivenLongMessageWithShortWords_WhenSplittingAt200px_ShouldBe3LinesOfText()
        {
            _ts.Text = "This is a test message in which the words should be able to easily be split into multiple lines";
            _ts.LineLength = 200;

            var result = _ts.SplitIntoLines();

            Assert.AreEqual(3, result.Count);
        }

        [Test]
        [Timeout(2000)]
        public void GivenLongMessageAndLongWordsAndLineEnd_WhenSplittingAt200px_ShouldEndEachLineExceptLastWithLineEnd()
        {
            _ts.Text = "Test messageeeeeeeeeeeeeeeeeeeeeeeeee oneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
            _ts.LineLength = 200;
            _ts.LineEnd = "---";

            var result = _ts.SplitIntoLines();

            Assert.IsTrue(result.Except(new[] {result.Last()}).All(x => x.EndsWith(_ts.LineEnd)));
            Assert.IsFalse(result.Last().EndsWith(_ts.LineEnd));
        }

        [Test]
        [Timeout(2000)]
        public void GivenLongMessageAndShortWordsAndLineEnd_WhenSplittingAt200px_ShouldEndEachLineExceptLastWithLineEnd()
        {
            _ts.Text = "This is a test message in which the words should be able to easily be split into multiple lines";
            _ts.LineLength = 200;
            _ts.LineEnd = "---";

            var result = _ts.SplitIntoLines();

            Assert.IsTrue(result.Except(new[] { result.Last() }).All(x => x.EndsWith(_ts.LineEnd)));
            Assert.IsFalse(result.Last().EndsWith(_ts.LineEnd));
        }

        [Test]
        [Timeout(2000)]
        public void GivenLongMessageWithNewLinesAndShortWordsAndLineEnd_WhenSplittingAt200px_ShouldEndEachLineExceptLastWithLineEnd()
        {
            _ts.Text = "This is a test message \nin which the words should \n\n\nbe able to easily be \nsplit into multiple\n\n lines";
            _ts.LineLength = 200;
            _ts.LineEnd = "---";

            var result = _ts.SplitIntoLines();

            Assert.IsTrue(result.Where(x => x != string.Empty).Except(new[] { result.Last() }).All(x => x.EndsWith(_ts.LineEnd)));
            Assert.IsFalse(result.Last().EndsWith(_ts.LineEnd));
        }

        [Test]
        [Timeout(2000)]
        public void GivenLongMessageAndLongWordsAndLineIndent_WhenSplittingAt200px_ShouldStartEachLineExceptFirstWithLineIndent()
        {
            _ts.Text = "Test messageeeeeeeeeeeeeeeeeeeeeeeeee oneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
            _ts.LineLength = 200;
            _ts.LineIndent = "        ";

            var result = _ts.SplitIntoLines();

            Assert.IsFalse(result.First().StartsWith(_ts.LineIndent));
            Assert.IsTrue(result.Except(new[] { result.First() }).All(x => x.StartsWith(_ts.LineIndent)));
        }

        [Test]
        [Timeout(2000)]
        public void GivenLongMessageAndShortWordsAndLineIndent_WhenSplittingAt200px_ShouldStartEachLineExceptFirstWithLineIndent()
        {
            _ts.Text = "This is a test message in which the words should be able to easily be split into multiple lines";
            _ts.LineLength = 200;
            _ts.LineIndent = "        ";

            var result = _ts.SplitIntoLines();

            Assert.IsFalse(result.First().StartsWith(_ts.LineIndent));
            Assert.IsTrue(result.Except(new[] { result.First() }).All(x => x.StartsWith(_ts.LineIndent)));
        }

        [Test]
        [Timeout(2000)]
        public void GivenMessageShorterThanLineLength_WithTrailingNewLines_WhenSplittingAt254px_HasExpectedLineCountAndContents()
        {
            const string ExpectedString = "A short message";
            _ts.Text = $"{ExpectedString}\n\n";
            _ts.LineLength = 254;

            var result = _ts.SplitIntoLines();

            Assert.That(result, Has.Count.EqualTo(2));
            CollectionAssert.AreEqual(new[] { ExpectedString, string.Empty }, result);
        }

        [Test]
        public void GivenMessageWithMultipleNewLineCharacters_WhenSplittingAt254px_HasExpectedLineCountAndContents()
        {
            var expectedLines = new[]
            {
                "A short message",
                "",
                "Followed by some",
                "Other content"
            };

            _ts.Text = $"{expectedLines[0]}\n{expectedLines[1]}\n{expectedLines[2]}\n{expectedLines[3]}\n";
            _ts.LineLength = 254;

            var result = _ts.SplitIntoLines();

            Assert.That(result, Has.Count.EqualTo(4));
            CollectionAssert.AreEqual(expectedLines, result);
        }

        private static SpriteFont LoadSpriteFontFromWorkingDirectory()
        {
            using (var content = new ContentManager(_gameManager.Game.Services, TestContext.CurrentContext.TestDirectory))
            {
                return content.Load<SpriteFont>("font_for_testing");
            }
        }
    }
}


text:
package org.broad.igv.sam.cram;

import htsjdk.samtools.*;
import org.broad.igv.feature.genome.GenomeManager;
import org.junit.Before;
import org.junit.Test;

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

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;

/**
 * Created by jrobinso on 5/25/16.
 */

public class IGVReferenceSourceTest {

    public static final String FASTA_URL = "https://s3.amazonaws.com/igv.broadinstitute.org/genomes/seq/hg38/hg38.fa";
    public static final String COMPRESSED_FASTA_URL = "https://s3.amazonaws.com/igv.broadinstitute.org/genomes/seq/hg38/hg38.fa.gz";
    public static final String EXPECTED_REFERENCE_BASES = "AAACCCAGGGCAAAGAATCTGGCCCTA"; //bases at 22:27198875-271988902

    @Before
    public void setUp() throws Exception {

    }

    private void assertReferenceReqionRequestsWork(final String fastaUrl) throws IOException {
        GenomeManager.getInstance().loadGenome(fastaUrl, null);

        IGVReferenceSource refSource = new IGVReferenceSource();
        String expected = EXPECTED_REFERENCE_BASES;
        SAMSequenceRecord rec = new SAMSequenceRecord("22", 50818468);
        byte[] bases = refSource.getReferenceBasesByRegion(rec, 27198874, expected.length());
        assertEquals(expected.length(), bases.length);
        assertEquals(expected, new String(bases, StandardCharsets.US_ASCII));
    }

    @Test
    public void testGetReferenceBasesByRegion() throws Exception {
        assertReferenceReqionRequestsWork(IGVReferenceSourceTest.FASTA_URL);
    }

    @Test
    public void testGetReferenceBasesByRegionCompressed() throws Exception {
        assertReferenceReqionRequestsWork(COMPRESSED_FASTA_URL);
    }

    @Test
    public void testGetReferenceBasesCompressed() throws Exception {

        GenomeManager.getInstance().loadGenome(COMPRESSED_FASTA_URL, null);

        IGVReferenceSource refSource = new IGVReferenceSource();
        SAMSequenceRecord rec = new SAMSequenceRecord("22", 50818468);
        byte[] bases = refSource.getReferenceBases(rec, false);

        assertEquals(50818468, bases.length);

        assertEquals('N', bases[0]);
        String expected = EXPECTED_REFERENCE_BASES;
        String actual = new String(Arrays.copyOfRange(bases, 27198874, 27198874 + expected.length()), StandardCharsets.US_ASCII);
        assertEquals(expected, actual);
    }

//    @Test
//    public void testCompressedTiming() throws Exception {
//
//        String fastaURL = "https://s3.amazonaws.com/igv.broadinstitute.org/genomes/seq/hg38/hg38.fa";
//        GenomeManager.getInstance().loadGenome(fastaURL, null);
//        IGVReferenceSource refSource = new IGVReferenceSource();
//        SAMSequenceRecord rec = new SAMSequenceRecord("1", 248956422);
//
//        long t = System.currentTimeMillis();
//        byte[] bases = refSource.getReferenceBases(rec, false);
//        assertEquals(248956422, bases.length);
//        long dt = System.currentTimeMillis() - t;
//
//
//        fastaURL = "https://s3.amazonaws.com/igv.broadinstitute.org/genomes/seq/hg38/hg38.fa.gz";
//        GenomeManager.getInstance().loadGenome(fastaURL, null);
//        refSource = new IGVReferenceSource();
//        rec = new SAMSequenceRecord("1", 248956422);
//
//        long t1 = System.currentTimeMillis();
//        bases = refSource.getReferenceBases(rec, false);
//        assertEquals(248956422, bases.length);
//        long dt1 = System.currentTimeMillis() - t1;
//
//        System.out.println(dt + "    " + dt1);
//
//        assertTrue(dt1 < dt);
//
//    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <base data-ice="baseUrl" href="../../">
  <title data-ice="title">Rule | API Document</title>
  <link type="text/css" rel="stylesheet" href="css/style.css">
  <link type="text/css" rel="stylesheet" href="css/prettify-tomorrow.css">

  Home

  Reference
  Source

  Repository

    <input class="search-input">

CGrammar

CRule

VBACK

VCOLOR

VFORWARD

VPOP

VPUSH

VROTATE

VSCALE

VRESTRICTED

import Rule from 'arborjs/src/rule.js'

  public
  class

  | source

Rule

Encapsulates a single production rule in a grammar.

Constructor Summary

Public Constructor

      public

           constructor(predicate: string, production: string): Rule

Creates a new rule instance.

Member Summary

Public Members

      public

           conditionals: *

      public

           parameters: *

      public

           predecessor: *

      public

           production: *

      public

           symbol: *

Method Summary

Public Methods

      public

           addCondition(condition: string, production: string): Rule

Adds a condition production to the rule.

      public

           evaluate(arglist: number[]): Object[]

Given an ordered argument list, returns an ordered array of tokens produced by the the rule.

      public

           virtualize(expression: string): function(ctx: Object)

Virtualizes simple expressions for repeated evaluation.

Public Constructors

    public

    constructor(predicate: string, production: string): Rule

      source

Creates a new rule instance.

Params:

Name	Type	Attribute	Description

      predicate
      string

Rule predicate that expands into a production when interpreted.

      production
      string

nullable: true

The default production of this rule. If none is provided, the identity
production is assumed.

Return:

        Rule

A new rule instance.

Public Members

    public

    conditionals: *

      source

    public

    parameters: *

      source

    public

    predecessor: *

      source

    public

    production: *

      source

    public

    symbol: *

      source

Public Methods

    public

    addCondition(condition: string, production: string): Rule

      source

Adds a condition production to the rule. Returns target rule and may be chained.

Params:

Name	Type	Attribute	Description

      condition
      string

Conditional expression to evaluate.

      production
      string

Production emitted when conditional expression is true.

Return:

        Rule

The rule to which the conditional production was added.

    public

    evaluate(arglist: number[]): Object[]

      source

Given an ordered argument list, returns an ordered array of tokens produced by the the rule.

Params:

Name	Type	Attribute	Description

      arglist
      number[]

Numeric arguments to bind to predecessor parameters.

Return:

        Object[]

List of generated tokens containing a symbol and evaluated parameters.

    public

    virtualize(expression: string): function(ctx: Object)

      source

Virtualizes simple expressions for repeated evaluation.

Params:

Name	Type	Attribute	Description

      expression
      string

nullable: false

The simple expression to virtualize.

Return:

        function(ctx: Object)

Function that evaluates the expression for a provided context.

  Generated by ESDoc(0.4.7)


text:
Capistrano::Configuration.instance(:must_exist).load do
  namespace :deprec do
    namespace :swiftiply do

      set(:swiftiply_conf_dir) { "/etc/swiftiply/" }
      set(:swiftiply_conf) { "/etc/swiftiply/swiftiply.conf" }
      set(:swiftiply_pid_file) { "/var/run/swiftiply/swiftiply.pid" }
      set :swiftiply_port, 9000

      # No Rubygems loading (citing reasons of speed)
      SRC_PACKAGES[:swiftiply] = {
        :filename => 'swiftiply-0.6.1.1.tar.bz2',
        :md5sum => "c2ff6de68701f778fd7d3d40b907e562  swiftiply-0.6.1.1.tar.bz2",
        :dir => 'swiftiply-0.6.1.1',
        :url => "http://swiftiply.swiftcore.org/files/swiftiply-0.6.1.1.tar.bz2",
        :unpack => "tar jxf swiftiply-0.6.1.1.tar.bz2;",
        :install => 'ruby setup.rb;'
      }

      # No Rubygems loading (citing reasons of speed)
      SRC_PACKAGES[:event_machine] = {
        :filename => 'eventmachine-0.10.0.tar.gz',
        :md5sum => "5f9dd6419c7ae0e3af569d315d8ee4f2  eventmachine-0.10.0.tar.gz",
        :dir => 'eventmachine-0.10.0',
        :url => "http://files.rubyforge.vm.bytemark.co.uk/eventmachine/eventmachine-0.10.0.tar.gz",
        :unpack => "tar zxf eventmachine-0.10.0.tar.gz;",
        :install => 'ruby setup.rb;'
      }

      desc "Install swiftiply"
      task :install, :roles => :web do
        install_deps
        deprec2.download_src(SRC_PACKAGES[:swiftiply], src_dir)
        deprec2.install_from_src(SRC_PACKAGES[:swiftiply], src_dir)
      end

      task :install_deps do
        deprec2.download_src(SRC_PACKAGES[:event_machine], src_dir)
        deprec2.install_from_src(SRC_PACKAGES[:event_machine], src_dir)
      end

      SYSTEM_CONFIG_FILES[:swiftiply] = [

        {:template => "swiftiply-init-script",
         :path => '/etc/init.d/swiftiply',
         :mode => 0755,
         :owner => 'root:root'},

      ]

      desc "Generate configuration file(s) for swiftiply"
      task :config_gen do
        SYSTEM_CONFIG_FILES[:swiftiply].each do |file|
          deprec2.render_template(:swiftiply, file)
        end
      end

      desc 'Deploy configuration files(s) for swiftiply'
      task :config, :roles => :web do
        deprec2.push_configs(:swiftiply, SYSTEM_CONFIG_FILES[:swiftiply])
        deprec2.mkdir(swiftiply_conf_dir, :via => :sudo)
      end

      task :start, :roles => :web do
        send(run_method, "/etc/init.d/swiftiply start")
      end

      task :stop, :roles => :web do
        send(run_method, "/etc/init.d/swiftiply stop")
      end

      task :restart, :roles => :web do
        send(run_method, "/etc/init.d/swiftiply restart")
      end

      task :reload, :roles => :web do
        send(run_method, "/etc/init.d/swiftiply reload")
      end

      # This task will be called from a handler's config_project
      # merges a yml file into the swiftiply conf
      task :config_merge, :roles => :web do
      end

      # This task will be called from a handler's config_project
      # unmerges a yml file into the swiftiply conf
      task :config_unmerge, :roles => :web do
      end

      task :activate, :roles => :web do
        send(run_method, "update-rc.d swiftiply defaults")
      end

      task :deactivate, :roles => :web do
        send(run_method, "update-rc.d swiftiply defaults")
      end

      task :backup, :roles => :web do
      end

      task :restore, :roles => :web do
      end

    end
  end
end


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/shiyuncard_panel"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:layout_marginLeft="@dimen/pay_qrcode_pay_panel_marginleft"
              android:layout_marginTop="@dimen/pay_shiyuncard_margintop"
              android:layout_weight="2.1"
              android:orientation="vertical">

    <TextView
        android:id="@+id/account_label"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/pay_shiyuncard_account_label"
        android:textSize="@dimen/pay_shiyuncard_account_label_textsize"/>

    <TextView
        android:id="@+id/recharge_error_msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textColor="#fe8109"
        android:textSize="@dimen/pay_shiyuncard_account_label_textsize"
        android:visibility="gone"/>

    <EditText
        android:id="@+id/shiyuncard_input"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/pay_shiyuncard_input_margintop"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:nextFocusDown="@+id/shiyuncard_submit"
        android:nextFocusLeft="@id/videocard"
        android:paddingLeft="5dip"
        android:singleLine="true"
        android:textSize="32sp"
    />

    <Button
        android:id="@+id/shiyuncard_submit"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/pay_channel_weixin_height"
        android:layout_gravity="center"
        android:layout_marginTop="@dimen/pay_shiyuncard_submit_margintop"
        android:background="@drawable/paychannel_btn_selector"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:text="@string/pay_shiyuncard_submit_label"
        android:textColor="#FFF8F8FF"
        android:textSize="@dimen/pay_shiyuncard_submit_textsize"/>

</LinearLayout>


text:
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Simple Test</title>

  <link rel="stylesheet" type="text/css" href="../jquery.jqplot.min.css" />
  <link rel="stylesheet" type="text/css" href="examples.css" />

    <?php include "topbanner.inc"; ?>

    <?php include "nav.inc"; ?>


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

<TITLE>
NullAudioDevice
</TITLE>

<META NAME="keywords" CONTENT="javazoom.jl.player.NullAudioDevice class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

javazoom.jl.player

Class NullAudioDevice

java.lang.Object
  javazoom.jl.player.AudioDeviceBase
      javazoom.jl.player.NullAudioDevice

All Implemented Interfaces:
AudioDevice

public class NullAudioDevice
extends AudioDeviceBase

The NullAudioDevice implements a silent, no-op
 audio device. This is useful for testing purposes.

Since:

0.0.8

Constructor Summary

NullAudioDevice()

Method Summary

 int
getPosition()

          Retrieves the current playback position in milliseconds.

Methods inherited from class javazoom.jl.player.AudioDeviceBase

close, closeImpl, flush, flushImpl, getDecoder, isOpen, open, openImpl, setOpen, write, writeImpl

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

NullAudioDevice

public NullAudioDevice()

Method Detail

getPosition

public int getPosition()

Description copied from interface: AudioDevice

Retrieves the current playback position in milliseconds.

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

JavaZOOM 1999-2008


text:
using System;
using System.Collections.Generic;
using System.Text;
using XenAPI;

namespace XenAdmin.Commands
{
    internal abstract class SRCommand : Command
    {
        public SRCommand()
        {
        }

        public SRCommand(IMainWindow mainWindow, IEnumerable<SelectedItem> selection)
            : base(mainWindow, selection)
        {
        }

        public SRCommand(IMainWindow mainWindow, SR selection)
            : base(mainWindow, selection)
        {
        }

        /// <summary>
        /// Converts the storage link repositories in the selected selection into SRs.
        /// </summary>
        private static SelectedItemCollection ConvertStorageLinkRepositories(IEnumerable<SelectedItem> selection)
        {
            Util.ThrowIfParameterNull(selection, "selection");

            return new SelectedItemCollection(new List<SelectedItem>(selection).ConvertAll(s =>
            {
                if (s.XenObject is StorageLinkRepository)
                {
                    SR sr = ((StorageLinkRepository)s.XenObject).SR(ConnectionsManager.XenConnectionsCopy);
                    return new SelectedItem(sr, sr.Connection, s.HostAncestor, s.PoolAncestor);
                }
                return s;
            }));
        }

        protected override SelectedItemCollection GetSelectionCore()
        {
            return ConvertStorageLinkRepositories(base.GetSelectionCore());
        }
    }
}


text:
package org.mammon.messaging.impl;

import java.io.File;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

import org.mammon.messaging.DirectedMessage;
import org.mammon.messaging.DualIdentityTransitionable;
import org.mammon.messaging.ForwardRemote;
import org.mammon.messaging.Identifiable;
import org.mammon.messaging.Message;
import org.mammon.messaging.MessageEmitter;
import org.mammon.messaging.Transactable;
import org.mammon.messaging.Transitionable;
import org.mammon.messaging.ObjectStorage.StoredObject;

public class MessagingSystem {

	private static final Logger LOG = Logger.getLogger(MessagingSystem.class.getName());

	private final JsonUtil jsonUtil;

	private final FileObjectStorage storage;

	private final Map<Class<?>, StateHandler<?>> stateHandlers = new HashMap<Class<?>, StateHandler<?>>();

	private final ExecutorService executor = Executors.newSingleThreadExecutor();

	private final RemoteMessaging remoteMessaging;

	public MessagingSystem(JsonUtil jsonUtil, String nodeId) throws IOException {
		this.jsonUtil = jsonUtil;
		jsonUtil.registerClass(StringRedeliverableMessage.class);
		jsonUtil.registerClass(NetworkMessage.class);
		jsonUtil.registerClass(PublishObject.class);
		storage = new FileObjectStorage(jsonUtil, new File("../storage." + nodeId));
//		storage = new ExampleObjectStorage(jsonUtil);
		registerStateHandler(MessageEmitter.class, new MessageEmitterHandler());
		remoteMessaging = new RemoteMessaging(this, jsonUtil, nodeId);
	}

	public void restoreFromObjectStorage() {
		for (StoredObject storedObject : storage) {
			Identifiable object = storedObject.getObject();
			if (!(object instanceof StringRedeliverableMessage)) {
				enteredState(object, storedObject.getReplyTo());
			}
		}
	}

	public void shutdown() {
		remoteMessaging.shutdown();
		executor.shutdown();
	}

	public void connect(String remoteHost) throws UnknownHostException, IOException {
		remoteMessaging.connect(remoteHost);
	}

	public String publish(String remoteId, Identifiable objectId) {
		return remoteMessaging.publish(remoteId, objectId);
	}

	public void awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
		executor.awaitTermination(timeout, unit);
	}

	public void addObject(Identifiable object) {
		addObject(object, false);
	}

	public void addObject(Identifiable object, boolean publishToAll) {
		storage.store(object, null);
		enteredState(object, null);
		if (publishToAll) {
			remoteMessaging.publish(null, object);
		}
	}

	public <C> void registerStateHandler(Class<C> clazz, StateHandler<C> stateHandler) {
		stateHandlers.put(clazz, stateHandler);
	}

	private <C> void enteredState(C object, String enteredBy) {
		Class<?> clazz = object.getClass();
		for (Entry<Class<?>, StateHandler<?>> entry : stateHandlers.entrySet()) {
			if (entry.getKey().isAssignableFrom(clazz)) {
				StateHandler<C> stateHandler = (StateHandler<C>) entry.getValue();
				stateHandler.enteredState(object, enteredBy);
			}
		}
	}

	private <C> void leftState(C object) {
		Class<?> clazz = object.getClass();
		for (Entry<Class<?>, StateHandler<?>> entry : stateHandlers.entrySet()) {
			if (entry.getKey().isAssignableFrom(clazz)) {
				StateHandler<C> stateHandler = (StateHandler<C>) entry.getValue();
				stateHandler.leftState(object);
			}
		}
	}

	public void sendMessage(DirectedMessage message) {
		sendMessage(message, message.getDestination(), null);
	}

	void sendMessage(Message message, final String destination, final String replyDestination) {
		final String serializedMessage = storage.serializeObject(message, null);
		if (destination == null) {
			LOG.warning("Destination for message is null: " + serializedMessage);
		}

		executor.execute(new Runnable() {

			@Override
			public void run() {
				Message message = (Message) jsonUtil.deserializeObject(serializedMessage, null);
				Identifiable destObj = storage.get(destination);
				LOG.fine("Message " + serializedMessage + " to " + destination + " (" + destObj + ")");
				Object newObject = null;

				if (destObj == null || destObj.getClass().isAnnotationPresent(ForwardRemote.class)) {
					if (!remoteMessaging.sendMessage(message, destination, replyDestination)) {
						LOG.info("Discarded message: " + serializedMessage);
					}
				} else if (destObj instanceof Transactable) {
					Transactable t = (Transactable) destObj;
					Object reply = t.transact(message);
					if (reply != null) {
						if (reply instanceof DirectedMessage) {
							sendMessage((Message) reply, ((DirectedMessage) reply).getDestination(), destination);
						} else if (reply instanceof Message && replyDestination != null) {
							sendMessage((Message) reply, replyDestination, destination);
						} else if (reply instanceof String) {
							sendMessage(message, (String) reply, replyDestination);
						} else {
							newObject = reply;
						}
					}
				} else if (destObj instanceof Transitionable) {
					Transitionable t = (Transitionable) destObj;
					newObject = t.transition(message);
					leftState(destObj);
					storage.remove(destination);

					if (newObject instanceof Message) {
						newObject = new StringRedeliverableMessage(destination.toString(), message, (Message) newObject);
					}
				}

				if (newObject != null) {
					if (newObject instanceof Identifiable) {
						Identifiable newIdentifiable = (Identifiable) newObject;
						storage.store(newIdentifiable, replyDestination);
						Identifiable testObj = newIdentifiable;
						if (newObject instanceof DualIdentityTransitionable) {
							testObj = ((DualIdentityTransitionable) newObject);
						}
						if (newObject instanceof Transitionable && destination.equals(testObj.getIdentity())) {
							Object testState = ((Transitionable) testObj).transition(message);
							if (testState == null || !testState.equals(newObject)) {
								LOG.warning(message + " transitioned " + destObj + " into " + newObject
										+ ", but fails Redeliverable requirement");
							}
						}
					}
					enteredState(newObject, replyDestination);
				}
			}
		});
	}

	private class MessageEmitterHandler implements StateHandler<MessageEmitter> {

		@Override
		public void enteredState(MessageEmitter object, String enteredBy) {
			Message message = object.emitMessage();
			String identity = null;
			if (object instanceof Identifiable) {
				identity = ((Identifiable) object).getIdentity();
			}

			String destination = enteredBy;
			if (message instanceof DirectedMessage) {
				destination = ((DirectedMessage) message).getDestination();
			}
			MessagingSystem.this.sendMessage(message, destination, identity);
		}

		@Override
		public void leftState(MessageEmitter object) {
			// Empty
		}

	}

}


text:
if [ ! -d "key" ]; then
  mkdir key
fi

ionic build android --prod --release

cp ./platforms/android/build/outputs/apk/android-release-unsigned.apk ./key

cd key

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.jks android-release-unsigned.apk zhuzhiqiang

zipalign -v 4 android-release-unsigned.apk 天气.apk


text:
package cat.kanbanapps.gradlekiller;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class KillGradleAction extends AnAction {
    public void actionPerformed(AnActionEvent event) {
        Project project = event.getData(PlatformDataKeys.PROJECT);
        String[] pids;
        try {
            pids = getPids();
        } catch (UnsupportedOperationException e) {
            Messages.showMessageDialog(project, "Could not get process data!", "Gradle Killer", Messages.getErrorIcon());
            return;
        }

        if (pids.length == 0) {
            Messages.showMessageDialog(project, "No Gradle process is running!", "Gradle Killer", Messages.getErrorIcon());
        } else {
            boolean result = true;
            for (String pid : pids) {
                result = result & killProcess(pid);
            }
            if (result) {
                Messages.showMessageDialog(project, "Gradle was killed! Your IDE may show you some other dialogs, it's safe to ignore them.", "Gradle Killer", Messages.getInformationIcon());
            } else {
                Messages.showMessageDialog(project, "Could not kill gradle! Check that your system supports killing processes!", "Gradle Killer", Messages.getErrorIcon());
            }
        }
    }

    private String[] getPids() throws UnsupportedOperationException {
        if (System.getProperty("os.name").startsWith("Windows")) {
            return getPidsOnWindows();
        } else {
            return getPidsOnUnix();
        }
    }

    /**
     * @param pid The PID of the process to kill
     * @return true if killed, false if not
     */
    private boolean killProcess(String pid) {
        if (System.getProperty("os.name").startsWith("Windows")) {
            return killProcessOnWindows(pid);
        } else {
            return killProcessOnUnix(pid);
        }
    }

    private String[] getPidsOnUnix() throws UnsupportedOperationException {
        ArrayList<String> pids = new ArrayList<String>();
        Runtime r = Runtime.getRuntime();
        Process p;
        try {
            p = r.exec("pgrep -f gradle-launcher");
            p.waitFor();

            if (p.exitValue() != 0 && p.exitValue() != 1) { //OK found, OK not found
                throw new UnsupportedOperationException("pgrep returned error value!");
            } else {
                BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line;

                while ((line = b.readLine()) != null) {
                    pids.add(line);
                }

                b.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new UnsupportedOperationException("pgrep parsing failed!");
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new UnsupportedOperationException("pgrep parsing failed!");
        }
        return pids.toArray(new String[pids.size()]);
    }

    private String[] getPidsOnWindows() throws UnsupportedOperationException {
        ArrayList<String> pids = new ArrayList<String>();
        Runtime r = Runtime.getRuntime();
        Process p;
        try {
            p = r.exec("wmic process where \"commandline like '%gradle-launcher%' and name like '%java%'\" get processid");
            p.waitFor();
            BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;

            while ((line = b.readLine()) != null) {
                try {
                    //noinspection ResultOfMethodCallIgnored
                    Integer.parseInt(line.trim());
                    pids.add(line.trim());
                } catch (NumberFormatException e) {
                    //Don't add it, it's a string!
                }
            }

            b.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new UnsupportedOperationException("wmic parsing failed!");
        } catch (InterruptedException e) {
            e.printStackTrace();
            throw new UnsupportedOperationException("wmic parsing failed!");
        }
        return pids.toArray(new String[pids.size()]);
    }

    private boolean killProcessOnWindows(String pid) {
        Runtime r = Runtime.getRuntime();
        Process p;
        try {
            p = r.exec("taskkill /F /PID " + pid);
            p.waitFor();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }

    private boolean killProcessOnUnix(String pid) {
        Runtime r = Runtime.getRuntime();
        Process p;
        try {
            p = r.exec("kill -9 " + pid);
            p.waitFor();

            return p.exitValue() == 0;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }
}


text:
const eventMiddleware = (channel, param) => {
  const result = param;
  if (result.type === 'event' && result.payload.target) {
    result.payload = result.payload.target.value;
  }
  return result;
};

const logger = (channel, param) => {
  // eslint-disable-next-line no-console
  console.log({
    channel,
    param,
  });
  return param;
};

export default [
  eventMiddleware,
  logger,
];


text:
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "GenericOctree.h"

#include "GameFramework/Actor.h"
#include "SpacePartioner.generated.h"

USTRUCT()
struct FOctreeElement
{
	GENERATED_USTRUCT_BODY()

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="Octree Element Struct")
	AActor* MyActor;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Octree Element Struct")
	FBoxSphereBounds BoxSphereBounds;

	FOctreeElement()
	{
		MyActor = nullptr;
		BoxSphereBounds = FBoxSphereBounds(FVector(0.0f, 0.0f, 0.0f), FVector(1.0f, 1.0f, 1.0f), 1.0f);
	}
};

struct FOctreeSematics
{
	enum { MaxElementsPerLeaf = 2 }; // 16
	enum { MinInclusiveElementsPerNode = 7 };
	enum { MaxNodeDepth = 12 };

	typedef TInlineAllocator<MaxElementsPerLeaf> ElementAllocator;

	/**
	* Get the bounding box of the provided octree element. In this case, the box
	* is merely the point specified by the element.
	*
	* @param	Element	Octree element to get the bounding box for
	*
	* @return	Bounding box of the provided octree element
	*/
	FORCEINLINE static FBoxSphereBounds GetBoundingBox(const FOctreeElement& Element)
	{
		return Element.BoxSphereBounds;
	}

	FORCEINLINE static bool AreElementsEqual(const FOctreeElement& A, const FOctreeElement& B)
	{
		return A.MyActor == B.MyActor;
	}

	FORCEINLINE static void SetElementId(const FOctreeElement& Element, FOctreeElementId Id)
	{
	}

	FORCEINLINE static void ApplyOffset(FOctreeElement& Element, FVector Offset)
	{
		FVector NewPostion = Element.MyActor->GetActorLocation() + Offset;
		Element.MyActor->SetActorLocation(NewPostion);
		Element.BoxSphereBounds.Origin = NewPostion;
	}

};

typedef TOctree<FOctreeElement, FOctreeSematics> FSimpleOctree;

UCLASS()
class SPUSINGTOCTREE_API ASpacePartioner : public AActor
{
	GENERATED_BODY()

public:
	// Sets default values for this actor's properties
	ASpacePartioner(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());

	/**
	* Used in conjunction with a constructor to initialize the object.
	* @param NewBounds	Intial size of the Octree
	* @param inDrawDebugInfo	Whether or not to display debug boundaries
	*/
	UFUNCTION(BlueprintCallable, Category = Octree)
	void Initialize(const FBox& inNewBounds, const bool& inDrawDebugInfo);

	/**
	* Used in conjunction with a constructor to initialize the object.
	* @param inExtent	Intial size of the Octree
	* @param inDrawDebugInfo	Whether or not to display debug boundaries
	*/
	void Initialize(const float& inExtent, const bool& inDrawDebugInfo);

	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

	// Called every frame
	virtual void Tick( float DeltaSeconds ) override;

	/**
	* Adds a spefic element to the Octree
	* @param NewOctreeElement	FOctreeElement to be added.
	*/
	UFUNCTION(BlueprintCallable, Category = Octree)
	void AddOctreeElement(const FOctreeElement& inNewOctreeElement);

	/**
	* Returns elements within the specified region.
	* @param inBoundingBoxQuery	Box to query Octree.
	* @return TArray of Elements
	*/
	UFUNCTION(BlueprintCallable, Category = Octree)
	TArray<FOctreeElement> GetElementsWithinBounds(const FBoxSphereBounds& inBoundingBoxQuery);

	/**
	* Returns elements within the specified region.
	* @param inBoundingBoxQuery	Box to query Octree.
	* @return TArray of Elements
	*/
	TArray<FOctreeElement> GetElementsWithinBounds(const FBoxCenterAndExtent& inBoundingBoxQuery);

	/** Draws Debug information at runtime */
	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Debug)
	bool bDrawDebugInfo = false;

private:

	void DrawOctreeBounds();

	FSimpleOctree* OctreeData;
	bool bInitialized;

};


text:
using Foundation;
using System.CodeDom.Compiler;

namespace SDWebImageSample
{
	[Register ("DetailViewController")]
	partial class DetailViewController
	{
		[Outlet]
		UIKit.UIImageView ImageView { get; set; }

		void ReleaseDesignerOutlets ()
		{
			if (ImageView != null) {
				ImageView.Dispose ();
				ImageView = null;
			}
		}
	}
}


text:
require 'warcorrespondent/logging.rb'
require 'warcorrespondent/reporter.rb'
require 'warcorrespondent/uplink.rb'
require 'warcorrespondent/installer.rb'
require 'json'
require 'systeminformation'
require 'yaml'

module WarCorrespondent
  def self.config_base_directory
    [ '/etc/warcorrespondent', '~/.warcorrespondent'].each do |f|
      if File.exists?(File.expand_path(f))
        return File.expand_path(f)
      end
    end
    nil
  end

  def self.config_file
    config_base_directory+"/warcorrespondent.yml" if config_base_directory
  end

  def self.reporters_directory
    config_base_directory+"/reporters" if config_base_directory
  end

  def self.log_file
    '/var/log/warcorrespondent'
  end

  def self.setup
    @@reporters ||= []
    @@uplink = Uplink.new
    begin
      @@config = YAML.load_file(config_file)
      @@uplink.url = @@config['url']
      @@uplink.secret = @@config['secret']
    rescue
      Logging::logger.fatal "Could not load config file #{config_file}. Bailing out."
      exit
    end
    Dir.glob("#{reporters_directory}/*.rb").each do |i|
      begin
        Logging::logger.info "including #{i}"
        require i
      rescue
        Logging::logger.fatal "Parse error in #{i}. Bailing out."
      end
    end
  end

  def self.run
    Logging::logger.info{'warcorrespondent starting up'}
    setup
    Logging::logger.debug "config loaded..."
    Thread.new do
      @@uplink.run
    end
    @@reporters.each do |reporter|
      Thread.new do
        reporter.run
      end
    end
    loop do
      sleep 1
    end
  end

  def self.register_reporter(reporter)
    @@reporters ||= []
    @@reporters << reporter
  end

  def self.update(message)
    @@uplink.add(message)
  end
end


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_BOARD_H
#define CONF_BOARD_H

/** Enable Com Port. */
#define CONF_BOARD_UART_CONSOLE

/** Usart Hw ID used by the console (UART). */
#define CONSOLE_UART_ID          ID_UART

#endif /* CONF_BOARD_H */


text:
package scalaguide.async.websockets

import play.api.test._
import scala.concurrent.Promise

object ScalaWebSockets extends PlaySpecification {

  import java.io.Closeable
  import play.api.libs.iteratee._
  import play.api.mvc.{Result, WebSocket}
  import play.api.libs.json.{Json, JsValue}

  "Scala WebSockets" should {

    "support actors" in {

      def runWebSocket[In, Out](webSocket: WebSocket[In, Out], in: Enumerator[In]): Either[Result, List[Out]] = {
        await(webSocket.f(FakeRequest())).right.map { f =>
          val consumed = Promise[List[Out]]()
          def getChunks(chunks: List[Out]): Iteratee[Out, Unit] = Cont {
            case Input.El(out) => getChunks(out :: chunks)
            case Input.EOF => Done(consumed.success(chunks.reverse))
            case Input.Empty => getChunks(chunks)
          }
          f(in, getChunks(Nil))
          await(consumed.future)
        }

      }

      import akka.actor._

      "allow creating a simple echoing actor" in new WithApplication() {
        runWebSocket(Samples.Controller1.socket, Enumerator("foo") >>> Enumerator.eof) must beRight.like {
          case list => list must_== List("I received your message: foo")
        }
      }

      "allow cleaning up" in new WithApplication() {
        @volatile var closed = false
        val someResource = new Closeable() {
          def close() = closed = true
        }
        class MyActor extends Actor {
          def receive = PartialFunction.empty

          //#actor-post-stop
          override def postStop() = {
            someResource.close()
          }
          //#actor-post-stop
        }

        runWebSocket(
          WebSocket.acceptWithActor[String, String](req => out => Props(new MyActor)), Enumerator.eof
        ) must beRight[List[String]]
        closed must beTrue
      }

      "allow closing the WebSocket" in new WithApplication() {
        class MyActor extends Actor {
          def receive = PartialFunction.empty

          //#actor-stop
          import akka.actor.PoisonPill

          self ! PoisonPill
          //#actor-stop
        }

        runWebSocket(
          WebSocket.acceptWithActor[String, String](req => out => Props(new MyActor)), Enumerator.empty
        ) must beRight[List[String]]
      }

      "allow rejecting the WebSocket" in new WithApplication() {
        runWebSocket(Samples.Controller2.socket, Enumerator.empty) must beLeft.which { result =>
          result.header.status must_== FORBIDDEN
        }
      }

      "allow creating a json actor" in new WithApplication() {
        val json = Json.obj("foo" -> "bar")
        runWebSocket(Samples.Controller4.socket, Enumerator[JsValue](json) >>> Enumerator.eof) must beRight.which { out =>
          out must_== List(json)
        }
      }

      "allow creating a higher level object actor" in new WithApplication() {
        runWebSocket(
          Samples.Controller5.socket,
          Enumerator(Samples.Controller5.InEvent("blah")) >>> Enumerator.eof
        ) must beRight.which { out =>
          out must_== List(Samples.Controller5.OutEvent("blah"))
        }
      }

    }

    "support iteratees" in {

      def runWebSocket[In, Out](webSocket: WebSocket[In, Out], in: Enumerator[In]): Either[Result, List[Out]] = {
        await(webSocket.f(FakeRequest())).right.map { f =>
          val consumed = Promise[List[Out]]()
          @volatile var chunks = List.empty[Out]
          def getChunks: Iteratee[Out, Unit] = Cont {
            case Input.El(out) =>
              chunks = out :: chunks
              getChunks
            case Input.EOF => Done(consumed.trySuccess(chunks.reverse))
            case Input.Empty => getChunks
          }

          import scala.concurrent.ExecutionContext.Implicits.global
          import scala.concurrent.duration._
          f(in.onDoneEnumerating {
            // Yeah, ugly, but it makes a race condition unlikely.
            play.api.libs.concurrent.Promise.timeout((), 100.milliseconds).onSuccess {
              case _ => consumed.trySuccess(chunks)
            }
          }, getChunks)
          await(consumed.future)
        }
      }

      "iteratee1" in new WithApplication() {
        runWebSocket(Samples.Controller6.socket, Enumerator.eof) must beRight.which { out =>
          out must_== List("Hello!")
        }
      }

      "iteratee2" in new WithApplication() {
        runWebSocket(Samples.Controller7.socket, Enumerator.empty) must beRight.which { out =>
          out must_== List("Hello!")
        }
      }

      "iteratee3" in new WithApplication() {
        runWebSocket(Samples.Controller8.socket, Enumerator("foo") >>> Enumerator.eof) must beRight.which { out =>
          out must_== List("I received your message: foo")
        }
      }

    }
  }

}

object Samples {
  object Controller1 {
    import Actor1.MyWebSocketActor

    //#actor-accept
    import play.api.mvc._
    import play.api.Play.current

    def socket = WebSocket.acceptWithActor[String, String] { request => out =>
      MyWebSocketActor.props(out)
    }
    //#actor-accept
  }

  object Actor1 {

    //#example-actor
    import akka.actor._

    object MyWebSocketActor {
      def props(out: ActorRef) = Props(new MyWebSocketActor(out))
    }

    class MyWebSocketActor(out: ActorRef) extends Actor {
      def receive = {
        case msg: String =>
          out ! ("I received your message: " + msg)
      }
    }
    //#example-actor
  }

  object Controller2 extends play.api.mvc.Controller {
    import Actor1.MyWebSocketActor

    //#actor-try-accept
    import scala.concurrent.Future
    import play.api.mvc._
    import play.api.Play.current

    def socket = WebSocket.tryAcceptWithActor[String, String] { request =>
      Future.successful(request.session.get("user") match {
        case None => Left(Forbidden)
        case Some(_) => Right(MyWebSocketActor.props)
      })
    }
    //#actor-try-accept
  }

  object Controller4 {
    import akka.actor._

    class MyWebSocketActor(out: ActorRef) extends Actor {
      import play.api.libs.json.JsValue
      def receive = {
        case msg: JsValue =>
          out ! msg
      }
    }

    object MyWebSocketActor {
      def props(out: ActorRef) = Props(new MyWebSocketActor(out))
    }

    //#actor-json
    import play.api.mvc._
    import play.api.libs.json._
    import play.api.Play.current

    def socket = WebSocket.acceptWithActor[JsValue, JsValue] { request => out =>
      MyWebSocketActor.props(out)
    }
    //#actor-json

  }

  object Controller5 {
    import akka.actor._

    case class InEvent(foo: String)
    case class OutEvent(bar: String)

    class MyWebSocketActor(out: ActorRef) extends Actor {
      def receive = {
        case InEvent(foo) =>
          out ! OutEvent(foo)
      }
    }

    object MyWebSocketActor {
      def props(out: ActorRef) = Props(new MyWebSocketActor(out))
    }

    //#actor-json-formats
    import play.api.libs.json._

    implicit val inEventFormat = Json.format[InEvent]
    implicit val outEventFormat = Json.format[OutEvent]
    //#actor-json-formats

    //#actor-json-frames
    import play.api.mvc.WebSocket.FrameFormatter

    implicit val inEventFrameFormatter = FrameFormatter.jsonFrame[InEvent]
    implicit val outEventFrameFormatter = FrameFormatter.jsonFrame[OutEvent]
    //#actor-json-frames

    //#actor-json-in-out
    import play.api.mvc._
    import play.api.Play.current

    def socket = WebSocket.acceptWithActor[InEvent, OutEvent] { request => out =>
      MyWebSocketActor.props(out)
    }
    //#actor-json-in-out

  }

  object Controller6 {

    //#iteratee1
    import play.api.mvc._
    import play.api.libs.iteratee._
    import play.api.libs.concurrent.Execution.Implicits.defaultContext

    def socket = WebSocket.using[String] { request =>

      // Log events to the console
      val in = Iteratee.foreach[String](println).map { _ =>
        println("Disconnected")
      }

      // Send a single 'Hello!' message
      val out = Enumerator("Hello!")

      (in, out)
    }
    //#iteratee1

  }

  object Controller7 {

    //#iteratee2
    import play.api.mvc._
    import play.api.libs.iteratee._

    def socket = WebSocket.using[String] { request =>

      // Just ignore the input
      val in = Iteratee.ignore[String]

      // Send a single 'Hello!' message and close
      val out = Enumerator("Hello!").andThen(Enumerator.eof)

      (in, out)
    }
    //#iteratee2

  }

  object Controller8 {

    //#iteratee3
    import play.api.mvc._
    import play.api.libs.iteratee._
    import play.api.libs.concurrent.Execution.Implicits.defaultContext

    def socket =  WebSocket.using[String] { request =>

      // Concurrent.broadcast returns (Enumerator, Concurrent.Channel)
      val (out, channel) = Concurrent.broadcast[String]

      // log the message to stdout and send response back to client
      val in = Iteratee.foreach[String] {
        msg => println(msg)
          // the Enumerator returned by Concurrent.broadcast subscribes to the channel and will
          // receive the pushed messages
          channel push("I received your message: " + msg)
      }
      (in,out)
    }
    //#iteratee3
  }

}


text:
<resources>

    <style name="ui_theme" parent="android:Theme.Holo.Light.NoActionBar">
    </style>

    <style name="ui_titleFontStyle" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_centerHorizontal">true</item>
        <item name="android:layout_centerVertical">true</item>
        <item name="android:textSize">@dimen/ui_titleFontSize</item>
        <item name="android:textColor">@color/ui_titleFontColor</item>
    </style>

</resources>


text:
layout: page
title: Macdonald - Mercer Wedding
date: 2016-05-24
author: Mark Maynard
tags: weekly links, java
status: published
summary: Vivamus scelerisque faucibus quam, quis consectetur leo.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 04/22/2016
  endDate: 04/25/2016
  ctyhocn: DALCKHX
  groupCode: MMW
published: true
---
Integer aliquam erat risus, sed malesuada neque ultricies non. Praesent ac egestas turpis, ut laoreet tellus. Sed varius nisl in eleifend condimentum. Donec sollicitudin ipsum odio, ac accumsan nibh tempor vel. Suspendisse eleifend purus elementum vestibulum ullamcorper. Fusce at odio in augue mollis volutpat feugiat in erat. Nam sit amet erat congue, malesuada elit pretium, fermentum turpis. Mauris vitae ex ex.

* Praesent blandit mi ac mollis aliquam
* In eget metus bibendum, porttitor lorem eget, faucibus metus.

Aliquam id nulla quis risus iaculis sodales a non eros. Quisque posuere dui at elit fringilla, ornare molestie mauris ultricies. Suspendisse hendrerit commodo lectus, at bibendum neque tincidunt quis. Donec varius vitae arcu ut maximus. Ut ullamcorper elit volutpat, dapibus tellus sed, tempus quam. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc vehicula rhoncus ex ut tristique. Morbi non gravida nunc. Curabitur a sagittis enim. In pretium nec ipsum eget lacinia. Aenean mauris ex, lobortis eget tellus vitae, congue pulvinar metus. Etiam justo nibh, venenatis non commodo id, dapibus in tellus. In tortor metus, placerat in faucibus in, ullamcorper rhoncus neque. Phasellus accumsan lobortis odio, quis scelerisque erat vehicula vitae. Phasellus dictum placerat efficitur. Maecenas porta tempor risus ut vestibulum.


text:
import React, { Component, PropTypes } from 'react';
import './ActiveItem.scss';

export default class ActiveCollaborator extends Component {
	constructor (props) {
		super(props);
		this.state = {

		}
	}

	static propTypes = {

	};

	render() {
		let itemStyle = {
			marginLeft: '10px'
		}
		let buttonStyle = {
			textAlign: 'center',
			fontSize: '16px'
		}
		return (

						{this.props.activeItem.name}

 {/* ActiveItem-Name-Text */}

 {/* ActiveItem-Name */}
				{/*

			{this.props.activeItem.details}

*/}

					Add to team

 {/* ActiveItem-Functionality-Add */}

					Remove from team

 {/* ActiveItem-Functionality-Remove */}

{/* ActiveItem-Functionality */}

						{/*
				{this.displayHeader()}
				{this.displayRow()} */}

				{this.props.activeItem.mainView}

 {/* ActiveItem-Name-MainView-Content */}

{/* ActiveItem-MainView */}

		)
	}
}