text:
package com.linkedin.drelephant.spark.fetchers

import java.net.URI
import java.text.SimpleDateFormat
import java.util.{Calendar, Date, SimpleTimeZone}

import scala.concurrent.ExecutionContext
import scala.util.Try

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.linkedin.drelephant.spark.fetchers.statusapiv1.{ApplicationAttemptInfo, ApplicationInfo, ExecutorSummary, JobData, StageData}
import javax.ws.rs.{GET, Path, PathParam, Produces}
import javax.ws.rs.client.WebTarget
import javax.ws.rs.core.{Application, MediaType}
import javax.ws.rs.ext.ContextResolver
import org.apache.spark.SparkConf
import org.glassfish.jersey.client.ClientConfig
import org.glassfish.jersey.server.ResourceConfig
import org.glassfish.jersey.test.{JerseyTest, TestProperties}
import org.scalatest.{AsyncFunSpec, Matchers}
import org.scalatest.compatible.Assertion

class SparkRestClientTest extends AsyncFunSpec with Matchers {
  import SparkRestClientTest._

  /**

  describe("SparkRestClient") {
    /**
    it("throws an exception if spark.eventLog.dir is missing") {
      an[IllegalArgumentException] should be thrownBy(new SparkRestClient(new SparkConf()))
    }
      **/

    it("returns the desired data from the Spark REST API for cluster mode application") {
      import ExecutionContext.Implicits.global
      val fakeJerseyServer = new FakeJerseyServer() {
        override def configure(): Application = super.configure() match {
          case resourceConfig: ResourceConfig =>
            resourceConfig
              .register(classOf[FetchClusterModeDataFixtures.ApiResource])
              .register(classOf[FetchClusterModeDataFixtures.ApplicationResource])
              .register(classOf[FetchClusterModeDataFixtures.JobsResource])
              .register(classOf[FetchClusterModeDataFixtures.StagesResource])
              .register(classOf[FetchClusterModeDataFixtures.ExecutorsResource])
          case config => config
        }
      }

      fakeJerseyServer.setUp()

      val historyServerUri = fakeJerseyServer.target.getUri

      val sparkConf = new SparkConf().set("spark.yarn.historyServer.address", s"${historyServerUri.getHost}:${historyServerUri.getPort}")
      val sparkRestClient = new SparkRestClient(sparkConf)

      /**
        *sparkRestClient.fetchData(FetchClusterModeDataFixtures.APP_ID) map { restDerivedData =>
        *restDerivedData.applicationInfo.id should be(FetchClusterModeDataFixtures.APP_ID)
        *restDerivedData.applicationInfo.name should be(FetchClusterModeDataFixtures.APP_NAME)
        *restDerivedData.jobDatas should not be(None)
        *restDerivedData.stageDatas should not be(None)
        *restDerivedData.executorSummaries should not be(None)
        * } andThen { case assertion: Try[Assertion] =>
        *fakeJerseyServer.tearDown()
        * assertion
        * }
        **/
    }

    it("returns the desired data from the Spark REST API for client mode application") {
      import ExecutionContext.Implicits.global
      val fakeJerseyServer = new FakeJerseyServer() {
        override def configure(): Application = super.configure() match {lack
          case resourceConfig: ResourceConfig =>
            resourceConfig
              .register(classOf[FetchClientModeDataFixtures.ApiResource])
              .register(classOf[FetchClientModeDataFixtures.ApplicationResource])
              .register(classOf[FetchClientModeDataFixtures.JobsResource])
              .register(classOf[FetchClientModeDataFixtures.StagesResource])
              .register(classOf[FetchClientModeDataFixtures.ExecutorsResource])
          case config => config
        }
      }

      fakeJerseyServer.setUp()

      val historyServerUri = fakeJerseyServer.target.getUri

      val sparkConf = new SparkConf().set("spark.yarn.historyServer.address", s"${historyServerUri.getHost}:${historyServerUri.getPort}")
      val sparkRestClient = new SparkRestClient(sparkConf)

      /**
        *sparkRestClient.fetchData(FetchClusterModeDataFixtures.APP_ID) map { restDerivedData =>
        *restDerivedData.applicationInfo.id should be(FetchClusterModeDataFixtures.APP_ID)
        *restDerivedData.applicationInfo.name should be(FetchClusterModeDataFixtures.APP_NAME)
        *restDerivedData.jobDatas should not be(None)
        *restDerivedData.stageDatas should not be(None)
        *restDerivedData.executorSummaries should not be(None
        * } andThen { case assertion: Try[Assertion] =>
        *fakeJerseyServer.tearDown()
        * assertion
        * }
        **/
    }
  }
  **/
}

object SparkRestClientTest {
  class FakeJerseyServer extends JerseyTest {
    override def configure(): Application = {
      forceSet(TestProperties.CONTAINER_PORT, "0")
      enable(TestProperties.LOG_TRAFFIC)
      enable(TestProperties.DUMP_ENTITY)

      new ResourceConfig()
        .register(classOf[FakeJerseyObjectMapperProvider])
    }

    override def configureClient(clientConfig: ClientConfig): Unit = {
      clientConfig.register(classOf[FakeJerseyObjectMapperProvider])
    }
  }

  class FakeJerseyObjectMapperProvider extends ContextResolver[ObjectMapper] {
    lazy val objectMapper = {
      val objectMapper = new ObjectMapper()
      objectMapper.registerModule(DefaultScalaModule)
      objectMapper.setDateFormat(dateFormat)
      objectMapper
    }

    lazy val dateFormat = {
      val iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'GMT'")
      val cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"))
      iso8601.setCalendar(cal)
      iso8601
    }

    override def getContext(cls: Class[_]): ObjectMapper = objectMapper
  }

  object FetchClusterModeDataFixtures {
    val APP_ID = "application_1"
    val APP_NAME = "app"

    @Path("/api/v1")
    class ApiResource {
      @Path("applications/{appId}")
      def getApplication(): ApplicationResource = new ApplicationResource()

      @Path("applications/{appId}/{attemptId}/jobs")
      def getJobs(): JobsResource = new JobsResource()

      @Path("applications/{appId}/{attemptId}/stages")
      def getStages(): StagesResource = new StagesResource()

      @Path("applications/{appId}/{attemptId}/executors")
      def getExecutors(): ExecutorsResource = new ExecutorsResource()
    }

    @Produces(Array(MediaType.APPLICATION_JSON))
    class ApplicationResource {
      @GET
      def getApplication(@PathParam("appId") appId: String): ApplicationInfo = {
        val t2 = System.currentTimeMillis
        val t1 = t2 - 1
        val duration = 8000000L
        new ApplicationInfo(
          APP_ID,
          APP_NAME,
          Seq(
            newFakeApplicationAttemptInfo(Some("2"), startTime = new Date(t2 - duration), endTime = new Date(t2)),
            newFakeApplicationAttemptInfo(Some("1"), startTime = new Date(t1 - duration), endTime = new Date(t1))
          )
        )
      }
    }

    @Produces(Array(MediaType.APPLICATION_JSON))
    class JobsResource {
      @GET
      def getJobs(@PathParam("appId") appId: String, @PathParam("attemptId") attemptId: String): Seq[JobData] =
        if (attemptId == "2") Seq.empty else throw new Exception()
    }

    @Produces(Array(MediaType.APPLICATION_JSON))
    class StagesResource {
      @GET
      def getStages(@PathParam("appId") appId: String, @PathParam("attemptId") attemptId: String): Seq[StageData] =
        if (attemptId == "2") Seq.empty else throw new Exception()
    }

    @Produces(Array(MediaType.APPLICATION_JSON))
    class ExecutorsResource {
      @GET
      def getExecutors(@PathParam("appId") appId: String, @PathParam("attemptId") attemptId: String): Seq[ExecutorSummary] =
        if (attemptId == "2") Seq.empty else throw new Exception()
    }
  }

  object FetchClientModeDataFixtures {
    val APP_ID = "application_1"
    val APP_NAME = "app"

    @Path("/api/v1")
    class ApiResource {
      @Path("applications/{appId}")
      def getApplication(): ApplicationResource = new ApplicationResource()

      @Path("applications/{appId}/jobs")
      def getJobs(): JobsResource = new JobsResource()

      @Path("applications/{appId}/stages")
      def getStages(): StagesResource = new StagesResource()

      @Path("applications/{appId}/executors")
      def getExecutors(): ExecutorsResource = new ExecutorsResource()
    }

    @Produces(Array(MediaType.APPLICATION_JSON))
    class ApplicationResource {
      @GET
      def getApplication(@PathParam("appId") appId: String): ApplicationInfo = {
        val t2 = System.currentTimeMillis
        val t1 = t2 - 1
        val duration = 8000000L
        new ApplicationInfo(
          APP_ID,
          APP_NAME,
          Seq(
            newFakeApplicationAttemptInfo(None, startTime = new Date(t2 - duration), endTime = new Date(t2)),
            newFakeApplicationAttemptInfo(None, startTime = new Date(t1 - duration), endTime = new Date(t1))
          )
        )
      }
    }

    @Produces(Array(MediaType.APPLICATION_JSON))
    class JobsResource {
      @GET
      def getJobs(@PathParam("appId") appId: String): Seq[JobData] =
        Seq.empty
    }

    @Produces(Array(MediaType.APPLICATION_JSON))
    class StagesResource {
      @GET
      def getStages(@PathParam("appId") appId: String): Seq[StageData] =
        Seq.empty
    }

    @Produces(Array(MediaType.APPLICATION_JSON))
    class ExecutorsResource {
      @GET
      def getExecutors(@PathParam("appId") appId: String): Seq[ExecutorSummary] =
        Seq.empty
    }
  }

  def newFakeApplicationAttemptInfo(
                                     attemptId: Option[String],
                                     startTime: Date,
                                     endTime: Date
                                   ): ApplicationAttemptInfo = new ApplicationAttemptInfo(
    attemptId,
    startTime,
    endTime,
    sparkUser = "foo",
    completed = true
  )
}


text:
var gTestfile = '10.1.4-1.js';

/**
   ECMA Section: 10.1.4.1 Entering An Execution Context
   ECMA says:
   * Global Code, Function Code
   Variable instantiation is performed using the global object as the
   variable object and using property attributes { DontDelete }.

   * Eval Code
   Variable instantiation is performed using the calling context's
   variable object and using empty property attributes.
*/

var BUGNUMBER = '(none)';
var summary = '10.1.4.1 Entering An Execution Context';
var actual = '';
var expect = '';

test();

function test()
{
  enterFunc ("test");
  printBugNumber(BUGNUMBER);
  printStatus (summary);

  var y;
  eval("var x = 1");

  if (delete y)
    reportCompare('PASS', 'FAIL', "Expected *NOT* to be able to delete y");

  if (typeof x == "undefined")
    reportCompare('PASS', 'FAIL', "x did not remain defined after eval()");
  else if (x != 1)
    reportCompare('PASS', 'FAIL', "x did not retain it's value after eval()");

  if (!delete x)
    reportCompare('PASS', 'FAIL', "Expected to be able to delete x");

  reportCompare('PASS', 'PASS', '10.1.4.1 Entering An Execution Context');

  exitFunc("test");
}

