text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.Security.Principal;
using CommandLine;
using Microsoft.Win32.TaskScheduler;
using System.Reflection;
using ACMESharp;
using ACMESharp.HTTP;
using ACMESharp.JOSE;
using ACMESharp.PKI;
using System.Security.Cryptography;
using ACMESharp.ACME;
using Serilog;
using System.Text;

namespace LetsEncrypt.ACME.Simple
{
    class Program
    {
        private const string ClientName = "letsencrypt-win-simple";
        private static string _certificateStore = "WebHosting";
        public static float RenewalPeriod = 60;
        public static bool CentralSsl = false;
        public static string BaseUri { get; set; }
        private static string _configPath;
        private static string _certificatePath;
        private static Settings _settings;
        private static AcmeClient _client;
        public static Options Options;

        static bool IsElevated
            => new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);

        private static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.AppSettings()
                .CreateLogger();
            Log.Information("The global logger has been configured");

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 |
                                                   SecurityProtocolType.Tls12;

            var commandLineParseResult = Parser.Default.ParseArguments<Options>(args);
            var parsed = commandLineParseResult as Parsed<Options>;
            if (parsed == null)
            {
#if DEBUG
                Log.Debug("Program Debug Enabled");
                Console.WriteLine("Press enter to continue.");
                Console.ReadLine();
#endif
                return; // not parsed
            }
            Options = parsed.Value;
            Log.Debug("{@Options}", Options);
            Console.WriteLine("Let's Encrypt (Simple Windows ACME Client)");
            BaseUri = Options.BaseUri;
            if (Options.Test)
            {
                BaseUri = "https://acme-staging.api.letsencrypt.org/";
                Log.Debug("Test paramater set: {BaseUri}", BaseUri);
            }
            if (Options.San)
            {
                Log.Debug("San Option Enabled: Running per site and not per host");
            }

            try
            {
                RenewalPeriod = Properties.Settings.Default.RenewalDays;
                Console.WriteLine("Renewal Period: " + RenewalPeriod);
                Log.Information("Renewal Period: {RenewalPeriod}", RenewalPeriod);
            }
            catch (Exception ex)
            {
                Log.Warning("Error reading RenewalDays from app config, defaulting to {RenewalPeriod} Error: {@ex}",
                    RenewalPeriod.ToString(), ex);
            }
            try
            {
                _certificateStore = Properties.Settings.Default.CertificateStore;
                Console.WriteLine("Certificate Store: " + _certificateStore);
                Log.Information("Certificate Store: {_certificateStore}", _certificateStore);
            }
            catch (Exception ex)
            {
                Log.Warning(
                    "Error reading CertificateStore from app config, defaulting to {_certificateStore} Error: {@ex}",
                    _certificateStore, ex);
            }

            Console.WriteLine($"\nACME Server: {BaseUri}");
            Log.Information("ACME Server: {BaseUri}", BaseUri);

            if (!string.IsNullOrWhiteSpace(Options.CentralSslStore))
            {
                Console.WriteLine("Using Centralized SSL Path: " + Options.CentralSslStore);
                Log.Information("Using Centralized SSL Path: {CentralSslStore}", Options.CentralSslStore);
                CentralSsl = true;
            }

