text:
package org.quartz.core;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicBoolean;

import org.quartz.QuartzScheduler;
import org.quartz.exceptions.JobPersistenceException;
import org.quartz.exceptions.SchedulerException;
import org.quartz.triggers.OperableTrigger;
import org.quartz.triggers.Trigger;
import org.quartz.triggers.Trigger.CompletedExecutionInstruction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *

 * The thread responsible for performing the work of firing {@link Trigger} s that are registered with the
 * {@link QuartzScheduler}.
 *

 *
 * @see QuartzScheduler
 * @see org.quartz.jobs.Job
 * @see Trigger
 * @author James House
 */
public class QuartzSchedulerThread extends Thread {

  /*
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Data members.
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   */
  private QuartzScheduler quartzScheduler;

  private QuartzSchedulerResources quartzSchedulerResources;

  private final Object sigLock = new Object();

  private boolean signaled;

  private long signaledNextFireTime;

  private boolean paused;

  private AtomicBoolean halted;

  private Random random = new Random(System.currentTimeMillis());

  // When the scheduler finds there is no current trigger to fire, how long
  // it should wait until checking again...
  private static long DEFAULT_IDLE_WAIT_TIME = 30L * 1000L;

  private long idleWaitTime = DEFAULT_IDLE_WAIT_TIME;

  private int idleWaitVariablness = 7 * 1000;

  private final Logger logger = LoggerFactory.getLogger(getClass());

  /**
   *

   * Construct a new QuartzSchedulerThread for the given QuartzScheduler as a non-daemon Thread with normal
   * priority.
   *

   */
  public QuartzSchedulerThread(QuartzScheduler qs, QuartzSchedulerResources qsRsrcs) {

    this(qs, qsRsrcs, qsRsrcs.getMakeSchedulerThreadDaemon(), Thread.NORM_PRIORITY);
  }

  /**
   *

   * Construct a new QuartzSchedulerThread for the given QuartzScheduler as a Thread with the given attributes.
   *

   */
  private QuartzSchedulerThread(QuartzScheduler quartzScheduler, QuartzSchedulerResources quartzSchedulerResources, boolean setDaemon, int threadPrio) {

    super(quartzScheduler.getSchedulerThreadGroup(), quartzSchedulerResources.getThreadName());
    this.quartzScheduler = quartzScheduler;
    this.quartzSchedulerResources = quartzSchedulerResources;
    this.setDaemon(setDaemon);
    if (quartzSchedulerResources.isThreadsInheritInitializersClassLoadContext()) {
      logger.info("QuartzSchedulerThread Inheriting ContextClassLoader of thread: " + Thread.currentThread().getName());
      this.setContextClassLoader(Thread.currentThread().getContextClassLoader());
    }

    this.setPriority(threadPrio);

    // start the underlying thread, but put this object into the 'paused'
    // state
    // so processing doesn't start yet...
    paused = true;
    halted = new AtomicBoolean(false);
  }

  /*
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Interface.
   * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
   */

  private long getRandomizedIdleWaitTime() {

    return idleWaitTime - random.nextInt(idleWaitVariablness);
  }

  /**
   *

   * Signals the main processing loop to pause at the next possible point.
   *

   */
  public void togglePause(boolean pause) {

    synchronized (sigLock) {
      paused = pause;

      if (paused) {
        signalSchedulingChange(0);
      } else {
        sigLock.notifyAll();
      }
    }
  }

  /**
   *

   * Signals the main processing loop to pause at the next possible point.
   *

   */
  public void halt() {

    synchronized (sigLock) {
      halted.set(true);

      if (paused) {
        sigLock.notifyAll();
      } else {
        signalSchedulingChange(0);
      }
    }
  }

  public boolean isPaused() {

    return paused;
  }

  /**
   *

   * Signals the main processing loop that a change in scheduling has been made - in order to interrupt any sleeping that may be occurring while
   * waiting for the fire time to arrive.
   *

   *
   * @param candidateNewNextFireTime the time (in millis) when the newly scheduled trigger will fire. If this method is being called do to some other
   *        even (rather than scheduling a trigger), the caller should pass zero (0).
   */
  void signalSchedulingChange(long candidateNewNextFireTime) {

    synchronized (sigLock) {
      signaled = true;
      signaledNextFireTime = candidateNewNextFireTime;
      sigLock.notifyAll();
    }
  }

  private void clearSignaledSchedulingChange() {

    synchronized (sigLock) {
      signaled = false;
      signaledNextFireTime = 0;
    }
  }

  public boolean isScheduleChanged() {

    synchronized (sigLock) {
      return signaled;
    }
  }

  public long getSignaledNextFireTime() {

    synchronized (sigLock) {
      return signaledNextFireTime;
    }
  }

  /**
   *

   * The main processing loop of the QuartzSchedulerThread.
   *

   */
  @Override
  public void run() {

    boolean lastAcquireFailed = false;

    while (!halted.get()) {
      try {
        // check if we're supposed to pause...
        synchronized (sigLock) {
          while (paused && !halted.get()) {
            try {
              // wait until togglePause(false) is called...
              sigLock.wait(1000L);
            } catch (InterruptedException ignore) {
            }
          }

          if (halted.get()) {
            break;
          }
        }

        int availThreadCount = quartzSchedulerResources.getThreadPool().blockForAvailableThreads();
        if (availThreadCount > 0) { // will always be true, due to semantics of blockForAvailableThreads...

          List<OperableTrigger> triggers = null;

          long now = System.currentTimeMillis();

          clearSignaledSchedulingChange();
          try {
            triggers = quartzSchedulerResources.getJobStore().acquireNextTriggers(now + idleWaitTime,
                Math.min(availThreadCount, quartzSchedulerResources.getMaxBatchSize()), quartzSchedulerResources.getBatchTimeWindow());
            lastAcquireFailed = false;
            if (logger.isDebugEnabled()) {
              logger.debug("batch acquisition of " + (triggers == null ? 0 : triggers.size()) + " triggers");
            }
          } catch (JobPersistenceException jpe) {

            lastAcquireFailed = true;
          } catch (RuntimeException e) {
            if (!lastAcquireFailed) {
              logger.error("quartzSchedulerThreadLoop: RuntimeException " + e.getMessage(), e);
            }
            lastAcquireFailed = true;
          }

          if (triggers != null && !triggers.isEmpty()) {

            now = System.currentTimeMillis();
            long triggerTime = triggers.get(0).getNextFireTime().getTime();
            long timeUntilTrigger = triggerTime - now;
            while (timeUntilTrigger > 2) {
              synchronized (sigLock) {
                if (halted.get()) {
                  break;
                }
                if (!isCandidateNewTimeEarlierWithinReason(triggerTime, false)) {
                  try {
                    // we could have blocked a long while
                    // on 'synchronize', so we must recompute
                    now = System.currentTimeMillis();
                    timeUntilTrigger = triggerTime - now;
                    if (timeUntilTrigger >= 1) {
                      sigLock.wait(timeUntilTrigger);
                    }
                  } catch (InterruptedException ignore) {
                  }
                }
              }
              if (releaseIfScheduleChangedSignificantly(triggers, triggerTime)) {
                break;
              }
              now = System.currentTimeMillis();
              timeUntilTrigger = triggerTime - now;
            }

            // this happens if releaseIfScheduleChangedSignificantly decided to release triggers
            if (triggers.isEmpty()) {
              continue;
            }

            // set triggers to 'executing'
            List<TriggerFiredResult> bndles = new ArrayList<TriggerFiredResult>();

            boolean goAhead = true;
            synchronized (sigLock) {
              goAhead = !halted.get();
            }
            if (goAhead) {
              try {
                List<TriggerFiredResult> res = quartzSchedulerResources.getJobStore().triggersFired(triggers);
                if (res != null) {
                  bndles = res;
                }
              } catch (SchedulerException se) {
                quartzScheduler.notifySchedulerListenersError("An error occurred while firing triggers '" + triggers + "'", se);
              }

            }

            for (int i = 0; i < bndles.size(); i++) {

              TriggerFiredResult result = bndles.get(i);
              TriggerFiredBundle bndle = result.getTriggerFiredBundle();
              Exception exception = result.getException();

              if (exception instanceof RuntimeException) {
                logger.error("RuntimeException while firing trigger " + triggers.get(i), exception);

                continue;
              }

              // it's possible to get 'null' if the triggers was paused,
              // blocked, or other similar occurrences that prevent it being
              // fired at this time... or if the scheduler was shutdown (halted)
              if (bndle == null) {
                try {
                  quartzSchedulerResources.getJobStore().releaseAcquiredTrigger(triggers.get(i));
                } catch (SchedulerException se) {
                  quartzScheduler.notifySchedulerListenersError("An error occurred while releasing triggers '" + triggers.get(i).getName() + "'", se);

                }
                continue;
              }

              // TODO: improvements:
              //
              // 2- make sure we can get a job runshell before firing triggers, or
              // don't let that throw an exception (right now it never does,
              // but the signature says it can).
              // 3- acquire more triggers at a time (based on num threads available?)

              JobRunShell shell = null;
              try {
                shell = quartzSchedulerResources.getJobRunShellFactory().createJobRunShell(bndle);
                shell.initialize(quartzScheduler);
              } catch (SchedulerException se) {
                try {
                  quartzSchedulerResources.getJobStore().triggeredJobComplete(triggers.get(i), bndle.getJobDetail(),
                      CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_ERROR);
                } catch (SchedulerException se2) {
                  quartzScheduler.notifySchedulerListenersError("An error occurred while placing job's triggers in error state '"
                      + triggers.get(i).getName() + "'", se2);

                }
                continue;
              }

              if (quartzSchedulerResources.getThreadPool().runInThread(shell) == false) {
                try {
                  // this case should never happen, as it is indicative of the
                  // scheduler being shutdown or a bug in the thread pool or
                  // a thread pool being used concurrently - which the docs
                  // say not to do...
                  logger.error("ThreadPool.runInThread() return false!");
                  quartzSchedulerResources.getJobStore().triggeredJobComplete(triggers.get(i), bndle.getJobDetail(),
                      CompletedExecutionInstruction.SET_ALL_JOB_TRIGGERS_ERROR);
                } catch (SchedulerException se2) {
                  quartzScheduler.notifySchedulerListenersError("An error occurred while placing job's triggers in error state '"
                      + triggers.get(i).getName() + "'", se2);

                }
              }

            }

            continue; // while (!halted)
          }
        } else { // if(availThreadCount > 0)
          // should never happen, if threadPool.blockForAvailableThreads() follows contract
          continue; // while (!halted)
        }

        long now = System.currentTimeMillis();
        long waitTime = now + getRandomizedIdleWaitTime();
        long timeUntilContinue = waitTime - now;
        synchronized (sigLock) {
          try {
            sigLock.wait(timeUntilContinue);
          } catch (InterruptedException ignore) {
          }
        }

      } catch (RuntimeException re) {
        logger.error("Runtime error occurred in main trigger firing loop.", re);
      }
    } // while (!halted)

    // drop references to scheduler stuff to aid garbage collection...
    quartzScheduler = null;
    quartzSchedulerResources = null;
  }

