text:
#ifndef TRITONSORT_STAT_LOGGER_H
#define TRITONSORT_STAT_LOGGER_H

#include <map>
#include <queue>
#include <sstream>
#include <stdint.h>
#include <string>
#include <vector>

#include "core/LogLineDescriptor.h"
#include "core/StatContainerInterface.h"
#include "StatWriter.h"
#include "core/TritonSortAssert.h"

class LogDataContainer;
class Params;

/**
   Provides a convenient wrapper for logging unsigned integer statistics using
   stat containers that implement StatContainerInterface.
 */
class StatLogger {
private:
  typedef std::map<uint64_t, StatContainerInterface*> StatContainerMap;
  typedef StatContainerMap::iterator StatContainerMapIter;
  typedef StatContainerMap::const_iterator StatContainerMapConstIter;

public:
  /// Shorthand for a list of stat containers
  typedef std::list<StatContainerInterface*> StatContainerList;

  /// Shorthand for an iterator through a list of stat containers
  typedef StatContainerList::iterator StatContainerListIter;

  /// Shorthand for a const iterator through a list of stat containers
  typedef StatContainerList::const_iterator StatContainerListConstIter;

  /// Constructor
  /**
     \param loggerName a string name describing this logger
   */
  StatLogger(const std::string& loggerName);

  /// Constructor
  /**
     \param stageOrPoolName the name of the stage or resource pool using this
     StatLogger

     \param id the worker or pool id of the stage or resource pool using the
     logger
   */
  StatLogger(const std::string& stageOrPoolName, uint64_t id);

  /// Constructor
  /**
     StatLoggers constructed using this interface are used to log the
     interaction between a particular worker for a stage and a particular
     resource pool.

     \param stageName the name of the stage

     \param id the worker ID of the worker

     \param poolName the name of the pool

     \param poolNumber the pool ID of the pool
   */
  StatLogger(const std::string& stageName, uint64_t id,
             const std::string& poolName, uint64_t poolNumber);

  /// Destructor
  virtual ~StatLogger();

  /// Register a statistic with this stat logger
  /**
     Subsequent calls to StatLogger::add for the desired statistic must provide
     that statistic's ID.

     Caller is required to specify an ID distinct from all
     previously-registered IDs; not doing so will result in an exception.

     \param statName the name of this statistic

     \param threshold the smallest value for the statistic that will be
     recorded; statistics logged by StatLogger::add that fall below the
     threshold will not be logged individually, but will contribute to summary
     statistics

     \return the unique ID of this statistic, used in subsequent calls to
     StatLogger::add
   */
  uint64_t registerStat(const std::string& statName, uint64_t threshold = 0);

  /// Register a statistic with this stat logger
  /**
     Subsequent calls to StatLogger::add for the desired statistic must provide
     that statistic's ID.

     Caller is required to specify an ID distinct from all
     previously-registered IDs; not doing so will result in an exception.

     \param statName the name of this statistic

     \param threshold the smallest value for the timer's elapsed time that will
     be recorded; statistics logged by StatLogger::add that fall below the
     threshold will not be logged individually, but will contribute to summary
     statistics

     \return the unique ID of this statistic, used in subsequent calls to
     StatLogger::add
   */
  uint64_t registerTimerStat(const std::string& statName,
                             uint64_t threshold = 0);

  /// Register a statistic with this stat logger that is backed by a histogram
  /**
     Subsequent calls to StatLogger::add for the desired statistic must provide
     that statistic's ID.

     Caller is required to specify an ID distinct from all
     previously-registered IDs; not doing so will result in an exception.

     \param statName the name of this statistic

     \param binSize the size of the bins used by the histogram

     \return the unique ID of this statistic, used in subsequent calls to
     StatLogger::add
   */
  uint64_t registerHistogramStat(const std::string& statName, uint64_t binSize);

  /// Register a statistic with this stat logger for which you will only log
  /// summary statistics
  /**
     Subsequent calls to StatLogger::add for the desired statistic must provide
     that statistic's ID.

     Caller is required to specify an ID distinct from all
     previously-registered IDs; not doing so will result in an exception.

     \param statName the name of this statistic

     \return the unique ID of this statistic, used in subsequent calls to
     StatLogger::add
   */
  uint64_t registerSummaryStat(const std::string& statName);

  /// Add a value to the given statistic
  /**
     Any values that fall below the threshold provided at registration (see
     StatLogger::registerStat) will not be recorded.

     \param statID the unique ID of this statistic
     \param stat the statistic to log
   */
  void add(uint64_t statID, uint64_t stat);

  /// Add a value to the given statistic
  /**
     Any values that fall below the threshold provided at registration (see
     StatLogger::registerStat) will not be recorded.

     \param statID the unique ID of this statistic
     \param timer the timer whose start, end and elapsed times will be logged
   */
  void add(uint64_t statID, const Timer& timer);

  /// Log a datum
  /**
     A datum is a piece of information that is assumed to be logged
     infrequently (usually only once) and is meant to be stored in its raw form
     without any thresholding, aggregation, etc.

     \param statName a string name describing the datum

     \param datum the value of the datum to log
   */
  void logDatum(const std::string& statName, const std::string& datum);

  /// Log a datum
  /**
     A datum is a piece of information that is assumed to be logged
     infrequently (usually only once) and is meant to be stored in its raw form
     without any thresholding, aggregation, etc.

     \param statName a string name describing the datum

     \param datum the value of the datum to log
   */
  void logDatum(const std::string& statName, uint64_t datum);

  /// Log a datum
  /**
     A datum is a piece of information that is assumed to be logged
     infrequently (usually only once) and is meant to be stored in its raw form
     without any thresholding, aggregation, etc.

     \param statName a string name describing the datum

     \param datum the value of the datum to log
   */
  void logDatum(const std::string& statName, const Timer& datum);

private:
  uint64_t largestRegisteredStatID;

  LogLineDescriptor logLineDescriptor;

  uint64_t statLoggerID;

  StatContainerMap stats;
  StatContainerMap summaryStats;

  uint64_t nextStatPushTime;

  LogDataContainer* data;

  void init();

  /// \todo(AR) These constants should be configurable.
  inline void setNextStatPushTime() {
    nextStatPushTime = Timer::posixTimeInMicros() + 500000 +
      (lrand48() % 1000000);
  }

  template <typename T> void addStatToContainer(
    uint64_t statID, const T& stat) {

    StatContainerMapIter iter = stats.find(statID);

    ABORT_IF(iter == stats.end(), "No statistic with id %llu registered in "
             "this logger", statID);

    StatContainerInterface* statContainer = iter->second;
    statContainer->add(stat);

    iter = summaryStats.find(statID);

    if (iter != summaryStats.end()) {
      (iter->second)->add(stat);
    }

    // Push all stats if we're past the next stat push time
    if (Timer::posixTimeInMicros() > nextStatPushTime) {
      for (iter = stats.begin(); iter != stats.end(); iter++) {
        StatContainerInterface*& statContainer = iter->second;

        if (statContainer->isReadyForWriting()) {
          StatContainerInterface* emptyStatContainerCopy =
            statContainer->newEmptyCopy();

          StatWriter::addStatContainer(statContainer);
          statContainer = emptyStatContainerCopy;
        }
      }

      setNextStatPushTime();
    }
  }

  void addStatContainer(
    StatContainerInterface* container, const std::string& statName,
    bool createSummary);
};

#endif // TRITONSORT_STAT_LOGGER_H

redpajama_set_name: RedPajamaGithub


text:
package vtk.repository.systemjob;

import vtk.repository.SystemChangeContext;
import vtk.repository.Repository;

/**
 * A path selector interface. A path selector is an implementation that
 * selects a set of repository resource paths for a system job to work.
 * For each path, the provided {@link PathSelectCallback} should be invoked
 * once with the path.
 */
public interface PathSelector {

    /**
     * When invoked, the path selector will execute its selection process
     * and invoke the provided {@link PathSelectCallback} once for each
     * selected path, possibly using the provided repository and system change
     * context.
     *
     * @param repository a {@link Repository}
     * @param context a {@link SystemChangeContext}
     * @param callback instance of PathSelectCallback provided by client
     * code.
     * @throws Exception
     */
    public void selectWithCallback(Repository repository,
                                   SystemChangeContext context,
                                   PathSelectCallback callback) throws Exception;

}


text:
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';

export const Events = new Mongo.Collection('events');

Meteor.methods({
  'removeAllEvents' : function () {
    Events.remove({});
  },
  'resetAllEvents': function() {
    Events.remove({});
  }
});


text:
"""Support for Vallox ventilation units."""
from __future__ import annotations

from dataclasses import dataclass, field
from datetime import date
import ipaddress
import logging
from typing import Any, NamedTuple
from uuid import UUID

from vallox_websocket_api import PROFILE as VALLOX_PROFILE, Vallox
from vallox_websocket_api.exceptions import ValloxApiException
from vallox_websocket_api.vallox import (
    get_next_filter_change_date as calculate_next_filter_change_date,
    get_uuid as calculate_uuid,
)
import voluptuous as vol

from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_HOST, CONF_NAME, Platform
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.typing import ConfigType, StateType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed

from .const import (
    DEFAULT_FAN_SPEED_AWAY,
    DEFAULT_FAN_SPEED_BOOST,
    DEFAULT_FAN_SPEED_HOME,
    DEFAULT_NAME,
    DOMAIN,
    METRIC_KEY_PROFILE_FAN_SPEED_AWAY,
    METRIC_KEY_PROFILE_FAN_SPEED_BOOST,
    METRIC_KEY_PROFILE_FAN_SPEED_HOME,
    STATE_SCAN_INTERVAL,
)

_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
    vol.All(
        cv.deprecated(DOMAIN),
        {
            DOMAIN: vol.Schema(
                {
                    vol.Required(CONF_HOST): vol.All(ipaddress.ip_address, cv.string),
                    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
                }
            )
        },
    ),
    extra=vol.ALLOW_EXTRA,
)

PLATFORMS: list[str] = [
    Platform.SENSOR,
    Platform.FAN,
    Platform.BINARY_SENSOR,
]

ATTR_PROFILE_FAN_SPEED = "fan_speed"