            _settings = new Settings(ClientName, BaseUri);
            Log.Debug("{@_settings}", _settings);
            _configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ClientName,
                CleanFileName(BaseUri));
            Console.WriteLine("Config Folder: " + _configPath);
            Log.Information("Config Folder: {_configPath}", _configPath);
            Directory.CreateDirectory(_configPath);

            _certificatePath = Properties.Settings.Default.CertificatePath;

            if (string.IsNullOrWhiteSpace(_certificatePath))
            {
                _certificatePath = _configPath;
            }
            else
            {
                try
                {
                    Directory.CreateDirectory(_certificatePath);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(
                        $"Error creating the certificate directory, {_certificatePath}. Defaulting to config path");
                    Log.Warning(
                        "Error creating the certificate directory, {_certificatePath}. Defaulting to config path. Error: {@ex}",
                        _certificatePath, ex);

                    _certificatePath = _configPath;
                }
            }

            Console.WriteLine("Certificate Folder: " + _certificatePath);
            Log.Information("Certificate Folder: {_certificatePath}", _certificatePath);

            try
            {
                using (var signer = new RS256Signer())
                {
                    signer.Init();

                    var signerPath = Path.Combine(_configPath, "Signer");
                    if (File.Exists(signerPath))
                    {
                        Console.WriteLine($"Loading Signer from {signerPath}");
                        Log.Information("Loading Signer from {signerPath}", signerPath);
                        using (var signerStream = File.OpenRead(signerPath))
                            signer.Load(signerStream);
                    }

                    using (_client = new AcmeClient(new Uri(BaseUri), new AcmeServerDirectory(), signer))
                    {
                        _client.Init();
                        Console.WriteLine("\nGetting AcmeServerDirectory");
                        Log.Information("Getting AcmeServerDirectory");
                        _client.GetDirectory(true);

                        var registrationPath = Path.Combine(_configPath, "Registration");
                        if (File.Exists(registrationPath))
                        {
                            Console.WriteLine($"Loading Registration from {registrationPath}");
                            Log.Information("Loading Registration from {registrationPath}", registrationPath);
                            using (var registrationStream = File.OpenRead(registrationPath))
                                _client.Registration = AcmeRegistration.Load(registrationStream);
                        }
                        else
                        {
                            Console.Write("Enter an email address (not public, used for renewal fail notices): ");
                            var email = Console.ReadLine().Trim();

                            var contacts = new string[] {};
                            if (!String.IsNullOrEmpty(email))
                            {
                                Log.Debug("Registration email: {email}", email);
                                email = "mailto:" + email;
                                contacts = new string[] {email};
                            }

                            Console.WriteLine("Calling Register");
                            Log.Information("Calling Register");
                            var registration = _client.Register(contacts);

                            if (!Options.AcceptTos && !Options.Renew)
                            {
                                Console.WriteLine($"Do you agree to {registration.TosLinkUri}? (Y/N) ");
                                if (!PromptYesNo())
                                    return;
                            }

                            Console.WriteLine("Updating Registration");
                            Log.Information("Updating Registration");
                            _client.UpdateRegistration(true, true);

                            Console.WriteLine("Saving Registration");
                            Log.Information("Saving Registration");
                            using (var registrationStream = File.OpenWrite(registrationPath))
                                _client.Registration.Save(registrationStream);

                            Console.WriteLine("Saving Signer");
                            Log.Information("Saving Signer");
                            using (var signerStream = File.OpenWrite(signerPath))
                                signer.Save(signerStream);
                        }

                        if (Options.Renew)
                        {
                            CheckRenewals();
#if DEBUG
                            Console.WriteLine("Press enter to continue.");
                            Console.ReadLine();
#endif
                            return;
                        }
                        var targets = new List<Target>();
                        if (!Options.San)
                        {
                            foreach (var plugin in Target.Plugins.Values)
                            {
                                if (string.IsNullOrEmpty(Options.ManualHost))
                                {
                                    targets.AddRange(plugin.GetTargets());
                                }
                            }
                        }
                        else
                        {
                            foreach (var plugin in Target.Plugins.Values)
                            {
                                if (string.IsNullOrEmpty(Options.ManualHost))
                                {
                                    targets.AddRange(plugin.GetSites());
                                }
                            }
                        }

                        if (targets.Count == 0 && string.IsNullOrEmpty(Options.ManualHost))
                        {
                            Console.WriteLine("No targets found.");
                            Log.Error("No targets found.");
                        }
                        else
                        {
                            int hostsPerPage = 50;
                            try
                            {
                                hostsPerPage = Properties.Settings.Default.HostsPerPage;
                            }
                            catch (Exception ex)
                            {
                                Log.Error("Error getting HostsPerPage setting, setting to default value. Error: {@ex}",
                                    ex);
                            }
                            var count = 1;
                            if (targets.Count > hostsPerPage)
                            {
                                do
                                {
                                    if ((count + hostsPerPage) <= targets.Count)
                                    {
                                        int stop = count + hostsPerPage;
                                        for (int i = count; i < stop; i++)
                                        {
                                            if (!Options.San)
                                            {
                                                Console.WriteLine($" {count}: {targets[count - 1]}");
                                            }
                                            else
                                            {
                                                Console.WriteLine($" {targets[count - 1].SiteId}: SAN - {targets[count - 1]}");
                                            }
                                            count++;
                                        }
                                    }
                                    else
                                    {
                                        for (int i = count; i <= targets.Count; i++)
                                        {
                                            if (!Options.San)
                                            {
                                                Console.WriteLine($" {count}: {targets[count - 1]}");
                                            }
                                            else
                                            {
                                                Console.WriteLine(
                                                    $" {targets[count - 1].SiteId}: SAN - {targets[count - 1]}");
                                            }
                                            count++;
                                        }
                                    }

                                    if (count < targets.Count)
                                    {
                                        Console.WriteLine(" Q: Quit");
                                        Console.Write("Press enter to continue to next page ");
                                        var continueResponse = Console.ReadLine().ToLowerInvariant();
                                        switch (continueResponse)
                                        {
                                            case "q":
                                                throw new Exception($"Requested to quit application");
                                            default:
                                                break;
                                        }
                                    }
                                } while (count < targets.Count);
                            }
                            else
                            {
                                foreach (var binding in targets)
                                {
                                    if (!Options.San)
                                    {
                                        Console.WriteLine($" {count}: {binding}");
                                    }
                                    else
                                    {
                                        Console.WriteLine($" {binding.SiteId}: SAN - {binding}");
                                    }
                                    count++;
                                }
                            }
                        }

                        Console.WriteLine();
                        foreach (var plugin in Target.Plugins.Values)
                        {
                            if (string.IsNullOrEmpty(Options.ManualHost))
                            {
                                plugin.PrintMenu();
                            }
                            else if (plugin.Name == "Manual")
                            {
                                plugin.PrintMenu();
                            }
                        }
                        if (string.IsNullOrEmpty(Options.ManualHost))
                        {
                            Console.WriteLine(" A: Get certificates for all hosts");
                            Console.WriteLine(" Q: Quit");
                            Console.Write("Which host do you want to get a certificate for: ");
                            var response = Console.ReadLine().ToLowerInvariant();
                            switch (response)
                            {
                                case "a":
                                    foreach (var target in targets)
                                    {
                                        target.Plugin.Auto(target);
                                    }
                                    break;
                                case "q":
                                    return;
                                default:
                                    var targetId = 0;
                                    if (Int32.TryParse(response, out targetId))
                                    {
                                        if (!Options.San)
                                        {
                                            targetId--;
                                            if (targetId >= 0 && targetId < targets.Count)
                                            {
                                                var binding = targets[targetId];
                                                binding.Plugin.Auto(binding);
                                            }
                                        }
                                        else
                                        {
                                            var binding = targets.Where(t => t.SiteId == targetId).First();
                                            binding.Plugin.Auto(binding);
                                        }
                                    }
                                    else
                                    {
                                        foreach (var plugin in Target.Plugins.Values)
                                        {
                                            plugin.HandleMenuResponse(response, targets);
                                        }
                                    }
                                    break;
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Error {@e}", e);
                Console.ForegroundColor = ConsoleColor.Red;
                var acmeWebException = e as AcmeClient.AcmeWebException;
                if (acmeWebException != null)
                {
                    Console.WriteLine(acmeWebException.Message);
                    Console.WriteLine("ACME Server Returned:");
                    Console.WriteLine(acmeWebException.Response.ContentAsString);
                }
                else
                {
                    Console.WriteLine(e);
                }
                Console.ResetColor();
            }

            Console.WriteLine("Press enter to continue.");
            Console.ReadLine();
        }

        private static string CleanFileName(string fileName)
            =>
                Path.GetInvalidFileNameChars()
                    .Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));

        public static bool PromptYesNo()
        {
            while (true)
            {
                var response = Console.ReadKey(true);
                if (response.Key == ConsoleKey.Y)
                    return true;
                if (response.Key == ConsoleKey.N)
                    return false;
                Console.WriteLine("Please press Y or N.");
            }
        }

        public static void Auto(Target binding)
        {
            var auth = Authorize(binding);
            if (auth.Status == "valid")
            {
                var pfxFilename = GetCertificate(binding);

                if (Options.Test && !Options.Renew)
                {
                    Console.WriteLine(
                        $"\nDo you want to install the .pfx into the Certificate Store/ Central SSL Store? (Y/N) ");
                    if (!PromptYesNo())
                        return;
                }

                if (!CentralSsl)
                {
                    X509Store store;
                    X509Certificate2 certificate;
                    Log.Information("Installing Non-Central SSL Certificate in the certificate store");
                    InstallCertificate(binding, pfxFilename, out store, out certificate);
                    if (Options.Test && !Options.Renew)
                    {
                        Console.WriteLine($"\nDo you want to add/update the certificate to your server software? (Y/N) ");
                        if (!PromptYesNo())
                            return;
                    }
                    Log.Information("Installing Non-Central SSL Certificate in server software");
                    binding.Plugin.Install(binding, pfxFilename, store, certificate);
                    if (!Options.KeepExisting)
                    {
                        UninstallCertificate(binding.Host, out store, certificate);
                    }
                }
                else if (!Options.Renew || !Options.KeepExisting)
                {
                    //If it is using centralized SSL, renewing, and replacing existing it needs to replace the existing binding.
                    Log.Information("Updating new Central SSL Certificate");
                    binding.Plugin.Install(binding);
                }

                if (Options.Test && !Options.Renew)
                {
                    Console.WriteLine(
                        $"\nDo you want to automatically renew this certificate in {RenewalPeriod} days? This will add a task scheduler task. (Y/N) ");
                    if (!PromptYesNo())
                        return;
                }

                if (!Options.Renew)
                {
                    Log.Information("Adding renewal for {binding}", binding);
                    ScheduleRenewal(binding);
                }
            }
        }

        public static void InstallCertificate(Target binding, string pfxFilename, out X509Store store,
            out X509Certificate2 certificate)
        {
            try
            {
                store = new X509Store(_certificateStore, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
            }
            catch (CryptographicException)
            {
                store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
            }
            catch (Exception ex)
            {
                Log.Error("Error encountered while opening certificate store. Error: {@ex}", ex);
                throw new Exception(ex.Message);
            }

            Console.WriteLine($" Opened Certificate Store \"{store.Name}\"");
            Log.Information("Opened Certificate Store {Name}", store.Name);
            certificate = null;
            try
            {
                // See http://paulstovell.com/blog/x509certificate2
                certificate = new X509Certificate2(pfxFilename, Properties.Settings.Default.PFXPassword,
                    X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet |
                    X509KeyStorageFlags.Exportable);

                certificate.FriendlyName =
                    $"{binding.Host} {DateTime.Now.ToString(Properties.Settings.Default.FileDateFormat)}";
                Log.Debug("{FriendlyName}", certificate.FriendlyName);

                Console.WriteLine($" Adding Certificate to Store");
                Log.Information("Adding Certificate to Store");
                store.Add(certificate);

                Console.WriteLine($" Closing Certificate Store");
                Log.Information("Closing Certificate Store");
            }
            catch (Exception ex)
            {
                Log.Error("Error saving certificate {@ex}", ex);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Error saving certificate: {ex.Message.ToString()}");
                Console.ResetColor();
            }
            store.Close();
        }

        public static void UninstallCertificate(string host, out X509Store store, X509Certificate2 certificate)
        {
            try
            {
                store = new X509Store(_certificateStore, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
            }
            catch (CryptographicException)
            {
                store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.OpenExistingOnly | OpenFlags.ReadWrite);
            }
            catch (Exception ex)
            {
                Log.Error("Error encountered while opening certificate store. Error: {@ex}", ex);
                throw new Exception(ex.Message);
            }

            Console.WriteLine($" Opened Certificate Store \"{store.Name}\"");
            Log.Information("Opened Certificate Store {Name}", store.Name);
            try
            {
                X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, host, false);

                foreach (var cert in col)
                {
                    var subjectName = cert.Subject.Split(',');

                    if (cert.FriendlyName != certificate.FriendlyName && subjectName[1] == " CN=" + host)
                    {
                        Console.WriteLine($" Removing Certificate from Store {cert.FriendlyName}");
                        Log.Information("Removing Certificate from Store {@cert}", cert);
                        store.Remove(cert);
                    }
                }

                Console.WriteLine($" Closing Certificate Store");
                Log.Information("Closing Certificate Store");
            }
            catch (Exception ex)
            {
                Log.Error("Error removing certificate {@ex}", ex);
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Error removing certificate: {ex.Message.ToString()}");
                Console.ResetColor();
            }
            store.Close();
        }

        public static string GetCertificate(Target binding)
        {
            var dnsIdentifier = binding.Host;
            var sanList = binding.AlternativeNames;
            List<string> allDnsIdentifiers = new List<string>();

            if (!Options.San)
            {
                allDnsIdentifiers.Add(binding.Host);
            }
            if (binding.AlternativeNames != null)
            {
                allDnsIdentifiers.AddRange(binding.AlternativeNames);
            }

            var cp = CertificateProvider.GetProvider();
            var rsaPkp = new RsaPrivateKeyParams();
            try
            {
                if (Properties.Settings.Default.RSAKeyBits >= 1024)
                {
                    rsaPkp.NumBits = Properties.Settings.Default.RSAKeyBits;
                    Log.Debug("RSAKeyBits: {RSAKeyBits}", Properties.Settings.Default.RSAKeyBits);
                }
                else
                {
                    Log.Warning(
                        "RSA Key Bits less than 1024 is not secure. Letting ACMESharp default key bits. http://openssl.org/docs/manmaster/crypto/RSA_generate_key_ex.html");
                }
            }
            catch (Exception ex)
            {
                Log.Warning("Unable to set RSA Key Bits, Letting ACMESharp default key bits, Error: {@ex}", ex);
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(
                    $"Unable to set RSA Key Bits, Letting ACMESharp default key bits, Error: {ex.Message.ToString()}");
                Console.ResetColor();
            }

            var rsaKeys = cp.GeneratePrivateKey(rsaPkp);
            var csrDetails = new CsrDetails
            {
                CommonName = allDnsIdentifiers[0],
            };
            if (sanList != null)
            {
                if (sanList.Count > 0)
                {
                    csrDetails.AlternativeNames = sanList;
                }
            }
            var csrParams = new CsrParams
            {
                Details = csrDetails,
            };
            var csr = cp.GenerateCsr(csrParams, rsaKeys, Crt.MessageDigest.SHA256);

            byte[] derRaw;
            using (var bs = new MemoryStream())
            {
                cp.ExportCsr(csr, EncodingFormat.DER, bs);
                derRaw = bs.ToArray();
            }
            var derB64U = JwsHelper.Base64UrlEncode(derRaw);

            Console.WriteLine($"\nRequesting Certificate");
            Log.Information("Requesting Certificate");
            var certRequ = _client.RequestCertificate(derB64U);

            Log.Debug("certRequ {@certRequ}", certRequ);

            Console.WriteLine($" Request Status: {certRequ.StatusCode}");
            Log.Information("Request Status: {StatusCode}", certRequ.StatusCode);

            if (certRequ.StatusCode == System.Net.HttpStatusCode.Created)
            {
                var keyGenFile = Path.Combine(_certificatePath, $"{dnsIdentifier}-gen-key.json");
                var keyPemFile = Path.Combine(_certificatePath, $"{dnsIdentifier}-key.pem");
                var csrGenFile = Path.Combine(_certificatePath, $"{dnsIdentifier}-gen-csr.json");
                var csrPemFile = Path.Combine(_certificatePath, $"{dnsIdentifier}-csr.pem");
                var crtDerFile = Path.Combine(_certificatePath, $"{dnsIdentifier}-crt.der");
                var crtPemFile = Path.Combine(_certificatePath, $"{dnsIdentifier}-crt.pem");
                string crtPfxFile = null;
                if (!CentralSsl)
                {
                    crtPfxFile = Path.Combine(_certificatePath, $"{dnsIdentifier}-all.pfx");
                }
                else
                {
                    crtPfxFile = Path.Combine(Options.CentralSslStore, $"{dnsIdentifier}.pfx");
                }

                using (var fs = new FileStream(keyGenFile, FileMode.Create))
                    cp.SavePrivateKey(rsaKeys, fs);
                using (var fs = new FileStream(keyPemFile, FileMode.Create))
                    cp.ExportPrivateKey(rsaKeys, EncodingFormat.PEM, fs);
                using (var fs = new FileStream(csrGenFile, FileMode.Create))
                    cp.SaveCsr(csr, fs);
                using (var fs = new FileStream(csrPemFile, FileMode.Create))
                    cp.ExportCsr(csr, EncodingFormat.PEM, fs);

                Console.WriteLine($" Saving Certificate to {crtDerFile}");
                Log.Information("Saving Certificate to {crtDerFile}", crtDerFile);
                using (var file = File.Create(crtDerFile))
                    certRequ.SaveCertificate(file);

                Crt crt;
                using (FileStream source = new FileStream(crtDerFile, FileMode.Open),
                    target = new FileStream(crtPemFile, FileMode.Create))
                {
                    crt = cp.ImportCertificate(EncodingFormat.DER, source);
                    cp.ExportCertificate(crt, EncodingFormat.PEM, target);
                }

                // To generate a PKCS#12 (.PFX) file, we need the issuer's public certificate
                var isuPemFile = GetIssuerCertificate(certRequ, cp);

                Log.Debug("CentralSsl {CentralSsl} San {San}", CentralSsl.ToString(), Options.San.ToString());

                if (CentralSsl && Options.San)
                {
                    foreach (var host in allDnsIdentifiers)
                    {
                        Console.WriteLine($"Host: {host}");
                        crtPfxFile = Path.Combine(Options.CentralSslStore, $"{host}.pfx");

                        Console.WriteLine($" Saving Certificate to {crtPfxFile}");
                        Log.Information("Saving Certificate to {crtPfxFile}", crtPfxFile);
                        using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                            target = new FileStream(crtPfxFile, FileMode.Create))
                        {
                            try
                            {
                                var isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                                cp.ExportArchive(rsaKeys, new[] {crt, isuCrt}, ArchiveFormat.PKCS12, target,
                                    Properties.Settings.Default.PFXPassword);
                            }
                            catch (Exception ex)
                            {
                                Log.Error("Error exporting archive {@ex}", ex);
                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine($"Error exporting archive: {ex.Message.ToString()}");
                                Console.ResetColor();
                            }
                        }
                    }
                }
                else //Central SSL and San need to save the cert for each hostname
                {
                    Console.WriteLine($" Saving Certificate to {crtPfxFile}");
                    Log.Information("Saving Certificate to {crtPfxFile}", crtPfxFile);
                    using (FileStream source = new FileStream(isuPemFile, FileMode.Open),
                        target = new FileStream(crtPfxFile, FileMode.Create))
                    {
                        try
                        {
                            var isuCrt = cp.ImportCertificate(EncodingFormat.PEM, source);
                            cp.ExportArchive(rsaKeys, new[] {crt, isuCrt}, ArchiveFormat.PKCS12, target,
                                Properties.Settings.Default.PFXPassword);
                        }
                        catch (Exception ex)
                        {
                            Log.Error("Error exporting archive {@ex}", ex);
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine($"Error exporting archive: {ex.Message.ToString()}");
                            Console.ResetColor();
                        }
                    }
                }

                cp.Dispose();

                return crtPfxFile;
            }
            Log.Error("Request status = {StatusCode}", certRequ.StatusCode);
            throw new Exception($"Request status = {certRequ.StatusCode}");
        }

        public static void EnsureTaskScheduler()
        {
            var taskName = $"{ClientName} {CleanFileName(BaseUri)}";

            using (var taskService = new TaskService())
            {
                bool addTask = true;
                if (_settings.ScheduledTaskName == taskName)
                {
                    addTask = false;
                    Console.WriteLine($"\nDo you want to replace the existing {taskName} task? (Y/N) ");
                    if (!PromptYesNo())
                        return;
                    addTask = true;
                    Console.WriteLine($" Deleting existing Task {taskName} from Windows Task Scheduler.");
                    Log.Information("Deleting existing Task {taskName} from Windows Task Scheduler.", taskName);
                    taskService.RootFolder.DeleteTask(taskName, false);
                }

                if (addTask == true)
                {
                    Console.WriteLine($" Creating Task {taskName} with Windows Task Scheduler at 9am every day.");
                    Log.Information("Creating Task {taskName} with Windows Task scheduler at 9am every day.", taskName);

                    // Create a new task definition and assign properties
                    var task = taskService.NewTask();
                    task.RegistrationInfo.Description = "Check for renewal of ACME certificates.";

                    var now = DateTime.Now;
                    var runtime = new DateTime(now.Year, now.Month, now.Day, 9, 0, 0);
                    task.Triggers.Add(new DailyTrigger {DaysInterval = 1, StartBoundary = runtime});

                    var currentExec = Assembly.GetExecutingAssembly().Location;

                    // Create an action that will launch the app with the renew parameters whenever the trigger fires
                    task.Actions.Add(new ExecAction(currentExec, $"--renew --baseuri \"{BaseUri}\"",
                        Path.GetDirectoryName(currentExec)));

                    task.Principal.RunLevel = TaskRunLevel.Highest; // need admin
                    Log.Debug("{@task}", task);

                    Console.WriteLine($"\nDo you want to specify the user the task will run as? (Y/N) ");
                    if (PromptYesNo())
                    {
                        // Ask for the login and password to allow the task to run
                        Console.Write("Enter the username (Domain\\username): ");
                        var username = Console.ReadLine();
                        Console.Write("Enter the user's password: ");
                        var password = ReadPassword();
                        Log.Debug("Creating task to run as {username}", username);
                        taskService.RootFolder.RegisterTaskDefinition(taskName, task, TaskCreation.Create, username,
                            password, TaskLogonType.Password);
                    }
                    else
                    {
                        Log.Debug("Creating task to run as current user only when the user is logged on");
                        taskService.RootFolder.RegisterTaskDefinition(taskName, task);
                    }
                    _settings.ScheduledTaskName = taskName;
                }
            }
        }

        public static void ScheduleRenewal(Target target)
        {
            EnsureTaskScheduler();

            var renewals = _settings.LoadRenewals();

            foreach (var existing in from r in renewals.ToArray() where r.Binding.Host == target.Host select r)
            {
                Console.WriteLine($" Removing existing scheduled renewal {existing}");
                Log.Information("Removing existing scheduled renewal {existing}", existing);
                renewals.Remove(existing);
            }

            var result = new ScheduledRenewal()
            {
                Binding = target,
                CentralSsl = Options.CentralSslStore,
                San = Options.San.ToString(),
                Date = DateTime.UtcNow.AddDays(RenewalPeriod),
                KeepExisting = Options.KeepExisting.ToString(),
                Script = Options.Script,
                ScriptParameters = Options.ScriptParameters
            };
            renewals.Add(result);
            _settings.SaveRenewals(renewals);

            Console.WriteLine($" Renewal Scheduled {result}");
            Log.Information("Renewal Scheduled {result}", result);
        }

        public static void CheckRenewals()
        {
            Console.WriteLine("Checking Renewals");
            Log.Information("Checking Renewals");

            var renewals = _settings.LoadRenewals();
            if (renewals.Count == 0)
            {
                Console.WriteLine(" No scheduled renewals found.");
                Log.Information("No scheduled renewals found.");
            }

            var now = DateTime.UtcNow;
            foreach (var renewal in renewals)
            {
                Console.WriteLine($" Checking {renewal}");
                Log.Information("Checking {renewal}", renewal);
                if (renewal.Date < now)
                {
                    Console.WriteLine($" Renewing certificate for {renewal}");
                    Log.Information("Renewing certificate for {renewal}", renewal);
                    if (string.IsNullOrWhiteSpace(renewal.CentralSsl))
                    {
                        //Not using Central SSL
                        CentralSsl = false;
                        Options.CentralSslStore = null;
                    }
                    else
                    {
                        //Using Central SSL
                        CentralSsl = true;
                        Options.CentralSslStore = renewal.CentralSsl;
                    }
                    if (string.IsNullOrWhiteSpace(renewal.San))
                    {
                        //Not using San
                        Options.San = false;
                    }
                    else if (renewal.San.ToLower() == "true")
                    {
                        //Using San
                        Options.San = true;
                    }
                    else
                    {
                        //Not using San
                        Options.San = false;
                    }
                    if (string.IsNullOrWhiteSpace(renewal.KeepExisting))
                    {
                        //Not using KeepExisting
                        Options.KeepExisting = false;
                    }
                    else if (renewal.KeepExisting.ToLower() == "true")
                    {
                        //Using KeepExisting
                        Options.KeepExisting = true;
                    }
                    else
                    {
                        //Not using KeepExisting
                        Options.KeepExisting = false;
                    }
                    if (!string.IsNullOrWhiteSpace(renewal.Script))
                    {
                        Options.Script = renewal.Script;
                    }
                    if (!string.IsNullOrWhiteSpace(renewal.ScriptParameters))
                    {
                        Options.ScriptParameters = renewal.ScriptParameters;
                    }
                    renewal.Binding.Plugin.Renew(renewal.Binding);

                    renewal.Date = DateTime.UtcNow.AddDays(RenewalPeriod);
                    _settings.SaveRenewals(renewals);
                    Console.WriteLine($" Renewal Scheduled {renewal}");
                    Log.Information("Renewal Scheduled {renewal}", renewal);
                }
            }
        }

        public static string GetIssuerCertificate(CertificateRequest certificate, CertificateProvider cp)
        {
            var linksEnum = certificate.Links;
            if (linksEnum != null)
            {
                var links = new LinkCollection(linksEnum);
                var upLink = links.GetFirstOrDefault("up");
                if (upLink != null)
                {
                    var tmp = Path.GetTempFileName();
                    try
                    {
                        using (var web = new WebClient())
                        {
                            var uri = new Uri(new Uri(BaseUri), upLink.Uri);
                            web.DownloadFile(uri, tmp);
                        }

                        var cacert = new X509Certificate2(tmp);
                        var sernum = cacert.GetSerialNumberString();

                        var cacertDerFile = Path.Combine(_certificatePath, $"ca-{sernum}-crt.der");
                        var cacertPemFile = Path.Combine(_certificatePath, $"ca-{sernum}-crt.pem");

                        if (!File.Exists(cacertDerFile))
                            File.Copy(tmp, cacertDerFile, true);

                        Console.WriteLine($" Saving Issuer Certificate to {cacertPemFile}");
                        Log.Information("Saving Issuer Certificate to {cacertPemFile}", cacertPemFile);
                        if (!File.Exists(cacertPemFile))
                            using (FileStream source = new FileStream(cacertDerFile, FileMode.Open),
                                target = new FileStream(cacertPemFile, FileMode.Create))
                            {
                                var caCrt = cp.ImportCertificate(EncodingFormat.DER, source);
                                cp.ExportCertificate(caCrt, EncodingFormat.PEM, target);
                            }

                        return cacertPemFile;
                    }
                    finally
                    {
                        if (File.Exists(tmp))
                            File.Delete(tmp);
                    }
                }
            }

            return null;
        }

        public static AuthorizationState Authorize(Target target)
        {
            List<string> dnsIdentifiers = new List<string>();
            if (!Options.San)
            {
                dnsIdentifiers.Add(target.Host);
            }
            if (target.AlternativeNames != null)
            {
                dnsIdentifiers.AddRange(target.AlternativeNames);
            }
            List<AuthorizationState> authStatus = new List<AuthorizationState>();

            foreach (var dnsIdentifier in dnsIdentifiers)
            {
                var webRootPath = target.WebRootPath;

                Console.WriteLine(
                    $"\nAuthorizing Identifier {dnsIdentifier} Using Challenge Type {AcmeProtocol.CHALLENGE_TYPE_HTTP}");
                Log.Information("Authorizing Identifier {dnsIdentifier} Using Challenge Type {CHALLENGE_TYPE_HTTP}",
                    dnsIdentifier, AcmeProtocol.CHALLENGE_TYPE_HTTP);
                var authzState = _client.AuthorizeIdentifier(dnsIdentifier);
                var challenge = _client.DecodeChallenge(authzState, AcmeProtocol.CHALLENGE_TYPE_HTTP);
                var httpChallenge = challenge.Challenge as HttpChallenge;

                // We need to strip off any leading '/' in the path
                var filePath = httpChallenge.FilePath;
                if (filePath.StartsWith("/", StringComparison.OrdinalIgnoreCase))
                    filePath = filePath.Substring(1);
                var answerPath = Environment.ExpandEnvironmentVariables(Path.Combine(webRootPath, filePath));

                target.Plugin.CreateAuthorizationFile(answerPath, httpChallenge.FileContent);

                target.Plugin.BeforeAuthorize(target, answerPath, httpChallenge.Token);

                var answerUri = new Uri(httpChallenge.FileUrl);
                Console.WriteLine($" Answer should now be browsable at {answerUri}");
                Log.Information("Answer should now be browsable at {answerUri}", answerUri);

                try
                {
                    Console.WriteLine(" Submitting answer");
                    Log.Information("Submitting answer");
                    authzState.Challenges = new AuthorizeChallenge[] {challenge};
                    _client.SubmitChallengeAnswer(authzState, AcmeProtocol.CHALLENGE_TYPE_HTTP, true);

                    // have to loop to wait for server to stop being pending.
                    // TODO: put timeout/retry limit in this loop
                    while (authzState.Status == "pending")
                    {
                        Console.WriteLine(" Refreshing authorization");
                        Log.Information("Refreshing authorization");
                        Thread.Sleep(4000); // this has to be here to give ACME server a chance to think
                        var newAuthzState = _client.RefreshIdentifierAuthorization(authzState);
                        if (newAuthzState.Status != "pending")
                            authzState = newAuthzState;
                    }

                    Console.WriteLine($" Authorization Result: {authzState.Status}");
                    Log.Information("Auth Result {Status}", authzState.Status);
                    if (authzState.Status == "invalid")
                    {
                        Log.Error("Authorization Failed {Status}", authzState.Status);
                        Log.Debug("Full Error Details {@authzState}", authzState);
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(
                            "\n******************************************************************************");
                        Console.WriteLine($"The ACME server was probably unable to reach {answerUri}");
                        Log.Error("Unable to reach {answerUri}", answerUri);

                        Console.WriteLine("\nCheck in a browser to see if the answer file is being served correctly.");

                        target.Plugin.OnAuthorizeFail(target);

                        Console.WriteLine(
                            "\n******************************************************************************");
                        Console.ResetColor();
                    }
                    authStatus.Add(authzState);
                }
                finally
                {
                    if (authzState.Status == "valid")
                    {
                        target.Plugin.DeleteAuthorization(answerPath, httpChallenge.Token, webRootPath, filePath);
                    }
                }
            }
            foreach (var authState in authStatus)
            {
                if (authState.Status != "valid")
                {
                    return authState;
                }
            }
            return new AuthorizationState {Status = "valid"};
        }

        // Replaces the characters of the typed in password with asterisks
        // More info: http://rajeshbailwal.blogspot.com/2012/03/password-in-c-console-application.html
        private static String ReadPassword()
        {
            var password = new StringBuilder();
            try
            {
                ConsoleKeyInfo info = Console.ReadKey(true);
                while (info.Key != ConsoleKey.Enter)
                {
                    if (info.Key != ConsoleKey.Backspace)
                    {
                        Console.Write("*");
                        password.Append(info.KeyChar);
                    }
                    else if (info.Key == ConsoleKey.Backspace)
                    {
                        if (password != null)
                        {
                            // remove one character from the list of password characters
                            password.Remove(password.Length - 1, 1);
                            // get the location of the cursor
                            int pos = Console.CursorLeft;
                            // move the cursor to the left by one character
                            Console.SetCursorPosition(pos - 1, Console.CursorTop);
                            // replace it with space
                            Console.Write(" ");
                            // move the cursor to the left by one character again
                            Console.SetCursorPosition(pos - 1, Console.CursorTop);
                        }
                    }
                    info = Console.ReadKey(true);
                }
                // add a new line because user pressed enter at the end of their password
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error Reading Password {ex.Message}");
                Log.Error("Error Reading Password: {@ex}", ex);
            }

            return password.ToString();
        }
    }
}