redpajama_set_name: RedPajamaGithub


text:
package be.italent.repository;

import be.italent.model.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

@Repository
@Component
public interface CategoryRepo extends JpaRepository<Category, Integer> {

}


text:
package alraune.back;

import static alraune.back.Al.span;
import static alraune.back.AlTag.oo;

@SuppressWarnings("unused")
class SpitDashboardPage implements SpitPage {
    @Override public void spit() {
        Al.spitUsualPage(AlRender.minimalMainContainer(() -> {
            oo(span("I am exciting dashboard page"));
        }));
    }
}


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>Round fractions up</title>

bindec

cos

Math Functions

PHP Manual

ceil

(PHP 4, PHP 5)

ceil — Round fractions up

Description

    float ceil
     ( float $value
    )

   Returns the next highest integer value by rounding up
   value if necessary.

Parameters

value

       The value to round

Return Values

   value rounded up to the next highest
   integer.
   The return value of ceil() is still of type
   float as the value range of float is
   usually bigger than that of integer.

Examples

Example #1 ceil() example

<?php
echo ceil(4.3);    // 5
echo ceil(9.999);  // 10
echo ceil(-3.14);  // -3
?>

See Also

floor() - Round fractions down

round() - Rounds a float

bindec

cos

Math Functions

PHP Manual


text:
import { every } from 'lodash';
import { Engine } from 'random-js';
import { stdOpts, CheckOptions } from './constants';
import { Arbitrary } from './arbitrary';
import { shrinkNoop } from './shrink';
import { take, join, Seq } from './seq';

/**
 *  A result of property test.
 */
export interface TestResult {
    // The result of test.
    ok: boolean,
    // The input samples.
    samples: any[]
    // the exception thrown, if any.
    theException: Error | null,
}

/**
 * Succeed Result.
 */
function succeed(samples: any[]): TestResult {
    return {
        ok: true,
        samples: samples,
        theException: null
    };
}

/**
 * Failed Result.
 */
function failed(samples: any[], error = null): TestResult {
    return {
        ok: false,
        samples: samples,
        theException: error
    }
}

/**
 * A predicate takes an entity or entities in the domain of discourse as input
 * and outputs either True or False.
 */
export type Predicate = Function;

/**
 * A property is a promise like Generator, but generate a
 * test result.
 */
export type Property = (engine: Engine, locale: string) => Promise<TestResult>;

/**
 * Apply a predicate to an given samples.
 */
export async function apply(predicate: Function, samples: any[]): Promise<TestResult> {
    return new Promise<TestResult>((resolve, reject) => {
        try {
            const r = predicate.apply(null, samples);
            resolve(r ? succeed(samples) : failed(samples));
        } catch (error) {
            resolve(failed(samples, error));
        }
    });
}

export async function shrink(predicate: Function, failure: TestResult, shrunkens: Seq<any[]>): Promise<TestResult> {
    return new Promise<TestResult>(async (resolve, reject) => {
        let samples = take(shrunkens, 1);
        if (samples.length === 0) return resolve(failure);
        let r = await apply(predicate, samples[0]);
        if (r.ok) return resolve(failure);
        return resolve(await shrink(predicate, r, shrunkens));
    });
}

/**
 * Check Result.
 */
export interface CheckResult {
    ok: boolean,
    tests: number,
    pass: number,
    samples: any[] | null,
    theException: Error | null,
    seed: number
}

/**
 * Check the property.
 */
export async function check(property: Property, opts: CheckOptions) {
    const result = await safeCheck(property, opts);
    return opts.format ? formatCheckResult(result) : result;
}

export async function safeCheck(property: Property, opts: CheckOptions) {
    opts.engine.seed(opts.seed);
    // Run a property to catch an exception as
    // easier as possible.
    const safe = await property(opts.engine, opts.locale);
    return safe.ok ? await checkWith(property, opts) : {
        ok: false,
        tests: 1,
        pass: 0,
        samples: safe.samples,
        theException: safe.theException,
        seed: opts.seed
    };
}

export async function checkWith(property: Property,  opts: CheckOptions) {
    const tests = [];
    for (let i = 0; i < opts.tests; i++) {
        tests.push(property(opts.engine, opts.locale));
    }
    const results = await Promise.all(tests);
    const total = results.length;
    let pass = 0;
    for(let i = 0; i < total; i++) {
        if (results[i].ok) {
            pass += 1
        }
    }
    let samples = null;
    if (total !== pass) {
        const r = results.find(r => !r.ok);
        if (!!r) {
            samples = r.samples;
        }
    }
    return {
        ok: total === pass,
        tests: total,
        pass: pass,
        samples: samples,
        theException: null,
        seed: opts.seed
    };
}

/**
 * Format the results.
 */
export function formatCheckResult(result: CheckResult): string {
    const msg = [];
    msg.push(result.ok ? '+ Ok' : '+ Fail');
    msg.push(', ');
    msg.push(`pass ${result.pass} tests`);
    msg.push(', ');
    msg.push(`seed: ${result.seed}`);
    msg.push(`, `);
    msg.push(`samples: ${result.samples}`);
    msg.push('\n');
    if (result.theException) {
        msg.push(result.theException.stack);
    }
    return msg.join('');
}

/**
 * Create a property.
 */
export function property(
    predicate: Predicate,
    ...quantifiers: Arbitrary<any, any>[]) {
        return new ForAll(quantifiers).predicate(predicate).makeProperty();
};

/**
 * Constructor a ForAll.
 */
export function forAll(...arbs: Arbitrary<any, any>[]) {
    return new ForAll(arbs);
};

/**
 * The thing which can be tested,
 */
export class ForAll {
    _predicate: Predicate;
    quantifiers: Arbitrary<any, any>[];
    /**
     * Make a Prop.
     */
    constructor(quantifiers: Arbitrary<any, any>[]) {
        this.quantifiers = quantifiers;
    }
    /**
     * Set predicate.
     */
    predicate(pf: Predicate) {
        if (pf.length !== this.quantifiers.length) {
            throw new Error('quantifiers parameter do not match signature of predicate');
        }
        this._predicate = pf;
        return this;
    }
    /**
     * Generate sample values.
     */
    makeSamples(engine: Engine, locale: string): any[] {
        const samples = this.quantifiers.map(
            q => q.makeGenerator()(engine, locale)
        );
        return samples;
    }
    makeShrunkens(seeds: any[], locale: string): Seq<any[]> {
        const shrinkers = this.quantifiers.map(
            q => q.shrinker || shrinkNoop
        );
        const seqs = seeds.map((v, i) => shrinkers[i](v));
        return join(seqs);
    }
    /**
     * Convert the thing to a property.
     */
    makeProperty(): Property {
        return async (engine, locale) => {
            const r = <TestResult>await apply(this._predicate, this.makeSamples(engine, locale));
            if (r.ok) {
                return r;
            } else {
                return await shrink(this._predicate, r, this.makeShrunkens(r.samples, locale));
            }
        };
    }
    /**
     * Evaluate the function with quantifiers.
     */
    eval(f: Function, opts = stdOpts) {
        return f.apply(null, this.makeSamples(opts.engine, opts.locale));
    }
    /**
     * Check this property.
     */
    check(opts = stdOpts) {
        check(this.makeProperty(), opts).then(console.log).catch(console.error);
    }
}


text:
namespace A2D {

    ////////////////////////////////////////////////////////////////////////////////
    // FORWARD DECLARATIONS
    ////////////////////////////////////////////////////////////////////////////////

    class AbstractFrame;
    class Abstract;
    class Graphics;
    class Component;
    struct ImageProperties;
    class ComponentManager;
	class Easing;

	// Typedef animation
	typedef void** Animation;

    ////////////////////////////////////////////////////////////////////////////////
    // DECLARATION
    ////////////////////////////////////////////////////////////////////////////////

    class Component : public ComponentEventSource
    {
        friend class ComponentManager;
        friend class CascadingLayout;
		friend class AbstractEventQueue;
		friend class Animator;

    public:

        Component();
        ~Component();

	private:

		bool                        m_forcedBounds;
        bool                        m_focused;
        bool                        m_focusable;

		int							m_depth;

        AbstractFrame*              m_frame;
        Component*                  m_parent;
		OrderedList<Component*>     m_children;

		OrderedList<A2DINTERPOLATORFLOAT*>  m_interpolators;

        ComponentManager*           m_componentManager;
		AbstractEventQueue*			m_eventQueue;

		Component*                  m_nextCompListener;
        Component*                  m_prevCompListener;

		A2DCACHEDANIMATION2			m_cachedAnimationPositionXY;
		Animation					m_positionAnimationXY;

    protected:

		int							m_id;

		int							m_calculatedRowIndex;
		int							m_calculatedColumnIndex;

		int							m_previousCalculatedRowIndex;
		int							m_previousCalculatedColumnIndex;

		bool                        m_validatedContents;
		bool						m_activeInterpolations;
		bool						m_componentTreeValidationRequest;

		bool						m_scrolling;
		float						m_scrollTop;
		float						m_scrollLeft;

		A2DCOMPONENTRENDERSTYLESET	m_styleSet;

		Rect                        m_region;
		A2DFLOAT4					m_subRegion;
		A2DFLOAT4					m_subBordersRegion;
		Rect						m_backgroundRegion;
        Rect                        m_calculatedRegion;
        Rect                        m_visibleRegion;
		Dims						m_previousVisibleDimensions;
		Dims						m_previousDimensions;

		Pipeline*                   m_pipeline;
		Graphics*                   m_graphics;

    public:

		void						captureScroll();
		void						releaseScroll();

		void						setId(int x_id);
        void                        setDoubleBuffered(bool xDoubleBuffer);
		void                        setBackgroundImage(wchar_t * x_src);
		void                        setBackgroundPaint(Paint& xOptPaint);
        void                        setPosition(Style::Position xPosition);
        void                        setDisplay(Style::Display xDisplay);
        void                        setFloat(Style::Float xFloat);
        void                        setSize(Style::Units xWidthUnits, float xWidth, Style::Units xHeightUnits, float xHeight);
        void                        setMargins(Style::Units xLeftUnits, float xLeft, Style::Units xTopUnits, float xTop, Style::Units xRightUnits, float xRight, Style::Units xBottomUnits, float xBottom);
        void                        setPositioning(Style::Units xLeftUnits, float xLeft, Style::Units xTopUnits, float xTop, Style::Units xRightUnits, float xRight, Style::Units xBottomUnits, float xBottom);
		void                        setPadding(Style::Units xLeftUnits, float xLeft, Style::Units xTopUnits, float xTop, Style::Units xRightUnits, float xRight, Style::Units xBottomUnits, float xBottom);
		void                        setBorderWidths(Style::Units xLeftUnits, float xLeft, Style::Units xTopUnits, float xTop, Style::Units xRightUnits, float xRight, Style::Units xBottomUnits, float xBottom);
		void                        setBorderRadii(Style::Units xLeftUnits, float xLeft, Style::Units xTopUnits, float xTop, Style::Units xRightUnits, float xRight, Style::Units xBottomUnits, float xBottom);
		void						setBorderColor(unsigned int xLeft, unsigned int xTop, unsigned int xRight, unsigned int xBottom);
        void                        setFocusable(bool xFocusable);

