text:
namespace site_isolation {

namespace {

using IsolatedOriginSource =
    content::ChildProcessSecurityPolicy::IsolatedOriginSource;

}  // namespace

// static
bool SiteIsolationPolicy::IsIsolationForPasswordSitesEnabled() {
  // If the user has explicitly enabled site isolation for password sites from
  // chrome://flags or from the command line, honor this regardless of policies
  // that may disable site isolation.  In particular, this means that the
  // chrome://flags switch for this feature takes precedence over any memory
  // threshold restrictions and over a switch for disabling site isolation.
  if (base::FeatureList::GetInstance()->IsFeatureOverriddenFromCommandLine(
          features::kSiteIsolationForPasswordSites.name,
          base::FeatureList::OVERRIDE_ENABLE_FEATURE)) {
    return true;
  }

  // Don't isolate anything when site isolation is turned off by the user or
  // policy. This includes things like the switches::kDisableSiteIsolation
  // command-line switch, the corresponding "Disable site isolation" entry in
  // chrome://flags, enterprise policy controlled via
  // switches::kDisableSiteIsolationForPolicy, and memory threshold checks in
  // ShouldDisableSiteIsolationDueToMemoryThreshold().
  if (!content::SiteIsolationPolicy::AreDynamicIsolatedOriginsEnabled())
    return false;

  // The feature needs to be checked last, because checking the feature
  // activates the field trial and assigns the client either to a control or an
  // experiment group - such assignment should be final.
  return base::FeatureList::IsEnabled(features::kSiteIsolationForPasswordSites);
}

// static
bool SiteIsolationPolicy::IsIsolationForOAuthSitesEnabled() {
  // If the user has explicitly enabled site isolation for OAuth sites from the
  // command line, honor this regardless of policies that may disable site
  // isolation.
  if (base::FeatureList::GetInstance()->IsFeatureOverriddenFromCommandLine(
          features::kSiteIsolationForOAuthSites.name,
          base::FeatureList::OVERRIDE_ENABLE_FEATURE)) {
    return true;
  }

  // Don't isolate anything when site isolation is turned off by the user or
  // policy. This includes things like the switches::kDisableSiteIsolation
  // command-line switch, the corresponding "Disable site isolation" entry in
  // chrome://flags, enterprise policy controlled via
  // switches::kDisableSiteIsolationForPolicy, and memory threshold checks in
  // ShouldDisableSiteIsolationDueToMemoryThreshold().
  if (!content::SiteIsolationPolicy::AreDynamicIsolatedOriginsEnabled())
    return false;

  // The feature needs to be checked last, because checking the feature
  // activates the field trial and assigns the client either to a control or an
  // experiment group - such assignment should be final.
  return base::FeatureList::IsEnabled(features::kSiteIsolationForOAuthSites);
}

// static
bool SiteIsolationPolicy::IsEnterprisePolicyApplicable() {
#if BUILDFLAG(IS_ANDROID)
  // https://crbug.com/844118: Limiting policy to devices with > 1GB RAM.
  // Using 1077 rather than 1024 because 1) it helps ensure that devices with
  // exactly 1GB of RAM won't get included because of inaccuracies or off-by-one
  // errors and 2) this is the bucket boundary in Memory.Stats.Win.TotalPhys2.
  bool have_enough_memory = base::SysInfo::AmountOfPhysicalMemoryMB() > 1077;
  return have_enough_memory;
#else
  return true;
#endif
}

// static
bool SiteIsolationPolicy::ShouldDisableSiteIsolationDueToMemoryThreshold(
    content::SiteIsolationMode site_isolation_mode) {
  // The memory threshold behavior differs for desktop and Android:
  // - Android uses a 1900MB default threshold for partial site isolation modes
  //   and a 3200MB default threshold for strict site isolation. See docs in
  //   https://crbug.com/849815. The thresholds roughly correspond to 2GB+ and
  //   4GB+ devices and are lower to account for memory carveouts, which
  //   reduce the amount of memory seen by AmountOfPhysicalMemoryMB(). Both
  //   partial and strict site isolation thresholds can be overridden via
  //   params defined in a kSiteIsolationMemoryThresholds field trial.
  // - Desktop does not enforce a default memory threshold, but for now we
  //   still support a threshold defined via a kSiteIsolationMemoryThresholds
  //   field trial.  The trial typically carries the threshold in a param; if
  //   it doesn't, use a default that's slightly higher than 1GB (see
  //   https://crbug.com/844118).
  int default_memory_threshold_mb;
#if BUILDFLAG(IS_ANDROID)
  if (site_isolation_mode == content::SiteIsolationMode::kStrictSiteIsolation) {
    default_memory_threshold_mb = 3200;
  } else {
    default_memory_threshold_mb = 1900;
  }
#else
  default_memory_threshold_mb = 1077;
#endif

  if (base::FeatureList::IsEnabled(features::kSiteIsolationMemoryThresholds)) {
    std::string param_name;
    switch (site_isolation_mode) {
      case content::SiteIsolationMode::kStrictSiteIsolation:
        param_name = features::kStrictSiteIsolationMemoryThresholdParamName;
        break;
      case content::SiteIsolationMode::kPartialSiteIsolation:
        param_name = features::kPartialSiteIsolationMemoryThresholdParamName;
        break;
    }
    int memory_threshold_mb = base::GetFieldTrialParamByFeatureAsInt(
        features::kSiteIsolationMemoryThresholds, param_name,
        default_memory_threshold_mb);
    return base::SysInfo::AmountOfPhysicalMemoryMB() <= memory_threshold_mb;
  }

#if BUILDFLAG(IS_ANDROID)
  if (base::SysInfo::AmountOfPhysicalMemoryMB() <=
      default_memory_threshold_mb) {
    return true;
  }
#endif

  return false;
}

// static
void SiteIsolationPolicy::PersistIsolatedOrigin(
    content::BrowserContext* context,
    const url::Origin& origin,
    IsolatedOriginSource source) {
  DCHECK(context);
  DCHECK(!context->IsOffTheRecord());
  DCHECK(!origin.opaque());

  // This function currently supports two sources for persistence, for
  // user-triggered and web-triggered isolated origins.
  if (source == IsolatedOriginSource::USER_TRIGGERED) {
    PersistUserTriggeredIsolatedOrigin(context, origin);
  } else if (source == IsolatedOriginSource::WEB_TRIGGERED) {
    PersistWebTriggeredIsolatedOrigin(context, origin);
  } else {
    NOTREACHED();
  }
}

// static
void SiteIsolationPolicy::PersistUserTriggeredIsolatedOrigin(
    content::BrowserContext* context,
    const url::Origin& origin) {
  // User-triggered isolated origins are currently stored in a simple list of
  // unlimited size.
  // TODO(alexmos): Cap the maximum number of entries and evict older entries.
  // See https://crbug.com/1172407.
  ListPrefUpdate update(user_prefs::UserPrefs::Get(context),
                        site_isolation::prefs::kUserTriggeredIsolatedOrigins);
  base::Value* list = update.Get();
  base::Value value(origin.Serialize());
  if (!base::Contains(list->GetListDeprecated(), value))
    list->Append(std::move(value));
}

// static
void SiteIsolationPolicy::PersistWebTriggeredIsolatedOrigin(
    content::BrowserContext* context,
    const url::Origin& origin) {
  // Web-triggered isolated origins are stored in a dictionary of (origin,
  // timestamp) pairs.  The number of entries is capped by a field trial param,
  // and older entries are evicted.
  DictionaryPrefUpdate update(
      user_prefs::UserPrefs::Get(context),
      site_isolation::prefs::kWebTriggeredIsolatedOrigins);
  base::Value* dict = update.Get();

  // Add the origin.  If it already exists, this will just update the
  // timestamp.
  dict->SetKey(origin.Serialize(), base::TimeToValue(base::Time::Now()));

  // Check whether the maximum number of stored sites was exceeded and remove
  // one or more entries, starting with the oldest timestamp. Note that more
  // than one entry may need to be removed, since the maximum number of entries
  // could change over time (via a change in the field trial param).
  size_t max_size =
      ::features::kSiteIsolationForCrossOriginOpenerPolicyMaxSitesParam.Get();
  while (dict->DictSize() > max_size) {
    auto items = dict->DictItems();
    auto oldest_site_time_pair = std::min_element(
        items.begin(), items.end(), [](auto pair_a, auto pair_b) {
          absl::optional<base::Time> time_a = base::ValueToTime(pair_a.second);
          absl::optional<base::Time> time_b = base::ValueToTime(pair_b.second);
          // has_value() should always be true unless the prefs were corrupted.
          // In that case, prioritize the corrupted entry for removal.
          return (time_a.has_value() ? time_a.value() : base::Time::Min()) <
                 (time_b.has_value() ? time_b.value() : base::Time::Min());
        });
    dict->RemoveKey(oldest_site_time_pair->first);
  }
}

// static
void SiteIsolationPolicy::ApplyPersistedIsolatedOrigins(
    content::BrowserContext* browser_context) {
  auto* policy = content::ChildProcessSecurityPolicy::GetInstance();

  // If the user turned off password-triggered isolation, don't apply any
  // stored isolated origins, but also don't clear them from prefs, so that
  // they can be used if password-triggered isolation is re-enabled later.
  if (IsIsolationForPasswordSitesEnabled()) {
    std::vector<url::Origin> origins;
    for (const auto& value : user_prefs::UserPrefs::Get(browser_context)
                                 ->GetList(prefs::kUserTriggeredIsolatedOrigins)
                                 ->GetListDeprecated()) {
      origins.push_back(url::Origin::Create(GURL(value.GetString())));
    }

    if (!origins.empty()) {
      policy->AddFutureIsolatedOrigins(
          origins, IsolatedOriginSource::USER_TRIGGERED, browser_context);
    }

    base::UmaHistogramCounts1000(
        "SiteIsolation.SavedUserTriggeredIsolatedOrigins.Size", origins.size());
  }

  // Similarly, load saved web-triggered isolated origins only if isolation of
  // COOP sites (currently the only source of these origins) is enabled with
  // persistence, but don't remove them from prefs otherwise.
  if (content::SiteIsolationPolicy::ShouldPersistIsolatedCOOPSites()) {
    std::vector<url::Origin> origins;
    std::vector<std::string> expired_entries;

    auto* pref_service = user_prefs::UserPrefs::Get(browser_context);
    auto* dict =
        pref_service->GetDictionary(prefs::kWebTriggeredIsolatedOrigins);
    if (dict) {
      for (auto site_time_pair : dict->DictItems()) {
        // Only isolate origins that haven't expired.
        absl::optional<base::Time> timestamp =
            base::ValueToTime(site_time_pair.second);
        base::TimeDelta expiration_timeout =
            ::features::
                kSiteIsolationForCrossOriginOpenerPolicyExpirationTimeoutParam
                    .Get();
        if (timestamp.has_value() &&
            base::Time::Now() - timestamp.value() <= expiration_timeout) {
          origins.push_back(url::Origin::Create(GURL(site_time_pair.first)));
        } else {
          expired_entries.push_back(site_time_pair.first);
        }
      }
      // Remove expired entries (as well as those with an invalid timestamp).
      if (!expired_entries.empty()) {
        DictionaryPrefUpdate update(pref_service,
                                    prefs::kWebTriggeredIsolatedOrigins);
        base::Value* updated_dict = update.Get();
        for (const auto& entry : expired_entries)
          updated_dict->RemoveKey(entry);
      }
    }

    if (!origins.empty()) {
      policy->AddFutureIsolatedOrigins(
          origins, IsolatedOriginSource::WEB_TRIGGERED, browser_context);
    }

    base::UmaHistogramCounts100(
        "SiteIsolation.SavedWebTriggeredIsolatedOrigins.Size", origins.size());
  }
}

// static
void SiteIsolationPolicy::IsolateStoredOAuthSites(
    content::BrowserContext* browser_context,
    const std::vector<url::Origin>& logged_in_sites) {
  // Only isolate logged-in sites if the corresponding feature is enabled and
  // other isolation requirements (such as memory threshold) are satisfied.
  // Note that we don't clear logged-in sites from prefs if site isolation is
  // disabled so that they can be used if isolation is re-enabled later.
  if (!IsIsolationForOAuthSitesEnabled())
    return;

  auto* policy = content::ChildProcessSecurityPolicy::GetInstance();
  policy->AddFutureIsolatedOrigins(
      logged_in_sites,
      content::ChildProcessSecurityPolicy::IsolatedOriginSource::USER_TRIGGERED,
      browser_context);

  // Note that the max count matches
  // login_detection::GetOauthLoggedInSitesMaxSize().
  base::UmaHistogramCounts100("SiteIsolation.SavedOAuthSites.Size",
                              logged_in_sites.size());
}

// static
void SiteIsolationPolicy::IsolateNewOAuthURL(
    content::BrowserContext* browser_context,
    const GURL& signed_in_url) {
  if (!IsIsolationForOAuthSitesEnabled())
    return;

  // OAuth information is currently persisted and restored by other layers. See
  // login_detection::prefs::SaveSiteToOAuthSignedInList().
  constexpr bool kShouldPersist = false;

  content::SiteInstance::StartIsolatingSite(
      browser_context, signed_in_url,
      content::ChildProcessSecurityPolicy::IsolatedOriginSource::USER_TRIGGERED,
      kShouldPersist);
}

// static
bool SiteIsolationPolicy::ShouldPdfCompositorBeEnabledForOopifs() {
  // We only create pdf compositor client and use pdf compositor service when
  // one of the site isolation modes that forces OOPIFs is on. This includes
  // full site isolation on desktop, password-triggered site isolation on
  // Android for high-memory devices, and/or isolated origins specified via
  // command line, enterprise policy, or field trials.
  //
  // TODO(weili, thestig): Eventually, we should remove this check and use pdf
  // compositor service by default for printing.
  return content::SiteIsolationPolicy::UseDedicatedProcessesForAllSites() ||
         IsIsolationForPasswordSitesEnabled() ||
         content::SiteIsolationPolicy::AreIsolatedOriginsEnabled();
}

}  // namespace site_isolation