text:
package org.elasticsearch.index.analysis;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.util.Version;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.AbstractIndexComponent;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;

/**
 *
 */
public abstract class AbstractIndexAnalyzerProvider<T extends Analyzer> extends AbstractIndexComponent implements AnalyzerProvider<T> {

    private final String name;

    protected final Version version;

    /**
     * Constructs a new analyzer component, with the index name and its settings and the analyzer name.
     *
     * @param index         The index name
     * @param indexSettings The index settings
     * @param name          The analyzer name
     */
    public AbstractIndexAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, String name, Settings settings) {
        super(index, indexSettings);
        this.name = name;
        this.version = Lucene.parseVersion(settings.get("version"), Lucene.ANALYZER_VERSION, logger);
    }

    /**
     * Constructs a new analyzer component, with the index name and its settings and the analyzer name.
     *
     * @param index          The index name
     * @param indexSettings  The index settings
     * @param prefixSettings A settings prefix (like "com.mycompany") to simplify extracting the component settings
     * @param name           The analyzer name
     */
    public AbstractIndexAnalyzerProvider(Index index, @IndexSettings Settings indexSettings, String prefixSettings, String name, Settings settings) {
        super(index, indexSettings, prefixSettings);
        this.name = name;
        this.version = Lucene.parseVersion(settings.get("version"), Lucene.ANALYZER_VERSION, logger);
    }

    @Override
    public String name() {
        return this.name;
    }

    @Override
    public AnalyzerScope scope() {
        return AnalyzerScope.INDEX;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * This is the model class for table "user".
 *
 */
class Member extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Users the static model class
	 */
	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'user';
	}

	/**
	 * @return array validation rules for model attributes.
	 */

	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(array('active', 'boolean')	);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		return array
		(
			'issues' => array(self::HAS_MANY, 'Issue', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array
		(
			'username' => 'Member Name',
			'active' => 'Is active?',
		);

	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

	}

	public function getAllMembers()
	{
		$dataProvider = new CActiveDataProvider('Member');
		return $dataProvider;
	}

	public function deleteMember($id)
	{
		try
		{
			$member = $this->findByPk($id);
			if (isset($member) && !empty($member))
			{
				if ($member->delete())
					return TRUE;
				else
					return FALSE;
			}
			else
				return FALSE;

		}
		catch (Exception $e)
		{
			return FALSE;
		}

	}
}