		void						setWidthUnits(Style::Units x_units);
		void						setWidth(float x_width);
		inline float				getWidth() { return m_styleSet.m_size.m_width; }

		void						setHeightUnits(Style::Units x_units);
		void						setHeight(float x_height);
		inline float				getHeight() { return m_styleSet.m_size.m_height; }

		void						setBorderRadiiTopLeftUnits(Style::Units x_units);
		void						setBorderRadiiTopLeft(float x_value);
		inline float				getBorderRadiiTopLeft() { return m_styleSet.m_borderRadii.m_left; }

		void						setOpacity(float x_opacity);
		inline float				getOpacity() { return m_styleSet.m_opacity; }

		void						setBorderRadiiUnified(float x_value);
		inline float				getBorderRadiiUnified() { return m_styleSet.m_borderRadii.m_left; }

		float						getBoundsY();
		void 						setBoundsY(float x_y);

		float						getBoundsX();
		void						setBoundsX(float x_x);

		void						setBoundsXY(float x_x, float x_y);

		void						setScroll(float x_left, float x_top);
		void						setScrollTop(float x_top);
		inline float				getScrollLeft() { return m_scrollLeft; };
		inline float				getScrollTop() { return m_scrollTop; };

        STATUS                      requestFocus();
        STATUS                      addMouseListener(MouseListener * xListener);
        STATUS                      addMouseMotionListener(MouseMotionListener * xListener);
        STATUS                      addFocusListener(FocusListener * xListener);
        STATUS                      addActionListener(ActionListener * xListener);

        void                        update();

        void                        revalidate();
        void                        validated();
        void                        invalidate();
        void                        add(Component& xComponent);
        void                        remove(Component& xComponent);
        void                        forceBounds(bool xForce);
        STATUS						initialize();

		int							getDepth();
        Graphics&                   getGraphics();
        Component&                  getParent();
        Component&                  getRoot();
        AbstractFrame&              getFrame();
        Rect*                       getVisibleRegion();
        Rect*                       getBoundsAsPtr();
        Rect                        getBounds();
		wchar_t*                    getBackgroundImage();
		Paint&                      getBackgroundPaint();

        bool                        isDoubleBuffered();

	private:

		void						interpolate();
		void                        validate();

		void						setEventQueue(AbstractEventQueue& x_eventQueue);
		void                        setDepth(int xDepth);
		void                        setGraphics(Graphics& xGraphics);
		void                        setParent(Component& xComponent);
		void                        setFrame(AbstractFrame& xFrame);
		void						setComponentManager(ComponentManager& x_componentManager);

    protected:

        virtual void                paintComponent();
        virtual void                paintComponentBorder();
        virtual Rect*               getEventRegion();

		void						setBounds(float xX, float xY, float xWidth, float xHeight);

    };
}
#endif


text:
"""Interface for the program NACCESS.

See: http://wolf.bms.umist.ac.uk/naccess/

errors likely to occur with the binary:
default values are often due to low default settings in accall.pars
- e.g. max cubes error: change in accall.pars and recompile binary

use naccess -y, naccess -h or naccess -w to include HETATM records
"""

from __future__ import print_function

import os
import tempfile
import shutil
import subprocess
import warnings
from Bio.PDB.PDBIO import PDBIO
from Bio.PDB.AbstractPropertyMap import AbstractResiduePropertyMap, AbstractAtomPropertyMap

