text:
namespace MyCompany.MyProject.WebApi
{
    using Autofac;
    using Autofac.Extensions.DependencyInjection;
    using Dike.Core.Utils.Extensions;
    using Dike.Web;
    using Microsoft.ApplicationInsights;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.ApiExplorer;
    using Microsoft.AspNetCore.Mvc.Cors.Internal;
    using Microsoft.AspNetCore.Mvc.Versioning;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using MyCompany.MyProject.Authentication.JwtBearer;
    using MyCompany.MyProject.Configuration;
    using Serilog;
    using Swashbuckle.AspNetCore.Swagger;
    using System;
    using System.Linq;

#if FEATURE_SIGNALR
    using Microsoft.AspNet.SignalR;
    using Microsoft.Owin.Cors;
    using Owin;
    using Abp.Owin;
    using AedesIT.MyProject.Owin;
#endif

    /// <summary>
    /// Provides startup functionality for the Web-API.
    /// </summary>
    public class ApiStartup
    {
        #region Fields

        private const string _defaultCorsPolicyName = "localhost";

        private IContainer _applicationContainer;

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ApiStartup" /> class.
        /// </summary>
        /// <param name="env">The hosting environment.</param>
        public ApiStartup(IHostingEnvironment env)
        {
            Configuration = env.GetAppConfiguration();
        }

        #endregion Constructors

        #region Properties

        /// <summary>
        /// Gets the DI application container.
        /// </summary>
        /// <value>The DI application container.</value>
        public IContainer ApplicationContainer
            => _applicationContainer;

        /// <summary>
        /// Gets the configuration.
        /// </summary>
        /// <value>The configuration.</value>
        public IConfiguration Configuration
        {
            get;
        }

        #endregion Properties

        #region Methods

        /// <summary>
        /// Configures the application using the provided builder, hosting environment, and logging factory.
        /// </summary>
        /// <param name="app">The current application builder.</param>
        /// <param name="env">The current hosting environment.</param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            // configuring Application Insights service
            Microsoft.ApplicationInsights.DataContracts.TelemetryContext context = app.ApplicationServices.GetService<TelemetryClient>().Context;
            context.Properties["ApplicationName"] = typeof(ApiStartup).Assembly.GetName().Name;
            context.Component.Version = typeof(ApiStartup).Assembly.GetName().Version.ToString();

            // ensure that any buffered events are sent at shutdown
            IApplicationLifetime appLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>();
            appLifetime.ApplicationStopped.Register(Log.CloseAndFlush);

            // Initializes DIKE framework as WebApi
            app.UseDike(options =>
            {
                options.UseRequestLocalization = false;
            });

            // set exception page in function of environment
            if (env.IsDevelopment())
            {
                // activate developer exception page
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // TODO : IPA - activate our own exception page
                app.UseDeveloperExceptionPage();
            }

            // Enable CORS!
            app.UseCors(_defaultCorsPolicyName);

            // activate compression
            app.UseResponseCompression();

            app.UseStaticFiles();

            app.UseAuthentication();
            app.UseJwtTokenMiddleware();

            app.UseDikeRequestLocalization();

#if FEATURE_SIGNALR
            // Integrate to OWIN
            app.UseAppBuilder(ConfigureOwinServices);
#endif

            // activate MVC
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "defaultWithArea",
                    template: "{area}/{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            // Enable middle-ware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();

            // Enable middle-ware to serve SwaggerUI assets (HTML, JS, CSS etc.)
            app.UseSwaggerUI(options =>
            {
                options.InjectOnCompleteJavaScript("/scripts/swagger/ui/dike.js");
                options.InjectOnCompleteJavaScript("/scripts/swagger/ui/on-complete.js");

                // build a swagger endpoint for each discovered API version
                IApiVersionDescriptionProvider provider = app.ApplicationServices.GetRequiredService<IApiVersionDescriptionProvider>();
                foreach (ApiVersionDescription description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerEndpoint(
                        $"/swagger/{description.GroupName}/swagger.json",
                        description.GroupName.ToUpperInvariant());
                }

                // ------->
                // TODO : IPA - activate security for swaggger
                // Provide client ID, client secret, realm and application name
                // action.ConfigureOAuth2(
                //     currentSettings.Value.IdentityServer.SwaggerClientId,
                //     currentSettings.Value.IdentityServer.SwaggerClientSecret,
                //     "swagger-ui-realm",
                //     "Swagger UI");
                // <-------
            });

            // trace Web-API startup
            Log.Logger.Information("{AssemblyType} started", typeof(ApiStartup).Assembly.GetName().Name);
        }

        /// <summary>
        /// Configuring dependency injection services of the Web-API.
        /// </summary>
        /// <param name="services">Instance of the service collection.</param>
        /// <returns>A populated dependency injection service provider.</returns>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            // add compression
            services.AddResponseCompression();

            // add MVC Core services and :
            //    - format the version as "major[.minor][-status]"
            //    - Add controllers as services so they'll be resolved.
            services.AddMvcCore()
                .AddVersionedApiExplorer(options => options.GroupNameFormat = "VVV")
                .AddControllersAsServices();

            // add versioning
            services.AddApiVersioning(options =>
            {
                // configure versioning
                options.ReportApiVersions = true;
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                options.ApiVersionReader = new QueryStringApiVersionReader();
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory(_defaultCorsPolicyName));
            })
            .ConfigureApplicationPartManager(options =>
            {
                options.FeatureProviders.Add(new Dike.Web.Mvc.Providers.AppServiceControllerFeatureProvider());
            });

            Core.Identity.IdentityRegistrar.Register(services);
            AuthConfigurer.Configure(services, Configuration);

            // Configure CORS for angular2 UI
            services.AddCors(options =>
            {
                options.AddPolicy(_defaultCorsPolicyName, policyBuilder =>
                {
                    // App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
                    policyBuilder
                        .WithOrigins(Configuration["App:CorsOrigins"].Split(",", StringSplitOptions.RemoveEmptyEntries)
                                                                     .Select(o => o.RemovePostFix("/"))
                                                                     .ToArray())
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });

            // add Swagger and configure it
            services.AddSwaggerGen(options =>
            {
                // configure document filtering based on the version in the group names
                options.DocInclusionPredicate((docName, api)
                    => api.GroupName == null || api.GroupName.Contains(docName));

                // resolve the IApiVersionDescriptionProvider service
                IApiVersionDescriptionProvider provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();

                // add a swagger document for each discovered API version
                foreach (ApiVersionDescription description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerDoc(
                        description.GroupName,
                        new Info()
                        {
                            Title = $"{typeof(ApiStartup).Assembly.GetName().Name} {description.ApiVersion}".Trim(),
                            Version = description.ApiVersion.ToString(),
                        });
                }

                options.DocInclusionPredicate((docName, description) => true);

                // Define the BearerAuth scheme that's in use
                options.AddSecurityDefinition("bearerAuth", new ApiKeyScheme()
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name = "Authorization",
                    In = "header",
                    Type = "apiKey",
                });

                // Assign scope requirements to operations based on AuthorizeAttribute
                options.OperationFilter<SecurityRequirementsOperationFilter>();

                // TODO : IPA - Add XML files to swagger
                // add XML document files
                /////foreach (string file in setupOptions.XmlCommentFiles)
                ////{
                ////    options.IncludeXmlComments(file);
                ////}

                // ------->
                ////// add Accept-Language header parameter to filters
                ////options.OperationFilter<Swagger.AcceptLanguageOperationFilter>();
                // <-------
            });

            // Configure Dike and Dependency Injection
            _applicationContainer = services.AddDike<WebApiModule>();

            return new AutofacServiceProvider(_applicationContainer);
        }

        #endregion Methods

#if FEATURE_SIGNALR
        private static void ConfigureOwinServices(IAppBuilder app)
        {
            app.Properties["host.AppName"] = "MyProject";

            app.UseAbp();

            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    EnableJSONP = true
                };
                map.RunSignalR(hubConfiguration);
            });
        }
#endif
    }
}


text:
namespace FreelanceMe.Web.Areas.Administration.Controllers
{
    using AutoMapper.QueryableExtensions;
    using FreelanceMe.Data.Common.Models;
    using FreelanceMe.Data.Common.Repository;
    using FreelanceMe.Data.Models;
    using FreelanceMe.Web.Areas.Administration.Models.InputModels;
    using FreelanceMe.Web.Areas.Administration.Models.ViewModels;
    using System;
    using System.Data.Entity;
    using System.Linq;
    using System.Web.Mvc;

    public class CategoryController : Controller
    {
        private readonly IDeletableEntityRepository<Category> categories;
        private readonly IDeletableEntityRepository<Subcategory> subcategories;

        public CategoryController(IDeletableEntityRepository<Category> categories, IDeletableEntityRepository<Subcategory> subcategories)
        {
            this.categories = categories;
            this.subcategories = subcategories;
        }

        [HttpGet]
        public ActionResult Index(string search, int page = 1, int numberPerPage = 5)
        {
            if (search == null)
            {
                search = "";
            }

            var categoriesCount = this.categories
                .All()
                .Where(c => c.Name.Contains(search) || c.Description.Contains(search))
                .OrderBy(c => c.Name)
                .Count();

            var dbCategories = this.categories
                .All()
                .Where(c => c.Name.Contains(search) || c.Description.Contains(search))
                .OrderBy(c => c.Name)
                .Skip((page - 1) * numberPerPage)
                .Take(numberPerPage)
                .Project()
                .To<CategoryViewModel>()
                .ToList();

            ViewBag.Search = search;
            ViewBag.NumberOfPages = 1;
            if (categoriesCount > 0)
            {
                ViewBag.NumberOfPages = categoriesCount / numberPerPage;
                if (categoriesCount % numberPerPage > 0)
                {
                    ViewBag.NumberOfPages += 1;
                }
            }

            ViewBag.CurrentPage = page;
            ViewBag.NextPage = page + 1;
            ViewBag.PreviousPage = page - 1;

            if (page == ViewBag.NumberOfPages)
            {
                ViewBag.NextPage = page;
            }

            if (page == 1)
            {
                ViewBag.PreviousPage = 1;
            }

            return View(dbCategories);
        }

        [HttpGet]
        public ActionResult Create()
        {
            return this.PartialView("_CreatePartial");
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CategoryInputModel category)
        {
            if (!ModelState.IsValid)
            {
                return this.PartialView("_CreatePartial", category);
            }

            var categoryDb = this.categories.All().Where(c => c.Name == category.Name).FirstOrDefault();
            if (categoryDb != null)
            {
                ModelState.AddModelError("", "Category with the same name already exists!");
                return this.PartialView("_CreatePartial", category);
            }

            this.categories.Add(new Category()
            {
                Name = category.Name,
                Description = category.Description
            });
            this.categories.SaveChanges();

            return this.Json("OK");
        }