text:
require "minitest_helper"

class TestConfiguration < Minitest::Test

  def setup
    super
    @config = Upstatic::Configuration.new
  end

  def test_reads_from_file
    path = File.expand_path("../upload_dir/Upstatic", __FILE__)
    config = Upstatic::Configuration.read(path)
    assert_equal "upstatic", config.bucket
  end

  def test_cache_control_sanitizes_extensions
    @config.cache_control "html", "public"
    assert_equal "public", @config.cache_controls[".html"]
  end

  def test_cache_control_accepts_symbols_as_extensions
    @config.cache_control :css, "public"
    assert_equal "public", @config.cache_controls[".css"]
  end

  def test_gzip_extensions_sanitizes_extensions
    @config.gzip_extensions :html, "css", ".js"
    assert @config.gzip_extensions.include?(".html")
    assert @config.gzip_extensions.include?(".css")
    assert @config.gzip_extensions.include?(".js")
  end

end


text:
<!---

This README is automatically generated from the comments in these files:
iron-range-behavior.html

Edit those files, and our readme bot will duplicate them over here!
Edit this file, and the bot will squash your changes :)

The bot does some handling of markdown. Please file a bug if it does the wrong
thing! https://github.com/PolymerLabs/tedium/issues

-->

[![Build status](https://travis-ci.org/PolymerElements/iron-range-behavior.svg?branch=master)](https://travis-ci.org/PolymerElements/iron-range-behavior)

_[Demo and API docs](https://elements.polymer-project.org/elements/iron-range-behavior)_

##Polymer.IronRangeBehavior

`iron-range-behavior` provides the behavior for something with a minimum to maximum range.


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package com.cloud.storage;

import com.cloud.dc.DataCenterVO;
import com.cloud.dc.dao.DataCenterDao;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.org.Grouping;
import com.cloud.serializer.GsonHelper;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.user.Account;
import com.cloud.user.AccountManager;
import com.cloud.user.AccountVO;
import com.cloud.user.User;
import com.cloud.user.UserVO;
import com.cloud.utils.db.TransactionLegacy;
import com.cloud.vm.UserVmManager;
import com.cloud.vm.UserVmVO;
import com.cloud.vm.VirtualMachine;
import com.cloud.vm.VirtualMachine.State;
import com.cloud.vm.dao.UserVmDao;
import com.cloud.vm.dao.VMInstanceDao;
import com.cloud.vm.snapshot.VMSnapshotVO;
import com.cloud.vm.snapshot.dao.VMSnapshotDao;
import junit.framework.Assert;
import org.apache.cloudstack.acl.ControlledEntity;
import org.apache.cloudstack.acl.SecurityChecker.AccessType;
import org.apache.cloudstack.api.command.user.volume.CreateVolumeCmd;
import org.apache.cloudstack.api.command.user.volume.DetachVolumeCmd;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeService;
import org.apache.cloudstack.framework.jobs.AsyncJobExecutionContext;
import org.apache.cloudstack.framework.jobs.AsyncJobManager;
import org.apache.cloudstack.framework.jobs.dao.AsyncJobJoinMapDao;
import org.apache.cloudstack.framework.jobs.impl.AsyncJobVO;
import org.apache.cloudstack.storage.datastore.db.PrimaryDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.StoragePoolVO;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import javax.inject.Inject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class VolumeApiServiceImplTest {
    @Inject
    VolumeApiServiceImpl _svc = new VolumeApiServiceImpl();
    @Mock
    VolumeDao _volumeDao;
    @Mock
    AccountManager _accountMgr;
    @Mock
    UserVmDao _userVmDao;
    @Mock
    PrimaryDataStoreDao _storagePoolDao;
    @Mock
    VMSnapshotDao _vmSnapshotDao;
    @Mock
    AsyncJobManager _jobMgr;
    @Mock
    AsyncJobJoinMapDao _joinMapDao;
    @Mock
    VolumeDataFactory _volFactory;

    @Mock
    VMInstanceDao _vmInstanceDao;
    @Mock
    VolumeInfo volumeInfoMock;
    @Mock
    SnapshotInfo snapshotInfoMock;
    @Mock
    VolumeService volService;
    @Mock
    CreateVolumeCmd createVol;
    @Mock
    UserVmManager _userVmMgr;
    @Mock
    DataCenterDao _dcDao;

    DetachVolumeCmd detachCmd = new DetachVolumeCmd();
    Class<?> _detachCmdClass = detachCmd.getClass();

    @Before
    public void setup() throws Exception {
        MockitoAnnotations.initMocks(this);
        _svc._volsDao = _volumeDao;
        _svc._accountMgr = _accountMgr;
        _svc._userVmDao = _userVmDao;
        _svc._storagePoolDao = _storagePoolDao;
        _svc._vmSnapshotDao = _vmSnapshotDao;
        _svc._vmInstanceDao = _vmInstanceDao;
        _svc._jobMgr = _jobMgr;
        _svc.volFactory = _volFactory;
        _svc.volService = volService;
        _svc._userVmMgr = _userVmMgr;
        _svc._dcDao = _dcDao;
        _svc._gson = GsonHelper.getGsonLogger();

        // mock caller context
        AccountVO account = new AccountVO("admin", 1L, "networkDomain", Account.ACCOUNT_TYPE_NORMAL, "uuid");
        UserVO user = new UserVO(1, "testuser", "password", "firstname", "lastName", "email", "timezone", UUID.randomUUID().toString(), User.Source.UNKNOWN);
        CallContext.register(user, account);
        // mock async context
        AsyncJobExecutionContext context = new AsyncJobExecutionContext();
        AsyncJobExecutionContext.init(_svc._jobMgr, _joinMapDao);
        AsyncJobVO job = new AsyncJobVO();
        context.setJob(job);
        AsyncJobExecutionContext.setCurrentExecutionContext(context);

        TransactionLegacy txn = TransactionLegacy.open("runVolumeDaoImplTest");
        try {
            // volume of running vm id=1
            VolumeVO volumeOfRunningVm = new VolumeVO("root", 1L, 1L, 1L, 1L, 1L, "root", "root", Storage.ProvisioningType.THIN, 1, null,
                    null, "root", Volume.Type.ROOT);
            when(_svc._volsDao.findById(1L)).thenReturn(volumeOfRunningVm);

            UserVmVO runningVm = new UserVmVO(1L, "vm", "vm", 1, HypervisorType.XenServer, 1L, false,
                    false, 1L, 1L, 1, 1L, null, "vm", null);
            runningVm.setState(State.Running);
            runningVm.setDataCenterId(1L);
            when(_svc._userVmDao.findById(1L)).thenReturn(runningVm);

            // volume of stopped vm id=2
            VolumeVO volumeOfStoppedVm = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null,
                    null, "root", Volume.Type.ROOT);
            volumeOfStoppedVm.setPoolId(1L);
            when(_svc._volsDao.findById(2L)).thenReturn(volumeOfStoppedVm);

            UserVmVO stoppedVm = new UserVmVO(2L, "vm", "vm", 1, HypervisorType.XenServer, 1L, false,
                    false, 1L, 1L, 1, 1L, null, "vm", null);
            stoppedVm.setState(State.Stopped);
            stoppedVm.setDataCenterId(1L);
            when(_svc._userVmDao.findById(2L)).thenReturn(stoppedVm);

            // volume of hyperV vm id=3
            UserVmVO hyperVVm = new UserVmVO(3L, "vm", "vm", 1, HypervisorType.Hyperv, 1L, false,
                    false, 1L, 1L, 1, 1L, null, "vm", null);
            hyperVVm.setState(State.Stopped);
            hyperVVm.setDataCenterId(1L);
            when(_svc._userVmDao.findById(3L)).thenReturn(hyperVVm);

            VolumeVO volumeOfStoppeHyperVVm = new VolumeVO("root", 1L, 1L, 1L, 1L, 3L, "root", "root", Storage.ProvisioningType.THIN, 1, null,
                    null, "root", Volume.Type.ROOT);
            volumeOfStoppeHyperVVm.setPoolId(1L);
            when(_svc._volsDao.findById(3L)).thenReturn(volumeOfStoppeHyperVVm);

            StoragePoolVO unmanagedPool = new StoragePoolVO();

            when(_svc._storagePoolDao.findById(1L)).thenReturn(unmanagedPool);

            // volume of managed pool id=4
            StoragePoolVO managedPool = new StoragePoolVO();
            managedPool.setManaged(true);
            when(_svc._storagePoolDao.findById(2L)).thenReturn(managedPool);
            VolumeVO managedPoolVolume = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null,
                    null, "root", Volume.Type.ROOT);
            managedPoolVolume.setPoolId(2L);
            when(_svc._volsDao.findById(4L)).thenReturn(managedPoolVolume);

            // non-root non-datadisk volume
            VolumeInfo volumeWithIncorrectVolumeType = Mockito.mock(VolumeInfo.class);
            when(volumeWithIncorrectVolumeType.getId()).thenReturn(5L);
            when(volumeWithIncorrectVolumeType.getVolumeType()).thenReturn(Volume.Type.ISO);
            when(_svc.volFactory.getVolume(5L)).thenReturn(volumeWithIncorrectVolumeType);

            // correct root volume
            VolumeInfo correctRootVolume = Mockito.mock(VolumeInfo.class);
            when(correctRootVolume.getId()).thenReturn(6L);
            when(correctRootVolume.getDataCenterId()).thenReturn(1L);
            when(correctRootVolume.getVolumeType()).thenReturn(Volume.Type.ROOT);
            when(correctRootVolume.getInstanceId()).thenReturn(null);
            when(correctRootVolume.getState()).thenReturn(Volume.State.Ready);
            when(correctRootVolume.getTemplateId()).thenReturn(null);
            when(correctRootVolume.getPoolId()).thenReturn(1L);
            when(_svc.volFactory.getVolume(6L)).thenReturn(correctRootVolume);

            VolumeVO correctRootVolumeVO = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null,
                    null, "root", Volume.Type.ROOT);
            when(_svc._volsDao.findById(6L)).thenReturn(correctRootVolumeVO);

            // managed root volume
            VolumeInfo managedVolume = Mockito.mock(VolumeInfo.class);
            when(managedVolume.getId()).thenReturn(7L);
            when(managedVolume.getDataCenterId()).thenReturn(1L);
            when(managedVolume.getVolumeType()).thenReturn(Volume.Type.ROOT);
            when(managedVolume.getInstanceId()).thenReturn(null);
            when(managedVolume.getPoolId()).thenReturn(2L);
            when(_svc.volFactory.getVolume(7L)).thenReturn(managedVolume);

            VolumeVO managedVolume1 = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null,
                    null, "root", Volume.Type.ROOT);
            managedVolume1.setPoolId(2L);
            managedVolume1.setDataCenterId(1L);
            when(_svc._volsDao.findById(7L)).thenReturn(managedVolume1);

            // vm having root volume
            UserVmVO vmHavingRootVolume = new UserVmVO(4L, "vm", "vm", 1, HypervisorType.XenServer, 1L, false,
                    false, 1L, 1L, 1, 1L, null, "vm", null);
            vmHavingRootVolume.setState(State.Stopped);
            vmHavingRootVolume.setDataCenterId(1L);
            when(_svc._userVmDao.findById(4L)).thenReturn(vmHavingRootVolume);
            List<VolumeVO> vols = new ArrayList<VolumeVO>();
            vols.add(new VolumeVO());
            when(_svc._volsDao.findByInstanceAndDeviceId(4L, 0L)).thenReturn(vols);

            // volume in uploaded state
            VolumeInfo uploadedVolume = Mockito.mock(VolumeInfo.class);
            when(uploadedVolume.getId()).thenReturn(8L);
            when(uploadedVolume.getDataCenterId()).thenReturn(1L);
            when(uploadedVolume.getVolumeType()).thenReturn(Volume.Type.ROOT);
            when(uploadedVolume.getInstanceId()).thenReturn(null);
            when(uploadedVolume.getPoolId()).thenReturn(1L);
            when(uploadedVolume.getState()).thenReturn(Volume.State.Uploaded);
            when(_svc.volFactory.getVolume(8L)).thenReturn(uploadedVolume);

            VolumeVO upVolume = new VolumeVO("root", 1L, 1L, 1L, 1L, 2L, "root", "root", Storage.ProvisioningType.THIN, 1, null,
                    null, "root", Volume.Type.ROOT);
            upVolume.setPoolId(1L);
            upVolume.setDataCenterId(1L);
            upVolume.setState(Volume.State.Uploaded);
            when(_svc._volsDao.findById(8L)).thenReturn(upVolume);

            // helper dao methods mock
            when(_svc._vmSnapshotDao.findByVm(any(Long.class))).thenReturn(new ArrayList<VMSnapshotVO>());
            when(_svc._vmInstanceDao.findById(any(Long.class))).thenReturn(stoppedVm);

            DataCenterVO enabledZone = Mockito.mock(DataCenterVO.class);
            when(enabledZone.getAllocationState()).thenReturn(Grouping.AllocationState.Enabled);

            when(_svc._dcDao.findById(anyLong())).thenReturn(enabledZone);

        } finally {
            txn.close("runVolumeDaoImplTest");
        }

        // helper methods mock
        doNothing().when(_svc._accountMgr).checkAccess(any(Account.class), any(AccessType.class), any(Boolean.class), any(ControlledEntity.class));
        doNothing().when(_svc._jobMgr).updateAsyncJobAttachment(any(Long.class), any(String.class), any(Long.class));
        when(_svc._jobMgr.submitAsyncJob(any(AsyncJobVO.class), any(String.class), any(Long.class))).thenReturn(1L);
    }

    /**
     * TESTS FOR DETACH ROOT VOLUME, COUNT=4
     * @throws Exception
     */

    @Test(expected = InvalidParameterValueException.class)
    public void testDetachVolumeFromRunningVm() throws NoSuchFieldException, IllegalAccessException {
        Field dedicateIdField = _detachCmdClass.getDeclaredField("id");
        dedicateIdField.setAccessible(true);
        dedicateIdField.set(detachCmd, 1L);
        _svc.detachVolumeFromVM(detachCmd);
    }

    @Test(expected = InvalidParameterValueException.class)
    public void testDetachVolumeFromStoppedHyperVVm() throws NoSuchFieldException, IllegalAccessException {
        Field dedicateIdField = _detachCmdClass.getDeclaredField("id");
        dedicateIdField.setAccessible(true);
        dedicateIdField.set(detachCmd, 3L);
        _svc.detachVolumeFromVM(detachCmd);
    }

    @Test(expected = InvalidParameterValueException.class)
    public void testDetachVolumeOfManagedDataStore() throws NoSuchFieldException, IllegalAccessException {
        Field dedicateIdField = _detachCmdClass.getDeclaredField("id");
        dedicateIdField.setAccessible(true);
        dedicateIdField.set(detachCmd, 4L);
        _svc.detachVolumeFromVM(detachCmd);
    }

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testDetachVolumeFromStoppedXenVm() throws NoSuchFieldException, IllegalAccessException {
        thrown.expect(NullPointerException.class);
        Field dedicateIdField = _detachCmdClass.getDeclaredField("id");
        dedicateIdField.setAccessible(true);
        dedicateIdField.set(detachCmd, 2L);
        _svc.detachVolumeFromVM(detachCmd);
    }

    /**
     * TESTS FOR ATTACH ROOT VOLUME, COUNT=7
     */

    // Negative test - try to attach non-root non-datadisk volume
    @Test(expected = InvalidParameterValueException.class)
    public void attachIncorrectDiskType() throws NoSuchFieldException, IllegalAccessException {
        _svc.attachVolumeToVM(1L, 5L, 0L);
    }

    // Negative test - attach root volume to running vm
    @Test(expected = InvalidParameterValueException.class)
    public void attachRootDiskToRunningVm() throws NoSuchFieldException, IllegalAccessException {
        _svc.attachVolumeToVM(1L, 6L, 0L);
    }

    // Negative test - attach root volume to non-xen vm
    @Test(expected = InvalidParameterValueException.class)
    public void attachRootDiskToHyperVm() throws NoSuchFieldException, IllegalAccessException {
        _svc.attachVolumeToVM(3L, 6L, 0L);
    }

    // Negative test - attach root volume from the managed data store
    @Test(expected = InvalidParameterValueException.class)
    public void attachRootDiskOfManagedDataStore() throws NoSuchFieldException, IllegalAccessException {
        _svc.attachVolumeToVM(2L, 7L, 0L);
    }

    // Negative test - root volume can't be attached to the vm already having a root volume attached
    @Test(expected = InvalidParameterValueException.class)
    public void attachRootDiskToVmHavingRootDisk() throws NoSuchFieldException, IllegalAccessException {
        _svc.attachVolumeToVM(4L, 6L, 0L);
    }

    // Negative test - root volume in uploaded state can't be attached
    @Test(expected = InvalidParameterValueException.class)
    public void attachRootInUploadedState() throws NoSuchFieldException, IllegalAccessException {
        _svc.attachVolumeToVM(2L, 8L, 0L);
    }

    // Positive test - attach ROOT volume in correct state, to the vm not having root volume attached
    @Test
    public void attachRootVolumePositive() throws NoSuchFieldException, IllegalAccessException {
        thrown.expect(NullPointerException.class);
        _svc.attachVolumeToVM(2L, 6L, 0L);
    }

    // volume not Ready
    @Test(expected = InvalidParameterValueException.class)
    public void testTakeSnapshotF1() throws ResourceAllocationException {
        when(_volFactory.getVolume(anyLong())).thenReturn(volumeInfoMock);
        when(volumeInfoMock.getState()).thenReturn(Volume.State.Allocated);
        when(volumeInfoMock.getPoolId()).thenReturn(1L);
        _svc.takeSnapshot(5L, Snapshot.MANUAL_POLICY_ID, 3L, null, false, null);
    }

    @Test
    public void testTakeSnapshotF2() throws ResourceAllocationException {
        when(_volFactory.getVolume(anyLong())).thenReturn(volumeInfoMock);
        when(volumeInfoMock.getState()).thenReturn(Volume.State.Ready);
        when(volumeInfoMock.getInstanceId()).thenReturn(null);
        when(volumeInfoMock.getPoolId()).thenReturn(1L);
        when (volService.takeSnapshot(Mockito.any(VolumeInfo.class))).thenReturn(snapshotInfoMock);
        _svc.takeSnapshot(5L, Snapshot.MANUAL_POLICY_ID, 3L, null, false, null);
    }

    @Test
    public void testNullGetVolumeNameFromCmd() {
        when(createVol.getVolumeName()).thenReturn(null);
        Assert.assertNotNull(_svc.getVolumeNameFromCommand(createVol));
    }

    @Test
    public void testEmptyGetVolumeNameFromCmd() {
        when(createVol.getVolumeName()).thenReturn("");
        Assert.assertNotNull(_svc.getVolumeNameFromCommand(createVol));
    }

    @Test
    public void testBlankGetVolumeNameFromCmd() {
        when(createVol.getVolumeName()).thenReturn("   ");
        Assert.assertNotNull(_svc.getVolumeNameFromCommand(createVol));
    }

    @Test
    public void testNonEmptyGetVolumeNameFromCmd() {
        when(createVol.getVolumeName()).thenReturn("abc");
        Assert.assertSame(_svc.getVolumeNameFromCommand(createVol), "abc");
    }

    @Test
    public void testUpdateMissingRootDiskControllerWithNullChainInfo() {
        _svc.updateMissingRootDiskController(null, null);
        verify(_svc._userVmMgr, times(0)).persistDeviceBusInfo(any(UserVmVO.class), anyString());
    }

    @Test
    public void testUpdateMissingRootDiskControllerWithValidChainInfo() {
        UserVmVO vm = _svc._userVmDao.findById(1L);
        assert vm.getType() == VirtualMachine.Type.User;
        _svc.updateMissingRootDiskController(vm, "{\"diskDeviceBusName\":\"scsi0:0\",\"diskChain\":[\"[somedatastore] i-3-VM-somePath/ROOT-1.vmdk\"]}");
        verify(_svc._userVmMgr, times(1)).persistDeviceBusInfo(any(UserVmVO.class), eq("scsi"));
    }

    @Test
    /**
     * Setting locationType for a non-managed storage should give an error
     */
    public void testAllocSnapshotNonManagedStorageArchive() {
        try {
            _svc.allocSnapshot(6L, 1L, "test", Snapshot.LocationType.SECONDARY);
        } catch (InvalidParameterValueException e) {
            Assert.assertEquals(e.getMessage(), "VolumeId: 6 LocationType is supported only for managed storage");
            return;
        } catch (ResourceAllocationException e) {
            Assert.fail("Unexpected excepiton " + e.getMessage());
        }

        Assert.fail("Expected Exception for archive in non-managed storage");
    }

    @After
    public void tearDown() {
        CallContext.unregister();
    }
}