  private boolean releaseIfScheduleChangedSignificantly(List<OperableTrigger> triggers, long triggerTime) {

    if (isCandidateNewTimeEarlierWithinReason(triggerTime, true)) {

      for (OperableTrigger trigger : triggers) {
        try {
          // above call does a clearSignaledSchedulingChange()
          quartzSchedulerResources.getJobStore().releaseAcquiredTrigger(trigger);
        } catch (JobPersistenceException jpe) {
          quartzScheduler.notifySchedulerListenersError("An error occurred while releasing trigger '" + trigger.getName() + "'", jpe);

        } catch (RuntimeException e) {
          logger.error("releaseTriggerRetryLoop: RuntimeException " + e.getMessage(), e);

        }
      }
      triggers.clear();
      return true;
    }
    return false;
  }

  private boolean isCandidateNewTimeEarlierWithinReason(long oldTime, boolean clearSignal) {

    // So here's the deal: We know due to being signaled that 'the schedule'
    // has changed. We may know (if getSignaledNextFireTime() != 0) the
    // new earliest fire time. We may not (in which case we will assume
    // that the new time is earlier than the trigger we have acquired).
    // In either case, we only want to abandon our acquired trigger and
    // go looking for a new one if "it's worth it". It's only worth it if
    // the time cost incurred to abandon the trigger and acquire a new one
    // is less than the time until the currently acquired trigger will fire,
    // otherwise we're just "thrashing" the job store (e.g. database).
    //
    // So the question becomes when is it "worth it"? This will depend on
    // the job store implementation (and of course the particular database
    // or whatever behind it). Ideally we would depend on the job store
    // implementation to tell us the amount of time in which it "thinks"
    // it can abandon the acquired trigger and acquire a new one. However
    // we have no current facility for having it tell us that, so we make
    // a somewhat educated but arbitrary guess ;-).

    synchronized (sigLock) {

      if (!isScheduleChanged()) {
        return false;
      }

      boolean earlier = false;

      if (getSignaledNextFireTime() == 0) {
        earlier = true;
      } else if (getSignaledNextFireTime() < oldTime) {
        earlier = true;
      }

      if (earlier) {
        // so the new time is considered earlier, but is it enough earlier?
        long diff = oldTime - System.currentTimeMillis();
        if (diff < 7L) {
          earlier = false;
        }
      }

      if (clearSignal) {
        clearSignaledSchedulingChange();
      }

      return earlier;
    }
  }

} // end of QuartzSchedulerThread


text:
using Certify.Management;
using Certify.Models;
using Certify.UI.Resources;
using PropertyChanged;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;

namespace Certify.UI.ViewModel
{
    public class AppModel : BindableBase
    {
        /// <summary>
        /// Provide single static instance of model for all consumers
        /// </summary>
        //public static AppModel AppViewModel = new DesignViewModel(); // for UI testing
        public static AppModel AppViewModel = AppModel.GetModel();

        public const int ProductTypeId = 1;

        private CertifyManager certifyManager = null;

        public PluginManager PluginManager { get; set; }

        public string CurrentError { get; set; }
        public bool IsError { get; set; }

        public void RaiseError(Exception exp)
        {
            this.IsError = true;
            this.CurrentError = exp.Message;

            System.Windows.MessageBox.Show(exp.Message);
        }

        #region properties

        /// <summary>
        /// List of all the sites we currently manage
        /// </summary>
        public ObservableCollection<ManagedSite> ManagedSites
        {
            get { return managedSites; }
            set
            {
                managedSites = value;
                if (SelectedItem != null)
                {
                    SelectedItem = SelectedItem;
                    RaisePropertyChanged(nameof(SelectedItem));
                }
            }
        }
        private ObservableCollection<ManagedSite> managedSites;

        /// <summary>
        /// If set, there are one or more vault items available to be imported as managed sites
        /// </summary>
        public ObservableCollection<ManagedSite> ImportedManagedSites { get; set; }

        internal virtual void LoadVaultTree()
        {
            VaultTree = new List<VaultItem>()
            {
                new VaultItem
                {
                    Name = "Registrations",
                    Children = new List<VaultItem>(certifyManager.GetContactRegistrations())
                },
                new VaultItem
                {
                    Name = "Identifiers",
                    Children = new List<VaultItem>(certifyManager.GeDomainIdentifiers())
                },
                new VaultItem
                {
                    Name = "Certificates",
                    Children = new List<VaultItem>(certifyManager.GetCertificates())
                }
            };
            PrimaryContactEmail = VaultTree.First(i => i.Name == "Registrations")
                .Children.FirstOrDefault()?.Name;
            ACMESummary = certifyManager.GetAcmeSummary();
            VaultSummary = certifyManager.GetVaultSummary();
        }

        /// <summary>
        /// If true, import from vault/iis scan will merge multi domain sites into one managed site
        /// </summary>
        public bool IsImportSANMergeMode { get; set; }

        public virtual bool HasRegisteredContacts
        {
            get
            {
                return certifyManager.HasRegisteredContacts();
            }
        }