        [HttpGet]
        public ActionResult Delete(int id)
        {
            var category = this.categories.All().Where(c => c.Id == id).Project().To<CategoryViewModel>().FirstOrDefault();
            var subcategoriesDb = this.subcategories.All().Where(s => s.CategoryId == id).Project().To<SubcategoryViewModel>().ToList();

            if (category == null)
            {
                return this.RedirectToAction("Index");
            }

            return this.PartialView("_DeletePartial", new CategoriesViewModel { Category = category, Subcategories = subcategoriesDb });
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete()
        {
            string idString = this.RouteData.Values["id"].ToString();
            int id = 0;

            if (!int.TryParse(idString, out id))
            {
                return Json(new { error = string.Format("Category with ID = {0} does not exists!", idString) });
            }

            var subcategoriesDb = this.subcategories.All().Where(s => s.CategoryId == id).ToList();
            foreach (var subcategory in subcategoriesDb)
            {
                this.subcategories.Delete(subcategory);
            }

            this.subcategories.SaveChanges();

            this.categories.Delete(id);
            this.categories.SaveChanges();

            return this.Json("OK");
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            var categoryDb = this.categories.All().Where(c => c.Id == id).Project().To<CategoryViewModel>().FirstOrDefault();
            if (categoryDb == null)
            {
                return this.RedirectToAction("Index");
            }

            var subcategoriesDb = this.subcategories.All().Where(s => s.CategoryId == id).Project().To<SubcategoryViewModel>().ToList();

            return this.PartialView("_EditPartial", new CategoriesViewModel { Category = categoryDb, Subcategories = subcategoriesDb });
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package de.mosmann.topics.basics.data;

import java.util.Date;

import de.mosmann.common.models.property.AbstractPropertyAccess;

public class Birthday extends AbstractPropertyAccess<Date, FormData> {

	public Birthday() {
		super(Date.class);
	}

	@Override
	public Date read(FormData source) {
		return source.getBirthday();
	}

	@Override
	public void write(FormData source, Date newValue) {
		source.setBirthday(newValue);
	}
}


text:
#include "modules/websockets/DOMWebSocket.h"

#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/SourceLocation.h"
#include "bindings/modules/v8/StringOrStringSequence.h"
#include "core/dom/DOMArrayBuffer.h"
#include "core/dom/DOMArrayBufferView.h"
#include "core/dom/Document.h"
#include "core/dom/ExceptionCode.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/SecurityContext.h"
#include "core/events/MessageEvent.h"
#include "core/fileapi/Blob.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/UseCounter.h"
#include "core/frame/csp/ContentSecurityPolicy.h"
#include "core/inspector/ConsoleMessage.h"
#include "modules/websockets/CloseEvent.h"
#include "platform/Histogram.h"
#include "platform/Logging.h"
#include "platform/blob/BlobData.h"
#include "platform/weborigin/KnownPorts.h"
#include "platform/weborigin/SecurityOrigin.h"
#include "public/platform/Platform.h"
#include "public/platform/WebInsecureRequestPolicy.h"
#include "wtf/Assertions.h"
#include "wtf/HashSet.h"
#include "wtf/MathExtras.h"
#include "wtf/StdLibExtras.h"
#include "wtf/text/CString.h"
#include "wtf/text/StringBuilder.h"

static const size_t kMaxByteSizeForHistogram = 100 * 1000 * 1000;
static const int32_t kBucketCountForMessageSizeHistogram = 50;

namespace blink {

DOMWebSocket::EventQueue::EventQueue(EventTarget* target)
    : m_state(Active)
    , m_target(target)
    , m_resumeTimer(this, &EventQueue::resumeTimerFired) { }

DOMWebSocket::EventQueue::~EventQueue() { stop(); }

void DOMWebSocket::EventQueue::dispatch(Event* event)
{
    switch (m_state) {
    case Active:
        ASSERT(m_events.isEmpty());
        ASSERT(m_target->getExecutionContext());
        m_target->dispatchEvent(event);
        break;
    case Suspended:
        m_events.append(event);
        break;
    case Stopped:
        ASSERT(m_events.isEmpty());
        // Do nothing.
        break;
    }
}

bool DOMWebSocket::EventQueue::isEmpty() const
{
    return m_events.isEmpty();
}

void DOMWebSocket::EventQueue::suspend()
{
    m_resumeTimer.stop();
    if (m_state != Active)
        return;

    m_state = Suspended;
}

void DOMWebSocket::EventQueue::resume()
{
    if (m_state != Suspended || m_resumeTimer.isActive())
        return;

    m_resumeTimer.startOneShot(0, BLINK_FROM_HERE);
}

void DOMWebSocket::EventQueue::stop()
{
    if (m_state == Stopped)
        return;

    m_state = Stopped;
    m_resumeTimer.stop();
    m_events.clear();
}

void DOMWebSocket::EventQueue::dispatchQueuedEvents()
{
    if (m_state != Active)
        return;

    HeapDeque<Member<Event>> events;
    events.swap(m_events);
    while (!events.isEmpty()) {
        if (m_state == Stopped || m_state == Suspended)
            break;
        ASSERT(m_state == Active);
        ASSERT(m_target->getExecutionContext());
        m_target->dispatchEvent(events.takeFirst());
        // |this| can be stopped here.
    }
    if (m_state == Suspended) {
        while (!m_events.isEmpty())
            events.append(m_events.takeFirst());
        events.swap(m_events);
    }
}

void DOMWebSocket::EventQueue::resumeTimerFired(TimerBase*)
{
    ASSERT(m_state == Suspended);
    m_state = Active;
    dispatchQueuedEvents();
}

DEFINE_TRACE(DOMWebSocket::EventQueue)
{
    visitor->trace(m_target);
    visitor->trace(m_events);
}

const size_t maxReasonSizeInBytes = 123;

static inline bool isValidSubprotocolCharacter(UChar character)
{
    const UChar minimumProtocolCharacter = '!'; // U+0021.
    const UChar maximumProtocolCharacter = '~'; // U+007E.
    // Set to true if character does not matches "separators" ABNF defined in
    // RFC2616. SP and HT are excluded since the range check excludes them.
    bool isNotSeparator = character != '"' && character != '(' && character != ')' && character != ',' && character != '/'
        && !(character >= ':' && character <= '@') // U+003A - U+0040 (':', ';', '<', '=', '>', '?', '@').
        && !(character >= '[' && character <= ']') // U+005B - U+005D ('[', '\\', ']').
        && character != '{' && character != '}';
    return character >= minimumProtocolCharacter && character <= maximumProtocolCharacter && isNotSeparator;
}

bool DOMWebSocket::isValidSubprotocolString(const String& protocol)
{
    if (protocol.isEmpty())
        return false;
    for (size_t i = 0; i < protocol.length(); ++i) {
        if (!isValidSubprotocolCharacter(protocol[i]))
            return false;
    }
    return true;
}

static String encodeSubprotocolString(const String& protocol)
{
    StringBuilder builder;
    for (size_t i = 0; i < protocol.length(); i++) {
        if (protocol[i] < 0x20 || protocol[i] > 0x7E)
            builder.append(String::format("\\u%04X", protocol[i]));
        else if (protocol[i] == 0x5c)
            builder.append("\\\\");
        else
            builder.append(protocol[i]);
    }
    return builder.toString();
}

static String joinStrings(const Vector<String>& strings, const char* separator)
{
    StringBuilder builder;
    for (size_t i = 0; i < strings.size(); ++i) {
        if (i)
            builder.append(separator);
        builder.append(strings[i]);
    }
    return builder.toString();
}

static void setInvalidStateErrorForSendMethod(ExceptionState& exceptionState)
{
    exceptionState.throwDOMException(InvalidStateError, "Still in CONNECTING state.");
}

const char* DOMWebSocket::subprotocolSeperator()
{
    return ", ";
}

DOMWebSocket::DOMWebSocket(ExecutionContext* context)
    : ActiveScriptWrappable(this)
    , ActiveDOMObject(context)
    , m_state(kConnecting)
    , m_bufferedAmount(0)
    , m_consumedBufferedAmount(0)
    , m_bufferedAmountAfterClose(0)
    , m_binaryType(BinaryTypeBlob)
    , m_binaryTypeChangesAfterOpen(0)
    , m_subprotocol("")
    , m_extensions("")
    , m_eventQueue(EventQueue::create(this))
    , m_bufferedAmountConsumeTimer(this, &DOMWebSocket::reflectBufferedAmountConsumption)
{
}

DOMWebSocket::~DOMWebSocket()
{
    ASSERT(!m_channel);
}

void DOMWebSocket::logError(const String& message)
{
    getExecutionContext()->addConsoleMessage(ConsoleMessage::create(JSMessageSource, ErrorMessageLevel, message));
}

DOMWebSocket* DOMWebSocket::create(ExecutionContext* context, const String& url, ExceptionState& exceptionState)
{
    StringOrStringSequence protocols;
    return create(context, url, protocols, exceptionState);
}

DOMWebSocket* DOMWebSocket::create(ExecutionContext* context, const String& url, const StringOrStringSequence& protocols, ExceptionState& exceptionState)
{
    if (url.isNull()) {
        exceptionState.throwDOMException(SyntaxError, "Failed to create a WebSocket: the provided URL is invalid.");
        return nullptr;
    }

    DOMWebSocket* webSocket = new DOMWebSocket(context);
    webSocket->suspendIfNeeded();

    if (protocols.isNull()) {
        Vector<String> protocolsVector;
        webSocket->connect(url, protocolsVector, exceptionState);
    } else if (protocols.isString()) {
        Vector<String> protocolsVector;
        protocolsVector.append(protocols.getAsString());
        webSocket->connect(url, protocolsVector, exceptionState);
    } else {
        ASSERT(protocols.isStringSequence());
        webSocket->connect(url, protocols.getAsStringSequence(), exceptionState);
    }

    if (exceptionState.hadException())
        return nullptr;

    return webSocket;
}

void DOMWebSocket::connect(const String& url, const Vector<String>& protocols, ExceptionState& exceptionState)
{
    UseCounter::count(getExecutionContext(), UseCounter::WebSocket);

    WTF_LOG(Network, "WebSocket %p connect() url='%s'", this, url.utf8().data());
    m_url = KURL(KURL(), url);

    if (getExecutionContext()->securityContext().getInsecureRequestPolicy() & kUpgradeInsecureRequests && m_url.protocol() == "ws") {
        UseCounter::count(getExecutionContext(), UseCounter::UpgradeInsecureRequestsUpgradedRequest);
        m_url.setProtocol("wss");
        if (m_url.port() == 80)
            m_url.setPort(443);
    }

    if (!m_url.isValid()) {
        m_state = kClosed;
        exceptionState.throwDOMException(SyntaxError, "The URL '" + url + "' is invalid.");
        return;
    }
    if (!m_url.protocolIs("ws") && !m_url.protocolIs("wss")) {
        m_state = kClosed;
        exceptionState.throwDOMException(SyntaxError, "The URL's scheme must be either 'ws' or 'wss'. '" + m_url.protocol() + "' is not allowed.");
        return;
    }

    if (m_url.hasFragmentIdentifier()) {
        m_state = kClosed;
        exceptionState.throwDOMException(SyntaxError, "The URL contains a fragment identifier ('" + m_url.fragmentIdentifier() + "'). Fragment identifiers are not allowed in WebSocket URLs.");
        return;
    }

    if (!isPortAllowedForScheme(m_url)) {
        m_state = kClosed;
        exceptionState.throwSecurityError("The port " + String::number(m_url.port()) + " is not allowed.");
        return;
    }

    // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
    if (!ContentSecurityPolicy::shouldBypassMainWorld(getExecutionContext()) && !getExecutionContext()->contentSecurityPolicy()->allowConnectToSource(m_url)) {
        m_state = kClosed;
        // The URL is safe to expose to JavaScript, as this check happens synchronously before redirection.
        exceptionState.throwSecurityError("Refused to connect to '" + m_url.elidedString() + "' because it violates the document's Content Security Policy.");
        return;
    }

    // Fail if not all elements in |protocols| are valid.
    for (size_t i = 0; i < protocols.size(); ++i) {
        if (!isValidSubprotocolString(protocols[i])) {
            m_state = kClosed;
            exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeSubprotocolString(protocols[i]) + "' is invalid.");
            return;
        }
    }

    // Fail if there're duplicated elements in |protocols|.
    HashSet<String> visited;
    for (size_t i = 0; i < protocols.size(); ++i) {
        if (!visited.add(protocols[i]).isNewEntry) {
            m_state = kClosed;
            exceptionState.throwDOMException(SyntaxError, "The subprotocol '" + encodeSubprotocolString(protocols[i]) + "' is duplicated.");
            return;
        }
    }

    String protocolString;
    if (!protocols.isEmpty())
        protocolString = joinStrings(protocols, subprotocolSeperator());

    m_channel = createChannel(getExecutionContext(), this);

    if (!m_channel->connect(m_url, protocolString)) {
        m_state = kClosed;
        exceptionState.throwSecurityError("An insecure WebSocket connection may not be initiated from a page loaded over HTTPS.");
        releaseChannel();
        return;
    }
}

void DOMWebSocket::updateBufferedAmountAfterClose(uint64_t payloadSize)
{
    m_bufferedAmountAfterClose += payloadSize;

    logError("WebSocket is already in CLOSING or CLOSED state.");
}

void DOMWebSocket::reflectBufferedAmountConsumption(TimerBase*)
{
    ASSERT(m_bufferedAmount >= m_consumedBufferedAmount);
    // Cast to unsigned long long is required since clang doesn't accept
    // combination of %llu and uint64_t (known as unsigned long).
    WTF_LOG(Network, "WebSocket %p reflectBufferedAmountConsumption() %llu => %llu", this, static_cast<unsigned long long>(m_bufferedAmount), static_cast<unsigned long long>(m_bufferedAmount - m_consumedBufferedAmount));

    m_bufferedAmount -= m_consumedBufferedAmount;
    m_consumedBufferedAmount = 0;
}

void DOMWebSocket::releaseChannel()
{
    ASSERT(m_channel);
    m_channel->disconnect();
    m_channel = nullptr;
}

void DOMWebSocket::logBinaryTypeChangesAfterOpen()
{
    DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, binaryTypeChangesHistogram, new CustomCountHistogram("WebCore.WebSocket.BinaryTypeChangesAfterOpen", 1, 1024, 10));
    DVLOG(3) << "WebSocket " << static_cast<void*>(this) << " logBinaryTypeChangesAfterOpen() logging " << m_binaryTypeChangesAfterOpen;
    binaryTypeChangesHistogram.count(m_binaryTypeChangesAfterOpen);
}

void DOMWebSocket::send(const String& message, ExceptionState& exceptionState)
{
    CString encodedMessage = message.utf8();

    WTF_LOG(Network, "WebSocket %p send() Sending String '%s'", this, encodedMessage.data());
    if (m_state == kConnecting) {
        setInvalidStateErrorForSendMethod(exceptionState);
        return;
    }
    // No exception is raised if the connection was once established but has subsequently been closed.
    if (m_state == kClosing || m_state == kClosed) {
        updateBufferedAmountAfterClose(encodedMessage.length());
        return;
    }

    recordSendTypeHistogram(WebSocketSendTypeString);

    ASSERT(m_channel);
    m_bufferedAmount += encodedMessage.length();
    m_channel->send(encodedMessage);
}

void DOMWebSocket::send(DOMArrayBuffer* binaryData, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "WebSocket %p send() Sending ArrayBuffer %p", this, binaryData);
    ASSERT(binaryData && binaryData->buffer());
    if (m_state == kConnecting) {
        setInvalidStateErrorForSendMethod(exceptionState);
        return;
    }
    if (m_state == kClosing || m_state == kClosed) {
        updateBufferedAmountAfterClose(binaryData->byteLength());
        return;
    }
    recordSendTypeHistogram(WebSocketSendTypeArrayBuffer);
    recordSendMessageSizeHistogram(WebSocketSendTypeArrayBuffer, binaryData->byteLength());
    ASSERT(m_channel);
    m_bufferedAmount += binaryData->byteLength();
    m_channel->send(*binaryData, 0, binaryData->byteLength());
}

void DOMWebSocket::send(DOMArrayBufferView* arrayBufferView, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "WebSocket %p send() Sending ArrayBufferView %p", this, arrayBufferView);
    ASSERT(arrayBufferView);
    if (m_state == kConnecting) {
        setInvalidStateErrorForSendMethod(exceptionState);
        return;
    }
    if (m_state == kClosing || m_state == kClosed) {
        updateBufferedAmountAfterClose(arrayBufferView->byteLength());
        return;
    }
    recordSendTypeHistogram(WebSocketSendTypeArrayBufferView);
    recordSendMessageSizeHistogram(WebSocketSendTypeArrayBufferView, arrayBufferView->byteLength());
    ASSERT(m_channel);
    m_bufferedAmount += arrayBufferView->byteLength();
    m_channel->send(*arrayBufferView->buffer(), arrayBufferView->byteOffset(), arrayBufferView->byteLength());
}

void DOMWebSocket::send(Blob* binaryData, ExceptionState& exceptionState)
{
    WTF_LOG(Network, "WebSocket %p send() Sending Blob '%s'", this, binaryData->uuid().utf8().data());
    ASSERT(binaryData);
    if (m_state == kConnecting) {
        setInvalidStateErrorForSendMethod(exceptionState);
        return;
    }
    if (m_state == kClosing || m_state == kClosed) {
        updateBufferedAmountAfterClose(binaryData->size());
        return;
    }
    unsigned long long size = binaryData->size();
    recordSendTypeHistogram(WebSocketSendTypeBlob);
    recordSendMessageSizeHistogram(WebSocketSendTypeBlob, clampTo<size_t>(size, 0, kMaxByteSizeForHistogram));
    m_bufferedAmount += size;
    ASSERT(m_channel);

    // When the runtime type of |binaryData| is File,
    // binaryData->blobDataHandle()->size() returns -1. However, in order to
    // maintain the value of |m_bufferedAmount| correctly, the WebSocket code
    // needs to fix the size of the File at this point. For this reason,
    // construct a new BlobDataHandle here with the size that this method
    // observed.
    m_channel->send(BlobDataHandle::create(binaryData->uuid(), binaryData->type(), size));
}

void DOMWebSocket::close(unsigned short code, const String& reason, ExceptionState& exceptionState)
{
    closeInternal(code, reason, exceptionState);
}

void DOMWebSocket::close(ExceptionState& exceptionState)
{
    closeInternal(WebSocketChannel::CloseEventCodeNotSpecified, String(), exceptionState);
}

void DOMWebSocket::close(unsigned short code, ExceptionState& exceptionState)
{
    closeInternal(code, String(), exceptionState);
}

void DOMWebSocket::closeInternal(int code, const String& reason, ExceptionState& exceptionState)
{
    String cleansedReason = reason;
    if (code == WebSocketChannel::CloseEventCodeNotSpecified) {
        WTF_LOG(Network, "WebSocket %p close() without code and reason", this);
    } else {
        WTF_LOG(Network, "WebSocket %p close() code=%d reason='%s'", this, code, reason.utf8().data());
        if (!(code == WebSocketChannel::CloseEventCodeNormalClosure || (WebSocketChannel::CloseEventCodeMinimumUserDefined <= code && code <= WebSocketChannel::CloseEventCodeMaximumUserDefined))) {
            exceptionState.throwDOMException(InvalidAccessError, "The code must be either 1000, or between 3000 and 4999. " + String::number(code) + " is neither.");
            return;
        }
        // Bindings specify USVString, so unpaired surrogates are already replaced with U+FFFD.
        CString utf8 = reason.utf8();
        if (utf8.length() > maxReasonSizeInBytes) {
            exceptionState.throwDOMException(SyntaxError, "The message must not be greater than " + String::number(maxReasonSizeInBytes) + " bytes.");
            return;
        }
        if (!reason.isEmpty() && !reason.is8Bit()) {
            ASSERT(utf8.length() > 0);
            // reason might contain unpaired surrogates. Reconstruct it from
            // utf8.
            cleansedReason = String::fromUTF8(utf8.data(), utf8.length());
        }
    }

    if (m_state == kClosing || m_state == kClosed)
        return;
    if (m_state == kConnecting) {
        m_state = kClosing;
        m_channel->fail("WebSocket is closed before the connection is established.", WarningMessageLevel, SourceLocation::create(String(), 0, 0, nullptr));
        return;
    }
    m_state = kClosing;
    if (m_channel)
        m_channel->close(code, cleansedReason);
}

const KURL& DOMWebSocket::url() const
{
    return m_url;
}

DOMWebSocket::State DOMWebSocket::readyState() const
{
    return m_state;
}

unsigned DOMWebSocket::bufferedAmount() const
{
    uint64_t sum = m_bufferedAmountAfterClose + m_bufferedAmount;

    if (sum > std::numeric_limits<unsigned>::max())
        return std::numeric_limits<unsigned>::max();
    return sum;
}

String DOMWebSocket::protocol() const
{
    return m_subprotocol;
}

String DOMWebSocket::extensions() const
{
    return m_extensions;
}

String DOMWebSocket::binaryType() const
{
    switch (m_binaryType) {
    case BinaryTypeBlob:
        return "blob";
    case BinaryTypeArrayBuffer:
        return "arraybuffer";
    }
    ASSERT_NOT_REACHED();
    return String();
}

void DOMWebSocket::setBinaryType(const String& binaryType)
{
    if (binaryType == "blob") {
        setBinaryTypeInternal(BinaryTypeBlob);
        return;
    }
    if (binaryType == "arraybuffer") {
        setBinaryTypeInternal(BinaryTypeArrayBuffer);
        return;
    }
    ASSERT_NOT_REACHED();
}

void DOMWebSocket::setBinaryTypeInternal(BinaryType binaryType)
{
    if (m_binaryType == binaryType)
        return;
    m_binaryType = binaryType;
    if (m_state == kOpen || m_state == kClosing)
        ++m_binaryTypeChangesAfterOpen;
}

const AtomicString& DOMWebSocket::interfaceName() const
{
    return EventTargetNames::DOMWebSocket;
}

ExecutionContext* DOMWebSocket::getExecutionContext() const
{
    return ActiveDOMObject::getExecutionContext();
}

void DOMWebSocket::contextDestroyed()
{
    WTF_LOG(Network, "WebSocket %p contextDestroyed()", this);
    DCHECK(!m_channel);
    DCHECK_EQ(kClosed, m_state);
    ActiveDOMObject::contextDestroyed();
}

bool DOMWebSocket::hasPendingActivity() const
{
    return m_channel || !m_eventQueue->isEmpty();
}

void DOMWebSocket::suspend()
{
    m_eventQueue->suspend();
}

void DOMWebSocket::resume()
{
    m_eventQueue->resume();
}

void DOMWebSocket::stop()
{
    m_eventQueue->stop();
    if (m_channel) {
        m_channel->close(WebSocketChannel::CloseEventCodeGoingAway, String());
        releaseChannel();
    }
    if (m_state != kClosed) {
        m_state = kClosed;
        logBinaryTypeChangesAfterOpen();
    }
}

void DOMWebSocket::didConnect(const String& subprotocol, const String& extensions)
{
    WTF_LOG(Network, "WebSocket %p didConnect()", this);
    if (m_state != kConnecting)
        return;
    m_state = kOpen;
    m_subprotocol = subprotocol;
    m_extensions = extensions;
    m_eventQueue->dispatch(Event::create(EventTypeNames::open));
}

void DOMWebSocket::didReceiveTextMessage(const String& msg)
{
    WTF_LOG(Network, "WebSocket %p didReceiveTextMessage() Text message '%s'", this, msg.utf8().data());
    if (m_state != kOpen)
        return;
    recordReceiveTypeHistogram(WebSocketReceiveTypeString);

    m_eventQueue->dispatch(MessageEvent::create(msg, SecurityOrigin::create(m_url)->toString()));
}

void DOMWebSocket::didReceiveBinaryMessage(std::unique_ptr<Vector<char>> binaryData)
{
    WTF_LOG(Network, "WebSocket %p didReceiveBinaryMessage() %lu byte binary message", this, static_cast<unsigned long>(binaryData->size()));
    switch (m_binaryType) {
    case BinaryTypeBlob: {
        size_t size = binaryData->size();
        RefPtr<RawData> rawData = RawData::create();
        binaryData->swap(*rawData->mutableData());
        std::unique_ptr<BlobData> blobData = BlobData::create();
        blobData->appendData(rawData.release(), 0, BlobDataItem::toEndOfFile);
        Blob* blob = Blob::create(BlobDataHandle::create(std::move(blobData), size));
        recordReceiveTypeHistogram(WebSocketReceiveTypeBlob);
        recordReceiveMessageSizeHistogram(WebSocketReceiveTypeBlob, size);
        m_eventQueue->dispatch(MessageEvent::create(blob, SecurityOrigin::create(m_url)->toString()));
        break;
    }

    case BinaryTypeArrayBuffer:
        DOMArrayBuffer* arrayBuffer = DOMArrayBuffer::create(binaryData->data(), binaryData->size());
        recordReceiveTypeHistogram(WebSocketReceiveTypeArrayBuffer);
        recordReceiveMessageSizeHistogram(WebSocketReceiveTypeArrayBuffer, binaryData->size());
        m_eventQueue->dispatch(MessageEvent::create(arrayBuffer, SecurityOrigin::create(m_url)->toString()));
        break;
    }
}

void DOMWebSocket::didError()
{
    WTF_LOG(Network, "WebSocket %p didError()", this);
    m_state = kClosed;
    logBinaryTypeChangesAfterOpen();
    m_eventQueue->dispatch(Event::create(EventTypeNames::error));
}

void DOMWebSocket::didConsumeBufferedAmount(uint64_t consumed)
{
    ASSERT(m_bufferedAmount >= consumed + m_consumedBufferedAmount);
    // Cast to unsigned long long is required since clang doesn't accept
    // combination of %llu and uint64_t (known as unsigned long).
    WTF_LOG(Network, "WebSocket %p didConsumeBufferedAmount(%llu)", this, static_cast<unsigned long long>(consumed));
    if (m_state == kClosed)
        return;
    m_consumedBufferedAmount += consumed;
    if (!m_bufferedAmountConsumeTimer.isActive())
        m_bufferedAmountConsumeTimer.startOneShot(0, BLINK_FROM_HERE);
}

void DOMWebSocket::didStartClosingHandshake()
{
    WTF_LOG(Network, "WebSocket %p didStartClosingHandshake()", this);
    m_state = kClosing;
}

void DOMWebSocket::didClose(ClosingHandshakeCompletionStatus closingHandshakeCompletion, unsigned short code, const String& reason)
{
    WTF_LOG(Network, "WebSocket %p didClose()", this);
    if (!m_channel)
        return;
    bool allDataHasBeenConsumed = m_bufferedAmount == m_consumedBufferedAmount;
    bool wasClean = m_state == kClosing && allDataHasBeenConsumed && closingHandshakeCompletion == ClosingHandshakeComplete && code != WebSocketChannel::CloseEventCodeAbnormalClosure;
    m_state = kClosed;

    m_eventQueue->dispatch(CloseEvent::create(wasClean, code, reason));
    releaseChannel();
}

void DOMWebSocket::recordSendTypeHistogram(WebSocketSendType type)
{
    DEFINE_THREAD_SAFE_STATIC_LOCAL(EnumerationHistogram, sendTypeHistogram, new EnumerationHistogram("WebCore.WebSocket.SendType", WebSocketSendTypeMax));
    sendTypeHistogram.count(type);
}

void DOMWebSocket::recordSendMessageSizeHistogram(WebSocketSendType type, size_t size)
{
    // Truncate |size| to avoid overflowing int32_t.
    int32_t sizeToCount = clampTo<int32_t>(size, 0, kMaxByteSizeForHistogram);
    switch (type) {
    case WebSocketSendTypeArrayBuffer: {
        DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, arrayBufferMessageSizeHistogram, new CustomCountHistogram("WebCore.WebSocket.MessageSize.Send.ArrayBuffer", 1, kMaxByteSizeForHistogram, kBucketCountForMessageSizeHistogram));
        arrayBufferMessageSizeHistogram.count(sizeToCount);
        return;
    }

    case WebSocketSendTypeArrayBufferView: {
        DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, arrayBufferViewMessageSizeHistogram, new CustomCountHistogram("WebCore.WebSocket.MessageSize.Send.ArrayBufferView", 1, kMaxByteSizeForHistogram, kBucketCountForMessageSizeHistogram));
        arrayBufferViewMessageSizeHistogram.count(sizeToCount);
        return;
    }