text:
import * as path from 'path';
import { runTests } from '@vscode/test-electron';

async function main() {
	try {
		const extensionDevelopmentPath = path.resolve(__dirname, '..');
		const extensionTestsPath = path.resolve(__dirname, './index');

		await runTests({extensionDevelopmentPath, extensionTestsPath});
	} catch (err) {
		console.error(err);
		console.error('Failed to run tests');
		process.exit(1);
	}
}

main();


text:
import angular from 'angular';
import ngTranslate from 'angular-translate';
import TALEND_WIDGET from '../../widgets/widget-module';

import ColumnProfileOptionsComponent from './column-profile-options-component';

const MODULE_NAME = 'data-prep.column-profile-options';

/**
 * @ngdoc object
 * @name data-prep.column-profile-options
 * @description Column profile (charts) options
 */
angular.module(MODULE_NAME, [ngTranslate, TALEND_WIDGET])
    .component('columnProfileOptions', ColumnProfileOptionsComponent);

export default MODULE_NAME;


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../../../style.css" type="text/css" media="screen">
<link rel="stylesheet" href="../../../../../../print.css" type="text/css" media="print">
<meta content="ISeries,com.yahoo.astra.fl.charts.series.ISeries,chart,dataProvider,displayName,length,clone,itemRendererToIndex,itemToItemRenderer" name="keywords">
<title>com.yahoo.astra.fl.charts.series.ISeries</title>