def run_naccess(model, pdb_file, probe_size=None, z_slice=None,
                naccess='naccess', temp_path='/tmp/'):

    # make temp directory;
    tmp_path = tempfile.mkdtemp(dir=temp_path)

    # file name must end with '.pdb' to work with NACCESS
    # -> create temp file of existing pdb
    #    or write model to temp file
    handle, tmp_pdb_file = tempfile.mkstemp('.pdb', dir=tmp_path)
    os.close(handle)
    if pdb_file:
        pdb_file = os.path.abspath(pdb_file)
        shutil.copy(pdb_file, tmp_pdb_file)
    else:
        writer = PDBIO()
        writer.set_structure(model.get_parent())
        writer.save(tmp_pdb_file)

    # chdir to temp directory, as NACCESS writes to current working directory
    old_dir = os.getcwd()
    os.chdir(tmp_path)

    # create the command line and run
    # catch standard out & err
    command = [naccess, tmp_pdb_file]
    if probe_size:
        command.extend(['-p', probe_size])
    if z_slice:
        command.extend(['-z', z_slice])

    p = subprocess.Popen(command, universal_newlines=True,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    os.chdir(old_dir)

    rsa_file = tmp_pdb_file[:-4] + '.rsa'
    asa_file = tmp_pdb_file[:-4] + '.asa'
    # Alert user for errors
    if err.strip():
        warnings.warn(err)

    if (not os.path.exists(rsa_file)) or (not os.path.exists(asa_file)):
        raise Exception('NACCESS did not execute or finish properly.')

    # get the output, then delete the temp directory
    with open(rsa_file) as rf:
        rsa_data = rf.readlines()
    with open(asa_file) as af:
        asa_data = af.readlines()

    # shutil.rmtree(tmp_path, ignore_errors=True)
    return rsa_data, asa_data

def process_rsa_data(rsa_data):
    # process the .rsa output file: residue level SASA data
    naccess_rel_dict = {}
    for line in rsa_data:
        if line.startswith('RES'):
            res_name = line[4:7]
            chain_id = line[8]
            resseq = int(line[9:13])
            icode = line[13]
            res_id = (' ', resseq, icode)
            naccess_rel_dict[(chain_id, res_id)] = {
                'res_name': res_name,
                'all_atoms_abs': float(line[16:22]),
                'all_atoms_rel': float(line[23:28]),
                'side_chain_abs': float(line[29:35]),
                'side_chain_rel': float(line[36:41]),
                'main_chain_abs': float(line[42:48]),
                'main_chain_rel': float(line[49:54]),
                'non_polar_abs': float(line[55:61]),
                'non_polar_rel': float(line[62:67]),
                'all_polar_abs': float(line[68:74]),
                'all_polar_rel': float(line[75:80])}
    return naccess_rel_dict

def process_asa_data(rsa_data):
    # process the .asa output file: atomic level SASA data
    naccess_atom_dict = {}
    for line in rsa_data:
        full_atom_id = line[12:16]
        atom_id = full_atom_id.strip()
        chainid = line[21]
        resseq = int(line[22:26])
        icode = line[26]
        res_id = (' ', resseq, icode)
        id = (chainid, res_id, atom_id)
        asa = line[54:62]               # solvent accessibility in Angstrom^2
        naccess_atom_dict[id] = asa
    return naccess_atom_dict

class NACCESS(AbstractResiduePropertyMap):

    def __init__(self, model, pdb_file=None,
                 naccess_binary='naccess', tmp_directory='/tmp'):
        res_data, atm_data = run_naccess(model, pdb_file,
                                         naccess=naccess_binary,
                                         temp_path=tmp_directory)
        naccess_dict = process_rsa_data(res_data)
        property_dict = {}
        property_keys = []
        property_list = []
        # Now create a dictionary that maps Residue objects to accessibility
        for chain in model:
            chain_id = chain.get_id()
            for res in chain:
                res_id = res.get_id()
                if (chain_id, res_id) in naccess_dict:
                    item = naccess_dict[(chain_id, res_id)]
                    res_name = item['res_name']
                    assert (res_name == res.get_resname())
                    property_dict[(chain_id, res_id)] = item
                    property_keys.append((chain_id, res_id))
                    property_list.append((res, item))
                    res.xtra["EXP_NACCESS"] = item
                else:
                    pass
        AbstractResiduePropertyMap.__init__(self, property_dict, property_keys,
                                            property_list)

class NACCESS_atomic(AbstractAtomPropertyMap):

    def __init__(self, model, pdb_file=None,
                 naccess_binary='naccess', tmp_directory='/tmp'):
        res_data, atm_data = run_naccess(model, pdb_file,
                                         naccess=naccess_binary,
                                         temp_path=tmp_directory)
        self.naccess_atom_dict = process_asa_data(atm_data)
        property_dict = {}
        property_keys = []
        property_list = []
        # Now create a dictionary that maps Atom objects to accessibility
        for chain in model:
            chain_id = chain.get_id()
            for residue in chain:
                res_id = residue.get_id()
                for atom in residue:
                    atom_id = atom.get_id()
                    full_id = (chain_id, res_id, atom_id)
                    if full_id in self.naccess_atom_dict:
                        asa = self.naccess_atom_dict[full_id]
                        property_dict[full_id] = asa
                        property_keys.append((full_id))
                        property_list.append((atom, asa))
                        atom.xtra['EXP_NACCESS'] = asa
        AbstractAtomPropertyMap.__init__(self, property_dict,
                                         property_keys, property_list)

if __name__ == "__main__":
    import sys
    from Bio.PDB import PDBParser

    p = PDBParser()
    s = p.get_structure('X', sys.argv[1])
    model = s[0]

    n = NACCESS(model, sys.argv[1])
    for e in n:
        print(e)


text:
<?php

namespace MicrosoftAzure\Storage\Common\Models;

use MicrosoftAzure\Storage\Common\Internal\Utilities;

/**
 * Holds elements of queue properties logging field.
 *
 * @category  Microsoft
 * @package   MicrosoftAzure\Storage\Common\Models
 * @author    Azure Storage PHP SDK <dmsh@microsoft.com>
 * @copyright 2016 Microsoft Corporation
 * @license   https://github.com/azure/azure-storage-php/LICENSE
 * @link      https://github.com/azure/azure-storage-php
 */
class Logging
{
    private $_version;
    private $_delete;
    private $_read;
    private $_write;
    private $_retentionPolicy;

    /**
     * Creates object from $parsedResponse.
     *
     * @internal
     * @param array $parsedResponse XML response parsed into array.
     *
     * @return Logging
     */
    public static function create(array $parsedResponse)
    {
        $result = new Logging();
        $result->setVersion($parsedResponse['Version']);
        $result->setDelete(Utilities::toBoolean($parsedResponse['Delete']));
        $result->setRead(Utilities::toBoolean($parsedResponse['Read']));
        $result->setWrite(Utilities::toBoolean($parsedResponse['Write']));
        $result->setRetentionPolicy(
            RetentionPolicy::create($parsedResponse['RetentionPolicy'])
        );

        return $result;
    }

    /**
     * Gets the retention policy
     *
     * @return MicrosoftAzure\Storage\Common\Models\RetentionPolicy
     *
     */
    public function getRetentionPolicy()
    {
        return $this->_retentionPolicy;
    }

    /**
     * Sets retention policy
     *
     * @param RetentionPolicy $policy object to use
     *
     * @return void
     */
    public function setRetentionPolicy(RetentionPolicy $policy)
    {
        $this->_retentionPolicy = $policy;
    }

    /**
     * Gets whether all write requests should be logged.
     *
     * @return bool.
     */
    public function getWrite()
    {
        return $this->_write;
    }

    /**
     * Sets whether all write requests should be logged.
     *
     * @param bool $write new value.
     *
     * @return void
     */
    public function setWrite($write)
    {
        $this->_write = $write;
    }

    /**
     * Gets whether all read requests should be logged.
     *
     * @return bool
     */
    public function getRead()
    {
        return $this->_read;
    }

    /**
     * Sets whether all read requests should be logged.
     *
     * @param bool $read new value.
     *
     * @return void
     */
    public function setRead($read)
    {
        $this->_read = $read;
    }

    /**
     * Gets whether all delete requests should be logged.
     *
     * @return void
     */
    public function getDelete()
    {
        return $this->_delete;
    }

    /**
     * Sets whether all delete requests should be logged.
     *
     * @param bool $delete new value.
     *
     * @return void
     */
    public function setDelete($delete)
    {
        $this->_delete = $delete;
    }

    /**
     * Gets the version of Storage Analytics to configure
     *
     * @return string
     */
    public function getVersion()
    {
        return $this->_version;
    }

    /**
     * Sets the version of Storage Analytics to configure
     *
     * @param string $version new value.
     *
     * @return void
     */
    public function setVersion($version)
    {
        $this->_version = $version;
    }

    /**
     * Converts this object to array with XML tags
     *
     * @internal
     * @return array
     */
    public function toArray()
    {
        return array(
            'Version'         => $this->_version,
            'Delete'          => Utilities::booleanToString($this->_delete),
            'Read'            => Utilities::booleanToString($this->_read),
            'Write'           => Utilities::booleanToString($this->_write),
            'RetentionPolicy' => !empty($this->_retentionPolicy)
                ? $this->_retentionPolicy->toArray()
                : null
        );
    }
}


text:
from datetime import datetime
from django import template
from django.utils import formats
from photologue import models

register = template.Library()

def get_exif_data(photo, attr):
    value = photo.EXIF.get(attr)
    if value is None:
        return
    if attr == 'EXIF DateTimeOriginal':
        dt = datetime.strptime(str(value), '%Y:%m:%d %H:%M:%S')
        value = formats.date_format(dt, 'DATETIME_FORMAT', True)
    elif attr == 'EXIF DateOriginal':
        value = photo.EXIF.get('EXIF DateTimeOriginal')
        if value is None:
            return
        dt = datetime.strptime(str(value), '%Y:%m:%d %H:%M:%S')
        value = formats.date_format(dt, 'DATE_FORMAT', True)
    elif attr == 'EXIF ApertureValue':
        f = value.split('/')
        if len(f) == 1:
            try:
                aperture = float(f[0])
            except ValueError:
                return '-'
        else:
            aperture = float(f[0]) / float(f[1])
        value = 'f/%.1f' % aperture
    return value

@register.inclusion_tag('cmsplugin_photologue_pro/polaroid.html')
def polaroid_thumbnail(photo, photosize=None, counter=''):
    if not photosize:
        photosize = models.PhotoSize.objects.get(name='thumbnail')
    photo.create_size(photosize)
    return {
        'url': photo.get_thumbnail_url,
        'title': photo.title,
        'counter': counter,
    }

@register.simple_tag
def exif(photo, attr):
    return get_exif_data(photo, attr)

@register.simple_tag
def get_exif(photo, attr):
    return get_exif_data(photo, attr)


text:
<?php

namespace Spatie\GoogleTagManager;

use Illuminate\Support\Traits\MacroableTrait as Macroable;

class GoogleTagManager
{
    use Macroable;

    /**
     * @var string
     */
    protected $id;

    /**
     * @var bool
     */
    protected $enabled;

    /**
     * @var \Spatie\GoogleTagManager\DataLayer
     */
    protected $dataLayer;

    /**
     * @param string $id
     */
    public function __construct($id)
    {
        $this->id = $id;
        $this->dataLayer = new DataLayer();

        $this->enabled = true;
    }

    /**
     * Return the Google Tag Manager id.
     *
     * @return string
     */
    public function id()
    {
        return $this->id;
    }

    /**
     * Check whether script rendering is enabled.
     *
     * @return bool
     */
    public function isEnabled()
    {
        return $this->enabled;
    }

    /**
     * Enable Google Tag Manager scripts rendering.
     */
    public function enable()
    {
        $this->enabled = true;
    }

    /**
     * Disable Google Tag Manager scripts rendering.
     */
    public function disable()
    {
        $this->enabled = false;
    }

    /**
     * Add data to the data layer.
     *
     * @param array|string $key
     * @param mixed        $value
     */
    public function set($key, $value = null)
    {
        $this->dataLayer->set($key, $value);
    }

    /**
     * Retrieve the data layer
     *
     * @return \Spatie\GoogleTagManager\DataLayer
     */
    public function getDataLayer()
    {
        return $this->dataLayer;
    }

    /**
     * Clear the data layer
     */
    public function clear()
    {
        $this->dataLayer = new DataLayer();
    }

    /**
     * Utility function to dump an array as json
     *
     * @param  array $data
     * @return string
     */
    public function dump($data)
    {
        return (new DataLayer($data))->toJson();
    }
}


text:
package org.wisdom.monitor.extensions.dashboard;

import akka.actor.Cancellable;
import com.codahale.metrics.*;
import com.codahale.metrics.graphite.Graphite;
import com.codahale.metrics.graphite.GraphiteReporter;
import com.codahale.metrics.jvm.BufferPoolMetricSet;
import com.codahale.metrics.jvm.GarbageCollectorMetricSet;
import com.codahale.metrics.jvm.MemoryUsageGaugeSet;
import com.codahale.metrics.jvm.ThreadStatesGaugeSet;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.ImmutableMap;
import org.apache.felix.ipojo.annotations.Context;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;
import org.osgi.framework.BundleContext;
import org.wisdom.akka.AkkaSystemService;
import org.wisdom.api.DefaultController;
import org.wisdom.api.annotations.Controller;
import org.wisdom.api.annotations.Path;
import org.wisdom.api.annotations.Route;
import org.wisdom.api.annotations.View;
import org.wisdom.api.configuration.ApplicationConfiguration;
import org.wisdom.api.content.Json;
import org.wisdom.api.http.HttpMethod;
import org.wisdom.api.http.Result;
import org.wisdom.api.http.websockets.Publisher;
import org.wisdom.api.security.Authenticated;
import org.wisdom.api.templates.Template;
import org.wisdom.monitor.service.HealthCheck;
import org.wisdom.monitor.service.MonitorExtension;
import scala.concurrent.duration.FiniteDuration;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import static org.wisdom.monitor.extensions.dashboard.HealthState.ko;

/**
 * Monitor extension handling the main dashboard.
 */
@Controller
@Path("/monitor/dashboard")
@Authenticated("Monitor-Authenticator")
public class DashboardExtension extends DefaultController implements MonitorExtension {

    @Requires
    Publisher publisher;

    @Requires
    ApplicationConfiguration configuration;

    @Requires
    Json json;

    @Requires
    AkkaSystemService akka;

    @Requires(specification = HealthCheck.class, optional = true)
    List<HealthCheck> healthChecks;

    @View("monitor/dashboard")
    Template monitor;

    @Context
    BundleContext bc;

    final MetricRegistry registry;

    private Cancellable task;
    private HttpMetricFilter httpMetricFilter;

    /**
     * Creates the instance of dashboard extension.
     */
    public DashboardExtension() {
        this.registry = new MetricRegistry();
    }

    /**
     * Starts the dashboard.
     */
    @Validate
    public void start() {
        logger().info("Registering JVM metrics");
        registry.register("jvm.memory", new MemoryUsageGaugeSet());
        registry.register("jvm.garbage", new GarbageCollectorMetricSet());
        registry.register("jvm.threads", new ThreadStatesGaugeSet());
        registry.register("jvm.buffers", new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
        registry.register("jvm.cpu", new CpuGaugeSet());
        registry.register("jvm.runtime", new RuntimeGaugeSet());

        if (configuration.getBooleanWithDefault("monitor.http.enabled", true)) {
            logger().info("Registering HTTP metrics");
            this.httpMetricFilter = new HttpMetricFilter(bc, configuration, registry);
            httpMetricFilter.start();
        }

        if (configuration.getBooleanWithDefault("monitor.jmx.enabled", true)) {
            logger().info("Initializing Metrics JMX reporting");
            final JmxReporter jmxReporter = JmxReporter.forRegistry(registry).build();
            jmxReporter.start();
        }

        if (configuration.getBooleanWithDefault("monitor.graphite.enabled", false)) {
            logger().info("Initializing Metrics Graphite reporting");
            String graphiteHost = configuration.getOrDie("monitor.graphite.host");
            int graphitePort = configuration.getIntegerOrDie("monitor.graphite.port");
            Graphite graphite = new Graphite(new InetSocketAddress(graphiteHost, graphitePort));
            GraphiteReporter graphiteReporter = GraphiteReporter.forRegistry(registry)
                    .convertRatesTo(TimeUnit.SECONDS)
                    .convertDurationsTo(TimeUnit.MILLISECONDS)
                    .build(graphite);
            graphiteReporter.start(1, TimeUnit.MINUTES);
        }

        task = akka.system().scheduler().schedule(new FiniteDuration(0, TimeUnit.SECONDS),
                new FiniteDuration(configuration.getIntegerWithDefault("monitor.period", 10), TimeUnit.SECONDS), new Runnable() {
                    /**
                     * Sends updated data to the websocket.
                     */
                    public void run() {
                        publisher.publish("/monitor/update", json.toJson(getData()));
                    }
                }, akka.system().dispatcher()
        );

    }

    /**
     * Sends the current metrics.
     *
     * @return the metrics.
     */
    @Route(method = HttpMethod.GET, uri = "/metrics")
    public Result metrics() {
        return ok(getData()).json();
    }

    /**
     * Build an immutable map containing the current metrics.
     *
     * @return the current metrics.
     */
    private ImmutableMap<String, ?> getData() {
        long active = 0;
        Counter counter = registry.counter("http.activeRequests");
        if (counter != null) {
            active = counter.getCount();
        }

        return ImmutableMap.<String, Object>builder()
                .put("gauges", registry.getGauges())
                .put("activeRequests", active)
                .put("timers", registry.getTimers())
                .put("counter", registry.getCounters())
                .put("meter", registry.getMeters())
                .put("health", getHealth())
                .build();
    }

    /**
     * @return the map name - heath check of all health sensors.
     */
    private SortedMap<String, HealthState> getHealth() {
        SortedMap<String, HealthState> map = new TreeMap<>();

        for (HealthCheck hc : healthChecks) {
            try {
                if (hc.check()) {
                    map.put(hc.name(), HealthState.ok());
                } else {
                    map.put(hc.name(), ko());
                }
            } catch (Exception e) { //NOSONAR
                map.put(hc.name(), ko(e));
            }
        }
        return map;
    }

    /**
     * @return information about threads.
     */
    @Route(method = HttpMethod.GET, uri = "/threads")
    public Result threads() {
        ArrayNode array = json.newArray();
        ThreadMXBean bean = ManagementFactory.getThreadMXBean();
        for (long id : bean.getAllThreadIds()) {
            ObjectNode node = json.newObject();
            ThreadInfo ti = bean.getThreadInfo(id, 10);
            node
                    .put("threadName", ti.getThreadName())
                    .put("threadId", ti.getThreadId())
                    .put("blockedTime", ti.getBlockedTime())
                    .put("blockedCount", ti.getBlockedCount())
                    .put("lockName", ti.getLockName())
                    .put("waitedTime", ti.getWaitedTime())
                    .put("waitedCount", ti.getWaitedCount())
                    .put("threadState", ti.getThreadState().toString())
                    .put("stack", stack(ti.getStackTrace()));
            array.add(node);
        }
        return ok(array);
    }

    private String stack(StackTraceElement[] stackTrace) {
        StringBuilder stack = new StringBuilder();
        for (StackTraceElement element : stackTrace) {
            if (stack.length() != 0) {
                stack.append('\n');
            }
            stack
                    .append(element.getClassName()).append(".").append(element.getMethodName())
                    .append(" (").append(element.getFileName()).append(':').append(element.getLineNumber()).append(')');
        }
        return stack.toString();
    }

    /**
     * Stops the dashboard.
     * It stops the web socket publication, and the sensors.
     */
    @Invalidate
    public void stop() {
        if (task != null && !task.isCancelled()) {
            task.cancel();
        }

        if (httpMetricFilter != null) {
            httpMetricFilter.stop();
        }

        registry.removeMatching(new MetricFilter() {
            /**
             * Returns true to remove all metrics.
             * @param s the name
             * @param metric the metric
             * @return {@code true}
             */
            public boolean matches(String s, Metric metric) {
                return true;
            }
        });
    }

    /**
     * @return the dashboard page.
     */
    @Route(method = HttpMethod.GET, uri = "")
    public Result index() {
        return ok(render(monitor));
    }

    /**
     * @return "Dashboard"
     */
    @Override
    public String label() {
        return "Dashboard";
    }

    /**
     * @return the dashboard page url.
     */
    @Override
    public String url() {
        return "/monitor/dashboard";
    }

    /**
     * @return the "root" category.
     */
    @Override
    public String category() {
        return "root";
    }
}


text:
package com.akamai.edgegrid.signer.gatling.simulations

import com.akamai.edgegrid.signer.ClientCredential
import com.akamai.edgegrid.signer.gatling.openapi.OpenApiHttpConfiguration
import io.gatling.core.Predef.Simulation

abstract class OpenApiSimulation(credential: ClientCredential) extends Simulation {

  val httpConf = OpenApiHttpConfiguration.openApiHttpConf(credential)

}


text:
require 'codeclimate-test-reporter'

CodeClimate::TestReporter.configure do |config|
  config.logger.level = Logger::WARN
end

CodeClimate::TestReporter.start


text:
const WebSocket = require('ws')
const { EventEmitter } = require('events')
const options = {
  host: 'localhost',
  port: 9090,
  reconnect: false,
  reconnectSleep: 3000,
  connectionTimeout: 10000,
  sendTimeout: 3000
}
const kodi = new EventEmitter()
let jsonrpcId = 0
let socket

const sentRequests = Object.create(null)

kodi.setOptions = opts => {
  if (opts === undefined) return
  Object.entries(opts).forEach(([ key, value ]) => {
    options[key] = value
  })
}

kodi.close = opts => {
  kodi.setOptions(opts)
  socket.close()
}

kodi.connect = opts => {
  kodi.setOptions(opts)

  socket = new WebSocket(`ws://${options.host}:${options.port}/jsonrpc`)

  const connectionTimeout = setTimeout(() => {
    kodi.emit('error', new Error('Was not able to connect before reaching timeout.'))
    setTimeout(() => socket.terminate(), 1)
  }, options.connectionTimeout)

  socket.on('open', () => {
    clearTimeout(connectionTimeout)
    kodi.emit('connect')
  })

  socket.on('close', () => {
    kodi.emit('close')
    if (options.reconnect) {
      setTimeout(() => {
        kodi.connect(options)
      }, options.reconnectSleep)
    }
  })

  socket.on('error', error => kodi.emit('error', error))

  socket.on('message', message => {
    let data
    try {
      data = JSON.parse(message)
      if (data.id && sentRequests[data.id] === undefined) {
        throw new Error(`Message for unknown id received.`)
      }
    } catch (error) {
      kodi.emit('error', error)
      return
    }
    const { id, method, params } = data
    if (id && sentRequests[id]) {
      sentRequests[id](data)
    } else {
      kodi.emit(method, params)
      kodi.emit('notification', { method, params })
    }
  })
}

kodi.send = (method, params) =>
  new Promise((resolve, reject) => {
    if (socket.readyState !== WebSocket.OPEN) {
      return reject(new Error('Failed to send message. No connection to kodi.'))
    }

    const message = { jsonrpc: '2.0', method, params, id: (jsonrpcId += 1) }

    socket.send(JSON.stringify(message), error => {
      if (error) {
        return reject(error)
      }

      const timeout = setTimeout(() => {
        reject(new Error('Failed to send message. No response within timeout.'))
        delete sentRequests[message.id]
      }, options.sendTimeout)

      sentRequests[message.id] = ({ id, error, result }) => {
        clearTimeout(timeout)
        delete sentRequests[id]
        if (error) {
          return reject(error)
        }
        resolve(result)
      }
    })
  })

module.exports = kodi


text:
@import "kityminder.css";
@import "button.css";
@import "buttonicon.css";
@import "splitbutton.css";
@import "combobox.css";
@import "comboboxmenu.css";
@import "dialog.css";
@import "dialogsize.css";
@import "popup.css";
@import "tab.css";
@import "tooltip.css";
@import "colorpicker.css";
@import "separator.css";
@import "markers.css";
@import "help.css";
@import "dropmenu.css";


text:
// flowlint ambiguous-object-type:error

'use strict';

const IRTransformer = require('../core/IRTransformer');

const getLiteralArgumentValues = require('../core/getLiteralArgumentValues');
const invariant = require('invariant');

import type CompilerContext from '../core/CompilerContext';
import type {Fragment, FragmentSpread} from '../core/IR';

const RELAY = 'relay';
const SCHEMA_EXTENSION = `
directive @relay(
  # Marks a fragment as being backed by a GraphQLList.
  plural: Boolean,

  # Marks a fragment spread which should be unmasked if provided false
  mask: Boolean = true,
) on FRAGMENT_DEFINITION | FRAGMENT_SPREAD
`;

/**
 * A transform that extracts `@relay(plural: Boolean)` directives and converts
 * them to metadata that can be accessed at runtime.
 */
function relayDirectiveTransform(context: CompilerContext): CompilerContext {
  return IRTransformer.transform(context, {
    Fragment: visitRelayMetadata(fragmentMetadata),
    FragmentSpread: visitRelayMetadata(fragmentSpreadMetadata),
  });
}

type MixedObj = {[key: string]: mixed, ...};
function visitRelayMetadata<T: Fragment | FragmentSpread>(
  metadataFn: MixedObj => MixedObj,
): T => T {
  return function(node) {
    const relayDirective = node.directives.find(({name}) => name === RELAY);
    if (!relayDirective) {
      return this.traverse(node);
    }
    const argValues = getLiteralArgumentValues(relayDirective.args);
    const metadata = metadataFn(argValues);
    return this.traverse({
      ...node,
      directives: node.directives.filter(
        directive => directive !== relayDirective,
      ),
      // $FlowFixMe[cannot-spread-indexer]
      metadata: {
        ...(node.metadata || {}),
        ...metadata,
      },
    });
  };
}

function fragmentMetadata({mask, plural}): MixedObj {
  invariant(
    plural === undefined || typeof plural === 'boolean',
    'RelayDirectiveTransform: Expected the "plural" argument to @relay ' +
      'to be a boolean literal if specified.',
  );
  invariant(
    mask === undefined || typeof mask === 'boolean',
    'RelayDirectiveTransform: Expected the "mask" argument to @relay ' +
      'to be a boolean literal if specified.',
  );
  return {mask, plural};
}

function fragmentSpreadMetadata({mask}): MixedObj {
  invariant(
    mask === undefined || typeof mask === 'boolean',
    'RelayDirectiveTransform: Expected the "mask" argument to @relay ' +
      'to be a boolean literal if specified.',
  );
  return {mask};
}

module.exports = {
  RELAY,
  SCHEMA_EXTENSION,
  transform: relayDirectiveTransform,
};


text:
package org.apache.hadoop.hbase.rest;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.rest.client.Client;
import org.apache.hadoop.hbase.rest.client.Cluster;
import org.apache.hadoop.hbase.rest.client.Response;
import org.apache.hadoop.hbase.rest.model.StorageClusterVersionModel;
import org.apache.hadoop.hbase.rest.model.VersionModel;
import org.apache.hadoop.hbase.testclassification.MediumTests;
import org.apache.hadoop.hbase.testclassification.RestTests;
import org.apache.hadoop.hbase.util.Bytes;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.junit.experimental.categories.Category;

@Category({RestTests.class, MediumTests.class})
public class TestVersionResource {
  private static final Log LOG = LogFactory.getLog(TestVersionResource.class);

  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
  private static final HBaseRESTTestingUtility REST_TEST_UTIL =
    new HBaseRESTTestingUtility();
  private static Client client;
  private static JAXBContext context;

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    TEST_UTIL.startMiniCluster();
    REST_TEST_UTIL.startServletContainer(TEST_UTIL.getConfiguration());
    client = new Client(new Cluster().add("localhost",
      REST_TEST_UTIL.getServletPort()));
    context = JAXBContext.newInstance(
      VersionModel.class,
      StorageClusterVersionModel.class);
  }

  @AfterClass
  public static void tearDownAfterClass() throws Exception {
    REST_TEST_UTIL.shutdownServletContainer();
    TEST_UTIL.shutdownMiniCluster();
  }

  private static void validate(VersionModel model) {
    assertNotNull(model);
    assertNotNull(model.getRESTVersion());
    assertEquals(model.getRESTVersion(), RESTServlet.VERSION_STRING);
    String osVersion = model.getOSVersion();
    assertNotNull(osVersion);
    assertTrue(osVersion.contains(System.getProperty("os.name")));
    assertTrue(osVersion.contains(System.getProperty("os.version")));
    assertTrue(osVersion.contains(System.getProperty("os.arch")));
    String jvmVersion = model.getJVMVersion();
    assertNotNull(jvmVersion);
    assertTrue(jvmVersion.contains(System.getProperty("java.vm.vendor")));
    assertTrue(jvmVersion.contains(System.getProperty("java.version")));
    assertTrue(jvmVersion.contains(System.getProperty("java.vm.version")));
    assertNotNull(model.getServerVersion());
    String jerseyVersion = model.getJerseyVersion();
    assertNotNull(jerseyVersion);
    assertEquals(jerseyVersion, ServletContainer.class.getPackage()
      .getImplementationVersion());
  }

  @Test
  public void testGetStargateVersionText() throws IOException {
    Response response = client.get("/version", Constants.MIMETYPE_TEXT);
    assertTrue(response.getCode() == 200);
    assertEquals(Constants.MIMETYPE_TEXT, response.getHeader("content-type"));
    String body = Bytes.toString(response.getBody());
    assertTrue(body.length() > 0);
    assertTrue(body.contains(RESTServlet.VERSION_STRING));
    assertTrue(body.contains(System.getProperty("java.vm.vendor")));
    assertTrue(body.contains(System.getProperty("java.version")));
    assertTrue(body.contains(System.getProperty("java.vm.version")));
    assertTrue(body.contains(System.getProperty("os.name")));
    assertTrue(body.contains(System.getProperty("os.version")));
    assertTrue(body.contains(System.getProperty("os.arch")));
    assertTrue(body.contains(ServletContainer.class.getPackage()
      .getImplementationVersion()));
  }

  @Test
  public void testGetStargateVersionXML() throws IOException, JAXBException {
    Response response = client.get("/version", Constants.MIMETYPE_XML);
    assertTrue(response.getCode() == 200);
    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
    VersionModel model = (VersionModel)
      context.createUnmarshaller().unmarshal(
        new ByteArrayInputStream(response.getBody()));
    validate(model);
    LOG.info("success retrieving Stargate version as XML");
  }

  @Test
  public void testGetStargateVersionJSON() throws IOException {
    Response response = client.get("/version", Constants.MIMETYPE_JSON);
    assertTrue(response.getCode() == 200);
    assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
  }

  @Test
  public void testGetStargateVersionPB() throws IOException {
    Response response = client.get("/version", Constants.MIMETYPE_PROTOBUF);
    assertTrue(response.getCode() == 200);
    assertEquals(Constants.MIMETYPE_PROTOBUF, response.getHeader("content-type"));
    VersionModel model = new VersionModel();
    model.getObjectFromMessage(response.getBody());
    validate(model);
    response = client.get("/version", Constants.MIMETYPE_PROTOBUF_IETF);
    assertTrue(response.getCode() == 200);
    assertEquals(Constants.MIMETYPE_PROTOBUF_IETF, response.getHeader("content-type"));
    model = new VersionModel();
    model.getObjectFromMessage(response.getBody());
    validate(model);
  }

  @Test
  public void testGetStorageClusterVersionText() throws IOException {
    Response response = client.get("/version/cluster", Constants.MIMETYPE_TEXT);
    assertTrue(response.getCode() == 200);
    assertEquals(Constants.MIMETYPE_TEXT, response.getHeader("content-type"));
  }

  @Test
  public void testGetStorageClusterVersionXML() throws IOException,
      JAXBException {
    Response response = client.get("/version/cluster",Constants.MIMETYPE_XML);
    assertTrue(response.getCode() == 200);
    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
    StorageClusterVersionModel clusterVersionModel =
      (StorageClusterVersionModel)
        context.createUnmarshaller().unmarshal(
          new ByteArrayInputStream(response.getBody()));
    assertNotNull(clusterVersionModel);
    assertNotNull(clusterVersionModel.getVersion());
    LOG.info("success retrieving storage cluster version as XML");
  }

  @Test
  public void doTestGetStorageClusterVersionJSON() throws IOException {
    Response response = client.get("/version/cluster", Constants.MIMETYPE_JSON);
    assertTrue(response.getCode() == 200);
    assertEquals(Constants.MIMETYPE_JSON, response.getHeader("content-type"));
  }

}


text:
layout: post
date: 2017-09-15
title: "Sherri Hill Prom Dresses Style 50128 Sleeveless Sweep/Brush Train Aline/Princess"
category: Sherri Hill
tags: [Sherri Hill ,Sherri Hill,Aline/Princess ,Halter,Sweep/Brush Train,Sleeveless]
---
### Sherri Hill Prom Dresses Style 50128
Just **$529.99**
###   Sleeveless Sweep/Brush Train Aline/Princess

BRANDS	Sherri Hill

Silhouette	Aline/Princess

Neckline	Halter

Hemline/Train	Sweep/Brush Train

Sleeve	Sleeveless

Buy it: [https://www.readybrides.com/en/sherri-hill-/50192-sherri-hill-prom-dresses-style-50128.html](https://www.readybrides.com/en/sherri-hill-/50192-sherri-hill-prom-dresses-style-50128.html)


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

namespace SmartConnect
{
    public class AP
    {
        String name;
        public String Name
        {
            get { return name; }
            set { name = value; }
        }

        String mac;
        public String MAC
        {
            get { return mac; }
            set { mac = value; }
        }

        int currentClients;
        public int CurrentClients
        {
            get { return currentClients; }
            set { currentClients = value; }
        }

        int maxClients;
        public int MaxClients
        {
            get { return maxClients; }
            set { maxClients = value; }
        }

        Boolean isLockable;
        public Boolean IsLockable
        {
            get { return isLockable; }
            set { isLockable = value; }
        }

        String[] aSSIDs;
        public String[] SSIDs
        {
            get { return aSSIDs; }
            set { aSSIDs = value; }
        }

        ConcurrentDictionary<String, SSID> dSSIDs = new ConcurrentDictionary<string, SSID>();

        public AP(String name, String mac, int currentClients, int maxClients, Boolean isLockable, String[] aSSIDs)
        {
            this.name = name;
            this.mac = mac;
            this.currentClients = currentClients;
            this.maxClients = maxClients;
            this.isLockable = isLockable;
            this.aSSIDs = aSSIDs;

        }

        public String GetListString()
        {
            return (name + " (" + mac + ")");

        }

        public void LinkSSIDs(WiFiConnect controller)
        {
            if (aSSIDs != null)
            {
                foreach (String ssidName in aSSIDs)
                {
                    try
                    {
                        dSSIDs[ssidName] = controller.GetSSID(ssidName);
                    }
                    catch (KeyNotFoundException ex)
                    {
                        controller.Log.Error("LinkSSIDs: KeyNotFound - " + ex.Message);
                    }
                }
            }
        }
    }
}


text:
Contact Us

Don't hesitate to get in touch with any queries, we're here to help.

Address

						<address class="text-muted">
						Unit 3, 868 Beaufort Street

						Inglewood, WA 6052

						Australia

						</address>

Sales

						<address class="text-muted">
						E:

						</address>

General Enquiries

						<address  class="text-muted">
						Matt Goode

						E:

						P:	6377 7690

						</address>


text:
<?php

namespace FreeDSx\Ldap\Protocol;

use FreeDSx\Asn1\Type\AbstractType;
use FreeDSx\Ldap\Control\Control;
use FreeDSx\Ldap\Operation\LdapResult;
use FreeDSx\Ldap\Operation\Response\ResponseInterface;

/**
 * The LDAP Message envelope PDU. This represents a message as a response from LDAP.
 *
 * @see LdapMessage
 * @author Chad Sikorra <Chad.Sikorra@gmail.com>
 */
class LdapMessageResponse extends LdapMessage
{
    /**
     * @var ResponseInterface
     */
    protected $response;

    /**
     * @param int $messageId
     * @param ResponseInterface $response
     * @param Control ...$controls
     */
    public function __construct(int $messageId, ResponseInterface $response, Control ...$controls)
    {
        $this->response = $response;
        parent::__construct($messageId, ...$controls);
    }

    /**
     * @return ResponseInterface|LdapResult
     */
    public function getResponse(): ResponseInterface
    {
        return $this->response;
    }

    /**
     * @return AbstractType
     */
    protected function getOperationAsn1(): AbstractType
    {
        return $this->response->toAsn1();
    }
}


text:
using System.IO;
using System.Text;

namespace Flexo
{
    public interface IJsonParser
    {
        JElement Parse(Stream stream, Encoding encoding = null);
    }
}


text:
package gui;

import java.awt.Color;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;

import util.Utils;

public class GUIVote extends JFrame {

	public GUIVote(){
		initComponents();
	}

	private void closeButtonActionPerformed(){
		dispose();
	}

	private void copyButtonActionPerformed(){
//		dispose();
	}

	private void resetGui() {
		timeError.setText("");

		label2.setForeground(Color.WHITE);
		label1.setForeground(Color.WHITE);
		label5.setForeground(Color.WHITE);
	}

	private void sendButtonActionPerformed() {

		boolean errors = false;
		resetGui();

		if (option2.getText().equals("")){
			label2.setForeground(Color.RED);
			errors = true;
		}
		if (option1.getText().equals("")){
			label1.setForeground(Color.RED);
			errors = true;
		}

		if (timeField.getText().equals("")){
			label5.setForeground(Color.RED);
			errors = true;
		}

		if (errors) return;

		try {
			int test = Integer.parseInt(timeField.getText());
			if (test < 1) {
				timeError.setText("Number must be > 0");
				errors = true;
			}
			if (comboBox.getItemAt(comboBox.getSelectedIndex()).equals("sec") && test > 999) {
				timeError.setText("Seconds must be 1-999");
				errors = true;
			}
		} catch (Exception e){
			timeError.setText("Problem with your number");;
			errors = true;
		}

		if (errors) return;

		StringBuilder sb = new StringBuilder("!startpoll");
		sb.append(" " + timeField.getText() + (comboBox.getItemAt(comboBox.getSelectedIndex()).equals("min") ? "m" : ""));
		sb.append(" " + option1.getText() + "]" + option2.getText()); //These 2 are mandatory, so always append them
		if (!option3.getText().equals("")){
			sb.append("]" + option3.getText());
		}
		if (!option4.getText().equals("")){
			sb.append("]" + option4.getText());
		}

//		String channel = GUIMain.channelPane.getTitleAt(GUIMain.channelPane.getSelectedIndex());
		String channel = GUIMain.getCurrentPane().getChannel();
		if (channel != null && !channel.equalsIgnoreCase("system logs")){
			if (!questionField.getText().equals("")){
				GUIMain.bot.getBot().sendMessage("#" + channel, questionField.getText());
			}
			GUIMain.bot.onMessage("#" + channel,
					GUIMain.currentSettings.accountManager.getUserAccount().getName(),
					sb.toString());

		} else {
			CombinedChatPane ccp = Utils.getCombinedChatPane(GUIMain.channelPane.getSelectedIndex());
			boolean comboExists = ccp != null;
			if (comboExists){
				String[] channels;
				if (!ccp.getActiveChannel().equalsIgnoreCase("all")) {
					channels = new String[]{ccp.getActiveChannel()};
				} else {
					channels = ccp.getChannels();
				}
				for (String c : channels){
					if (!questionField.getText().equals("")){
						GUIMain.bot.getBot().sendMessage("#" + c, questionField.getText());
					}
					GUIMain.bot.onMessage("#" + c,
							GUIMain.currentSettings.accountManager.getUserAccount().getName(),
							sb.toString());
				}
			}
		}

		this.dispose();
	}

	@Override
	public void setVisible(boolean b){
		super.setVisible(b);
	}

	private void initComponents() {
		copyButton = new JButton();
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);

		//======== this ========
		setTitle("Create a user poll");
		setResizable(false);

        //======== copyButton ========
        copyButton.setText("Copy");
        copyButton.addActionListener(e -> copyButtonActionPerformed());

        //======== textFields ========
        timeField = new JTextField();
        timeField.setToolTipText("0-999sec or Xmin");
        timeField.setText("1");

        //======== comboBox ========
        comboBox = new JComboBox<String>();
        comboBox.addItem("min");
        comboBox.addItem("sec");
        comboBox.setSelectedIndex(0);

        //======== labels ========
        timeError = new JLabel();
        timeError.setForeground(Color.RED);
        label1 = new JLabel();
        label1.setText("Option 1");
        label2 = new JLabel();
        label2.setText("Option 2");
        label3 = new JLabel();
        label3.setText("Option 3");
        label4 = new JLabel();
        label4.setText("Option 4");
        label5 = new JLabel();
        label5.setText("Time");

        //======== options ========
        option1 = new JTextField();
        option1.setToolTipText("<Required>");
        option2 = new JTextField();
        option2.setToolTipText("<Required>");
        option3 = new JTextField();
        option3.setToolTipText("<Optional>");
        option4 = new JTextField();
        option4.setToolTipText("<Optional>");

        //======== sendButton ========
        sendButton = new JButton();
        sendButton.setText("Start Poll");
        sendButton.addActionListener(e -> sendButtonActionPerformed());

        //======== closeButton ========
        closeButton = new JButton();
        closeButton.setText("Close");
        closeButton.addActionListener(e -> closeButtonActionPerformed());

        questionField = new JTextField();
        questionField.setToolTipText("<optional question>");
        questionField.setColumns(10);

        JLabel lblQuestion = new JLabel("Question");

        GroupLayout groupLayout = new GroupLayout(getContentPane());
        groupLayout.setHorizontalGroup(
        	groupLayout.createParallelGroup(Alignment.LEADING)
        		.addGroup(groupLayout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
        				.addGroup(groupLayout.createSequentialGroup()
        					.addComponent(label3)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(option3, GroupLayout.PREFERRED_SIZE, 209, GroupLayout.PREFERRED_SIZE))
        				.addGroup(groupLayout.createSequentialGroup()
        					.addComponent(label4)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(option4, GroupLayout.PREFERRED_SIZE, 209, GroupLayout.PREFERRED_SIZE))
        				.addGroup(groupLayout.createSequentialGroup()
        					.addComponent(sendButton)
        					.addPreferredGap(ComponentPlacement.RELATED)
        					.addComponent(closeButton))
        				.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
        					.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
        						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
        							.addComponent(label1)
        							.addComponent(label5)
        							.addComponent(lblQuestion))
        						.addPreferredGap(ComponentPlacement.RELATED)
        						.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
        							.addGroup(groupLayout.createSequentialGroup()
        								.addComponent(timeField, GroupLayout.PREFERRED_SIZE, 41, GroupLayout.PREFERRED_SIZE)
        								.addPreferredGap(ComponentPlacement.RELATED)
        								.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
        									.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        									.addComponent(timeError, Alignment.TRAILING)))
        							.addComponent(questionField)
        							.addComponent(option1, GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE)))
        					.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
        						.addComponent(label2)
        						.addPreferredGap(ComponentPlacement.RELATED)
        						.addComponent(option2, GroupLayout.PREFERRED_SIZE, 209, GroupLayout.PREFERRED_SIZE))))
        			.addGap(51))
        );
        groupLayout.setVerticalGroup(
        	groupLayout.createParallelGroup(Alignment.LEADING)
        		.addGroup(groupLayout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(lblQuestion)
        				.addComponent(questionField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
        				.addComponent(timeError)
        				.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
        					.addComponent(timeField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        					.addComponent(label5)
        					.addComponent(comboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
        			.addPreferredGap(ComponentPlacement.RELATED)
        			.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(option1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(label1))
        			.addGap(5)
        			.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(option2, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(label2))
        			.addGap(5)
        			.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(option3, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(label3))
        			.addGap(5)
        			.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(option4, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(label4))
        			.addGap(5)
        			.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(closeButton)
        				.addComponent(sendButton))
        			.addContainerGap())
        );
        getContentPane().setLayout(groupLayout);

        	pack();
            setLocationRelativeTo(getOwner());

	}

	private JLabel label1, label2, label3, label4, label5, timeError;
	private JComboBox<String> comboBox;
	private JTextField timeField, option1, option2, option3, option4;
	private JButton sendButton, closeButton, copyButton;
	private JTextField questionField;
}