SERVICE_SCHEMA_SET_PROFILE_FAN_SPEED = vol.Schema(
    {
        vol.Required(ATTR_PROFILE_FAN_SPEED): vol.All(
            vol.Coerce(int), vol.Clamp(min=0, max=100)
        )
    }
)

class ServiceMethodDetails(NamedTuple):
    """Details for SERVICE_TO_METHOD mapping."""

    method: str
    schema: vol.Schema

SERVICE_SET_PROFILE_FAN_SPEED_HOME = "set_profile_fan_speed_home"
SERVICE_SET_PROFILE_FAN_SPEED_AWAY = "set_profile_fan_speed_away"
SERVICE_SET_PROFILE_FAN_SPEED_BOOST = "set_profile_fan_speed_boost"

SERVICE_TO_METHOD = {
    SERVICE_SET_PROFILE_FAN_SPEED_HOME: ServiceMethodDetails(
        method="async_set_profile_fan_speed_home",
        schema=SERVICE_SCHEMA_SET_PROFILE_FAN_SPEED,
    ),
    SERVICE_SET_PROFILE_FAN_SPEED_AWAY: ServiceMethodDetails(
        method="async_set_profile_fan_speed_away",
        schema=SERVICE_SCHEMA_SET_PROFILE_FAN_SPEED,
    ),
    SERVICE_SET_PROFILE_FAN_SPEED_BOOST: ServiceMethodDetails(
        method="async_set_profile_fan_speed_boost",
        schema=SERVICE_SCHEMA_SET_PROFILE_FAN_SPEED,
    ),
}

@dataclass
class ValloxState:
    """Describes the current state of the unit."""

    metric_cache: dict[str, Any] = field(default_factory=dict)
    profile: VALLOX_PROFILE = VALLOX_PROFILE.NONE

    def get_metric(self, metric_key: str) -> StateType:
        """Return cached state value."""

        if (value := self.metric_cache.get(metric_key)) is None:
            return None

        if not isinstance(value, (str, int, float)):
            return None

        return value

    def get_uuid(self) -> UUID | None:
        """Return cached UUID value."""
        uuid = calculate_uuid(self.metric_cache)
        if not isinstance(uuid, UUID):
            raise ValueError
        return uuid

    def get_next_filter_change_date(self) -> date | None:
        """Return the next filter change date."""
        next_filter_change_date = calculate_next_filter_change_date(self.metric_cache)

        if not isinstance(next_filter_change_date, date):
            return None

        return next_filter_change_date

class ValloxDataUpdateCoordinator(DataUpdateCoordinator):
    """The DataUpdateCoordinator for Vallox."""

    data: ValloxState