YUI Flash Component Documentation	All Packages | All Classes | Index | FramesNo Frames

Interface ISeries	Properties | Methods | Events

Package	com.yahoo.astra.fl.charts.series

Interface	public interface ISeries extends flash.events.IEventDispatcher

Subinterfaces	ICategorySeries, ILegendItemSeries, IStackedSeries

Implementors	Series, SeriesItemRenderer

  A renderer for a series displayed on a chart.

Important: Must be a subclass of DisplayObject

See also

flash.display.DisplayObject

Public Properties

 	Property	Defined by

 	 	chart : Object

   The chart in which this series appears.

	ISeries

 	 	dataProvider : Object

   The data provider for this series.

	ISeries

 	 	displayName : String

   The name of the series as it appears to the user.

	ISeries

 	 	length : int
[read-only]
   The number of items in the series.

	ISeries

Public Methods

 	Method	Defined by

clone():ISeries

   Creates a copy of the ISeries object.

	ISeries

itemRendererToIndex(renderer:ISeriesItemRenderer):int

	ISeries

itemToItemRenderer(item:Object):ISeriesItemRenderer

	ISeries

Events

 	Event	Summary	Defined by

dataChange

  Dispatched when the data property for an ISeries changes.	ISeries

Property detail

chart	property

chart:Object  [read-write]

   The chart in which this series appears.