text:
import StackTest
import System.Directory

main :: IO ()
main = do
  isAlpine <- getIsAlpine
  if isAlpine || isARM
    then logInfo "Disabled on Alpine Linux and ARM since it cannot yet install its own GHC."
    else do
      run "cabal" ["sandbox", "init"]
      stack ["unpack", "acme-dont-1.1"]
      run "cabal" ["install", "./acme-dont-1.1"]
      removeDirectoryRecursive "acme-dont-1.1"
      stack ["--install-ghc", "init", "--solver"]
      stack ["build"]


text:
<?php
namespace EddieJaoude\Tests\Zf2Doctrine2ManagerRegistryServiceTest\Registry;

use EddieJaoude\Zf2Doctrine2ManagerRegistryService\Registry\ManagerRegistryFactory;

/**
 * Class ManagerRegistryFactoryTest
 *
 * @package EddieJaoude\Zf2Doctrine2ManagerRegistryService\Tests\Zf2Doctrine2ManagerRegistryServiceTest
 */
class ManagerRegistryFactoryTest extends \PHPUnit_Framework_TestCase
{

    /**
     * @var ManagerRegistryFactory
     */
    private $instance;

    public function setUp()
    {
        $this->instance = new ManagerRegistryFactory();
    }

    public function testGetEntityManagers()
    {
        $params = array(
            'emKey' => 'emValue'
        );

        $ems = $this->instance->getEntityManagers($params);

        $expected = array(
            'emKey' => 'doctrine.entitymanager.emKey'
        );

        $this->assertEquals($expected, $ems);
    }