    case WebSocketSendTypeBlob: {
        DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, blobMessageSizeHistogram, new CustomCountHistogram("WebCore.WebSocket.MessageSize.Send.Blob", 1, kMaxByteSizeForHistogram, kBucketCountForMessageSizeHistogram));
        blobMessageSizeHistogram.count(sizeToCount);
        return;
    }

    default:
        NOTREACHED();
    }
}

void DOMWebSocket::recordReceiveTypeHistogram(WebSocketReceiveType type)
{
    DEFINE_THREAD_SAFE_STATIC_LOCAL(EnumerationHistogram, receiveTypeHistogram, new EnumerationHistogram("WebCore.WebSocket.ReceiveType", WebSocketReceiveTypeMax));
    receiveTypeHistogram.count(type);
}

void DOMWebSocket::recordReceiveMessageSizeHistogram(WebSocketReceiveType type, size_t size)
{
    // Truncate |size| to avoid overflowing int32_t.
    int32_t sizeToCount = clampTo<int32_t>(size, 0, kMaxByteSizeForHistogram);
    switch (type) {
    case WebSocketReceiveTypeArrayBuffer: {
        DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, arrayBufferMessageSizeHistogram, new CustomCountHistogram("WebCore.WebSocket.MessageSize.Receive.ArrayBuffer", 1, kMaxByteSizeForHistogram, kBucketCountForMessageSizeHistogram));
        arrayBufferMessageSizeHistogram.count(sizeToCount);
        return;
    }

    case WebSocketReceiveTypeBlob: {
        DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, blobMessageSizeHistogram, new CustomCountHistogram("WebCore.WebSocket.MessageSize.Receive.Blob", 1, kMaxByteSizeForHistogram, kBucketCountForMessageSizeHistogram));
        blobMessageSizeHistogram.count(sizeToCount);
        return;
    }

    default:
        NOTREACHED();
    }
}