        public bool HasSelectedItemDomainOptions
        {
            get
            {
                if (SelectedItem != null && SelectedItem.DomainOptions != null && SelectedItem.DomainOptions.Any())
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public ManagedSite SelectedItem
        {
            get { return selectedItem; }
            set
            {
                if (value?.Id != null && !ManagedSites.Contains(value))
                {
                    value = ManagedSites.FirstOrDefault(s => s.Id == value.Id);
                }
                selectedItem = value;
            }
        }
        private ManagedSite selectedItem;

        public bool IsRegisteredVersion { get; set; }

        public virtual List<SiteBindingItem> WebSiteList
        {
            get
            {
                //get list of sites from IIS
                if (certifyManager.IsIISAvailable)
                {
                    return certifyManager.GetPrimaryWebSites(CoreAppSettings.Current.IgnoreStoppedSites);
                }
                else
                {
                    return new List<SiteBindingItem>();
                }
            }
        }

        internal void SaveManagedItemChanges()
        {
            UpdateManagedSiteSettings();
            AddOrUpdateManagedSite(SelectedItem);
            RaisePropertyChanged(nameof(IsSelectedItemValid));
        }

        internal void AddContactRegistration(ContactRegistration reg)
        {
            // in practise only one registered contact is used, so remove alternatives to avoid cert
            // processing picking up the wrong one
            certifyManager.RemoveAllContacts();

            if (certifyManager.AddRegisteredContact(reg))
            {
                //refresh content from vault
                LoadVaultTree();
            }
            RaisePropertyChanged(nameof(HasRegisteredContacts));
        }

        // Certify-supported challenge types
        public IEnumerable<string> ChallengeTypes { get; set; } = new string[] {
            ACMESharpCompat.ACMESharpUtils.CHALLENGE_TYPE_HTTP,
            ACMESharpCompat.ACMESharpUtils.CHALLENGE_TYPE_SNI
        };

        public IEnumerable<string> WebhookTriggerTypes => Webhook.TriggerTypes;

        public List<IPAddress> HostIPAddresses
        {
            get
            {
                try
                {
                    //return list of ipv4 network IPs
                    IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
                    return hostEntry.AddressList.Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).ToList();
                }
                catch (Exception)
                {
                    //return empty list
                    return new List<IPAddress>();
                }
            }
        }

        public SiteBindingItem SelectedWebSite
        {
            get; set;
        }

        public DomainOption PrimarySubjectDomain
        {
            get { return SelectedItem?.DomainOptions.FirstOrDefault(d => d.IsPrimaryDomain && d.IsSelected); }
            set
            {
                foreach (var d in SelectedItem.DomainOptions)
                {
                    if (d.Domain == value.Domain)
                    {
                        d.IsPrimaryDomain = true;
                        d.IsSelected = true;
                    }
                    else
                    {
                        d.IsPrimaryDomain = false;
                    }
                }
                SelectedItem.IsChanged = true;
            }
        }

        public bool IsSelectedItemValid
        {
            get => SelectedItem?.Id != null && !SelectedItem.IsChanged;
        }

        public string ValidationError { get; set; }

        public int MainUITabIndex { get; set; }

        [DependsOn(nameof(ProgressResults))]
        public bool HasRequestsInProgress
        {
            get
            {
                return (ProgressResults != null && ProgressResults.Any());
            }
        }

        public ObservableCollection<RequestProgressState> ProgressResults { get; set; }

        public List<VaultItem> VaultTree { get; set; }

        [DependsOn(nameof(VaultTree))]
        public string ACMESummary { get; set; }

        [DependsOn(nameof(VaultTree))]
        public string VaultSummary { get; set; }

        public string PrimaryContactEmail { get; set; }

        public bool IsUpdateAvailable { get; set; }

        /// <summary>
        /// If an update is available this will contain more info about the new update
        /// </summary>
        public UpdateCheck UpdateCheckResult { get; set; }

        #endregion properties

        #region methods

        public static AppModel GetModel()
        {
            var stack = new System.Diagnostics.StackTrace();
            if (stack.GetFrames().Last().GetMethod().Name == "Main")
            {
                return new AppModel();
            }
            else
            {
                return new DesignViewModel();
            }
        }

        public AppModel()
        {
            if (!(this is DesignViewModel))
            {
                certifyManager = new CertifyManager();
            }
            ProgressResults = new ObservableCollection<RequestProgressState>();
        }

        public virtual bool IsIISAvailable => certifyManager.IsIISAvailable;
        public virtual Version IISVersion => certifyManager.IISVersion;

        public void PreviewImport(bool sanMergeMode)
        {
            AppViewModel.IsImportSANMergeMode = sanMergeMode;
            //we have no managed sites, offer to import them from vault if we have one
            var importedSites = certifyManager.ImportManagedSitesFromVault(sanMergeMode);
            ImportedManagedSites = new ObservableCollection<ManagedSite>(importedSites);
        }

        public virtual void LoadSettings()
        {
            this.ManagedSites = new ObservableCollection<ManagedSite>(certifyManager.GetManagedSites());
            this.ImportedManagedSites = new ObservableCollection<ManagedSite>();

            /*if (this.ManagedSites.Any())
            {
                //preselect the first managed site
                //  this.SelectedItem = this.ManagedSites[0];

                //test state
                BeginTrackingProgress(new RequestProgressState { CurrentState = RequestState.InProgress, IsStarted = true, Message = "Registering Domain Identifier", ManagedItem = ManagedSites[0] });
                BeginTrackingProgress(new RequestProgressState { CurrentState = RequestState.Error, IsStarted = true, Message = "Rate Limited", ManagedItem = ManagedSites[0] });
            }*/
        }

        public virtual void SaveSettings()
        {
            certifyManager.SaveManagedSites(ManagedSites.ToList());
            foreach (var site in ManagedSites.Where(s => s.Deleted).ToList())
            {
                ManagedSites.Remove(site);
            }
            ManagedSites = new ObservableCollection<ManagedSite>(ManagedSites);
        }

        public bool ConfirmDiscardUnsavedChanges()
        {
            if (SelectedItem?.IsChanged ?? false)
            {
                //user needs to save or discard changes before changing selection
                if (MessageBox.Show(SR.ManagedSites_UnsavedWarning, SR.Alert, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)==DialogResult.OK)
                {
                    DiscardChanges();
                }
                else
                {
                    // user cancelled out of dialog
                    return false;
                }
            }
            return true;
        }

        public void DiscardChanges()
        {
            if (SelectedItem?.IsChanged ?? false)
            {
                if (SelectedItem.Id == null)
                {
                    SelectedItem = null;
                }
                else
                {
                    LoadSettings();
                }
            }
        }

        public async void RenewAll(bool autoRenewalsOnly)
        {
            //FIXME: currently user can run renew all again while renewals are still in progress

            Dictionary<string, Progress<RequestProgressState>> itemTrackers = new Dictionary<string, Progress<RequestProgressState>>();
            foreach (var s in ManagedSites)
            {
                if ((autoRenewalsOnly && s.IncludeInAutoRenew) || !autoRenewalsOnly)
                {
                    var progressState = new RequestProgressState { ManagedItem = s };
                    if (!itemTrackers.ContainsKey(s.Id))
                    {
                        itemTrackers.Add(s.Id, new Progress<RequestProgressState>(progressState.ProgressReport));

                        //begin monitoring progress
                        BeginTrackingProgress(progressState);
                    }
                }
            }

            var results = await certifyManager.PerformRenewalAllManagedSites(autoRenewalsOnly, itemTrackers);
            //TODO: store results in log
            //return results;
        }

        public void AddOrUpdateManagedSite(ManagedSite item)
        {
            int index = ManagedSites.ToList().FindIndex(s => s.Id == item.Id);
            if (index == -1)
            {
                ManagedSites.Add(item);
            }
            else
            {
                ManagedSites[index] = item;
            }
            SaveSettings();
        }

        public virtual void DeleteManagedSite(ManagedSite selectedItem)
        {
            var existing = ManagedSites.FirstOrDefault(s => s.Id == selectedItem.Id);
            if (existing != null)
            {
                if (MessageBox.Show(SR.ManagedItemSettings_ConfirmDelete, SR.ConfirmDelete, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning)==DialogResult.OK)
                {
                    existing.Deleted = true;
                    SaveSettings();
                }
            }
        }

        public void SANSelectAll(object o)
        {
            SelectedItem?.DomainOptions.ToList().ForEach(opt => opt.IsSelected = true);
        }

        public void SANSelectNone(object o)
        {
            SelectedItem?.DomainOptions.ToList().ForEach(opt => opt.IsSelected = false);
        }

        /// <summary>
        /// For the given set of options get a new CertRequestConfig to store
        /// </summary>
        /// <returns></returns>
        public void UpdateManagedSiteSettings()
        {
            var item = SelectedItem;
            var config = item.RequestConfig;
            var primaryDomain = item.DomainOptions.FirstOrDefault(d => d.IsPrimaryDomain == true);

            //if no primary domain need to go back and select one
            if (primaryDomain == null) throw new ArgumentException("Primary subject domain must be set.");

            var _idnMapping = new System.Globalization.IdnMapping();
            config.PrimaryDomain = _idnMapping.GetAscii(primaryDomain.Domain); // ACME service requires international domain names in ascii mode

            //apply remaining selected domains as subject alternative names
            config.SubjectAlternativeNames =
                item.DomainOptions.Where(dm => dm.IsSelected == true)
                .Select(i => i.Domain)
                .ToArray();

            // TODO: config.EnableFailureNotifications = chkEnableNotifications.Checked;

            //determine if this site has an existing entry in Managed Sites, if so use that, otherwise start a new one
            if (SelectedItem.Id == null)
            {
                var siteInfo = SelectedWebSite;
                //if siteInfo null we need to go back and select a site

                item.Id = Guid.NewGuid().ToString() + ":" + siteInfo.SiteId;
                item.GroupId = siteInfo.SiteId;
            }

            item.ItemType = ManagedItemType.SSL_LetsEncrypt_LocalIIS;
        }

        private void PopulateManagedSiteSettings(string siteId)
        {
            ValidationError = null;
            var managedSite = SelectedItem;
            managedSite.Name = SelectedWebSite.SiteName;
            managedSite.GroupId = SelectedWebSite.SiteId;

            //TODO: if this site would be a duplicate need to increment the site name

            //set defaults first
            managedSite.RequestConfig.WebsiteRootPath = Environment.ExpandEnvironmentVariables(SelectedWebSite.PhysicalPath);
            managedSite.RequestConfig.PerformExtensionlessConfigChecks = true;
            managedSite.RequestConfig.PerformTlsSniBindingConfigChecks = true;
            managedSite.RequestConfig.PerformChallengeFileCopy = true;
            managedSite.RequestConfig.PerformAutomatedCertBinding = true;
            managedSite.RequestConfig.PerformAutoConfig = true;
            managedSite.RequestConfig.EnableFailureNotifications = true;
            managedSite.RequestConfig.ChallengeType = ACMESharpCompat.ACMESharpUtils.CHALLENGE_TYPE_HTTP;
            managedSite.IncludeInAutoRenew = true;
            managedSite.DomainOptions.Clear();
            foreach (var option in GetDomainOptionsFromSite(siteId))
            {
                managedSite.DomainOptions.Add(option);
            }

            if (!managedSite.DomainOptions.Any())
            {
                ValidationError = "The selected site has no domain bindings setup. Configure the domains first using Edit Bindings in IIS.";
            }

            //TODO: load settings from previously saved managed site?
            RaisePropertyChanged(nameof(PrimarySubjectDomain));
            RaisePropertyChanged(nameof(HasSelectedItemDomainOptions));
        }

        protected virtual IEnumerable<DomainOption> GetDomainOptionsFromSite(string siteId)
        {
            return certifyManager.GetDomainOptionsFromSite(siteId);
        }

        public async void BeginCertificateRequest(string managedItemId)
        {
            //begin request process
            var managedSite = ManagedSites.FirstOrDefault(s => s.Id == managedItemId);

            if (managedSite != null)
            {
                MainUITabIndex = (int)MainWindow.PrimaryUITabs.CurrentProgress;

                //add request to observable list of progress state
                RequestProgressState progressState = new RequestProgressState();
                progressState.ManagedItem = managedSite;

                //begin monitoring progress
                BeginTrackingProgress(progressState);

                var progressIndicator = new Progress<RequestProgressState>(progressState.ProgressReport);
                var result = await certifyManager.PerformCertificateRequest(managedSite, progressIndicator);

                if (progressIndicator != null)
                {
                    var progress = (IProgress<RequestProgressState>)progressIndicator;

                    if (result.IsSuccess)
                    {
                        progress.Report(new RequestProgressState { CurrentState = RequestState.Success, Message = result.Message });
                    }
                    else
                    {
                        progress.Report(new RequestProgressState { CurrentState = RequestState.Error, Message = result.Message });
                    }
                }
            }
        }

        public async Task<APIResult> TestChallengeResponse(ManagedSite managedSite)
        {
            return await certifyManager.TestChallenge(managedSite, isPreviewMode: true);
        }

        public async Task<APIResult> RevokeSelectedItem()
        {
            var managedSite = SelectedItem;
            var result = await certifyManager.RevokeCertificate(managedSite);
            if (result.IsOK)
            {
                AddOrUpdateManagedSite(managedSite);
            }
            return result;
        }

        private void BeginTrackingProgress(RequestProgressState state)
        {
            var existing = ProgressResults.FirstOrDefault(p => p.ManagedItem.Id == state.ManagedItem.Id);
            if (existing != null)
            {
                ProgressResults.Remove(existing);
            }
            ProgressResults.Add(state);

            RaisePropertyChanged(nameof(HasRequestsInProgress));
        }

        #endregion methods

        #region commands

        public ICommand SANSelectAllCommand => new RelayCommand<object>(SANSelectAll);
        public ICommand SANSelectNoneCommand => new RelayCommand<object>(SANSelectNone);

        public ICommand AddContactCommand => new RelayCommand<ContactRegistration>(AddContactRegistration, this);

        public ICommand PopulateManagedSiteSettingsCommand => new RelayCommand<string>(PopulateManagedSiteSettings);
        public ICommand BeginCertificateRequestCommand => new RelayCommand<string>(BeginCertificateRequest);
        public ICommand RenewAllCommand => new RelayCommand<bool>(RenewAll);

        #endregion commands
    }
}

redpajama_set_name: RedPajamaGithub


text:
export class AppConstants {
  static UPDATE_CONTENT: string = 'APP_UPDATE_CONTENT';
}


text:
using Entitas;
using UnityEngine;
using Entitas.Unity.VisualDebugging;

public class VisualDebuggingExampleSystemsController : MonoBehaviour {
    Systems _systems;