Implementation

    public function get chart():Object

    public function set chart(value:Object):void

dataProvider	property

dataProvider:Object  [read-write]

   The data provider for this series. Accepts Array or XMLList objects.

Implementation

    public function get dataProvider():Object

    public function set dataProvider(value:Object):void

displayName	property

displayName:String  [read-write]

   The name of the series as it appears to the user.

Implementation

    public function get displayName():String

    public function set displayName(value:String):void

length	property

length:int  [read-only]

   The number of items in the series.

Implementation

    public function get length():int

Method detail

clone	()	method

public function clone():ISeries

   Creates a copy of the ISeries object.

Returns

	ISeries —
                        a new ISeries object

itemRendererToIndex	()	method

public function itemRendererToIndex(renderer:ISeriesItemRenderer):intParameters

	renderer:ISeriesItemRenderer

Returns

	int

itemToItemRenderer	()	method

public function itemToItemRenderer(item:Object):ISeriesItemRendererParameters

	item:Object

Returns

	ISeriesItemRenderer

Event detail

dataChange	event

Event object type: flash.events.Event

  Dispatched when the data property for an ISeries changes.


text:
//
// Copyright 2014 Mike Friesen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

package ca.gobits.dht.factory;

import static ca.gobits.dht.DHTIdentifier.NODE_ID_LENGTH;
import static ca.gobits.dht.util.DHTConversion.fitToSize;

import java.net.InetAddress;
import java.util.Date;

import ca.gobits.dht.DHTNode;
import ca.gobits.dht.DHTNode.State;

/**
 * DHTNode Factory class.
 *
 */
public final class DHTNodeFactory {

    /**
     * private constructor.
     */
    private DHTNodeFactory() {
    }

    /**
     * Creates DHTNode.
     * @param infoHash  InfoHash
     * @param state  State
     * @return DHTNode
     */
    public static DHTNode create(final byte[] infoHash, final State state) {

        DHTNode node = new DHTNode();
        node.setLastUpdated(new Date());
        updateInfoHash(node, infoHash);
        node.setState(state);
        return node;
    }

    /**
     * Creates DHTNode.
     * @param infoHash  InfoHash
     * @param addr  InetAddress
     * @param port  port
     * @param state  State
     * @return DHTNode
     */
    public static DHTNode create(final byte[] infoHash,
            final InetAddress addr, final int port, final State state) {

        DHTNode node = new DHTNode();
        node.setLastUpdated(new Date());
        updateInfoHash(node, infoHash);
        node.setState(state);

        node.setAddress(addr);
        node.setPort(port);

        return node;
    }

    /**
     * Updates Infohash to ensure correct length.
     * @param node  DHTNode
     * @param infoHash  infohash
     */
    private static void updateInfoHash(final DHTNode node,
            final byte[] infoHash) {
        node.setInfoHash(fitToSize(infoHash, NODE_ID_LENGTH));
    }
}


text:
class SceneManager
{
public:
#ifdef USE_QGLVIEWER
    SceneManager(qglviewer::Camera &camera, GLint vaoId, GLint vboPositionId, GLint eboId, GLuint colorLocation);
#else
    SceneManager(qglviewer_fake::Camera &camera, GLint vaoId, GLint vboPositionId, GLint eboId, GLuint colorLocation);
#endif

    typedef std::map<unsigned int, SceneObject*>::iterator iterator;
    typedef std::map<unsigned int, SceneObject*>::const_iterator const_iterator;

    inline iterator begin(){return m_objects.begin();}
    inline const_iterator begin() const{return m_objects.begin();}

    inline iterator end(){return m_objects.end();}
    inline const_iterator end() const{return m_objects.end();}

    ///
    /// \brief setup
    /// setup what we want for rendering
    ///
    void setup();

    ///
    /// \brief attaches an object to the manager.
    /// \param object object to attach
    /// \param reallocate specifies if the function is authorized to call glBindBuffer again if needed.
    /// It can be efficient to avoid reallocating when several objects are attached to the manager at once.
    ///
    void append(SceneObject* object, bool reallocate=true);

    ///
    /// \brief removes a object from the manager and returns it (often for deletion).
    /// \param id id of the object to be removed
    ///
    SceneObject *remove(unsigned int id);

    //OpenGL rendering

    ///
    /// \brief allocate the memory necessary to transfer class datas to VBO datas, done by remakeScene().
    ///
    ///
    void allocateScene();

    ///
    /// \brief transfer class datas to VAO/VBO/EBO datas.
    /// It updates any needed information about the OpenGL state. It also perform a reallocation if necessary.
    /// This function must be called whenever the size of the VBOs or the EBOs increases.
    /// If you know it doesn't, you probably prefer to call updateScene instead.
    ///
    void remakeScene();

    ///
    /// \brief transfer class datas to VAO/VBO/EBO datas.
    /// This shouldn't be used if the organisation of the VBO or the EBO changed. Use remakeScene() if it did.
    ///
    void updateScene();

    ///
    /// \brief draw the scene, using VBO/EBO datas.
    ///
    void drawScene();

    //Non-OpenGL rendering

    ///
    /// \brief myFirstRendering
    ///  a debugging rendering, just to see if my calculations (ray intersection, etc) are correct.
    ///  Fills a pixel with the face's color if there is something, black otherwise.
    ///
    void myFirstRendering();

    ///
    /// \brief phongRendering
    /// uses phong rendering to render each object, with some faces being light sources.
    /// \param quality precision of the shadowing
    /// \param N N*N stochastic tracing (use 0 if you don't want to use stochastic ray tracing)
    ///
    void mainRendering(size_t quality=0, SceneObject::Integral::Type_t typeIntegral=SceneObject::Integral::SINGLE_MEAN,
                        float reflectionAngle=M_PI, unsigned int reflectionQuality=0);

    //Other functions

    SceneObject *operator[](unsigned int i);

    void setObject(unsigned int index, SceneObject* object);
    SceneObject* getObject(unsigned int index);

    void allocateVBOPosition();
    void allocateEBO();

private:

    //render functions
    glm::vec3 lightenMaterialProp(SceneFace_Prop *face, const glm::vec3& positionFace, const glm::vec3 &normalFace,
                                  const glm::vec3 vToEye, size_t quality, SceneObject::Integral::Type_t type=SceneObject::Integral::SINGLE_MEAN);

    glm::vec3 reflectionMaterialProp(SceneFace_Prop *face, const glm::vec3& positionFace,
                                    const glm::vec3& normalFace, const glm::vec3 vToEye,
                                    size_t quality, SceneObject::Integral::Type_t typeIntegral,
                                    float angleReflection, unsigned int reflectionQuality);

    std::map<unsigned int, SceneObject*> m_objects;

    SceneCamera                     m_camera;

    /// OpenGL objects
    GLint                           m_VAOId;
    GLint                           m_VBOPositionId;
    GLint                           m_EBOId;
    GLint                           m_uColorLocation;

    /// VBO/EBO sizes
    GLsizeiptr                      m_VBOPositionSize;
    GLsizeiptr                      m_EBOSize;
    GLint                           m_currentBaseVertex;

    GLsizeiptr                      m_VBOPositionCapacity;
    GLsizeiptr                      m_EBOCapacity;
};

#endif // SCENEMANAGER_H


text:
<body>
Common package containing only the constants for the variability configuration.
</body>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Friesia 3(4): 301 (1947)

#### Original name
Sclerotinia caricis-ampullaceae Nyberg

### Remarks
null


text:
package io.circe.cursor

import cats.Applicative
import cats.data.Xor
import io.circe.{ ACursor, Decoder, DecodingFailure, GenericCursor, HCursor, Json }

/**
 * A helper trait that implements cursor operations for [[io.circe.ACursor]].
 */