DEFINE_TRACE(DOMWebSocket)
{
    visitor->trace(m_channel);
    visitor->trace(m_eventQueue);
    WebSocketChannelClient::trace(visitor);
    EventTargetWithInlineData::trace(visitor);
    ActiveDOMObject::trace(visitor);
}

} // namespace blink


text:
package org.apache.ivory.rerun.policy;

import java.util.Date;

import org.apache.ivory.IvoryException;
import org.apache.ivory.entity.v0.Frequency;
import org.apache.ivory.expression.ExpressionHelper;

public abstract class AbstractRerunPolicy {

	public long getDurationInMilliSec(Frequency frequency)
			throws IvoryException {
		ExpressionHelper helper = ExpressionHelper.get();
		return helper.evaluate(frequency.toString(), Long.class);

	}

	public static Date addTime(Date date, int milliSecondsToAdd) {
		return new Date(date.getTime() + milliSecondsToAdd);
	}

	public abstract long getDelay(Frequency delay, int eventNumber)
			throws IvoryException;

	public abstract long getDelay(Frequency delay, Date nominaltime,
			Date cutOffTime) throws IvoryException;
}


text:
import ApplicationAdapter from './application';

export default ApplicationAdapter.extend({

  urlForQuery(query, modelName) {  // jshint ignore:line
    const baseUrl = this.get('baseUrl');
    const params = `offset=${query.offset}&limit=${query.limit}`;

    return `${baseUrl}/me/playlists?${params}`;
  },

  urlForFindRecord(id, modelName, snapshot) {
    const baseUrl = this.get('baseUrl');
    const { ownerId } = snapshot.adapterOptions;
    const params = 'fields=description,external_urls,followers,id,images,name,owner,uri';

    return `${baseUrl}/users/${ownerId}/playlists/${id}/?${params}`;
  }

});