    Pool _pool;

    void Start() {
        _pool = new Pool(VisualDebuggingComponentIds.TotalComponents, 0, new PoolMetaData("Systems Pool", VisualDebuggingComponentIds.componentNames, VisualDebuggingComponentIds.componentTypes));
        #if (!ENTITAS_DISABLE_VISUAL_DEBUGGING && UNITY_EDITOR)
        new PoolObserver(_pool);
        #endif
        _systems = createNestedSystems();
        _systems.Initialize();
        _pool.CreateEntity().AddMyString("");
    }

    void Update() {
        _pool.GetGroup(VisualDebuggingMatcher.MyString).GetSingleEntity().ReplaceMyString(Random.value.ToString());
        _systems.Execute();
    }

    Systems createAllSystemCombinations() {
        return new Feature("All System Combinations")
            .Add(_pool.CreateSystem<SomeInitializeSystem>())
            .Add(_pool.CreateSystem<SomeExecuteSystem>())
            .Add(_pool.CreateSystem<SomeReactiveSystem>())
            .Add(_pool.CreateSystem<SomeInitializeExecuteSystem>())
            .Add(_pool.CreateSystem<SomeInitializeReactiveSystem>());
    }

    Systems createSubSystems() {
        var allSystems = createAllSystemCombinations();
        var subSystems = new Feature("Sub Systems").Add(allSystems);

        return new Feature("Systems with SubSystems")
            .Add(allSystems)
            .Add(allSystems)
            .Add(subSystems)
            .Add(subSystems);
    }

    Systems createSameInstance() {
        var system = _pool.CreateSystem<RandomDurationSystem>();
        return new Feature("Same System Instances")
            .Add(system)
            .Add(system)
            .Add(system);
    }

    Systems createNestedSystems() {
        var systems1 = new Feature("Nested 1");
        var systems2 = new Feature("Nested 2");
        var systems3 = new Feature("Nested 3");

        systems1.Add(systems2);
        systems2.Add(systems3);
        systems1.Add(createSomeSystems());

        return new Feature("Nested Systems")
            .Add(systems1);
    }

    Systems createEmptySystems() {
        var systems1 = new Feature("Empty 1");
        var systems2 = new Feature("Empty 2");
        var systems3 = new Feature("Empty 3");

        systems1.Add(systems2);
        systems2.Add(systems3);

        return new Feature("Empty Systems")
            .Add(systems1);
    }

    Systems createSomeSystems() {
        return new Feature("Some Systems")
            .Add(_pool.CreateSystem<SlowInitializeSystem>())
            .Add(_pool.CreateSystem<SlowInitializeExecuteSystem>())
            .Add(_pool.CreateSystem<FastSystem>())
            .Add(_pool.CreateSystem<SlowSystem>())
            .Add(_pool.CreateSystem<RandomDurationSystem>())
            .Add(_pool.CreateSystem<AReactiveSystem>())
            .Add(_pool.CreateSystem<RandomValueSystem>())
            .Add(_pool.CreateSystem<ProcessRandomValueSystem>());
    }
}


text:
package cachemode

// Setting represents a cache mode setting
type Setting int

// Possible cache modes
const (
	Unset       = iota // cache mode has not been set
	On                 // cache everything
	Development        // cache everything, except Amber, Lua, GCSS and Markdown
	Production         // cache everything, except Amber and Lua
	Images             // cache images (png, jpg, gif, svg)
	Small              // only cache small files (<=64KB) // 64 * 1024
	Off                // cache nothing
	Default     = On
)

var (
	// Names is a map of cache mode setting string representations
	Names = map[Setting]string{
		Unset:       "unset",
		On:          "On",
		Development: "Development",
		Production:  "Production",
		Images:      "Images",
		Small:       "Small",
		Off:         "Off",
	}
)

// New creates a CacheModeSetting based on a variety of string options, like "on" and "off".
func New(mode string) Setting {
	switch mode {
	case "everything", "all", "on", "1", "enabled", "yes", "enable": // Cache everything.
		return On
	case "production", "prod": // Cache everything, except: Amber and Lua.
		return Production
	case "images", "image": // Cache images (png, jpg, gif, svg).
		return Images
	case "small", "64k", "64KB": // Cache only small files (<=64KB), but not Amber and Lua
		return Small
	case "off", "disabled", "0", "no", "disable": // Disable caching entirely.
		return Off
	case "dev", "default", "unset": // Cache everything, except: Amber, Lua, GCSS and Markdown.
		fallthrough
	default:
		return Default
	}
}

// String returns the name of the cache mode setting, if set
func (cms Setting) String() string {
	for k, v := range Names {
		if k == cms {
			return v
		}
	}
	// Could not find the name
	return Names[Unset]
}


text:
.class public abstract Lcom/google/android/gms/internal/bx;
.super Lcom/google/android/gms/internal/cm;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/google/android/gms/internal/bx$b;,
        Lcom/google/android/gms/internal/bx$a;
    }
.end annotation

# instance fields
.field private final fw:Lcom/google/android/gms/internal/bz;

.field private final hn:Lcom/google/android/gms/internal/bw$a;

# direct methods
.method public constructor <init>(Lcom/google/android/gms/internal/bz;Lcom/google/android/gms/internal/bw$a;)V
    .locals 0

    invoke-direct {p0}, Lcom/google/android/gms/internal/cm;-><init>()V

    iput-object p1, p0, Lcom/google/android/gms/internal/bx;->fw:Lcom/google/android/gms/internal/bz;

    iput-object p2, p0, Lcom/google/android/gms/internal/bx;->hn:Lcom/google/android/gms/internal/bw$a;

    return-void
.end method

.method private static a(Lcom/google/android/gms/internal/cd;Lcom/google/android/gms/internal/bz;)Lcom/google/android/gms/internal/cb;
    .locals 1

    :try_start_0
    invoke-interface {p0, p1}, Lcom/google/android/gms/internal/cd;->b(Lcom/google/android/gms/internal/bz;)Lcom/google/android/gms/internal/cb;

    move-result-object v0
    :try_end_0
    .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0

    return-object v0

    :catch_0
    move-exception p0

    const-string v0, "Could not fetch ad response from ad request service."

    invoke-static {v0, p0}, Lcom/google/android/gms/internal/ct;->b(Ljava/lang/String;Ljava/lang/Throwable;)V

    const/4 v0, 0x0

    return-object v0
.end method

# virtual methods
.method public final ai()V
    .locals 2

    :try_start_0
    invoke-virtual {p0}, Lcom/google/android/gms/internal/bx;->al()Lcom/google/android/gms/internal/cd;

    move-result-object v0

    move-object v1, v0

    if-nez v0, :cond_0

    new-instance v1, Lcom/google/android/gms/internal/cb;

    const/4 v0, 0x0

    invoke-direct {v1, v0}, Lcom/google/android/gms/internal/cb;-><init>(I)V

    goto :goto_0

    :cond_0
    iget-object v0, p0, Lcom/google/android/gms/internal/bx;->fw:Lcom/google/android/gms/internal/bz;

    invoke-static {v1, v0}, Lcom/google/android/gms/internal/bx;->a(Lcom/google/android/gms/internal/cd;Lcom/google/android/gms/internal/bz;)Lcom/google/android/gms/internal/cb;

    move-result-object v0

    move-object v1, v0

    if-nez v0, :cond_1

    new-instance v1, Lcom/google/android/gms/internal/cb;

    const/4 v0, 0x0

    invoke-direct {v1, v0}, Lcom/google/android/gms/internal/cb;-><init>(I)V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    :cond_1
    :goto_0
    invoke-virtual {p0}, Lcom/google/android/gms/internal/bx;->ak()V

    goto :goto_1

    :catchall_0
    move-exception v1

    invoke-virtual {p0}, Lcom/google/android/gms/internal/bx;->ak()V

    throw v1

    :goto_1
    iget-object v0, p0, Lcom/google/android/gms/internal/bx;->hn:Lcom/google/android/gms/internal/bw$a;

    invoke-interface {v0, v1}, Lcom/google/android/gms/internal/bw$a;->a(Lcom/google/android/gms/internal/cb;)V

    return-void
.end method

.method public abstract ak()V
.end method

.method public abstract al()Lcom/google/android/gms/internal/cd;
.end method

.method public final onStop()V
    .locals 0

    invoke-virtual {p0}, Lcom/google/android/gms/internal/bx;->ak()V

    return-void
.end method