private[circe] trait ACursorOperations extends GenericCursor[ACursor] { this: ACursor =>
  type Focus[x] = Option[x]
  type Result = ACursor
  type M[x[_]] = Applicative[x]

  /**
   * A helper method to simplify performing operations on the underlying [[HCursor]].
   */
  private[this] def withHCursor(f: HCursor => ACursor): ACursor =
    ACursor(either.flatMap(c => f(c).either))

  def focus: Option[Json] = success.map(_.focus)
  def top: Option[Json] = success.map(_.top)

  def delete: ACursor = withHCursor(_.delete)
  def withFocus(f: Json => Json): ACursor = ACursor(either.map(_.withFocus(f)))
  def withFocusM[F[_]](f: Json => F[Json])(implicit F: Applicative[F]): F[ACursor] =
    either.fold(
      _ => F.pure(this),
      valid => F.map(valid.withFocusM(f))(ACursor.ok)
    )

  def lefts: Option[List[Json]]     = success.flatMap(_.lefts)
  def rights: Option[List[Json]]    = success.flatMap(_.rights)

  def fieldSet: Option[Set[String]] = success.flatMap(_.fieldSet)
  def fields: Option[List[String]]  = success.flatMap(_.fields)

  def up: ACursor                          = withHCursor(_.up)
  def left: ACursor                        = withHCursor(_.left)
  def right: ACursor                       = withHCursor(_.right)
  def first: ACursor                       = withHCursor(_.first)
  def last: ACursor                        = withHCursor(_.last)
  def leftN(n: Int): ACursor               = withHCursor(_.leftN(n))
  def rightN(n: Int): ACursor              = withHCursor(_.rightN(n))
  def leftAt(p: Json => Boolean): ACursor  = withHCursor(_.leftAt(p))
  def rightAt(p: Json => Boolean): ACursor = withHCursor(_.rightAt(p))
  def find(p: Json => Boolean): ACursor    = withHCursor(_.find(p))
  def downArray: ACursor                   = withHCursor(_.downArray)
  def downAt(p: Json => Boolean): ACursor  = withHCursor(_.downAt(p))
  def downN(n: Int): ACursor               = withHCursor(_.downN(n))
  def field(k: String): ACursor            = withHCursor(_.field(k))
  def downField(k: String): ACursor        = withHCursor(_.downField(k))
  def deleteGoLeft: ACursor                = withHCursor(_.deleteGoLeft)
  def deleteGoRight: ACursor               = withHCursor(_.deleteGoRight)
  def deleteGoFirst: ACursor               = withHCursor(_.deleteGoFirst)
  def deleteGoLast: ACursor                = withHCursor(_.deleteGoLast)
  def deleteLefts: ACursor                 = withHCursor(_.deleteLefts)
  def deleteRights: ACursor                = withHCursor(_.deleteRights)
  def setLefts(x: List[Json]): ACursor     = withHCursor(_.setLefts(x))
  def setRights(x: List[Json]): ACursor    = withHCursor(_.setRights(x))
  def deleteGoField(k: String): ACursor    = withHCursor(_.deleteGoField(k))

  def as[A](implicit d: Decoder[A]): Decoder.Result[A] = d.tryDecode(this)
  def get[A](k: String)(implicit d: Decoder[A]): Decoder.Result[A] = downField(k).as[A]
}


text:
Strava: Switch Units
""""""""""""""""""""

A Chrome extension to quickly switch between imperial and metric units without
navigating to the settings dialog.

For more information, please read:

  https://chris-lamb.co.uk/posts/quickly-switching-between-imperial-and-metric-units-strava

Installation
============

 * Clone (or otherwise download) the contents of this repository.

 * In Chrome, go to "Tools > Extensions".

 * Ensure "Developer mode" is ticked.

 * Click "Load unpacked extension" and select the directory you have stored
   this code.

 * Refresh any page on Strava - the extension will now be active.


text:
<?php

declare(strict_types=1);

namespace App\IqrfAppModule\Presenters;

use App\IqrfAppModule\Forms\IqrfNetBondingFormFactory;
use App\IqrfAppModule\Forms\IqrfNetDiscoveryFormFactory;
use App\IqrfAppModule\Forms\IqrfNetRfFormFactory;
use App\IqrfAppModule\Forms\IqrfNetSecurityFormFactory;
use App\Presenters\BasePresenter;
use Nette\Application\UI\Form;

/**
 * IQMESH Network Manager presenter
 */
class NetworkPresenter extends BasePresenter {

	/**
	 * @var IqrfNetBondingFormFactory IQMESH Bonding form
	 * @inject
	 */
	public $bondingForm;

	/**
	 * @var IqrfNetDiscoveryFormFactory IQMESH Discovery form
	 * @inject
	 */
	public $discoveryForm;

	/**
	 * @var IqrfNetRfFormFactory IQMESH RF form
	 * @inject
	 */
	public $rfForm;

	/**
	 * @var IqrfNetSecurityFormFactory IQMESH Security form
	 * @inject
	 */
	public $securityForm;

	/**
	 * Render default page
	 */
	public function renderDefault() {
		$this->onlyForAdmins();
	}

	/**
	 * Create IQMESH Bonding form
	 * @return Form IQMESH Bonding form
	 */
	protected function createComponentIqrfNetBondingForm(): Form {
		$this->onlyForAdmins();
		return $this->bondingForm->create($this);
	}

	/**
	 * Create IQMESH Discovery form
	 * @return Form IQMESH Discovery form
	 */
	protected function createComponentIqrfNetDiscoveryForm(): Form {
		$this->onlyForAdmins();
		return $this->discoveryForm->create($this);
	}

	/**
	 * Create IQMESH RF form
	 * @return Form IQMESH RF form
	 */
	protected function createComponentIqrfNetRfForm(): Form {
		$this->onlyForAdmins();
		return $this->rfForm->create($this);
	}

	/**
	 * Create IQMESH Security form
	 * @return Form IQMESH Security form
	 */
	protected function createComponentIqrfNetSecurityForm(): Form {
		$this->onlyForAdmins();
		return $this->securityForm->create($this);
	}

}


text:
package net.commandercoriander.testing.data;

import java.sql.ResultSet;
import java.sql.SQLException;

@FunctionalInterface
public interface DataAssertionBlock {
    void examine(ResultSet ts) throws SQLException;
}


text:
const state = {
  localStore: false,
  address: null,
  balance: '0',
  blockNumber: 0,
  identifier: '',
  isHardware: false,
  ledgerBLE: false,
  ledgerApp: {},
  instance: null,
  isOfflineApp: false,
  web3: {},
  ensDomains: null,
  tokens: [],
  loadingWalletInfo: true
};

export default state;


text:
import {ListWrapper, MapWrapper} from 'angular2/src/facade/collection';
import {Company, Opportunity, Offering, Account, CustomDate, STATUS_LIST}
    from './common';
import {For} from 'angular2/directives';

// TODO(radokirov): Once the application is transpiled by TS instead of Traceur,
// add those imports back into 'angular2/angular2';
import {Component, Directive} from 'angular2/src/core/annotations_impl/annotations';
import {View} from 'angular2/src/core/annotations_impl/view';

export class HasStyle {
  style:Map;

  constructor() {
    this.style = MapWrapper.create();
  }

  set width(w) {
    MapWrapper.set(this.style, 'width', w);
  }
}

@Component({
  selector: 'company-name',
  properties: {
    'width': 'cell-width',
    'company': 'company'
  }
})
@View({
    directives: [],
    template: `<div [style]="style">{{company.name}}</div>`
})
export class CompanyNameComponent extends HasStyle {
  company:Company;
}

@Component({
  selector: 'opportunity-name',
  properties: {
    'width': 'cell-width',
    'opportunity': 'opportunity'
  }
})
@View({
    directives: [],
    template: `<div [style]="style">{{opportunity.name}}</div>`
})
export class OpportunityNameComponent extends HasStyle {
  opportunity:Opportunity;
}

@Component({
  selector: 'offering-name',
  properties: {
    'width': 'cell-width',
    'offering': 'offering'
  }
})
@View({
    directives: [],
    template: `<div [style]="style">{{offering.name}}</div>`
})
export class OfferingNameComponent extends HasStyle {
  offering:Offering;
}

export class Stage {
  name:string;
  isDisabled:boolean;
  style:Map;
  apply:Function;
}

@Component({
  selector: 'stage-buttons',
  properties: {
    'width': 'cell-width',
    'offering': 'offering'
  }
})
@View({
    directives: [For],
    template: `
      <div [style]="style">
          <button template="for #stage of stages"
                  [disabled]="stage.isDisabled"
                  [style]="stage.style"
                  on-click="setStage(stage)">
            {{stage.name}}
          </button>
      </div>`
})
export class StageButtonsComponent extends HasStyle {
  _offering:Offering;
  stages:List<Stage>;

  get offering():Offering { return this._offering; }

  set offering(offering:Offering) {
    this._offering = offering;
    this._computeStageButtons();
  }

  setStage(stage:Stage) {
    this._offering.status = stage.name;
    this._computeStageButtons();
  }

  _computeStageButtons() {
    var disabled = true;
    this.stages = ListWrapper.clone(STATUS_LIST
      .map((status) => {
        var isCurrent = this._offering.status == status;
        var stage = new Stage();
        stage.name = status;
        stage.isDisabled = disabled;
        var stageStyle = MapWrapper.create();
        MapWrapper.set(stageStyle, 'background-color',
          disabled
            ? '#DDD'
            : isCurrent
              ? '#DDF'
              : '#FDD');
        stage.style = stageStyle;
        if (isCurrent) {
          disabled = false;
        }
        return stage;
      }));
  }
}

@Component({
  selector: 'account-cell',
  properties: {
    'width': 'cell-width',
    'account': 'account'
  }
})
@View({
    directives: [],
    template: `
      <div [style]="style">
        <a href="/account/{{account.accountId}}">
          {{account.accountId}}
        </a>
      </div>`
})
export class AccountCellComponent extends HasStyle {
  account:Account;
}

@Component({
  selector: 'formatted-cell',
  properties: {
    'width': 'cell-width',
    'value': 'value'
  }
})
@View({
    directives: [],
    template: `<div [style]="style">{{formattedValue}}</div>`
})
export class FormattedCellComponent extends HasStyle {
  formattedValue:string;

  set value(value) {
    if (value instanceof CustomDate) {
      this.formattedValue = `${value.month}/${value.day}/${value.year}`;
    } else {
      this.formattedValue = value.toString();
    }
  }
}