text:
'use strict';
import { expect } from 'chai';
import sinon from 'sinon';
import sinonTest from 'sinon-test';
import Faker from '../../src/index';
import data from '../../src/data/food.json';
const test = sinonTest(sinon, {useFakeTimers: false});

describe('Food', () => {
  describe('#ingredient', () => {
    it('should return a ingredient', test(function(this: typeof sinon) {
      this.stub(Faker.Random, 'element').withArgs(data['ingredients']).returns('ingredient');
      expect(Faker.Food.ingredient()).to.eql('ingredient');
    }));
  });

  describe('#spice', () => {
    it('should return a spice', test(function(this: typeof sinon) {
      this.stub(Faker.Random, 'element').withArgs(data['spices']).returns('spice');
      expect(Faker.Food.spice()).to.eql('spice');
    }));
  });

  describe('#measurement', () => {
    it('should return a measurement', test(function(this: typeof sinon) {
      this.stub(Faker.Random, 'element').withArgs(data['measurements']).returns('measurement');
      expect(Faker.Food.measurement()).to.eql('measurement');
    }));
  });
});


text:
var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter.Router;
var Route = ReactRouter.Route;
var IndexRoute = ReactRouter.IndexRoute;
var hashHistory = ReactRouter.hashHistory;
var Main = require('../components/Main');
var Home = require('../components/Home');

var routes = (
    <Router history={hashHistory}>
        <Route path='/' component={Main}>
            <IndexRoute path='/home' component={Home} />
        </Route>
    </Router>
);

module.exports = routes;


text:
import regexp from 'utils/regexp'
import fetch from 'isomorphic-fetch'
// import jsonp from 'fetch-jsonp'
// ------------------------------------
// Constants
// ------------------------------------
export const SUCCESS_GET_PRODUCT = 'SUCCESS_GET_PRODUCT'; //获取商品详情
export const FAILURE_GET_PRODUCT = 'FAILURE_GET_PRODUCT';

export const SUCCESS_GET_FARMER_PRODUCTS = 'SUCCESS_GET_FARMER_PRODUCTS'; //获取农场商品列表
export const FAILURE_GET_FARMER_PRODUCTS = 'FAILURE_GET_FARMER_PRODUCTS';

export const SUCCESS_GET_RECOMM_PRODUCTS = 'SUCCESS_GET_RECOMM_PRODUCTS'; //获取猜你喜欢商品列表
export const FAILURE_GET_RECOMM_PRODUCTS = 'FAILURE_GET_RECOMM_PRODUCTS';

export const SUCCESS_GET_PRODUCT_COMMENTS = 'SUCCESS_GET_PRODUCT_COMMENTS'; //获取商品评论
export const FAILURE_GET_PRODUCT_COMMENTS = 'FAILURE_GET_PRODUCT_COMMENTS';

export const CHECK_FAILURE_COMMENT = 'CHECK_FAILURE_COMMENT'; //评论校验失败
export const INIT_CHECK_COMMENT = 'INIT_CHECK_COMMENT';

export const SUCCESS_COMMENT = 'SUCCESS_COMMENT'; //评论
export const FAILURE_COMMENT = 'FAILURE_COMMENT';

export const SUCCESS_GET_PRODUCTS_BY_CATE = 'SUCCESS_GET_PRODUCTS_BY_CATE'; //根据分类查询商品列表
export const FAILURE_GET_PRODUCTS_BY_CATE = 'FAILURE_GET_PRODUCTS_BY_CATE';

export const ADD_PRODUCT_VIEW_HISTORY = 'ADD_PRODUCT_VIEW_HISTORY'; // 增加商品详情浏览历史
export const GET_PRODUCT_VIEW_HISTORY = 'GET_PRODUCT_VIEW_HISTORY'; // 查询商品详情历史

// ------------------------------------
// States
// ------------------------------------
const state = {
  productViewHistory: [],
  productsByCate: {},
  detail: {},
  farmerGoods: {},
  comments: {},
  promotions: [],
  comment: null
}

// ------------------------------------
// Getters
// ------------------------------------
export const getters = {
    productViewHistory: state => state.productViewHistory,
    productsByCate: state => state.productsByCate,
    productDetail: state => state.detail,
    productComments: state => state.comments,
    farmerGoods: state => state.farmerGoods
}