    public function testGetConnections()
    {
        $params = array(
            'connKey' => 'connValue'
        );

        $conns = $this->instance->getConnections($params);

        $expected = array(
            'connKey' => 'doctrine.connection.connKey'
        );

        $this->assertEquals($expected, $conns);
    }

    public function testCreateService()
    {
        $serviceManager = \Mockery::mock('Zend\ServiceManager\ServiceManager');
        $serviceManager->shouldReceive('get')
            ->with('Config')
            ->andReturn(
                array(
                    'doctrine' => array(
                        'connection'    => array(
                            'connKey' => 'connValue'
                        ),
                        'entitymanager' => array(
                            'emKey' => 'emValue'
                        )
                    )
                )
            );

        $registry = $this->instance->createService($serviceManager);

        $this->assertInstanceOf('Doctrine\Common\Persistence\AbstractManagerRegistry', $registry);
    }
}


text:
categories:
    - overview
    - design
tags:
    - page
menu: main
weight: 0
draft: true
---


text:
alter table short_urls add column title text;

# --- !Downs

alter table short_urls drop column title;


text:
// califaicon.h
/*
    Icono de Califa en XPM
*/

#ifndef CALIFAICON_H_INCLUDED
#define CALIFAICON_H_INCLUDED

extern const char *califa_icon[];