text:
Kwf.onElementReady('.kwcUserLoginFacebook', function(el, config){
    if (!Ext.get('fb-root')) {
        el.createChild({id: 'fb-root'});
    }
    Kwf.Facebook.onReady(function(){
        el.child('.kwfFbLoginButton').on('click', function(ev){
            loginInit();
        }, this);
    }, this);
    var loginInit = function() {
        FB.getLoginStatus(function(response){
            if (response.status === 'connected') {
                Ext.Ajax.request({
                    params: {
                        accessToken: response.authResponse.accessToken
                    },
                    url: config.controllerUrl + '/json-auth',
                    success: function(response, options, r) {
                        el.child('.success').show();
                        Kwf.callOnContentReady(el.dom, {newRender: false});
                    },
                    scope: this
                });
        } else {
            FB.login(function(response) {
                // handle the response
                loginInit();
            }, {scope: 'email'});
        }
    });
    }
});


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cloudikka.Swapi.Configuration {
    internal class DefaultSwapiConfiguration : SwapiConfiguration {
        private static string baseAddress = "http://swapi.co/api/";

        internal static SwapiConfiguration Create() {
            var uri = new Uri(baseAddress);
            var config = new DefaultSwapiConfiguration(uri);
            return config;
        }

        internal DefaultSwapiConfiguration(Uri baseAddress)
            : base(baseAddress){
        }
    }
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: >
    A TypeError exception is thrown if the this value is not an object for
    which the value of the internal [[Class]] property is "RegExp"
es5id: 15.10.6.3_A2_T3
description: The tested object is function object
---*/

__instance.test = RegExp.prototype.test;

//CHECK#1
try {
  __instance.test("message to investigate");
  $ERROR('#1.1: __instance.test = RegExp.prototype.test; __instance.test("message to investigate"); function __instance(){}');
} catch (e) {
  if ((e instanceof TypeError) !== true) {
    $ERROR('#1.2: __instance.test = RegExp.prototype.test; __instance.test("message to investigate"); function __instance(){}. Actual: ' + (e));
  }
}

function __instance(){};


text:
import { dia } from 'jointjs';
import * as _joint from 'jointjs';

const joint: any = _joint;

export class ViewUtils {

  static fitLabel(paper: dia.Paper, node: dia.Element, labelPath: string, paddingLeft: number, paddingRight?: number): void {
    if (isNaN(paddingRight)) {
      paddingRight = paddingLeft;
    }
    const label: string = node.attr(`${labelPath}/text`);
    const view = paper.findViewByModel(node);
    if (view && label) {
      const labelElement = view.findBySelector(labelPath)[0];
      if (!labelElement) {
        return;
      }
      let offset = 0;
      if (node.attr('.type-icon')) {
        const label2View = view.findBySelector('.type-icon')[0];
        if (label2View) {
          const box = joint.V(label2View).bbox(false, paper.viewport);
          let padding = 0;
          if (node.attr('.type-icon/ref')) {
            const refView = view.findBySelector(node.attr('.type-icon/ref'))[0];
            if (refView) {
              padding = box.x - joint.V(refView).bbox(false, paper.viewport).x;
            }
          } else {
            padding = box.x - view.getBBox().x;
          }
          offset = padding + box.width;
        }
      } else if (node.attr('.label2/text')) {
        const label2View = view.findBySelector('.label2')[0];
        if (label2View) {
          const box = joint.V(label2View).bbox(false, paper.viewport);
          let padding = 0;
          if (node.attr('.label2/ref')) {
            const refView = view.findBySelector(node.attr('.label2/ref'))[0];
            if (refView) {
              padding = box.x - joint.V(refView).bbox(false, paper.viewport).x;
            }
          } else {
            padding = box.x - view.getBBox().x;
          }
          offset = padding + box.width;
        }
      }

      let boundingBox = view.getBBox();
      if (node.attr(`${labelPath}/ref`)) {
        const refElement = view.findBySelector(node.attr(`${labelPath}/ref`))[0];
        if (refElement) {
          boundingBox = joint.V(refElement).bbox(false, paper.viewport);
        }
      }

      const threshold = boundingBox.width - paddingLeft - paddingRight - offset;

      let width = joint.V(labelElement).bbox(false, paper.viewport).width;

      if (width > threshold) {
        const styles = getComputedStyle(labelElement);
        const stylesObj: {} = {};
        for (let i = 0; i < styles.length; i++) {
          const property = styles.item(i);
          if (!property.startsWith('-')) {
            stylesObj[property] = styles.getPropertyValue(property);
          }
        }

        const svgDocument = joint.V('svg').node;
        const textSpan = joint.V('tspan').node;
        const textElement = joint.V('text').attr(stylesObj).append(textSpan).node;
        const textNode = document.createTextNode(label);

        // Prevent flickering
        textElement.style.opacity = 0;
        // Prevent FF from throwing an uncaught exception when `getBBox()`
        // called on element that is not in the render tree (is not measurable).
        // <tspan>.getComputedTextLength() returns always 0 in this case.
        // Note that the `textElement` resp. `textSpan` can become hidden
        // when it's appended to the DOM and a `display: none` CSS stylesheet
        // rule gets applied.
        textElement.style.display = 'block';
        textSpan.style.display = 'block';

        textSpan.appendChild(textNode);
        svgDocument.appendChild(textElement);

        document.body.appendChild(svgDocument);

        try {
          width = textSpan.getComputedTextLength();
          for (let i = 1; i < label.length && width > threshold; i++) {
            textNode.data = label.substr(0, label.length - i) + '\u2026';
            width = textSpan.getComputedTextLength();
          }

          if (offset) {
            node.attr(`${labelPath}/refX`, Math.max((offset + paddingLeft + width / 2) / boundingBox.width, 0.5), {silent: true});
          }
          // TODO: What does this do? Replaces rendering with silent update it seems. Verify later.
          node.attr(`${labelPath}/text`, textNode.data);
        } finally {
          document.body.removeChild(svgDocument);
        }
      } else {
        node.attr(`${labelPath}/refX`, Math.max((offset + paddingLeft + width / 2) / boundingBox.width, 0.5));
      }
    }
  }

  static fitLabelWithFixedLocation(paper: dia.Paper, node: dia.Element, labelPath: string, paddingRight?: number): void {
    if (isNaN(paddingRight)) {
      paddingRight = 0;
    }
    const label: string = node.attr(`${labelPath}/text`);
    const view = paper.findViewByModel(node);
    if (view && label) {
      const labelElement = view.findBySelector(labelPath)[0];
      if (!labelElement) {
        return;
      }

      let boundingBox = view.getBBox();
      if (node.attr(`${labelPath}/ref`)) {
        const refElement = view.findBySelector(node.attr(`${labelPath}/ref`))[0];
        if (refElement) {
          boundingBox = joint.V(refElement).bbox(false, paper.viewport);
        }
      }

      const labelInitialBox = joint.V(labelElement).bbox(false, paper.viewport);

      const locationX = labelInitialBox.x - boundingBox.x;

      const threshold = boundingBox.width - paddingRight - locationX;

      const width = labelInitialBox.width;

      if (width > threshold) {
        const styles = getComputedStyle(labelElement);
        const stylesObj: {} = {};
        for (let i = 0; i < styles.length; i++) {
          const property = styles.item(i);
          if (!property.startsWith('-')) {
            stylesObj[property] = styles.getPropertyValue(property);
          }
        }

        const truncatedText = ViewUtils.trucateTextWithEllipsis(label, threshold, stylesObj);
        node.attr(`${labelPath}/text`, truncatedText);
      }
    }
  }

  static fitLabelWithFixedWidth(paper: dia.Paper, node: dia.Element, labelPath: string, widthConstraint: number): void {
    if (isNaN(widthConstraint)) {
      throw new Error('Width constraint is invalid');
    }
    const label: string = node.attr(`${labelPath}/text`);
    const view = paper.findViewByModel(node);
    if (view && label) {
      const labelElement = view.findBySelector(labelPath)[0];
      if (!labelElement) {
        return;
      }

      const labelInitialBox = joint.V(labelElement).bbox(false, paper.viewport);

      const width = labelInitialBox.width;

      if (width > widthConstraint) {
        const styles = getComputedStyle(labelElement);
        const stylesObj: {} = {};
        for (let i = 0; i < styles.length; i++) {
          const property = styles.item(i);
          if (!property.startsWith('-')) {
            stylesObj[property] = styles.getPropertyValue(property);
          }
        }

        const truncatedText = ViewUtils.trucateTextWithEllipsis(label, widthConstraint, stylesObj);
        node.attr(`${labelPath}/text`, truncatedText);
      }
    }
  }

  /* Use calculation below rather than joint.util.breakText. The breakText needs the height which only seems
   * to work correctly if label height * 1.1 is provided. Won't work with the exact height.
   * Furthermore, no need for multiple lines hence the algo below is faster
   */
  static trucateTextWithEllipsis(label: string, widthConstraint: number, stylesObj: any): string {
    const svgDocument = joint.V('svg').node;
    const textSpan = joint.V('tspan').node;
    const textElement = joint.V('text').attr(stylesObj).append(textSpan).node;
    const textNode = document.createTextNode(label);

    // Prevent flickering
    textElement.style.opacity = 0;
    // Prevent FF from throwing an uncaught exception when `getBBox()`
    // called on element that is not in the render tree (is not measurable).
    // <tspan>.getComputedTextLength() returns always 0 in this case.
    // Note that the `textElement` resp. `textSpan` can become hidden
    // when it's appended to the DOM and a `display: none` CSS stylesheet
    // rule gets applied.
    textElement.style.display = 'block';
    textSpan.style.display = 'block';

    textSpan.appendChild(textNode);
    svgDocument.appendChild(textElement);

    document.body.appendChild(svgDocument);

    try {
      let width = textSpan.getComputedTextLength();
      for (let i = 1; i < label.length && width > widthConstraint; i++) {
        textNode.data = label.substr(0, label.length - i) + '\u2026';
        width = textSpan.getComputedTextLength();
      }

      return textNode.data;
    } finally {
      document.body.removeChild(svgDocument);
    }
  }
}


text:
class ProgressReporter (object):
    """description of class"""

    def __init__(self):
        self.progress = 0.0
        self.message = "idling..."

    def Report(self, event_args):
        self.progress += event_args.PercentWorkRepresented
        self.message = event_args.Message
        print "Increment:", event_args.PercentWorkRepresented
        print "Message:", event_args.Message


text:
using SignedMessages.CryptoHelpers;
using SignedMessages.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace SignedMessages.Controllers
{
    public class HomeController : Controller
    {
        string messageToValidate = "Ask Ronni for money, he wants to give everyone a million dollars!";
        public ActionResult Index()
        {
            //var keyinfo = CryptoHelpers.CryptoHelper.RSA(); already used this to generate a random private and public key
            //----------------
            var publicKeyInfo = System.IO.File.Open(Server.MapPath(@"~\PublicKey.xml"), FileMode.Open);
            var privateKeyInfo = System.IO.File.Open(Server.MapPath(@"~\PrivateKey.xml"), FileMode.Open);
            StreamReader publicKeyStream = new StreamReader(publicKeyInfo);
            StreamReader privateKeyStream = new StreamReader(privateKeyInfo);

            var privateCryptoParams = CryptoHelpers.CryptoHelper.GetCSPProviderFromXMLString(privateKeyStream.ReadToEnd());
            var publicCryptoParams = CryptoHelpers.CryptoHelper.GetCSPProviderFromXMLString(publicKeyStream.ReadToEnd());
            publicKeyInfo.Close();
            privateKeyInfo.Close();

            var publicKey = BouncyCastleHelpers.ExportPublicKey(publicCryptoParams);
            var privateKey = BouncyCastleHelpers.ExportPrivateKey(privateCryptoParams);

            var mac = CryptoHelper.CreateHMAC(messageToValidate, Encoding.Unicode.GetBytes(privateKey));

            ViewBag.MAC = mac;
            return View(new AssymetricKeyInformation { PublicKey = publicKey });
        }
        public ActionResult ValidateMACMessage()
        {
            return View();
        }
        [HttpPost]
        public ActionResult ValidateMACMessage(MACViewModel mvm)
        {
            bool isMacValid = CryptoHelper.ValidateHMAC(mvm.MAC, mvm.Message, Encoding.Unicode.GetBytes(mvm.PublicKey));
            ViewBag.Valid = isMacValid;
            return View();
        }
    }
}


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

namespace Amazon.Lambda.CloudWatchEvents.ECSEvents
{
    using System.Collections.Generic;

    ///
    /// Describes the resources available for a container instance.
    /// https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_Resource.html
    ///
    public class Resource
    {
        ///
        /// When the DoubleValue type is set, the value of the resource must be a
        /// double precision floating-point type.
        ///
        public double DoubleValue { get; set; }

        ///
        /// When the IntegerValue type is set, the value of the resource must be
        /// an integer.
        ///
        public int IntegerValue { get; set; }

        ///
        /// When the LongValue type is set, the value of the resource must be an
        /// extended precision floating-point type.
        ///
        public long LongValue { get; set; }

        ///
        /// The name of the resource, such as CPU, MEMORY, PORTS, PORTS_UDP, or a user-defined resource.
        ///
        public string Name { get; set; }

        ///
        /// The type of the resource, such as INTEGER, DOUBLE, LONG, or STRINGSET.
        ///
        public string Type { get; set; }

        ///
        /// When the stringSetValue type is set, the value of the resource must be a string type.
        ///
        public List<string> StringSetValue { get; set; }
    }
}


text:
package gdv.xport.deprecated.satz.feld.sparte10.wagnisart13;

import gdv.xport.annotation.FeldInfo;
import gdv.xport.annotation.FelderInfo;
import gdv.xport.feld.*;
import gdv.xport.satz.feld.common.Feld1bis7;

/**
 * Diese Enum-Klasse repraesentiert die Felder fuer Satzart 220, Sparte 10
 * (Leben - Kapitallebens-/Risikovers. = Wagnisart 1 u. 3).
 *
 * @author ralfklemmer
 * @since 17.01.2013
 * @deprecated bitte gleichnamige Enum aus gdv.xport.satz.feld.sparte10.wagnisart13
 * 			   benutzen
 */
@Deprecated
public enum Feld220Wagnis13ZukSummenaenderungen {

    // /// Teildatensatz 1 /////////////////////////////////////////////////

    /** Feld 1 - 7 sind fuer jeden (Teil-)Datensatz identisch. */
    @FelderInfo(
            sparte = 10,
            teildatensatz = 1,
            type = Feld1bis7.class)
    INTRO1,

    /**
     * Lfd. Nummer der versicherten Person (VP).
     * lfd. Nr., die im VU geführt wird
     */
    @FeldInfo(teildatensatz = 1, nr = 8, type = AlphaNumFeld.class, anzahlBytes = 17, byteAdresse = 43)
    LFD_NUMMER_VP_PERSONENGRUPPE,

    /**
     * Wagnisart.
     * 1 = Kapitallebensversicherung 3 = Risikoversicherung
     */
    @FeldInfo(teildatensatz = 1, nr = 9, type = Zeichen.class, anzahlBytes = 1, byteAdresse = 60)
    WAGNISART,

    /**
     * Laufende Nummer zur Wagnisart.
     */
    @FeldInfo(teildatensatz = 1, nr = 10, type = Zeichen.class, anzahlBytes = 1, byteAdresse = 61)
    LFD_NUMMER_ZUR_WAGNISART,

    /**
     * Laufende Nummer der Satzart.
     * Lfd. Nummer der Satzart 0220.010.2/6 innerhalb der gleichen Folgenummer
     * (z. B. n-fache hintereinanderfolgende Lieferung der Satzart 0220.010.2/6,
     * wenn mehrere Bezugsrechte vorhanden)
     */
    @FeldInfo(
            teildatensatz = 1,
            nr = 11,
            type = AlphaNumFeld.class,
            anzahlBytes = 2,
            byteAdresse = 62)
    LFD_NUMMER_SATZART,

    /**
     * Anfängliche Todesfall VS in Währungseinheiten.
     * Anfängliche bzw. erste Todesfalleistung
     * (9,0 Stellen)
     */
    @FeldInfo(teildatensatz = 1, nr = 12, type = Betrag.class, anzahlBytes = 9, byteAdresse = 64)
    ANFAENGLICHE_TODESFALL_VS_IN_WAEHRUNGSEINHEITEN,

    /**
     * Änderung der Todesfallleistung.
     * 0 = keine Änderung bzw. nur eine Todesfallleistung
     * 1 = Erhöhung der Todesfallleistung
     * 2 = Reduzierung der Todesfallleistung
     */
    @FeldInfo(teildatensatz = 1, nr = 13, type = Zeichen.class, anzahlBytes = 1, byteAdresse = 73)
    AENDERUNG_DER_TODESFALLLEISTUNG,

    /**
     * Abstand der Todesfalländerungstermine.
     * in Monaten bei periodischen Änderungsterminen
     * in Monaten bei periodischen Auszahlungen
     * 000 = keine Änderungen/Auszahlungen
     * 999 = unregelmäßige Änderungen/Auszahlungen
     */
    @FeldInfo(teildatensatz = 1, nr = 14, type = NumFeld.class, anzahlBytes = 3, byteAdresse = 74)
    ABSTAND_DER_TODESFALLAENDERUNGSTERMINE,

    /**
     * Todesfalländerungs-Prozentsatz.
     * Konstanter Prozentsatz der Steigerung bzw. Reduzierung der Todesfalleistung
     * (3,2 Stellen)
     */
    @FeldInfo(teildatensatz = 1, nr = 15, type = NumFeld.class, nachkommaStellen = 2, anzahlBytes = 5, byteAdresse = 77)
    TODESFALLAENDERUNGS_PROZENTSATZ,

    /**
     * Absolute Todesfalländerungssumme in Währungseinheiten.
     * Absolute Summe der Steigerung bzw. Reduzierung der Todesfalleistung
     * (9,0 Stellen)
     */
    @FeldInfo(teildatensatz = 1, nr = 16, type = NumFeld.class, anzahlBytes = 9, byteAdresse = 82)
    ABSOLUTE_TODESFALLAENDERUNGSSUMME_VS_IN_WAEHRUNGSEINHEITEN,

    /**
     * Nächste Todesfall VS in Währungseinheiten.
     * Todesfalleistung ab dem nächsten Änderungstermin
     * (9,0 Stellen)
     */
    @FeldInfo(teildatensatz = 1, nr = 17, type = Betrag.class, anzahlBytes = 9, byteAdresse = 91)
    NAECHSTE_TODESFALL_VS_IN_WAEHRUNGSEINHEITEN,

    /**
     * Beginndatum der nächsten Todesfall VS.
     * Sollten Tag und/oder Monat nicht vorhanden sein, muss "00" geschlüsselt werden Datum der nächsten
     * Todesfalländerung
     * Tag/Monat/Jahr (TTMMJJJJ)
     */
    @FeldInfo(teildatensatz = 1, nr = 18, type = Datum.class, anzahlBytes = 8, byteAdresse = 100)
    BEGINNDAT_DER_NAECHSTEN_TODESFALL_VS,

    /**
     * Anfängliche Erlebensfall VS in Währungseinheiten.
     * Anfängliche bzw. erste Erlebensfall VS
     */
    @FeldInfo(teildatensatz = 1, nr = 19, type = Betrag.class, anzahlBytes = 9, byteAdresse = 108)
    ANFAENGLICHE_ERLEBENSFALL_VS_IN_WAEHRUNGSEINHEITEN,

    /**
     * Änderung der Erlebensfall VS.
     * 0 = keine Änderung bzw. nur eine Erlebensfall VS
     * 1 = Erhöhung der Erlebensfall VS
     * 2 = Reduzierung der Erlebensfall VS
     */
    @FeldInfo(teildatensatz = 1, nr = 20, type = Zeichen.class, anzahlBytes = 1, byteAdresse = 117)
    AENDERUNG_DER_ERLEBENSFALL_VS,

    /**
     * Abstand der Erlebensfall VS-änderungstermine.
     * in Monaten bei periodischen Änderungsterminen
     * in Monaten bei periodischen Auszahlungen
     * 000 = keine Änderungen/Auszahlungen
     * 999 = unregelmäßige Änderungen/Auszahlungen
     */
    @FeldInfo(teildatensatz = 1, nr = 21, type = NumFeld.class, anzahlBytes = 3, byteAdresse = 118)
    ABSTAND_DER_ERLEBENSFAL_VS_AENDERUNGSTERMINE,

    /**
     * Erlebensfall VS-Änderungs-Prozentsatz.
     * Konstanter Prozentsatz der Steigerung bzw. Reduzierung der Erlebensfall VS
     * (3,2 Stellen)
     */
    @FeldInfo(teildatensatz = 1, nr = 22, type = NumFeld.class, nachkommaStellen = 2, anzahlBytes = 5, byteAdresse = 121)
    ERLEBENSFALL_VS_AENDERUNGS_PROZENTSATZ,

    /**
     * Absolute Erlebensfall VS in Währungseinheiten.
     * Absolute Summe der Steigerung bzw. Reduzierung der Erlebensfall VS
     */
    @FeldInfo(teildatensatz = 1, nr = 23, type = Betrag.class, anzahlBytes = 9, byteAdresse = 126)
    ABSOLUTE_ERLEBENSFALL_VS_IN_WAEHRUNGSEINHEITEN,

    /**
     * Nächste Erlebensfall VS in Währungseinheiten.
     * Erlebensfall VS ab dem nächsten Änderungstermin
     */
    @FeldInfo(teildatensatz = 1, nr = 24, type = Betrag.class, anzahlBytes = 9, byteAdresse = 135)
    NAECHSTE_ERLEBENSFALL_VS_IN_WAEHRUNGSEINHEITEN,

    /**
     * Beginndatum der nächsten Erlebensfall VS.
     * Sollten Tag und/oder Monat nicht vorhanden sein, muss "00" geschlüsselt werden Datum der nächsten Erlebensfall
     * VS
     * Tag/Monat/Jahr (TTMMJJJJ)
     */
    @FeldInfo(teildatensatz = 1, nr = 25, type = Datum.class, anzahlBytes = 8, byteAdresse = 144)
    BEGINNDAT_DER_NAECHSTEN_ERLEBENSFALL_VS,

    /**
     * Leerstellen.
     */
    @FeldInfo(teildatensatz = 1, nr = 26, type = AlphaNumFeld.class, anzahlBytes = 104, byteAdresse = 152)
    LEERSTELLEN
}


text:
from test import unittest
from test import run_only
from mock import patch
from mock import ANY

import configobj

from diamond.handler.stats_d import StatsdHandler
from diamond.metric import Metric
try:
    import statsd
    statsd  # Pyflakes
except ImportError:
    pass

def run_only_if_statsd_is_available(func):
    try:
        import statsd
        statsd  # workaround for pyflakes issue #13
    except ImportError:
        statsd = None
    pred = lambda: statsd is not None
    return run_only(func, pred)

class TestStatsdHandler(unittest.TestCase):

    @run_only_if_statsd_is_available
    @patch('statsd.Client')
    def test_single_gauge(self, mock_client):
        instance = mock_client.return_value
        instance._send.return_value = 1

        config = configobj.ConfigObj()
        config['host'] = 'localhost'
        config['port'] = '9999'
        config['batch'] = 1

        metric = Metric('servers.com.example.www.cpu.total.idle',
                        123, raw_value=123, timestamp=1234567,
                        host='will-be-ignored', metric_type='GAUGE')

        expected_data = {
            'servers.com.example.www.cpu.total.idle': '123|g'
        }

        handler = StatsdHandler(config)
        handler.process(metric)
        mock_client._send.assert_called_with(ANY, expected_data)

    @run_only_if_statsd_is_available
    @patch('statsd.Client')
    def test_single_counter(self, mock_client):
        instance = mock_client.return_value
        instance._send.return_value = 1

        config = configobj.ConfigObj()
        config['host'] = 'localhost'
        config['port'] = '9999'
        config['batch'] = 1

        metric = Metric('servers.com.example.www.cpu.total.idle',
                        5, raw_value=123, timestamp=1234567,
                        host='will-be-ignored', metric_type='COUNTER')

        expected_data = {
            'servers.com.example.www.cpu.total.idle': '123|c'
        }

        handler = StatsdHandler(config)
        handler.process(metric)
        mock_client._send.assert_called_with(ANY, expected_data)

    @run_only_if_statsd_is_available
    @patch('statsd.Client')
    def test_multiple_counter(self, mock_client):
        instance = mock_client.return_value
        instance._send.return_value = 1

        config = configobj.ConfigObj()
        config['host'] = 'localhost'
        config['port'] = '9999'
        config['batch'] = 1

        metric1 = Metric('servers.com.example.www.cpu.total.idle',
                         5, raw_value=123, timestamp=1234567,
                         host='will-be-ignored', metric_type='COUNTER')

        metric2 = Metric('servers.com.example.www.cpu.total.idle',
                         7, raw_value=128, timestamp=1234567,
                         host='will-be-ignored', metric_type='COUNTER')

        expected_data1 = {
            'servers.com.example.www.cpu.total.idle': '123|c'
        }

        expected_data2 = {
            'servers.com.example.www.cpu.total.idle': '5|c'
        }

        handler = StatsdHandler(config)
        handler.process(metric1)
        mock_client._send.assert_called_with(ANY, expected_data1)

        handler.process(metric2)
        mock_client._send.assert_called_with(ANY, expected_data2)


text:
<Record>
<Term>Lamvudine- Zidovudine</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<SemanticType>Organic Chemical</SemanticType>
<Synonym>Efavirenz;lamvudine;zidovudine</Synonym>
<Synonym>Lamvudine; zidovudine</Synonym>
<Synonym>Efavirenz-lamvudine-zidovudine</Synonym>
<Synonym>Lamvudine- Zidovudine</Synonym>
<Source>FDA Registry</Source>
</Record>


text:
dialog --clear --stdout \
--title "Update HstWB Installer" \
--yesno "Do you want to update HstWB Installer to latest version?" 0 0

# exit, if no is selected
if [ $? -ne 0 ]; then
	exit 1
fi

# git pull
clear
echo "Updating HstWB Installer to latest version..."
git pull

# show reset and update, if update failed
if [ $? -ne 0 ]; then
	# pause
	read -p "Press enter to continue"

	# show reset and update dialog
	dialog --clear --stdout \
	--title "Reset and update HstWB Installer" \
	--yesno "Update failed possibly due to local changes. Do you want to reset any changes and update HstWB Installer to latest version?" 0 0

	# exit, if no is selected
	if [ $? -ne 0 ]; then
		exit 1
	fi

	# git reset, clean and pull
	clear
	echo "Resetting and updating HstWB Installer to latest version..."
	git reset --hard
	git clean -xfd
	git pull
fi

# pause
read -p "Press enter to continue"


text:
(env | grep -q "^NEWRELIC_LICENSE_KEY=") && (env | grep -q "^NEWRELIC_APP_NAME=")
if [ $? -eq "1" ]; then
	gunicorn --threads=4 -b 0.0.0.0:5000 app:wsgi
else
	/usr/local/bin/newrelic-admin generate-config ${NEWRELIC_LICENSE_KEY} /root/newrelic.ini
	sed -i -re "s.app_name = Python Application.app_name = ${NEWRELIC_APP_NAME}.g" /root/newrelic.ini
        kill -9 1
	/usr/local/bin/newrelic-admin run-program gunicorn --threads=4 -b 0.0.0.0:5000 app:wsgi
fi


text:
const cors = require('cors-anywhere')
const path = require('path')

cors.createServer({
  helpFile: path.join(__dirname, 'help.txt'),
  removeHeaders: [
    'cookie',
    'cookie2'
  ]
}).listen(process.env.PORT || 8080)


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

<meta name="GENERATOR" content="PasDoc 0.9.0">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>synacrypt</title>
<link rel="StyleSheet" type="text/css" href="pasdoc.css">

Unit synacrypt

Description	uses	Classes, Interfaces, Objects and Records	Functions and Procedures	Types	Constants	Variables

Description

Encryption support

Implemented are DES and 3DES encryption/decryption by ECB, CBC, CFB-8bit, CFB-block, OFB and CTR methods.

uses

SysUtils

Classes

synautil

synafpc

Overview

Classes, Interfaces, Objects and Records

Name
Description

Class TSynaBlockCipher
Implementation of common routines block ciphers (dafault size is 64-bits)

Class TSynaCustomDes
Implementation of common routines for DES encryption

Class TSynaDes
Implementation of DES encryption

Class TSyna3Des
Implementation of 3DES encryption

Class TSynaAes
Implementation of AES encryption

Functions and Procedures

function TestDes: boolean;

function Test3Des: boolean;

function TestAes: boolean;

Types

TDesKeyData = array[0..31] of integer;

Constants

BC = 4;

MAXROUNDS = 14;

Description

Functions and Procedures

function TestDes: boolean;

Call internal test of all DES encryptions. Returns True if all is OK.

function Test3Des: boolean;

Call internal test of all 3DES encryptions. Returns True if all is OK.

function TestAes: boolean;

Call internal test of all AES encryptions. Returns True if all is OK.

Types

TDesKeyData = array[0..31] of integer;

Datatype for holding one DES key data

This data type is used internally.

Constants

BC = 4;

MAXROUNDS = 14;

Generated by PasDoc 0.9.0 on 2012-04-23 21:38:52


text:
/* *****************************************************************************
 *
 * Name:    xsession.h
 * Author:  Gabriel Gonzalez
 * Email:   gabeg@bu.edu
 * License: The MIT License (MIT)
 *
 * Description: Display username and password fields for ELM.
 *
 * Notes: None.
 *
 * *****************************************************************************
 */

/* Header guard */
#ifndef ELM_XSESSION_H
#define ELM_XSESSION_H

/* Includes */
#include "elmapp.h"
#include "elmgtk.h"
#include "elmsession.h"
#include "elmstd.h"
#include "elmstr.h"

/* Public functions */
GtkWidget * new_xsession_widget(void);
GtkWidget * get_xsession_button_widget(void);
GtkWidget * get_xsession_menu_widget(void);
void        set_xsession_info(GtkWidget *widget, gpointer data);

#endif /* ELM_XSESSION_H */


text:
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;

namespace TweetLib.Utils.Collections {
	/// <summary>
	/// A <see cref="Dictionary{TKey,TValue}"/> with nested keys.
	/// </summary>
	/// <typeparam name="K1">The type of the outer key.</typeparam>
	/// <typeparam name="K2">The type of the inner key.</typeparam>
	/// <typeparam name="V">The type of the values.</typeparam>
	[SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global")]
	[SuppressMessage("ReSharper", "UnusedMember.Global")]
	public sealed class TwoKeyDictionary<K1, K2, V> where K1 : notnull where K2 : notnull {
		private readonly Dictionary<K1, Dictionary<K2, V>> dict;
		private readonly int innerCapacity;

		/// <summary>
		/// Initializes a new <see cref="TwoKeyDictionary{K1,K2,V}"/> with the default initial capacity.
		/// </summary>
		public TwoKeyDictionary() : this(16, 16) {}

		/// <summary>
		/// Initializes a new <see cref="TwoKeyDictionary{K1,K2,V}"/> with the provided initial capacity.
		/// </summary>
		/// <param name="outerCapacity">The initial number of outer keys the dictionary can contain.</param>
		/// <param name="innerCapacity">The initial number of inner keys every outer key in the dictionary can contain.</param>
		public TwoKeyDictionary(int outerCapacity, int innerCapacity) {
			this.dict = new Dictionary<K1, Dictionary<K2, V>>(outerCapacity);
			this.innerCapacity = innerCapacity;
		}

		/// <summary>
		/// Gets or sets the value associated with the two keys.
		/// A get operation throws if either key is not present in the dictionary.
		/// A set operation creates both keys.
		/// </summary>
		public V this[K1 outerKey, K2 innerKey] {
			get {
				return dict[outerKey][innerKey];
			}

			set {
				if (!dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict)) {
					dict.Add(outerKey, innerDict = new Dictionary<K2, V>(innerCapacity));
				}

				innerDict[innerKey] = value;
			}
		}

		/// <summary>
		/// Enumerates all values in the dictionary.
		/// </summary>
		public IEnumerable<V> InnerValues {
			get {
				foreach (Dictionary<K2, V> innerDict in dict.Values) {
					foreach (V value in innerDict.Values) {
						yield return value;
					}
				}
			}
		}

		/// <summary>
		/// Adds the specified keys and <paramref name="value"/> to the dictionary.
		/// Throws if the key pair already exists.
		/// </summary>
		public void Add(K1 outerKey, K2 innerKey, V value) {
			if (!dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict)) {
				dict.Add(outerKey, innerDict = new Dictionary<K2, V>(innerCapacity));
			}

			innerDict.Add(innerKey, value);
		}

		/// <summary>
		/// Removes all keys and values from the dictionary.
		/// </summary>
		public void Clear() {
			dict.Clear();
		}

		/// <summary>
		/// Removes all inner keys and values associated with the <paramref name="outerKey"/>, but does not remove the <paramref name="outerKey"/>.
		/// Throws if the <paramref name="outerKey"/> is not present in the dictionary.
		/// </summary>
		public void Clear(K1 outerKey) {
			dict[outerKey].Clear();
		}

		/// <summary>
		/// Determines whether the dictionary contains the <paramref name="outerKey"/>.
		/// </summary>
		public bool Contains(K1 outerKey) {
			return dict.ContainsKey(outerKey);
		}

		/// <summary>
		/// Determines whether the dictionary contains the key pair.
		/// </summary>
		public bool Contains(K1 outerKey, K2 innerKey) {
			return dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict) && innerDict.ContainsKey(innerKey);
		}

		/// <summary>
		/// Returns the number of values in the dictionary.
		/// </summary>
		public int Count() {
			return dict.Values.Sum(static d => d.Count);
		}

		/// <summary>
		/// Returns the number of values that belong to the <paramref name="outerKey"/> in the dictionary.
		/// Throws if the <paramref name="outerKey"/> is not present in the dictionary.
		/// </summary>
		public int Count(K1 outerKey) {
			return dict[outerKey].Count;
		}

		/// <summary>
		/// Gets the value associated with the key pair.
		/// Returns true if the key pair was present.
		/// </summary>
		public bool TryGetValue(K1 outerKey, K2 innerKey, [MaybeNullWhen(false)] out V value) {
			if (dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict)) {
				return innerDict.TryGetValue(innerKey, out value);
			}
			else {
				value = default!;
				return false;
			}
		}

		/// <summary>
		/// Removes all inner keys and values associated with the <paramref name="outerKey"/>, including the <paramref name="outerKey"/> itself.
		/// Returns true if the <paramref name="outerKey"/> was present.
		/// </summary>
		public bool Remove(K1 outerKey) {
			return dict.Remove(outerKey);
		}

		/// <summary>
		/// Removes the value associated with the key pair.
		/// Returns true if the key pair was present.
		/// </summary>
		public bool Remove(K1 outerKey, K2 innerKey) {
			if (dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict) && innerDict.Remove(innerKey)) {
				if (innerDict.Count == 0) {
					dict.Remove(outerKey);
				}

				return true;
			}

			return false;
		}
	}
}