// ------------------------------------
// Action Handlers
// ------------------------------------
export const actions = {
  initCheckComment({commit}){
    commit(INIT_CHECK_COMMENT);
  },

  async getDetail({commit}, productId) {
    //发起ajax请求获取商品详情 'POST  http://ransj.com/detail/254'
    try{
      const res = await fetch(`http://ransj.com/detail/${productId}`, {
        method: "POST",
        body: ''
      })
      const detail = await res.json();
      if(detail && detail.id){
        commit(SUCCESS_GET_PRODUCT, detail);
      } else {
        commit(FAILURE_GET_PRODUCT);
      }
      return detail;
    } catch(e){
      commit(FAILURE_GET_PRODUCT);
    }
  },

  async getFarmerGoods({commit}, farmerid) {
    //发起ajax请求获取农场商品列表 'POST  http://ransj.com/topic/farmergoods?farmer_id=263'
    try{
      const res = await fetch(`http://ransj.com/topic/farmergoods?farmer_id=${farmerid}`)
      const data = await res.json();
      if(data && data.data){
        commit(SUCCESS_GET_FARMER_PRODUCTS, data);
      } else {
        commit(FAILURE_GET_FARMER_PRODUCTS);
      }
    } catch(e){
      commit(FAILURE_GET_FARMER_PRODUCTS);
    }
  },

  async getComments({commit}, productId){
    //发起ajax请求获取商品评论
    try{
      const res = await fetch(`http://ransj.com/comment?tid=${productId}`, {
        method: "POST",
        body: ''
      })
      const json = await res.json();
      if(json && json.errno == 0 && json.data.count) {
        commit(SUCCESS_GET_PRODUCT_COMMENTS, json.data);
      } else {
        commit(FAILURE_GET_PRODUCT_COMMENTS);
      }

    } catch(e){
      console.log(e)
      commit(FAILURE_GET_PRODUCT_COMMENTS);
    }

  },

  comment({commit}, param){
    //ajax发起评论
    commit(SUCCESS_COMMENT, {});
  },

  //根据分类查询分类列表
  async getProductListByCate({commit}, catId){
    //发起ajax请求获取商品评论
    const res = await fetch(`http://ransj.com/topic/list?category=${catId}`, {
      method: "POST",
      mode: 'cors',
      credentials: 'include',  // ['cors', include', 'same-origin']
      headers: {
        'Accept': 'application/json',
        'x-requested-with': 'XMLHttpRequest',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(catId)
    })
    const json = await res.json();
    if(json && json.data) {
      commit(SUCCESS_GET_PRODUCTS_BY_CATE, json)
    } else {
      commit(FAILURE_GET_PRODUCTS_BY_CATE, json)
    }
  },

  //添加商品浏览详情
  addProductViewHistory({commit}, product){
    let price, findIndex, item, history = store.get('productViewHistory');

    try{
      price = JSON.parse(product.price);
    } catch(e) {}
    item = {
      id: product.id,
      title: product.title,
      image: product.pictures[0],
      farm: product.farmer.title,
      specs: product.specification,
      price: price.present_price,
      price2: price.discount_price,
      viewTime: new Date().getTime()
    }

    if(!history || !history.length) {
      history = []
    }
    //删除相同的ID历史
    findIndex = history.findIndex((item)=>{
      return item.id == product.id
    })
    if(findIndex != -1) {
      history.splice(findIndex, 1)
    }

    //插入新的浏览记录
    history.unshift(item)

    store.set('productViewHistory', history);
    commit(ADD_PRODUCT_VIEW_HISTORY, history);
  },

  //查询商品浏览详情
  getProductViewHistory({commit}){
    let history = store.get('productViewHistory');
    commit(GET_PRODUCT_VIEW_HISTORY, history);
  }
}

// ------------------------------------
// Mutations
// ------------------------------------
export const mutations = {
  [CHECK_FAILURE_COMMENT](state, errorType){

  },

  [INIT_CHECK_COMMENT] (state) {
    state.comment = null;
  },

  //查询商品详情
  [SUCCESS_GET_PRODUCT](state, payload){
    state.detail = payload;
  },

  [FAILURE_GET_PRODUCT](state,data){
    state.detail = null
  },

  // 商品评论
  [SUCCESS_GET_PRODUCT_COMMENTS](state, payload){
    state.comments = payload;
  },

  [FAILURE_GET_PRODUCT_COMMENTS](state,data){
    state.comments = null
  },

  // 农场商品
  [SUCCESS_GET_FARMER_PRODUCTS](state, payload){
    state.farmerGoods = payload;
  },

  [FAILURE_GET_FARMER_PRODUCTS](state,data){
    state.farmerGoods = null
  },

  //查询某二级分类的商品列表
  [SUCCESS_GET_PRODUCTS_BY_CATE](state, payload){
    state.productsByCate = payload;
  },

  [FAILURE_GET_PRODUCTS_BY_CATE](state,data){
    state.productsByCate = null
  },

  //商品浏览详情 [增加/查询]
  [ADD_PRODUCT_VIEW_HISTORY](state, data){
    state.productViewHistory = data
  },

  [GET_PRODUCT_VIEW_HISTORY](state,data){
    state.productViewHistory = data
  },
}

export default {
    state,
    getters,
    actions,
    mutations
}


text:
import React from 'react'

export const HomeView = () => (

& Teges

    itenteges@gmail.com

)

export default HomeView


text:
layout: default
---

{% include when.html %}

{% include sponsors.html %}

{% include map.html %}

{% include organizers.html %}


text:
<?php

namespace Oro\Bundle\EmailBundle\Datagrid;

use Oro\Bundle\DataGridBundle\Datasource\ResultRecordInterface;

class EmailTemplatesGridHelper
{
    /** @var array */
    protected $entityNameChoices;

    public function __construct($entitiesConfig = [])
    {
        $this->entityNameChoices = array_map(
            function ($value) {
                return isset($value['name']) ? $value['name'] : '';
            },
            $entitiesConfig
        );
    }

    /**
     * Returns callback for configuration of grid/actions visibility per row
     *
     * @return callable
     */
    public function getActionConfigurationClosure()
    {
        return function (ResultRecordInterface $record) {
            if ($record->getValue('isSystem')) {
                return array('delete' => false);
            }
        };
    }

    /**
     * Returns choice list for entityName filter
     *
     * @return array
     */
    public function getEntityNameChoices()
    {
        return $this->entityNameChoices;
    }

    /**
     * Returns email template type choice list
     *
     * @return array
     */
    public function getTypeChoices()
    {
        return [
            'html' => 'oro.email.datagrid.emailtemplate.filter.type.html',
            'txt'  => 'oro.email.datagrid.emailtemplate.filter.type.txt'
        ];
    }

    /**
     * Returns choice list for isSystem field and filter
     *
     * @return array
     */
    public function getSystemChoices()
    {
        return [
            'oro.email.datagrid.emailtemplate.filter.isSystem.no',
            'oro.email.datagrid.emailtemplate.filter.isSystem.yes'
        ];
    }
}


text:
package org.usfirst.frc.team3019.robot.utilities;

public enum AutonomousMode {
	DRIVEFWD, TENSHOTRED, TENSHOTBLUE, TESTAUTOBLUE,GEARBLUE, BLUECOMBO;
}


text:
package com.orientechnologies.orient.core.index;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.orientechnologies.common.collection.OCompositeKey;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.OMultiValueChangeEvent;
import com.orientechnologies.orient.core.db.record.OMultiValueChangeListener;
import com.orientechnologies.orient.core.db.record.OTrackedList;
import com.orientechnologies.orient.core.db.record.OTrackedMap;
import com.orientechnologies.orient.core.db.record.OTrackedSet;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;

@Test
@SuppressWarnings("unchecked")
public class OCompositeIndexDefinitionTest {
  private OCompositeIndexDefinition compositeIndex;

  @BeforeMethod
  public void beforeMethod() {
    compositeIndex = new OCompositeIndexDefinition("testClass");

    compositeIndex.addIndex(new OPropertyIndexDefinition("testClass", "fOne", OType.INTEGER));
    compositeIndex.addIndex(new OPropertyIndexDefinition("testClass", "fTwo", OType.STRING));
  }

  @Test
  public void testGetFields() {
    final List<String> fields = compositeIndex.getFields();

    Assert.assertEquals(fields.size(), 2);
    Assert.assertEquals(fields.get(0), "fOne");
    Assert.assertEquals(fields.get(1), "fTwo");
  }

  @Test
  public void testCreateValueSuccessful() {
    final Object result = compositeIndex.createValue(Arrays.asList("12", "test"));

    Assert.assertEquals(result, new OCompositeKey(Arrays.asList(12, "test")));
  }

  @Test
  public void testCreateMapValueSuccessful() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyMapIndexDefinition("testCollectionClass", "fTwo", OType.STRING,
        OPropertyMapIndexDefinition.INDEX_BY.KEY));

    final Map<String, String> stringMap = new HashMap<String, String>();
    stringMap.put("key1", "val1");
    stringMap.put("key2", "val2");

    final Object result = compositeIndexDefinition.createValue(12, stringMap);

    final Collection<OCompositeKey> collectionResult = (Collection<OCompositeKey>) result;

    Assert.assertEquals(collectionResult.size(), 2);
    Assert.assertTrue(collectionResult.contains(new OCompositeKey(12, "key1")));
    Assert.assertTrue(collectionResult.contains(new OCompositeKey(12, "key2")));
  }

  @Test
  public void testCreateCollectionValueSuccessfulOne() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));

    final Object result = compositeIndexDefinition.createValue(12, Arrays.asList(1, 2));

    final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();

    expectedResult.add(new OCompositeKey(12, 1));
    expectedResult.add(new OCompositeKey(12, 2));

    Assert.assertEquals(result, expectedResult);
  }

  @Test
  public void testCreateCollectionValueSuccessfulTwo() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));

    final Object result = compositeIndexDefinition.createValue(Arrays.asList(Arrays.asList(1, 2), 12));

    final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();

    expectedResult.add(new OCompositeKey(1, 12));
    expectedResult.add(new OCompositeKey(2, 12));

    Assert.assertEquals(result, expectedResult);
  }

  @Test
  public void testCreateCollectionValueSuccessfulThree() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.STRING));

    final Object result = compositeIndexDefinition.createValue(12, Arrays.asList(1, 2), "test");

    final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();

    expectedResult.add(new OCompositeKey(12, 1, "test"));
    expectedResult.add(new OCompositeKey(12, 2, "test"));

    Assert.assertEquals(result, expectedResult);
  }

  @Test(expectedExceptions = OIndexException.class)
  public void testCreateCollectionValueTwoCollections() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));

    compositeIndexDefinition.createValue(Arrays.asList(1, 2), Arrays.asList(12));
  }

  @Test(expectedExceptions = NumberFormatException.class)
  public void testCreateValueWrongParam() {
    compositeIndex.createValue(Arrays.asList("1t2", "test"));
  }

  @Test
  public void testCreateValueSuccessfulArrayParams() {
    final Object result = compositeIndex.createValue("12", "test");

    Assert.assertEquals(result, new OCompositeKey(Arrays.asList(12, "test")));
  }

  @Test(expectedExceptions = NumberFormatException.class)
  public void testCreateValueWrongParamArrayParams() {
    compositeIndex.createValue("1t2", "test");
  }

  @Test
  public void testCreateValueDefinitionsMoreThanParams() {
    compositeIndex.addIndex(new OPropertyIndexDefinition("testClass", "fThree", OType.STRING));

    final Object result = compositeIndex.createValue("12", "test");
    Assert.assertEquals(result, new OCompositeKey(Arrays.asList(12, "test")));
  }

  @Test
  public void testCreateValueIndexItemWithTwoParams() {
    final OCompositeIndexDefinition anotherCompositeIndex = new OCompositeIndexDefinition("testClass");

    anotherCompositeIndex.addIndex(new OPropertyIndexDefinition("testClass", "f11", OType.STRING));
    anotherCompositeIndex.addIndex(new OPropertyIndexDefinition("testClass", "f22", OType.STRING));

    compositeIndex.addIndex(anotherCompositeIndex);

    final Object result = compositeIndex.createValue("12", "test", "tset");
    Assert.assertEquals(result, new OCompositeKey(Arrays.asList(12, "test", "tset")));
  }

  @Test
  public void testDocumentToIndexSuccessful() {
    final ODocument document = new ODocument();

    document.field("fOne", 12);
    document.field("fTwo", "test");

    final Object result = compositeIndex.getDocumentValueToIndex(document);
    Assert.assertEquals(result, new OCompositeKey(Arrays.asList(12, "test")));
  }

  @Test
  public void testDocumentToIndexMapValueSuccessful() {
    final ODocument document = new ODocument();

    final Map<String, String> stringMap = new HashMap<String, String>();
    stringMap.put("key1", "val1");
    stringMap.put("key2", "val2");

    document.field("fOne", 12);
    document.field("fTwo", stringMap);

    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyMapIndexDefinition("testCollectionClass", "fTwo", OType.STRING,
        OPropertyMapIndexDefinition.INDEX_BY.KEY));

    final Object result = compositeIndexDefinition.getDocumentValueToIndex(document);
    final Collection<OCompositeKey> collectionResult = (Collection<OCompositeKey>) result;

    Assert.assertEquals(collectionResult.size(), 2);
    Assert.assertTrue(collectionResult.contains(new OCompositeKey(12, "key1")));
    Assert.assertTrue(collectionResult.contains(new OCompositeKey(12, "key2")));
  }

  @Test
  public void testDocumentToIndexCollectionValueSuccessfulOne() {
    final ODocument document = new ODocument();

    document.field("fOne", 12);
    document.field("fTwo", Arrays.asList(1, 2));

    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));

    final Object result = compositeIndexDefinition.getDocumentValueToIndex(document);

    final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();

    expectedResult.add(new OCompositeKey(12, 1));
    expectedResult.add(new OCompositeKey(12, 2));

    Assert.assertEquals(result, expectedResult);
  }

  @Test
  public void testDocumentToIndexCollectionValueSuccessfulTwo() {
    final ODocument document = new ODocument();

    document.field("fOne", 12);
    document.field("fTwo", Arrays.asList(1, 2));

    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));

    final Object result = compositeIndexDefinition.getDocumentValueToIndex(document);

    final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();

    expectedResult.add(new OCompositeKey(1, 12));
    expectedResult.add(new OCompositeKey(2, 12));

    Assert.assertEquals(result, expectedResult);
  }

  @Test
  public void testDocumentToIndexCollectionValueSuccessfulThree() {
    final ODocument document = new ODocument();

    document.field("fOne", 12);
    document.field("fTwo", Arrays.asList(1, 2));
    document.field("fThree", "test");

    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.STRING));

    final Object result = compositeIndexDefinition.getDocumentValueToIndex(document);

    final ArrayList<OCompositeKey> expectedResult = new ArrayList<OCompositeKey>();

    expectedResult.add(new OCompositeKey(12, 1, "test"));
    expectedResult.add(new OCompositeKey(12, 2, "test"));

    Assert.assertEquals(result, expectedResult);
  }

  @Test(expectedExceptions = OException.class)
  public void testDocumentToIndexCollectionValueTwoCollections() {
    final ODocument document = new ODocument();

    document.field("fOne", Arrays.asList(12));
    document.field("fTwo", Arrays.asList(1, 2));

    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition("testCollectionClass");

    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.INTEGER));
    compositeIndexDefinition.getDocumentValueToIndex(document);
  }

  @Test(expectedExceptions = NumberFormatException.class)
  public void testDocumentToIndexWrongField() {
    final ODocument document = new ODocument();

    document.field("fOne", "1t2");
    document.field("fTwo", "test");

    compositeIndex.getDocumentValueToIndex(document);
  }

  @Test
  public void testGetParamCount() {
    final int result = compositeIndex.getParamCount();

    Assert.assertEquals(result, 2);
  }

  @Test
  public void testGetTypes() {
    final OType[] result = compositeIndex.getTypes();

    Assert.assertEquals(result.length, 2);
    Assert.assertEquals(result[0], OType.INTEGER);
    Assert.assertEquals(result[1], OType.STRING);
  }

  @Test
  public void testEmptyIndexReload() {
    final ODatabaseDocumentTx database = new ODatabaseDocumentTx("memory:compositetestone");
    database.create();

    final OCompositeIndexDefinition emptyCompositeIndex = new OCompositeIndexDefinition("testClass");

    emptyCompositeIndex.addIndex(new OPropertyIndexDefinition("testClass", "fOne", OType.INTEGER));
    emptyCompositeIndex.addIndex(new OPropertyIndexDefinition("testClass", "fTwo", OType.STRING));

    final ODocument docToStore = emptyCompositeIndex.toStream();
    database.save(docToStore);

    final ODocument docToLoad = database.load(docToStore.getIdentity());

    final OCompositeIndexDefinition result = new OCompositeIndexDefinition();
    result.fromStream(docToLoad);

    database.drop();
    Assert.assertEquals(result, emptyCompositeIndex);
  }

  @Test
  public void testIndexReload() {
    final ODocument docToStore = compositeIndex.toStream();

    final OCompositeIndexDefinition result = new OCompositeIndexDefinition();
    result.fromStream(docToStore);

    Assert.assertEquals(result, compositeIndex);
  }

  @Test
  public void testClassOnlyConstructor() {
    final ODatabaseDocumentTx database = new ODatabaseDocumentTx("memory:compositetesttwo");
    database.create();

    final OCompositeIndexDefinition emptyCompositeIndex = new OCompositeIndexDefinition("testClass", Arrays.asList(
        new OPropertyIndexDefinition("testClass", "fOne", OType.INTEGER), new OPropertyIndexDefinition("testClass", "fTwo",
            OType.STRING)));

    final OCompositeIndexDefinition emptyCompositeIndexTwo = new OCompositeIndexDefinition("testClass");

    emptyCompositeIndexTwo.addIndex(new OPropertyIndexDefinition("testClass", "fOne", OType.INTEGER));
    emptyCompositeIndexTwo.addIndex(new OPropertyIndexDefinition("testClass", "fTwo", OType.STRING));

    Assert.assertEquals(emptyCompositeIndex, emptyCompositeIndexTwo);

    final ODocument docToStore = emptyCompositeIndex.toStream();
    database.save(docToStore);

    final ODocument docToLoad = database.load(docToStore.getIdentity());

    final OCompositeIndexDefinition result = new OCompositeIndexDefinition();
    result.fromStream(docToLoad);

    database.drop();
    Assert.assertEquals(result, emptyCompositeIndexTwo);
  }

  public void testProcessChangeListEventsOne() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.STRING));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));

    final ODocument doc = new ODocument();
    doc.unsetDirty();
    Assert.assertFalse(doc.isDirty());

    final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
    final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();

    trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
      public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
        firedEvents.add(event);
      }
    });

    trackedList.add("l1");
    trackedList.add("l2");
    trackedList.add("l3");
    trackedList.remove("l2");

    Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
    Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();

    for (OMultiValueChangeEvent<Integer, String> multiValueChangeEvent : firedEvents)
      compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);

    Assert.assertEquals(keysToRemove.size(), 0);
    Assert.assertEquals(keysToAdd.size(), 2);

    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l1", 3)));
    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l3", 3)));
  }

  public void testProcessChangeListEventsTwo() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.STRING));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));

    final ODocument doc = new ODocument();
    doc.unsetDirty();
    Assert.assertFalse(doc.isDirty());

    final OTrackedList<String> trackedList = new OTrackedList<String>(doc);
    final List<OMultiValueChangeEvent<Integer, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Integer, String>>();

    trackedList.add("l1");
    trackedList.add("l2");
    trackedList.add("l3");
    trackedList.remove("l2");

    trackedList.addChangeListener(new OMultiValueChangeListener<Integer, String>() {
      public void onAfterRecordChanged(final OMultiValueChangeEvent<Integer, String> event) {
        firedEvents.add(event);
      }
    });

    trackedList.add("l4");
    trackedList.remove("l1");

    Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
    Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();

    for (OMultiValueChangeEvent<Integer, String> multiValueChangeEvent : firedEvents)
      compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);

    Assert.assertEquals(keysToRemove.size(), 1);
    Assert.assertEquals(keysToAdd.size(), 1);

    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l4", 3)));
    Assert.assertTrue(keysToRemove.containsKey(new OCompositeKey(2, "l1", 3)));
  }

  public void testProcessChangeSetEventsOne() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.STRING));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));

    final ODocument doc = new ODocument();
    doc.unsetDirty();
    Assert.assertFalse(doc.isDirty());

    final OTrackedSet<String> trackedSet = new OTrackedSet<String>(doc);
    final List<OMultiValueChangeEvent<String, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<String, String>>();

    trackedSet.addChangeListener(new OMultiValueChangeListener<String, String>() {
      public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
        firedEvents.add(event);
      }
    });

    trackedSet.add("l1");
    trackedSet.add("l2");
    trackedSet.add("l3");
    trackedSet.remove("l2");

    Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
    Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();

    for (OMultiValueChangeEvent<String, String> multiValueChangeEvent : firedEvents)
      compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);

    Assert.assertEquals(keysToRemove.size(), 0);
    Assert.assertEquals(keysToAdd.size(), 2);

    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l1", 3)));
    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l3", 3)));
  }

  public void testProcessChangeSetEventsTwo() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyListIndexDefinition("testCollectionClass", "fTwo", OType.STRING));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));

    final ODocument doc = new ODocument();
    doc.unsetDirty();
    Assert.assertFalse(doc.isDirty());

    final OTrackedSet<String> trackedMap = new OTrackedSet<String>(doc);
    final List<OMultiValueChangeEvent<String, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<String, String>>();

    trackedMap.add("l1");
    trackedMap.add("l2");
    trackedMap.add("l3");
    trackedMap.remove("l2");

    trackedMap.addChangeListener(new OMultiValueChangeListener<String, String>() {
      public void onAfterRecordChanged(final OMultiValueChangeEvent<String, String> event) {
        firedEvents.add(event);
      }
    });

    trackedMap.add("l4");
    trackedMap.remove("l1");

    Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
    Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();

    for (OMultiValueChangeEvent<String, String> multiValueChangeEvent : firedEvents)
      compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);

    Assert.assertEquals(keysToRemove.size(), 1);
    Assert.assertEquals(keysToAdd.size(), 1);

    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "l4", 3)));
    Assert.assertTrue(keysToRemove.containsKey(new OCompositeKey(2, "l1", 3)));
  }

  public void testProcessChangeKeyMapEventsOne() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyMapIndexDefinition("testCollectionClass", "fTwo", OType.STRING,
        OPropertyMapIndexDefinition.INDEX_BY.KEY));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));

    final ODocument doc = new ODocument();
    doc.unsetDirty();
    Assert.assertFalse(doc.isDirty());

    final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc);
    final List<OMultiValueChangeEvent<Object, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Object, String>>();

    trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() {
      public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) {
        firedEvents.add(event);
      }
    });

    trackedMap.put("k1", "v1");
    trackedMap.put("k2", "v2");
    trackedMap.put("k3", "v3");
    trackedMap.remove("k2");

    Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
    Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();

    for (OMultiValueChangeEvent<Object, String> multiValueChangeEvent : firedEvents)
      compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);

    Assert.assertEquals(keysToRemove.size(), 0);
    Assert.assertEquals(keysToAdd.size(), 2);

    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "k1", 3)));
    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "k3", 3)));
  }

  public void testProcessChangeKeyMapEventsTwo() {
    final OCompositeIndexDefinition compositeIndexDefinition = new OCompositeIndexDefinition();

    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fOne", OType.INTEGER));
    compositeIndexDefinition.addIndex(new OPropertyMapIndexDefinition("testCollectionClass", "fTwo", OType.STRING,
        OPropertyMapIndexDefinition.INDEX_BY.KEY));
    compositeIndexDefinition.addIndex(new OPropertyIndexDefinition("testCollectionClass", "fThree", OType.INTEGER));

    final ODocument doc = new ODocument();
    doc.unsetDirty();
    Assert.assertFalse(doc.isDirty());

    final OTrackedMap<String> trackedMap = new OTrackedMap<String>(doc);

    trackedMap.put("k1", "v1");
    trackedMap.put("k2", "v2");
    trackedMap.put("k3", "v3");
    trackedMap.remove("k2");

    final List<OMultiValueChangeEvent<Object, String>> firedEvents = new ArrayList<OMultiValueChangeEvent<Object, String>>();

    trackedMap.addChangeListener(new OMultiValueChangeListener<Object, String>() {
      public void onAfterRecordChanged(final OMultiValueChangeEvent<Object, String> event) {
        firedEvents.add(event);
      }
    });

    trackedMap.put("k4", "v4");
    trackedMap.remove("k1");

    Map<OCompositeKey, Integer> keysToAdd = new HashMap<OCompositeKey, Integer>();
    Map<OCompositeKey, Integer> keysToRemove = new HashMap<OCompositeKey, Integer>();

    for (OMultiValueChangeEvent<Object, String> multiValueChangeEvent : firedEvents)
      compositeIndexDefinition.processChangeEvent(multiValueChangeEvent, keysToAdd, keysToRemove, 2, 3);

    Assert.assertEquals(keysToRemove.size(), 1);
    Assert.assertEquals(keysToAdd.size(), 1);

    Assert.assertTrue(keysToAdd.containsKey(new OCompositeKey(2, "k4", 3)));
    Assert.assertTrue(keysToRemove.containsKey(new OCompositeKey(2, "k1", 3)));
  }

  @Test
  public void testClassName() {
    Assert.assertEquals("testClass", compositeIndex.getClassName());
  }
}


