text:
<!DOCTYPE html>

		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta name="description" content="Everest Admin Panel" />
		<meta name="keywords" content="Admin, Dashboard, Bootstrap3, Sass, transform, CSS3, HTML5, Web design, UI Design, Responsive Dashboard, Responsive Admin, Admin Theme, Best Admin UI, Bootstrap Theme, Wrapbootstrap, Bootstrap" />
		<meta name="author" content="Bootstrap Gallery" />
		<link rel="shortcut icon" href="img/favicon.ico">
		<title>Everest Admin Panel</title>

		<link href="css/bootstrap.css" rel="stylesheet" media="screen">

		<link href="css/animate.css" rel="stylesheet" media="screen">

		<link href="css/alertify/alertify.core.css" rel="stylesheet">
		<link href="css/alertify/alertify.default.css" rel="stylesheet">

		<link href="css/main.css" rel="stylesheet" media="screen">

		<link href="fonts/font-awesome.min.css" rel="stylesheet">

				<input type="text" class="search-query" placeholder="Search here">

						7+

						6

Recently Viewed

Users

Tasks

Fonts

Graphs

Home

Invoice

						4

								Messages

									Wilson
									Uploaded 28 new files yesterday.

									Adams
									Got 12 new messages.

									Sam
									Uploaded new project files today.

									Jennifer
									128 new purchases last 3 hours.

Welcome Mr. James

							Dashboard

							Timeline

							Blog

							Graphs

							Calendar

							Gallery

							Vector Maps

							Bonus Pages

									Invoice

									Profile

									Pricing

									Login

									404

									Basic Template

							UI Elements

									Buttons

									Panels

									Icons

									Grid

									Components

									Notifications

							Forms

									Form Elements

									Form Layouts

									Editor

							Tables

									Normal Tables

									Data Tables

Signups

							8

Users Online

							7

Images Uploaded

							4

					Notifications

$580

Today's Income

$235

Today's Expenses

Alerts

											Standard
											Success
											Error
											Custom
											Hide in 10 secs
											Persistent

Dialog Box

											Ajax - Multiple Dialog
											Alert Dialog
											Confirm Dialog
											Prompt Dialog
											Custom Labels
											Button Focus
											Button Order

Notifications

											<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>

											Well done! Its default alert notification.

											<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>

											Well done! You finally read this message.

											<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>

											Heads up! This alert needs your attention.

											<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>

											Warning! Check, you're not playing good.

											<button type="button" class="close" data-dismiss="alert" aria-hidden="true">x</button>

											Oh snap! Try to submit again.

Dismissable Alerts

												<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
												Well done! You successfully read this important alert message.

												<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
												Heads up! This alert needs your attention, but it's not super important.

												<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
												Warning! Better check yourself, you're not looking too good.

												<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
												Oh snap! Change a few things up and try submitting again.

Transparent Alert Style

												<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
												Well done! You successfully read this important alert message.

												<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
												Heads up! This alert needs your attention, but it's not super important.

												<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
												Warning! Better check yourself, you're not looking too good.

												<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
												Oh snap! Change a few things up and try submitting again.

				Copyright Everest Admin Panel 2014.

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="icon" href="favicon.ico">
	<link href='http://fonts.googleapis.com/css?family=Open+Sans:400italic,400,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

    <title>An example blog post with a responsive video embed
</title>

	<link href="../css/bootstrap.min.css" rel="stylesheet">
	<link href="../css/paperplane.css" rel="stylesheet">
	<link href="../css/font-awesome.min.css" rel="stylesheet">

   Home

   Blog

An example blog post with a responsive video embed

Home

Blog

An example blog post with a responsive video embed

		  February 22, 2015

Here's a cool video:

		  Tags: Video embed, YouTube

				Powered by PaperPlane


text:
/* @flow */

/**
 * External dependencies
 */
import {
  GraphQLBoolean,
  GraphQLEnumType,
  GraphQLID,
  GraphQLInputObjectType,
  GraphQLNonNull,
  GraphQLObjectType,
  GraphQLString,
} from 'graphql';
import {
  connectionArgs,
  connectionFromPromisedArray,
  connectionDefinitions,
  globalIdField,
  fromGlobalId,
} from 'graphql-relay';
import update from 'immutability-helper';

/**
 * Internal dependencies
 */
import { orderDirectionType, nodeInterface } from '../';
import { publishedPosts } from '../post';

/**
 * Flow types
 */
import type {
  GraphQLFieldConfig
} from 'graphql';
import type { Category } from '../../models';

/**
 * enum CategoryOrderField {
 *   SLUG
 * }
 */
export const categoryOrderFieldType: GraphQLEnumType = new GraphQLEnumType({
  name: 'CategoryOrderField',
  description: 'Possible fields in which to order a list of categories when provided an orderBy argument.',
  values: {
    SLUG: {
      value: 'slug',
      description: 'A slug of the category.'
    }
  }
});

/**
 * input CategoryOrder {
 *   field: CategoryOrderField!
 *   direction: OrderDirection!
 * }
 */
export const categoryOrderType: GraphQLInputObjectType = new GraphQLInputObjectType({
  name: 'CategoryOrder',
  description: 'Ordering options for category connections.',
  fields() {
    return {
      direction: {
        type: new GraphQLNonNull(orderDirectionType)
      },
      field: {
        type: new GraphQLNonNull(categoryOrderFieldType)
      }
    };
  }
});

/**
 * type Category {
 *   name: String!
 *   slug: String!
 *   link: String!
 *   tags(...): TagConnection
 *   publishedPosts(...): PostConnection
 * }
 */
export const categoryType: GraphQLObjectType = new GraphQLObjectType({
  name: 'Category',
  description: 'A group of tags that have the same meaning will be grouped for categorizing the post.',
  fields() {
    return {
      id: globalIdField('Category'),
      name: {
        type: new GraphQLNonNull(GraphQLString),
        description: 'A name of the category.'
      },
      slug: {
        type: new GraphQLNonNull(GraphQLString),
        description: 'A slug of the category.'
      },
      link: {
        type: new GraphQLNonNull(GraphQLString),
        description: 'A link to the category.'
      },
      publishedPosts: {
        ...publishedPosts,
        description: 'Return a list of published posts that belongs to the category.',
        resolve(rootValue: any, args: any, context: any) {
          return connectionFromPromisedArray(context.repositories.post.findAllPublishedPostsByCategory(rootValue), args);
        }
      }
    };
  },
  interfaces() {
    return [ nodeInterface ];
  }
});

/**
 * type CategoryConnection {
 *   pageInfo: PageInfo!
 *   edges: [CategoryEdge]
 * }
 */
const { connectionType: categoryConnectionType } = connectionDefinitions({ nodeType: categoryType });

/**
 * query {
 *   categories(
 *     after: String
 *     before: String
 *     first: Int
 *     last: Int
 *     orderBy: CategoryOrder
 *   ): CategoryConnection
 * }
 */
export const categories: GraphQLFieldConfig<string, any> = {
  type: categoryConnectionType,
  description: 'Return a list of categories.',
  args: {
    ...connectionArgs,
    orderBy: {
      type: categoryOrderType,
      description: 'Ordering options for list of categories returned from the connection.'
    }
  },
  resolve(rootValue: any, args: any, context: any) {
    return connectionFromPromisedArray(context.repositories.category.findAll(args), args);
  }
};

/**
 * query {
 *   category(id: ID!): Category
 * }
 */
export const category: GraphQLFieldConfig<string, any> = {
  type: categoryType,
  description: 'Return a category from its ID.',
  args: {
    id: {
      type: new GraphQLNonNull(GraphQLID),
      description: 'An ID of the category.'
    }
  },
  resolve(rootValue: any, args: any, context: any) {
    const { type, id } = fromGlobalId(args.id);

    return context.repositories.category.dataLoader.load(type.length ? id : args.id);
  }
};

/**
 * mutation {
 *   createCategory(input: CreateCategoryInput!): Category
 * }
 */
export const createCategory: GraphQLFieldConfig<string, any> = {
  type: categoryType,
  args: {
    input: {
      type: new GraphQLNonNull(new GraphQLInputObjectType({
        name: 'CreateCategoryInput',
        fields: {
          name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'A name of the category.'
          },
          slug: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'A slug of the category.'
          }
        }
      }))
    }
  },
  resolve(rootValue: any, { input }: any, context: any): Promise<Category> {
    return context.repositories.category.create(input);
  }
};

/**
 * mutation {
 *   updateCategory(input: UpdateCategoryInput!): Category
 * }
 */
export const updateCategory: GraphQLFieldConfig<string, any> = {
  type: categoryType,
  args: {
    input: {
      type: new GraphQLNonNull(new GraphQLInputObjectType({
        name: 'UpdateCategoryInput',
        fields: {
          id: {
            type: new GraphQLNonNull(GraphQLID),
            description: 'An ID of the category.'
          },
          name: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'A name of the category.'
          },
          slug: {
            type: new GraphQLNonNull(GraphQLString),
            description: 'A slug of the category.'
          }
        }
      }))
    }
  },
  resolve(rootValue: any, { input }: any, context: any) {
    const { type, id } = fromGlobalId(input.id);

    return context.repositories.category.update(
      type.length ? id : input.id,
      {
        ...update(input, {
          $unset: [ 'id' ]
        })
      }
    );
  }
};

/**
 * mutation {
 *   deleteCategory(input: DeleteCategoryInput!): Boolean!
 * }
 */
export const deleteCategory: GraphQLFieldConfig<string, any> = {
  type: new GraphQLNonNull(GraphQLBoolean),
  args: {
    input: {
      type: new GraphQLNonNull(new GraphQLInputObjectType({
        name: 'DeleteCategoryInput',
        fields: {
          id: {
            type: new GraphQLNonNull(GraphQLID),
            description: 'An ID of the category.'
          }
        }
      }))
    }
  },
  resolve(rootValue: any, { input }: any, context: any): Promise<boolean> {
    const { type, id } = fromGlobalId(input.id);

    return context.repositories.category.delete(type.length ? id : input.id);
  }
};


text:
body {
    font-family: "Roboto", sans-serif;
}

#overlay {
  position: absolute;
  left: 0px;
  top: 40px;
  padding: 8px;
  background: #fff;
  border: 1px solid #ccc;
  border-radius: 3px;
  /* overlay styling must be complete */
  font-size: 1rem;
}


text:
layout: organization
category: local

title: The Gowanus Dredgers Canoe Club
impact_area: Environment
keywords:
location_services:
location_offices:
website: http://www.gowanuscanal.org/

description:
mission: |
  Our mission is to assemble and educate a diverse group of individuals, businesses and organizations to improve the Gowanus waterfront in Brooklyn and foster awreness of issues affecting the New York-New Jersey harbor. The Gowanus Dredgers Canoe Club intends to contribute to transforming a dilapidated, historically significant estuary into a self-sustaining, environmentally friendly and healthy waterfront to be enjoyed and treasured by current and future generations.

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: Brooklyn
state: NY
address: |
  PO BOX 24403
  Brooklyn NY 11202