text:
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Input.Events;
using osu.Game.Configuration;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Overlays.Settings;
using osuTK;

namespace osu.Game.Overlays.Login
{
    public class LoginForm : FillFlowContainer
    {
        private TextBox username;
        private TextBox password;
        private ShakeContainer shakeSignIn;

        [Resolved(CanBeNull = true)]
        private IAPIProvider api { get; set; }

        public Action RequestHide;

        private void performLogin()
        {
            if (!string.IsNullOrEmpty(username.Text) && !string.IsNullOrEmpty(password.Text))
                api?.Login(username.Text, password.Text);
            else
                shakeSignIn.Shake();
        }

        [BackgroundDependencyLoader(permitNulls: true)]
        private void load(OsuConfigManager config, AccountCreationOverlay accountCreation)
        {
            Direction = FillDirection.Vertical;
            Spacing = new Vector2(0, 5);
            AutoSizeAxes = Axes.Y;
            RelativeSizeAxes = Axes.X;

            ErrorTextFlowContainer errorText;

            Children = new Drawable[]
            {
                username = new OsuTextBox
                {
                    PlaceholderText = "username",
                    RelativeSizeAxes = Axes.X,
                    Text = api?.ProvidedUsername ?? string.Empty,
                    TabbableContentContainer = this
                },
                password = new OsuPasswordTextBox
                {
                    PlaceholderText = "password",
                    RelativeSizeAxes = Axes.X,
                    TabbableContentContainer = this,
                },
                errorText = new ErrorTextFlowContainer
                {
                    RelativeSizeAxes = Axes.X,
                    AutoSizeAxes = Axes.Y,
                },
                new SettingsCheckbox
                {
                    LabelText = "Remember username",
                    Current = config.GetBindable<bool>(OsuSetting.SaveUsername),
                },
                new SettingsCheckbox
                {
                    LabelText = "Stay signed in",
                    Current = config.GetBindable<bool>(OsuSetting.SavePassword),
                },
                new Container
                {
                    RelativeSizeAxes = Axes.X,
                    AutoSizeAxes = Axes.Y,
                    Children = new Drawable[]
                    {
                        shakeSignIn = new ShakeContainer
                        {
                            RelativeSizeAxes = Axes.X,
                            AutoSizeAxes = Axes.Y,
                            Child = new SettingsButton
                            {
                                Text = "Sign in",
                                Action = performLogin
                            },
                        }
                    }
                },
                new SettingsButton
                {
                    Text = "Register",
                    Action = () =>
                    {
                        RequestHide();
                        accountCreation.Show();
                    }
                }
            };

            password.OnCommit += (sender, newText) => performLogin();

            if (api?.LastLoginError?.Message is string error)
                errorText.AddErrors(new[] { error });
        }