text:
package org.wildfly.swarm.internal;

import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;

/**
 * @author James R. Perkins
 */
@MessageLogger(projectCode = "WFSCONFIG", length = 4)
public interface SwarmConfigMessages extends BasicLogger {

    SwarmConfigMessages MESSAGES = Logger.getMessageLogger(SwarmConfigMessages.class, "org.wildfly.swarm.config");

    @LogMessage(level = Logger.Level.DEBUG)
    @Message(id = 1, value = "Marshalling Project Stage property %s")
    void marshalProjectStageProperty(String key);

    @LogMessage(level = Logger.Level.DEBUG)
    @Message(id = 2, value = "Marshalling XML from %s as: \n %s")
    void marshalXml(String location, String xml);

    @LogMessage(level = Logger.Level.DEBUG)
    @Message(id = 3, value = "Load standalone.xml via %s from %s")
    void loadingStandaloneXml(String loader, String location);

    @LogMessage(level = Logger.Level.DEBUG)
    @Message(id = 4, value = "Configuration:\n%s")
    void configuration(String configuration);

    @LogMessage(level = Logger.Level.ERROR)
    @Message(id = 5, value = "Error resolving configurable value for %s.")
    void errorResolvingConfigurableValue(String key, @Cause Throwable cause);

    @LogMessage(level = Logger.Level.ERROR)
    @Message(id = 6, value = "Error loading module.")
    void errorLoadingModule(@Cause Throwable cause);

    @LogMessage(level = Logger.Level.ERROR)
    @Message(id = 7, value = "Error create extension %s from module %s.")
    void errorCreatingExtension(String extensionClassName, String extensionModuleName, @Cause Throwable cause);

}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<dom-module id="rms-teams">
  <template>

      <paper-button>U10 Fall 2015 Indoor</paper-button>

      <paper-button  >U12 Fall 2015 Indoor</paper-button>

  <paper-carousel id="pc" src="../../carousel/carousel.json" ></paper-carousel>

  </template>

</dom-module>


text:
package com.facebook.buck.sandbox;

import com.facebook.buck.shell.programrunner.ProgramRunner;

/** A strategy that guarantees that sandboxing is not used. */
public class NoSandboxExecutionStrategy implements SandboxExecutionStrategy {
  @Override
  public boolean isSandboxEnabled() {
    return false;
  }

  @Override
  public ProgramRunner createSandboxProgramRunner(SandboxProperties sandboxProperties) {
    throw new IllegalStateException("Creating sandbox runner when sandbox is not present");
  }
}


text:
package com.galenframework.rainbow4j;

import java.awt.Color;

public class ColorDistribution {