lat: 40.692529
lng: -73.990996
phone: 718-243-0849
ext:
fax:
email:
preferred_contact:
contact_person_intro:
---


text:
<?xml version="1.0" encoding="utf-8"?>

  <chapter xmlns="http://docbook.org/ns/docbook"
           xmlns:xlink="http://www.w3.org/1999/xlink">

    <title>FAQ</title>

      <title>About Sensei</title>

      <qandaset>
        <qandaentry>
          <question>
            <para>Why is it called Sensei?</para>
          </question>
          <answer>
            <para><emphasis>Sensei</emphasis> means
            <emphasis>teacher</emphasis> or
            <emphasis>professor</emphasis> in Japanese (<link
            xlink:href="http://en.wikipedia.org/wiki/Sensei">http://en.wikipedia.org/wiki/Sensei</link>).
            It shares the same pronunciation and writing with the
            Chinese word that has the same meaning.  This name indicates
            that the system can be used in place of Oracle database in
            many applications.
            </para>
          </answer>
        </qandaentry>

        <qandaentry>
          <question>
            <para>Why did Sensei model Rest API after ElasticSearch Query DSL?</para>
          </question>
          <answer>
            <para>Aside from a few differences that are specific to
            Sensei, the Sensei Rest API is largely inspired by <link
            xlink:href="http://www.elasticsearch.org/guide/reference/query-dsl/">ElasticSearch's
            Query DSL</link>.  ElasticSearch's Query DSL is very well
            designed in exposing <link
            xlink:href="http://lucene.apache.org/java/3_5_0/api/core/org/apache/lucene/search/Query.html">Lucene's
            query</link> capabilities and features in an elegant way.
            We didn't think it was necessary to create yet another API
            that is completely different.</para>
          </answer>
        </qandaentry>

        <qandaentry>
          <question>
            <para>Why does Sensei use a pull-model for indexing instead of
            a push model like many other data systems, e.g. Solr, HBase,
            Cassandra, MongoDB etc.?</para>
          </question>
          <answer>
            <para>One requirement for Sensei is to have extremely fast
            update rate (thousands per second) while not compromising on
            search performance. Having a push-model while maintaining
            data consistency between replications implies a cost per
            udpate event. Furthermore, this is an anti-scaling pattern
            as number of replications grows to accomodate high
            avalability, the cost for update increases. So as you add
            more machines to handle more traffic, this slows down update
            rate. </para>

            <para>Therefore, it is a conscious design decision to avoid
            this cost. Though each replication is consuming from the
            data stream at presumablly different rates, each at
            Consistency is resolved a query time by consistent hashing
            on the <emphasis>routing parameter</emphasis> specified on
            the request.</para>

            <para>By having a data stream for consumption also provides
            the benefit of having a replaying mechanism which is very
            helpful in the cases of data re-balancing and
            re-indexing.</para>
          </answer>
        </qandaentry>

        <qandaentry>
          <question>
            <para>Are there plans to support dynamic schema like MongoDB
            or ElasticSearch?</para>
          </question>
          <answer>
            <para>Yes. We are planning for early 2012 to have a design
            in place.</para>
          </answer>
        </qandaentry>

        <qandaentry>
          <question>
            <para>Is BQL only for illustration purposes or is it a
            supported method to query Sensei?</para>
          </question>
          <answer>
            <para>No, BQL is not only for illustration purposes, it is
            real.  We are in the process of finalizing specs for BQL.
            Our intention is to support BQL as a first-class citizen in
            querying Sensei.</para>
          </answer>
        </qandaentry>

        <qandaentry>
          <question>
            <para>Is Sensei being developed outside of LinkedIn?</para>
          </question>
          <answer>
            <para>Sensei is mostly under actively development within
            LinkedIn although we have been working with the community
            for quite a while, and there are some deployements outside
            of LinkedIn.</para>

            <para>While driving the project within LinkedIn benefits
            from traffic and data resources, we do believe letting the
            community drive and planning the roadmap is beneficial in
            the long run. So if you have passion and energy, visit <link
            xlink:href="/contribute.html">Contribute</link> page and
            contribute.</para>
          </answer>
        </qandaentry>

      </qandaset>

      <title>Sensei Configuration</title>

      <para>(To Be Finished)</para>

      <title>Problems Running Sensei</title>

      <qandaset>
        <qandaentry>
          <question>
            <para>Got following compilation error, what is wrong?</para>

            <programlisting>sensei-core/src/main/java/com/sensei/search/nodes/AbstractConsistentHashBroker.java:[217,47] type parameters of <T> T cannot be determined; no unique maximal instance exists for type variable T with upper bounds REQUEST,java.lang.Object</programlisting>
          </question>
          <answer>
            <para>This is a known <link
            xlink:href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6302954">Java
            1.6 bug</link> found in earlier builds. Upgrade your JDK to
            a more recent version.</para>
          </answer>
        </qandaentry>

        <qandaentry>
          <question>
            <para>Seems indexing has stopped for no reason, what is
            wrong?</para>
          </question>
          <answer>
            <para>It is possible one of the data events is erroneous,
            and by default Sensei stops indexing to maintain a
            consistent view. Look in the logs and see if you see an
            indexing exception.</para>
          </answer>
        </qandaentry>
      </qandaset>

  </chapter>


text:
#include "builtin/array.hpp"
#include "builtin/class.hpp"
#include "builtin/exception.hpp"
#include "builtin/integer.hpp"
#include "builtin/string.hpp"
#include "builtin/time.hpp"
#include "object_memory.hpp"
#include "object_utils.hpp"
#include "ontology.hpp"
#include "util/time64.h"
#include "util/strftime.h"

namespace rubinius {
  void Time::init(STATE) {
    GO(time_class).set(ontology::new_class(state, "Time", G(object)));
    G(time_class)->set_object_type(state, TimeType);
  }

  Time* Time::now(STATE, Object* self) {
    Time* tm = state->new_object_dirty<Time>(as<Class>(self));

#ifdef HAVE_CLOCK_GETTIME
    struct timespec ts;

    ::clock_gettime(CLOCK_REALTIME, &ts);

    tm->seconds_ = ts.tv_sec;
    tm->nanoseconds_ = ts.tv_nsec;
#else
    struct timeval tv;

    /* don't fill in the 2nd argument here. getting the timezone here
     * this way is not portable and broken anyway.
     */
    ::gettimeofday(&tv, NULL);

    tm->seconds_ = tv.tv_sec;
    tm->nanoseconds_ = tv.tv_usec * 1000;
#endif

    tm->decomposed(state, nil<Array>());
    tm->is_gmt(state, cFalse);
    tm->offset(state, nil<Fixnum>());
    tm->zone(state, nil<String>());

    return tm;
  }

  Time* Time::at(STATE, time64_t seconds, long nanoseconds) {
    Time* tm = state->new_object_dirty<Time>(G(time_class));
    tm->seconds_ = seconds;
    tm->nanoseconds_ = nanoseconds;
    tm->decomposed(state, nil<Array>());
    tm->is_gmt(state, cFalse);
    tm->offset(state, nil<Fixnum>());
    tm->zone(state, nil<String>());
    return tm;
  }

  // Taken from MRI
#define NDIV(x,y) (-(-((x)+1)/(y))-1)
#define NMOD(x,y) ((y)-(-((x)+1)%(y))-1)

  Time* Time::specific(STATE, Object* self, Integer* sec, Integer* nsec,
                       Object* gmt, Object* offset)
  {
    Time* tm = state->new_object_dirty<Time>(as<Class>(self));

    tm->seconds_ = sec->to_long_long();
    tm->nanoseconds_ = nsec->to_native();

    // Do a little overflow cleanup.
    if(tm->nanoseconds_ >= 1000000000) {
      tm->seconds_ += tm->nanoseconds_ / 1000000000;
      tm->nanoseconds_ %= 1000000000;
    }

    if(tm->nanoseconds_ < 0) {
      tm->seconds_ += NDIV(tm->nanoseconds_, 1000000000);
      tm->nanoseconds_ = NMOD(tm->nanoseconds_, 1000000000);
    }

    tm->decomposed(state, nil<Array>());
    tm->is_gmt(state, RBOOL(CBOOL(gmt)));
    tm->offset(state, offset);
    tm->zone(state, nil<String>());

    return tm;
  }

  Time* Time::from_array(STATE, Object* self,
                         Fixnum* sec, Fixnum* min, Fixnum* hour,
                         Fixnum* mday, Fixnum* mon, Fixnum* year, Fixnum* nsec,
                         Fixnum* isdst, Object* from_gmt, Object* offset,
                         Fixnum* offset_sec, Fixnum* offset_nsec) {
    struct tm64 tm;

    tm.tm_sec = sec->to_native();
    if(tm.tm_sec < 0 || tm.tm_sec > 60) {
      Exception::argument_error(state, "sec must be in 0..60");
    }

    tm.tm_min = min->to_native();
    if(tm.tm_min < 0 || tm.tm_min > 60) {
      Exception::argument_error(state, "min must be in 0..60");
    }

    tm.tm_hour = hour->to_native();
    if(tm.tm_hour < 0 || tm.tm_hour > 24) {
      Exception::argument_error(state, "hour must be in 0..24");
    }

    tm.tm_mday = mday->to_native();
    if(tm.tm_mday < 1 || tm.tm_mday > 31) {
      Exception::argument_error(state, "mday must be in 1..31");
    }

    tm.tm_mon = mon->to_native() - 1;
    if(tm.tm_mon < 0 || tm.tm_mon > 11) {
      Exception::argument_error(state, "mon must be in 0..11");
    }

    tm.tm_wday = -1;
    tm.tm_gmtoff = 0;
    tm.tm_zone = 0;
    tm.tm_year = year->to_long_long();

    tm.tm_isdst = isdst->to_native();

    time64_t seconds = -1;

    if(CBOOL(from_gmt) || !offset->nil_p()) {
      seconds = ::timegm64(&tm);
    } else {
      tzset();
      seconds = ::timelocal64(&tm);
    }

    Time* obj = state->new_object_dirty<Time>(as<Class>(self));
    obj->seconds_ = seconds;
    obj->nanoseconds_ = nsec->to_native();
    obj->is_gmt(state, RBOOL(CBOOL(from_gmt)));

    if(!offset->nil_p()) {
      obj->seconds_ -= offset_sec->to_long_long();
      obj->nanoseconds_ -= offset_nsec->to_native();

      // Deal with underflow wrapping
      if(obj->nanoseconds_ < 0) {
        obj->seconds_ += NDIV(obj->nanoseconds_, 1000000000);
        obj->nanoseconds_ = NMOD(obj->nanoseconds_, 1000000000);
      }

      obj->offset(state, offset);
    } else {
      obj->offset(state, nil<Fixnum>());
    }

    obj->decomposed(state, nil<Array>());
    obj->zone(state, nil<String>());

    return obj;
  }

  Time* Time::dup(STATE, Object* self, Time* other) {
    Time* tm = state->new_object_dirty<Time>(as<Class>(self));
    tm->seconds_ = other->seconds_;
    tm->nanoseconds_ = other->nanoseconds_;
    tm->decomposed(state, other->decomposed_);
    tm->is_gmt(state, other->is_gmt_);
    tm->offset(state, other->offset_);
    tm->zone(state, other->zone_);

    return tm;
  }

  struct tm64 Time::get_tm() {
    time64_t seconds = seconds_;
    struct tm64 tm = {0};

    if(Fixnum* off = try_as<Fixnum>(offset_)) {
      seconds += off->to_long_long();
      gmtime64_r(&seconds, &tm);
    } else if(CBOOL(is_gmt_)) {
      gmtime64_r(&seconds, &tm);
    } else {
      tzset();
      localtime64_r(&seconds, &tm);
    }

    return tm;
  }

  Object* Time::utc_offset(STATE) {
    if(CBOOL(is_gmt_)) {
      return Fixnum::from(0);
    } else if(!offset_->nil_p()) {
      return offset_;
    }

    native_int off;

#ifdef HAVE_TM_NAME
    struct tm tm = get_tm();
    off = -tm.tm_tzadj;
#else /* !HAVE_TM_NAME */
#ifdef HAVE_TM_ZONE
#ifdef HAVE_TM_GMTOFF
    struct tm64 tm = get_tm();
    off = tm.tm_gmtoff;
#else
    off = _timezone;
#endif
#else /* !HAVE_TM_ZONE */
#if HAVE_VAR_TIMEZONE
#if HAVE_VAR_ALTZONE
    off = -(daylight ? timezone : altzone);
#else
    off = -timezone;
#endif
#else /* !HAVE_VAR_TIMEZONE */
#ifdef HAVE_GETTIMEOFDAY
    gettimeofday(&tv, &zone);
    off = -zone.tz_minuteswest * 60;
#else
    /* no timezone info, then calc by myself */
    {
      struct tm utc;
      time_t now;
      time(&now);
      gmtime_r(&now, &utc);
      off = (now - mktime(&utc));
    }
#endif
#endif /* !HAVE_VAR_TIMEZONE */
#endif /* !HAVE_TM_ZONE */
#endif /* !HAVE_TM_NAME */

    return Fixnum::from(off);
  }

  Array* Time::calculate_decompose(STATE) {
    if(!decomposed_->nil_p()) return decomposed_;

    struct tm64 tm = get_tm();

    /* update Time::TM_FIELDS when changing order of fields */
    Array* ary = Array::create(state, 11);
    ary->set(state, 0, Integer::from(state, tm.tm_sec));
    ary->set(state, 1, Integer::from(state, tm.tm_min));
    ary->set(state, 2, Integer::from(state, tm.tm_hour));
    ary->set(state, 3, Integer::from(state, tm.tm_mday));
    ary->set(state, 4, Integer::from(state, tm.tm_mon + 1));
    ary->set(state, 5, Integer::from(state, tm.tm_year));
    ary->set(state, 6, Integer::from(state, tm.tm_wday));
    ary->set(state, 7, Integer::from(state, tm.tm_yday + 1));
    ary->set(state, 8, RBOOL(tm.tm_isdst));

    if (zone_->nil_p()) {
      if(offset_->nil_p() && tm.tm_zone) {
        zone(state, locale_string(state, tm.tm_zone));
      } else {
        zone(state, nil<String>());
      }
    }
    ary->set(state, 9, zone());

    // Cache it.
    decomposed(state, ary);
    return ary;
  }

#define STRFTIME_STACK_BUF 128

  String* Time::strftime(STATE, String* format) {
    struct tm64 tm = get_tm();

    struct timespec64 ts;
    ts.tv_sec = seconds_;
    ts.tv_nsec = nanoseconds_;

    int off = 0;
    if(Fixnum* offset = try_as<Fixnum>(utc_offset(state))) {
      off = offset->to_int();
    }

    if(format->byte_size() == 0) return String::create(state, NULL, 0);

    char stack_str[STRFTIME_STACK_BUF];

    size_t chars = ::strftime_extended(stack_str, STRFTIME_STACK_BUF,
                       format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0,
                       off);

    size_t buf_size = format->byte_size();

    String* result = 0;

    if(chars == 0) {
      buf_size *= 2;
      char* malloc_str = (char*)malloc(buf_size);

      if(!malloc_str) {
        Exception::memory_error(state);
        return NULL;
      }

      chars = ::strftime_extended(malloc_str, buf_size,
                  format->c_str(state), &tm, &ts, CBOOL(is_gmt_) ? 1 : 0,
                  off);
      if(chars) {
        result = String::create(state, malloc_str, chars);
        result->encoding(state, format->encoding());
      }

      free(malloc_str);
    } else {
      result = String::create(state, stack_str, chars);
      result->encoding(state, format->encoding());
    }

    return result;
  }

  // Returns the environment time zone.
  String* Time::env_zone(STATE) {
    struct tm64 tm;

    tzset();
    localtime64_r(&seconds_, &tm);

    if(tm.tm_zone) {
      return locale_string(state, tm.tm_zone);
    } else {
      return nil<String>();
    }
  }

  String* Time::locale_string(STATE, const char* data) {
    String* str = String::create(state, data);
    Encoding* locale = Encoding::find(state, "locale");
    if(!locale->nil_p()) {
      str->encoding(state, locale);
    }
    return str;
  }
}


text:
package ch03

import ch03.List.{productWithFoldLeft, sumWithFoldLeft}
import org.specs2.mutable.Specification

class Ex311FoldLeftSpec extends Specification {
  "Sum with fold left" should {
    "return 0 for an empty list" in {
      sumWithFoldLeft(Nil) mustEqual 0
    }

    "return sum of a list with multiple elements" in {
      sumWithFoldLeft(List(1,2,3,4,5,6,7,8)) mustEqual 36
    }
  }

  "product with fold left" should {
    "return 1 for an empty list" in {
      productWithFoldLeft(Nil) mustEqual 1
    }

    "return multiplication of all elements in the list" in {
      productWithFoldLeft(List(1,2,3,4)) mustEqual 24
    }
  }
}


text:
- Use up-to-date JavaScript, with an option to upgrade to typescript
- Produce an ES2015 + ESM version to consume with webpack based embedders
- Produce an ES5 + ESM version to consume with webpack based embedders and older targets
- Produce an ES5 + UMD bundle to consume baremetal
- Do **not** bundle any dependencies.

### Styles

- Use a CSS preprocessor to get better scalability
- Include an autoprefixer to compile the styles to all supported browsers
- Separate themes from base style to be imported by default
- Keep the option to ship sass mixins such as Angular Material

## Idea

- Use babel to perform ESnext -> Downlevel transpilation with webpack/babel-loader
- Once upgrade to TS is done -> replace babel-loader by ts-loader
- Use less/sass-loader to transpile styles.
- Ship it roughly in this directory structure

---

- root
  - src (input code)
    - js
      - LayoutManager.js
    - less
      - base.less
      - theme-dark.less
      - theme-light.less
    - index.js
  - dist (output products)
    - css
      - goldenlayout.css
    - umd (completely bundled variant)
      - goldenlayout.min.js
      - goldenlayout.min.js.map
      - goldenlayout.js
    - module (ES5 code, ESM modules)
      - index.js
      - js
        - LayoutManager.js
    - es2015 (ES6 code, ESM modules)
      - index.js
      - js
        - LayoutManager.js

---


text:
package ru.redcraft.pinterest4j.core.api;

import java.util.List;

import ru.redcraft.pinterest4j.Board;
import ru.redcraft.pinterest4j.Comment;
import ru.redcraft.pinterest4j.Pin;
import ru.redcraft.pinterest4j.User;

public class LazyPin extends PinterestEntity<Pin, PinBuilder> implements Pin {

	private final long id;

	LazyPin(long id, InternalAPIManager apiManager) {
		super(apiManager);
		this.id = id;
	}

	LazyPin(PinBuilder pinBuilder, InternalAPIManager apiManager) {
		super(pinBuilder, apiManager);
		this.id = pinBuilder.getId();
	}

	LazyPin(String url, InternalAPIManager apiManager) {
		this(Long.valueOf(url.replace("/pin/", "").replace("/", "")), apiManager);
	}

	public Pin refresh() {
		setTarget(getApiManager().getPinAPI().getCompletePin(id));
		return this;
	}

	public long getId() {
		return id;
	}

	public String getDescription() {
		return getTarget().getDescription();
	}

	public String getLink() {
		return getTarget().getLink();
	}

	public String getImageURL() {
		return getTarget().getImageURL();
	}

	public Board getBoard() {
		return getTarget().getBoard();
	}

	public double getPrice() {
		return getTarget().getPrice();
	}

	public int getLikesCount() {
		return getTarget().getLikesCount();
	}

	public int getRepinsCount() {
		return getTarget().getRepinsCount();
	}

	public User getPinner() {
		return getTarget().getPinner();
	}

	public User getOriginalPinner() {
		return getTarget().getOriginalPinner();
	}

	public boolean isRepined() {
		return getTarget().isRepined();
	}

	public int getCommentsCount() {
		return getTarget().getCommentsCount();
	}

	public String getURL() {
		return "pin/" + Long.toString(id) + "/";
	}

	public List<Comment> getComments() {
		return getApiManager().getPinAPI().getComments(this);
	}

	@Override
	public String toString() {
		return "LazyPin [id=" + id + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		final int shift = 32;
		int result = 1;
		result = prime * result + (int) (id ^ (id >>> shift));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (!(obj instanceof LazyPin)) {
			return false;
		}
		LazyPin other = (LazyPin) obj;
		if (id != other.id) {
			return false;
		}
		return true;
	}

}


text:
#ifndef _CONDOR_ANNEX_CREATE_H
#define _CONDOR_ANNEX_CREATE_H

void callCreateOneAnnex();

#endif /* _CONDOR_ANNEX_UPDATE_H */


text:
package org.jboss.weld.tests.event.observer.validation.enterprise;

import jakarta.ejb.Local;

public @Local interface LazyFarmerLocal
{
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <me.caiying.indicator.LineTabIndicator
        android:id="@+id/line_tab_indicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

</LinearLayout>


text:
function buildNav(pageNumber, interviewId){
		var i = 0;
		var pages = [];
		if(study.INTRODUCTION != ""){
			pages[i] = checkPage(i, pageNumber, "INTRODUCTION");
			i++;
		}
		pages[i] = checkPage(i, pageNumber, "EGO ID");
		i++;
		if(!interviewId){
			$('#navbox ul').html('');
			for(z in pages){
				$('#navbox ul').append("
" + z + ". " + pages[z] + "
");
			}
			return;
		}
		var prompt = "";
		var ego_question_list = '';
		for(j in ego_questions){
			if(evalExpression(ego_questions[j].ANSWERREASONEXPRESSIONID, interviewId) != true)
				continue;

			if((parseInt(ego_questions[j].ASKINGSTYLELIST) != 1 || prompt != ego_questions[j].PROMPT.replace(/<\/*[^>]*>/gm, '').replace(/(\r\n|\n|\r)/gm,"")) && ego_question_list){
			    pages[i] = checkPage(i, pageNumber, ego_question_list.TITLE);
				prompt = "";
			    ego_question_list = '';
			    i++;
			}
			if(ego_questions[j].PREFACE != ""){
				pages[i] = checkPage(i, pageNumber, "PREFACE");
				i++;
			}
			if(parseInt(ego_questions[j].ASKINGSTYLELIST)){
			    prompt = ego_questions[j].PROMPT.replace(/<\/*[^>]*>/gm, '').replace(/(\r\n|\n|\r)/gm,"");
			    if(ego_question_list == '')
				    ego_question_list = ego_questions[j];
			}else{
			    pages[i] = checkPage(i, pageNumber, ego_questions[j].TITLE);
			    i++;
			}

		}
		if(ego_question_list){
			pages[i] = checkPage(i, pageNumber, ego_question_list.TITLE);
			ego_question_list = '';
			i++;
		}
		if(study.ALTERPROMPT.replace(/<\/*[^>]*>/gm, '').replace(/(\r\n|\n|\r)/gm,"")){
			pages[i] = checkPage(i, pageNumber, "ALTER_PROMPT");
			i++;
		}
		var alters = db.queryObjects("SELECT * FROM alters WHERE interviewId = " + interviewId).data;
		if(alters.length > 0){
			prompt = "";
			for(j in alter_questions){
				var alter_question_list = '';
				for(k in alters){
					if(evalExpression(alter_questions[j].ANSWERREASONEXPRESSIONID, interviewId, alters[k].ID) != true)
						continue;
					if(parseInt(alter_questions[j].ASKINGSTYLELIST)){
				    	alter_question_list = alter_questions[j];
				    }else{
						if(alter_questions[j].PREFACE != ""){
				    		pages[i] = checkPage(i, pageNumber, "PREFACE");
				    		i++;
				    	}
				    	pages[i] = checkPage(i, pageNumber, alter_questions[j].TITLE);
				    	i++;
				    }
				}
				if(parseInt(alter_questions[j].ASKINGSTYLELIST)){
				    if(alter_question_list){
				    	if(alter_questions[j].PREFACE != ""){
				    		pages[i] = checkPage(i, pageNumber, "PREFACE");
				    		i++;
				    	}
				    	pages[i] = checkPage(i, pageNumber, alter_question_list.TITLE);
				    	i++;
				    }
				}
			}
			prompt = "";
			for(j in alter_pair_questions){
				alters2 = alters.slice(0);
				preface = new Question;
				preface.ANSWERTYPE = "PREFACE";
				preface.PROMPT = alter_pair_questions[j].PREFACE;
				for(k in alters){
					if(alter_pair_questions[j].SYMMETRIC)
						alters2.shift();
					var alter_pair_question_list = '';
					for(l in alters2){
			    		if(alters[k].ID == alters2[l].ID)
			    			continue;
						if(evalExpression(alter_pair_questions[j].ANSWERREASONEXPRESSIONID, interviewId, alters[k].ID, alters2[l].ID) != true)
			    			continue;
			    		alter_pair_question_list = alter_pair_questions[j];
			    	}
			    	if(alter_pair_question_list){
						if(preface.PROMPT != ""){
				    		pages[i] = checkPage(i, pageNumber, "PREFACE");
							preface.PROMPT = "";
				    		i++;
				    	}
				    	pages[i] = checkPage(i, pageNumber, alter_pair_question_list.TITLE + " - " + alters[k].NAME);
				    	i++;
					}
				}
			}
			/*
			foreach(network_qs as question){
			    if(interviewId){
			    	expression = new Expression;
			    	if(!expression.evalExpression(question['answerReasonExpressionId'], interviewId))
			    		continue;
			    }
			    if(question['preface'] != ""){
			    	pages[i] = checkPage(i, pageNumber, "PREFACE");
			    	i++;
			    }
			    pages[i] = checkPage(i, pageNumber, question['title']);
			    i++;
			}*/
		}
		pages[i] = checkPage(i, pageNumber, "CONCLUSION");
		$('#navbox ul').html('');
		for(z in pages){
			$('#navbox ul').append("
" + z + ". " + pages[z] + "
");
		}
		return;
	}

	function checkPage(currentPage, pageNumber, text){
		if(currentPage == pageNumber)
			text = "" + text + "";
		return text;
	}


text:
"""Main Controller"""

from tg import expose, flash, require, url, request, redirect
from pylons.i18n import ugettext as _, lazy_ugettext as l_
from catwalk.tg2 import Catwalk
from repoze.what import predicates

from brie.lib.base import BaseController
from brie.lib.aurore_helper import *
from brie import model

import brie.controllers.scheduler as scheduler

#from brie.controllers.secure import SecureController
import brie.controllers.auth as auth_handler
from brie.controllers.auth import AuthRestController
from brie.controllers.rooms import RoomsController
from brie.controllers.members import MembersController
from brie.controllers.show import ShowController
from brie.controllers.search import SearchController
from brie.controllers.edit import EditController
from brie.controllers.administration import AdministrationController
from brie.controllers.stats import StatsController
from brie.controllers.getemails import GetEmailsController
from brie.controllers.error import ErrorController
from brie.controllers.registration import RegistrationController
from brie.controllers.treasury import TreasuryController
from brie.controllers.plugins import PluginsController

__all__ = ['RootController']

class RootController(BaseController):
    """
    The root controller for the Brie application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """
#    admin = Catwalk(model, DBSession)

    auth = AuthRestController()
    rooms = RoomsController()
    show = ShowController()
    edit = EditController(show)
    members = MembersController(edit)
    administration = AdministrationController()
    stats = StatsController()
    getemails = GetEmailsController()
    error = ErrorController()
    search = SearchController()
    registration = RegistrationController(edit, administration)
    treasury = TreasuryController()
    plugins = PluginsController()

    @expose('brie.templates.index')
    def index(self):
        user = auth_handler.current.get_user()
        residence = None

        if user is not None:
            residence = Residences.get_name_by_dn(user, user.residence_dn)
        #end if

	return { "user" : user, "residence" : residence }
    #end def
#end class


text:
<?php

namespace Kartenmacherei\CQRSFramework\Response;

use Kartenmacherei\CQRSFramework\Library\SessionId;

abstract class AbstractResponse implements Response
{
    /**
     * @var SessionId
     */
    private $sessionId;

    /**
     * @return SessionId
     */
    public function getSessionId()
    {
        return $this->sessionId;
    }

    /**
     * @param SessionId $sessionId
     */
    public function setSessionId(SessionId $sessionId)
    {
        $this->sessionId = $sessionId;
    }

    public function send()
    {
        if (isset($this->sessionId)) {
            setcookie($this->sessionId->getCookieName(), $this->sessionId->asString());
        }
        $this->doSend();
    }

    abstract protected function doSend();
}


text:
/*
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
*/

package annoyindex_test

import (
       "annoyindex"
       "os"
       "testing"
       "math"
       "math/rand"
       "github.com/stretchr/testify/assert"
       "github.com/stretchr/testify/suite"
)

type AnnoyTestSuite struct {
    suite.Suite
}

func Round(f float64) float64 {
    return math.Floor(f + 0.5)
}

func RoundPlus(f float64, places int) (float64) {
     shift := math.Pow(10, float64(places))
     return Round(f * shift) / shift
}

func (suite *AnnoyTestSuite) SetupTest() {
}

func (suite *AnnoyTestSuite) TestFileHandling() {
     index := annoyindex.NewAnnoyIndexAngular(3)
     index.AddItem(0, []float32{0, 0, 1})
     index.AddItem(1, []float32{0, 1, 0})
     index.AddItem(2, []float32{1, 0, 0})
     index.Build(10)

     index.Save("go_test.ann")

     info, err := os.Stat("go_test.ann")
     if err != nil {
        assert.Fail(suite.T(), "Failed to create file, file not found")
     }
     if info.Size() == 0 {
        assert.Fail(suite.T(), "Failed to create file, file size zero")
     }

     annoyindex.DeleteAnnoyIndexAngular(index)

     index = annoyindex.NewAnnoyIndexAngular(3)
     if ret := index.Load("go_test.ann"); ret == false {
        assert.Fail(suite.T(), "Failed to load file")
     }

     os.Remove("go_test.ann")
     index.Save("go_test2.ann", false)

     info, err = os.Stat("go_test2.ann")
     if err != nil {
        assert.Fail(suite.T(), "Failed to create file without prefault, file not found")
     }
     if info.Size() == 0 {
        assert.Fail(suite.T(), "Failed to create file without prefault, file size zero")
     }

     annoyindex.DeleteAnnoyIndexAngular(index)

     index = annoyindex.NewAnnoyIndexAngular(3)
     if ret := index.Load("go_test2.ann", false); ret == false {
        assert.Fail(suite.T(), "Failed to load file without prefault")
     }

     os.Remove("go_test2.ann")
     index.Save("go_test3.ann", true)

     info, err = os.Stat("go_test3.ann")
     if err != nil {
        assert.Fail(suite.T(), "Failed to create file allowing prefault, file not found")
     }
     if info.Size() == 0 {
        assert.Fail(suite.T(), "Failed to create file allowing prefault, file size zero")
     }

     annoyindex.DeleteAnnoyIndexAngular(index)

     index = annoyindex.NewAnnoyIndexAngular(3)
     if ret := index.Load("go_test3.ann", true); ret == false {
        assert.Fail(suite.T(), "Failed to load file allowing prefault")
     }
     annoyindex.DeleteAnnoyIndexAngular(index)

     os.Remove("go_test3.ann")
}

func (suite *AnnoyTestSuite) TestOnDiskBuild() {
     index := annoyindex.NewAnnoyIndexAngular(3)
     index.OnDiskBuild("go_test.ann");

     info, err := os.Stat("go_test.ann")
     if err != nil {
        assert.Fail(suite.T(), "Failed to create file, file not found")
     }
     if info.Size() == 0 {
        assert.Fail(suite.T(), "Failed to create file, file size zero")
     }

     index.AddItem(0, []float32{0, 0, 1})
     index.AddItem(1, []float32{0, 1, 0})
     index.AddItem(2, []float32{1, 0, 0})
     index.Build(10)

     index.Unload();
     index.Load("go_test.ann");

     var result []int
     index.GetNnsByVector([]float32{3, 2, 1}, 3, -1, &result)
     assert.Equal(suite.T(), []int{2, 1, 0}, result)

     index.GetNnsByVector([]float32{1, 2, 3}, 3, -1, &result)
     assert.Equal(suite.T(), []int{0, 1, 2}, result)

     index.GetNnsByVector([]float32{2, 0, 1}, 3, -1, &result)
     assert.Equal(suite.T(), []int{2, 0, 1}, result)

     annoyindex.DeleteAnnoyIndexAngular(index)

     os.Remove("go_test.ann")
}

func (suite *AnnoyTestSuite) TestGetNnsByVector() {
     index := annoyindex.NewAnnoyIndexAngular(3)
     index.AddItem(0, []float32{0, 0, 1})
     index.AddItem(1, []float32{0, 1, 0})
     index.AddItem(2, []float32{1, 0, 0})
     index.Build(10)

     var result []int
     index.GetNnsByVector([]float32{3, 2, 1}, 3, -1, &result)
     assert.Equal(suite.T(), []int{2, 1, 0}, result)

     index.GetNnsByVector([]float32{1, 2, 3}, 3, -1, &result)
     assert.Equal(suite.T(), []int{0, 1, 2}, result)

     index.GetNnsByVector([]float32{2, 0, 1}, 3, -1, &result)
     assert.Equal(suite.T(), []int{2, 0, 1}, result)

     annoyindex.DeleteAnnoyIndexAngular(index)
}

func (suite *AnnoyTestSuite) TestGetNnsByItem() {
     index := annoyindex.NewAnnoyIndexAngular(3)
     index.AddItem(0, []float32{2, 1, 0})
     index.AddItem(1, []float32{1, 2, 0})
     index.AddItem(2, []float32{0, 0, 1})
     index.Build(10)

     var result []int
     index.GetNnsByItem(0, 3, -1, &result)
     assert.Equal(suite.T(), []int{0, 1, 2}, result)

     index.GetNnsByItem(1, 3, -1, &result)
     assert.Equal(suite.T(), []int{1, 0, 2}, result)

     annoyindex.DeleteAnnoyIndexAngular(index)
}

func (suite *AnnoyTestSuite) TestGetItem() {
     index := annoyindex.NewAnnoyIndexAngular(3)
     index.AddItem(0, []float32{2, 1, 0})
     index.AddItem(1, []float32{1, 2, 0})
     index.AddItem(2, []float32{0, 0, 1})
     index.Build(10)

     var result []float32

     index.GetItem(0, &result)
     assert.Equal(suite.T(), []float32{2, 1, 0}, result)

     index.GetItem(1, &result)
     assert.Equal(suite.T(), []float32{1, 2, 0}, result)

     index.GetItem(2, &result)
     assert.Equal(suite.T(), []float32{0, 0, 1}, result)

     annoyindex.DeleteAnnoyIndexAngular(index)
}

func (suite *AnnoyTestSuite) TestGetDistance() {
     index := annoyindex.NewAnnoyIndexAngular(2)
     index.AddItem(0, []float32{0, 1})
     index.AddItem(1, []float32{1, 1})
     index.Build(10)

     assert.Equal(suite.T(), RoundPlus(math.Pow(2 * (1.0 - math.Pow(2, -0.5)), 0.5), 3), RoundPlus(float64(index.GetDistance(0, 1)), 3))

     annoyindex.DeleteAnnoyIndexAngular(index)
}

func (suite *AnnoyTestSuite) TestGetDotProductDistance() {
    index := annoyindex.NewAnnoyIndexDotProduct(2)
    index.AddItem(0, []float32{0, 1})
    index.AddItem(1, []float32{1, 1})
    index.Build(10)

    assert.True(suite.T(),
        math.Abs(1.0-float64(index.GetDistance(0, 1))) < 0.00001)

    annoyindex.DeleteAnnoyIndexDotProduct(index)
}

func (suite *AnnoyTestSuite) TestLargeEuclideanIndex() {
     index := annoyindex.NewAnnoyIndexEuclidean(10)

     for j := 0; j < 10000; j += 2 {
         p := make([]float32, 0, 10)
         for i := 0; i < 10; i++ {
	     p = append(p, rand.Float32())
	 }
	 x := make([]float32, 0, 10)
	 for i := 0; i < 10; i++ {
	     x = append(x, 1 + p[i] + rand.Float32() * 1e-2)
	 }
	 y := make([]float32, 0, 10)
	 for i := 0; i < 10; i++ {
	     y = append(y, 1 + p[i] + rand.Float32() * 1e-2)
	 }
	 index.AddItem(j, x)
	 index.AddItem(j + 1, y)
     }
     index.Build(10)
     for j := 0; j < 10000; j += 2 {
         var result []int
	 index.GetNnsByItem(j, 2, -1, &result)

         assert.Equal(suite.T(), result, []int{j, j + 1})

	 index.GetNnsByItem(j + 1, 2, -1, &result)
	 assert.Equal(suite.T(), result, []int{j + 1, j})
     }
     annoyindex.DeleteAnnoyIndexEuclidean(index)
}

func TestAnnoyTestSuite(t *testing.T) {
    suite.Run(t, new(AnnoyTestSuite))
}


text:
package com.aspose.total.cloud.disk;

import com.aspose.storage.api.StorageApi;
import com.aspose.storage.model.DiscUsageResponse;
import com.aspose.total.cloud.Configuration;

public class GetDiskUsageAsposeCloudExample {

    public static void main(String[] args) {
        //ExStart: 1
        try {
            StorageApi storageApi = new StorageApi(Configuration.apiKey, Configuration.appSID, true);
            DiscUsageResponse apiResponse = storageApi.GetDiscUsage("MyStorage");
            if (apiResponse != null && apiResponse.getStatus().equals("OK")) {
                System.out.println("Total Size (bytes): " + apiResponse.getDiscUsage().getTotalSize());
                System.out.println("Used Size (bytes): " + apiResponse.getDiscUsage().getUsedSize());
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        //ExEnd: 1
    }
}


text:
class ProcessUsage < Scout::Plugin
  MEM_CONVERSION = 1024

  def build_report
    if option(:command_name).nil? or option(:command_name) == ""
      return error("Please specify the name of the process you want to monitor.")
    end
    ps_command   = option(:ps_command) || "ps auxww"
    ps_regex     = (option(:ps_regex) || "(?i:\\bCOMMAND\\b)").to_s.gsub("COMMAND") { Regexp.escape(option(:command_name)) }

    ps_output = `#{ps_command}`
    unless $?.success?
      return error("Couldn't use `ps` as expected.", error.message)
    end

    ps_lines = ps_output.split(/\n/)
    fields   = ps_lines.shift.downcase.split
    unless (memory_index = fields.index("rss")) && (pid_index = fields.index('pid'))
      return error( "RSS or PID field not found.",
                    "The output from `#{ps_command}` did not include the needed RSS and PID fields." )
    end

    # narrow the ps lines to just those mentioning the process we're interested in
    process_lines = ps_lines.grep(Regexp.new(ps_regex))

    if process_lines.any?
      rss_values = process_lines.map { |com| Float(com.split[memory_index]).abs }
      pids       = process_lines.map { |com| Integer(com.split[pid_index]) }
      highest    = rss_values.max
      total      = rss_values.inject(0){|s,value| s + value }
      restarts   = 0

      if remembered_pids = memory(:pids)
        # Find how many new pids we haven't seen before
        new_pids     = (pids - remembered_pids).length

        # Find how many more pids we have now than before
        started_pids = pids.length - remembered_pids.length
        started_pids = 0 if started_pids < 1

        # Don't include newly started processes as restarts
        restarts = new_pids - started_pids
      end

      report(:memory        => (highest/MEM_CONVERSION).to_i,
             :total_rss     => (total/MEM_CONVERSION).to_i,
             :num_processes => process_lines.size,
             :restarts      => restarts)

      remember(:pids => pids)
    else
      error( "Command not found.",
             "No processes found matching #{option(:command_name)}." )
    end
  rescue Exception => e
    error("Error when executing: #{e.class}", e.message)
  end
end


text:
package net.java.sip.communicator.impl.gui.main.call;

import java.awt.*;
import java.awt.event.*;
import java.beans.*;

import net.java.sip.communicator.impl.gui.*;
import net.java.sip.communicator.impl.gui.utils.*;
import net.java.sip.communicator.plugin.desktoputil.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.resources.*;
import net.java.sip.communicator.util.skin.*;

/**
 * The base class for all toggle buttons which control the call from the UI.
 * Allows extending buttons to focus on performing their toggle actions.
 *
 * @author Dmitri Melnikov
 * @author Adam Netocny
 * @author Yana Stamcheva
 * @author Lyubomir Marinov
 */
public abstract class AbstractCallToggleButton
    extends SIPCommToggleButton
    implements Skinnable
{
    /**
     * The button model of this call toggle button.
     */
    private class CallToggleButtonModel
        extends ToggleButtonModel
        implements ActionListener,
                   Runnable
    {
        private Thread runner;

        public CallToggleButtonModel(Call call)
        {
            addActionListener(this);
        }

        public synchronized void actionPerformed(ActionEvent event)
        {
            if(spawnActionInNewThread)
            {
                if (runner == null)
                {
                    runner = new Thread(this, LocalVideoButton.class.getName());
                    runner.setDaemon(true);

                    setEnabled(false);
                    runner.start();
                }
            }
            else
                buttonPressed();
        }

        private void doRun()
        {
            buttonPressed();
        }

        public void run()
        {
            try
            {
                doRun();
            }
            finally
            {
                synchronized (this)
                {
                    if (Thread.currentThread().equals(runner))
                    {
                        runner = null;
                        setEnabled(true);
                    }
                }
            }
        }
    }

    /**
     * The background image.
     */
    protected ImageID bgImageID;

    /**
     * The rollover image
     */
    protected ImageID bgRolloverImageID;

    /**
     * The <tt>Call</tt> that this button controls.
     */
    protected final Call call;

    /**
     * The <tt>CallPanel</tt> which is the current ancestor of this instance and
     * which, for example, represents the full-screen display state of this
     * instance.
     */
    private CallPanel callPanel;

    /**
     * The <tt>PropertyChangeListener</tt> which listens to {@link #callPanel}
     * about changes to the values of its properties such as
     * {@link CallContainer#PROP_FULL_SCREEN}.
     */
    private final PropertyChangeListener callPanelPropertyChangeListener
        = new PropertyChangeListener()
        {
            public void propertyChange(PropertyChangeEvent ev)
            {
                AbstractCallToggleButton.this.callPanelPropertyChange(ev);
            }
        };

    /**
     * The indicator which determines whether this instance is displayed in
     * full-screen or windowed mode.
     */
    private boolean fullScreen = false;

    /**
     * The icon image.
     */
    protected ImageID iconImageID;

    /**
     * The pressed icon image.
     */
    protected ImageID pressedIconImageID;

    /**
     * The pressed image.
     */
    protected ImageID pressedImageID;

    private final boolean settingsPanel;

    /**
     * Whether we should spawn action when clicking the button in new thread.
     * Volume control buttons use this abstract button for its fullscreen view
     * and don't need the new thread. Default is true, create new thread.
     */
    private boolean spawnActionInNewThread = true;

    /**
     * Initializes a new <tt>AbstractCallToggleButton</tt> instance which is to
     * control a toggle action for a specific <tt>Call</tt>.
     *
     * @param call the <tt>Call</tt> to be controlled by the instance
     * @param settingsPanel indicates if this button is added in the settings
     * panel on the bottom of the call window
     * @param selected <tt>true</tt> if the new toggle button is to be initially
     * selected; otherwise, <tt>false</tt>
     * @param iconImageID the <tt>ImageID</tt> of the image to be used as the
     * icon of the new instance
     * @param pressedIconImageID the <tt>ImageID</tt> of the image to be used
     * as the icon in the pressed button state of the new instance
     * @param toolTipTextKey the key in the <tt>ResourceManagementService</tt>
     * of the internationalized string which is to be used as the tool tip text
     * of the new instance
     */
    protected AbstractCallToggleButton(
            Call call,
            boolean settingsPanel,
            boolean selected,
            ImageID iconImageID,
            ImageID pressedIconImageID,
            String toolTipTextKey)
    {
        this.call = call;

        this.iconImageID = iconImageID;
        this.pressedIconImageID = pressedIconImageID;
        this.settingsPanel = settingsPanel;

        if(settingsPanel)
        {
            bgRolloverImageID = ImageLoader.CALL_SETTING_BUTTON_BG;
            pressedImageID = ImageLoader.CALL_SETTING_BUTTON_PRESSED_BG;
        }
        else
        {
            bgImageID = ImageLoader.SOUND_SETTING_BUTTON_BG;
            bgRolloverImageID = ImageLoader.SOUND_SETTING_BUTTON_BG;
            pressedImageID = ImageLoader.SOUND_SETTING_BUTTON_PRESSED;
        }

        if (toolTipTextKey != null)
        {
            setToolTipText(
                GuiActivator.getResources().getI18NString(toolTipTextKey));
        }

        setModel(new CallToggleButtonModel(call));

        /*
         * AbstractCallToggleButton is dependent on whether it is displayed in
         * full-screen or windowed mode. Because AbstractCallToggleButton is
         * associated with a Call and because we know Calls are depicted by
         * CallPanels, keep track of the CallPanel in which this instance is
         * added and use the full-screen state of the CallPanel.
         */
        addHierarchyListener(
                new HierarchyListener()
                {
                    public void hierarchyChanged(HierarchyEvent ev)
                    {
                        AbstractCallToggleButton.this.hierarchyChanged(ev);
                    }
                });
        hierarchyChanged(null);

        setSelected(selected);

        // All items are now instantiated and could safely load the skin.
        loadSkin();
    }

    /**
     * Initializes a new <tt>AbstractCallToggleButton</tt> instance which is to
     * control a toggle action for a specific <tt>Call</tt>.
     *
     * @param call the <tt>Call</tt> to be controlled by the instance
     * @param selected <tt>true</tt> if the new toggle button is to be initially
     * selected; otherwise, <tt>false</tt>
     * @param iconImageID the <tt>ImageID</tt> of the image to be used as the
     * icon of the new instance
     * @param toolTipTextKey the key in the <tt>ResourceManagementService</tt>
     * of the internationalized string which is to be used as the tool tip text
     * of the new instance
     */
    protected AbstractCallToggleButton(
            Call call,
            boolean selected,
            ImageID iconImageID,
            String toolTipTextKey)
    {
        this(call, true, selected, iconImageID, null, toolTipTextKey);
    }

    /**
     * Notifies this <tt>AbstractCallToggleButton</tt> that its associated
     * action has been performed and that it should execute its very logic.
     */
    public abstract void buttonPressed();

    /**
     * Notifies this instance about a <tt>PropertyChangeEvent</tt> fired by
     * {@link #callPanel}.
     *
     * @param ev the <tt>PropertyChangeEvent</tt> fired by <tt>callPanel</tt> to
     * notify this instance about
     */
    private void callPanelPropertyChange(PropertyChangeEvent ev)
    {
        if ((ev == null)
                || CallContainer.PROP_FULL_SCREEN.equals(ev.getPropertyName()))
        {
            boolean fullScreen
                = (callPanel == null) ? false : callPanel.isFullScreen();

            if (this.fullScreen != fullScreen)
            {
                this.fullScreen = fullScreen;

                loadSkin();
            }
        }
    }

    /**
     * Notifies this instance that the UI hierarchy that it belongs to has been
     * changed.
     *
     * @param ev an <tt>HierarchyEvent</tt> which identifies the specific of the
     * change in the UI hierarchy that this instance belongs
     */
    private void hierarchyChanged(HierarchyEvent ev)
    {
        /*
         * Keep track of the CallPanel which is the current ancestor of this
         * instance and its full-screen display state.
         */

        CallPanel callPanel = null;

        for (Container parent = getParent();
                parent != null;
                parent = parent.getParent())
        {
            if (parent instanceof CallPanel)
            {
                callPanel = (CallPanel) parent;
                break;
            }
        }

        if (this.callPanel != callPanel)
        {
            if (this.callPanel != null)
            {
                this.callPanel.removePropertyChangeListener(
                        CallContainer.PROP_FULL_SCREEN,
                        callPanelPropertyChangeListener);
            }

            this.callPanel = callPanel;

            if (this.callPanel != null)
            {
                this.callPanel.addPropertyChangeListener(
                        CallContainer.PROP_FULL_SCREEN,
                        callPanelPropertyChangeListener);
            }

            /*
             * If the callPanel instance has changed, then the full-screen
             * display state that it represents may have changed from the point
             * of view of this instance.
             */
            callPanelPropertyChange(null);
        }
    }

    /**
     * Determines whether this instance is displayed in full-screen or windowed
     * mode.
     *
     * @return <tt>true</tt> if this instance is displayed in full-screen mode
     * or <tt>false</tt> for windowed mode
     */
    protected boolean isFullScreen()
    {
        return fullScreen;
    }

    /**
     * Loads images.
     */
    public void loadSkin()
    {
        int width = CallToolBarButton.DEFAULT_WIDTH;
        int height = CallToolBarButton.DEFAULT_HEIGHT;

        if (bgImageID != null)
        {
            Image bgImage = ImageLoader.getImage(bgImageID);
            setBgImage(bgImage);

            width = bgImage.getWidth(this);
            height = bgImage.getHeight(this);
        }

        setPreferredSize(new Dimension(width, height));
        setMaximumSize(new Dimension(width, height));
        setMinimumSize(new Dimension(width, height));

        setBgRolloverImage(ImageLoader.getImage(bgRolloverImageID));
        setPressedImage(ImageLoader.getImage(pressedImageID));

        boolean fullScreen = isFullScreen();

        if (iconImageID != null)
        {
            Image iconImage = ImageLoader.getImage(iconImageID);

            if (!fullScreen && !settingsPanel)
            {
                iconImage
                    = ImageUtils.scaleImageWithinBounds(iconImage, 18, 18);
            }
            setIconImage(iconImage);
        }

        if (pressedIconImageID != null)
        {
            Image iconImage = ImageLoader.getImage(pressedIconImageID);

            if (!fullScreen && !settingsPanel)
            {
                iconImage
                    = ImageUtils.scaleImageWithinBounds(iconImage, 18, 18);
            }
            setPressedIconImage(iconImage);
        }
    }

    /**
     * Sets the icon image of this button.
     *
     * @param iconImageID the identifier of the icon image
     */
    public void setIconImageID(ImageID iconImageID)
    {
        this.iconImageID = iconImageID;

        Image iconImage = ImageLoader.getImage(iconImageID);

        if (!isFullScreen() && !settingsPanel)
            iconImage = ImageUtils.scaleImageWithinBounds(iconImage, 18, 18);
        setIconImage(iconImage);
    }

    /**
     * Changes behavior, whether we should start new thread for executing
     * actions, buttonPressed().
     *
     * @param spawnActionInNewThread
     */
    public void setSpawnActionInNewThread(boolean spawnActionInNewThread)
    {
        this.spawnActionInNewThread = spawnActionInNewThread;
    }
}


text:
@interface EditItemViewController : UIViewController <UITextFieldDelegate>

@property (nonatomic, strong) id item;
@property (nonatomic, assign) BOOL editingMode;
@property (nonatomic, assign) BOOL blurBackground;
@property (weak, nonatomic) IBOutlet UITextField *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *valueTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *valueUnitsLabel;
@property (weak, nonatomic) IBOutlet UITextField *valueField;
@property (weak, nonatomic) IBOutlet UILabel *carbsTitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *carbsUnitsLabel;
@property (weak, nonatomic) IBOutlet UITextField *carbsField;

@property(strong, nonatomic) ANBlurredImageView* blur;
@property (weak, nonatomic) IBOutlet UIButton *dateButton;

- (IBAction)doneClicked:(id)sender;
- (IBAction)dateClicked:(id)sender;
@end


text:
class CreateScValues < ActiveRecord::Migration
  def change
    create_table :sc_values do |t|
      t.belongs_to :contract, index: true
      t.string :key
      t.string :value

      t.timestamps null: false
    end
    add_foreign_key :sc_values, :contracts
  end
end


text:
Rails.application.routes.draw do

  root 'events#index'

  get '/events/category/:category_id' => 'events#index'

  resources :events do
  	resources :comments, only: [:create, :destroy]
  end

  resources :categories

  post '/euvou/:attended_event_id' => 'eu_vous#create'

  delete '/euvou/:attended_event_id' => 'eu_vous#destroy'

  post '/report/:reported_event_id' => 'reports#create'

  delete '/report/:reported_event_id' => 'reports#destroy'

  match '/profile/:id/finish_signup' => 'users#finish_signup', via: [:get, :patch], :as => :finish_signup
  match '/profile/:id' => 'users#user_show', via: [:get, :patch], :as => :user_show
  devise_for :users, :controllers => { registration: 'registration', omniauth_callbacks: 'omniauth_callbacks' }

end


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Microsoft.AspNetCore.Identity;

namespace Aranasoft.Cobweb.EntityFrameworkCore.Validation.Tests.Support {
    public class TableBasedEntity {
        [Key]
        public int Id { get; set; }

        [NotMapped]
        public string IgnoredColumn { get; set; }

        [MaxLength(256)]
        public string Field { get; set; }

        [Column("NumberValue")]
        public decimal Number { get; set; }

        [Required]
        public IdentityRole<int> Role { get; set; }

        public int ComputedNumber { get;set; }

        public int ComputedAndStoredNumber { get;set; }
    }
}


text:
import { Configuration, Linter, LintResult } from 'tslint';
import { Program, getPreEmitDiagnostics, Diagnostic } from 'typescript';
import { BuildContext } from '../util/interfaces';
import { isObject } from 'util';

export interface LinterOptions {
  typeCheck?: boolean;
}

export interface LinterConfig {
  [key: string]: any;
}

/**
 * Lint a file according to config
 * @param {Linter} linter
 * @param {LinterConfig} config
 * @param {string} filePath
 * @param {string} fileContents
 */
export function lint(linter: Linter, config: LinterConfig, filePath: string, fileContents: string): void {
  linter.lint(filePath, fileContents, config as any);
}

/**
 * Get the linter result
 * @param {Linter} linter
 * @return {LintResult}
 */
export function getLintResult(linter: Linter): LintResult {
  return linter.getResult();
}

/**
 * Type check a TS program
 * @param {BuildContext} context
 * @param {Program} program
 * @param {LinterOptions} linterOptions
 * @return {Promise<Diagnostic[]>}
 */
export function typeCheck(context: BuildContext, program: Program, linterOptions?: LinterOptions): Promise<Diagnostic[]> {
  if (isObject(linterOptions) && linterOptions.typeCheck) {
    return Promise.resolve(getPreEmitDiagnostics(program));
  }
  return Promise.resolve([]);
}

/**
 * Create a TS program based on the BuildContext {rootDir} or TS config file path (if provided)
 * @param {BuildContext} context
 * @param {string} tsConfig
 * @return {Program}
 */
export function createProgram(context: BuildContext, tsConfig: string): Program {
  return Linter.createProgram(tsConfig, context.rootDir);
}

/**
 * Get all files that are sourced in TS config
 * @param {BuildContext} context
 * @param {Program} program
 * @return {Array<string>}
 */
export function getFileNames(context: BuildContext, program: Program): string[] {
  return Linter.getFileNames(program);
}

/**
 * Get lint configuration
 * @param {string} tsLintConfig
 * @param {LinterOptions} linterOptions
 * @return {Linter}
 */
export function getTsLintConfig(tsLintConfig: string, linterOptions?: LinterOptions): LinterConfig {
  const config = Configuration.loadConfigurationFromPath(tsLintConfig);
  Object.assign(config, isObject(linterOptions) ? {linterOptions} : {});
  return config;
}

/**
 * Create a TS linter
 * @param {BuildContext} context
 * @param {Program} program
 * @return {Linter}
 */
export function createLinter(context: BuildContext, program: Program): Linter {
  return new Linter({
    fix: false
  }, program);
}


text:
require 'json'

class Repository

  attr_accessor :url

  JSON_HEADERS = {'Accept'=>'application/json', 'Content-Type'=>'application/json'}

  def initialize(url, logger)
    @url = url
    @logger = logger
  end

  def find_by_uuid(uuid)
    @logger.debug "Repository.find_by_uuid(#{uuid})"
    begin
      response = RestClient.get(@url+"/#{uuid}", JSON_HEADERS)
      JSON.parse response.body
    rescue => e
      @logger.error format_error(e.backtrace)
      e.to_json
    end
  end

  def find(params)
    headers = JSON_HEADERS
    headers[:params] = params unless params.empty?
    method = "Repository.find(#{params})"
    @logger.debug(method) {"headers #{headers}"}
    @logger.debug(method) {"calling #{@url}"}

    begin
      response = RestClient.get(@url, headers)
      @logger.debug(method) {"response=#{response}"}
      services_or_functions = JSON.parse(response.body)
      case response.code.to_i
      when 200
        {status: 200, count: services_or_functions.count, items: services_or_functions, message:"OK"}
      when 400
      when 404
        {status: 200, count: 0, items: [], message:"OK"}
      else
        {status: 500, count: 0, items: [], message:"Internal Error"}
      end
    rescue => e
      @logger.error(method) {"response=#{response}"}
      @logger.error(method) {e.backtrace.each {|l| puts l}} #format_error(e.backtrace)
      {status: 500, count: 0, items: [], message: "#{e.backtrace.join("\n\t")}"}
    end
  end

  private

  def format_error(backtrace)
    first_line = backtrace[0].split(":")
    "In "+first_line[0].split("/").last+", "+first_line.last+": "+first_line[1]
  end
end


text:
from __future__ import unicode_literals

import os

from jms_utils.paths import ChDir
import pytest

from pyupdater.utils import (check_repo,
                             convert_to_list,
                             EasyAccessDict,
                             get_hash,
                             get_mac_dot_app_dir,
                             get_package_hashes,
                             parse_platform,
                             remove_dot_files,
                             Version
                             )
from pyupdater.utils.exceptions import UtilsError, VersionError
from pyupdater.utils.package import Patch, Package

TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'test data',
                             'patcher-test-data')

@pytest.mark.usefixtures('cleandir')
class TestUtils(object):

    @pytest.fixture()
    def hasher(self):
        with open('hash-test.txt', 'w') as f:
            f.write('I should find some lorem text' * 123)
        return None

    def test_check_repo_fail(self):
        with pytest.raises(SystemExit):
            check_repo()

    def test_convert_to_list(self):
        assert isinstance(convert_to_list('test'), list)
        assert isinstance(convert_to_list(('test', 'test2')), list)
        assert isinstance(convert_to_list(['test']), list)

    def test_convert_to_list_default(self):
        assert isinstance(convert_to_list({}, default=[]), list)

    def test_package_hash(self, hasher):
        digest = ('cb44ec613a594f3b20e46b768c5ee780e0a9b66ac'
                  '6d5ac1468ca4d3635c4aa9b')
        assert digest == get_package_hashes('hash-test.txt')

    def test_get_hash(self):
        digest = ('380fd2bf3d78bb411e4c1801ce3ce7804bf5a22d79'
                  '405d950e5d5c8f3169fca0')
        assert digest == get_hash('Get this hash please')

    def test_get_mac_app_dir(self):
        main = 'Main'
        path = os.path.join(main, 'Contents', 'MacOS', 'app')
        assert get_mac_dot_app_dir(path) == main

    def test_easy_access_dict(self):
        good_data = {'test': True}
        easy = EasyAccessDict()
        assert easy('bad-key') is None
        good_easy = EasyAccessDict(good_data)
        assert good_easy.get('test') is True
        assert good_easy.get('no-test') is None

    def test_parse_platform(self):
        assert parse_platform('app-mac-0.1.0.tar.gz') == 'mac'
        assert parse_platform('app-win-1.0.0.zip') == 'win'
        assert parse_platform('Email Parser-mac-0.2.0.tar.gz') == 'mac'

    def test_parse_platform_fail(self):
        with pytest.raises(UtilsError):
            parse_platform('app-nex-1.0.0.tar.gz')

    def test_remove_dot_files(self):
        bad_list = ['.DS_Store', 'test', 'stuff', '.trash']
        good_list = ['test', 'stuff']
        for n in remove_dot_files(bad_list):
            assert n in good_list

    def test_version(self):
        v1 = Version('1.1b1')
        v2 = Version('1.1')
        assert v2 > v1
        v3 = Version('1.2.1b1')
        v4 = Version('1.2.1')
        assert v3 < v4
        v5 = Version('1.2.1a1')
        v6 = Version('1.2.1a2')
        assert v5 < v6
        assert Version('5.0') == Version('5.0')
        assert Version('4.5') != Version('5.1')
        with pytest.raises(VersionError):
            Version('1')
        with pytest.raises(VersionError):
            Version('1.1.1.1')

    def test_package_1(self):
        test_file_1 = 'jms-mac-0.0.1.zip'
        with ChDir(TEST_DATA_DIR):
            p1 = Package(test_file_1)

        assert p1.name == 'jms'
        assert p1.version == '0.0.1.2.0'
        assert p1.filename == test_file_1
        assert p1.platform == 'mac'
        assert p1.info['status'] is True

    def test_package_ignored_file(self):
        with open('.DS_Store', 'w') as f:
            f.write('')
        p = Package('.DS_Store')
        assert p.info['status'] is False

    def test_package_bad_extension(self):
        test_file_2 = 'pyu-win-0.0.2.bzip2'
        with ChDir(TEST_DATA_DIR):
            p2 = Package(test_file_2)

        assert p2.filename == test_file_2
        assert p2.name is None
        assert p2.version is None
        assert p2.info['status'] is False
        assert p2.info['reason'] == ('Not a supported archive format: '
                                     '{}'.format(test_file_2))

    def test_package_bad_version(self):
        with ChDir(TEST_DATA_DIR):
            p = Package('pyu-win-1.tar.gz')
        assert p.info['reason'] == 'Package version not formatted correctly'

    def test_package_bad_platform(self):
        with ChDir(TEST_DATA_DIR):
            p = Package('pyu-wi-1.1.tar.gz')
        assert p.info['reason'] == 'Package platform not formatted correctly'

    def test_package_ignored_file(self):
        test_file_3 = '.DS_Store'
        with ChDir(TEST_DATA_DIR):
            Package(test_file_3)

    def test_package_missing(self):
        test_file_4 = 'jms-nix-0.0.3.tar.gz'
        with ChDir(TEST_DATA_DIR):
            Package(test_file_4)

    def test_patch(self):
        with open('app.py', 'w') as f:
            f.write('a = 0')

        info = {
            'dst': 'app.py',
            'patch_name': 'p-name-1',
            'package': 'filename-mac-0.1.1.tar.gz'
            }
        p = Patch(info)
        assert p.ready is True

    def test_patch_bad_info(self):
        info = {
            'dst': 'app.py',
            'patch_name': 'p-name-1',
            'package': 'filename-mac-0.1.1.tar.gz'
            }
        temp_dst = info['dst']
        info['dst'] = None
        p = Patch(info)
        assert p.ready is False

        info['dst'] = temp_dst
        temp_patch = info['patch_name']
        info['patch_name'] = None
        p = Patch(info)
        assert p.ready is False

        info['patch_name'] = temp_patch
        info['package'] = None
        p = Patch(info)
        assert p.ready is False


text:
package com.welhome.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.welhome.domain.account.Account;
import com.welhome.repositories.accounts.AccountsRepository;

@Service
public class AccountDetailsService implements UserDetailsService{

	private final AccountsRepository repository;

	@Autowired
	public AccountDetailsService(AccountsRepository repository) {
		this.repository = repository;
	}

	@Override
	public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
		Account account = this.repository.findByName(name);
		return new User(account.getName(), account.getPassword(), AuthorityUtils.createAuthorityList(account.getRoles()));
	}

}


text:
package com.adatar.requesthandler;

import com.adatar.service.BookService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.adatar.resourceloader.BooksFileLoader;
import com.adatar.resourceloader.dtos.BookDto;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
class SearchRequestHandler {

    @Autowired
    private BookService bookService;

    @RequestMapping(value = "/book/isbn/{isbn}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getBook(@PathVariable String isbn){

        return bookService.serviceRequest(isbn);
    }

    @RequestMapping(value = "/book/default", produces = MediaType.APPLICATION_JSON_VALUE)
    public BookDto getBook(){

        BookDto book = new BookDto();
        book.setISBN("A123456");
        book.setTitle("CS 101 For Dummies");
        book.setPublisher("Dummy");
        book.setYear(2016);
        book.setImage_s("www.yahoo.com");
        book.setImage_m("www.bing.com");
        book.setImage_l("www.google.com");

        return book;

    }
}


text:
import com.maxeler.LMemLoopback.LMemLoopbackService;

import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/** LMemLoopback BasicStatic example. */
public final class LMemLoopbackClient {

  /** Server port. */
  private static final int PORT = 9090;

  /** Size of int in bytes. */
  private static final int SIZE_OF_INT_IN_BYTES = 4;

  /** Size of int in bits. */
  private static final int SIZE_OF_INT = 32;

  /** Number of nano seconds in one second. */
  private static final int NUM_OF_NANO_SECONDS = 1000000000;

  /** Utility classes should not have a public or default constructor. */
  private LMemLoopbackClient() { }

  /**
   * Checks if lmemLoopbackDfe and lmemLoopbackCpu are the same.
   *
   * @param size       Size
   * @param dataOutDfe Out data from DFE
   * @param dataOutCpu Out data from CPU
   *
   * @return status Number of elements that doesn't match
   */
  public static int check(final List<Integer> dataOutDfe,
                           final List<Integer> dataOutCpu, final int size) {
    int status = 0;

    for (int i = 0; i < size; i++) {
      if (!dataOutDfe.get(i).equals(dataOutCpu.get(i))) {
        System.out.println(
            "Output data @ " + i + " = " + dataOutDfe.get(i)
            + " (expected " + dataOutCpu.get(i) + ")");

        status++;
      }
    }

    return status;
  }

  /**
   * LMemLoopback on CPU. outData = inA + inB
   *
   * @param size    Size
   * @param inA     In A
   * @param inB     In B
   *
   * @return        Out data
   */
  public static List<Integer> lmemLoopbackCpu(
      final int size, final List<Integer> inA, final List<Integer> inB) {
    List<Integer> outData = new ArrayList<Integer>();
    DecimalFormat timeFormat = new DecimalFormat("#0.00000");

    for (int i = 0; i < size; i++) {
      outData.add(inA.get(i) + inB.get(i));
    }

    return outData;
  }

  /**
   * LMemLoopback on DFE. outData = inA + inB
   *
   * @param size    Size
   * @param inA     In A
   * @param inB     In B
   *
   * @return        Out data
   */
  public static List<Integer> lmemLoopbackDfe(
      final int size, final List<Integer> inA, final List<Integer> inB) {
    List<Integer> outData = new ArrayList<Integer>();
    DecimalFormat timeFormat = new DecimalFormat("#0.00000");

    double startTime = System.nanoTime();
    double estimatedTime;
    int sizeBytes = size * SIZE_OF_INT_IN_BYTES;

    // Make socket
    TTransport transport;
    transport = new TSocket("localhost", PORT);

    // Wrap in a protocol
    TProtocol protocol = new  TBinaryProtocol(transport);

    // Create a client to use the protocol encoder
    LMemLoopbackService.Client client =
        new LMemLoopbackService.Client(protocol);

    estimatedTime = (System.nanoTime() - startTime)
                         / NUM_OF_NANO_SECONDS;
    System.out.println("Creating a client:\t\t\t\t\t"
                       + timeFormat.format(estimatedTime) + "s");
    try {
      // Connect!
      startTime = System.nanoTime();
      transport.open();
      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("Opening connection:\t\t\t\t\t"
                           + timeFormat.format(estimatedTime) + "s");

      // Allocate and send input streams to server
      startTime = System.nanoTime();
      final long addressInA = client.malloc_int32_t(size);
      client.send_data_int32_t(addressInA, inA);

      final long addressInB = client.malloc_int32_t(size);
      client.send_data_int32_t(addressInB, inB);

      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("Sending input data:\t\t\t\t\t"
                           + timeFormat.format(estimatedTime) + "s");

      // Allocate memory for output stream on server
      startTime = System.nanoTime();
      final long addressOutData = client.malloc_int32_t(size);
      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("Allocating memory for output stream on server:\t"
                           + timeFormat.format(estimatedTime) + "s");

      // Write to LMem
      startTime = System.nanoTime();
      client.LMemLoopback_writeLMem(0, sizeBytes, addressInA);
      client.LMemLoopback_writeLMem(sizeBytes, sizeBytes, addressInB);
      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("Writing to LMem:\t\t\t\t\t"
                           + timeFormat.format(estimatedTime) + "s");

      // Executing action
      startTime = System.nanoTime();
      client.LMemLoopback(size);
      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("LMemLoopback time:\t\t\t\t\t"
                           + timeFormat.format(estimatedTime) + "s");

      // Read from LMem
      startTime = System.nanoTime();
      client.LMemLoopback_readLMem(2 * sizeBytes, sizeBytes, addressOutData);
      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("Reading from LMem:\t\t\t\t\t"
                           + timeFormat.format(estimatedTime) + "s");

      // Get output stream from server
      startTime = System.nanoTime();
      outData = client.receive_data_int32_t(addressOutData, size);
      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("Getting output stream:\t(size = "
                          + size * SIZE_OF_INT + " bit)\t"
                          + timeFormat.format(estimatedTime) + "s");

      // Free allocated memory for streams on server
      startTime = System.nanoTime();
      client.free(addressInA);
      client.free(addressInB);
      client.free(addressOutData);
      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("Freeing allocated memory for streams on server:\t"
                           + timeFormat.format(estimatedTime) + "s");

      // Close!
      startTime = System.nanoTime();
      transport.close();
      estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
      System.out.println("Closing connection:\t\t\t\t\t"
                           + timeFormat.format(estimatedTime) + "s");

    } catch (TException x) {
      x.printStackTrace();
      System.exit(-1);
    }

    return outData;
  }

  /**
   * Calculates lmemLoopbackDfe and lmemLoopbackCpu and
   * checks if they return the same value.
   *
   * @param args Command line arguments
   */
  public static void main(final String[] args) {
    final int size = 384;
    double startTime = System.nanoTime();
    double estimatedTime;
    final DecimalFormat timeFormat = new DecimalFormat("#0.00000");

    // Generate data
    startTime = System.nanoTime();
    List<Integer> inA = new ArrayList<Integer>();
    List<Integer> inB = new ArrayList<Integer>();

    for (int i = 0; i < size; i++) {
      inA.add(i);
      inB.add(size - i);
    }
    estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
    System.out.println("Generating input data:\t\t\t\t"
                         + timeFormat.format(estimatedTime)
                         + "s");

    // DFE Output
    startTime = System.nanoTime();
    final List<Integer> dataOutDfe = lmemLoopbackDfe(size, inA, inB);
    estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
    System.out.println("DFE LMemLoopback total time:\t\t\t"
                         + timeFormat.format(estimatedTime) + "s");

    // CPU Output
    startTime = System.nanoTime();
    final List<Integer> dataOutCpu = lmemLoopbackCpu(size, inA, inB);
    estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
    System.out.println("CPU LMemLoopback total time:\t\t\t"
                         + timeFormat.format(estimatedTime) + "s");

    // Checking results
    startTime = System.nanoTime();
    int status = check(dataOutDfe, dataOutCpu, size);
    estimatedTime = (System.nanoTime() - startTime) / NUM_OF_NANO_SECONDS;
    System.out.println("Checking results:\t\t\t\t\t"
                         + timeFormat.format(estimatedTime) + "s");
    if (status == 0) {
      System.out.println("Test passed!");
    } else {
      System.out.println("Test failed " + status + " times!");
      System.exit(-1);
    }
  }
}


text:
"""\
Grip
----

Render local readme files before sending off to GitHub.

:copyright: (c) 2014-2022 by Joe Esposito.
:license: MIT, see LICENSE for more details.
"""

import os
import sys

if __name__ == '__main__':
    sys.path.insert(1, os.path.dirname(os.path.dirname(
        os.path.abspath(__file__))))

    from grip.command import main
    main()


text:
package edu.indiana.d2i.komadu.axis2.client;

public class KomaduClientConstants {

    public static final String AGENT_USER = "agent.user";
    public static final String AGENT_GENERIC = "agent.generic";

    public static final String ACTIVITY_WORKFLOW = "activity.workflow";
    public static final String ACTIVITY_SERVICE = "activity.service";
    public static final String ACTIVITY_METHOD = "activity.method";
    public static final String ACTIVITY_GENERIC = "activity.generic";

    public static final String ENTITY_FILE = "entity.file";
    public static final String ENTITY_COLLECTION = "entity.collection";
    public static final String ENTITY_GENERIC = "entity.generic";

    public static final String WORKFLOW_ID = "workflowID";
    public static final String WORKFLOW_NODE_ID = "workflowNodeID";
    public static final String SERVICE_ID = "serviceID";
    public static final String METHOD_ID = "methodID";
    public static final String ACTIVITY_ID = "activityID";
    public static final String INSTANCE_OF_ID = "instanceOfID";
    public static final String INSTANCE_OF_VERSION = "instanceOfVersion";

    public static final String AGENT_ID = "agentID";
    public static final String AGENT_FULL_NAME = "fullName";
    public static final String AGENT_AFFILIATION = "affiliation";
    public static final String AGENT_EMAIL = "email";

    public static final String FILE_URI = "fileURI";
    public static final String FILE_OWNER = "ownerDN";
    public static final String FILE_CREATE_DATE = "createDate";
    public static final String FILE_SIZE = "size";
    public static final String FILE_NAME = "fileName";

    public static final String ENTITY_URI = "entityURI";

    public static enum Derivation {
        DERIVATION, REVISION, QUOTATION, PRIMARY_SOURCE
    }
}


text:
var Errors = require(__dirname + '/../src/errors').Errors;

var Driver = function Driver(callback) {

};

Driver.prototype.visit = function(url, callback) {
    throw Errors.NotImplementedError();
};

Driver.prototype.click = function(selector, callback) {
    throw Errors.NotImplementedError();
};

Driver.prototype.fill = function(selector, value, callback) {
    throw Errors.NotImplementedError();
};

exports.Driver = Driver;