#endif // CALIFAICON_H_INCLUDED


text:
<?php

namespace NNWelcome\LocationBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use NNWelcome\LocationBundle\Entity\City;
use NNWelcome\LocationBundle\Form\CityType;
use NNWelcome\LocationBundle\Form\CityFilterType;

/**
 * City controller.
 *
 */
class CityController extends Controller {

    private $query;
    private $metadata;
    private static $current_class;

    /**
     * @Template()
     */
    public function indexAction(Request $request) {
        $page = $request->query->get('page');

        if ($page) {
            $request->getSession()->set('admin_city_page', $page);
        } elseif ($request->getSession()->has('admin_city_page')) {
            $page = $request->getSession()->get('admin_city_page');
        } else {
            $page = 1;
        }

        $paginator = $this->get('knp_paginator');
        $pagination = $paginator->paginate(
                $this->BuildQuery($request), $page, /* page number */ 20/* limit per page */
        );
        $deleteForm = $this->createEmptyDeleteForm();

        $filterForm = $this->createForm(new CityFilterType(), $this->getFilterModel($request));

        return array(
            'pagination' => $pagination,
            'delete_form' => $deleteForm->createView(),
            'filter_form' => $filterForm->createView()
        );
    }

    public function filterAction(Request $request) {
        $form = $this->createForm(new CityFilterType());
        $form->bind($request);

        $this->setFilter($request, $form);
        $request->getSession()->set('admin_city_page', 1);

        return $this->redirect($this->generateUrl('admin_city'));
    }

    public function resetFilterAction(Request $request) {
        $request->getSession()->remove('admin_city_filter');
        $request->getSession()->set('admin_city_page', 1);

        return $this->redirect($this->generateUrl('admin_city'));
    }

    private function BuildQuery($request) {
        $em = $this->getDoctrine()->getManager();
        $this->query = $em->getRepository('LocationBundle:City')
                ->retriveCity($request);

        $this->getFilter($request);

        return $this->query->getQuery()->setHint(
                        \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER, 'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker')->execute();
    }

    private function setFilter($request, $form) {
        $filter = array();
        foreach ($form as $one) {
            if ($one->getData() !== null) {
                $type = $this->getDbType('NNWelcome\LocationBundle\Entity\City', $one->getName());
                if ($type == 'entity')
                    $filter[$one->getName()] = array('type' => $type, 'value' => $one->getData()->getId());
                else
                    $filter[$one->getName()] = array('type' => $type, 'value' => $one->getData());
            }
        }
        $request->getSession()->set('admin_city_filter', $filter);
    }