    private Color color;
    private double percentage;

    public ColorDistribution(Color color, double percentage) {
        this.color = color;
        this.percentage = percentage;
    }
    public Color getColor() {
        return color;
    }
    public void setColor(Color color) {
        this.color = color;
    }
    public double getPercentage() {
        return percentage;
    }
    public void setPercentage(double percentage) {
        this.percentage = percentage;
    }

}


text:
module ServerSide
  module HTTP
  end
end

http_dir = File.dirname(__FILE__)/'http'

require http_dir/'const'
require http_dir/'error'
require http_dir/'parsing'
require http_dir/'request'
require http_dir/'caching'
require http_dir/'static'
require http_dir/'response'
require http_dir/'server'


text:
package org.apache.tinkerpop.gremlin.orientdb.traversal.strategy.optimization;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.stream.Collectors;
import org.apache.tinkerpop.gremlin.orientdb.traversal.step.map.OrientClassCountStep;
import org.apache.tinkerpop.gremlin.orientdb.traversal.step.sideeffect.OrientGraphStep;
import org.apache.tinkerpop.gremlin.process.traversal.*;
import org.apache.tinkerpop.gremlin.process.traversal.step.map.CountGlobalStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.EmptyStep;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.HasContainer;
import org.apache.tinkerpop.gremlin.process.traversal.strategy.AbstractTraversalStrategy;
import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalHelper;

/**
 * This strategy will try to optimize the Count Step when it's possible.
 *
 * @author Enrico Risa
 * @example
 *

 * g.V().count()                               // is replaced by OrientClassCountStep
 * g.E().count()                               // is replaced by OrientClassCountStep
 * g.V().hasLabel('Foo').count()               // is replaced by OrientClassCountStep
 * g.E().hasLabel('Foo').count()               // is replaced by OrientClassCountStep
 *

 *

 */
public class OrientGraphCountStrategy
    extends AbstractTraversalStrategy<TraversalStrategy.ProviderOptimizationStrategy>
    implements TraversalStrategy.ProviderOptimizationStrategy {

  private static final OrientGraphCountStrategy INSTANCE = new OrientGraphCountStrategy();

  private OrientGraphCountStrategy() {}

  @Override
  public void apply(Traversal.Admin<?, ?> traversal) {

    if (!(traversal.getParent() instanceof EmptyStep) || TraversalHelper.onGraphComputer(traversal))
      return;

    List<Step> steps = traversal.getSteps();
    if (steps.size() < 2) return;

    Step<?, ?> startStep = traversal.getStartStep();
    Step<?, ?> endStep = traversal.getEndStep();
    if (steps.size() == 2
        && startStep instanceof OrientGraphStep
        && endStep instanceof CountGlobalStep) {

      OrientGraphStep step = (OrientGraphStep) startStep;

      if (step.getHasContainers().size() == 1) {
        List<HasContainer> hasContainers = step.getHasContainers();
        List<String> classes =
            hasContainers.stream()
                .filter(this::isLabelFilter)
                .map(this::extractLabels)
                .flatMap((s) -> s.stream())
                .collect(Collectors.toList());
        if (classes.size() > 0) {
          TraversalHelper.removeAllSteps(traversal);
          traversal.addStep(new OrientClassCountStep(traversal, classes, step.isVertexStep()));
        }
      } else if (step.getHasContainers().size() == 0) {
        TraversalHelper.removeAllSteps(traversal);
        String baseClass = step.isVertexStep() ? "V" : "E";
        traversal.addStep(
            new OrientClassCountStep(
                traversal, Collections.singletonList(baseClass), step.isVertexStep()));
      }
    }
  }

  protected boolean isLabelFilter(HasContainer f) {
    boolean labelFilter = f.getKey().equals("~label");

    BiPredicate<?, ?> predicate = f.getBiPredicate();

    if (predicate instanceof Compare) {
      return labelFilter && Compare.eq.equals(predicate);
    }
    if (predicate instanceof Contains) {
      return labelFilter && Contains.within.equals(predicate);
    }

    return false;
  }

  protected List<String> extractLabels(HasContainer f) {
    Object value = f.getValue();
    List<String> classLabels = new ArrayList<>();
    if (value instanceof List) {
      ((List) value).forEach(label -> classLabels.add((String) label));
    } else {
      classLabels.add((String) value);
    }
    return classLabels;
  }

  @Override
  public Set<Class<? extends ProviderOptimizationStrategy>> applyPrior() {
    return Collections.singleton(OrientGraphStepStrategy.class);
  }

  public static OrientGraphCountStrategy instance() {
    return INSTANCE;
  }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Diplophragmia petsamoeensis Vain.

### Remarks
null


text:
//---------------------------------------------------------------------
// <copyright file="DimensionValuePair.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Microsoft.SqlServer.Test.TestShell.Core.InputSpaceModeling
{
	/// <summary>
	/// A dimension with its value.
	/// </summary>
	public abstract class DimensionValuePair
	{
		private readonly Dimension _dimension;
		private readonly object _value;

		/// <summary>
		/// Constructs a dimension-value pair.
		/// </summary>
		/// <param name="dimension">The dimension.</param>
		/// <param name="value">The value.</param>
		protected internal DimensionValuePair(Dimension dimension, object value)
		{
			if (dimension == null)
			{
				throw new ArgumentNullException("dimension");
			}
			_dimension = dimension;
			_value = value;
		}

		/// <summary>
		/// Gets the dimension as the untyped object.
		/// </summary>
		internal Dimension BaseDimension
		{
			get { return _dimension; }
		}

		/// <summary>
		/// Gets the value as the untyped object.
		/// </summary>
		internal object BaseValue
		{
			get { return _value; }
		}
	}

	/// <summary>
	/// A dimension with its value.
	/// </summary>
	/// <typeparam name="T">THe type of the value.</typeparam>
	public class DimensionValuePair<T> : DimensionValuePair
	{
		/// <summary>
		/// Constructs a dimension-value pair.
		/// </summary>
		/// <param name="dimension">The dimension.</param>
		/// <param name="value">The value.</param>
		internal DimensionValuePair(Dimension<T> dimension, T value)
			: base(dimension, value)
		{
		}

		/// <summary>
		/// Gets the dimension.
		/// </summary>
		public Dimension<T> Dimension
		{
			get { return (Dimension<T>)BaseDimension; }
		}

		/// <summary>
		/// Gets the value.
		/// </summary>
		public T Value
		{
			get { return (T)BaseValue; }
		}
	}
}


text:
package org.apache.hadoop.hive.ql.udf;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.ql.exec.UDF;

public class UDFFloor implements UDF {

  private static Log LOG = LogFactory.getLog(UDFFloor.class.getName());

  public UDFFloor() {
  }

  public Long evaluate(Double i)  {
    if (i == null) {
      return null;
    } else {
      return Long.valueOf((long)Math.floor(i));
    }
  }

}


text:
TODO: Write a gem description

## Installation

Add this line to your application's Gemfile:

    gem 'graph'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install graph

## Usage

TODO: Write usage instructions here

## Contributing

1. Fork it ( http://github.com/<my-github-username>/graph/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
$('#save-barcode-button').on('click', function(e)
{
	e.preventDefault();

	if ($(".combobox-menu-visible").length)
	{
		return;
	}

	var jsonData = $('#barcode-form').serializeJSON();
	jsonData.amount = jsonData.display_amount;
	delete jsonData.display_amount;
	jsonData.qu_id = $("#qu_id").val();

	Grocy.FrontendHelpers.BeginUiBusy("barcode-form");

	if (Grocy.EditMode === 'create')
	{
		Grocy.Api.Post('objects/product_barcodes', jsonData,
			function(result)
			{
				Grocy.EditObjectId = result.created_object_id;
				Grocy.Components.UserfieldsForm.Save()

				window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
				window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
			},
			function(xhr)
			{
				Grocy.FrontendHelpers.EndUiBusy("barcode-form");
				Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
			}
		);
	}
	else
	{
		Grocy.Components.UserfieldsForm.Save();
		Grocy.Api.Put('objects/product_barcodes/' + Grocy.EditObjectId, jsonData,
			function(result)
			{
				window.parent.postMessage(WindowMessageBag("ProductBarcodesChanged"), U("/product/" + GetUriParam("product")));
				window.parent.postMessage(WindowMessageBag("CloseAllModals"), U("/product/" + GetUriParam("product")));
			},
			function(xhr)
			{
				Grocy.FrontendHelpers.EndUiBusy("barcode-form");
				Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response);
			}
		);
	}
});

$('#barcode').on('keyup', function(e)
{
	Grocy.FrontendHelpers.ValidateForm('barcode-form');
});

$('#qu_id').on('change', function(e)
{
	Grocy.FrontendHelpers.ValidateForm('barcode-form');
});

$('#display_amount').on('keyup', function(e)
{
	Grocy.FrontendHelpers.ValidateForm('barcode-form');
});

$('#barcode-form input').keydown(function(event)
{
	if (event.keyCode === 13) //Enter
	{
		event.preventDefault();

		if (document.getElementById('barcode-form').checkValidity() === false) //There is at least one validation error
		{
			return false;
		}
		else
		{
			$('#save-barcode-button').click();
		}
	}
});

Grocy.Components.ProductAmountPicker.Reload(Grocy.EditObjectProduct.id, Grocy.EditObjectProduct.qu_id_purchase);
if (Grocy.EditMode == "edit")
{
	$("#display_amount").val(Grocy.EditObject.amount);
	$(".input-group-productamountpicker").trigger("change");
	Grocy.Components.ProductAmountPicker.SetQuantityUnit(Grocy.EditObject.qu_id);
}

Grocy.FrontendHelpers.ValidateForm('barcode-form');
setTimeout(function()
{
	$('#barcode').focus();
}, 250);
RefreshLocaleNumberInput();
Grocy.Components.UserfieldsForm.Load()

$(document).on("Grocy.BarcodeScanned", function(e, barcode, target)
{
	if (target !== "#barcode")
	{
		return;
	}

	$("#barcode").val(barcode);
});


text:
const keystone = require('keystone');
const Types = keystone.Field.Types;

const Technique = new keystone.List('Technique', {
  autokey: { from: 'text.english', path: 'key', unique: true },
  plural: 'Techniques',
  singular: 'Technique',
});

Technique.add({
  name: { type: String },
  text: {
    english: { type: String, index: true },
    'chinese_traditional': { type: String },
    'chinese_simplified': { type: String },
  },
  type: { type: Types.Select, options: 'Dyeing, Washing, Printing', default: 'Dyeing' },
});

Technique.track = true;
Technique.defaultColumns = 'name, text.english';
Technique.register();

Technique.get = (something, cb) => {
  Technique.model.find({}).exec((err, technique) => {
    if (err) {
      console.log('server getting failed', err);
    } else {
      console.log('server getting succssful', technique);
      cb(null, technique);
    }
  })
}

module.exports = Technique;