text:
<?php

namespace Symfony\Component\Messenger\DependencyInjection;

use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\OutOfBoundsException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Messenger\Handler\HandlerDescriptor;
use Symfony\Component\Messenger\Handler\HandlersLocator;
use Symfony\Component\Messenger\Handler\MessageSubscriberInterface;
use Symfony\Component\Messenger\TraceableMessageBus;
use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;

/**
 * @author Samuel Roze <samuel.roze@gmail.com>
 */
class MessengerPass implements CompilerPassInterface
{
    private $handlerTag;
    private $busTag;
    private $receiverTag;

    public function __construct(string $handlerTag = 'messenger.message_handler', string $busTag = 'messenger.bus', string $receiverTag = 'messenger.receiver')
    {
        if (0 < \func_num_args()) {
            trigger_deprecation('symfony/messenger', '5.3', 'Configuring "%s" is deprecated.', __CLASS__);
        }

        $this->handlerTag = $handlerTag;
        $this->busTag = $busTag;
        $this->receiverTag = $receiverTag;
    }

    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        $busIds = [];
        foreach ($container->findTaggedServiceIds($this->busTag) as $busId => $tags) {
            $busIds[] = $busId;
            if ($container->hasParameter($busMiddlewareParameter = $busId.'.middleware')) {
                $this->registerBusMiddleware($container, $busId, $container->getParameter($busMiddlewareParameter));

                $container->getParameterBag()->remove($busMiddlewareParameter);
            }

            if ($container->hasDefinition('data_collector.messenger')) {
                $this->registerBusToCollector($container, $busId);
            }
        }