async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up the integration from configuration.yaml (DEPRECATED)."""
    if DOMAIN not in config:
        return True

    hass.async_create_task(
        hass.config_entries.flow.async_init(
            DOMAIN,
            context={"source": SOURCE_IMPORT},
            data=config[DOMAIN],
        )
    )

    return True

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the client and boot the platforms."""
    host = entry.data[CONF_HOST]
    name = entry.data[CONF_NAME]

    client = Vallox(host)

    async def async_update_data() -> ValloxState:
        """Fetch state update."""
        _LOGGER.debug("Updating Vallox state cache")

        try:
            metric_cache = await client.fetch_metrics()
            profile = await client.get_profile()

        except (OSError, ValloxApiException) as err:
            raise UpdateFailed("Error during state cache update") from err

        return ValloxState(metric_cache, profile)

    coordinator = ValloxDataUpdateCoordinator(
        hass,
        _LOGGER,
        name=f"{name} DataUpdateCoordinator",
        update_interval=STATE_SCAN_INTERVAL,
        update_method=async_update_data,
    )

    await coordinator.async_config_entry_first_refresh()

    service_handler = ValloxServiceHandler(client, coordinator)
    for vallox_service, service_details in SERVICE_TO_METHOD.items():
        hass.services.async_register(
            DOMAIN,
            vallox_service,
            service_handler.async_handle,
            schema=service_details.schema,
        )

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
        "client": client,
        "coordinator": coordinator,
        "name": name,
    }

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a config entry."""
    if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
        hass.data[DOMAIN].pop(entry.entry_id)

        if hass.data[DOMAIN]:
            return unload_ok

        for service in SERVICE_TO_METHOD:
            hass.services.async_remove(DOMAIN, service)

    return unload_ok

class ValloxServiceHandler:
    """Services implementation."""

    def __init__(
        self, client: Vallox, coordinator: DataUpdateCoordinator[ValloxState]
    ) -> None:
        """Initialize the proxy."""
        self._client = client
        self._coordinator = coordinator

    async def async_set_profile_fan_speed_home(
        self, fan_speed: int = DEFAULT_FAN_SPEED_HOME
    ) -> bool:
        """Set the fan speed in percent for the Home profile."""
        _LOGGER.debug("Setting Home fan speed to: %d%%", fan_speed)

        try:
            await self._client.set_values(
                {METRIC_KEY_PROFILE_FAN_SPEED_HOME: fan_speed}
            )
            return True

        except (OSError, ValloxApiException) as err:
            _LOGGER.error("Error setting fan speed for Home profile: %s", err)
            return False

    async def async_set_profile_fan_speed_away(
        self, fan_speed: int = DEFAULT_FAN_SPEED_AWAY
    ) -> bool:
        """Set the fan speed in percent for the Away profile."""
        _LOGGER.debug("Setting Away fan speed to: %d%%", fan_speed)

        try:
            await self._client.set_values(
                {METRIC_KEY_PROFILE_FAN_SPEED_AWAY: fan_speed}
            )
            return True

        except (OSError, ValloxApiException) as err:
            _LOGGER.error("Error setting fan speed for Away profile: %s", err)
            return False

    async def async_set_profile_fan_speed_boost(
        self, fan_speed: int = DEFAULT_FAN_SPEED_BOOST
    ) -> bool:
        """Set the fan speed in percent for the Boost profile."""
        _LOGGER.debug("Setting Boost fan speed to: %d%%", fan_speed)

        try:
            await self._client.set_values(
                {METRIC_KEY_PROFILE_FAN_SPEED_BOOST: fan_speed}
            )
            return True

        except (OSError, ValloxApiException) as err:
            _LOGGER.error("Error setting fan speed for Boost profile: %s", err)
            return False

    async def async_handle(self, call: ServiceCall) -> None:
        """Dispatch a service call."""
        service_details = SERVICE_TO_METHOD.get(call.service)
        params = call.data.copy()

        if service_details is None:
            return

        if not hasattr(self, service_details.method):
            _LOGGER.error("Service not implemented: %s", service_details.method)
            return

        result = await getattr(self, service_details.method)(**params)

        # This state change affects other entities like sensors. Force an immediate update that can
        # be observed by all parties involved.
        if result:
            await self._coordinator.async_request_refresh()


text:
@class MISSING_TYPE;

@interface _TtC15IDESourceEditor23EditAssitantChangeFerry : _TtCs12_SwiftObject
{
    MISSING_TYPE *observed;
    MISSING_TYPE *destination;
    MISSING_TYPE *expressionRange;
    MISSING_TYPE *insertionsCount;
}

@end


text:
<TITLE>Review for Original Sin (2001)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Original Sin (2001)

reviewed by
Jerry Saravia

ORIGINAL SIN (2001)
Reviewed by Jerry Saravia
August 5th, 2001

While watching the over-exaggerated histrionics and sexual biplay of "Original
Sin," all I could think of was how much more I admire Stanley Kubrick's wildly
panned last hurrah, "Eyes Wide Shut." If you recall, "Eyes Wide Shut" was the
infamous film starring Tom Cruise and Nicole Kidman that dealt with jealousy in
a marriage and sexual innuendoes. Except for the de-eroticized orgy, most of
"Eyes Wide Shut" left sexual romps to the imagination. It was all done with
class, style and sophistication and left audiences puzzled and frustrated,
particularly since one was not privy to seeing Kidman and Cruise in their
birthday suits. "Original Sin" delivers on its promise of promiscuity, sex and
tons of nudity - yes, Angelina Jolie is naked throughout this film. And so is
the leading romantic star Antonio Banderas. And it is all about as sexy and
erotic as any episode of "Red Shoe Diaries."

Based on the novel "Waltz into Darkness" by Cornell Woolrich, the film begins
with a Cuban coffee planter, Luis Durand (Antonio Banderas), who is ready to
marry a mail-order bride. His interests are primarily lustful since he does not
believe in love ("Love is for those who believe in it.") Durand meets the bride
named Julia Russell (Angelina Jolie) although she looks nothing like the
photograph she sent him. This should be cause for alarm but Durand is, after
all, rather smitten (hey, it is Lara Croft after all!). They agree that they
can't trust each other since he told her he was a worker at a coffee plant, not
the owner.  What is striking about this scene is how lovingly composed it is.
Director Michael Cristofer ("Gia") takes a cue from Martin Scorsese's "The Age
of Innocence" by showing us Durand's subjective glances at the striking figure
of Julia, dissolving from shots of her hair, lips, eyes, hands, etc. After
seeing this sequence, I was convinced that Cristofer was g!
oing to rein us in on one heck o
f a full-blooded, passionate love story. Not so.

What starts as a sumptuous mood piece quickly degenerates into heavy,
over-the-top melodrama. Julia is not what she seems since she takes Durand's
money and splits. Durand is heartbroken, so much that he is ready to kill her
only to then realize he is actually ready to kill for her (?). He hires a
private investigator (Thomas Jane) to find her, though the investigator has
already been looking for her for reasons that should be obvious to anyone who
loves melodramas of this type. Revelations take place as does twists and turns,
all foreseeable if, again, you have not lived in a monastery for the last twenty
years. Oh, yes, but we do see Banderas and Jolie cavorting in the nude, in
high-angle, softly pornographic scenes that only made me yawn. To call this
eroticism is to forget what true eroticism is - consider the lovemaking scene
between Greta Scacchi and Tim Robbins in "The Player," which is as erotic as
they come. Even Bertolucci's "Last Tango in Paris" had a modicum of nud!
ity. The sex scenes in this film
 play like a Playfold centerfold with Jolie at its center - it is no different
than any soft-porno film you might catch late at night on HBO.

Perhaps "Original Sin" was meant to be melodramatic (I have not read the book
nor seen Truffaut's original film version) but it is so high-pitched complete
with a grating soundtrack of Spanish songs that it becomes a chore to sit
through. Banderas succeeds in making Durand a torn man and I do enjoy watching
Jolie, a stunning screen presence. They just do not have an iota of chemistry
and since the characters are so one-dimensional, it is hard to care about them.
Thomas Jane's role is crudely overdone and simply too cartoonish. The ending is
such a howler and so nearly parodic that the whole audience erupted in laughter.
"Original Sin" simply needed to be dialed down a bit for its own good.

For an analysis of Stanley Kubrick's EYES WIDE SHUT, go to
http://moviething.com/members/movies/faust/index5.shtml

For more reviews, check out JERRY AT THE MOVIES at
http://moviething.com/members/movies/faust/JATMindex.shtml

E-mail me with any questions, comments or general complaints at
faustus_08520@yahoo.com or at Faust668@aol.com

==========
X-RAMR-ID: 29074
X-Language: en
X-RT-ReviewID: 242693
X-RT-TitleID: 1109215
X-RT-SourceID: 875
X-RT-AuthorID: 1314

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
namespace content {

using DedicatedOrSharedWorkerToken =
    blink::MultiToken<blink::DedicatedWorkerToken, blink::SharedWorkerToken>;

// Holds information about a single service worker client:
// https://w3c.github.io/ServiceWorker/#client
class CONTENT_EXPORT ServiceWorkerClientInfo {
 public:
  ServiceWorkerClientInfo();
  explicit ServiceWorkerClientInfo(
      const blink::DedicatedWorkerToken& dedicated_worker_token);
  explicit ServiceWorkerClientInfo(
      const blink::SharedWorkerToken& shared_worker_token);
  explicit ServiceWorkerClientInfo(
      const DedicatedOrSharedWorkerToken& worker_token);

  ServiceWorkerClientInfo(const ServiceWorkerClientInfo& other);
  ServiceWorkerClientInfo& operator=(const ServiceWorkerClientInfo& other);

  ~ServiceWorkerClientInfo();

  // Returns the type of this client.
  blink::mojom::ServiceWorkerClientType type() const { return type_; }

  GlobalRenderFrameHostId GetRenderFrameHostId() const;
  void SetRenderFrameHostId(
      const GlobalRenderFrameHostId& render_frame_host_id);

  // Returns the corresponding DedicatedWorkerToken. This should only be called
  // if "type() == blink::mojom::ServiceWorkerClientType::kDedicatedWorker".
  blink::DedicatedWorkerToken GetDedicatedWorkerToken() const;

  // Returns the corresponding SharedWorkerToken. This should only be called
  // if "type() == blink::mojom::ServiceWorkerClientType::kSharedWorker".
  blink::SharedWorkerToken GetSharedWorkerToken() const;

 private:
  // The client type.
  blink::mojom::ServiceWorkerClientType type_;

  // For a window client.
  // Currently, there is a time lag between when ServiceWorkerClientInfo is
  // created and `render_frame_host_id_` is set.
  // TODO(asamidoi): Set GlobalRenderFrameHostId in the constructor of
  // ServiceWorkerClientInfo and remove SetRenderFrameHostId().
  GlobalRenderFrameHostId render_frame_host_id_;

  // The ID of the client, if it is a worker.
  absl::optional<DedicatedOrSharedWorkerToken> worker_token_;
};

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_SERVICE_WORKER_CLIENT_INFO_H_


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             tools:context="com.yuzhou.rss.ui.PreferenceFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginStart="10dp"
        android:orientation="vertical">

        <Button
            android:id="@+id/prefs__layout_title_only"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#fff"
            android:gravity="center|start"
            android:text="Title Only"/>

        <Button
            android:id="@+id/prefs__layout_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#fff"
            android:gravity="center|start"
            android:text="List"/>

        <Button
            android:id="@+id/prefs__layout_card"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#fff"
            android:gravity="center|start"
            android:text="Card"/>

    </LinearLayout>
</FrameLayout>


text:
<?php

/**
 * @file
 * Contains \Drupal\menu_ui\Tests\Migrate\MigrateMenuSettingsTest.
 */

namespace Drupal\menu_ui\Tests\Migrate;

use Drupal\migrate_drupal\Tests\d7\MigrateDrupal7TestBase;

/**
 * Tests migration of menu_ui settings.
 *
 * @group menu_ui
 */
class MigrateMenuSettingsTest extends MigrateDrupal7TestBase {

  public static $modules = ['menu_ui'];

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->installConfig(['menu_ui']);
    $this->executeMigration('menu_settings');
  }

  public function testMigration() {
    $this->assertTrue(\Drupal::config('menu_ui.settings')->get('override_parent_selector'));
  }

}


text:
/**
 * Check that the tested object is a spy that has been called once (and exactly
 * once) with expected arguments.
 *
 * @message
 *   Expect [actual] to have been called once but was called [count] time(s)
 *   Expect [actual] to have been called once but was called [count] time(s) with different arguments
 *
 * @example
 *   const spy = jasmine.createSpy('foo');
 *   expect(spy).not.toHaveBeenCalledOnce();
 *
 *   spy('foo');
 *   expect(spy).toHaveBeenCalledOnceWith('foo');
 *   expect(spy).not.toHaveBeenCalledOnceWith('bar');
 *
 * @param {Object} ctx Test context.
 * @param {...*} args Expected call arguments.
 * @return {Object} Test result.
 * @since 0.1.0
 */
export function toHaveBeenCalledOnceWith({actual, callCount, equals, argsFor, pp}, ...args) {
  const count = callCount(actual) || 0;
  const wasCalledOnce = count === 1;
  const ok = wasCalledOnce && equals(argsFor(actual, 0), args);
  const msg = wasCalledOnce && !ok ? ' with different arguments' : '';

  return {
    pass: ok,
    message() {
      return `Expect ${pp(actual)} {{not}} to have been called once but was called ${pp(count)} time(s)${msg}`;
    },
  };
}


text:
const redux = require('redux');
const tap = require('tap');

/**
 * mostly validating basic functionality with redux
 */

const INC = 'INC';
const DEC = 'DEC';
const SAME = 'SAME';
const INITIAL_STATE = {value: 0};
const state = (pState, action) => {
    var update = {};
    var value = pState ? pState.value : 0;
    update.value = value;

    switch (action.type) {
        case INC:
            update.value = ++value;
            break;

        case DEC:
            update.value = --value;
            break;

        case SAME:
            // do not change value -- a noop
            break;
    }

    return Object.assign({}, pState || INITIAL_STATE, update);
};

tap.test('redux', (reduxTap) => {

    reduxTap.test('initial state', (initialTap) => {
        const store = redux.createStore(state);

        var myState = store.getState();

        initialTap.isEqual(myState.value, 0, 'value starts at 0');

        initialTap.end();
    });

    reduxTap.test('INC', (INCtap) => {

        const store = redux.createStore(state);
        store.dispatch({type: INC});

        var myState = store.getState();

        INCtap.isEqual(myState.value, 1, 'value increments to 1');

        INCtap.end();
    });

    reduxTap.end();
});


text:
require 'spec_helper'

describe Status::Project, '#github_api_url' do
  let(:object)  { described_class.new(name, tags)                     }

  let(:name)    { 'mbj/rom-status'                                    }

  let(:tags)    { mock('tags')                                        }

  subject       { object.github_api_url                               }

  it_should_behave_like 'an idempotent method'

  it { should eql('https://api.github.com/repo/mbj/rom-status') }
end


text:
/**
 * NodeList objects are collections of nodes
 * such as those returned by Node.childNodes and the document.querySelectorAll method..
 *
  * @see https://developer.mozilla.org/en/docs/Web/API/NodeList
 */
export default class NodeList {
    constructor() {
        /**
         * @property {number} length length of the list
         */
        this.length = 0;
    }

    /**
     * @param {number} index
     * @return {Node|null}
     */
    item(index) {
        return this[index] || null;
    }

    _push() {
        Array.prototype.push.call(this, ...arguments);
    }

    [Symbol.iterator]() {
        let index = 0;

        return {
            next: () => ({ value: this[index++], done: index > this.length }),
        };
    }
}


text:
#include "tc_set.h"
#include "link_set.h"
#include "lq_plugin.h"
#include "olsr_spf.h"
#include "lq_packet.h"
#include "olsr.h"
#include "lq_plugin_etx_ff.h"
#include "parser.h"
#include "mid_set.h"
#include "scheduler.h"
#include "olsr_logging.h"
#include "common/string.h"

#define PLUGIN_DESCR "Freifunk ETX metric based on the original design of Elektra and Thomas Lopatic"
#define PLUGIN_AUTHOR "Henning Rogge"

#define LQ_ALGORITHM_ETX_FF_NAME "etx_ff"

#define LQ_FF_QUICKSTART_INIT 4

#define LQ_PLUGIN_RELEVANT_COSTCHANGE_FF 16

static bool lq_etxff_enable(void);

static void lq_etxff_initialize(void);
static void lq_etxff_deinitialize(void);

static olsr_linkcost lq_etxff_calc_link_entry_cost(struct link_entry *);
static olsr_linkcost lq_etxff_calc_lq_hello_neighbor_cost(struct lq_hello_neighbor *);
static olsr_linkcost lq_etxff_calc_tc_edge_entry_cost(struct tc_edge_entry *);

static bool lq_etxff_is_relevant_costchange(olsr_linkcost c1, olsr_linkcost c2);

static olsr_linkcost lq_etxff_packet_loss_handler(struct link_entry *, bool);

static void lq_etxff_memorize_foreign_hello(struct link_entry *, struct lq_hello_neighbor *);
static void lq_etxff_copy_link_entry_lq_into_tc_edge_entry(struct tc_edge_entry *target, struct link_entry *source);

static void lq_etxff_clear_link_entry(struct link_entry *);

static void lq_etxff_serialize_hello_lq(uint8_t **curr, struct link_entry *link);
static void lq_etxff_serialize_tc_lq(uint8_t **curr, struct link_entry *link);
static void lq_etxff_deserialize_hello_lq(uint8_t const **curr, struct lq_hello_neighbor *lq);
static void lq_etxff_deserialize_tc_lq(uint8_t const **curr, struct tc_edge_entry *lq);

static int lq_etxff_get_linkentry_data(struct link_entry *, int);
static const char *lq_etxff_print_cost(olsr_linkcost cost, char *buffer, size_t bufsize);
static const char *lq_etxff_print_link_entry_lq(struct link_entry *entry, int index, char *buffer, size_t bufsize);

static struct olsr_cookie_info *default_lq_ff_timer_cookie = NULL;

OLSR_PLUGIN6_NP() {
  .descr = PLUGIN_DESCR,
  .author = PLUGIN_AUTHOR,
  .enable = lq_etxff_enable,
  .type = PLUGIN_TYPE_LQ
};

/* etx lq plugin (freifunk fpm version) settings */
struct lq_linkdata_type lq_etxff_linktypes[] = {
  { "ETX", 5, 65536, 65536*2, 65536*4, INT32_MAX },
  { "LQ", 5, 255, 240, 192, 0 },
  { "NLQ", 5, 255, 240, 192, 0 }
};

struct lq_handler lq_etxff_handler = {
  "etx (freifunk)",

  &lq_etxff_initialize,
  &lq_etxff_deinitialize,

  &lq_etxff_calc_link_entry_cost,
  &lq_etxff_calc_lq_hello_neighbor_cost,
  &lq_etxff_calc_tc_edge_entry_cost,

  &lq_etxff_is_relevant_costchange,

  &lq_etxff_packet_loss_handler,

  &lq_etxff_memorize_foreign_hello,
  &lq_etxff_copy_link_entry_lq_into_tc_edge_entry,

  &lq_etxff_clear_link_entry,
  NULL,
  NULL,

  &lq_etxff_serialize_hello_lq,
  &lq_etxff_serialize_tc_lq,
  &lq_etxff_deserialize_hello_lq,
  &lq_etxff_deserialize_tc_lq,

  &lq_etxff_get_linkentry_data,
  &lq_etxff_print_cost,
  &lq_etxff_print_link_entry_lq,

  lq_etxff_linktypes,
  ARRAYSIZE(lq_etxff_linktypes),

  sizeof(struct lq_etxff_tc_edge),
  sizeof(struct lq_etxff_lq_hello_neighbor),
  sizeof(struct lq_etxff_link_entry),

  LQ_HELLO_MESSAGE,
  LQ_TC_MESSAGE,

  4,4
};

static bool lq_etxff_enable(void) {
  active_lq_handler = &lq_etxff_handler;
  return false;
}

static void
lq_etxff_packet_parser(struct olsr_packet *pkt, uint8_t *binary __attribute__ ((unused)),
    struct interface *in_if, union olsr_ip_addr *from_addr)
{
  const union olsr_ip_addr *main_addr;
  struct lq_etxff_link_entry *lnk;
  uint32_t seq_diff;

  /* Find main address */
  main_addr = olsr_lookup_main_addr_by_alias(from_addr);

  /* Loopup link entry */
  lnk = (struct lq_etxff_link_entry *)lookup_link_entry(from_addr, main_addr, in_if);
  if (lnk == NULL) {
    return;
  }

  if (lnk->last_seq_nr == pkt->seqno) {
#ifndef REMOVE_LOG_WARN
    struct ipaddr_str buf;
#endif
    OLSR_WARN(LOG_LQ_PLUGINS, "Got package with same sequence number from %s\n", olsr_ip_to_string(&buf, from_addr));
    return;
  }
  if (lnk->last_seq_nr > pkt->seqno) {
    seq_diff = (uint32_t) pkt->seqno + 65536 - lnk->last_seq_nr;
  } else {
    seq_diff = pkt->seqno - lnk->last_seq_nr;
  }

  /* Jump in sequence numbers ? */
  if (seq_diff > 256) {
    seq_diff = 1;
  }

  lnk->received[lnk->activePtr]++;
  lnk->lost[lnk->activePtr] += (seq_diff - 1);

  lnk->last_seq_nr = pkt->seqno;
  lnk->missed_seconds = 0;
}

static void
lq_etxff_timer(void __attribute__ ((unused)) * context)
{
  struct link_entry *link;
  OLSR_FOR_ALL_LINK_ENTRIES(link) {
    struct lq_etxff_link_entry *lq_link;
    uint32_t ratio;
    uint16_t i, received, lost;

#ifndef REMOVE_LOG_DEBUG
    struct ipaddr_str buf;
    // struct lqtextbuffer lqbuffer;
#endif
    lq_link = (struct lq_etxff_link_entry *)link;

    OLSR_DEBUG(LOG_LQ_PLUGINS, "LQ-FF new entry for %s: rec: %d lost: %d",
               olsr_ip_to_string(&buf, &link->neighbor_iface_addr),
               lq_link->received[lq_link->activePtr], lq_link->lost[lq_link->activePtr]);

    received = 0;
    lost = 0;

    /* enlarge window if still in quickstart phase */
    if (lq_link->windowSize < LQ_FF_WINDOW) {
      lq_link->windowSize++;
    }
    for (i = 0; i < lq_link->windowSize; i++) {
      received += lq_link->received[i];
      lost += lq_link->lost[i];
    }

    OLSR_DEBUG(LOG_LQ_PLUGINS, " total-rec: %d total-lost: %d", received, lost);

    /* calculate link quality */
    if (received + lost == 0) {
      lq_link->lq.valueLq = 0;
    } else {

      /* keep missed hello periods in mind (round up hello interval to seconds) */
      uint32_t missed_hello_cost = lq_link->missed_seconds / ((lq_link->core.link_loss_timer->timer_period + 999) / 1000);
      lost += missed_hello_cost * missed_hello_cost;

      // start with link-loss-factor
      ratio = link->loss_link_multiplier;

      // calculate received/(received + loss) factor
      ratio = ratio * received;
      ratio = ratio / (received + lost);
      ratio = (ratio * 255) >> 16;

      lq_link->lq.valueLq = (uint8_t) (ratio);
    }

    // shift buffer
    lq_link->activePtr = (lq_link->activePtr + 1) % LQ_FF_WINDOW;
    lq_link->lost[lq_link->activePtr] = 0;
    lq_link->received[lq_link->activePtr] = 0;
    lq_link->missed_seconds++;
  }
  OLSR_FOR_ALL_LINK_ENTRIES_END(link);
}

static struct timer_entry *lq_etxff_timer_struct = NULL;

static void
lq_etxff_initialize(void)
{
  /* Some cookies for stats keeping */
  olsr_packetparser_add_function(&lq_etxff_packet_parser);
  default_lq_ff_timer_cookie = olsr_alloc_cookie("Default Freifunk LQ", OLSR_COOKIE_TYPE_TIMER);
  lq_etxff_timer_struct = olsr_start_timer(1000, 0, OLSR_TIMER_PERIODIC, &lq_etxff_timer, NULL, default_lq_ff_timer_cookie);
}

static void
lq_etxff_deinitialize(void)
{
  olsr_stop_timer(lq_etxff_timer_struct);
  olsr_packetparser_remove_function(&lq_etxff_packet_parser);
}

static olsr_linkcost
lq_etxff_calc_linkcost(struct lq_etxff_linkquality *lq)
{
  olsr_linkcost cost;

  if (lq->valueLq < (unsigned int)(255 * MINIMAL_USEFUL_LQ) || lq->valueNlq < (unsigned int)(255 * MINIMAL_USEFUL_LQ)) {
    return LINK_COST_BROKEN;
  }

  cost = 65536 * 255 / (int)lq->valueLq * 255 / (int)lq->valueNlq;

  if (cost > LINK_COST_BROKEN)
    return LINK_COST_BROKEN;
  if (cost == 0)
    return 1;
  return cost;
}

static olsr_linkcost
lq_etxff_calc_link_entry_cost(struct link_entry *link)
{
  struct lq_etxff_link_entry *lq_link = (struct lq_etxff_link_entry *)link;

  return lq_etxff_calc_linkcost(&lq_link->lq);
}

static olsr_linkcost
lq_etxff_calc_lq_hello_neighbor_cost(struct lq_hello_neighbor *neigh)
{
  struct lq_etxff_lq_hello_neighbor *lq_neigh = (struct lq_etxff_lq_hello_neighbor *)neigh;

  return lq_etxff_calc_linkcost(&lq_neigh->lq);
}

static olsr_linkcost
lq_etxff_calc_tc_edge_entry_cost(struct tc_edge_entry *edge)
{
  struct lq_etxff_tc_edge *lq_edge = (struct lq_etxff_tc_edge *)edge;

  return lq_etxff_calc_linkcost(&lq_edge->lq);
}

static bool
lq_etxff_is_relevant_costchange(olsr_linkcost c1, olsr_linkcost c2)
{
  if (c1 > c2) {
    return c2 - c1 > LQ_PLUGIN_RELEVANT_COSTCHANGE_FF;
  }
  return c1 - c2 > LQ_PLUGIN_RELEVANT_COSTCHANGE_FF;
}

static olsr_linkcost
lq_etxff_packet_loss_handler(struct link_entry *link, bool loss __attribute__ ((unused)))
{
  return lq_etxff_calc_link_entry_cost(link);
}

static void
lq_etxff_memorize_foreign_hello(struct link_entry *target, struct lq_hello_neighbor *source)
{
  struct lq_etxff_link_entry *lq_target = (struct lq_etxff_link_entry *)target;
  struct lq_etxff_lq_hello_neighbor *lq_source = (struct lq_etxff_lq_hello_neighbor *)source;

  if (source) {
    lq_target->lq.valueNlq = lq_source->lq.valueLq;
  } else {
    lq_target->lq.valueNlq = 0;
  }

}

static void
lq_etxff_copy_link_entry_lq_into_tc_edge_entry(struct tc_edge_entry *target, struct link_entry *source)
{
  struct lq_etxff_tc_edge *lq_target = (struct lq_etxff_tc_edge *)target;
  struct lq_etxff_link_entry *lq_source = (struct lq_etxff_link_entry *)source;

  lq_target->lq = lq_source->lq;
}

static void
lq_etxff_clear_link_entry(struct link_entry *link)
{
  struct lq_etxff_link_entry *lq_link = (struct lq_etxff_link_entry *)link;
  int i;

  lq_link->windowSize = LQ_FF_QUICKSTART_INIT;
  for (i = 0; i < LQ_FF_WINDOW; i++) {
    lq_link->lost[i] = 3;
  }
}

static void
lq_etxff_serialize_hello_lq(uint8_t **curr, struct link_entry *link)
{
  struct lq_etxff_link_entry *lq_link = (struct lq_etxff_link_entry *)link;

  pkt_put_u8(curr, lq_link->lq.valueLq);
  pkt_put_u8(curr, lq_link->lq.valueNlq);
  pkt_put_u16(curr, 0);
}
static void
lq_etxff_serialize_tc_lq(uint8_t **curr, struct link_entry *link)
{
  struct lq_etxff_link_entry *lq_link = (struct lq_etxff_link_entry *)link;

  pkt_put_u8(curr, lq_link->lq.valueLq);
  pkt_put_u8(curr, lq_link->lq.valueNlq);
  pkt_put_u16(curr, 0);
}

static void
lq_etxff_deserialize_hello_lq(uint8_t const **curr, struct lq_hello_neighbor *neigh)
{
  struct lq_etxff_lq_hello_neighbor *lq_neigh = (struct lq_etxff_lq_hello_neighbor *)neigh;

  pkt_get_u8(curr, &lq_neigh->lq.valueLq);
  pkt_get_u8(curr, &lq_neigh->lq.valueNlq);
  pkt_ignore_u16(curr);

}
static void
lq_etxff_deserialize_tc_lq(uint8_t const **curr, struct tc_edge_entry *edge)
{
  struct lq_etxff_tc_edge *lq_edge = (struct lq_etxff_tc_edge *)edge;

  pkt_get_u8(curr, &lq_edge->lq.valueLq);
  pkt_get_u8(curr, &lq_edge->lq.valueNlq);
  pkt_ignore_u16(curr);
}

static int
lq_etxff_get_linkentry_data(struct link_entry *link, int idx) {
  struct lq_etxff_link_entry *lq = (struct lq_etxff_link_entry *)link;
  return idx == 1 ? lq->lq.valueLq : lq->lq.valueNlq;
}

static const char *
lq_etxff_print_link_entry_lq(struct link_entry *link, int idx, char *buffer, size_t bufsize)
{
  struct lq_etxff_link_entry *lq = (struct lq_etxff_link_entry *)link;
  uint8_t value;

  if (idx == 1) {
    value = lq->lq.valueLq;
  }
  else {
    value = lq->lq.valueNlq;
  }

  if (value == 255) {
    strscpy(buffer, "1.000", bufsize);
  } else {
    snprintf(buffer, bufsize, "0.%03d", (value * 1000) / 255);
  }
  return buffer;
}

static const char *
lq_etxff_print_cost(olsr_linkcost cost, char *buffer, size_t bufsize)
{
  // must calculate
  uint32_t roundDown = cost >> 16;
  uint32_t fraction = ((cost & 0xffff) * 1000) >> 16;

  snprintf(buffer, bufsize, "%u.%03u", roundDown, fraction);
  return buffer;
}

/*
 * Local Variables:
 * c-basic-offset: 2
 * indent-tabs-mode: nil
 * End:
 */


text:
<?php defined('C5_EXECUTE') or die("Access Denied.");
$v = $c->getVersionObject();
$require_version_comments = (bool) Config::get('concrete.misc.require_version_comments');
$datetime = loader::helper('form/date_time');
?>

<form method="post" id="ccm-check-in" action="<?=$controller->action('submit')?>">

<?=t('Version Comments')?>

<textarea name="comments" id="ccm-check-in-comments"<?php echo $require_version_comments ? ' required="required"' : ''; ?>></textarea>

<?php if ($cp->canApprovePageVersions()) {
    if ($c->isPageDraft()) {
        $publishTitle = t('Publish Page');
    } else {
        $publishTitle = t('Publish Changes');
        $pk = PermissionKey::getByHandle('approve_page_versions');
        $pk->setPermissionObject($c);
        $pa = $pk->getPermissionAccessObject();
        $workflows = array();
        $canApproveWorkflow = true;
        if (is_object($pa)) {
            $workflows = $pa->getWorkflows();
        }
        foreach ($workflows as $wf) {
            if (!$wf->canApproveWorkflow()) {
                $canApproveWorkflow = false;
            }
        }

        if (count($workflows) > 0 && !$canApproveWorkflow) {
            $publishTitle = t('Submit to Workflow');
        }
    }
    ?>

    <?php $publishAction = (is_object($publishErrors) && $publishErrors->has()) ? false : true ?>

        <button id="ccm-check-in-publish" type="submit" name="action" value="publish"
                class="btn btn-primary" <?=$publishAction ?: 'disabled' ?>>
            <?=$publishTitle?>
        </button>
        <button id="ccm-check-in-schedule" type="button" class="btn btn-primary" <?= $publishAction ?: 'disabled' ?>>

        </button>

    <?php if ($canApproveWorkflow): ?>

Scheduled Publish

            Remove

                <?= $datetime->datetime('check-in-scheduler', $publishDate, false, true,
                    'check-in-scheduler-calendar'); ?>

                <?=$timezone ?>
                <button type="submit" name="action" value="schedule"
                        class="btn btn-primary ccm-check-in-schedule " <?=$publishAction ?: 'disabled' ?>>
                    Schedule
                </button>

    <?php endif ?>

        <?php foreach ($publishErrors->getList() as $error): ?>

 <?=$error?>

        <?php endforeach; ?>

        <?php $pagetype = PageType::getByID($c->getPageTypeID()); ?>
        <?php if (count($publishErrors->getList()) && (is_object($pagetype))): ?>

                        <?=t('You can specify page name, page location and attributes from the ' .
                             'Page Compose interface.',
                             URL::to('/ccm/system/panels/details/page/composer')); ?>

        <?php endif ?>

<?php
} ?>

	<button id="ccm-check-in-preview" type="submit" name="action" value="save" class="btn-block btn-success btn"><?=t('Save Changes')?></button>

    <?php if ($c->isPageDraft() && $cp->canDeletePage()) {
    ?>
		<button id="ccm-check-in-discard" type="submit" name="action" value="discard" class="btn-block btn-danger btn"><?=t('Discard Draft')?></button>
	<?php
} elseif ($v->canDiscard()) {
    ?>
		<button id="ccm-check-in-discard" type="submit" name="action" value="discard" class="btn-block btn-danger btn"><?=t('Discard Changes')?></button>
	<?php
} ?>
	<input type="hidden" name="approve" value="PREVIEW" id="ccm-approve-field" />

</form>


text:
TBANS is the service in The Blue Alliance that manages dispatching notifications and managing client subscription state with Firebase. Details about TBANS can be found in the [TBANS Eng Design Doc](https://docs.google.com/document/d/16ZdyL3WOJ1B4HmRAP6Qsl8DarZ29oYOul1Hv7PJuJOw/edit?usp=sharing).

## Running TBANS Locally

TBANS will start with the Docker container (usually running on port 8087). Otherwise, you can start TBANS on port 8080 using paver.

```
$ paver run_tbans
```

You can curl the TBANS service to test endpoints.

```bash
$ curl -X POST -H 'Content-Type: application/json' -d '{
  "webhook": {
    "url": "http://mysite.com",
    "secret": "some_secret"
  }
}' http://localhost:8087/tbans.ping
```

Notifications are best tested via the web notifications or webhooks. This documentation will be updated when the web supports notifications to provide instructions on how to test. Webhooks can be tested via [ngrok](https://ngrok.com/download), or the steps outlined in the [testing section of our webhook documentation](https://www.thebluealliance.com/apidocs/webhooks#testing).

As a note, until https://issuetracker.google.com/issues/35901176 is solved, only hit HTTP webhooks, unless you're able to do the suggested workaround.

## Structure of a Notification

All `Notification` objects are subclasses of the base `Notification` object. A `Notification` manages a notification's data payload, it's human-readable title/message, and any platform-specific configuration options. The same `Notification` objects are used for push notifications as well as webhooks.

For more details on FCM notification payloads, see the [FCM v1 HTTP message documentation](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages). For more details on webhook notification payloads, see [The Blue Alliance's webhook documentation](https://www.thebluealliance.com/apidocs/webhooks).

### Notification Type

```jsonc
// an FCM payload for a Notification with only a type
{
  "message": {
    "notification": {
      "title": "Some Title",
      "body": "Some body message"
    },
    "data": {
      "event_key": "2018miket",
      "match_key": "2018miketqm1",
      "notification_type": "upcoming_match"
    }
  }
}

// a webhook payload for a Notification with only a type
{
  "message_data": {
    "event_key": "2018miket",
    "match_key": "2018miketqm1"
  }
  "message_type": "upcoming_match"
}
```


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 edu.nr.states;

/**
 *
 * @author alexbrinister
 */
public class DriveState {
    private DriveState() {
    }

    public static final int DRIVE_IDLE = 0;
    public static final int DRIVE_TELEOP = 1;
    public static final int DRIVE_DISTANCE = 2;
    public static final int DRIVE_STRAIGHT_LINE = 3;
    public static final int DRIVE_DISTANCE_PID = 4;
}


text:
layout: post
title:  "Mixing together TextInput and MouseArea(s)"
description: "Put MouseArea over TextInput and control focus"
date: 2016-03-03
category:
  - qml
  - programming
comments: true
---

`TextInput` gets activated with **pressing** rather than *clicking*. This creates some problems on mobile devices where you would like to add swipe or press and hold behaviors over `TextInput` with `MouseArea` over it. While I was developing [Mantar][mantar_url]. I wanted to press and hold over a `TextInput` to toggle the done state of a task and when I click on it, I wanted to start editing the task. I also had a topmost `MouseArea` that controlled swipe up and down gestures to open or close the menu.

To add a topmost `MouseArea` and still get the mouse or touch events to the other `MouseArea`s you just need to set the `propagateComposedEvents` value to true. And then, you add another `MouseArea` over the `TextInput` and set `propagateComposedEvents` value to true.

```qml
TextInput {
    id: textBox
    selectByMouse: true
    clip: true

    MouseArea {
        anchors.fill: parent
        //Set the focus reason so we can activate the keyboard on mobile devices
        onClicked: textBox.forceActiveFocus(Qt.MouseFocusReason)
        propagateComposedEvents: true
        visible: !textBox.focus
        onPressAndHold: {
            if (textBox.text.length > 0) {
                done = !done;
                root.editingFinished(done);
            }
        }
    }
}
```

[mantar_url]: https://github.com/ZerronLabs/Mantar


text:
<?php

/**
 * Default Object/Relational Mapping objetct
 *
 * @uses        One_Core_Orm_DataMapper
 *
 * @access      public
 * @author      gplanchat
 * @category    Core
 * @package     One_Core
 * @subpackage  One_Core
 */
class One_Core_Resource_Orm_DataMapper_Standard
    extends One_Core_Orm_DataMapperAbstract
{
    public function save(One_Core_Bo_EntityAbstract $boInstance)
    {
        return $boInstance->getData();
    }

    public function load(One_Core_Bo_EntityAbstract $boInstance, Array $daoData)
    {
        $boInstance->setData($daoData);

        return $boInstance;
    }
}


text:
<?php

/* @var $this yii\web\View */
/* @var $form yii\bootstrap\ActiveForm */
/* @var $model \frontend\models\SignupForm */

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use common\modules\i18n\Module;
use frontend\widgets\CaptchaWidget;

$this->title = \common\modules\i18n\Module::t('Signup');
$this->params['breadcrumbs'][] = $this->title;

echo \frontend\widgets\BreadcrumbWidget::widget([
    'type'       => 'common',
    'commonName' => $this->title
]);

?>

<?= Html::encode($this->title) ?>

            <?php $form = ActiveForm::begin([
                'id'             => 'form-signup',
                'options'        => [
                    'class' => 'signup-form'
                ],
                'validateOnBlur' => false,
            ]); ?>

            <?= $form->field($model, 'username')->textInput([
                'autofocus' => true,
                'class'     => 'form-input'
            ]) ?>

            <?= $form->field($model, 'email')->textInput([
                'class' => 'form-input'
            ]) ?>

            <?= $form->field($model, 'password')->passwordInput([
                'class' => 'form-input'
            ]) ?>

            <?= $form->field($model, 'passwordRepeat')->passwordInput([
                'class' => 'form-input'
            ]) ?>

            <?= $form->field($model, 'subscription')->checkbox([
                'class' => 'icheckbox'
            ])->label(Module::t('I would like to receive news from Jenadin')) ?>

            <?= CaptchaWidget::widget([
                'lang' => \common\models\Lang::getLanguageISOUrl()
            ]) ?>

                <?= Html::submitButton(Module::t('Signup'), ['class' => 'btn btn-black btn-signup', 'name' => 'signup-button']) ?>

            <?php ActiveForm::end(); ?>


text:
@implementation CIDType0Font

@end


text:
/**
 * @file Main entry point into the scripts.
 * @author Dom Light
 * @license MIT
 */

const t1 = new Date().getTime();
require("creepExt");
const roleFactory = require("roleFactory");
const constructionPlanner = require("constructionPlanner");

// Handle any new constructions.
for (const roomId in Game.rooms) {
	constructionPlanner.handleConstruction(Game.rooms[roomId]);
}

const t2 = new Date().getTime();

// See if there's any new creeps that should be spawned.
for (const spawn of _.values(Game.spawns)) {
	const nextRole = roleFactory.getNextRole(spawn.room);
	if (!nextRole) {
		continue;
	}

	const role = require("role-" + nextRole);
	const creepDefinition = role.getCreepDefinition(spawn);
	if (spawn.canCreateCreep(creepDefinition) === OK) {
		spawn.createCreep(creepDefinition, undefined, {
			"role":        role.name,
			"justSpawned": true,
			"spawn":       spawn.id,
		});
	}
}

const t3 = new Date().getTime();

// Make all the creeps do their actions.
for (const creep of _.values(Game.creeps)) {
	if (creep.memory.role) {
		const role = require("role-" + creep.memory.role);
		role.action(creep);
	}
}

const t4 = new Date().getTime();

console.log(`constructionPlanner: ${t2 - t1}ms,
	roleFactory: ${t3 - t2}ms,
	roles: ${t4 - t3}ms,
	total: ${t4 - t1}ms`);


text:
var battleship = angular.module('battleship', ['ngRoute']);

// Setup the Routes
battleship.config(['$routeProvider', '$locationProvider',
    function($routeProvider, $locationProvider) {
        $routeProvider
            .when('/gamehub', {
                templateUrl: '/views/gamehub.html',
                controller: 'gamehub'
            })
            .when('/game/:gameId', {
                templateUrl: '/views/battle.html',
                controller: 'battleController'
            })
            .otherwise('/gamehub');

        $locationProvider.html5Mode(true);
    }]
);

// ----------------------
// Factories and Services

/**
 * The IO factory wraps the socket.io library so that calls to it will automatically trigger an update to the views
 * in angular.
 */
battleship.factory('io', ['$rootScope', '$location', function($rootScope, $location) {
    var socket = null;
    var errorHandler = function(err) {
        console.warn('App Error: ', err);

        var cssClass = 'alert-danger';
        if (err.type == 'warning') {
            cssClass = 'alert-warning';
        } else if (err.type == 'notice') {
            cssClass = 'alert-info';
        }
        err['class'] = cssClass;

        if (!angular.isArray($rootScope.messages)) {
            $rootScope.messages = [];
        }
        $rootScope.messages.push(err);

        if (err.redirect) {
            $location.path(err.navigateTo);
        }
    };
    var socketWrapper = {
        on: function(event, callback) {
            socket.on(event, function() {
                var args = arguments;
                $rootScope.$apply(function() {
                    callback.apply(socket, args);
                });
            });
        },
        emit: function (eventName, data, callback) {
            socket.emit(eventName, data, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            })
        }
    };

    var factory = function(namespace) {
        socket = io(namespace);
        socketWrapper.on('app-error', errorHandler);
        //socketWrapper.on('disconnect', function() {
        //    console.log('Disconnected from server: ', arguments);
        //    errorHandler({msg: 'Disconnected from server', type: 'warning'});
        //});
        return socketWrapper;
    };
    factory.getSocket = function() {
        return socketWrapper;
    };
    factory.getRawSocket = function() {
        return socket;
    };

    return factory;
}]);

// ----------------------
//     Controllers

battleship.controller('gamehub', ['$scope', '$location', 'io', function($scope, $location, io) {
    var socket = io('/games');
    var user;

    // Define the socket events
    socket.on('user-info', function(userInfo) {
        user = userInfo;
    });
    socket.on('game-add', function(game) {
        if (user && (game.player1 == user.username || game.player2 == user.username)) {
            $scope.games.private.push(game);
        } else {
            $scope.games.public.push(game);
        }
    });
    socket.on('games-list', function(games) {
        if (games) {
            $scope.games = games;
        }
    });
    socket.on('game-join', function(gameId) {
        // Player has joined a game, open the game page
        $location.path('/game/' + gameId);
    });
    socket.on('game-update', function(game) {
        // A game has been updated
        // Find the game
        var index = -1;
        var isPublic = false;
        angular.forEach($scope.games, function(games, key) {
            if (index == -1) {
                for (var i = 0, l = games.length; i < l; i++) {
                    if (games[i]._id == game._id) {
                        games[i] = game;
                        index = i;
                        isPublic = (key == 'public');
                        break;
                    }
                }
            }
        });

        // Handle moving public games bettween the lists
        if (index >= 0 && isPublic) {
            if (game.player1 == user.username || game.player2 == user.username) {
                // Move from public to private
                $scope.games.private.push($scope.games.public[index]);
            }
            // Remove the game from public
            $scope.games.public.splice(index, 1);
        }

        $scope.joinDisabled = false;
    });
    socket.on('app-error', function() {
        // The server sent an error message to us, this may be due to a failed game join, re-enabled the join game buttons
        $scope.joinDisabled = false;
    });

    $scope.games = {
        public: [],
        private: []
    };
    $scope.openCreateGameDialog = function() {
        $(".createGameOverlay").css("display", "block");
        $(".createGameModal").css("display", "block");
    };
    $scope.createGame = function() {
        //console.log("We should actually send information to the server at this point");
        $(".createGameOverlay").css("display", "none");
        $(".createGameModal").css("display", "none");

        socket.emit('game-add', $scope.gameName);
    };

    $scope.joinGame = function(game) {
        socket.emit('game-join', game._id);
        $scope.joinDisabled = true;
    };

    // TODO make this run in angular?
    jQuery(document).ready(function($) {

        $("#cancelCreateGameButton").click(function() {
            $(".createGameOverlay").css("display", "none");
            $(".createGameModal").css("display", "none");
        });
    });

}]);


text:
@implementation AutomatToken

- (NSString *)description {
    return [NSString stringWithFormat: @"Token string: %@, with range: {%lu, %lu}", _string, (unsigned long)_range.location, (unsigned long)_range.length];
}

@end


text:
A blog for me to post my thoughts and info related to front-end web development.

## Info

Built with [Jekyll](http://jekyllrb.com/).

Themed with [Hyde](http://andhyde.com/).

## Copyright

All content is copyright of me as of now.


text:
package org.carbon.web.context.session.key.manage;

import java.util.Arrays;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.carbon.web.context.session.ShouldHandleRequest;
import org.carbon.web.context.session.key.SessionKey;
import org.carbon.web.context.session.key.SessionKeyGenerator;

/**
 * @author Shota.Oda 2018/03/03.
 */
public class CookieSessionKeyManager extends AbstractSessionKeyManager {

    private String cooKey;

    public CookieSessionKeyManager(
            ShouldHandleRequest shouldHandle,
            SessionKeyGenerator keyGenerator,
            String cooKey) {
        super(shouldHandle, keyGenerator);
        this.cooKey = cooKey;
    }

    @Override
    public SessionKey handle(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            cookies = new Cookie[]{};
        }
        return Arrays.stream(cookies)
                .filter(cookie -> cookie.getName().equals(cooKey))
                .findFirst()
                .map(Cookie::getValue)
                .map(super::getKey)
                .orElseGet(() -> {
                    SessionKey key = generateKey();
                    String keyStr = key.key();
                    response.addCookie(new Cookie(cooKey, keyStr));
                    return key;
                });
    }
}


text:
import isotope from 'isotope-layout';
import Inputmask from "inputmask";

// Init isotope grid;
$(document).ready(() => {
  const ISOTOPE_GRID = '.js-isotopeGrid';
  const ISOTOPE_CONTROLS = '.js-isotopeBtns';
  const ISOTOPE_GRID_ITEM = '.js-gridItem';

  const isotopeSettings = {
    itemSelector: ISOTOPE_GRID_ITEM,
    layoutMode: 'fitRows',
  }

  const $grid = $(ISOTOPE_GRID);
  const $controls = $(ISOTOPE_CONTROLS);

  const isotopeFilter = ({ currentTarget: key }) => $(key).data('filter');

  const iso = new isotope(
    ISOTOPE_GRID,
    isotopeSettings,
    );

  $controls.on('click', 'button', event => iso.arrange({
    filter: isotopeFilter(event)
  }));

  $controls.each(function(i, buttonGroup) {
    const $buttonGroup = $(buttonGroup);
    $buttonGroup.on( 'click', 'button', function() {
      $buttonGroup.find('.is-checked').removeClass('is-checked');
      $(this).addClass('is-checked');
    });

    $buttonGroup.find('button')[0].click(function() {
      $buttonGroup.find('.is-checked').removeClass('is-checked');
      $(this).addClass('is-checked');
    });
  });
});

// Show more

$(document).ready(() => {
  Validation();
  Validation_methods();

  var stackModal = 0;
  $(document).on('show.bs.modal', '.modal', function (event) {
    var zIndex = 1040 + (10 * $('.modal:visible').length);
    $(this).css('z-index', zIndex);
    stackModal++;
    setTimeout(function() {
      $('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
    }, 0);
  });

  $(document).on('hidden.bs.modal', '.modal', function (event) {
    stackModal--;
    if(stackModal > 0) {
      $('body').addClass("modal-open");
    } else {
      $('body').removeClass("modal-open");
    }
  });

  setTimeout(() => {
    $(document).scrollTop('0')
  }, 300)

  $.validator.addMethod('filesize', function (value, element, param) {
    return this.optional(element) || (element.files[0].size <= param)
  }, 'File size must be less than {0}');

  let didScroll;
  let lastScrollTop = 0;
  const delta = 5;
  const navbarHeight = $('.header').outerHeight();

  $(window).scroll(function(event){
    didScroll = true;
  });

  setInterval(function() {
    if (didScroll) {
      hasScrolled();
      didScroll = false;
    }
  }, 250);

  function hasScrolled() {
    var st = $(document).scrollTop();

    if (st > (navbarHeight)) {
      $('.header').addClass('sticky');
    } else {
      $('.header').removeClass('sticky');
    }

    if (Math.abs(lastScrollTop - st) <= delta) return;

    if (st > lastScrollTop && st > navbarHeight) {
      $('.header').removeClass('sticky-up');
    } else {
      if(st + $(window).height() < $(document).height()) {
        $('.header').addClass('sticky-up');
      }
    }
    lastScrollTop = st;
  }

  // smooth scroll
  const offsetTopHeader = $('.header').innerHeight();

  $('a.smooth').click(function () {
    $('html, body').animate({
      scrollTop: $($.attr(this, 'href')).offset().top - offsetTopHeader
    }, 350);
    return false;
  });

  const $items = $('.js-moreProducts');
  const $btnShowItems = $('.js-showMore');

  $items.css({
    display: 'none',
  })

  $btnShowItems.on('click', event => {
    event.preventDefault()
    $items.css({
      display: 'block',
    })
  })

  const $phones = document.querySelectorAll('[data-input="phone"]')
  const phoneMask = new Inputmask('+7 (999) 999-99-99')
  phoneMask.mask($phones)

  //file input

  const handleFileSelectText = ({
    target: {
      files,
    }
  }) => {
    let name;
    if (files[0] !== undefined) {
      return name = files[0].name;
    } else {
      name = 'Выберите файл';
    }
    return name;
  }

  $('.custom-file-input').on('change', function(event) {
    const fileName = handleFileSelectText(event)
    const textField = $(this).next()

    textField.attr('data-text', fileName)
  })

  $('#file-input input').on('change', function(event) {
    const fileName = handleFileSelectText(event)
    const textField = $(this).prev()

    textField.text(fileName)
  })

  // init validation
  $('.modal-form').validate({
    rules: {
      picture: {
        extension: 'png|jpg|jpeg',
        filesize: 1048576 * 8,
      }
    },

    messages: {
      user: {
        required: "Это обязательное поле",
      },

      phone: {
        required: "Это обязательное поле",
        tel: "Введите валидный номер телефона",
      },

      email: {
        email: "Укажите правильный e-mail",
      },

      picture: {
        extension: 'Не верный формат файла',
        filesize: 'Файл превышает 8 мб',
      }
    },

    errorElement: "span",

    errorPlacement: (error, element) => {
      error.addClass( "help-block" );
      if ( element.prop( "type" ) === "checkbox" ) {
        error.insertAfter( element.parent( "label" ) );
      } else {
        error.insertAfter( element );
      }
    },

    highlight: (element, errorClass, validClass) => {
      $(element)
      .parents(".form-group")
      .addClass("has-danger")
      .removeClass("has-success");
    },

    unhighlight: (element, errorClass, validClass) => {
      $(element)
      .parents(".form-group")
      .addClass( "has-success")
      .removeClass("has-danger");
    },

    submitHandler: (form, event) => {
      const url = 'simpleForm.php';
      const data = new FormData(form);

      const success = () => {
        $('#call').modal('hide');
        $('#thx').modal('show');

        setTimeout(() => {
          $('#thx').modal('hide');
        }, 10000);
      }

      $.ajax({
        type: "POST",
        url: url,
        data: data,
        success: success,
        processData: false,
        contentType: false,
      });

      event.preventDefault();
    }
  });

  const msfCssClasses = {
    header: "msf-header",
    step: "msf-step",
    stepComplete: "complete",
    stepActive: "active",
    content: "msf-content",
    view: "msf-view",
    navigation: "msf-navigation",
    navButton: "msf-nav-button"
  };

  const msfNavTypes = {
    back: "back",
    next: "next",
    submit: "submit"
  };

  const msfEventTypes = {
    viewChanged : "msf:viewChanged"
  };

  $.validator.prototype.subset = function (container) {
    var ok = true;
    var self = this;
    $(container).find(':input').each(function () {
      if (!self.element($(this))) ok = false;
    });
    return ok;
  };

  $.each(['show', 'hide'], function (i, ev) {
    var el = $.fn[ev];
    $.fn[ev] = function () {
      this.trigger(ev);
      return el.apply(this, arguments);
    };
  });

  $.fn.multiStepForm = function (options) {
    var form = this;

    var defaults = {
      activeIndex: 0,
      validate: {},
      hideBackButton: false
    };

    var settings = $.extend({}, defaults, options);
    form.content = this.find("." + msfCssClasses.content).first();
    form.views = $(this.content).find("." + msfCssClasses.view);
    form.header = this.find("." + msfCssClasses.header).first();
    form.navigation = this.find("." + msfCssClasses.navigation).first();
    form.steps = [];

    form.getActiveView = function() {
      return form.views.filter(function () { return this.style && this.style.display !== '' && this.style.display !== 'none' });
    };

    form.setActiveView = function(index) {
      var view = form.getActiveView();
      var previousIndex = form.views.index(view);

      view = form.views.eq(index);
      view.show();
      view.find(':input').first().focus();

      form.trigger(msfEventTypes.viewChanged, {
        currentIndex : index,
        previousIndex : previousIndex,
        totalSteps : form.steps.length
      });
    }

    form.init = function () {

      this.initHeader = function () {
        if (form.header.length === 0) {
          form.header = $("<div/>", {
            "class": msfCssClasses.header,
            "display": "none"
          });

          $(form).prepend(form.header);
        }

        form.steps = $(form.header).find("." + msfCssClasses.step);

        this.initStep = function (index, view) {

          if (form.steps.length < index + 1) {
            $(form.header).append($("<div/>", {
              "class": msfCssClasses.step,
              "display": "none"
            }));
          }
        }

        $.each(form.views, this.initStep);

        form.steps = $(form.header).find("." + msfCssClasses.step);
      };

      this.initNavigation = function () {
        if (form.navigation.length === 0) {
          form.navigation = $("<div/>", {
            "class": msfCssClasses.navigation
          });

          $(form.content).after(form.navigation);
        }

        this.initNavButton = function (type, buttonType) {
          var element = this.navigation.find("button[data-type='" + type + "'], input[type='button']"), type;
          if (element.length === 0) {
            element = $("<button/>", {
              "class": msfCssClasses.navButton,
              "data-type": type,
              "html": type,
              type: buttonType,
            });
            element.appendTo(form.navigation);
          }

          return element;
        };

        form.backNavButton = this.initNavButton(msfNavTypes.back, 'button');
        form.nextNavButton = this.initNavButton(msfNavTypes.next, 'button');
        form.submitNavButton = this.initNavButton(msfNavTypes.submit, 'submit');
      };

      this.initHeader();
      this.initNavigation();

      this.views.each(function (index, element) {

        var view = element,
        $view = $(element);

        $view.on('show', function (e) {
          if (this !== e.target)
            return;

          form.getActiveView().hide();

          if (index > 0 && !settings.hideBackButton) {
            form.backNavButton.show();
          }

          if (index == form.views.length - 1) {
            form.nextNavButton.hide();
            form.submitNavButton.show();
          }
          else {
            form.submitNavButton.hide();
            form.nextNavButton.show();

            $(this).find(':input').keypress(function (e) {
              if (e.which == 13)
              {
                form.nextNavButton.click();
                return false;
              }
            });
          }

          $.each(form.steps, function (i, element) {
            if (i < index) {
              $(element).removeClass(msfCssClasses.stepActive);
              $(element).addClass(msfCssClasses.stepComplete);
            }

            else if (i === index) {
              $(element).removeClass(msfCssClasses.stepComplete);
              $(element).addClass(msfCssClasses.stepActive);
            }
            else {
              $(element).removeClass(msfCssClasses.stepComplete);
              $(element).removeClass(msfCssClasses.stepActive);
            }
          });
        });

        $view.on('hide', function (e) {
          if (this !== e.target)
            return;
          form.backNavButton.hide();
          form.nextNavButton.hide();
          form.submitNavButton.hide();
        });

        console.log(view, index);
      });

      form.setActiveView(settings.activeIndex);
    };

    form.init();

    form.nextNavButton.click(function () {
      var view = form.getActiveView();
      if (form.validate(settings.validate).subset(view)) {
        var i = form.views.index(view);

        form.setActiveView(i+1);
      }
    });

    //hack
    $('#step2').on('click', event => {
      form.nextNavButton.click();
    });

    $('#step3').on('click', event => {
      form.nextNavButton.click();
    });

    $('#step4').on('click', event => {
      form.nextNavButton.click();
    });

    $('#submitHack').on('click', event => {
      form.submitNavButton.click();
      event.stopPropagation();
    });

    form.backNavButton.click(function () {
      var view = form.getActiveView();
      var i = form.views.index(view);

      form.setActiveView(i-1);
    });

    $('.msf-step').each((idx, item) => {
      $(item).on('click', () => {
        if($(item).hasClass('complete')) {
          form.setActiveView(idx);
        }
      })
    })
  };

  const isFrontSide = () => $('[data-side="front"]').is(':checked');
  const isBackSide = () => $('[data-side="back"]').is(':checked');

  const sizeSettings = (() => {
    const sizeSet = $('.size-set').find('input');
    const isSizeSetOne = items => items.length === 1;

    if(isSizeSetOne(sizeSet)) {
      $(sizeSet[0]).prop('checked', true)
    }
  })();

  const isRequiredDress = nubmer => {
    return Array.from(document.querySelectorAll('input[name=dress]')).map((input, idx) => {
      return $(input).on('change', ({target}) => {
        return nubmer === idx;
      });
    })
  }

  $(".msf").multiStepForm({
    activeIndex: 0,
    hideBackButton: false,

    validate: {
      rules: {
        dress: {
          required: true,
        },

        'size-set-1': {
          required: isRequiredDress(0),
        },

        'size-set-2': {
          required: isRequiredDress(1),
        },

        'size-set-3': {
          required: isRequiredDress(2),
        },

        'size-set-4': {
          required: isRequiredDress(3),
        },

        'size-set-5': {
          required: isRequiredDress(4),
        },

        'size-set-6': {
          required: isRequiredDress(5),
        },

        'color-set-1': {
          required: isRequiredDress(0),
        },

        'color-set-2': {
          required: isRequiredDress(1),
        },

        'color-set-3': {
          required: isRequiredDress(2),
        },

        'color-set-4': {
          required: isRequiredDress(3),
        },

        'color-set-5': {
          required: isRequiredDress(4),
        },

        'color-set-6': {
          required: isRequiredDress(5),
        },

        thread: {
          required: true,
        },

        face: {
          required: true,
        },

        user: {
          required: true,
        },

        phone: {
          required: true,
        },

        email: {
          email: true,
        },

        picture: {
          extension: 'png|jpg|jpeg',
          filesize: 1048576 * 8,
        },

        userLetteringText: {
          required: () => $('#user-lettering').is(':checked')
        },
      },

      messages: {
        dress: {
          required: "Это обязательное поле",
        },

        'size-set-1': {
          required: "Это обязательное поле",
        },

        'size-set-2': {
          required: "Это обязательное поле",
        },

        'size-set-3': {
          required: "Это обязательное поле",
        },

        'size-set-4': {
          required: "Это обязательное поле",
        },

        'size-set-5': {
          required: "Это обязательное поле",
        },

        'size-set-6': {
          required: "Это обязательное поле",
        },

        'color-set-1': {
          required: "Это обязательное поле",
        },

        'color-set-2': {
          required: "Это обязательное поле",
        },

        'color-set-3': {
          required: "Это обязательное поле",
        },

        'color-set-4': {
          required: "Это обязательное поле",
        },

        'color-set-5': {
          required: "Это обязательное поле",
        },

        'color-set-6': {
          required: "Это обязательное поле",
        },

        thread: {
          required: "Это обязательное поле",
        },

        face: {
          required: "Это обязательное поле",
        },

        user: {
          required: "Это обязательное поле",
        },

        phone: {
          required: "Это обязательное поле",
          tel: "Введите валидный номер телефона",
        },

        email: {
          email: "Укажите правильный e-mail",
        },

        picture: {
          extension: 'Не верный формат файла',
          filesize: 'Файл превышает 8 мб',
        },

        userLetteringText: {
          required: "Это обязательное поле",
        }
      },

      errorPlacement: (error, element) => {
        const { errorcontainer } = $(element).data();
        error.addClass("help-block");
        $(errorcontainer).append(error);
      },

      highlight: (element, errorClass, validClass) => {
        $(element)
        .parents(".form-group")
        .addClass("has-danger")
        .removeClass("has-success");
      },

      unhighlight: (element, errorClass, validClass) => {
        $(element)
        .parents(".form-group")
        .addClass( "has-success")
        .removeClass("has-danger");
      },

      submitHandler: (form, event) => {
        const url = 'longForm.php';
        const data = new FormData(form);

        const success = () => {
          $('#call').modal('hide');
          $('#thx').modal('show');

          setTimeout(() => {
            $('#thx').modal('hide');
          }, 10000);
        }

        $.ajax({
          type: "POST",
          url: url,
          data: data,
          success: success,
          processData: false,
          contentType: false,
        });

        event.preventDefault();
      },
    }
  });

  $('.msf').on('msf:viewChanged', function() {
    $('html, body').animate({
      scrollTop: $('.msf').offset().top - offsetTopHeader
    }, 350);
  })

  const checkBoxLettering = $('#user-lettering');
  const letteringField = $('#user-letteringField');

  const isCheckedLettering = checkbox => checkbox.is(':checked');
  const shownLetteringField = isChecked => {
    if (isChecked) {
      $('#user-letteringField-error').css({display: 'block'});
      letteringField.css({display: 'block'})
    } else {
      $('#user-letteringField-error').css({display: 'none'});
      letteringField.css({display: 'none'})
    }
  }

  shownLetteringField(
    isCheckedLettering(
      checkBoxLettering,
    )
  );

  checkBoxLettering.on('change', () => {
    shownLetteringField(
      isCheckedLettering(
        checkBoxLettering,
      )
    );
  });

  const threadSetImageSrc = $('#threadSetImg');
  const threadImageChange = event => {
    if (event.target.getAttribute('src')) {
      const pathToImg = event.target.getAttribute('src');
      threadSetImageSrc.attr('src', pathToImg);
    }
  }

  $('input[name=thread]').on('change', threadImageChange)

  const threadSetImageSrc2 = $('#threadSetImg2');
  const threadImageChange2 = event => {
    if (event.target.getAttribute('src')) {
      const pathToImg = event.target.getAttribute('src');
      threadSetImageSrc2.attr('src', pathToImg);
    }
  }

  $('input[name=face]').on('change', threadImageChange2);

  Array.from(document.querySelectorAll('input[name=dress]')).map((input, idx) => {
    const content = Array.from(document.querySelectorAll('.dress-option'));
    $(input).on('change', ({target}) => {
      $('.dress-option').css({'display': 'none'});
      $(content[idx]).css({'display': 'block'});
      $('.dress-option .has-danger *').remove();
    });
  })

  $('[data-toggle="tooltip"]').tooltip();

  const disableTooltips = (() => {
    if (window.innerWidth < 460) {
      $('[data-toggle="tooltip"]').tooltip('dispose');
    }
  })();

  var pluginName = "Morphext",
  defaults = {
    animation: "bounceIn",
    separator: ",",
    speed: 2000,
    complete: $.noop
  };

  function Plugin (element, options) {
    this.element = $(element);

    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._init();
  }

  Plugin.prototype = {
    _init: function () {
      var $that = this;
      this.phrases = [];

      this.element.addClass("morphext");

      $.each(this.element.text().split(this.settings.separator), function (key, value) {
        $that.phrases.push($.trim(value));
      });

      this.index = -1;
      this.animate();
      this.start();
    },
    animate: function () {
      this.index = ++this.index % this.phrases.length;
      this.element[0].innerHTML = "<span class=\"animated " + this.settings.animation + "\">" + this.phrases[this.index] + "</span>";

      if ($.isFunction(this.settings.complete)) {
        this.settings.complete.call(this);
      }
    },
    start: function () {
      var $that = this;
      this._interval = setInterval(function () {
        $that.animate();
      }, this.settings.speed);
    },
    stop: function () {
      this._interval = clearInterval(this._interval);
    }
  };

  $.fn[pluginName] = function (options) {
    return this.each(function() {
      if (!$.data(this, "plugin_" + pluginName)) {
        $.data(this, "plugin_" + pluginName, new Plugin(this, options));
      }
    });
  };

  $('#morphext').Morphext({
    animation: "fadeInDown",
    separator: ",",
    speed: 2000,
  });
});


text:
'use strict';

(function($) {
  $.fn.phAnim = function( options ) {

    // Set default option
    var settings = $.extend({}, options),
    		label,
  			ph;

    // get label elem
    function getLabel(input) {
      return $(input).parent().find('label');
    }

    // generate an id
    function makeid() {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
      for( var i=0; i < 5; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));
      return text;
    }

    return this.each( function() {

      // check if the input has id or create one
      if( $(this).attr('id') == undefined ) {
        $(this).attr('id', makeid());
      }

      // check if elem has label or create one
      if( getLabel($(this)).length == 0 ) {

        // check if elem has placeholder
        if( $(this).attr('placeholder') != undefined ) {
          ph = $(this).attr('placeholder');
          $(this).attr('placeholder', '');
          // create a label with placeholder text
          $(this).parent().prepend('<label for='+ $(this).attr('id') +'>'+ ph +'</label>');
        }
      } else {

        // if elem has label remove placeholder
        $(this).attr('placeholder', '');
        // check label for attr or set it
        if(getLabel($(this)).attr('for') == undefined ) {
          getLabel($(this)).attr('for', $(this).attr('id'));

        }
      }

      $(this).on('focus', function() {
        label = getLabel($(this));
        label.addClass('active focusIn');
        if($(this).prop("tagName") === "TEXTAREA") $(this).addClass('textAreaHeight');
      }).on('focusout', function() {
        if( $(this).val() == '' ) {
          label.removeClass('active');
        }
        label.removeClass('focusIn');
        if($(this).prop("tagName") === "TEXTAREA") $(this).removeClass('textAreaHeight');;
      });
    });
  };
}(jQuery));

$(document).ready(function() {
	$('.custom-input input, textarea').phAnim();
});