    private function getFilter($request) {
        if ($request->getSession()->has('admin_city_filter')) {
            foreach ($request->getSession()->get('admin_city_filter') as $i => $one) {
                call_user_func_array(array($this, 'add' . ucfirst($one['type']) . 'Filter'), array($i, $one['value']));
            }
        }
    }

    private function getFilterModel($request) {
        $entity = new City();
        $entity->setIsActive(null);
        if ($request->getSession()->has('admin_city_filter')) {
            foreach ($request->getSession()->get('admin_city_filter') as $i => $one) {
                if ($one['type'] == 'entity') {
                    $metadata = $this->getMetadatas('NNWelcome\LocationBundle\Entity\City');
                    $targetClass = $metadata->getAssociationTargetClass($i);
                    $one['value'] = $this->getDoctrine()->getManager()->getRepository($targetClass)->find($one['value']);
                }
                $entity->set($i, $one['value']);
            }
        }
        //exit;
        return $entity;
    }

    private function addBooleanFilter($field, $value) {
        if ("" !== $value) {
            $this->query->andWhere(sprintf('c.%s = :%s', $field, $field));
            $this->query->setParameter($field, $value);
        }
    }

    private function addStringFilter($field, $value) {
        $this->query->andWhere(sprintf('c.%s LIKE :%s', $field, $field));
        $this->query->setParameter($field, '%' . $value . '%');
    }

    private function addTextFilter($field, $value) {
        $this->query->andWhere(sprintf('c.%s LIKE :%s', $field, $field));
        $this->query->setParameter($field, '%' . $value . '%');
    }

    public function addEntityFilter($field, $value) {
        $metadata = $this->getMetadatas('NNWelcome\LocationBundle\Entity\City');
        $targetClass = $metadata->getAssociationTargetClass($field);

        $this->query->innerJoin($targetClass, $field);
        $this->query->andWhere($field . '.id = :' . $field);
        $this->query->andWhere(sprintf('c.%s = :%s', $field, $field));
        $this->query->setParameter($field, $value);
    }

    protected function getMetadatas($class = null) {
        if ($class) {
            self::$current_class = $class;
        }

        if (isset($this->metadata[self::$current_class]) || !$class) {
            return $this->metadata[self::$current_class];
        }

        if (!$this->getDoctrine()->getEntityManager()->getConfiguration()->getMetadataDriverImpl()->isTransient($class)) {
            $this->metadata[self::$current_class] = $this->getDoctrine()->getEntityManager()->getClassMetadata($class);
        }

        return $this->metadata[self::$current_class];
    }

    public function getDbType($class, $fieldName) {
        $metadata = $this->getMetadatas($class);

        if ($metadata->hasAssociation($fieldName)) {
            if ($metadata->isSingleValuedAssociation($fieldName)) {
                return 'entity';
            } else {
                return 'collection';
            }
        }

        if ($metadata->hasField($fieldName)) {
            return $metadata->getTypeOfField($fieldName);
        }

        return 'virtual';
    }

    /**
     * @Template()
     */
    public function newAction(Request $request) {
        $entity = new City();

        $form = $this->createForm(new CityType(), $entity);

        $page = 1;
        if ($request->getSession()->has('admin_city_page')) {
            $page = $request->getSession()->get('admin_city_page');
        }
        return array(
            'page' => $page,
            'entity' => $entity,
            'form' => $form->createView(),
        );
    }

    /**
     * @Template("LocationBundle:City:new.html.twig")
     */
    public function createAction(Request $request) {
        $entity = new City();
        $form = $this->createForm(new CityType(), $entity);
        $form->bind($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            $this->get('session')->setFlash('notice', $this->get('translator')->trans('Entry is successfully saved!')
            );

            if ($entity->getAction() == 'close')
                return $this->redirect($this->generateUrl('admin_city'));

            return $this->redirect($this->generateUrl('admin_city_edit', array('id' => $entity->getId())));
        }

        $this->get('session')->setFlash('error', $this->get('translator')->trans('Correct validation errors and try saving again.')
        );

        $page = 1;
        if ($request->getSession()->has('admin_city_page')) {
            $page = $request->getSession()->get('admin_city_page');
        }
        return array(
            'page' => $page,
            'entity' => $entity,
            'form' => $form->createView(),
        );
    }

    /**
     * @Template()
     */
    public function editAction($id, Request $request) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('LocationBundle:City')->find($id);

        if (!$entity) {
            $this->get('session')->setFlash('warnin', $this->get('translator')->trans('Unable to find entry with id = "%id%".', array('%id%' => $id))
            );
            return $this->redirect($this->generateUrl('admin_city'));
        }

        $editForm = $this->createForm(new CityType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        $page = 1;
        if ($request->getSession()->has('admin_city_page')) {
            $page = $request->getSession()->get('admin_city_page');
        }
        return array(
            'page' => $page,
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * @Template("LocationBundle:City:edit.html.twig")
     */
    public function updateAction(Request $request, $id) {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository('LocationBundle:City')->find($id);

        if (!$entity) {
            $this->get('session')->setFlash('warnin', $this->get('translator')->trans('Unable to find entry with id = "%id%".', array('%id%' => $id))
            );
            return $this->redirect($this->generateUrl('admin_city'));
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new CityType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {

            $em->persist($entity);
            $em->flush();

            $this->get('session')->setFlash('notice', $this->get('translator')->trans('"%title%" is successfully updated!', array('%title%' => $entity->getTitle()))
            );

            if ($entity->getAction() == 'close')
                return $this->redirect($this->generateUrl('admin_city'));

            return $this->redirect($this->generateUrl('admin_city_edit', array('id' => $entity->getId())));
        }

        $this->get('session')->setFlash('error', $this->get('translator')->trans('Correct validation errors and try saving again.')
        );

        $page = 1;
        if ($request->getSession()->has('admin_city_page')) {
            $page = $request->getSession()->get('admin_city_page');
        }
        return array(
            'page' => $page,
            'entity' => $entity,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    public function deleteAction(Request $request, $id) {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('LocationBundle:City')->find($id);

            if (!$entity) {
                $this->get('session')->setFlash('warnin', $this->get('translator')->trans('Unable to find entry with id = "%id%".', array('%id%' => $id))
                );
                return $this->redirect($this->generateUrl('admin_city'));
            }

            $em->remove($entity);
            $em->flush();

            $this->get('session')->setFlash('notice', $this->get('translator')->trans('"%title%" is successfully deleted!', array('%title%' => $entity->getTitle()))
            );
        } else {
            $this->get('session')->setFlash('error', $this->get('translator')->trans('Error deleting "%title%".', array('%title%' => $entity->getTitle()))
            );
        }

        return $this->redirect($this->generateUrl('admin_city'));
    }

    private function createDeleteForm($id) {
        return $this->createFormBuilder(array('id' => $id))
                        ->add('id', 'hidden')
                        ->getForm()
        ;
    }

    private function createEmptyDeleteForm() {
        return $this->createFormBuilder()
                        ->add('id', 'hidden')
                        ->getForm()
        ;
    }

    public function changeActiveAction(Request $request) {
        if ($request->getMethod() == 'POST') {
            $id = $request->request->get('id');
            $active = $request->request->get('active');

            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('LocationBundle:City')->find($id);

            if (!$entity) {
                return null;
            }

            if ($active)
                $active = 0;
            else
                $active = 1;

            $entity->setIsActive($active);
            $em->persist($entity);
            $em->flush();
        }
        else {
            $active = "";
        }
        return $this->render(
                        'LocationBundle:City:_ajaxResponse.html.twig', array(
                    'text' => $active
                        )
        );
    }

}


text:
import logging
import sys

from devil.android import device_errors
from devil.android.valgrind_tools import base_tool

def SetChromeTimeoutScale(device, scale):
  """Sets the timeout scale in /data/local/tmp/chrome_timeout_scale to scale."""
  path = '/data/local/tmp/chrome_timeout_scale'
  if not scale or scale == 1.0:
    # Delete if scale is None/0.0/1.0 since the default timeout scale is 1.0
    device.RemovePath(path, force=True, as_root=True)
  else:
    device.WriteFile(path, '%f' % scale, as_root=True)

class AddressSanitizerTool(base_tool.BaseTool):
  """AddressSanitizer tool."""

  WRAPPER_NAME = '/system/bin/asanwrapper'
  # Disable memcmp overlap check.There are blobs (gl drivers)
  # on some android devices that use memcmp on overlapping regions,
  # nothing we can do about that.
  EXTRA_OPTIONS = 'strict_memcmp=0,use_sigaltstack=1'

  def __init__(self, device):
    super().__init__()
    self._device = device

  @classmethod
  def CopyFiles(cls, device):
    """Copies ASan tools to the device."""
    del device

  def GetTestWrapper(self):
    return AddressSanitizerTool.WRAPPER_NAME

  def GetUtilWrapper(self):
    """Returns the wrapper for utilities, such as forwarder.

    AddressSanitizer wrapper must be added to all instrumented binaries,
    including forwarder and the like. This can be removed if such binaries
    were built without instrumentation. """
    return self.GetTestWrapper()

  def SetupEnvironment(self):
    try:
      self._device.EnableRoot()
    except device_errors.CommandFailedError as e:
      # Try to set the timeout scale anyway.
      # TODO(jbudorick) Handle this exception appropriately after interface
      #                 conversions are finished.
      logging.error(str(e))
    SetChromeTimeoutScale(self._device, self.GetTimeoutScale())

  def CleanUpEnvironment(self):
    SetChromeTimeoutScale(self._device, None)

  def GetTimeoutScale(self):
    # Very slow startup.
    return 20.0

TOOL_REGISTRY = {
    'asan': AddressSanitizerTool,
}

def CreateTool(tool_name, device):
  """Creates a tool with the specified tool name.

  Args:
    tool_name: Name of the tool to create.
    device: A DeviceUtils instance.
  Returns:
    A tool for the specified tool_name.
  """
  if not tool_name:
    return base_tool.BaseTool()

  ctor = TOOL_REGISTRY.get(tool_name)
  if ctor:
    return ctor(device)
  print('Unknown tool %s, available tools: %s' %
        (tool_name, ', '.join(sorted(TOOL_REGISTRY.keys()))))
  sys.exit(1)

def PushFilesForTool(tool_name, device):
  """Pushes the files required for |tool_name| to |device|.

  Args:
    tool_name: Name of the tool to create.
    device: A DeviceUtils instance.
  """
  if not tool_name:
    return

  clazz = TOOL_REGISTRY.get(tool_name)
  if clazz:
    clazz.CopyFiles(device)
  else:
    print('Unknown tool %s, available tools: %s' % (tool_name, ', '.join(
        sorted(TOOL_REGISTRY.keys()))))
    sys.exit(1)