        public override bool AcceptsFocus => true;

        protected override bool OnClick(ClickEvent e) => true;

        protected override void OnFocus(FocusEvent e)
        {
            Schedule(() => { GetContainingInputManager().ChangeFocus(string.IsNullOrEmpty(username.Text) ? username : password); });
        }
    }
}


text:
package com.centurylink.mdw.camel;

import java.util.Map;

import org.apache.camel.Endpoint;
import org.apache.camel.impl.DefaultComponent;

public class MdwComponent extends DefaultComponent {

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String,Object> parameters) throws Exception {
        MdwEndpoint endpoint = new MdwEndpoint(uri, remaining, this);
        endpoint.setNamespaces(namespaces);
        return endpoint;
    }

    private Map<String,String> namespaces;
    public Map<String,String> getNamespaces() { return namespaces; }
    public void setNamespaces(Map<String,String> namespaces) { this.namespaces = namespaces; }

}


text:
//-------------------------------------------------------------------------//
//
// Copyright 2018 Sascha Kaden
//
// 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.
//
//-------------------------------------------------------------------------//

#ifndef UTILLIST_HPP
#define UTILLIST_HPP

#include <memory>
#include <string>

#include <ippp/dataObj/Node.hpp>

namespace ippp {
namespace util {

bool contains(const std::string &string, const std::string &subject);
void trimWhitespaces(std::string &str);
std::string getFileName(const std::string &filePath);

/*!
*  \brief      Removes Node by reference object
*  \author     Sascha Kaden
*  \param[in]  list
*  \param[in]  pointer of Node
*  \date       2016-12-19
*/
template <unsigned int dim>
void eraseFromList(std::vector<std::shared_ptr<Node<dim>>> &list, const std::shared_ptr<Node<dim>> &node) {
    list.erase(std::remove(list.begin(), list.end(), node), list.end());
}

/*!
*  \brief      Returns the Node with the lowest cost and removes it from the list
*  \author     Sascha Kaden
*  \param[in]  list
*  \param[out] Node with lowest cost
*  \date       2016-12-19
*/
template <unsigned int dim>
std::shared_ptr<Node<dim>> removeMinFromList(std::vector<std::shared_ptr<Node<dim>>> &list) {
    double min = std::numeric_limits<double>::max();
    std::shared_ptr<Node<dim>> minNode = nullptr;
    for (size_t i = 0; i < list.size(); ++i) {
        if (list[i]->getPathCost() < min) {
            minNode = list[i];
            min = list[i]->getPathCost();
        }
    }
    if (minNode != nullptr)
        eraseFromList(list, minNode);

    return minNode;
}

/*!
*  \brief      Return true, if the list contains the passed Node
*  \author     Sascha Kaden
*  \param[in]  list
*  \param[in]  Node
*  \param[out] true, if list contains passed Node
*  \date       2016-12-19
*/
template <unsigned int dim>
bool contains(const std::vector<std::shared_ptr<Node<dim>>> &list, const std::shared_ptr<Node<dim>> &node) {
    if (std::find(list.begin(), list.end(), node) != list.end())
        return true;

    return false;
}

} /* namespace util */
} /* namespace ippp */

#endif    // UTILLIST_HPP


text:
layout: post
title:  "appydroid - The thought of Open Source"
date:   2016-01-06 18:00:00
highlight: false
author: jlelse
image: /img/1.jpg
---
I think Open Source is an essential part of keeping a project active. In addition to this I really like networks like [Medium](http://medium.com) which enables everyone to publish own content.

To keep appydroid free and open too I decided to license it under the Apache 2.0 license.

The articles as well as the page code are with this license. This means that you can reuse them but you have to mention it and if you modify anything you have to publish your modifications.

```
   Copyright 2016 Jan-Lukas Else

   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.
```

jlelse
*Founder of appydroid*


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

<title>ca.islandora.alpaca.connector.broadcast</title>
<meta name="date" content="2018-08-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

ca.islandora.alpaca.connector.broadcast

Classes

BroadcastRouter