text:
package com.noctarius.snowcast.impl.operations;

import com.hazelcast.nio.Address;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.spi.BackupOperation;
import com.noctarius.snowcast.SnowcastEpoch;
import com.noctarius.snowcast.impl.NodeSequencerService;
import com.noctarius.snowcast.impl.SequencerDataSerializerHook;
import com.noctarius.snowcast.impl.SequencerDefinition;
import com.noctarius.snowcast.impl.SequencerPartition;

import java.io.IOException;

public class BackupAttachLogicalNodeOperation
        extends AbstractSequencerOperation
        implements BackupOperation {

    private SequencerDefinition definition;
    private int logicalNodeId;
    private Address address;

    public BackupAttachLogicalNodeOperation() {
    }

    public BackupAttachLogicalNodeOperation(SequencerDefinition definition, int logicalNodeId, Address address) {
        super(definition.getSequencerName());
        this.definition = definition;
        this.logicalNodeId = logicalNodeId;
        this.address = address;
    }

    @Override
    public int getId() {
        return SequencerDataSerializerHook.TYPE_BACKUP_ATTACH_LOGICAL_NODE;
    }

    @Override
    public void run()
            throws Exception {

        NodeSequencerService sequencerService = getService();
        SequencerPartition partition = sequencerService.getSequencerPartition(getPartitionId());
        partition.assignLogicalNode(definition, logicalNodeId, address);
    }

    @Override
    protected void writeInternal(ObjectDataOutput out)
            throws IOException {

        super.writeInternal(out);
        out.writeInt(logicalNodeId);
        address.writeData(out);
        out.writeLong(definition.getEpoch().getEpochOffset());
        out.writeInt(definition.getMaxLogicalNodeCount());
        out.writeShort(definition.getBackupCount());
    }

    @Override
    protected void readInternal(ObjectDataInput in)
            throws IOException {

        super.readInternal(in);
        logicalNodeId = in.readInt();
        address = new Address();
        address.readData(in);

        long epochOffset = in.readLong();
        int maxLogicalNodeCount = in.readInt();
        short backupCount = in.readShort();

        SnowcastEpoch epoch = SnowcastEpoch.byTimestamp(epochOffset);
        definition = new SequencerDefinition(getSequencerName(), epoch, maxLogicalNodeCount, backupCount);
    }
}


text:
import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  Input,
  OnChanges,
  OnDestroy,
  SimpleChanges,
  ViewChild
} from '@angular/core';
import { SubscriptionLike } from 'rxjs';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';
import { createSystemJsSandbox } from '@codelab/code-demos/src/lib/shared/sandbox';
import { compileTemplates } from '../runner/prepare-templates';
import { ScriptLoaderService } from '@codelab/code-demos/src/lib/shared/script-loader.service';
import { addMetaInformation } from '../shared/helpers';

interface CodeFiles {
  [key: string]: string;
}