        if ($container->hasDefinition('messenger.receiver_locator')) {
            $this->registerReceivers($container, $busIds);
        }
        $this->registerHandlers($container, $busIds);
    }

    private function registerHandlers(ContainerBuilder $container, array $busIds)
    {
        $definitions = [];
        $handlersByBusAndMessage = [];
        $handlerToOriginalServiceIdMapping = [];

        foreach ($container->findTaggedServiceIds($this->handlerTag, true) as $serviceId => $tags) {
            foreach ($tags as $tag) {
                if (isset($tag['bus']) && !\in_array($tag['bus'], $busIds, true)) {
                    throw new RuntimeException(sprintf('Invalid handler service "%s": bus "%s" specified on the tag "%s" does not exist (known ones are: "%s").', $serviceId, $tag['bus'], $this->handlerTag, implode('", "', $busIds)));
                }

                $className = $this->getServiceClass($container, $serviceId);
                $r = $container->getReflectionClass($className);

                if (null === $r) {
                    throw new RuntimeException(sprintf('Invalid service "%s": class "%s" does not exist.', $serviceId, $className));
                }

                if (isset($tag['handles'])) {
                    $handles = isset($tag['method']) ? [$tag['handles'] => $tag['method']] : [$tag['handles']];
                } else {
                    $handles = $this->guessHandledClasses($r, $serviceId);
                }

                $message = null;
                $handlerBuses = (array) ($tag['bus'] ?? $busIds);

                foreach ($handles as $message => $options) {
                    $buses = $handlerBuses;

                    if (\is_int($message)) {
                        if (\is_string($options)) {
                            $message = $options;
                            $options = [];
                        } else {
                            throw new RuntimeException(sprintf('The handler configuration needs to return an array of messages or an associated array of message and configuration. Found value of type "%s" at position "%d" for service "%s".', get_debug_type($options), $message, $serviceId));
                        }
                    }

                    if (\is_string($options)) {
                        $options = ['method' => $options];
                    }

                    if (!isset($options['from_transport']) && isset($tag['from_transport'])) {
                        $options['from_transport'] = $tag['from_transport'];
                    }

                    $priority = $tag['priority'] ?? $options['priority'] ?? 0;
                    $method = $options['method'] ?? '__invoke';

                    if (isset($options['bus'])) {
                        if (!\in_array($options['bus'], $busIds)) {
                            $messageLocation = isset($tag['handles']) ? 'declared in your tag attribute "handles"' : ($r->implementsInterface(MessageSubscriberInterface::class) ? sprintf('returned by method "%s::getHandledMessages()"', $r->getName()) : sprintf('used as argument type in method "%s::%s()"', $r->getName(), $method));

                            throw new RuntimeException(sprintf('Invalid configuration "%s" for message "%s": bus "%s" does not exist.', $messageLocation, $message, $options['bus']));
                        }

                        $buses = [$options['bus']];
                    }

                    if ('*' !== $message && !class_exists($message) && !interface_exists($message, false)) {
                        $messageLocation = isset($tag['handles']) ? 'declared in your tag attribute "handles"' : ($r->implementsInterface(MessageSubscriberInterface::class) ? sprintf('returned by method "%s::getHandledMessages()"', $r->getName()) : sprintf('used as argument type in method "%s::%s()"', $r->getName(), $method));

                        throw new RuntimeException(sprintf('Invalid handler service "%s": class or interface "%s" "%s" not found.', $serviceId, $message, $messageLocation));
                    }

                    if (!$r->hasMethod($method)) {
                        throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::%s()" does not exist.', $serviceId, $r->getName(), $method));
                    }

                    if ('__invoke' !== $method) {
                        $wrapperDefinition = (new Definition('callable'))->addArgument([new Reference($serviceId), $method])->setFactory('Closure::fromCallable');

                        $definitions[$definitionId = '.messenger.method_on_object_wrapper.'.ContainerBuilder::hash($message.':'.$priority.':'.$serviceId.':'.$method)] = $wrapperDefinition;
                    } else {
                        $definitionId = $serviceId;
                    }

                    $handlerToOriginalServiceIdMapping[$definitionId] = $serviceId;

                    foreach ($buses as $handlerBus) {
                        $handlersByBusAndMessage[$handlerBus][$message][$priority][] = [$definitionId, $options];
                    }
                }

                if (null === $message) {
                    throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::getHandledMessages()" must return one or more messages.', $serviceId, $r->getName()));
                }
            }
        }

        foreach ($handlersByBusAndMessage as $bus => $handlersByMessage) {
            foreach ($handlersByMessage as $message => $handlersByPriority) {
                krsort($handlersByPriority);
                $handlersByBusAndMessage[$bus][$message] = array_merge(...$handlersByPriority);
            }
        }

        $handlersLocatorMappingByBus = [];
        foreach ($handlersByBusAndMessage as $bus => $handlersByMessage) {
            foreach ($handlersByMessage as $message => $handlers) {
                $handlerDescriptors = [];
                foreach ($handlers as $handler) {
                    $definitions[$definitionId = '.messenger.handler_descriptor.'.ContainerBuilder::hash($bus.':'.$message.':'.$handler[0])] = (new Definition(HandlerDescriptor::class))->setArguments([new Reference($handler[0]), $handler[1]]);
                    $handlerDescriptors[] = new Reference($definitionId);
                }

                $handlersLocatorMappingByBus[$bus][$message] = new IteratorArgument($handlerDescriptors);
            }
        }
        $container->addDefinitions($definitions);

        foreach ($busIds as $bus) {
            $container->register($locatorId = $bus.'.messenger.handlers_locator', HandlersLocator::class)
                ->setArgument(0, $handlersLocatorMappingByBus[$bus] ?? [])
            ;
            if ($container->has($handleMessageId = $bus.'.middleware.handle_message')) {
                $container->getDefinition($handleMessageId)
                    ->replaceArgument(0, new Reference($locatorId))
                ;
            }
        }

        if ($container->hasDefinition('console.command.messenger_debug')) {
            $debugCommandMapping = $handlersByBusAndMessage;
            foreach ($busIds as $bus) {
                if (!isset($debugCommandMapping[$bus])) {
                    $debugCommandMapping[$bus] = [];
                }

                foreach ($debugCommandMapping[$bus] as $message => $handlers) {
                    foreach ($handlers as $key => $handler) {
                        $debugCommandMapping[$bus][$message][$key][0] = $handlerToOriginalServiceIdMapping[$handler[0]];
                    }
                }
            }
            $container->getDefinition('console.command.messenger_debug')->replaceArgument(0, $debugCommandMapping);
        }
    }

    private function guessHandledClasses(\ReflectionClass $handlerClass, string $serviceId): iterable
    {
        if ($handlerClass->implementsInterface(MessageSubscriberInterface::class)) {
            return $handlerClass->getName()::getHandledMessages();
        }

        try {
            $method = $handlerClass->getMethod('__invoke');
        } catch (\ReflectionException $e) {
            throw new RuntimeException(sprintf('Invalid handler service "%s": class "%s" must have an "__invoke()" method.', $serviceId, $handlerClass->getName()));
        }

        if (0 === $method->getNumberOfRequiredParameters()) {
            throw new RuntimeException(sprintf('Invalid handler service "%s": method "%s::__invoke()" requires at least one argument, first one being the message it handles.', $serviceId, $handlerClass->getName()));
        }

        $parameters = $method->getParameters();
        if (!$type = $parameters[0]->getType()) {
            throw new RuntimeException(sprintf('Invalid handler service "%s": argument "$%s" of method "%s::__invoke()" must have a type-hint corresponding to the message class it handles.', $serviceId, $parameters[0]->getName(), $handlerClass->getName()));
        }

        if ($type instanceof \ReflectionUnionType) {
            $types = [];
            foreach ($type->getTypes() as $type) {
                if (!$type->isBuiltin()) {
                    $types[] = (string) $type;
                }
            }

            if ($types) {
                return $types;
            }
        }

        if ($type->isBuiltin()) {
            throw new RuntimeException(sprintf('Invalid handler service "%s": type-hint of argument "$%s" in method "%s::__invoke()" must be a class , "%s" given.', $serviceId, $parameters[0]->getName(), $handlerClass->getName(), $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type));
        }

        return [$type->getName()];
    }

    private function registerReceivers(ContainerBuilder $container, array $busIds)
    {
        $receiverMapping = [];
        $failureTransportsMap = [];
        if ($container->hasDefinition('console.command.messenger_failed_messages_retry')) {
            $commandDefinition = $container->getDefinition('console.command.messenger_failed_messages_retry');
            $globalReceiverName = $commandDefinition->getArgument(0);
            if (null !== $globalReceiverName) {
                if ($container->hasAlias('messenger.failure_transports.default')) {
                    $failureTransportsMap[$globalReceiverName] = new Reference('messenger.failure_transports.default');
                } else {
                    $failureTransportsMap[$globalReceiverName] = new Reference('messenger.transport.'.$globalReceiverName);
                }
            }
        }

        foreach ($container->findTaggedServiceIds($this->receiverTag) as $id => $tags) {
            $receiverClass = $this->getServiceClass($container, $id);
            if (!is_subclass_of($receiverClass, ReceiverInterface::class)) {
                throw new RuntimeException(sprintf('Invalid receiver "%s": class "%s" must implement interface "%s".', $id, $receiverClass, ReceiverInterface::class));
            }

            $receiverMapping[$id] = new Reference($id);

            foreach ($tags as $tag) {
                if (isset($tag['alias'])) {
                    $receiverMapping[$tag['alias']] = $receiverMapping[$id];
                    if ($tag['is_failure_transport'] ?? false) {
                        $failureTransportsMap[$tag['alias']] = $receiverMapping[$id];
                    }
                }
            }
        }

        $receiverNames = [];
        foreach ($receiverMapping as $name => $reference) {
            $receiverNames[(string) $reference] = $name;
        }

        $buses = [];
        foreach ($busIds as $busId) {
            $buses[$busId] = new Reference($busId);
        }

        if ($hasRoutableMessageBus = $container->hasDefinition('messenger.routable_message_bus')) {
            $container->getDefinition('messenger.routable_message_bus')
                ->replaceArgument(0, ServiceLocatorTagPass::register($container, $buses));
        }

        if ($container->hasDefinition('console.command.messenger_consume_messages')) {
            $consumeCommandDefinition = $container->getDefinition('console.command.messenger_consume_messages');

            if ($hasRoutableMessageBus) {
                $consumeCommandDefinition->replaceArgument(0, new Reference('messenger.routable_message_bus'));
            }

            $consumeCommandDefinition->replaceArgument(4, array_values($receiverNames));
            try {
                $consumeCommandDefinition->replaceArgument(6, $busIds);
            } catch (OutOfBoundsException $e) {
                // ignore to preserve compatibility with symfony/framework-bundle < 5.4
            }
        }

        if ($container->hasDefinition('console.command.messenger_setup_transports')) {
            $container->getDefinition('console.command.messenger_setup_transports')
                ->replaceArgument(1, array_values($receiverNames));
        }

        $container->getDefinition('messenger.receiver_locator')->replaceArgument(0, $receiverMapping);

        $failureTransportsLocator = ServiceLocatorTagPass::register($container, $failureTransportsMap);

        $failedCommandIds = [
            'console.command.messenger_failed_messages_retry',
            'console.command.messenger_failed_messages_show',
            'console.command.messenger_failed_messages_remove',
        ];
        foreach ($failedCommandIds as $failedCommandId) {
            if ($container->hasDefinition($failedCommandId)) {
                $definition = $container->getDefinition($failedCommandId);
                $definition->replaceArgument(1, $failureTransportsLocator);
            }
        }
    }

    private function registerBusToCollector(ContainerBuilder $container, string $busId)
    {
        $container->setDefinition(
            $tracedBusId = 'debug.traced.'.$busId,
            (new Definition(TraceableMessageBus::class, [new Reference($tracedBusId.'.inner')]))->setDecoratedService($busId)
        );

        $container->getDefinition('data_collector.messenger')->addMethodCall('registerBus', [$busId, new Reference($tracedBusId)]);
    }

    private function registerBusMiddleware(ContainerBuilder $container, string $busId, array $middlewareCollection)
    {
        $middlewareReferences = [];
        foreach ($middlewareCollection as $middlewareItem) {
            $id = $middlewareItem['id'];
            $arguments = $middlewareItem['arguments'] ?? [];
            if (!$container->has($messengerMiddlewareId = 'messenger.middleware.'.$id)) {
                $messengerMiddlewareId = $id;
            }

            if (!$container->has($messengerMiddlewareId)) {
                throw new RuntimeException(sprintf('Invalid middleware: service "%s" not found.', $id));
            }

            if ($container->findDefinition($messengerMiddlewareId)->isAbstract()) {
                $childDefinition = new ChildDefinition($messengerMiddlewareId);
                $childDefinition->setArguments($arguments);
                if (isset($middlewareReferences[$messengerMiddlewareId = $busId.'.middleware.'.$id])) {
                    $messengerMiddlewareId .= '.'.ContainerBuilder::hash($arguments);
                }
                $container->setDefinition($messengerMiddlewareId, $childDefinition);
            } elseif ($arguments) {
                throw new RuntimeException(sprintf('Invalid middleware factory "%s": a middleware factory must be an abstract definition.', $id));
            }

            $middlewareReferences[$messengerMiddlewareId] = new Reference($messengerMiddlewareId);
        }

        $container->getDefinition($busId)->replaceArgument(0, new IteratorArgument(array_values($middlewareReferences)));
    }

    private function getServiceClass(ContainerBuilder $container, string $serviceId): string
    {
        while (true) {
            $definition = $container->findDefinition($serviceId);

            if (!$definition->getClass() && $definition instanceof ChildDefinition) {
                $serviceId = $definition->getParent();

                continue;
            }

            return $definition->getClass();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
PYTHON_VERSION=3.6.15
pyenv local $PYTHON_VERSION

if [[ $0 == $${BASH_SOURCE[0]} ]] ; then
    echo "This script should be *sourced* rather than run directly through bash"
    exit 1
fi

git checkout master && git pull && pyenv local $PYTHON_VERSION


text:
FROM node:8
RUN apt-get update -y
RUN apt-get upgrade -y
RUN apt-get install wget -y
RUN apt-get install -y mongodb
RUN apt-get install python-pip python-dev g++ build-essential redis-server -y
RUN apt-get install git -y
RUN pip install --upgrade pip
RUN pip install pymongo numpy Algorithmia websocket_server
RUN pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.2.1-cp27-none-linux_x86_64.whl
RUN mkdir /data
RUN mkdir /data/db
RUN mkdir -p /usr/src/Echo
RUN chown node:node /usr/src/Echo
USER node
COPY . /usr/src/Echo
WORKDIR /usr/src/Echo
RUN mkdir /home/node/.npm-global
ENV PATH=/home/node/.npm-global/bin:$PATH
ENV NPM_CONFIG_PREFIX=/home/node/.npm-global
RUN npm install -g npm
RUN npm install -g gulp norch
RUN npm install
RUN npm install gulp
RUN npm install gulp-nodemon
RUN gulp es6
RUN gulp styles
USER root
EXPOSE 3000 8001
CMD ["./run.sh"]


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Limitless - Responsive Web Application Kit by Eugene Kopyov</title>

	<link href="https://fonts.googleapis.com/css?family=Roboto:400,300,100,500,700,900" rel="stylesheet" type="text/css">
	<link href="assets/css/icons/icomoon/styles.css" rel="stylesheet" type="text/css">
	<link href="assets/css/bootstrap.css" rel="stylesheet" type="text/css">
	<link href="assets/css/core.css" rel="stylesheet" type="text/css">
	<link href="assets/css/components.css" rel="stylesheet" type="text/css">
	<link href="assets/css/colors.css" rel="stylesheet" type="text/css">
	<link href="assets/css/extras/animate.min.css" rel="stylesheet" type="text/css">

						Git updates
						9

							Git updates

									Drop the IE specific hacks for temporal inputs

4 minutes ago

									Add full font overrides for popovers and tooltips

36 minutes ago

									Chris Arney created a new Design branch

2 hours ago

									Eugene Kopyov merged Master and Dev branches

Dec 18, 18:36

									Have Carousel ignore keyboard events

Dec 12, 05:46

				Online

							Users

								Users online

										Jordana Ansley
										Lead web developer

										Will Brason
										Marketing manager

										Hanna Walden
										Project manager

										Dori Laperriere
										Business developer

										Vanessa Aurelius
										UX expert

							Messages
							2

								Messages

										5

											James Alexander
											04:58

										who knows, maybe that would be the best thing for me...

										4

											Margo Baker
											12:16

										That was something he was unable to do because...

											Jeremy Victorino
											22:48

										But that would be extremely strained and suspicious...

											Beatrix Diaz
											Tue

										What a strenuous career it is that I've chosen...

											Richard Vango
											Mon

										Other travelling salesmen live a life of luxury...

							Victoria

 My profile

 My balance

58  Messages

 Account settings

 Logout

									Victoria Baker

										  Santa Ana, CA

Main

 Dashboard

									 Page layouts

Fixed navbar

Fixed navbar & sidebar

Fixed sidebar native scroll

Hideable navbar

Hideable & fixed sidebar

Fixed footer

Boxed with default sidebar

Boxed with mini sidebar

Boxed full width

									 Layouts

Layout 1

Layout 2 Current

Layout 3

Layout 4

Layout 5

Layout 6 Coming soon

									 Color system

Primary palette

Danger palette

Success palette

Warning palette

Info palette

Pink palette

Violet palette

Purple palette

Indigo palette

Blue palette

Teal palette

Green palette

Orange palette

Brown palette

Grey palette

Slate palette

									 Starter kit

Horizontal navigation

1 column

2 columns

											3 columns

Dual sidebars

Double sidebars

4 columns

											Detached layout

Left sidebar

Right sidebar

Sticky sidebar

Boxed layout

Fixed main navbar

Fixed secondary navbar

Both navbars fixed

Fixed layout

 Changelog 1.4

 RTL version

Forms

									 Form components

Basic inputs

Checkboxes & radios

Input groups

Extended controls

Floating labels

											Selects

Select2 selects

Bootstrap multiselect

SelectBoxIt selects

Bootstrap selects

Tag inputs

Dual Listboxes

Editable forms

Validation

Inputs grid

									 JSON forms

Basic inputs

Advanced inputs

Controls

									 Wizards

Steps wizard

Form wizard

Stepy wizard

									 Editors

Summernote editor

CKEditor

WYSIHTML5 editor

Code editor

									 Pickers

Date & time pickers

Color pickers

Location pickers

									 Form layouts

Vertical form

Horizontal form

Appearance

									 Components

Modals

Dropdown menus

Tabs component

Pills component

Accordion and navs

Buttons

PNotify notifications

Other notifications

Tooltips and popovers

Alerts

Pagination

Labels and badges

Loaders and bars

Thumbnails

Page header

Breadcrumbs

Media objects

Affix and Scrollspy

									 Content appearance

Content panels

Panel heading elements

Panel footer elements

Draggable panels

Text styling

Typography

Helper classes

Syntax highlighter

Grid system

									 Extra components

NoUI sliders

Ion range sliders

Session timeout

Idle timeout

Dynamic tree views

Context menu

Floating action buttons

									 Animations

CSS3 animations

											Velocity animations

Basic usage

UI pack effects

Advanced examples

									 Icons

Glyphicons

Icomoon

Font awesome

Layout

									 Sidebars

Default collapsible

Default hideable

Mini collapsible

Mini hideable

											Dual sidebar

Dual sidebar

Dual double collapse

Dual double hide

Swap sidebars

											Double sidebar

Collapse main sidebar

Hide main sidebar

Fix default width

Fix mini width

Opposite sidebar visible

											Detached sidebar

Left position

Right position

Sticky (custom scroll)

Sticky (native scroll)

Separate categories

Hidden sidebar

Light sidebar

Sidebar components

									 Vertical navigation

Collapsible menu

Accordion menu

Navigation sizing

Bordered navigation

Right icons

Labels and badges

Disabled navigation links

									 Horizontal navigation

Submenu on click

Submenu on hover

With custom elements

Tabbed navigation

Disabled navigation links

Horizontal mega menu

									 Navbars

Single navbar

											Multiple navbars

Navbar + navbar

Navbar + header

Header + navbar

Top + bottom

Color options

Sizing options

Hide on scroll

Navbar components

									 Menu levels

 Second level

											 Second level with child

 Third level

													 Third level with child

 Fourth level

 Fourth level

 Third level

 Second level

Data visualization

									 Echarts library

Lines and areas

Columns and waterfalls

Bars and tornados

Scatter charts

Pies and donuts

Funnels and chords

Candlesticks and others

Chart combinations

									 D3 library

Simple lines

Advanced lines

Simple bars

Advanced bars

Pie charts

Circle diagrams

Tree layout

Other charts

									 Dimple library

											Line charts

Horizontal orientation

Vertical orientation

											Bar charts

Horizontal orientation

Vertical orientation

											Area charts

Horizontal orientation

Vertical orientation

											Step charts

Horizontal orientation

Vertical orientation

Pie charts

Ring charts

Scatter charts

Bubble charts

									 C3 library

Lines and areas

Bars and pies

Advanced examples

Chart axis

Grid options

									 Google visualization

Line charts

Bar charts

Pie charts

Bubble & scatter charts

Other charts

									 Maps integration

											Google maps

Basics

Controls

Markers

Map drawings

Layers

Vector maps

Extensions

									 Extensions

Image cropper

Block UI

Drag and drop

									 JQuery UI

Interactions

Forms

Components

Sliders

Navigation

									 File uploaders

Plupload

Bootstrap file uploader

Dropzone

									 Event calendars

Basic views

Event styling

Language and time

Advanced usage

									 Internationalization

Direct translation

Querystring parameter

Set language on init

Set language after init

Language fallback

Callbacks

Tables

									 Basic tables

Basic examples

Table sizing

Table borders

Table styling

Table elements

									 Data tables

Basic initialization

Basic styling

Advanced examples

Sorting options

Using API

Data sources

									 Data tables extensions

Columns reorder

Row reorder

Fixed columns

Fixed header

Auto fill

Key table

Scroller

Select

											Buttons

Initialization

Flash buttons

Print buttons

HTML5 buttons

Columns visibility

									 Handsontable

Basic configuration

Advanced setup

Column features

Cell features

Basic cell types

Custom & checkboxes

Autocomplete & password

Search

Context menu

									 Responsive options

Responsive basic tables

Responsive data tables

Page kits

									 Task manager

Task grid

Task list

Task detailed

									 Invoicing

Invoice template

Invoice grid

Invoice archive

									 User pages

User cards

User list

Simple profile

Profile with cover

									 Login & registration

Simple login

More login info

Simple registration

More registration info

Unlock user

Reset password

Hide navbar

Transparent box

Background option

With validation

Tabbed form

Inside modals

									 Timelines

Left timeline

Right timeline

Centered timeline

									 Support

Conversation layouts

Conversation options

Knowledgebase

FAQ page

									 Search

Basic search results

User search results

Image search results

Video search results

									 Gallery

Media grid

Media with titles

Media with description

Media library

									 Error pages

Error 403

Error 404

Error 405

Error 500

Error 503

Offline page

 Extensions - Block UI

								Statistics
								 Invoices
								 Schedule

 Home

Extensions

Block UI

 Support

									Settings

 Account security

 Analytics

 Accessibility

 All settings

BlockUI extension

BlockUI overview

The jQuery BlockUI Plugin lets you simulate synchronous behavior when using AJAX, without locking the browser (Using the XMLHttpRequest object in synchronous mode causes the entire browser to lock until the remote call completes. This is usually not a desirable behavior). When activated, it will prevent user activity with the page (or part of the page) until it is deactivated. BlockUI adds elements to the DOM to give it both the appearance and behavior of blocking user interaction. By default blockUI message displays text inside a bordered frame. In this template default style is rotating spinner icon. Other message, overlay and plugin options you can find in demos below.

Sample markup

Sample examples of blocking user activity with the entire page and with content panel on button click. In both examples auto unblock is enabled for demonstration purposes and unblock specified containers in 2 seconds. In real final working version all containers can be unblocked when ajax activity stops. All styles for overlay and message are custom, default message displays text only.

Block the panel

/* Block the panel on button click */
$('#block-panel').on('click', function() {
	var block = $(this).parent().parent();
	$(block).block({
	    message: '<i class="icon-spinner4 spinner"></i>',
	    timeout: 2000, //unblock after 2 seconds
	    overlayCSS: {
	        backgroundColor: '#fff',
	        opacity: 0.8,
	        cursor: 'wait'
	    },
	    css: {
	        border: 0,
	        padding: 0,
	        backgroundColor: 'transparent'
	    }
	});
});

Block current page

/* Block current page on button click */
$('#block-page').on('click', function() {
	$.blockUI({
	    message: '<i class="icon-spinner4 spinner"></i>',
	    timeout: 2000, //unblock after 2 seconds
	    overlayCSS: {
	        backgroundColor: '#1b2024',
	        opacity: 0.8,
	        cursor: 'wait'
	    },
	    css: {
	        border: 0,
	        color: '#fff',
	        padding: 0,
	        backgroundColor: 'transparent'
	    }
	});
});

						Blocking areas
						Block layout areas, content components or entire page

Whole page blocking

Block entire page using default options

								<button type="button" class="btn btn-primary" id="block-page">Block the whole page</button>

Layout area blocking

Block layout areas using default options

								<button type="button" class="btn btn-primary" id="block-sidebar">Block left sidebar</button>

Content component blocking

Block content components using default options

								<button type="button" class="btn btn-primary" id="block-panel">Block this panel</button>

						Overlay options
						Default and custom overlay options

Basic light overlay

Displays basic overlay with opacity

								<button type="button" class="btn btn-danger" id="basic-overlay">Basic overlay</button>

Custom overlay color

Displays custom background color in overlay

								<button type="button" class="btn btn-danger" id="overlay-custom">Custom overlay color</button>

Full overlay cover

Displays fully opaque overlay

								<button type="button" class="btn btn-danger" id="overlay-cover">Full overlay cover</button>

						Display options
						Variations of message and overlay appearance

Block without message

Displays overlay only, message is empty

								<button type="button" class="btn btn-success" id="no-message">No message</button>

Block without overlay

Displays message only, overlay is hidden

								<button type="button" class="btn btn-success" id="no-overlay">No overlay</button>

Basic Growl example

Displays message and overlay as a Growl

								<button type="button" class="btn btn-success" id="growl">Growl example</button>

						              BlockUI Growl Notification

						Message options
						Default and custom options for messages

Block with spinner only

Displays animated spinner icon only, no text

								<button type="button" class="btn btn-info" id="spinner-only">With spinner only</button>

Block with DOM element

Displays DOM element as a message

								<button type="button" class="btn btn-info" id="dom-message">DOM element as a message</button>

						            Loading

Block with default message

Displays default text message, no spinner

								<button type="button" class="btn btn-info" id="default-message">With default message</button>

Multiple messages

Multiple messages with different styles

								<button type="button" class="btn btn-info" id="multiple-messages">Multiple messages</button>

						            Loading

Block with custom message

Custom message with overlay and spinner

								<button type="button" class="btn btn-info" id="custom-message">With custom message</button>

Message animation

Message animation using animate.css

								<button type="button" class="btn btn-info" id="custom-message-animation" data-animation="fadeInDown">Custom message animation</button>

						Other options
						Message position and unblocking options

Message position

Displays custom message position

								<button type="button" class="btn btn-warning" id="custom-position">Custom message position</button>

Auto unblocking

Demonstrates auto unblocking feature

								<button type="button" class="btn btn-warning" id="auto-unblock">Auto unblock</button>

Click to unblock

Click overlay to unblock the element

								<button type="button" class="btn btn-warning" id="click-unblock">Click overlay to unblock</button>

						Callback methods
						On block, on unblock and on overlay click

onBlock callback

Invoked when blocking message is visible

								<button type="button" class="btn bg-teal" id="block-callback">onBlock callback</button>

onUnblock callback

Invoked when unblocking has completed

								<button type="button" class="btn bg-teal" id="unblock-callback">onUnblock callback</button>

onOverlayClick callback

Invoked when blocking overlay is clicked

								<button type="button" class="btn bg-teal" id="overlay-callback">onOverlayClick callback</button>

						© 2015. Limitless Web App Kit by Eugene Kopyov


text:
using Bossr.Lib.Models.Interfaces;
using System.Threading.Tasks;

namespace Bossr.Api.Repositories.Interfaces
{
    public interface IUpdatable<T> where T : IEntity
    {
        Task UpdateAsync(T entity);
    }
}


text:
<!DOCTYPE html>

<title>geolocation test</title>
<link rel="stylesheet" type="text/css" href="style.css"/>

NOT TESTED (script did not run)

Test setup: Set opera:config#Geolocation|LocationProviderURL to


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using TAPI;

namespace Avalon.Projectiles.FromPlayer.Throwables
{
    /// <summary>
    /// The Sticky Spike Ball.
    /// </summary>
    public sealed class StickySpikeBall : ModProjectile
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="velocityChange"></param>
        /// <returns></returns>
        public override bool OnTileCollide(ref Vector2 velocityChange)
        {
            velocityChange = projectile.velocity = Vector2.Zero;

            return false;
        }
    }
}


text:
import {Injectable} from 'angular2/core';
// import {isArray} from 'lodash';
import {ApiService} from './xhr';
import {WpCollection, WpModel, WpResourceConfig, WpModelFactory} from './wp_resource';

@Injectable()
export class PostModel extends WpModel {
  url: string = '/posts';
  _tags: any[];

  id: number;
  date: Date;
  date_gmt: Date;
  guid: any;
  link: string;
  modified: Date;
  modified_gmt: Date;
  password: string;
  slug: string;
  status: string;
  type: string;
  title: any;
  content: any;
  author: any;
  excerpt: any;
  featured_image: any;
  comment_status: string;
  ping_status: string;
  sticky: boolean;
  format: string;
  _links: any;
  _embedded: any;
  // TODO: Improve to support w/o _embedded and probably move out
  get tags() {
    if (this._tags) { return this._tags; }

    // let tagTaxonomy = this.config.taxonomy.tag;
    // this._embedded['https://api.w.org/term'].forEach(terms => {
    //   if (isArray(terms)) {
    //     terms.forEach(term => {
    //       if (term.taxonomy === tagTaxonomy) {
    //         this._tags = this._tags || [];
    //         this.tags.push(term);
    //       }
    //     });
    //   }
    // });
    return this._tags;
  }
}

@Injectable()
export class PostsCollection extends WpCollection<PostModel> {
  modelToken = PostModel;
  url = '/posts';
  constructor(api: ApiService, config: WpResourceConfig, modelFactory: WpModelFactory) {
    super(api, config, modelFactory);
  }
}

export const POSTS_PROVIDERS = [
  PostsCollection,
  PostModel
];


text:
using System;

namespace Piranha.Extend
{
    public sealed class AppModuleList : AppDataList<IModule, AppModule>
    {
        /// <summary>
        /// Performs additional processing on the item before
        /// adding it to the collection.
        /// </summary>
        /// <typeparam name="TValue">The value type</typeparam>
        /// <param name="item">The item</param>
        /// <returns>The processed item</returns>
        protected override AppModule OnRegister<TValue>(AppModule item) {
            item.Instance = Activator.CreateInstance<TValue>();

            return item;
        }
    }
}


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

namespace Fosol.Data.Models.Configuration.Serialization
{
    [XmlRoot(ElementName = "column")]
    public sealed class ColumnElement
    {
        #region Variables
        #endregion

        #region Properties
        [XmlAttribute(AttributeName = "name")]
        public string Name { get; set; }

        [XmlAttribute(AttributeName = "alias")]
        public string Alias { get; set; }

        [XmlAttribute(AttributeName = "action")]
        public ImportAction Action { get; set; }
        #endregion

        #region Constructors
        internal ColumnElement()
        {
            this.Action = ImportAction.Import;
        }

        internal ColumnElement(string name, string alias = null, ImportAction action = ImportAction.Import)
            : this()
        {
            this.Name = name;
            this.Alias = alias;
            this.Action = action;
        }
        #endregion

        #region Methods

        #endregion

        #region Operators
        public static explicit operator ColumnElement(Configuration.ColumnElement obj)
        {
            return new ColumnElement(obj.Name, obj.Alias, obj.Action);
        }
        #endregion

        #region Events
        #endregion
    }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**Admin** | Pointer to **bool** |  | [optional]
**Push** | Pointer to **bool** |  | [optional]
**Pull** | Pointer to **bool** |  | [optional]
**Class** | Pointer to **string** |  | [optional]

## Methods

### NewGithubRepositorypermissions

`func NewGithubRepositorypermissions() *GithubRepositorypermissions`

NewGithubRepositorypermissions instantiates a new GithubRepositorypermissions object
This constructor will assign default values to properties that have it defined,
and makes sure properties required by API are set, but the set of arguments
will change when the set of required properties is changed

### NewGithubRepositorypermissionsWithDefaults

`func NewGithubRepositorypermissionsWithDefaults() *GithubRepositorypermissions`

NewGithubRepositorypermissionsWithDefaults instantiates a new GithubRepositorypermissions object
This constructor will only assign default values to properties that have it defined,
but it doesn't guarantee that properties required by API are set

### GetAdmin

`func (o *GithubRepositorypermissions) GetAdmin() bool`

GetAdmin returns the Admin field if non-nil, zero value otherwise.

### GetAdminOk

`func (o *GithubRepositorypermissions) GetAdminOk() (*bool, bool)`

GetAdminOk returns a tuple with the Admin field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.

### SetAdmin

`func (o *GithubRepositorypermissions) SetAdmin(v bool)`

SetAdmin sets Admin field to given value.

### HasAdmin

`func (o *GithubRepositorypermissions) HasAdmin() bool`

HasAdmin returns a boolean if a field has been set.

### GetPush

`func (o *GithubRepositorypermissions) GetPush() bool`

GetPush returns the Push field if non-nil, zero value otherwise.

### GetPushOk

`func (o *GithubRepositorypermissions) GetPushOk() (*bool, bool)`

GetPushOk returns a tuple with the Push field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.

### SetPush

`func (o *GithubRepositorypermissions) SetPush(v bool)`

SetPush sets Push field to given value.

### HasPush

`func (o *GithubRepositorypermissions) HasPush() bool`

HasPush returns a boolean if a field has been set.

### GetPull

`func (o *GithubRepositorypermissions) GetPull() bool`

GetPull returns the Pull field if non-nil, zero value otherwise.

### GetPullOk

`func (o *GithubRepositorypermissions) GetPullOk() (*bool, bool)`

GetPullOk returns a tuple with the Pull field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.

### SetPull

`func (o *GithubRepositorypermissions) SetPull(v bool)`

SetPull sets Pull field to given value.

### HasPull

`func (o *GithubRepositorypermissions) HasPull() bool`

HasPull returns a boolean if a field has been set.

### GetClass

`func (o *GithubRepositorypermissions) GetClass() string`

GetClass returns the Class field if non-nil, zero value otherwise.

### GetClassOk

`func (o *GithubRepositorypermissions) GetClassOk() (*string, bool)`

GetClassOk returns a tuple with the Class field if it's non-nil, zero value otherwise
and a boolean to check if the value has been set.

### SetClass

`func (o *GithubRepositorypermissions) SetClass(v string)`

SetClass sets Class field to given value.

### HasClass

`func (o *GithubRepositorypermissions) HasClass() bool`

HasClass returns a boolean if a field has been set.

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
#import <UIKit/UIKit.h>
#import "CommonUtil.h"
#import "PreferenceProvider.h"
#import "Common.h"
#import "NSString+EnumParser.h"

@interface AlarmCell : UITableViewCell
{
    __weak IBOutlet UIImageView *alarmIcon;
    __weak IBOutlet UILabel *alarmDec;
    __weak IBOutlet UILabel *alarmDate;
    __weak IBOutlet UIView *newIconView;
    __weak IBOutlet UIImageView *imageAccView;
    __weak IBOutlet UIImageView *checkView;

}

- (void)setAlarmCell:(GetNotification*)alarmInfo isDeleteMode:(BOOL)isDeleteMode;
@end


text:
class CreateFrogs < ActiveRecord::Migration
  def change
    create_table :frogs do |t|
      t.string :name
      t.string :color
      t.belongs_to :pond

      t.timestamps null: false
    end
  end
end


text: from zendesk.client import Client


text:
widget Name : {{vm.title}}

<button ng-click="vm.setFormData()">SetForm</button>


text:
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('donate-banner', 'Integration | Component | donate banner', {
  integration: true
});

test('it renders', function(assert) {

    this.set('testDate', new Date(2017, 7, 7));

    this.render(hbs`{{donate-banner currentDate=testDate}}`);

    assert.equal(this.$('div').attr('style'), 'display:""');

});

test('does not show', function(assert) {

    this.set('testDate', new Date(2017, 5, 7));

    this.render(hbs`{{donate-banner currentDate=testDate}}`);

    assert.equal(this.$('div').attr('style'), 'display:none');

});


text:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.SortedSet;
import java.util.TreeSet;
/**
 * The program will read in one or more sorted .txt file from user
 * and merge them while keeping the sorted order.
 * The result will be printed to standard output.
 *
 * Usage:
 * For standard output, type
 *   java MergeFile f1.txt [f2.txt] [f3.txt] ...
 *
 * To redirect output to output.txt, type
 *   java MergeFile f1.txt [f2.txt] [f3.txt] ... > output.txt
 *
 * NOTE: if unsorted file (input.txt) is detected, the program
 * will sort the file and output a new file named sorted-input.txt
 * Please use the output file as arguments for program execution
 * Also, note that the program uses string comparator to do the sorting.
 * Integers in the file will be read as strings
 *
 * @author jinglu
 *
 */

public class MergeFile {
	//size to split
	private static int splitSize = 100000;
	public static void main(String[] args) throws Exception{
		//list to store file names
		List<String> files = new ArrayList<String>();
		//check command line arguments
		//if no arguments, print instructions
		if(args.length < 1){
			programInfo();
		}else{
			//read file names into list
			for(int i=0; i<args.length; i++){
			   File f = new File(args[i]);
			   if(f.exists()){
			      files.add(f.getAbsolutePath());
			   //if user-specified file doesn't exist,
			   //print error message and exit
			   }else{
			   	  System.out.println("Input file [" + args[i] + "] not found in current directory.");
			   	  System.exit(1);
			   }
			}
		}
		mergeFile(files);
	}

    /**
     * Merge the files in the list while maintaining the sorted order
     *
     */
	public static void mergeFile(List<String> files) throws Exception{
		int fileNum = 1;
		//sorted set to rank files using comparator
		SortedSet<MyFile> fSet = new TreeSet<MyFile>(new MyFileComparator());
		//construct MyFile object for each file in the list
		for(int i=0; i<files.size(); i++){
			File f = new File(files.get(i));
			BufferedReader reader = new BufferedReader(new FileReader(f));
			MyFile myFile = new MyFile();
			//increment fileNum each time
			myFile.setFileNum(fileNum);
			fileNum ++;
			myFile.setReader(reader);
			//set currVal of myFile to be the first elment in the file
			String currVal = reader.readLine();
			//only add file to set if it is not empty
			if(currVal != null){
				myFile.setCurrVal(currVal);
				myFile.setCurrLine(1);
				fSet.add(myFile);
			}
		}

        //use a queue to store output
		Queue<String> valSet = new LinkedList<String>();
		while(!fSet.isEmpty()){
			//get the file with first rank
			MyFile currFile = fSet.first();
			valSet.add(currFile.getCurrVal());
			//if queue gets too large,
			//print the contents to standard output and clear the queue
	        if(valSet.size() >= splitSize){
	        	 stdWrite(valSet);
                 valSet.clear();
	        }
	        //clone a new file
	        MyFile nextFile = currFile.clone();

	        //remove currFile from the set
	        fSet.remove(currFile);
            //if this file still has data to read
            //add nextFile to set
            //and the set will re-rank the files
            int cond = nextFile.nextVal();
	        if(cond == 1){
	        	fSet.add(nextFile);
	        }else if(cond == 0){
                String unsortedName = files.get(nextFile.getFileNum()-1);
                sortFile(unsortedName);
                unsortedName = unsortedName.substring(unsortedName.lastIndexOf("/")+1);
                System.out.println("----------NOTE-----------");
                System.out.println("DETECTED: " +  unsortedName + " is unsorted.");
                System.out.println("Sorted version of the file is output as sorted-" + unsortedName);
                System.out.println("Please use sorted-" + unsortedName + " as arguments for program execution");
                System.exit(1);
	        }

	     }
         //print rest contents in the queue to standard output
         stdWrite(valSet);
         valSet.clear();
	}

    /**
     * write results to standard output
     * @param queue containing partial results
     */
	public static void stdWrite(Queue<String> valSet){
		PrintWriter writer = new PrintWriter(System.out, true);
		Iterator<String> iter = valSet.iterator();
		while(iter.hasNext()){
			writer.println(iter.next());
		}
		writer.close();
	}

    /**
     * sort the file
     * @param file name of the file to be sorted
     * @return name of sorted file
     */
	public static void sortFile(String fileName) throws Exception{
		File f = new File(fileName);
		SortedSet<String> s = new TreeSet<String>();
		FileReader fRead = new FileReader(f);
		BufferedReader reader = new BufferedReader(fRead);
		//build name of output file
        String fName = fileName.substring(0,fileName.lastIndexOf("/")+1) + "sorted-" + fileName.substring(fileName.lastIndexOf("/")+1);
        String curr = reader.readLine();
        boolean isFirst = true;
        while(curr != null){
        	//skip empty lines
        	if(!curr.trim().isEmpty()){
        	   s.add(curr);
        	   if(s.size() >= splitSize){
	        	 writeOutput(s,fName,isFirst);
	        	 isFirst = false;
                 s.clear();
	           }
        	}
        	curr = reader.readLine();

        }
        reader.close();
        fRead.close();
        writeOutput(s, fName,isFirst);
	}

    /**
     * write contents of set into a file
     * @param set containing elements to be writter
     * @param name of output file
     */
	public static void writeOutput(SortedSet<String> s, String fileName, boolean isFirst) throws Exception{
		File output = new File(fileName);
		//delete file if it is previously exists
		if(output.exists() && isFirst){
			output.delete();
		}
		if(!output.exists()){
		   output.createNewFile();
		}
		FileWriter fWriter = new FileWriter(output, true);
		BufferedWriter writer = new BufferedWriter(fWriter);
		Iterator<String> iter = s.iterator();
		while(iter.hasNext()){
			writer.write(iter.next());
			writer.newLine();
		}
		writer.flush();
		if(writer != null){
			writer.close();
		}
		if(fWriter != null){
			fWriter.close();
		}
	}

    /**
     * print instructions for the program
     */
	public static void programInfo(){
        System.out.println("---------------- Usage ---------------------");
		System.out.println("To execute the program, type");
		System.out.println("   java MergeFile f1.txt f2.txt f3.txt ... ");
		System.out.println();
		System.out.println("To redirect output to file, type ");
		System.out.println("   java MergeFile f1.txt [f2.txt] ... > output.txt ");
		System.out.println();
		System.out.println("NOTE: If unsorted file is detected, the program will output");
		System.out.println("a sorted version of the file and please use the output file");
		System.out.println("as arguments for program execution");
	}

}

/**
 * The MyFile object extracts important information
 * from the input file.
 */
class MyFile {
	private int fileNum;
	private int currLine = 0;
	private String currVal;
	private BufferedReader reader;

    /**
     * get file number
     * @return file number
     */
    public int getFileNum(){
    	return this.fileNum;
    }

    /**
     * set file number
     * @param file number
     */
    public void setFileNum(int fileNum){
    	this.fileNum = fileNum;
    }

    /**
     * get current line number
     * @return current line number
     */
    public int getCurrLine(){
    	return this.currLine;
    }

    /**
     * set current line number
     * @param current line number
     */
    public void setCurrLine(int currLine){
    	this.currLine = currLine;
    }

    /**
     * get current element it is reading
     * @return current element
     */
    public String getCurrVal(){
    	return this.currVal;
    }

    /**
     * set current-reading element
     * @param current element
     */
    public void setCurrVal(String currVal){
    	this.currVal = currVal;
    }

    /**
     * get BufferedReader for the file
     * @return bufferedreader
     */
    public BufferedReader getReader(){
    	return this.reader;
    }

    /**
     * set BufferedReader for the file
     * @param buffered reader
     */
    public void setReader(BufferedReader reader){
    	this.reader = reader;
    }

    /**
     * clone a new file using myFile
     * @return cloned file
     */
    public MyFile clone(){
    	MyFile cloneFile = new MyFile();
        cloneFile.setFileNum(getFileNum());
        cloneFile.setCurrLine(getCurrLine());
        cloneFile.setCurrVal(getCurrVal());
        cloneFile.setReader(getReader());
        return cloneFile;
    }

    /**
     * read next element in the file and update currVal
     * @return 1 if successfully read a new element
     *         -1 if we reach the end of the file
     *         0 if unsorted file detected
     */
	public int nextVal() throws Exception{
		String readVal = this.reader.readLine();
		//if some empty lines exist between the words in the file
		//skip the empty lines
		while(readVal!=null && readVal.trim().isEmpty()){
			readVal = this.reader.readLine();
			this.currLine ++;
		}
		if(readVal != null){
			if(this.currVal.compareTo(readVal) > 0){
				return 0;
			}
			this.currVal = readVal;
			this.currLine ++;
			return 1;
		}else{
			this.reader.close();
			return -1;
		}
	}

    /**
     * get file information
     * @return file info
     */
	public String toString(){
		String info = "FileNum: " + getFileNum() + "; ";
		info += "CurrLine: " + getCurrLine() + "; ";
		info += "CurrVal: " + getCurrVal() + ".";
		return info;
	}

}

/**
 * Comparator for MyFile object
 *
 * Compare currently-reading element of two files
 * If two elements are the same, compare by file number
 */
class MyFileComparator implements Comparator<MyFile>{
    public int compare(MyFile f1, MyFile f2){
    	String v1 = f1.getCurrVal();
    	String v2 = f2.getCurrVal();
    	if(v1.compareTo(v2) != 0){
    		return v1.compareTo(v2);
    	}else{
    		return f1.getFileNum() - f2.getFileNum();
    	}
    }
}


text:
title: Hpku-Teman Belajarku - Mentoring 13 September 2012
date: 2012-09-13
categories:
- laporan
- mentoring
- Hpku-Teman Belajarku
---

     Dari Ali Sahbana ke Heru Tjatur via surel dengan subyek: Laporan Naratif untuk Program HPku Teman Belajarku

Salam Mas Tjatur, dan Tim Pengawas CMB

Berikut kami sampaikan laporan Hpku Teman Belajarku dari 1000guru Kediri periode Januari s/d Agustus 2012, atas saran dan masukannya kami sampaikan terimakasih yang sebesar-besarnya.

Hormat Kami

Ali Sahbana


text:
package _02_rasSpecificPapers;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import _02_rasSpecificPapers.S03_TranslateKefedModelsToFrames.Options;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import edu.isi.bmkeg.kefed.utils.json.JsonKefedModel;
import edu.isi.bmkeg.kefed.utils.json.KefedFieldValueTemplate;
import edu.isi.bmkeg.kefed.utils.json.KefedObject;
import edu.isi.bmkeg.utils.Converters;

/**
 * This script runs through serialized JSON files from the model and converts
 * them to VPDMf KEfED models, including the data.
 *
 * @author Gully
 *
 */
public class S04_TranslateKefedModelsInDirectoryToFrames {

	public static class Options {

		@Option(name = "-jsonDir", usage = "KEfED Directory", required = true, metaVar = "KEFED_MODEL")
		public File kefedDir;

	}

	private static Logger logger = Logger
			.getLogger(S03_TranslateKefedModelsToDumpFiles.class);

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {

		Options options = new Options();

		CmdLineParser parser = new CmdLineParser(options);

		try {

			parser.parseArgument(args);

			Pattern patt = Pattern.compile("\\.json");
			Map<String, File> files = Converters.recursivelyListFiles(options.kefedDir, patt);
			for(File f: files.values()) {
				if(f.getName().endsWith( "_frame.json") ) {
					f.delete();
				}
			}

			files = Converters.recursivelyListFiles(options.kefedDir, patt);
			for(File f: files.values()) {

				String newPath = f.getPath().replace(".json", "_frame.json");

				String[] args2 = new String[] {
						"-jsonKefedFile", f.getPath(),
						"-frameFile", newPath
						};
				S03_TranslateKefedModelsToFrames.main(args2);

			}

		} catch (CmdLineException e) {

			System.err.println(e.getMessage());
			System.err.print("Arguments: ");
			parser.printSingleLineUsage(System.err);
			System.err.println("\n\n Options: \n");
			parser.printUsage(System.err);
			System.exit(-1);

		} catch (Exception e2) {

			e2.printStackTrace();

		}

	}

	private JsonKefedModel readJsonKefedModel(File kefedFile)
			throws Exception {

		BufferedReader in = new BufferedReader(new FileReader(kefedFile));

		StringBuilder sb = new StringBuilder();

		String inputLine;
		while ((inputLine = in.readLine()) != null) {
			sb.append(inputLine + "\n");
			// System.out.println(inputLine);
		}
		in.close();

		String kefedJson = sb.toString();

		List<JsonKefedModel> list = new ArrayList<JsonKefedModel>();

		Gson gson = new Gson();
		JsonParser parser = new JsonParser();
		JsonObject json = parser.parse(kefedJson).getAsJsonObject();

		JsonKefedModel model = gson.fromJson(json, JsonKefedModel.class);

		return model;

	}

	private Set<Entry<String, JsonElement>> readJsonKefedData(File kefedFile)
			throws Exception {

		BufferedReader in = new BufferedReader(new FileReader(kefedFile));

		StringBuilder sb = new StringBuilder();

		String inputLine;
		while ((inputLine = in.readLine()) != null) {
			sb.append(inputLine + "\n");
			// System.out.println(inputLine);
		}
		in.close();

		String kefedJson = sb.toString();

		List<JsonKefedModel> list = new ArrayList<JsonKefedModel>();

		Gson gson = new Gson();
		JsonParser parser = new JsonParser();
		JsonObject json = parser.parse(kefedJson).getAsJsonObject();

		JsonObject data = json.get("experimentData").getAsJsonObject();

		return data.entrySet();

	}

	private String clean(String s) {

		s = s.replaceAll("\\n", " ");
		s = s.replaceAll("\\r", " ");
		s = s.replaceAll("\\s+$", "");
		s = s.replaceAll("\\s*\\(.*\\)\\s*$", "");
		s = s.replaceAll("-\\s*\\d+\\s*$", "");
		s = s.replaceAll("\\s+\\d+\\s*$", "");

		return s;

	}

}


text:
namespace Snippets4.UnitTesting
{
    using System;
    using NServiceBus;
    using NServiceBus.Testing;

    public class Unobtrusive
    {
        public class Setup
        {
            public Setup()
            {
                #region SetupConventionsForUnitTests
                MessageConventionExtensions.IsMessageTypeAction = MyMessageTypeConvention;

                Test.Initialize();
                #endregion
            }

            bool MyMessageTypeConvention(Type arg)
            {
                return true;
            }
        }
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package sistema_escolar.repository;

import java.util.List;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import sistema_escolar.qualifier.MyDatabase;
import sistema_escolar.model.Aluno;
import sistema_escolar.model.Serie;

/**
 *
 * @author Vitor Freitas
 */
public class AlunoRepository extends AbstractRepository<Long, Aluno>
{
    @Inject @MyDatabase
    private EntityManager manager;

    @Override
    public List<Aluno> getAll()
    {
        return manager.createNamedQuery(Aluno.GET_ALL).getResultList();
    }

    @Override
    public List<Aluno> getAllLazyLoad(int startingAt, int maxPerPage)
    {
        return (List<Aluno>) manager.createNamedQuery(Aluno.GET_ALL)
                .setFirstResult(startingAt)
                .setMaxResults(maxPerPage)
                .getResultList();
    }

    public List<Aluno> getAllBySerieWithoutTurma(Serie serie)
    {
        try
        {
            return getByRestriction(Aluno.GET_ALL_BY_SERIE_WITHOUT_TURMA, "serie"
                , serie);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }

    }
}


text:
@class APCSchedule, APCScheduledTask;

@interface APCTask : NSManagedObject

@property (nonatomic, retain) NSDate * createdAt;
@property (nonatomic, retain) NSString * sortString;
@property (nonatomic, retain) NSString * taskClassName;
@property (nonatomic, retain) NSString * taskCompletionTimeString;
@property (nonatomic, retain) NSString * taskContentFileName;
@property (nonatomic, retain) NSData * taskDescription;
@property (nonatomic, retain) NSString * taskHRef;
@property (nonatomic, retain) NSString * taskID;
@property (nonatomic, retain) NSNumber * taskIsOptional;
@property (nonatomic, retain) NSString * taskTitle;
@property (nonatomic, retain) NSNumber * taskVersionNumber;
@property (nonatomic, retain) NSDate * updatedAt;
@property (nonatomic, retain) NSSet *scheduledTasks;
@property (nonatomic, retain) NSSet *schedules;
@end

@interface APCTask (CoreDataGeneratedAccessors)

- (void)addScheduledTasksObject:(APCScheduledTask *)value;
- (void)removeScheduledTasksObject:(APCScheduledTask *)value;
- (void)addScheduledTasks:(NSSet *)values;
- (void)removeScheduledTasks:(NSSet *)values;

- (void)addSchedulesObject:(APCSchedule *)value;
- (void)removeSchedulesObject:(APCSchedule *)value;
- (void)addSchedules:(NSSet *)values;
- (void)removeSchedules:(NSSet *)values;

@end


text:
Tamara's Astro Tools

This is a place I'll try to upload useful snippets of code as I make them.


text:
package daemon

import (
	"io"
	"runtime"

	"github.com/docker/docker/image/tarexport"
	"github.com/docker/docker/pkg/system"
)

// ExportImage exports a list of images to the given output stream. The
// exported images are archived into a tar when written to the output
// stream. All images with the given tag and all versions containing
// the same tag are exported. names is the set of tags to export, and
// outStream is the writer which the images are written to.
func (daemon *Daemon) ExportImage(names []string, outStream io.Writer) error {
	// TODO @jhowardmsft LCOW. This will need revisiting later.
	platform := runtime.GOOS
	if platform == "windows" && system.LCOWSupported() {
		platform = "linux"
	}
	imageExporter := tarexport.NewTarExporter(daemon.stores[platform].imageStore, daemon.stores[platform].layerStore, daemon.stores[platform].referenceStore, daemon)
	return imageExporter.Save(names, outStream)
}

// LoadImage uploads a set of images into the repository. This is the
// complement of ImageExport.  The input stream is an uncompressed tar
// ball containing images and metadata.
func (daemon *Daemon) LoadImage(inTar io.ReadCloser, outStream io.Writer, quiet bool) error {
	// TODO @jhowardmsft LCOW. This will need revisiting later.
	platform := runtime.GOOS
	if platform == "windows" && system.LCOWSupported() {
		platform = "linux"
	}
	imageExporter := tarexport.NewTarExporter(daemon.stores[platform].imageStore, daemon.stores[platform].layerStore, daemon.stores[platform].referenceStore, daemon)
	return imageExporter.Load(inTar, outStream, quiet)
}


text:
<?php

return array(
    'controllers' => array(
        'invokables' => array(
            'WS\Controller\Index' => 'WS\Controller\IndexController',
            'WS\Controller\Cliente' => 'WS\Controller\ClienteController',
        ),
    ),
    'router' => array(
        'routes' => array(
            'services' => array(
                'type'    => 'Literal',
                'options' => array(
                    // Change this to something specific to your module
                    'route'    => '/services',
                    'defaults' => array(
                        // Change this value to reflect the namespace in which
                        // the controllers for your module are found
                        '__NAMESPACE__' => 'WS\Controller',
                        'controller'    => 'Index',
                        'action'        => 'index',
                    ),
                ),
                'may_terminate' => true,
                'child_routes' => array(
                    // This route is a sane default when developing a module;
                    // as you solidify the routes for your module, however,
                    // you may want to remove it and replace it with more
                    // specific routes.
                    'default' => array(
                        'type'    => 'Segment',
                        'options' => array(
                            'route'    => '/[:controller[/:action]]',
                            'constraints' => array(
                                'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
                                'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
                            ),
                            'defaults' => array(
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),
    'view_manager' => array(
        'template_path_stack' => array(
            'WS' => __DIR__ . '/../view',
        ),
    ),/*'strategies' => array(
            'ViewJsonStrategy',
        ),*/
);


text:
var TestHelper = module.exports = require('./helper');

var fs = require('fs');

TestHelper.insertCSS('diagram-js.css', fs.readFileSync(__dirname + '/../assets/diagram-js.css', 'utf8'));

TestHelper.insertCSS('diagram-js-testing.css',
  '.test-container .result { height: 500px; }' + '.test-container > div'
);


text:
<?php

namespace Mailvan\Tests\Core;

use Mailvan\Core\ClientFactory;

/**
 * Class ClientFactoryTest
 * @package Mailvan\Test\Core
 *
 * @group Client
 * @covers \Mailvan\Core\ClientFactory
 */
class ClientFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldCreateFactoryWithDefaultConfig()
    {
        $factory = new ClientFactory();
    }
}


text:
/**
 * @class Flags
 * @constructor
 * @param {Array} newFlags Optional array of flag keys to define when the flags module is instantiated
 */
/*global module,define*/
var Flags = function( newFlags ){
    this.flags = 0;
    this.flagHash = {};
    this.keys = 0;
    if(newFlags){
        this.newFlags(newFlags);
    }
};

Flags.prototype = (function(){
    /*jshint curly:false */
    /**
     * An object representing the public attributes and methods of the flags object
     *
     * @type {Object}
     */
    var _public = {};

    /**
     * A function for registering a single flag
     *
     * @param  {String} name The name of the flag to be created
     */
    var createFlag = function( name ){
        if(this.flagHash[name]) return this.flagHash[name];
        if(this.keys === 32) throw 'a single instance of the flag module can only hold 32 flags. Try instantiating a second copy of the flag object';
        this.flagHash[name] = Math.pow(2, this.keys);
        this.keys += 1;
    };

    /**
     * Adds a single flag to the user object
     *
     * @param {String} name The name of the flag to add to the user
     */
    var addFlag = function( name ){
        if( !this.flagHash[name] ) throw name + "is not a valid flag. Make sure you created it with the newFlag function";

        if(this.flags & this.flagHash[name]) return;

        this.flags += this.flagHash[name];
    };

    /**
     * Removes a single flag from the user
     *
     * @param  {String} name The name of the flag to be removed
     */
    var removeFlag = function( name ){
        if( !this.flagHash[name] ) throw name + "is not a valid flag. Make sure you created it with the newFlag function";

        if(!(this.flags & this.flagHash[name])) return;

        this.flags -= this.flagHash[name];
    };

    /**
     * Creates a mask based on an array of keys
     *
     * @param  {Array}  flags An array of flag keys to be converted to a mask
     * @return {Number}       A number mask representing the specified flags
     */
    var createMask = function( flags ){
        var mask = 0;
        for(var f in flags){
            if (flags.hasOwnProperty(f)){
                if( !this.flagHash[flags[f]] ) throw flags[f] + " is not a valid flag. Make sure you created it with the newFlag function";

                mask += this.flagHash[flags[f]];
            }
        }

        return mask;
    };

    /**
     * Tests whether the user's flags match the input criteria
     *
     * @param  {Number}  mask    A filter representing the keys to check the user's flags against
     * @param  {Boolean} all     Whether or not this function is checking against 'all' or 'any' of the keys
     * @param  {Boolean} inverse Whether to check if the user has the properties or does not have the properties
     * @return {Boolean}         Whether the user's flags match the input criteria
     */
    var flagTest = function( mask, all, inverse ){
        var flagMask = (typeof mask === "number") ? mask : (typeof mask === "string") ? this.flagHash[mask] : createMask.call(this, mask);
        var ret = false;

        if(all){
            ret = ((this.flags & flagMask) === flagMask) ? true : false;
        } else {
            ret = (this.flags & flagMask) ? true : false;
        }

        if (inverse){
            ret = !ret;
        }

        return ret;
    };

    /**
     * Creates new possible flags
     *
     * @method newFlags
     * @param  {[String]} flags A string representing a possible flag
     * @param  {[Array]}  flags An array of strings representing possible flags
     * @return {Flags}          Returns self for chaining
     */
    _public.newFlags = function( flags ){
        if(typeof flags === 'string'){
            createFlag.call(this, flags);
        } else {
            for(var flag in flags){
                if (flags.hasOwnProperty(flag)){
                    createFlag.call(this, flags[flag]);
                }
            }
        }
        return this;
    };

    /**
     * Returns a mask with a given array of flags. Used primarily for debugging
     *
     * @example
     * Util.Flag.newFlags(['cat', 'dog', 'bat']);
     * Util.Flag._createMask(['cat, dog']); // 3
     *
     * @method _createMask
     * @param  {Array}  flags An array of flag key strings
     * @return {Number}       An integer representing the mask created my those options
     */
    _public._createMask = function( flags ){
        return createMask.call(this, flags);
    };

    /**
     * Checks to see if the user has any of the described flags
     *
     * @method hasAny
     * @param  {[String]} mask A string representing a flag to check
     * @param  {[Number]} mask A number mask
     * @param  {[Array]}  mask An array of flag key strings to be checked
     * @return {Boolean}       A boolean representing whether the user has any of the specified flags
     */
    _public.hasAny = function( mask ){
        return flagTest.call(this, mask, false, false);
    };

    /**
     * Checks to see if the user has all of the specified flags
     *
     * @method hasAllOf
     * @param  {[String]} mask A string representing a flag to check
     * @param  {[Number]} mask A number mask
     * @param  {[Array]}  mask An array of flag key strings to be checked
     * @return {Boolean}       A boolean representing whether the user has any of the specified flags
     */
    _public.hasAllOf = function( mask ){
        return flagTest.call(this, mask, true, false);
    };

    /**
     * Checks to see if the user has all of the flags that have been defined
     *
     * @method all
     * @return {Boolean} A boolean representing whether the user has all the defined flags
     */
    _public.all = function(){
        var flagTotal = Math.pow(2, this.keys) - 1;
        if(this.flags === flagTotal){
            return true;
        }
        return false;
    };

    /**
     * Checks to see if the user does not have any of the specified flags
     * This method will return `true` if the user *does not* have **any** of the specified flags
     *
     * @method notAny
     * @param  {[String]} mask A string representing a flag to check
     * @param  {[Number]} mask A number mask
     * @param  {[Array]}  mask An array of flag key strings to be checked
     * @return {Boolean}       A boolean representing whether the user has any of the specified flags
     */
    _public.notAny = function( mask ){
        return flagTest.call(this, mask, false, true);
    };

    /**
     * Checks to see if the user does not have all of a set of specified flags
     * This method will only return `true` if the user *does not* have **all** of the specified flags
     *
     * @method notAllOf
     * @param  {[String]} mask A string representing a flag to check
     * @param  {[Number]} mask A number mask
     * @param  {[Array]}  mask An array of flag key strings to be checked
     * @return {Boolean}       A boolean representing whether the user has any of the specified flags
     */
    _public.notAllOf = function( mask ){
        return flagTest.call(this, mask, true, true);
    };

    /**
     * Checks to see if the user has *any* flags defined
     * This method will return true only if the user has **no** flags set
     *
     * @method none
     * @return {Boolean} A boolean representing whether the user has no set flags
     */
    _public.none = function(){
        if(this.flags === 0){
            return true;
        }
        return false;
    };

    /**
     * Converts the user's flags back into their keys. Returns an array of flags that
     * have been set on the user
     *
     * @method parseFlags
     * @return {Array} An array of flags set on the user
     */
    _public.parseFlags = function(){
        var aFromFlags = [];
        for(var key in this.flagHash){
            if (this.flagHash.hasOwnProperty(key)){
                if(this.flags & this.flagHash[key]){
                    aFromFlags.push(key);
                }
            }
        }
        return aFromFlags;
    };

    /**
     * Converts the current state of the flag object into a javascript object with the
     * flag keys as the keys and true or false as the value. This method also allows the
     * flag object to interact correctly with JSON methods
     *
     * @example
     *     JSON.stringify(flag);
     *     flag.toJSON();
     *
     * @method toJSON
     * @return {Object} An object representing the current state of the flags object
     */
    _public.toJSON = function(){
        var oFromFlags = {};
        for(var key in this.flagHash){
            if (this.flagHash.hasOwnProperty(key)){
                oFromFlags[key] = (this.flags & this.flagHash[key]) ? true : false;
            }
        }

        return oFromFlags;
    };

    /**
     * Sets a flag as true on the user
     *
     * @todo   merge this and the remove method for a mor DRY implementation
     * @method add
     * @param  {[String]} flags A flag key string to be set on the user
     * @param  {[Array]}  flags An array of flag key strings to be set on the user
     * @return {Flags}          Self reference for chaining
     */
    _public.add = function(flags) {
        if (typeof flags === 'string') {
            addFlag.call(this, flags);
        } else {
            for (var flag in flags) {
                if (flags.hasOwnProperty(flag)) {
                    addFlag.call(this, flags[flag]);
                }
            }
        }

        return this;
    };

    /**
     * Sets a flag as false on the user
     *
     * @method remove
     * @param  {[String]} flags A flag key string to be set on the user
     * @param  {[Array]}  flags An array of flag key strings to be set on the user
     * @return {Flags}          Self reference for chaining
     */
    _public.remove = function(flags) {
        if (typeof flags === 'string') {
            removeFlag.call(this, flags);
        } else {
            for (var flag in flags) {
                if (flags.hasOwnProperty(flag)) {
                    removeFlag.call(this, flags[flag]);
                }
            }
        }

        return this;
    };

    /**
     * Resets the flags currently set to the specified mask
     *
     * @method reset
     * @param  {Number} flags A mask representing the flags to reset the state to
     * @param  {String} flags Resets the currently set flags, delegates to the add function
     * @param  {Array}  flags Resets the currently set flags, delegates to the add function
     * @return {Flags}        Returns self for chaning;
     */
    _public.reset = function(flags){
        var flagTotal = Math.pow(2, this.keys) - 1;

        if(typeof flags !== 'number'){
            this.flags = 0;
            return this.add(flags);
        }

        if(flags <= flagTotal){
            this.flags = flags;
        } else {
            throw flags + ' is not a valid flag mask. Please make sure all your flags are defined';
        }

        return this;
    };

    _public.unregister = function(){
        this.keys = 0;
        this.flagHash = {};
        this.flags = 0;
    };

    return _public;
}());

// Expose module to AMD and Node systems
if(typeof define === 'function' && define.amd){
    define('flags', [], function(){
        return Flags;
    });
} else if (typeof exports !== 'undefined'){
    module.exports = Flags;
}


text:
int kqueue_init(struct queue *queue, unsigned int size, unsigned int item_size)
{
	int ret = 0;

	if (!queue) {
		ret = -EINVAL;
		goto err;
	}

	queue->item_queued = 0;
	queue->size = size;
	queue->item_size = item_size;

	queue->head = (unsigned int *)kmalloc(size * item_size);
	if (!queue->head) {
		ret = -ENOMEM;
		goto err;
	}

	queue->curr = queue->head;
	queue->wr = queue->head;
	queue->tail = queue->head + (size * item_size);

	wait_queue_init(&queue->wait_receive);
	wait_queue_init(&queue->wait_post);

	trace_queue_create(queue, item_size, size);

err:
	return ret;
}

int kqueue_clear(struct queue *queue)
{
	int ret = 0;

	if (!queue) {
		ret = -EINVAL;
		goto err;
	}

	queue->item_queued = 0;
	queue->wr = queue->head;
	queue->curr = queue->head;

	trace_queue_clear(queue);

err:
	return ret;
}

int kqueue_destroy(struct queue *queue)
{
	int ret = 0;

	if (!queue) {
		ret = -EINVAL;
		goto err;
	}

	kfree(queue->head);

err:
	return ret;
}

int kqueue_update(struct queue *queue, unsigned int size, unsigned int item_size)
{
	int ret = 0;

	if (!queue) {
		ret = -EINVAL;
		goto err;
	}

	ret = kqueue_destroy(queue);
	if (ret < 0)
		goto err;

	ret = kqueue_init(queue, size, item_size);

	trace_queue_update(queue, item_size, size);

err:
	return ret;
}

static void _kqueue_post(struct queue *queue, void *item)
{
	thread_lock(state);

	if (queue->item_queued < queue->size) {
		if ((queue->wr + queue->item_size) <= queue->tail) {
			memcpy(queue->wr, item, queue->item_size);
			debug_printk("wr: %x, v: %d\r\n", queue->wr, *(int *)item);
			queue->wr += queue->item_size;
			queue->item_queued++;

			wait_queue_wake_irqstate(&queue->wait_receive, &state);
		}
	}

	thread_unlock(state);
}

int kqueue_post(struct queue *queue, void *item, unsigned int timeout)
{
	int ret = 0;
	int back_from_sleep = 0;

	if (!queue) {
		ret = -EINVAL;
		goto err;
	}

	trace_queue_send(queue, item);

	for (;;) {
		if (back_from_sleep) {
			break;
		} else if (queue->item_queued < queue->size) {
			_kqueue_post(queue, item);
			break;
		} else if (timeout) {
			return -ENOTSUP;
			ktime_usleep(timeout);
			back_from_sleep = 1;
		} else if (!timeout) {
			ret = -EAGAIN;
			break;
		}
	}

err:
	return ret;
}

static void _kqueue_receive(struct queue *queue, void *item)
{
	thread_lock(state);

	if (queue->item_queued) {
		if ((queue->curr + queue->item_size) <= queue->wr) {
			memcpy(item, queue->curr, queue->item_size);
			queue->curr += queue->item_size;
			queue->item_queued--;

			wait_queue_wake_irqstate(&queue->wait_post, &state);
		}

		if (queue->curr == queue->wr)
			kqueue_clear(queue);
	}

	thread_unlock(state);
}

int kqueue_receive(struct queue *queue, void *item, unsigned int timeout)
{
	int ret = 0;
	int back_from_sleep = 0;

	if (!queue) {
		ret = -EINVAL;
		goto err;
	}

	trace_queue_receive(queue, timeout);

	for (;;) {
		if (queue->item_queued) {
			_kqueue_receive(queue, item);
			break;
		} else if (timeout) {
			return -ENOTSUP;
			ktime_usleep(timeout);
			back_from_sleep = 1;
		} else if (back_from_sleep || !timeout) {
			ret = -EAGAIN;
			break;
		}
	}
err:
	return ret;
}