const presets = {
  angular(sandbox, scriptLoaderService) {
    sandbox.evalJs(scriptLoaderService.getScript('shim'));
    sandbox.evalJs(scriptLoaderService.getScript('zone'));
    sandbox.evalJs(scriptLoaderService.getScript('system-config'));
    sandbox.evalJs(scriptLoaderService.getScript('ng-bundle'));
  },
  react(sandbox, scriptLoaderService) {
    // TODO(kirjs): Make it work
    // sandbox.addCss(require('../inner.css'));
    sandbox.setHtml('

');
    sandbox.evalJs(scriptLoaderService.getScript('react'));
    sandbox.evalJs(scriptLoaderService.getScript('react-dom'));
    // sandbox.evalJs(transform(code, {presets: ['react']}).code);
  }
};

@Component({
  selector: 'code-demo-runner',
  templateUrl: './code-demo-runner.component.html',
  styleUrls: ['./code-demo-runner.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CodeDemoRunnerComponent
  implements OnDestroy, AfterViewInit, OnChanges {
  @Input() code: CodeFiles = {};
  @Input() jsFiles: CodeFiles = {};
  @Input() bootstrap: string;
  @Input() url = 'about:blank';
  @Input() ui = 'browser';
  changedFilesSubject = new BehaviorSubject<Record<string, string>>({});
  @ViewChild('runner', { static: false }) runnerElement: ElementRef;
  presets = ['angular'];
  private subscription: SubscriptionLike;

  constructor(
    public scriptLoaderService: ScriptLoaderService,
    private cdr: ChangeDetectorRef
  ) {}

  get displayUrl() {
    if (this.url === '/assets/runner') {
      return 'http://localhost:4200';
    }
    return this.url.replace('assets/runner', '');
  }

  @Input('presets')
  public set setPresets(presets: any) {
    if (typeof presets === 'string') {
      presets = presets.split(',');
    }
    this.presets = presets.filter(a => a);
  }

  ngOnChanges(changes: SimpleChanges) {
    if (changes.code) {
      this.changedFilesSubject.next(changes.code.currentValue);
    }
  }

  async ngAfterViewInit() {
    const sandbox = await createSystemJsSandbox(
      this.runnerElement.nativeElement,
      {
        id: 'testing',
        url: this.url
      }
    );

    sandbox.setHtml(
      this.code['index.html'] ||
        '<app-root></app-root><my-app></my-app>

'
    );

    this.presets.forEach(preset =>
      presets[preset](sandbox, this.scriptLoaderService)
    );

    Object.entries(this.code)
      .filter(([moduleName]) => moduleName.match(/\.css/))
      .forEach(([moduleName, code]) => {
        sandbox.addCss(code);
      });

    compileTemplates(this.code, sandbox);

    this.subscription = this.changedFilesSubject.subscribe(files => {
      addMetaInformation(sandbox, files);

      if (files['index.html']) {
        sandbox.setHtml(files['index.html']);
      }

      const jsFiles = Object.entries(files).filter(([path]) =>
        path.match(/\.js$/)
      );
      const hasErrors = jsFiles.some(([path, code]) => {
        sandbox.evalJs(
          `System.registry.delete(System.normalizeSync('./${path.replace(
            '.js',
            ''
          )}'));`
        );

        try {
          sandbox.evalJs(code);
        } catch (e) {
          const [errorLabel] = e.toString().split('\r\n');
          console.groupCollapsed(errorLabel);
          console.log(e);
          console.groupEnd();
          return true;
        }
        return false;
      });

      Object.entries(files)
        .filter(([path]) => path.match(/\.css$/))
        .forEach(([path, code]) => {
          // TODO(kirjs): Consider deleting old CSS.
          sandbox.addCss(code);
        });

      if (jsFiles.length) {
        if (!this.bootstrap) {
          console.error('Bootstrap missing');
        }

        if (!hasErrors) {
          sandbox.evalJs(`System.import('${this.bootstrap}')`);
        }
      }
    });

    this.trackIframeUrl(sandbox.iframe);
  }

  trackIframeUrl(iframe) {
    const interval = window.setInterval(() => {
      if (iframe.contentWindow) {
        const url = iframe.contentWindow.location.href.replace(
          'assets/runner/',
          ''
        ); // .replace(this.urlBase, '')
        if (this.url !== url) {
          this.url = url;
          this.cdr.markForCheck();
        }
      } else {
        window.clearInterval(interval);
      }
    }, 200);
  }

  ngOnDestroy() {
    if (this.subscription) {
      this.subscription.unsubscribe();
      this.subscription = null;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
(function() {

function DynamicRenderingEngine(viewResolver) {
	this.viewResolver = viewResolver || null;
}

DynamicRenderingEngine.prototype.viewResolver = null;

DynamicRenderingEngine.prototype.render = function render(name, data, elementOrId) {
	var promise = new Bloodhound.RenderPromise(this),
	    element = null,
	    doc = this.viewResolver.getDocument();

	if (elementOrId) {
		if (typeof elementOrId === "string") {
			element = doc.getElementById(elementOrId);

			if (!element) {
				throw new Error("Failed to find element '" + elementOrId + "' in document: " + (doc.documentURI || doc.location));
			}
		}
		else {
			element = elementOrId;
		}
	}

	this.viewResolver.find(name, function(template) {
		var result = template.render(data);

		if (element) {
			element.innerHTML = result;
		}

		promise.fulfill("done", result, template, element);

		element = template = data = null;
	});

	return promise;
};

Bloodhound.RenderingEngines.DynamicRenderingEngine = DynamicRenderingEngine;

})();


text:
from functools import partial
from sqlalchemy import event

from backend.utils import slugify as _slugify, was_decorated_without_parenthesis

# EVENTS DOCS
# http://docs.sqlalchemy.org/en/rel_1_1/core/event.html
# ORM EVENTS DOCS
# http://docs.sqlalchemy.org/en/rel_1_1/orm/events.html

class _SQLAlchemyEvent(object):
    """Private helper class for the @attach_events and @on decorators"""
    ATTR = '_sqlalchemy_event'

    def __init__(self, field_name, event_name, listen_kwargs=None):
        self.field_name = field_name
        self.event_name = event_name
        self.listen_kwargs = listen_kwargs or {}

def attach_events(*args):
    """Class decorator for SQLAlchemy models to attach listeners on class
    methods decorated with :func:`.on`

    Usage::

        @attach_events
        class User(Model):
            email = Column(String(50))

            @on('email', 'set')
            def lowercase_email(self, new_value, old_value, initiating_event):
                self.email = new_value.lower()
    """
    def wrapper(cls):
        for name, fn in cls.__dict__.items():
            if not name.startswith('__') and hasattr(fn, _SQLAlchemyEvent.ATTR):
                e = getattr(fn, _SQLAlchemyEvent.ATTR)
                if e.field_name:
                    event.listen(getattr(cls, e.field_name), e.event_name, fn,
                                 **e.listen_kwargs)
                else:
                    event.listen(cls, e.event_name, fn, **e.listen_kwargs)
        return cls
    if was_decorated_without_parenthesis(args):
        return wrapper(args[0])
    return wrapper

def on(*args, **listen_kwargs):
    """Class method decorator for SQLAlchemy models. Must be used in
    conjunction with the :func:`.attach_events` class decorator

    Usage::

        @attach_events
        class Post(Model):
            uuid = Column(String(36))
            post_tags = relationship('PostTag', back_populates='post')  # m2m

            # instance event (only one positional argument, the event name)
            # kwargs are passed on to the sqlalchemy.event.listen function
            @on('init', once=True)
            def generate_uuid(self, args, kwargs):
                self.uuid = str(uuid.uuid4())

            # attribute event (two positional args, field name and event name)
            @on('post_tags', 'append')
            def set_tag_order(self, post_tag, initiating_event):
                if not post_tag.order:
                    post_tag.order = len(self.post_tags) + 1
    """
    if len(args) == 1:
        field_name, event_name = (None, args[0])
    elif len(args) == 2:
        field_name, event_name = args
    else:
        raise NotImplementedError('@on accepts only one or two positional arguments')

    def wrapper(fn):
        setattr(fn, _SQLAlchemyEvent.ATTR,
                _SQLAlchemyEvent(field_name, event_name, listen_kwargs))
        return fn
    return wrapper

def slugify(field_name, slug_field_name=None, mutable=False):
    """Class decorator to specify a field to slugify. Slugs are immutable by
    default unless mutable=True is passed.

    Usage::

        @slugify('title')
        def Post(Model):
            title = Column(String(100))
            slug = Column(String(100))

        # pass a second argument to specify the slug attribute field:
        @slugify('title', 'title_slug')
        def Post(Model)
            title = Column(String(100))
            title_slug = Column(String(100))

        # optionally set mutable to True for a slug that changes every time
        # the slugified field changes:
        @slugify('title', mutable=True)
        def Post(Model):
            title = Column(String(100))
            slug = Column(String(100))
    """
    slug_field_name = slug_field_name or 'slug'

    def _set_slug(target, value, old_value, _, mutable=False):
        existing_slug = getattr(target, slug_field_name)
        if existing_slug and not mutable:
            return
        if value and (not existing_slug or value != old_value):
            setattr(target, slug_field_name, _slugify(value))

    def wrapper(cls):
        event.listen(getattr(cls, field_name), 'set',
                     partial(_set_slug, mutable=mutable))
        return cls
    return wrapper


text:
using Newtonsoft.Json;

namespace OpenApiLib.Json
{
	public class SymbolJson : AbstractJson
	{
		public string SymbolName { get; set; }
		public int Digits { get; set; }
		public int PipPosition { get; set; }
		public string MeasurementUnits { get; set; }
		public string BaseAsset { get; set; }
		public string QuoteAsset { get; set; }
		public bool TradeEnabled { get; set; }
		public double TickSize { get; set; }
		public string Description { get; set; }
		public int MaxLeverage{ get; set; }
		public long MinOrderVolume{ get; set; }
		public long MinOrderStep{ get; set; }
		public long MaxOrderVolume{ get; set; }
		public double SwapLong{ get; set; }
		public double SwapShort{ get; set; }
		public string ThreeDaysSwaps{ get; set; }
		public string AssetClass{ get; set; }
		[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
		public double LastAsk{ get; set; }
		[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
		public double LastBid{ get; set; }
	}
}


text:
package org.monte.media.jmf.codec.video;

import org.monte.media.quicktime.AnimationCodec;
import java.awt.image.BufferedImage;
import javax.media.Buffer;
import javax.media.Format;
import javax.media.ResourceUnavailableException;
import javax.media.format.RGBFormat;
import javax.media.format.VideoFormat;

public class QTAnimationDecoder extends AbstractVideoDecoder {

    @Override
    protected Format[] getMatchingOutputFormats(Format input) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public int process(Buffer input, Buffer output) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}


text:
import { Component, OnInit } from '@angular/core';
import { LocationStrategy, PlatformLocation, Location } from '@angular/common';
import { AuthService } from './service/auth.service';
import { Router } from '@angular/router';
import { UserService } from './service/user.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

     constructor(public location: Location,
                 private auth: AuthService,
                 router: Router,
                 private userService: UserService
                 ) {
                   auth.user$.subscribe(user => {
                     if (user) {
                        userService.save(user);

                       const returnUrl = localStorage.getItem('returnUrl');
                       router.navigateByUrl(returnUrl);
                     }
                   });

                 }

    // tslint:disable-next-line:one-line
    ngOnInit(){
    }

    // tslint:disable-next-line:one-line
    isMap(path){
      let titlee = this.location.prepareExternalUrl(this.location.path());
      titlee = titlee.slice( 1 );
      // tslint:disable-next-line:one-line
      if (path === titlee){
        return false;
      }
      // tslint:disable-next-line:one-line
      else {
        return true;
      }
    }
}


text:
package uk.gov.gchq.gaffer.rest.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import uk.gov.gchq.gaffer.commonutil.CloseableUtil;
import uk.gov.gchq.gaffer.commonutil.pair.Pair;
import uk.gov.gchq.gaffer.core.exception.GafferRuntimeException;
import uk.gov.gchq.gaffer.core.exception.Status;
import uk.gov.gchq.gaffer.operation.Operation;
import uk.gov.gchq.gaffer.rest.factory.ExamplesFactory;
import uk.gov.gchq.gaffer.rest.factory.GraphFactory;
import uk.gov.gchq.gaffer.rest.factory.UserFactory;
import uk.gov.gchq.gaffer.rest.model.OperationDetail;
import uk.gov.gchq.gaffer.rest.service.v2.AbstractOperationService;

import java.io.IOException;
import java.util.Set;

import static uk.gov.gchq.gaffer.jsonserialisation.JSONSerialiser.createDefaultMapper;
import static uk.gov.gchq.gaffer.rest.ServiceConstants.GAFFER_MEDIA_TYPE;
import static uk.gov.gchq.gaffer.rest.ServiceConstants.GAFFER_MEDIA_TYPE_HEADER;
import static uk.gov.gchq.gaffer.rest.ServiceConstants.JOB_ID_HEADER;

@RestController
public class OperationController extends AbstractOperationService implements IOperationController {

    private final GraphFactory graphFactory;
    private final UserFactory userFactory;
    private final ExamplesFactory examplesFactory;

    public final ObjectMapper mapper = createDefaultMapper();

    @Autowired
    public OperationController(final GraphFactory graphFactory, final UserFactory userFactory, final ExamplesFactory examplesFactory) {
        this.graphFactory = graphFactory;
        this.userFactory = userFactory;
        this.examplesFactory = examplesFactory;
    }

    @Override
    public Set<Class<? extends Operation>> getOperations() {
        return getSupportedOperations();
    }

    @Override
    public Set<OperationDetail> getAllOperationDetails() {
        return getSupportedOperationDetails();
    }

    @Override
    public OperationDetail getOperationDetails(@PathVariable("className") @ApiParam(name = "className", value = "The Operation class") final String className) {
        try {
            final Class<? extends Operation> operationClass = getOperationClass(className);

            if (graphFactory.getGraph().getSupportedOperations().contains(operationClass)) {
                return new OperationDetail(operationClass, getNextOperations(operationClass), generateExampleJson(operationClass));
            } else {
                throw new GafferRuntimeException("Class: " + className + " is not supported by the current store.");
            }
        } catch (final ClassNotFoundException e) {
            throw new GafferRuntimeException("Class: " + className + " was not found on the classpath.", e, Status.NOT_FOUND);
        } catch (final ClassCastException e) {
            throw new GafferRuntimeException(className + " does not extend Operation", e, Status.BAD_REQUEST);
        } catch (final  IllegalAccessException | InstantiationException e) {
            throw new GafferRuntimeException("Unable to instantiate " + className, e);
        }
    }

    @Override
    public Set<Class<? extends Operation>> getNextOperations(@PathVariable("className") @ApiParam(name = "className", value = "The Operation class") final String className) {
        Class<? extends Operation> opClass;
        try {
            opClass = getOperationClass(className);
        } catch (final ClassNotFoundException e) {
            throw new GafferRuntimeException("Operation class was not found: " + className, e, Status.NOT_FOUND);
        } catch (final ClassCastException e) {
            throw new GafferRuntimeException(className + " does not extend Operation", e, Status.BAD_REQUEST);
        }

        return getNextOperations(opClass);
    }

    @Override
    public Operation getOperationExample(@PathVariable("className") @ApiParam(name = "className", value = "The Operation class") final String className) {
        Class<? extends Operation> operationClass;
        try {
            operationClass = getOperationClass(className);
        } catch (final ClassNotFoundException e) {
            throw new GafferRuntimeException("Class: " + className + " was not found on the classpath.", e, Status.NOT_FOUND);
        } catch (final ClassCastException e) {
            throw new GafferRuntimeException(className + " does not extend Operation", e, Status.BAD_REQUEST);
        }
        try {
            return generateExampleJson(operationClass);
        } catch (final InstantiationException | IllegalAccessException e) {
            throw new GafferRuntimeException("Unable to create example for class " + className, e, Status.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    public ResponseEntity<Object> execute(@RequestBody final Operation operation) {
        Pair<Object, String> resultAndJobId = _execute(operation, userFactory.createContext());
        return ResponseEntity.ok()
                .header(GAFFER_MEDIA_TYPE_HEADER, GAFFER_MEDIA_TYPE)
                .header(JOB_ID_HEADER, resultAndJobId.getSecond())
                .body(resultAndJobId.getFirst());
    }

    @Override
    public ResponseEntity<StreamingResponseBody> executeChunked(@RequestBody final Operation operation) {
        StreamingResponseBody responseBody = response -> {
            try {
                Pair<Object, String> resultAndJobId = _execute(operation, userFactory.createContext());
                Object result = resultAndJobId.getFirst();
                if (result instanceof Iterable) {
                    final Iterable itr = (Iterable) result;
                    try {
                        for (final Object item : itr) {
                            String itemString = mapper.writeValueAsString(item) + "\r\n";
                            response.write(itemString.getBytes());
                            response.flush();
                        }
                    } catch (final IOException ioe) {
                        throw new GafferRuntimeException("Unable to serialise chunk: ", ioe, Status.INTERNAL_SERVER_ERROR);
                    } finally {
                        CloseableUtil.close(itr);
                    }
                } else {
                    try {
                        response.write(mapper.writeValueAsString(result).getBytes());
                        response.flush();
                    } catch (final IOException ioe) {
                        throw new GafferRuntimeException("Unable to serialise chunk: ", ioe, Status.INTERNAL_SERVER_ERROR);
                    }
                }
            } catch (final Exception e) {
                throw new GafferRuntimeException("Unable to create chunk: ", e, Status.INTERNAL_SERVER_ERROR);
            } finally {
                CloseableUtil.close(operation);
            }
        };

        return ResponseEntity.ok()
                .header(GAFFER_MEDIA_TYPE_HEADER, GAFFER_MEDIA_TYPE)
                .contentType(MediaType.APPLICATION_JSON)
                .body(responseBody);
    }

    @Override
    protected UserFactory getUserFactory() {
        return userFactory;
    }

    @Override
    protected ExamplesFactory getExamplesFactory() {
        return examplesFactory;
    }

    @Override
    protected GraphFactory getGraphFactory() {
        return graphFactory;
    }

}


text:
=head1 NAME

pacinfo - display package information

=head1 SYNOPSIS

 pacinfo [options] (<pkgspec>|<pkgname>)...
 pacinfo (--help|--version)

=head1 DESCRIPTION

If a I<pkgname> is given, information for all packages matching that name in
all databases will be displayed.

If F<stdin> is not connected to a terminal, packages will be read from
F<stdin>.

=head1 OPTIONS

=over

=item B<--config>=F<path>

Set an alternate configuration file path.

=item B<--dbext>=I<extension>

Set an alternate sync database extension.

=item B<--dbpath>=F<path>

Set an alternate database path.

=item B<--root>=F<path>

Set an alternate installation root.

=item B<--sysroot>=F<path>

Set an alternate system root.  See L<pacutils-sysroot(7)>.

=item B<--null>[=I<sep>]

Set an alternate separator for values parsed from F<stdin>.  By default
a newline C<\n> is used as the separator.  If B<--null> is used without
specifying I<sep> C<NUL> will be used.

=item B<--no-timeout>

Disable low-speed timeouts for downloads.

=item B<--short>

Display brief information.  Suitable for printing a potentially large number of
packages:

 pacsift --name libreoffice | pacinfo --short

=item B<--verbose>

Display additional package information: C<required by>, C<optional for>, and
C<base64 signature>.

=item B<--raw>

Display raw numeric size and date values.

=item B<--removable-size>

Include the size of any removable dependencies in installed size.

=item B<--help>

Display usage information and exit.

=item B<--version>

Display version information and exit.

=back

=head1 CAVEATS

B<pacinfo> determines whether or not to read packages from F<stdin> based on
a naive check using L<isatty(3)>.  If B<pacinfo> is called in an environment,
such as a shell function or script being used in a pipe, where F<stdin> is not
connected to a terminal but does not contain packages to print, B<pacinfo>
should be called with F<stdin> closed.  For POSIX-compatible shells, this can
be done with C<< <&- >>.


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using Newtonsoft.Json;

namespace osu.Game.Rulesets.Mods
{
    public interface IMod
    {
        /// <summary>
        /// The shortened name of this mod.
        /// </summary>
        [JsonProperty("acronym")]
        string Acronym { get; }
    }
}


text:
package io.vertigo.dashboard.impl.services.data;

import java.time.Instant;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.inject.Inject;
import javax.inject.Named;

import io.vertigo.app.Home;
import io.vertigo.commons.analytics.health.HealthCheck;
import io.vertigo.commons.analytics.health.HealthMeasure;
import io.vertigo.commons.analytics.health.HealthMeasureBuilder;
import io.vertigo.commons.analytics.metric.Metric;
import io.vertigo.dashboard.services.data.ClusteredMeasure;
import io.vertigo.dashboard.services.data.DataFilter;
import io.vertigo.dashboard.services.data.DataProvider;
import io.vertigo.dashboard.services.data.TimeFilter;
import io.vertigo.dashboard.services.data.TimedDatas;
import io.vertigo.lang.Assertion;

public final class DataProviderImpl implements DataProvider {

	private final DataProviderPlugin dataProviderPlugin;
	private final String appName;

	@Inject
	public DataProviderImpl(
			@Named("appName") final Optional<String> appNameOpt,
			final DataProviderPlugin dataProviderPlugin) {
		Assertion.checkNotNull(appNameOpt);
		Assertion.checkNotNull(dataProviderPlugin);
		//---
		appName = appNameOpt.orElse(Home.getApp().getConfig().getNodeConfig().getAppName());
		this.dataProviderPlugin = dataProviderPlugin;
	}

	@Override
	public TimedDatas getTimeSeries(final List<String> measures, final DataFilter dataFilter, final TimeFilter timeFilter) {
		Assertion.checkNotNull(measures);
		Assertion.checkNotNull(dataFilter);
		Assertion.checkNotNull(timeFilter.getDim());// we check dim is not null because we need it
		//---
		return dataProviderPlugin.getTimeSeries(appName, measures, dataFilter, timeFilter);

	}

	@Override
	public TimedDatas getClusteredTimeSeries(final ClusteredMeasure clusteredMeasure, final DataFilter dataFilter, final TimeFilter timeFilter) {
		Assertion.checkNotNull(dataFilter);
		Assertion.checkNotNull(timeFilter);
		Assertion.checkNotNull(timeFilter.getDim()); // we check dim is not null because we need it
		Assertion.checkNotNull(clusteredMeasure);
		//---
		Assertion.checkArgNotEmpty(clusteredMeasure.getMeasure());
		Assertion.checkNotNull(clusteredMeasure.getThresholds());
		Assertion.checkState(!clusteredMeasure.getThresholds().isEmpty(), "For clustering the measure '{0}' you need to provide at least one threshold", clusteredMeasure.getMeasure());
		//we use the natural order
		clusteredMeasure.getThresholds().sort(Comparator.naturalOrder());
		//---
		return dataProviderPlugin.getClusteredTimeSeries(appName, clusteredMeasure, dataFilter, timeFilter);
	}

	@Override
	public TimedDatas getTabularData(final List<String> measures, final DataFilter dataFilter, final TimeFilter timeFilter, final boolean keepTime, final String... groupBy) {
		return dataProviderPlugin.getTabularData(appName, measures, dataFilter, timeFilter, keepTime, groupBy);
	}

	@Override
	public TimedDatas getTops(final String measure, final DataFilter dataFilter, final TimeFilter timeFilter, final String groupBy, final int maxRows) {
		return dataProviderPlugin.getTops(appName, measure, dataFilter, timeFilter, groupBy, maxRows);
	}

	@Override
	public List<String> getTagValues(final String measurement, final String tag) {
		return dataProviderPlugin.getTagValues(appName, measurement, tag);
	}

	@Override
	public List<HealthCheck> getHealthChecks() {

		final List<String> measures = Arrays.asList("status:last", "message:last", "name:last", "module:last", "feature:last", "checker:last");
		final DataFilter dataFilter = DataFilter.builder("healthcheck").build();
		final TimeFilter timeFilter = TimeFilter.builder("now() - 5w", "now()").build();// before 5 weeks we consider that we don't have data

		return getTabularData(measures, dataFilter, timeFilter, true, "name", "feature")
				.getTimedDataSeries()
				.stream()
				.map(timedDataSerie -> new HealthCheck(
						(String) timedDataSerie.getValues().get("name:last"),
						(String) timedDataSerie.getValues().get("checker:last"),
						(String) timedDataSerie.getValues().get("module:last"),
						(String) timedDataSerie.getValues().get("feature:last"),
						Instant.ofEpochMilli(timedDataSerie.getTime()),
						buildHealthMeasure(
								(Double) timedDataSerie.getValues().get("status:last"),
								(String) timedDataSerie.getValues().get("message:last"))))
				.collect(Collectors.toList());

	}

	private static HealthMeasure buildHealthMeasure(final Double status, final String message) {
		final HealthMeasureBuilder healthMeasureBuilder = HealthMeasure.builder();
		switch (status.intValue()) {
			case 0:
				healthMeasureBuilder
						.withRedStatus(message, null);
				break;
			case 1:
				healthMeasureBuilder
						.withYellowStatus(message, null);
				break;
			case 2:
				healthMeasureBuilder
						.withGreenStatus(message);
				break;
			default:
				throw new IllegalArgumentException("HealthStatus with number '" + status + "' is unknown");
		}
		return healthMeasureBuilder.build();
	}

	@Override
	public List<Metric> getMetrics() {
		final List<String> measures = Arrays.asList("value:last", "name:last", "feature:last");
		final DataFilter dataFilter = DataFilter.builder("metric").build();
		final TimeFilter timeFilter = TimeFilter.builder("now() - 5w", "now()").build();// before 5 weeks we consider that we don't have data

		return getTabularData(measures, dataFilter, timeFilter, true, "name", "feature")
				.getTimedDataSeries()
				.stream()
				.filter(timedDataSerie -> timedDataSerie.getValues().get("value:last") != null)
				.map(timedDataSerie -> Metric.builder()
						.withName((String) timedDataSerie.getValues().get("name:last"))
						.withFeature((String) timedDataSerie.getValues().get("feature:last"))
						.withMeasureInstant(Instant.ofEpochMilli(timedDataSerie.getTime()))
						.withValue((Double) timedDataSerie.getValues().get("value:last"))
						.withSuccess()
						.build())
				.collect(Collectors.toList());

	}

}


text:
/**
 * @fileoverview A base class of all visualization charts.
 * @version 1.0.1
 * @see https://google.github.io/styleguide/jsguide.html
 * @see https://github.com/google/closure-compiler/wiki
 */

/**
 * A base class of all visualization charts.
 * @param {string|Element} container The HTML container.
 * @constructor
 * @class A base class of all visualization charts.
 * @requires charts.Tooltip
 * @requires util.Object
 */
charts.BaseChart = function(container) {

  /**
   * Defaults chart options.
   * @dict
   * @see charts.BaseChart#getOptions
   * @example {
   *   'font': {'family': 'Arial', 'size': 13},
   *   'opacity': 0.8,
   *   'colors': [list of colors]
   * }
   */
  this.defaults = {
    'font': {'family': 'Arial', 'size': 13},
    'opacity': 0.7,
    'colors': charts.BaseChart.DEFAULT_COLORS
  };

  /**
   * The reference to HTML chart container.
   * @type {Element}
   */
  this.container = typeof container == 'string' ?
      dom.getElementById(container) : container;

  /**
   * Instance of charts.Tooltip.
   * @type {!charts.Tooltip}
   * @see charts.Tooltip
   * @protected
   */
  this.tooltip = new charts.Tooltip;

  /**
   * Draws the chart based on data and opt_options.
   * Abstract method, should be overwritten in nested classes.
   * All overwritten methods should be exported for closure compiler.
   * @param {!Array.<Array>} data A chart data.
   * @param {Object=} opt_options A optional chart's configuration options.
   */
  this.draw = function(data, opt_options) {};

  /**
   * Gets chart's options merged with defaults chart's options.
   * @param {Object.<string, *>=} opt_options Options map.
   * @return {!Object.<string, *>} A map of name/value pairs.
   * @see charts.BaseChart#defaults
   */
  this.getOptions = function(opt_options) {
    return util.Object.extend(self_.defaults, opt_options || {});
  };

  /**
   * Extracts columns from data.
   * @param {Array.<Array>} data The chart data.
   * @return {!Array.<string>} Returns data columns.
   */
  this.getDataColumns = function(data) {
    // Return copy of first data row.
    return /** @type {!Array.<string>} */ (data[0].slice());
  };

  /**
   * Extracts rows from data.
   * @param {Array.<Array>} data The chart data.
   * @return {!Array.<Array>} Returns cloned data rows.
   */
  this.getDataRows = function(data) {
    // Return copy of data rows except first row.
    return data.slice(1);
  };

  /**
   * Gets data range with min and max values.
   * @param {Array.<Array>} data The chart data.
   * @param {number=} opt_column Optional columns index starting from.
   * @return {!Array.<number>} Returns range as [min, max] array.
   */
  this.getDataRange = function(data, opt_column) {
    if (!data.range_) {
      opt_column = opt_column || 0;
      /** @type {!Array.<Array>} */ var rows = self_.getDataRows(data);
      /** @type {number} */ var maxValue = 0;
      /** @type {?number} */ var minValue = null;
      for (/** @type {number} */ var i = 0; i < rows.length;) {
        /** @type {Array.<number>} */ var row = rows[i++];
        for (/** @type {number} */ var j = opt_column; j < row.length; j++) {
          maxValue = Math.max(maxValue, row[j]);
          if (minValue == null) minValue = maxValue;
          minValue = Math.min(minValue, row[j]);
        }
      }
      data.range_ = [minValue, maxValue];
    }
    return data.range_;
  };

  /**
   * Gets max value.
   * @param {Array.<Array>} data The chart data.
   * @return {number} Returns max value.
   */
  this.getMaxValue = function(data) {
    return self_.getDataRange(data)[1];
  };

  /**
   * Gets min value.
   * @param {Array.<Array>} data The chart data.
   * @return {number} Returns min value.
   */
  this.getMinValue = function(data) {
    return self_.getDataRange(data)[0];
  };

  /**
   * Draws content into this.container as innerHTML.
   * @param {string} content SVG or VML markup content.
   * @param {number=} opt_width Optional chart width.
   * @param {number=} opt_height Optional chart height.
   */
  this.drawContent = function(content, opt_width, opt_height) {
    opt_width = opt_width || self_.container.offsetWidth || 200;
    opt_height = opt_height || self_.container.offsetHeight || opt_width;

    self_.container.style.position = 'relative';
    self_.container.style.overflow = 'hidden';

    self_.container.innerHTML += (charts.IS_SVG_SUPPORTED ?
        wrapSvgContent_ : wrapVmlContent_)(content, opt_width, opt_height);
  };

  /**
   * Wraps SVG markup content into <svg> container.
   * @param {string} content SVG markup content.
   * @param {number} width The chart width.
   * @param {number} height The chart height.
   * @return {string} Returns wrapped SVG markup.
   * @private
   */
  function wrapSvgContent_(content, width, height) {
    // style="shape-rendering:geometricPrecision;
    //        text-rendering:geometricPrecision;
    //        image-rendering:optimizeQuality;
    //        fill-rule:evenodd;
    //        clip-rule:evenodd"
    return '<svg width="' + width + '" height="' + height + '" version="1.0" ' +
           'xmlns="http://www.w3.org/2000/svg" ' +
           'xmlns:xlink="http://www.w3.org/1999/xlink" ' +
           'style="position:absolute">' +
           content + '</svg>';
  }

  /**
   * Wraps VML markup content into <vml:group> container.
   * @param {string} content VML markup content.
   * @param {number} width The chart width.
   * @param {number} height The chart height.
   * @return {string} Returns wrapped VML markup.
   * @private
   */
  function wrapVmlContent_(content, width, height) {
    return '<v:group coordorigin="0 0" ' +
           'coordsize="' + width + ' ' + height + '" ' +
           'style="position:absolute;left:0;top:0;' +
           'width:' + width + 'px;height:' + height + 'px">' +
           content + '</v:group>';
  }

  /**
   * Initializes default behaviors.
   * @private
   */
  function init_() {

    if (!charts.IS_SVG_SUPPORTED) {
      try {
        dom.document['namespaces']['add'](
            'v', 'urn:schemas-microsoft-com:vml', '#default#VML');
      } catch (e) {
        //window.console && console.log(['vml:namespaces.add', e.message || e]);
      }

      try {
        /** @type {Object} */ var sheet = dom.document['createStyleSheet']();
        sheet['addRule']('v\\:group',
                         'behavior:url(#default#VML);antialias:true;' +
                         'display:inline-block');
      } catch (e) {
        //window.console && console.log(['vml:sheet.addRule', e.message || e]);
      }
    }
  }

  /**
   * The reference to current class instance. Used in private methods.
   * @type {!charts.BaseChart}
   * @private
   */
  var self_ = this;

  init_();
};

/**
 * List of default colors.
 * @type {!Array.<string>}
 * @static
 */
charts.BaseChart.DEFAULT_COLORS = [
  '#3366BB', '#DD3311', '#FF9911', '#119911', '#991199',
  '#0099CC', '#DD4488', '#66AA33', '#BB2222', '#336699',
  '#9955AA', '#11AA99', '#AABB11', '#6633DD', '#EE7700',
  '#880000', '#661166', '#339966', '#5577AA', '#3333AA',
  '#BB7722', '#11DD22', '#BB1188', '#FF3399', '#995533',
  '#AACC11', '#227788', '#668811', '#BBAA11', '#005522',
  '#773311', '#4EDB05', '#377D18', '#AD9E88', '#4C49E3',
  '#86D0DD', '#5613EA', '#29F847', '#828295', '#B7F439',
  '#224256', '#490A7F', '#622A17', '#E188A1', '#F65A2D',
  '#87F586', '#DF56E4', '#F3E815', '#C528D6', '#32BDC0',
  '#91F51C', '#A75590', '#556F7C', '#520036', '#64B6AA',
  '#825B4A', '#63B75A', '#DC8BF7', '#811D02', '#FB1D45',
  '#76856A', '#F240BB', '#D53C9B', '#67AEC8', '#01786A',
  '#A08A65', '#715E3F', '#92B88A', '#3A5D6D', '#B8D9D9',
  '#622C1B', '#1F566F', '#F221EE', '#04808D', '#7A787A',
  '#F48A8A', '#A60FFA', '#5FDF71', '#F4D11E', '#EDA971',
  '#3F0AF2', '#E84203', '#2344FA', '#98CFB5', '#E0F068',
  '#83D7E3', '#1500EA', '#99C760', '#21E636', '#241BB8',
  '#C44FF5', '#3499BF', '#CFC58F', '#91A739', '#7222B0'];


text:
class ToErb < OpenStruct
  def render(template)
    ERB.new(template).result(binding)
  end
end


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>JovemFrameWork</groupId>
		<artifactId>pai</artifactId>
		<version>1.0.0</version>
	</parent>
	<artifactId>lib</artifactId>
	<name>lib</name>
	<description>lib</description>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.16</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.1.10.Final</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.33</version>
		</dependency>

		<dependency>
			<groupId>org.hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<version>2.2.4</version>
		</dependency>

		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.1.10.Final</version>
		</dependency>

		<dependency>
			<groupId>javax.persistence</groupId>
			<artifactId>persistence-api</artifactId>
			<version>1.0.2</version>
		</dependency>

		<dependency>
			<groupId>commons-lang</groupId>
			<artifactId>commons-lang</artifactId>
			<version>2.6</version>
		</dependency>

		<dependency>
			<groupId>net.coobird</groupId>
			<artifactId>thumbnailator</artifactId>
			<version>0.4.3</version>
		</dependency>

		<dependency>
			<groupId>org.apache.pdfbox</groupId>
			<artifactId>pdfbox</artifactId>
			<version>1.8.1</version>
		</dependency>

		<dependency>
			<groupId>org.quartz-scheduler</groupId>
			<artifactId>quartz</artifactId>
			<version>2.1.7</version>
		</dependency>

		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-email</artifactId>
			<version>1.3.1</version>
		</dependency>

		<dependency>
			<groupId>javax.mail</groupId>
			<artifactId>mail</artifactId>
			<version>1.4</version>
		</dependency>

		<dependency>
			<groupId>javax.activation</groupId>
			<artifactId>activation</artifactId>
			<version>1.1-rev-1</version>
		</dependency>

		<dependency>
			<groupId>com.google.code.gson</groupId>
			<artifactId>gson</artifactId>
			<version>2.3</version>
		</dependency>
	</dependencies>

</project>


text:
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <title>Aria CMS</title>


text:
package org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.string;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.List;
import org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.BeamSqlExpression;
import org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.BeamSqlPrimitive;
import org.apache.calcite.sql.type.SqlTypeName;
import org.junit.Test;

/**
 * Test for BeamSqlStringUnaryExpression.
 */
public class BeamSqlStringUnaryExpressionTest {

  @Test public void accept() throws Exception {
    List<BeamSqlExpression> operands = new ArrayList<>();

    operands.add(BeamSqlPrimitive.of(SqlTypeName.VARCHAR, "hello"));
    assertTrue(new BeamSqlCharLengthExpression(operands).accept());

    operands.clear();
    operands.add(BeamSqlPrimitive.of(SqlTypeName.INTEGER, 1));
    assertFalse(new BeamSqlCharLengthExpression(operands).accept());

    operands.clear();
    operands.add(BeamSqlPrimitive.of(SqlTypeName.VARCHAR, "hello"));
    operands.add(BeamSqlPrimitive.of(SqlTypeName.VARCHAR, "hello"));
    assertFalse(new BeamSqlCharLengthExpression(operands).accept());
  }

}


text:
package objsets

import TweetReader._

/**
  * A class to represent tweets.
  */
class Tweet(val user: String, val text: String, val retweets: Int) {
  override def toString: String =
    "User: " + user + "\n" +
      "Text: " + text + " [" + retweets + "]"
}

/**
  * This represents a set of objects of type `Tweet` in the form of a binary search
  * tree. Every branch in the tree has two children (two `TweetSet`s). There is an
  * invariant which always holds: for every branch `b`, all elements in the left
  * subtree are smaller than the tweet at `b`. The elements in the right subtree are
  * larger.
  *
  * Note that the above structure requires us to be able to compare two tweets (we
  * need to be able to say which of two tweets is larger, or if they are equal). In
  * this implementation, the equality / order of tweets is based on the tweet's text
  * (see `def incl`). Hence, a `TweetSet` could not contain two tweets with the same
  * text from different users.
  *
  *
  * The advantage of representing sets as binary search trees is that the elements
  * of the set can be found quickly. If you want to learn more you can take a look
  * at the Wikipedia page [1], but this is not necessary in order to solve this
  * assignment.
  *
  * [1] http://en.wikipedia.org/wiki/Binary_search_tree
  */
abstract class TweetSet {

  /**
    * This method takes a predicate and returns a subset of all the elements
    * in the original set for which the predicate is true.
    *
    * Question: Can we implement this method here, or should it remain abstract
    * and be implemented in the subclasses?
    */
  def filter(p: Tweet => Boolean): TweetSet = filterAcc(p, new Empty)

  /**
    * This is a helper method for `filter` that propagates the accumulated tweets.
    */
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet

  /**
    * Returns a new `TweetSet` that is the union of `TweetSet`s `this` and `that`.
    *
    * Question: Should we implement this method here, or should it remain abstract
    * and be implemented in the subclasses?
    */
  def union(that: TweetSet): TweetSet

  /**
    * Returns the tweet from this set which has the greatest retweet count.
    *
    * Calling `mostRetweeted` on an empty set should throw an exception of
    * type `java.util.NoSuchElementException`.
    *
    * Question: Should we implement this method here, or should it remain abstract
    * and be implemented in the subclasses?
    */
  def mostRetweeted: Tweet

  /**
    * Returns a list containing all tweets of this set, sorted by retweet count
    * in descending order. In other words, the head of the resulting list should
    * have the highest retweet count.
    *
    * Hint: the method `remove` on TweetSet will be very useful.
    * Question: Should we implement this method here, or should it remain abstract
    * and be implemented in the subclasses?
    */
  def descendingByRetweet: TweetList

  /**
    * The following methods are already implemented
    */

  /**
    * Returns a new `TweetSet` which contains all elements of this set, and the
    * the new element `tweet` in case it does not already exist in this set.
    *
    * If `this.contains(tweet)`, the current set is returned.
    */
  def incl(tweet: Tweet): TweetSet

  /**
    * Returns a new `TweetSet` which excludes `tweet`.
    */
  def remove(tweet: Tweet): TweetSet

  /**
    * Tests if `tweet` exists in this `TweetSet`.
    */
  def contains(tweet: Tweet): Boolean

  /**
    * This method takes a function and applies it to every element in the set.
    */
  def foreach(f: Tweet => Unit): Unit

  // helper method
  def isEmpty: Boolean
}

class Empty extends TweetSet {
  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = acc

  /**
    * The following methods are already implemented
    */

  def contains(tweet: Tweet): Boolean = false

  def incl(tweet: Tweet): TweetSet = new NonEmpty(tweet, new Empty, new Empty)

  def remove(tweet: Tweet): TweetSet = this

  def foreach(f: Tweet => Unit): Unit = ()

  // helper method
  def isEmpty: Boolean = true

  // Overridden methods
  /**
    * Returns a list containing all tweets of this set, sorted by retweet count
    * in descending order. In other words, the head of the resulting list should
    * have the highest retweet count.
    **/

  override def descendingByRetweet: TweetList = Nil

  /** Returns a new `TweetSet` that is the union of `TweetSet`s `this` and `that`.
    *
    */
  override def union(that: TweetSet): TweetSet = that

  /**
    * Returns the tweet from this set which has the greatest retweet count.
    *
    * Calling `mostRetweeted` on an empty set should throw an exception of
    * type `java.util.NoSuchElementException`.
    */
  override def mostRetweeted: Tweet = throw new java.util.NoSuchElementException()
}

class NonEmpty(elem: Tweet, left: TweetSet, right: TweetSet) extends TweetSet {

  def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
    if (p(elem)) left.filterAcc(p, right.filterAcc(p, acc.incl(elem)))
    else
      left.filterAcc(p, right.filterAcc(p, acc))

  }

  /**
    * The following methods are already implemented
    */

  def contains(x: Tweet): Boolean =
    if (x.text < elem.text) left.contains(x)
    else if (elem.text < x.text) right.contains(x)
    else true

  def incl(x: Tweet): TweetSet = {
    if (x.text < elem.text) new NonEmpty(elem, left.incl(x), right)
    else if (elem.text < x.text) new NonEmpty(elem, left, right.incl(x))
    else this
  }

  def remove(tw: Tweet): TweetSet =
    if (tw.text < elem.text) new NonEmpty(elem, left.remove(tw), right)
    else if (elem.text < tw.text) new NonEmpty(elem, left, right.remove(tw))
    else left.union(right)

  def foreach(f: Tweet => Unit): Unit = {
    f(elem)
    left.foreach(f)
    right.foreach(f)
  }

  // helper method
  def isEmpty: Boolean = false

  /**
    * Returns a new `TweetSet` that is the union of `TweetSet`s `this` and `that`.
    *
    */
  override def union(that: TweetSet): TweetSet = {
    if (that.isEmpty) this
    else that.filterAcc(x => true, this)
  }

  /**
    * Returns the tweet from this set which has the greatest retweet count.
    *
    */
  override def mostRetweeted: Tweet = {

    def moreTweets(x: Tweet, y: Tweet): Tweet = {
      if (x.retweets > y.retweets) x else y
    }

    if (left.isEmpty && right.isEmpty) elem
    else if (left.isEmpty && !right.isEmpty) moreTweets(elem, right.mostRetweeted)
    else if (right.isEmpty && !left.isEmpty) moreTweets(elem, left.mostRetweeted)
    else moreTweets(elem, moreTweets(left.mostRetweeted, right.mostRetweeted))
  }

  /**
    * Returns a list containing all tweets of this set, sorted by retweet count
    * in descending order. In other words, the head of the resulting list should
    * have the highest retweet count.
    *
    */
  override def descendingByRetweet: TweetList =
    new Cons(mostRetweeted, remove(mostRetweeted).descendingByRetweet)
}

trait TweetList {
  def head: Tweet

  def tail: TweetList

  def isEmpty: Boolean

  def foreach(f: Tweet => Unit): Unit =
    if (!isEmpty) {
      f(head)
      tail.foreach(f)
    }
}

object Nil extends TweetList {
  def head = throw new java.util.NoSuchElementException("head of EmptyList")

  def tail = throw new java.util.NoSuchElementException("tail of EmptyList")

  def isEmpty = true
}

class Cons(val head: Tweet, val tail: TweetList) extends TweetList {
  def isEmpty = false
}

object GoogleVsApple {
  val google = List("android", "Android", "galaxy", "Galaxy", "nexus", "Nexus")
  val apple = List("ios", "iOS", "iphone", "iPhone", "ipad", "iPad")

  lazy val googleTweets: TweetSet = TweetReader.allTweets.filter { t => google.exists { keyWord => t.text.contains(keyWord) } }
  lazy val appleTweets: TweetSet = TweetReader.allTweets.filter { t => apple.exists { keyWord => t.text.contains(keyWord) } }

  /**
    * A list of all tweets mentioning a keyword from either apple or google,
    * sorted by the number of retweets.
    */
  lazy val trending: TweetList = appleTweets.union(googleTweets).descendingByRetweet
}

object Main extends App {
  // Print the trending tweets
  GoogleVsApple.trending foreach println
}


text:
package org.hibernate.cache.infinispan.timestamp;

import org.infinispan.config.Configuration;
import org.infinispan.config.Configuration.CacheMode;
import org.infinispan.eviction.EvictionStrategy;

import org.hibernate.cache.CacheException;
import org.hibernate.cache.infinispan.TypeOverrides;

/**
 * TimestampTypeOverrides.
 *
 * @author Galder Zamarreño
 * @since 3.5
 */
public class TimestampTypeOverrides extends TypeOverrides {
   @Override
   public void validateInfinispanConfiguration(Configuration configuration) throws CacheException {
      CacheMode cacheMode = configuration.getCacheMode();
      if (cacheMode.equals(CacheMode.INVALIDATION_ASYNC) || cacheMode.equals(CacheMode.INVALIDATION_SYNC)) {
         throw new CacheException("Timestamp cache cannot be configured with invalidation");
      }
      EvictionStrategy strategy = configuration.getEvictionStrategy();
      if (!strategy.equals(EvictionStrategy.NONE)) {
         throw new CacheException("Timestamp cache cannot be configured with eviction");
      }
   }
}


text:
require 'spec_helper'

describe Pocketsphinx::Configuration do
  subject { Pocketsphinx::Configuration.default }

  it "provides a default pocketsphinx configuration" do
    expect(subject).to be_a(Pocketsphinx::Configuration::Default)
  end

  it "supports integer settings" do
    expect(subject['frate']).to eq(100)
    expect(subject['frate']).to be_a(Fixnum)

    subject['frate'] = 50
    expect(subject['frate']).to eq(50)

    expect { subject['frate'] = nil }.to raise_exception "Only string settings can be set to nil"
  end

  it "supports float settings" do
    expect(subject['samprate']).to eq(16000)
    expect(subject['samprate']).to be_a(Float)

    subject['samprate'] = 8000
    expect(subject['samprate']).to eq(8000)

    expect { subject['samprate'] = nil }.to raise_exception "Only string settings can be set to nil"
  end

  it "supports string settings" do
    expect(subject['warp_type']).to eq('inverse_linear')

    subject['warp_type'] = 'different_type'
    expect(subject['warp_type']).to eq('different_type')

    subject['warp_type'] = nil
    expect(subject['warp_type']).to eq(nil)
  end

  it "supports boolean settings" do
    expect(subject['smoothspec']).to eq(false)

    subject['smoothspec'] = true
    expect(subject['smoothspec']).to eq(true)

    expect { subject['smoothspec'] = nil }.to raise_exception "Only string settings can be set to nil"
  end

  it "does not support string lists" do
    subject.setting_definitions['string_list_setting'] = Pocketsphinx::Configuration::SettingDefinition.new(
      'string_list_setting', 32, nil, nil
    )

    expect { subject['string_list_setting'] }.to raise_exception NotImplementedError
    expect { subject['string_list_setting'] = 'value' }.to raise_exception NotImplementedError
  end

  it 'raises exceptions when setting with incorrectly typed values' do
    expect { subject['frate'] = true }.to raise_exception "Configuration setting 'frate' must be of type Integer"
  end

  it 'raises exceptions when a setting is unknown' do
    expect { subject['unknown'] = true }.to raise_exception "Configuration setting 'unknown' does not exist"
  end

  describe '#setting_names' do
    it 'contains the names of all possible system settings' do
      expect(subject.setting_names.count).to eq(112)
    end
  end

  describe '#details' do
    it 'gives details for a single setting' do
      expect(subject.details 'vad_threshold').to eq({
        name: "vad_threshold",
        type: :float,
        default: 2.0,
        required: false,
        value: 2.0,
        info: "Threshold for decision between noise and silence frames. Log-ratio between signal level and noise level."
      })
    end

    it 'gives details for all settings when no name is specified' do
      details = subject.details

      expect(details.count).to eq(112)
      expect(details.first).to eq({
        name: "agc",
        type: :string,
        default: "none",
        required: false,
        value: "none",
        info: "Automatic gain control for c0 ('max', 'emax', 'noise', or 'none')"
      })
    end
  end

  context 'keyword spotting configuration' do
    subject { Pocketsphinx::Configuration::KeywordSpotting.new('Okay computer') }

    it 'modifies the default configuration keyphrase and language model' do
      changes = subject.changes

      expect(changes.count).to be(2)

      expect(changes[0][:name]).to eq('keyphrase')
      expect(changes[0][:value]).to eq('okay computer')

      expect(changes[1][:name]).to eq('lm')
      expect(changes[1][:value]).to be_nil
    end

    it 'exposes the keyphrase setting as #keyword' do
      subject.keyword = 'Hello computer'

      expect(subject.keyword).to eq('hello computer')
      expect(subject['keyphrase']).to eq('hello computer')
    end

    it 'exposes the kws_threshold setting as #kws_threshold' do
      subject.kws_threshold = 24

      expect(subject.kws_threshold).to eq(24)
      expect(subject['kws_threshold']).to eq(24)
    end
  end
end


text:
require "spec_helper"

describe FeedBag::Feedbaggable do
  before do
    VCR.use_cassette('new_wikipedia') do
      @current_entries = FeedGrabber.new("http://en.wikipedia.org/w/index.php?title=Special:NewPages&feed=atom").parse_entries
    end
    @entry = Entry.new
  end

  context "Class Methods" do
    it "can tell if the model is up to date" do
      expect(@entry.feed_current?).to be_true
    end
  end
end


text:
package org.apache.skywalking.apm.collector.storage.dao.register;

import org.apache.skywalking.apm.collector.storage.base.dao.DAO;
import org.apache.skywalking.apm.collector.storage.table.register.ServiceName;

/**
 * @author peng-yongsheng
 */
public interface IServiceNameRegisterDAO extends DAO {
    int getMaxServiceId();

    int getMinServiceId();

    void save(ServiceName serviceName);
}


text:
<?php

declare(strict_types=1);

namespace Comely\IO\DependencyInjection\Services;

use Comely\IO\DependencyInjection\Exception\ServicesException;

/**
 * Class Service
 * @package Comely\IO\DependencyInjection\Services
 */
class Service
{
    /** @var string */
    private $key;
    /** @var null|string */
    private $class;
    /** @var array */
    private $methods;
    /** @var null|ServiceInjectMethod */
    private $constructor;
    /** @var null|ServiceInjectProps */
    private $props;

    /**
     * Service constructor.
     * @param string $key
     * @throws ServicesException
     */
    public function __construct(string $key)
    {
        $this->key = $key;
        $this->methods = [];
    }

    /**
     * @param string $className
     * @return Service
     * @throws ServicesException
     */
    public function class(string $className): self
    {
        if (!preg_match('/^[a-zA-Z0-9\_\\\]{4,}$/', $className)) {
            throw new ServicesException(sprintf('Invalid class name signature for key "%s"', $this->key));
        }

        return $this;
    }

    /**
     * @return ServiceInjectMethod
     */
    public function constructor(): ServiceInjectMethod
    {
        if (!$this->constructor) {
            $this->constructor = new ServiceInjectMethod("__construct");
        }

        return $this->constructor;
    }

    /**
     * @param string $name
     * @return ServiceInjectMethod
     */
    public function method(string $name): ServiceInjectMethod
    {
        $injectMethod = new ServiceInjectMethod($name);
        $this->methods[$name] = $injectMethod;
        return $injectMethod;
    }

    /**
     * @return ServiceInjectProps
     */
    public function props(): ServiceInjectProps
    {
        if (!$this->props) {
            $this->props = new ServiceInjectProps();
        }

        return $this->props;
    }

    /**
     * @param array ...$args
     * @return mixed
     * @throws ServicesException
     */
    public function createInstance(...$args)
    {
        // Check if class exists
        if (!$this->class || !class_exists($this->class)) {
            throw new ServicesException(
                sprintf('Failed to create instance for "%s", class "%s" does not exist', $this->key, $this->class ?? "")
            );
        }

        // Constructor
        $className = $this->class;
        $constructorArgs = $args;
        if ($this->constructor) {
            $constructorArgs = array_merge($constructorArgs, $this->constructor->getArgs());
        }

        $constructorArgs = $this->processArgs($constructorArgs);

        // Create instance
        $object = new $className(...$constructorArgs);

        // Methods
        /** @var $method ServiceInjectMethod */
        foreach ($this->methods as $method) {
            // No need to check if method exists but quite possibly magic __call method may be implemented
            call_user_func_array(
                [$object, $method->getName()], // Method name
                $this->processArgs($method->getArgs()) // Method arguments processed
            );
        }

        // Properties
        if ($this->props) {
            $props = $this->props->getAll();
            foreach ($props as $propName => $propValue) {
                $object->$propName = $this->processArg($propValue);
            }
        }

        // Return created object
        return $object;
    }

    /**
     * @param array ...$args
     * @return array
     * @throws ServicesException
     */
    private function processArgs(...$args): array
    {
        $processed = [];
        foreach ($args as $arg) {
            $arg = $this->processArg($arg);
            $processed[] = $arg;
        }

        return $processed;
    }

    /**
     * @param $arg
     * @return mixed
     * @throws ServicesException
     */
    private function processArg($arg)
    {
        if (is_object($arg) && $arg instanceof Service) {
            $arg = $arg->createInstance();
        }

        return $arg;
    }
}


text:
package dk.javacode.srsm.testmodel;

import dk.javacode.srsm.converters.JdbcDataConverter;

public class NumberJdbcConverter implements JdbcDataConverter<Integer> {

	@Override
	public Integer convertToPojo(Object o) {
		if (o == null) {
			return null;
		}
		if (!(o instanceof Integer)) {
			throw new RuntimeException("Number converter can only convert integers");
		}
		return ((Integer) o) + 5000;
	}

	@Override
	public Object pojoToDatabase(Object o) {
		return ((Integer) o) - 5000;
	}
}


text:
var path = require('path');
var dir = path.resolve(__dirname, '../example');
var Monitor = require('carcass-monitor');
var supertest = require('supertest');

describe('Server / http:', function() {

    var monitor = new Monitor();
    var request = supertest('http://127.0.0.1:3210');

    after(function(done) {
        monitor.close(done);
    });

    it.skip('cannot be connected before started', function(done) {
        request.get('/ping')
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect(200, done);
    });

    it('can start', function(done) {
        monitor.stack({
            sourceDir: dir,
            script: 'program.js',
            options: ['-s', 'http'],
            startupMessage: 'listening'
        }).start(done);
    });

    it('can handle a request', function(done) {
        request.get('/ping')
            .set('Accept', 'application/json')
            .expect('Content-Type', /json/)
            .expect(200, done);
    });

});


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="/releases/4.3.0/css/style.css" rel="stylesheet" />

<title>-buildrepo repo ( ',' repo ) *</title>
<meta name="generator" content="Jekyll v3.8.5" />
<meta property="og:title" content="-buildrepo repo ( ',' repo ) *" />
<meta property="og:locale" content="en_US" />
<meta name="description" content="After bnd has build a project it creates 0 or more JARs. If the -buildrepo is set, the JARs are put into the given repositories. The syntax is as follows:" />
<meta property="og:description" content="After bnd has build a project it creates 0 or more JARs. If the -buildrepo is set, the JARs are put into the given repositories. The syntax is as follows:" />

			Intro
			Headers
			Instructions
			Macros
			Commands

<button class="dropbtn">4.3.0</button>

Introduction

How to install bnd

Guided Tour

Guided Tour Workspace & Projects

Concepts

Best practices

Build

Project Setup

Generating JARs

Versioning

Baselining

Service Components

Metatype

Contracts

Bundle Annotations

Accessor Properties

SPI Annotations

Resolving Dependencies

Launching

Startlevels

Testing

Testing with Launchpad

Packaging Applications

JPMS Libraries

Wrapping Libraries to OSGi Bundles

Generating Documentation

Commands

For Developers

Tools bound to bnd

Headers

Instruction Reference

Instruction Index

Macro Reference

Macro Index

Plugins

Settings

Errors

Warnings

Frequently Asked Questions

 -buildrepo  repo ( ',' repo ) *

After bnd has build a project it creates 0 or more JARs. If the -buildrepo is set, the JARs are put into the given repositories. The syntax is as follows:

 -buildrepo   ::= repo ( ',' repo )*
 repo			::= NAME ( ';' NAME ('=' VALUE)? )*

The instruction provides a name of a repository, the repository must exist in the workspace. Any properties added to the name are provided as properties in the release context and thus given to the repository.

This feature was inspired by the Maven Bnd Repository. In the Maven development process, projects are installed in the local repository (usually ~/.m2/repository) so they can be shared with other Maven projects. Setting the -buildrepo to a Maven repository will allow a bnd workspace to participate in this process on equal footing. Every time the project is build, all its JARs are installed in the associated Maven repository.

For example:

-plugin.maven  \
	aQute.bnd.repository.maven.provider.MavenBndRepository; \
	name=Local

-buildrepo: Local

The install process is taking place in-line with the build process. It is therefore recommended to only use this for local (i.e. file system based) installs.

GitHub


text:
'use strict';

pizzaApp.directive('recordAvailabilityValidator',
  ['$http', function($http) {

  return {
    require : 'ngModel',
    link : function(scope, element, attrs, ngModel) {
      var apiUrl = attrs.recordAvailabilityValidator;

      function setAsLoading(bool) {
        ngModel.$setValidity('recordLoading', !bool);
      }

      function setAsAvailable(bool) {
        ngModel.$setValidity('recordAvailable', bool);
      }

      ngModel.$parsers.push(function(value) {
        if(!value || value.length == 0) return;
        // append id to apiUrl if it exists
        // if passed the record from the existing user
        // will excluded in the validation (this was setup for testing unique email address)
        // var urlQuery = '/' + value;
        var urlQuery = '/' + value + (scope.user.id ? '/id/'+scope.user.id : '');

        setAsLoading(true);
        setAsAvailable(false);

        $http.get(apiUrl + urlQuery)
          .then(function (data) {
            setAsLoading(false);
            setAsAvailable(Boolean(data.data.length === 0));
          });

        return value;
      })
    }
  }
}]);


text:
package com.onextent.android.activity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.text.Html;
import android.text.util.Linkify;
import android.graphics.Color;
import android.view.Window;
import android.widget.TextView;

import com.onextent.oemap.R;

public class AboutDialog extends Dialog {

    private static Context mContext = null;

    public AboutDialog(Context context) {
        super(context);
        mContext = context;
    }

    public static String readRawTextFile(int id) {
        InputStream inputStream = mContext.getResources().openRawResource(id);

        InputStreamReader in = new InputStreamReader(inputStream);
        BufferedReader buf = new BufferedReader(in);
        String line;

        StringBuilder text = new StringBuilder();
        try {
            while ((line = buf.readLine()) != null) text.append(line);
        } catch (IOException e) {
            return null;
        }

        return text.toString();
    }

    /**
     * Standard Android on create method that gets called when the activity initialized.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {

        getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.about_dialog);

        TextView tv = (TextView) findViewById(R.id.legal_text);

        tv.setText(readRawTextFile(R.raw.legal));

        tv = (TextView) findViewById(R.id.info_text);

        tv.setText(Html.fromHtml(readRawTextFile(R.raw.info)));

        //tv.setLinkTextColor(Color.WHITE);

        Linkify.addLinks(tv, Linkify.ALL);
    }
}


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

namespace XMovie.Models.Settings
{
    public class FileExtensionSettings : ICloneable
    {
        public string Ext { get; set; }
        public bool IsEnabled { get; set; } = true;

        public static ObservableCollection<FileExtensionSettings> GetDefaultMovieExtensions()
        {
            var list = new string[]
            {
                "avi",
                "flv",
                "m4v",
                "mov",
                "mp4",
                "mpeg",
                "mpg",
                "rm",
                "wmv",
                "ts",
            };

            var result = new ObservableCollection<FileExtensionSettings>();
            foreach (var ext in list)
            {
                result.Add(new FileExtensionSettings() { Ext = ext, IsEnabled = true });
            }
            return result;
        }

        public object Clone()
        {
            return this.MemberwiseClone();
        }
    }
}


text:
require 'rubygems'
require 'test/unit'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'dollsearch'

class Test::Unit::TestCase
end


text:
namespace PluginsBase
{
    public interface IPlugin
    {
        string Name { get; }
        void Run();
    }
}


text:
var AuthenticatedClient = require('./../../../lib/core/client/authenticated-client.js');
var DataCenterClient = require('./../../../lib/base-services/datacenters/datacenter-client.js');
var GroupClient = require('./../../../lib/compute-services/groups/group-client.js');
var _ = require('underscore');
var DataCenter = require('./../../../lib/base-services/datacenters/domain/datacenter.js');

describe('Test Server client functions [INTEGRATION]', function () {
    var authClient = new AuthenticatedClient();
    var dataCenterClient = new DataCenterClient(authClient);
    var groupClient = new GroupClient(authClient);

    it('Should return group by ID', function (done) {
        this.timeout(15 * 1000);

        dataCenterClient
            .findAllDataCenters()
            .then(function (list) {
                return _.findWhere(list, {id: DataCenter.DE_FRANKFURT.id});
            })
            .then(function (dataCenter) {
                return _.findWhere(dataCenter.links, {rel: 'group'}).id;
            })
            .then(function (targetGroupId) {
                return groupClient.findGroupById(targetGroupId);
            })
            .then(function (result) {
                done();
            });
    });
});


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!doctype html>

    <meta charset="utf-8">
	<title>Ayjo Consulting</title>
   <meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="description" content="AyjoConsulting">
	<meta name="keywords" content="online payment, payment, payment gateway, gateway, AyjoConsulting">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<link rel="stylesheet" href="<?php echo base_url(); ?>resources/css/bootstrap.min.css">
	<link rel="stylesheet" href="<?php echo base_url(); ?>resources/css/bootstrap-theme.min.css">
	<link rel="stylesheet" href="<?php echo base_url(); ?>resources/css/main.css">

	<link href='http://fonts.googleapis.com/css?family=Lato:100,300,400' rel='stylesheet' type='text/css'>

<a href="<?=base_url()?>" style="color:#FFF;text-decoration:none">AyjoConsulting payments.

			<?php if($transaction['tr_status']=='1') {?>

<?=html_escape($status)?>

			<?php }else if($transaction['tr_status']=='2') {?>

<?=html_escape($status)?>

			<?php } ?>

Please note your transaction details below:

Payment From	<?=html_escape($customer['c_name'])." (".html_escape($customer['c_email']).") "?>

Payment To	<?=html_escape($vendor['v_name'])." (".html_escape($vendor['v_email']).") "?>

Transaction Amount	$<?=html_escape($transaction['tr_amount'])?>

Invoice Number	<?=html_escape($transaction['tr_id']);?>

Transaction-Id	<?=html_escape($transaction['hps_tr_id'])?>

Transaction Status	<?=html_escape($message)?>

Response Text	<?=html_escape($transaction['hps_res_text'])?>

Response Code	<?=html_escape($transaction['hps_res_code'])?>

 For any confusion regarding this payment, please mail us the query along with your invoice number

© <a href="<?php echo site_url(); ?>/home/contact" style="color:#FFF; text-decoration:none;" target="_blank">AyjoConsulting

      <a href="<?php echo site_url(); ?>" style="color:#FFF; text-decoration:none;" target="_blank">Home | <a href="<?php echo site_url(); ?>/home/services" style="color:#FFF; text-decoration:none;" target="_blank">Services | <a href="<?php echo site_url(); ?>/home/pricing" style="color:#FFF; text-decoration:none;" target="_blank">Pricing | <a href="<?php echo site_url(); ?>/home/contact" style="color:#FFF; text-decoration:none;" target="_blank">Contact | <a href="<?php echo site_url(); ?>/admin/" style="color:#FFF; text-decoration:none;" target="_blank">Login


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

namespace Badger.ViewModels
{
    [Export(typeof(IBadgerSettingsItemViewModel))]
    public class WebSettingsViewModel : BadgerSettingsItemViewModel
    {
        /// <summary>
        ///
        /// </summary>
        [ImportingConstructor]
        public WebSettingsViewModel()
        {
            this.DisplayName = "Web";
        }
    }
}


text:
module Cheers
  class Face < ImageComponent

    def apply
      wip = canvas
      [UpperGlow, LowerGlow, Texture, Mouth].each do |klass|
        wip = klass.new(wip, color_randomizer, image_randomizer.dup).apply
      end

      wip
    end

  end
end


text:
<style>
.row {
  width: 100%;
  display: block;
  line-height: 60px;
  text-align: center;
}
input[type="checkbox"] {
  display: none;
}
input[type="checkbox"] + label {
  display: inline-block;
  width: 40px;
  height: 20px;
  position: relative;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  margin: 0px 20px;
  box-sizing: border-box;
}
input[type="checkbox"] + label:after {
  content: '';
  display: block;
  position: absolute;
  left: 0px;
  top: 0px;
  width: 20px;
  height: 20px;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  cursor: pointer;
}
#simple_1:checked + label.red,
#simple_2:checked + label.red,
#simple_3:checked + label.red {
  background: #ECA9A7;
}
#simple_1:checked + label.red:after,
#simple_2:checked + label.red:after,
#simple_3:checked + label.red:after {
  background: #D9534F;
}
#simple_1:checked + label.green,
#simple_2:checked + label.green,
#simple_3:checked + label.green {
  background: #AEDCAE;
}
#simple_1:checked + label.green:after,
#simple_2:checked + label.green:after,
#simple_3:checked + label.green:after {
  background: #5CB85C;
}
#simple_1:checked + label:after,
#simple_2:checked + label:after,
#simple_3:checked + label:after {
  left: calc(100% - 20px);
}
#simple_1 + label,
#simple_2 + label,
#simple_3 + label {
  background: #ddd;
  border-radius: 20px;
  box-shadow: 1px 1px 3px #aaa;
}
#simple_1 + label:after,
#simple_2 + label:after,
#simple_3 + label:after {
  background: #fff;
  border-radius: 50%;
  box-shadow: 1px 1px 3px #aaa;
}
</style>


text:
[![Build Status](https://secure.travis-ci.org/realityforge/chef-tomcat.png?branch=master)](http://travis-ci.org/realityforge/chef-tomcat)

The tomcat cookbook installs and configures the Tomcat application server. The cookbook contains LWRPs to create
and configure Tomcat instances and deploy resources into the container.


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>CellValueFormatter</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jetel.util.spreadsheet

Class CellValueFormatter

java.lang.Object

org.jetel.util.spreadsheet.CellValueFormatter

public class CellValueFormatter
extends java.lang.Object

Constructor Summary

Constructors

Constructor and Description

CellValueFormatter()

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
formatCellValue(org.apache.poi.ss.usermodel.Cell cell,
               org.apache.poi.ss.usermodel.FormulaEvaluator formulaEvaluator,
               java.lang.String locale)

java.lang.String
formatRawCellContents(double cellValue,
                     int formatIndex,
                     java.lang.String formatString,
                     java.lang.String localeString,
                     boolean use1904windowing)

org.apache.poi.ss.usermodel.DataFormatter
getLocalizedDataFormater(java.lang.String localeString)

static java.lang.String
modifyFormatString(int formatIndex,
                  java.lang.String formatString)

We are using this method to implement formatting behavior as close to Excel as possible.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

CellValueFormatter

public CellValueFormatter()

Method Detail

formatRawCellContents

public java.lang.String formatRawCellContents(double cellValue,
                                     int formatIndex,
                                     java.lang.String formatString,
                                     java.lang.String localeString,
                                     boolean use1904windowing)

getLocalizedDataFormater

public org.apache.poi.ss.usermodel.DataFormatter getLocalizedDataFormater(java.lang.String localeString)

formatCellValue

public java.lang.String formatCellValue(org.apache.poi.ss.usermodel.Cell cell,
                               org.apache.poi.ss.usermodel.FormulaEvaluator formulaEvaluator,
                               java.lang.String locale)

modifyFormatString

public static java.lang.String modifyFormatString(int formatIndex,
                                  java.lang.String formatString)

We are using this method to implement formatting behavior as close to Excel as possible.

Parameters:

formatIndex -

formatString -

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
<?php
require_once '../models/Room.php';

$token = filter_input(INPUT_GET, "token", FILTER_SANITIZE_URL);
$Room = new Room($token);
$player = $Room->player;

function getPlayerName( $player ) {
    if ($player === 7) {
        return "a spectator";
    } else {
        return "player " . ($player + 1);
    }
}

// VIEW
include '../views/room.php';


text:
<?php

class PmatrixLogger {

    static function error($msg, $file = null) {
        file_put_contents("php://stderr", "ERROR:\t" . $msg . "\t" . $file . PHP_EOL);
    }

    static function info($msg, $file = null) {
        file_put_contents("php://stderr", "INFO:\t" . $msg . "\t" . $file . PHP_EOL);
    }

    static function warn($msg, $file = null) {
        file_put_contents("php://stderr", "WARN:\t" . $msg . "\t" . $file . PHP_EOL);
    }

    static function counter($group, $key, $value) {
        file_put_contents('php://stderr', "reporter:counter:{$group},{$key},{$value}\n");
    }
}


text:
namespace OKHOSTING.ORM.Conversions
{
	/// <summary>
	/// Converts a string to its representation in uppercase
	/// <para xml:lang="es">
	/// Convierte una cadena en su representacion en mayusculas
	/// </para>
	/// </summary>
	public class UppercaseConverter : ConverterBase<string, string>
	{
		/// <summary>
		/// Returns a copy of the string containing the value of the member but converted to uppercase.
		/// <para xml:lang="es">
		/// Devuelve una copia de la cadena que contiene el valor del miembro pero convertida en mayúsculas.
		/// </para>
		/// </summary>
		/// <param name="memberValue">
		/// Member value.
		/// <para xml:lang="es">Valor del miembro.</para>
		/// </param>
		public override string MemberToColumn(string memberValue)
		{
			return memberValue.ToUpper();
		}

		/// <summary>
		/// Returns a copy of the string containing the value column but converted to uppercase.
		/// <para xml:lang="es">
		/// Devuelve una copia de la cadena que contiene el valor de la columna pero convertida en mayúsculas.
		/// </para>
		/// </summary>
		/// <param name="columnValue">
		/// Column value.
		/// <para xml:lang="es">Valor de la columna.</para>
		/// </param>
		public override string ColumnToMember(string columnValue)
		{
			return columnValue.ToUpper();
		}
	}
}


text:
void SCaptureRegionWidget::Construct( const FArguments& InArgs )
{
	this->ChildSlot
	.VAlign(VAlign_Center)
	.HAlign(HAlign_Center)
		[
			SNew(STextBlock)
			.Font( FSlateFontInfo( FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Regular.ttf"), 20 ) )
			.ShadowOffset(FVector2D(1, 1))
			.Text(NSLOCTEXT("CaptureRegion", "SpecifyRectangleToCaptureMessage", "Please specify capture rectangle"))
		];

	Deactivate(true);

//	OnCaptureRegionChanged = InArgs._OnCaptureRegionChanged;
//	OnCaptureRegionCompleted = InArgs._OnCaptureRegionCompleted;

	CurrentState = State_Inactive;
	PotentialInteraction = PI_DrawNewCaptureRegion;
	bIgnoreExistingCaptureRegion = false;
}

void SCaptureRegionWidget::Activate(bool bCurrentCaptureRegionIsFullViewport)
{
	SetVisibility(EVisibility::Visible);

	OriginalCaptureRegion = GetHighResScreenshotConfig().UnscaledCaptureRegion;
	bIgnoreExistingCaptureRegion = bCurrentCaptureRegionIsFullViewport;
}

void SCaptureRegionWidget::Deactivate(bool bKeepChanges)
{
	if (GetVisibility() != EVisibility::Hidden)
	{
		SetVisibility(EVisibility::Hidden);

		bIgnoreExistingCaptureRegion = false;

		if (!bKeepChanges)
		{
			GetHighResScreenshotConfig().UnscaledCaptureRegion = OriginalCaptureRegion;
		}
	}
}

void SCaptureRegionWidget::Reset()
{
	bIgnoreExistingCaptureRegion = true;
}

FReply SCaptureRegionWidget::OnMouseButtonDown( const FGeometry& MyGeometry, const FPointerEvent& MouseEvent )
{
	if (IsEnabled() && MouseEvent.GetEffectingButton() == EKeys::LeftMouseButton)
	{
		FVector2D ViewportPosition = MouseEvent.GetScreenSpacePosition() - MyGeometry.AbsolutePosition;
		FIntRect& CurrentCaptureRegion = GetHighResScreenshotConfig().UnscaledCaptureRegion;

		switch (PotentialInteraction)
		{
		case PI_DrawNewCaptureRegion:
			{
				DragStartPosition = MouseEvent.GetScreenSpacePosition() - MyGeometry.AbsolutePosition;
				BuildNewCaptureRegion(DragStartPosition, DragStartPosition);
				CurrentState = State_Dragging;
				break;
			}
		case PI_ResizeBL:
			{
				DragStartPosition = FVector2D(CurrentCaptureRegion.Max.X, CurrentCaptureRegion.Min.Y);
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				CurrentState = State_Dragging;
				break;
			}

		case PI_ResizeTL:
			{
				DragStartPosition = FVector2D(CurrentCaptureRegion.Max.X, CurrentCaptureRegion.Max.Y);
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				CurrentState = State_Dragging;
				break;
			}
		case PI_ResizeBR:
			{
				DragStartPosition = FVector2D(CurrentCaptureRegion.Min.X, CurrentCaptureRegion.Min.Y);
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				CurrentState = State_Dragging;
				break;
			}

		case PI_ResizeTR:
			{
				DragStartPosition = FVector2D(CurrentCaptureRegion.Min.X, CurrentCaptureRegion.Max.Y);
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				CurrentState = State_Dragging;
				break;
			}

		case PI_ResizeBottom:
			{
				DragStartPosition = FVector2D(CurrentCaptureRegion.Min.X, CurrentCaptureRegion.Min.Y);
				CurrentState = State_YAxisResize;
				break;
			}

		case PI_ResizeTop:
			{
				DragStartPosition = FVector2D(CurrentCaptureRegion.Min.X, CurrentCaptureRegion.Max.Y);
				CurrentState = State_YAxisResize;
				break;
			}

		case PI_ResizeLeft:
			{
				DragStartPosition = FVector2D(CurrentCaptureRegion.Max.X, CurrentCaptureRegion.Min.Y);
				CurrentState = State_XAxisResize;
				break;
			}

		case PI_ResizeRight:
			{
				DragStartPosition = FVector2D(CurrentCaptureRegion.Min.X, CurrentCaptureRegion.Min.Y);
				CurrentState = State_XAxisResize;
				break;
			}

		case PI_MoveExistingRegion:
			{
				DragStartPosition = ViewportPosition;
				CurrentState = State_Moving;
				break;
			}
		}

		return FReply::Handled();
	}
	else
	{
		return FReply::Unhandled();
	}
}

FReply SCaptureRegionWidget::OnMouseButtonUp( const FGeometry& MyGeometry, const FPointerEvent& MouseEvent )
{
	if (IsEnabled() && MouseEvent.GetEffectingButton() == EKeys::LeftMouseButton)
	{
		FVector2D ViewportPosition = MouseEvent.GetScreenSpacePosition() - MyGeometry.AbsolutePosition;
		FIntRect& CurrentCaptureRegion = GetHighResScreenshotConfig().UnscaledCaptureRegion;

		switch (CurrentState)
		{
		case State_Dragging:
			{
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				CurrentState = State_Inactive;
				bIgnoreExistingCaptureRegion = false;
				break;
			}

		case State_XAxisResize:
			{
				ViewportPosition.Y = CurrentCaptureRegion.Max.Y;
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				CurrentState = State_Inactive;
				break;
			}

		case State_YAxisResize:
			{
				ViewportPosition.X = CurrentCaptureRegion.Max.X;
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				CurrentState = State_Inactive;
				break;
			}

		case State_Moving:
			{
				CurrentState = State_Inactive;
				//OnCaptureRegionChanged.ExecuteIfBound(CurrentCaptureRegion);
				SendUpdatedCaptureRegion();
				break;
			}

		case State_Inactive:
			{
				break;
			}

		default:
			{
				check(false);
				break;
			}
		}

		return FReply::Handled();
	}
	else
	{
		return FReply::Unhandled();
	}
}

FReply SCaptureRegionWidget::OnMouseMove( const FGeometry& MyGeometry, const FPointerEvent& MouseEvent )
{
	if (IsEnabled())
	{
		FVector2D ViewportPosition = MouseEvent.GetScreenSpacePosition() - MyGeometry.AbsolutePosition;
		FIntRect& CurrentCaptureRegion = GetHighResScreenshotConfig().UnscaledCaptureRegion;

		switch (CurrentState)
		{
		case State_Dragging:
			{
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				break;
			}

		case State_Moving:
			{
				FVector2D Delta = ViewportPosition - DragStartPosition;
				DragStartPosition = ViewportPosition;
				CurrentCaptureRegion += FIntPoint((int32)Delta.X, (int32)Delta.Y);
				//OnCaptureRegionChanged.ExecuteIfBound(CurrentCaptureRegion);
				SendUpdatedCaptureRegion();
				break;
			}

		case State_XAxisResize:
			{
				ViewportPosition.Y = CurrentCaptureRegion.Max.Y;
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				break;
			}

		case State_YAxisResize:
			{
				ViewportPosition.X = CurrentCaptureRegion.Max.X;
				BuildNewCaptureRegion(ViewportPosition, DragStartPosition);
				break;
			}

		case State_Inactive:
			{
				if (CurrentCaptureRegion.Area() > 0 && !bIgnoreExistingCaptureRegion)
				{
					// Common tests
					bool bWithinXRangeOfExistingRegion = ViewportPosition.X >= CurrentCaptureRegion.Min.X && ViewportPosition.X <= CurrentCaptureRegion.Max.X;
					bool bWithinYRangeOfExistingRegion = ViewportPosition.Y >= CurrentCaptureRegion.Min.Y && ViewportPosition.Y <= CurrentCaptureRegion.Max.Y;

					// Distance away from an edge which we consider intersecting
					const float EdgeDistance = 5;

					// Check if we're over the corners
					if ((ViewportPosition - FVector2D((float)CurrentCaptureRegion.Min.X, CurrentCaptureRegion.Min.Y)).Size() < EdgeDistance)
					{
						this->Cursor = EMouseCursor::ResizeSouthEast;
						PotentialInteraction = PI_ResizeTL;
					}
					else if ((ViewportPosition - FVector2D((float)CurrentCaptureRegion.Min.X, CurrentCaptureRegion.Max.Y)).Size() < EdgeDistance)
					{
						this->Cursor = EMouseCursor::ResizeSouthWest;
						PotentialInteraction = PI_ResizeBL;
					}
					else if ((ViewportPosition - FVector2D((float)CurrentCaptureRegion.Max.X, CurrentCaptureRegion.Min.Y)).Size() < EdgeDistance)
					{
						this->Cursor = EMouseCursor::ResizeSouthWest;
						PotentialInteraction = PI_ResizeTR;
					}
					else if ((ViewportPosition - FVector2D((float)CurrentCaptureRegion.Max.X, CurrentCaptureRegion.Max.Y)).Size() < EdgeDistance)
					{
						this->Cursor = EMouseCursor::ResizeSouthEast;
						PotentialInteraction = PI_ResizeBR;
					}
					else if (FMath::Abs((float)CurrentCaptureRegion.Min.X - ViewportPosition.X) < EdgeDistance && bWithinYRangeOfExistingRegion)
					{
						this->Cursor = EMouseCursor::ResizeLeftRight;
						PotentialInteraction = PI_ResizeLeft;
					}
					else if (FMath::Abs((float)CurrentCaptureRegion.Max.X - ViewportPosition.X) < EdgeDistance && bWithinYRangeOfExistingRegion)
					{
						this->Cursor = EMouseCursor::ResizeLeftRight;
						PotentialInteraction = PI_ResizeRight;
					}
					else if (FMath::Abs((float)CurrentCaptureRegion.Min.Y - ViewportPosition.Y) < EdgeDistance && bWithinXRangeOfExistingRegion)
					{
						this->Cursor = EMouseCursor::ResizeUpDown;
						PotentialInteraction = PI_ResizeTop;
					}
					else if (FMath::Abs((float)CurrentCaptureRegion.Max.Y - ViewportPosition.Y) < EdgeDistance && bWithinXRangeOfExistingRegion)
					{
						this->Cursor = EMouseCursor::ResizeUpDown;
						PotentialInteraction = PI_ResizeBottom;
					}
					else if (CurrentCaptureRegion.Contains(FIntPoint((int32)ViewportPosition.X, (int32)ViewportPosition.Y)))
					{
						this->Cursor = EMouseCursor::CardinalCross;
						PotentialInteraction = PI_MoveExistingRegion;
					}
					else
					{
						this->Cursor = EMouseCursor::Crosshairs;
						PotentialInteraction = PI_DrawNewCaptureRegion;
					}
				}
				else
				{
					this->Cursor = EMouseCursor::Crosshairs;
					PotentialInteraction = PI_DrawNewCaptureRegion;
				}

				break;
			}

		default:
			{
				check(false);
				break;
			}
		}

		return FReply::Handled();
	}
	else
	{
		return FReply::Unhandled();
	}
}

void SCaptureRegionWidget::BuildNewCaptureRegion(const FVector2D& InPointA, const FVector2D& InPointB)
{
	FIntRect& CurrentCaptureRegion = GetHighResScreenshotConfig().UnscaledCaptureRegion;
	CurrentCaptureRegion.Min = FIntPoint(FMath::Min((int32)InPointA.X, (int32)InPointB.X), FMath::Min((int32)InPointA.Y, (int32)InPointB.Y));
	CurrentCaptureRegion.Max = FIntPoint(FMath::Max((int32)InPointA.X, (int32)InPointB.X), FMath::Max((int32)InPointA.Y, (int32)InPointB.Y));
	//OnCaptureRegionChanged.ExecuteIfBound(CurrentCaptureRegion);
	SendUpdatedCaptureRegion();
}

void SCaptureRegionWidget::SendUpdatedCaptureRegion()
{
	auto& Config = GetHighResScreenshotConfig();
	auto ConfigViewport = Config.TargetViewport.Pin();
	if (ConfigViewport.IsValid())
	{
		ConfigViewport->Invalidate();
	}
}


text:
A simple MySQLi polyfill.
It is not feature-complete at the moment, but features (and unit tests) will be added as requested/needed.


text:
This Dockerfile is based on Alpine Linux 3.5 and Node 6.9. It builds pump.io from the Git repository.

## Building

The image should build without any further options. The compilation error from node-gyp during the `npm install` can be ignored, as they only affect optional dependencies.

```
docker build --tag pumpio:latest .
```

The Dockerfile also allows to define the UID and GUID of the `pumpio` user which runs pump.io via build arguments.

```
docker build --tag pumpio:latest --build-arg PUMPIO__GUID=1337 --build-arg PUMPIO__UID=1337 .
```

You can also use `docker-compose` to build the image: `docker-compose build`

## Running

By default this Dockerfile only includes the `databank-mongodb` driver. Therefore you will have to add the configuration parameters for MongoDB. The recommended way to configure pump.io is to configure the options via environment variables, as described in the project's README. You can see some example variables in the `docker-compose.yml` file. This file will also show a basic working version which you can expand on.

Running via `docker-compose`:

```
docker-compose up -d
```

Stopping and removing:

```
docker-compose down -v
```

Notice the `-v` parameter, as the docker-compose file defines volumes. Without this parameter they will be left behind.

If you have Docker Swarm active, you can also deploy this as a Service Stack:

```
docker stack deploy --compose-file docker-compose.yml pumpio
```