text:
/**
 * Populates a Servlet request with a new Spring Security compliant {@code HttpServletRequestWrapper}.
 * <p>
 * To use, simply add the {@code SecurityContextHolderAwareRequestFilter} to the Spring Security filter chain.
 */
package org.springframework.security.web.servletapi;

redpajama_set_name: RedPajamaGithub


text:
/**
 * Contains the model for SPARQL-Generate and SPARQL-Template queries.
 *
 * The equivalent package in Jena is org.apache.jena.query
 */
package fr.mines_stetienne.ci.sparql_generate.query;


text:
package com.koch.ambeth.persistence.noversion.models;

import com.koch.ambeth.model.AbstractBusinessObject;

public class NoVersionExternal extends AbstractBusinessObject {
	private int id;

	private String name;

	@Override
	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}


text:
module YARD
  module Templates
    module Helpers
      module Markup
        begin require 'rdoc'; rescue LoadError; nil end
        begin
          require 'rdoc/markdown'
        rescue LoadError
          raise NameError, "could not load RDoc Markdown support (rdoc is too old)"
        end

        class RDocMarkdown < RDocMarkup
          def initialize(text)
            super RDoc::Markdown.new.parse(text)
          end

          def fix_typewriter(html) html end
        end
      end
    end
  end
end


text:
package com.google.ratel.deps.jackson.databind.util;

import java.io.*;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Helper for simple bounded LRU maps used for reusing lookup values.
 *<p>
 * Note that serialization behavior is such that contents are NOT serialized,
 * on assumption that all use cases are for caching where persistence
 * does not make sense. The only thing serialized is the cache size of Map.
 */
public class LRUMap<K,V> extends LinkedHashMap<K,V>
    implements java.io.Serializable
{
    private static final long serialVersionUID = 1L;

    protected final int _maxEntries;

    public LRUMap(int initialEntries, int maxEntries)
    {
        super(initialEntries, 0.8f, true);
        _maxEntries = maxEntries;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry<K,V> eldest)
    {
        return size() > _maxEntries;
    }

    /*
    /**********************************************************
    /* Serializable overrides
    /**********************************************************
     */

    /**
     * Ugly hack, to work through the requirement that _value is indeed final,
     * and that JDK serialization won't call ctor(s) if Serializable is implemented.
     *
     * @since 2.1
     */
    protected transient int _jdkSerializeMaxEntries;

    private void readObject(ObjectInputStream in) throws IOException {
        _jdkSerializeMaxEntries = in.readInt();
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeInt(_jdkSerializeMaxEntries);
    }

    protected Object readResolve() {
        return new LRUMap<Object,Object>(_jdkSerializeMaxEntries, _jdkSerializeMaxEntries);
    }
}


text:
local random = require 'lqc.random'
local lqc = require 'lqc.quickcheck'
local Gen = require 'lqc.generator'
local char = require 'lqc.generators.char'
local char_gen = char()

-- NOTE: The shrink algorithms are *heavily* based on triq
--       https://github.com/krestenkrab/triq

--- Determines how many items to shrink.
-- @param length size of the string
-- @return integer indicating how many items to shrink
local function shrink_how_many(length)
  -- 20% chance more than 1 member is shrunk
  if random.between(1, 5) == 1 then
    return random.between(1, length)
  end

  return 1
end

--- Replaces a character in the string 'str' at index 'idx' with 'new_char'.
-- @param str string to be modified
-- @param new_char value that will replace the old character in the string
-- @param idx position in the string where the character should be replaced
-- @return updated string
local function string_replace_char(str, new_char, idx)
  local result = {}
  result[1] = string.sub(str, 1, idx - 1)
  result[2] = new_char
  result[3] = string.sub(str, idx + 1)
  return table.concat(result)
end

--- Replaces 1 character at a random location in the string, tries up to 100
--  times if shrink gave back same result.
-- @param prev previously generated string value
-- @param length size of the string
-- @param iterations_count remaining tries to shrink down this string
-- @return shrunk down string value
local function do_shrink_generic(prev, length, iterations_count)
  local idx = random.between(1, length)
  local old_char = string.sub(prev, idx, idx)
  local new_char = char_gen:shrink(old_char)

  if new_char == old_char and iterations_count ~= 0 then
    -- Shrink introduced no simpler result, retry at other index.
    return do_shrink_generic(prev, length, iterations_count - 1)
  end

  return string_replace_char(prev, new_char, idx)
end

--- Shrinks an amount of characters in the string.
-- @param str string to be shrunk down
-- @param length size of the string
-- @param how_many amount of characters to shrink
-- @return shrunk down string value
local function shrink_generic(str, length, how_many)
  if how_many ~= 0 then
    local new_str = do_shrink_generic(str, length, lqc.numshrinks)
    return shrink_generic(new_str, length, how_many - 1)
  end

  return str
end

--- Determines if the string should be shrunk down to a shorter string
-- @param str_len size of the string
-- @return true: string should be made shorter; false: string should remain
--               size during shrinking
local function should_shrink_smaller(str_len)
  if str_len == 0 then return false end
  return random.between(1, 5) == 1
end

--- Shrinks the string by removing 1 character
-- @param str string to be shrunk down
-- @param str_len size of the string
-- @return new string with 1 random character removed
local function shrink_smaller(str, str_len)
  local idx = random.between(1, str_len)

  -- Handle edge cases (first or last char)
  if idx == 1 then
    return string.sub(str, 2)
  end
  if idx == str_len then
    return string.sub(str, 1, idx - 1)
  end

  local new_str = {
    string.sub(str, 1, idx - 1),
    string.sub(str, idx + 1)
  }
  return table.concat(new_str)
end

--- Generates a string with a specific size.
-- @param size size of the string to generate
-- @return string of a specific size
local function do_generic_pick(size)
  local result = {}
  for _ = 1, size do
    result[#result + 1] = char_gen:pick()
  end
  return table.concat(result)
end

--- Generates a string with arbitrary length (0 <= size <= numtests).
-- @param numtests Number of times the property uses this generator; used to
--                 guide the optimization process.
-- @return string of an arbitrary size
local function arbitrary_length_pick(numtests)
  local size = random.between(0, numtests)
  return do_generic_pick(size)
end

--- Shrinks a string to a simpler form (smaller / different chars).
--  1. Returns empty strings instantly
--  2. Determine if string should be made shorter
--  2.1 if true: remove a char
--  2.2 otherwise:
--   * simplify a random amount of characters
--   * remove a char if simplify did not help
--   * otherwise return the simplified string
-- @param prev previously generated string value
-- @return shrunk down string value
local function arbitrary_length_shrink(prev)
  local length = #prev
  if length == 0 then return prev end  -- handle empty strings

  if should_shrink_smaller(length) then
    return shrink_smaller(prev, length)
  end

  local new_str = shrink_generic(prev, length, shrink_how_many(length))
  if new_str == prev then
    -- shrinking didn't help, remove an element
    return shrink_smaller(new_str, length)
  end

  -- string shrunk succesfully!
  return new_str
end

--- Helper function for generating a string with a specific size
-- @param size size of the string to generate
-- @return function that can generate strings of a specific size
local function specific_length_pick(size)
  local function do_specific_pick()
    return do_generic_pick(size)
  end
  return do_specific_pick
end

--- Shrinks a string to a simpler form (only different chars since length is fixed).
--   * "" -> ""
--   * non-empty string, shrinks upto max 5 chars of the string
-- @param prev previously generated string value
-- @return shrunk down string value
local function specific_length_shrink(prev)
  local length = #prev
  if length == 0 then return prev end  -- handle empty strings
  return shrink_generic(prev, length, shrink_how_many(length))
end

--- Generator for a string with an arbitrary size
-- @return generator for a string of arbitrary size
local function arbitrary_length_string()
  return Gen.new(arbitrary_length_pick, arbitrary_length_shrink)
end

--- Creates a generator for a string of a specific size
-- @param size size of the string to generate
-- @return generator for a string of a specific size
local function specific_length_string(size)
  return Gen.new(specific_length_pick(size), specific_length_shrink)
end

--- Creates a new ASCII string generator
-- @param size size of the string
-- @return generator that can generate the following:
--   1. size provided: a string of a specific size
--   2. no size provided: string of an arbitrary size
local function new(size)
  if size then
    return specific_length_string(size)
  end
  return arbitrary_length_string()
end

return new


text:
package io.picopalette.apps.event_me.Utils;

import android.content.Context;
import android.util.AttributeSet;
import io.picopalette.apps.event_me.R;

public class TokenTextView extends android.support.v7.widget.AppCompatTextView {

    public TokenTextView(Context context) {
        super(context);
    }
    public TokenTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    @Override
    public void setSelected(boolean selected) {
        super.setSelected(selected);
        setCompoundDrawablesWithIntrinsicBounds(0, 0, selected ? R.drawable.ic_clear_white_18dp : 0, 0);
    }
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.pigbear.hi_andgmusic.ui.play.RoundFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />

</FrameLayout>


text:
class UsersController < ApplicationController
  def index
  end

  def create
  end

  def new
  end

  def edit
  end

  def show
  end

  def update
  end
end


text:
using danek::ConfigurationException;
using danek::UidIdentifierProcessor;
using namespace testing;

namespace
{
    struct UidIdentifierProcessorMock : public UidIdentifierProcessor
    {
        void advanceCount(std::size_t n)
        {
            nextCount(n);
        }
    };
}

class UidIdentifierProcessorTest : public testing::Test
{
public:
    void SetUp() override
    {
        processor = std::make_unique<UidIdentifierProcessor>();
    }

    std::unique_ptr<UidIdentifierProcessor> processor;
};

TEST_F(UidIdentifierProcessorTest, expandString)
{
    const auto result = processor->expand("abc");
    EXPECT_THAT(result, StrEq("abc"));
}

TEST_F(UidIdentifierProcessorTest, expandWithScope)
{
    const auto result = processor->expand("a.b.c");
    EXPECT_THAT(result, StrEq("a.b.c"));
}

TEST_F(UidIdentifierProcessorTest, expandWithScopeAndUid)
{
    const auto result = processor->expand("a.uid-b.uid-0013-c");
    EXPECT_THAT(result, StrEq("a.uid-000000000-b.uid-000000001-c"));
}

TEST_F(UidIdentifierProcessorTest, expandWithUid)
{
    const auto result = processor->expand("uid-xyz");
    EXPECT_THAT(result, StrEq("uid-000000000-xyz"));
}

TEST_F(UidIdentifierProcessorTest, expandWithUidIncreasesUid)
{
    const auto result = processor->expand("uid-x.uid-y.uid-z");
    EXPECT_THAT(result, StrEq("uid-000000000-x.uid-000000001-y.uid-000000002-z"));
}

TEST_F(UidIdentifierProcessorTest, expandMaintaintsUidState)
{
    const auto result = processor->expand("uid-x");
    const auto result1 = processor->expand("uid-y");
    const auto result2 = processor->expand("uid-z33");
    EXPECT_THAT(result, StrEq("uid-000000000-x"));
    EXPECT_THAT(result1, StrEq("uid-000000001-y"));
    EXPECT_THAT(result2, StrEq("uid-000000002-z33"));
}

TEST_F(UidIdentifierProcessorTest, expandWithUidAndNumber)
{
    const auto result = processor->expand("uid-01234-xyz12");
    EXPECT_THAT(result, StrEq("uid-000000000-xyz12"));
}

TEST_F(UidIdentifierProcessorTest, expandWithWithouthUidSuffixThrows)
{
    EXPECT_THROW(processor->expand("uid-"), ConfigurationException);
    EXPECT_THROW(processor->expand("uid--"), ConfigurationException);
    EXPECT_THROW(processor->expand("uid--abc"), ConfigurationException);
    EXPECT_THROW(processor->expand("uid-9abc"), ConfigurationException);
    EXPECT_THROW(processor->expand("uid-123-"), ConfigurationException);
    EXPECT_THROW(processor->expand("uid-123--a"), ConfigurationException);
    EXPECT_THROW(processor->expand("uid-123-456a"), ConfigurationException);
    EXPECT_THROW(processor->expand("uid-9"), ConfigurationException);
}

TEST_F(UidIdentifierProcessorTest, expandThrowsIfNineDigitsAreExceeded)
{
    UidIdentifierProcessorMock mock;
    mock.advanceCount(1'000'000'000);
    EXPECT_THROW(mock.expand("uid-00000-abc"), std::domain_error);
}

TEST_F(UidIdentifierProcessorTest, unexpandString)
{
    const auto result = processor->unexpand("abc");
    EXPECT_THAT(result, StrEq("abc"));
}

TEST_F(UidIdentifierProcessorTest, unexpandWithScope)
{
    const auto result = processor->unexpand("a.b.c");
    EXPECT_THAT(result, StrEq("a.b.c"));
}

TEST_F(UidIdentifierProcessorTest, unexpandWithScopeAndUid)
{
    const auto result = processor->unexpand("a.uid-000000000-b.uid-000000001-c");
    EXPECT_THAT(result, StrEq("a.uid-b.uid-c"));
}

TEST_F(UidIdentifierProcessorTest, unexpandWithUid)
{
    const auto result = processor->unexpand("uid-xyz");
    EXPECT_THAT(result, StrEq("uid-xyz"));
}

TEST_F(UidIdentifierProcessorTest, unexpandWithUidAndNumber)
{
    const auto result = processor->unexpand("uid-000000003-xyz");
    EXPECT_THAT(result, StrEq("uid-xyz"));
}

TEST_F(UidIdentifierProcessorTest, unexpandWithUidAndUidWithNumbers)
{
    const auto result = processor->unexpand("uid-000000000-x.uid-y.uid-000000002-z");
    EXPECT_THAT(result, StrEq("uid-x.uid-y.uid-z"));
}

TEST_F(UidIdentifierProcessorTest, unexpandWithDifferentUid)
{
    const auto result1 = processor->unexpand("uid-000000000-x");
    const auto result2 = processor->unexpand("uid-000000001-y");
    const auto result3 = processor->unexpand("uid-000000002-z");
    EXPECT_THAT(result1, StrEq("uid-x"));
    EXPECT_THAT(result2, StrEq("uid-y"));
    EXPECT_THAT(result3, StrEq("uid-z"));
}


text:
package com.englishtown.promises.impl;

import com.englishtown.promises.Scheduler;

import javax.inject.Inject;
import javax.inject.Provider;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;

/**
 * Default implementation of {@link com.englishtown.promises.Scheduler}
 */
public class DefaultScheduler implements Scheduler {

    private final Executor _enqueue;
    private final Queue<Runnable> _handlerQueue;
    private final Queue<Runnable> _afterQueue;
    private boolean _running;

    @Inject
    public DefaultScheduler(Provider<Executor> enqueue) {
        this._enqueue = enqueue.get();
        this._handlerQueue = new ConcurrentLinkedQueue<>();
        this._afterQueue = new ConcurrentLinkedQueue<>();
        this._running = false;
    }

    /**
     * Enqueue a task. If the queue is not currently scheduled to be
     * drained, schedule it.
     *
     * @param task task to be run
     */
    @Override
    public void enqueue(Runnable task) {
        this._handlerQueue.add(task);
        if (!this._running) { // TODO: sync
            this._running = true;
            this._enqueue.execute(this::drain);
        }
    }

    @Override
    public void afterQueue(Runnable task) {
        this._afterQueue.add(task);
        if (!this._running) {
            this._running = true;
            this._enqueue.execute(this::drain);
        }
    }

    /**
     * Drain the handler queue entirely, being careful to allow the
     * queue to be extended while it is being processed, and to continue
     * processing until it is truly empty.
     */
    public void drain() {
        Queue<Runnable> q = this._handlerQueue;
        Runnable task = q.poll();

        while (task != null) {
            task.run();
            task = q.poll();
        }

        this._running = false;

        q = this._afterQueue;
        task = q.poll();
        while (task != null) {
            task.run();
            task = q.poll();
        }
    }

}


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>
PolicySpi (Java Platform SE 6)
</TITLE>

<META NAME="date" CONTENT="2007-03-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

java.security

类 PolicySpi

java.lang.Object
  java.security.PolicySpi

public abstract class PolicySpi
extends Object

此类为 Policy 类定义服务提供者接口 (SPI)。每个想要提供 Policy 实现的服务提供者都必须实现此类中的所有抽象方法。

 此抽象类的子类实现必须提供可将 Policy.Parameters 对象作为输入参数的公共构造方法。如果此构造方法不理解 Policy.Parameters 输入,它同样必须抛出 IllegalArgumentException。

从以下版本开始:

1.6

构造方法摘要

PolicySpi()

方法摘要

protected  PermissionCollection
engineGetPermissions(CodeSource codesource)

          返回包含授予指定 CodeSource 的权限集的 PermissionCollection 对象。

protected  PermissionCollection
engineGetPermissions(ProtectionDomain domain)

          返回包含授予指定 ProtectionDomain 的权限集的 PermissionCollection 对象。

protected abstract  boolean
engineImplies(ProtectionDomain domain,
              Permission permission)

          检查该策略是否已将 Permission 授予 ProtectionDomain。

protected  void
engineRefresh()

          刷新/重载策略配置。

从类 java.lang.Object 继承的方法

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

构造方法详细信息

PolicySpi

public PolicySpi()

方法详细信息

engineImplies

protected abstract boolean engineImplies(ProtectionDomain domain,
                                         Permission permission)

检查该策略是否已将 Permission 授予 ProtectionDomain。

参数:
domain - 要检查的 ProtectionDomain。
permission - 检查是否已将此权限授予指定的域。

返回:
如果已将此权限授予该域,则返回 boolean 值 true。

engineRefresh

protected void engineRefresh()

刷新/重载策略配置。此方法的行为取决于实现。例如,对基于文件的策略调用 refresh 将导致重新读取该文件。

 此方法的默认实现不执行任何操作。如果策略实现支持刷新操作,则应该重写此方法。

engineGetPermissions

protected PermissionCollection engineGetPermissions(CodeSource codesource)

返回包含授予指定 CodeSource 的权限集的 PermissionCollection 对象。

 此方法的默认实现返回 Policy.UNSUPPORTED_EMPTY_COLLECTION 对象。如果策略实现可以返回授予 CodeSource 的权限集,则可以重写此方法。

参数:
codesource - 授予了返回 PermissionCollection 的 CodeSource。

返回:
授予指定 CodeSource 的权限集。如果支持此操作,则返回的权限集必须是可变的新实例,并且它必须支持不同的 Permission 类型。如果不支持此操作,则返回 Policy.UNSUPPORTED_EMPTY_COLLECTION。

engineGetPermissions

protected PermissionCollection engineGetPermissions(ProtectionDomain domain)

返回包含授予指定 ProtectionDomain 的权限集的 PermissionCollection 对象。

 此方法的默认实现返回 Policy.UNSUPPORTED_EMPTY_COLLECTION 对象。如果策略实现可以返回授予 ProtectionDomain 的权限集,则可以重写此方法。

参数:
domain - 授予了返回 PermissionCollection 的 ProtectionDomain。

返回:
授予指定 ProtectionDomain 的权限集。如果支持此操作,则返回的权限集必须是可变的新实例,并且它必须支持不同的 Permission 类型。如果不支持此操作,则返回 Policy.UNSUPPORTED_EMPTY_COLLECTION。

      概述
      软件包
    类
      使用
      树
      已过时
      索引
      帮助

JavaTM Platform
Standard Ed. 6

 上一个类
 下一个类

  框架
 无框架

  所有类

  摘要: 嵌套 | 字段 | 构造方法 | 方法

详细信息: 字段 | 构造方法 | 方法

提交错误或意见
有关更多的 API 参考资料和开发人员文档,请参阅 Java SE 开发人员文档。该文档包含更详细的、面向开发人员的描述,以及总体概述、术语定义、使用技巧和工作代码示例。
版权所有 2007 Sun Microsystems, Inc. 保留所有权利。 请遵守许可证条款。另请参阅文档重新分发政策。


text:
@interface GalleryViewPhotoSource : TTURLRequestModel <TTPhotoSource> {
 @private
  NSDictionary *_context;
  NSString *_title;
  NSMutableArray *_galleryItems;
}
@property (nonatomic, strong) NSDictionary *context;
@property (nonatomic, strong) NSMutableArray *galleryItems;
@property (nonatomic, copy) NSString *title;
- (id)initWithContext:(NSString*)contextId;
- (void)loadArts;
- (void)loadMoreArtsIfNeeded:(GalleryItem *)item;
@end


text:
dir_here="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
dir_bin="$(dirname "${dir_here}")"
dir_project_root=$(dirname "${dir_bin}")

source ${dir_bin}/py/python-env.sh

${open_command} ${path_sphinx_index_html}


text:
#include "Element.h"

#include "Comment.h"

QUML_BEGIN_NAMESPACE_UK

QHash<QString, Element*> Element::mElementsById;

Element::Element() {
    mElementsById.insert(uniqueId(), this);

    elementChanged += [=] {
        this->childElementChanged();
        if(this->parent())
            this->parent()->childElementChanged();
    };
}

Element::Element(const Element&) {
    NYI();
    mElementsById.insert(uniqueId(), this);
}

Element::~Element() {
    mElementsById.remove(uniqueId());
}

QString Element::uniqueId() const {
    return mUniqueId.toString();
}

void Element::setUniqueId(const QString& s) {
    mElementsById.remove(uniqueId());
    mUniqueId = s;
    mElementsById.insert(s, this);
}

Element* Element::byId(const QString& s) {
    auto it = mElementsById.find(s);
    return it == mElementsById.end() ? nullptr : *it;
}

QUML_END_NAMESPACE_UK


text:
import pkg from './package.json';

// Typescript creates the commonJS package, let rollup do the rest

export default [
  // browser-friendly UMD build
  {
    input: 'dist/index.js',
    output: {
      file: pkg.browser,
      format: 'umd',
      name: 'maquetteCssTransitions'
    },
    plugins: []
  },
  // CommonJS build for nodeJS
  {
    input: 'dist/index.js',
    output: {
      file: pkg.main,
      format: 'cjs'
    }
  }
];


text:
package com.qingbo.gingko.integration.shiro.aop;

import org.apache.shiro.aop.AnnotationResolver;
import org.apache.shiro.authz.aop.AuthorizingAnnotationMethodInterceptor;

public class MyAdminUserAnnotationMethodInterceptor extends AuthorizingAnnotationMethodInterceptor {

    public MyAdminUserAnnotationMethodInterceptor() {
        super( new MyAdminUserAnnotationHandler() );
    }

    public MyAdminUserAnnotationMethodInterceptor(AnnotationResolver resolver) {
        super(new MyAdminUserAnnotationHandler(), resolver);
    }
}


text:
package flca.xlsx.util;

import java.beans.IntrospectionException;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

class ReflectionHelper extends AbstractXlsxUtils {

	private static final Logger LOGGER = Logger.getLogger(ReflectionHelper.class.getName());

	private static final String DELIM = ",";

	private XlsxConvertUtils convertUtils;
	private Map<Byte, XlsxDataHash> xlsDataMap = null;
	private byte activeSheetNr;

	ReflectionHelper(byte activeSheetNr, Map<Byte, XlsxDataHash> xlsDataMap, XlsxConvertUtils convertUtils) {
		super();
		this.activeSheetNr = activeSheetNr;
		this.convertUtils = convertUtils;
		this.xlsDataMap = xlsDataMap;
	}

	Object makeObject(final Class<?> clz, final int nr)
			throws XlsxSetValueException, NoSuchFieldException, SecurityException, IntrospectionException
	{
		XlsxData xlsdata = getXlsxData(clz.getName(), nr);
		if (convertUtils.canConvert(clz)) {
			return makeKnownObjectint(clz, nr, xlsdata);
		} else if (clz.isEnum()) {
			return makeEnum(clz, nr, xlsdata);
		} else {
			return makeAndFillObject(nr, xlsdata);
		}
	}

	private Object makeKnownObjectint(Class<?> clz, int nr, XlsxData xlsdata) throws IntrospectionException, NoSuchFieldException,XlsxSetValueException
	{
		final String value = xlsdata.getValue(nr,  0);
		return convertUtils.convert(clz, value);
	}

	private Object makeAndFillObject(int nr, XlsxData xlsdata) throws IntrospectionException, NoSuchFieldException,XlsxSetValueException
	{
		Object target = makeInstance(xlsdata);

		int nCols = xlsdata.getNames().length;
		for (int col = 0; col < nCols; col++) {
			setValue(nr, xlsdata, target, col);
		}

		return target;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Enum makeEnum(final Class<?> clz, final int nr, final XlsxData xlsdata) {
		String enumval = xlsdata.getValue(nr, 0);
		return Enum.valueOf((Class<? extends Enum>)clz, enumval);
	}

	private void setValue(int nr, XlsxData xlsdata, Object target, int col)
			throws IntrospectionException, NoSuchFieldException, SecurityException, XlsxSetValueException {
		String propname = null;
		String value = null;
		try {
			propname = xlsdata.getNames()[col];
			value = xlsdata.getValue(nr, col);
			if (value != null) {
				Method setter = getSetter(target, propname);
				Class<?> proptyp = getPropType(setter);
				PropKind propkind = getPropertyKind(proptyp, propname);
				if (PropKind.SINGLE_PROP.equals(propkind)) {
					setPropValue(target, proptyp, setter, value);
				} else if (PropKind.ENUM_PROP.equals(propkind)) {
					setEnumValue(target, proptyp, setter, value, xlsdata);
				} else if (PropKind.SINGLE_REL.equals(propkind)) {
					setRelation(target, proptyp, setter, value);
				} else if (propkind.equals(PropKind.MULTI_REL)) {
					if (setter.getParameterTypes().length==1 && setter.getParameterTypes()[0].isArray()) {
						setArray(target, setter, value);
					} else {
						setMultiRelations(target, setter, value);
					}
				}
			}
		} catch (Exception e) {
			final String msg = "error setting propery " + propname + " with " + value;
			LOGGER.severe(msg);
			throw new XlsxSetValueException(msg, value);
		}
	}

	private Method getSetter(Object target, String propname) throws NoSuchFieldException, IntrospectionException {
		Method method = MethodHelper.getSetter(target, propname);
		if (method != null) {
			return method;
		} else {
			throw new NoSuchFieldException("No such field " + propname + " in " + target.getClass().getName());
		}

	}

	private Class<?> getGenericType(Method setter) {
		Type[] genericParameterTypes = setter.getGenericParameterTypes();
		for (int i = 0; i < genericParameterTypes.length; i++) {
			if (genericParameterTypes[i] instanceof ParameterizedType) {
				Type[] parameters = ((ParameterizedType) genericParameterTypes[i]).getActualTypeArguments();
				if (parameters != null && parameters.length == 1) {
					return (Class<?>) parameters[0];
				}
			}
		}
		return null;
	}

	private Class<?> getPropType(Method setter) throws NoSuchFieldException {
		if (setter.getParameterTypes().length == 1) {
			return setter.getParameterTypes()[0];
		} else {
			throw new NoSuchFieldException(setter.getName() + " should have exactly 1 parameter");
		}

	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void setEnumValue(Object target, Object propType, Method setter, String value, XlsxData xlsdata)
			throws XlsxSetValueException {

		try {
			if (isNumeric(value)) {
				setter.invoke(target,
						Enum.valueOf((Class<Enum>) propType, getStringValue(xlsdata, propType, Integer.valueOf(value))));
			} else {
				setter.invoke(target, Enum.valueOf((Class<Enum>) propType, value));
			}
		} catch (Exception e) {
			throw new XlsxSetValueException("Can not set enum with " + value, target);
		}
	}

	private String getStringValue(XlsxData xlsdata, Object target, int nr) {
		final XlsxData xlsEnumData = getXlsxData((Class<?>) target, nr);
		return xlsEnumData.getValue(nr, 0);
	}

	private void setPropValue(Object target, Object propType, Method setter, String value) throws XlsxSetValueException {
		if (isRefToNr(propType, value)) {
			final XlsxData xlsdata = getXlsxData((Class<?>)propType, getNr(value));
			setThePropValue(target, propType, setter, getStringValue(xlsdata, propType, getNr(value)));
		} else {
			setThePropValue(target, propType, setter, value);
		}
	}

	private boolean isRefToNr(Object propType, String value) {
		Class<?> clz =(Class<?>)propType;
		return isNumeric(value) && !clz.isPrimitive() && getXlsxData((Class<?>)propType, getNr(value)) != null;
	}

	private void setThePropValue(Object target, Object propType, Method setter, String value) throws XlsxSetValueException {
		if (convertUtils.canConvert((Class<?>) propType)) {
			try {
				setter.invoke(target, convertUtils.convert((Class<?>) propType, value));
			} catch (Exception e) {
				final String msg = "Error setting via " + setter.getName() + " with " + value + " :" + e.getMessage();
				LOGGER.severe(msg);
				throw new XlsxSetValueException(msg, value);
			}
		}
	}

	private void setRelation(Object target, Class<?> propType, Method setter, String value)
			throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, XlsxSetValueException,
			NumberFormatException, NoSuchFieldException, SecurityException, IntrospectionException {

		int nr = getNr(value);
		Object obj = makeObject(propType, nr);
		if (obj != null) {
			setter.invoke(target, new Object[] { obj });
		}
	}

	private void setMultiRelations(Object target, Method setter, String value) throws XlsxSetValueException {
		try {
			Class<?> gentyp = getGenericType(setter);
			if (gentyp != null) {
				Class<?> basetyp = getConcreteCollType(setter);
				if (basetyp.equals(List.class)) {
					setRelationsList(target, setter, value, gentyp);
				} else if (basetyp.equals(Set.class)) {
					setRelationsSet(target, setter, value, gentyp);
				}
			} else {
				throw new Exception("dont know the generic type of " + setter.getName());
			}
		} catch (Exception ex) {
			String msg = "error while setting " + setter.getName() + " : " + ex.getMessage();
			LOGGER.severe(msg);
			throw new XlsxSetValueException(msg, target);
		}
	}

	private void setRelationsList(Object target, Method setter, String value, Class<?> gentyp)
			throws XlsxSetValueException, NoSuchFieldException, IllegalAccessException, InvocationTargetException,
			SecurityException, IntrospectionException {
		List<Object> objects = new ArrayList<Object>();
		for (int nr : getNrs(value)) {
			Object obj = makeObject(gentyp, nr);
			if (obj != null) {
				objects.add(obj);
			}
		}
		setter.invoke(target, new Object[] { objects });
	}

	private void setRelationsSet(Object target, Method setter, String value, Class<?> gentyp)
			throws XlsxSetValueException, NoSuchFieldException, IllegalAccessException, InvocationTargetException,
			SecurityException, IntrospectionException
	{
		Set<Object> objects = new HashSet<Object>();
		for (int nr : getNrs(value)) {
			Object obj = makeObject(gentyp, nr);
			if (obj != null) {
				objects.add(obj);
			}
		}
		setter.invoke(target, new Object[] { objects });
	}

	private void setArray(Object target, Method setter, String value) throws XlsxSetValueException {
		try {
			Class<?> typ = setter.getParameterTypes()[0].getComponentType();
			String strvalues[] = value.split(DELIM);
			Object objects = Array.newInstance(typ, strvalues.length);
			for (int i=0; i<strvalues.length; i++) {
				Object obj = convertUtils.convert(typ, strvalues[i]);
				Array.set(objects, i, obj);
			}
			setter.invoke(target, new Object[]{objects});
		} catch (Exception ex) {
			String msg = "error while setting " + setter.getName() + " : " + ex.getMessage();
			LOGGER.severe(msg);
			throw new XlsxSetValueException(msg, target);
		}
	}

	private Object makeInstance(XlsxData xlsdata) {
		try {
			Class<?> clz = Class.forName(xlsdata.getFqn());
			return clz.newInstance();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e.getMessage());
		}
	}

	private PropKind getPropertyKind(Class<?> clz, String propName) throws NoSuchFieldException, SecurityException {
		if (clz.isEnum()) {
			return PropKind.ENUM_PROP;
		} else if (isMultiProp(clz)) {
			if (convertUtils.canConvert(clz)) {
				return PropKind.MULTI_PROP;
			} else {
				return PropKind.MULTI_REL;
			}
		} else {
			if (convertUtils.canConvert(clz)) {
				return PropKind.SINGLE_PROP;
			} else {
				return PropKind.SINGLE_REL;
			}
		}
	}

	private boolean isMultiProp(Class<?> clz) {
		return Collection.class.isAssignableFrom(clz) || clz.equals(Set.class) || clz.isArray();
	}

	private Class<?> getConcreteCollType(Method setter) throws NoSuchFieldException, ClassNotFoundException {
		Class<?> basetyp = getPropType(setter);
		if (Collection.class.equals(basetyp)) {
			return List.class;
		} else if (List.class.equals(basetyp)) {
			return List.class;
		} else if (Set.class.equals(basetyp)) {
			return Set.class;
		} else {
			String msg = "Dont know how to make concrete class of " + basetyp;
			LOGGER.severe(msg);
			throw new ClassNotFoundException(msg);
		}
	}

	private XlsxData getXlsxData(Class<?> clz, int nr) {
		return getXlsxData(clz.getName(), nr);
	}

	private XlsxData getXlsxData(String classname, int nr) {
		XlsxDataHash datahash = xlsDataMap.get(activeSheetNr);
		if (datahash.hasXlsData(classname, nr)) {
			return datahash.getData(classname, nr);
		} else {
			for (byte index=0; index<sheetCount(); index++) {
				if (index != activeSheetNr && datahash.hasXlsData(classname, nr)) {
					return datahash.getData(classname, nr);
				}
			}
		}
		return null;
	}

	private byte sheetCount() {
		return (byte) xlsDataMap.size();
	}

	private enum PropKind {
		SINGLE_PROP, MULTI_PROP, SINGLE_REL, MULTI_REL, ENUM_PROP
	}

}


text:
package DDG::Goodie::OnionAddress;
# ABSTRACT: Recognize a web onion service address

use strict;
use DDG::Goodie;

zci is_cached => 1;
zci answer_type => "onion_address";

primary_example_queries '3g2upl4pq6kufc4m.onion';
secondary_example_queries 'How do I access https://3g2upl4pq6kufc4m.onion:81/?q=dont+track+us?';
description 'Recognize a web onion service address';
name 'OnionAddress';
code_url 'https://github.com/duckduckgo/zeroclickinfo-goodies/blob/master/lib/DDG/Goodie/OnionAddress.pm';
category 'reference';
topics 'special_interest', 'cryptography';
attribution email => 'ilv@torproject.org';

# regex to detect an onion service address
# this cover several cases, including addresses with ports and/or paths
# e.g. https://3g2upl4pq6kufc4m.onion:5000/?q=dont+track+us
my $onion_address_qr = qr/(\w+:\/\/)?([a-z0-9]{16})\.onion(:\d+)?(\/.*)?/;

# add an optional question mark in case it's at the end of a question sentence
# e.g. How do I access https://0123456789abcdef.onion?
triggers query_lc => qr/\b$onion_address_qr(\?)?\b/;

handle query_lc => sub {

    # we only accept queries for web onion services
    # we also assume that an onion service without protocol:// should be web
    return unless !$1 or ($1 eq 'https://' or $1 eq 'http://' and $2);

    my $plaintext = $2.'.onion';
    return $plaintext,
    structured_answer => {
    	id => 'onion_address',
    	name => 'OnionAddress',
    	data => {
    		title => $2.'.onion',
            subtitle => 'Onion/Hidden service',
    		description => 'You are trying to reach an onion/hidden service. To access '.$2.'.onion via web you will have to use the Tor Browser.'
    	},
    	meta => {
            sourceName => "Tor Project",
            sourceUrl => "https://www.torproject.org/projects/torbrowser.html.en#downloads"
        },
        templates => {
            group => 'text',
            options => {
                moreAt => 1
            }
        }
    };
};

1;


text:
<form>
  <view>
    <name>SpecimenDistributedEvent</name>

Distributed Event

CATISSUE_DISTRI_EVENT_PARAM

    <primaryKey>IDENTIFIER</primaryKey>

    <row>
      <numberField>
        <name>quantity</name>
        <udn>quantity</udn>

Quantity

        <column>DISTRIBUTED_QUANTITY</column>
        <mandatory>true</mandatory>
        <noOfDigitsAfterDecimal>4</noOfDigitsAfterDecimal>
      </numberField>
    </row>

    <row>
      <userField>
        <name>user</name>
        <udn>user</udn>

User

        <column>USER_ID</column>
        <showInGrid>true</showInGrid>
      </userField>
    </row>

    <row>
      <datePicker>
        <name>time</name>
        <udn>time</udn>

Date and Time

        <column>EVENT_TIMESTAMP</column>
        <format>MM-dd-yyyy HH:mm</format>
        <showInGrid>true</showInGrid>
      </datePicker>
    </row>

    <row>
      <textArea>
        <name>comments</name>
        <udn>comments</udn>

Comments

        <column>COMMENTS</column>
        <height>2</height>
      </textArea>
    </row>
  </view>
</form>


text:
//
//  UIImage+PearlScaling.h
//  Pearl
//
//  Created by Maarten Billemont on 30/07/09.
//  Copyright 2009 lhunath (Maarten Billemont). All rights reserved.
//

#import <UIKit/UIKit.h>

@interface UIImage(PearlScaling)

+ (UIImage *)imageNamed:(NSString *)imageName inSquareScalingHeight:(CGFloat)height;
+ (UIImage *)imageNamed:(NSString *)imageName inSquareScalingWidth:(CGFloat)width;
+ (UIImage *)imageNamed:(NSString *)imageName inSizeScalingHeight:(CGSize)size;
+ (UIImage *)imageNamed:(NSString *)imageName inSizeScalingWidth:(CGSize)size;
+ (UIImage *)imageNamed:(NSString *)imageName scaleInto:(CGSize)scaleSize cropTo:(CGSize)cropSize;

- (UIImage *)imageInSquareScalingHeight:(CGFloat)height;
- (UIImage *)imageInSquareScalingWidth:(CGFloat)width;
- (UIImage *)imageInSizeScalingHeight:(CGSize)size;
- (UIImage *)imageInSizeScalingWidth:(CGSize)size;
- (UIImage *)imageScaledInto:(CGSize)scaleSize cropTo:(CGSize)cropSize;

/** Scale an image such that its entire content fits in the given size.
 *
 * We scale until either the width or the height fills the image while the other either also fills the image or is smaller.
 *
 * The size of the output image is the size of the scaled image.  If forceSize is YES, the scaled image is centered in the target size. */
- (UIImage *)imageByScalingAndFittingInSize:(CGSize)targetSize;
- (UIImage *)imageByScalingAndFittingInSize:(CGSize)targetSize forceSize:(BOOL)forceSize;
/** Scale an image such that its entire content fills the given size.
 *
 * We scale until either the width or the height fills the image while the other either also fills the image or is larger and cropping the excess. */
- (UIImage *)imageByScalingAndCroppingToSize:(CGSize)targetSize;

@end


text:
import unittest
from eleven import *
from types import *
from sys import stdout
import os
import pandas as pd

mean = lambda seq: float(sum(seq))/len(seq)

class TestExpression(unittest.TestCase):
    def setUp(self):
        self.sample_list = [
                ['Exp1', 'Sample 1', 5.0],
                ['Exp1', 'Sample 2', 6.0],
                ['Exp2', 'Sample 1', 4.0],
                ['Exp2', 'Sample 2', 2.0],
                ['Ref1', 'Sample 1', 3.3],
                ['Ref1', 'Sample 2', 3.3]]
        self.sample_frame = pd.DataFrame(self.sample_list, columns=['Target', 'Sample', 'Cq'])

    def test_hello(self):
        r = expression_ddcq(self.sample_frame, 'Ref1', 'Sample 1')

"""
    def test_does_not_skip_good_genes_or_samples(self):
        sample_d, ignored_genes, ignored_samples = expression(self.sample_frame, 'Ref1', 'Sample 1')
        self.assertEqual(ignored_genes, [])
        self.assertEqual(ignored_samples, [])

    def test_skips_genes_with_no_references(self):
        sample_list = self.sample_list + [['Exp2', 'Sample 2', 10.0]]
        sample_frame = pd.DataFrame(sample_list, columns=['Target', 'Sample', 'Cq'])
        sample_d, ignored_genes, ignored_samples = expression(sample_frame, 'Ref1', 'Sample 1')
        self.assertIn('Exp2', ignored_genes)

    def test_skips_samples_with_no_reference(self):
        sample_list = self.sample_list + [['Exp1', 'Sample 3', 10.0]]
        sample_frame = pd.DataFrame(sample_list, columns=['Target', 'Sample', 'Cq'])
        sample_d, ignored_genes, ignored_samples = expression(sample_frame, 'Ref1', 'Sample 1')
        self.assertIn('Sample 3', ignored_samples)

    def test_right_ballpark(self):
        sample_d, ignored_genes, ignored_samples = expression(self.sample_frame, 'Ref1', 'Sample 1')
        self.assertAlmostEqual(mean(sample_d['Exp1']['Sample 2']), 0.5)

    def test_censor_background(self):
        addme =  [['Exp2', 'Sample 1', 10.0], ['Exp2', 'Sample 2', 5.0]]
        sample_list = self.sample_list + addme
        sample_list = sample_list + [['Exp2', 'NTC', 11.0]]
        sample_frame = pd.DataFrame(sample_list, columns=['Target', 'Sample', 'Cq'])
        censored = censor_frame_background(sample_frame, ntc_samples=['NTC'], margin=log2(10))

    def test_silences_near_ntc(self):
        addme =  [['Exp2', 'Sample 1', 10.0], ['Exp2', 'Sample 2', 5.0]]
        sample_list = self.sample_list + addme
        sample_frame = pd.DataFrame(sample_list, columns=['Target', 'Sample', 'Cq'])
        sample_d, ignored_genes, ignored_samples = expression(sample_frame, 'Ref1', 'Sample 1')
        self.assertAlmostEqual(mean(sample_d['Exp2']['Sample 2']), 2**5)

        sample_list = sample_list + [['Exp2', 'NTC', 11.0]]
        sample_frame = pd.DataFrame(sample_list, columns=['Target', 'Sample', 'Cq'])
        sample_d, ignored_genes, ignored_samples = expression(sample_frame, 'Ref1', 'Sample 1')
        self.assertIn('Exp2', ignored_genes)
"""

class TestAverage(unittest.TestCase):
    def test_averaging(self):
        self.assertAlmostEqual(average_cq((3.0,5.0)), 3.678071905112638)
        self.assertAlmostEqual(average_cq((3.0,4.0,5.0)), 3.7776075786635523)

class TestRankGenes(unittest.TestCase):
    def setUp(self):
        with open(os.path.join(os.path.dirname(__file__), 'test/vandesompele-2002-cq.txt')) as f:
            buf = f.readlines()
        self.gene_names = buf[0][:-1].split('\t')[2:]
        # slicing to cut off newlines on each line and skip header row
        # yields ['Tissue', 'Sample', Cq0, Cq1, Cq2...]
        buf = [line[:-1].split('\t') for line in buf[1:] if len(line) > 2]
        self.d = {}
        for line in buf:
            for (index, name) in enumerate(self.gene_names):
                self.d.setdefault(line[0], []).append([name, line[1], float(line[2+index])])
        for key in self.d:
            self.d[key] = pd.DataFrame(self.d[key], columns=['Target', 'Sample', 'Cq'])
        # e.g. d['Fib'] = [['ACTB', 'Fib1', 12.34], ...]

    def test_frame_ranking(self):
        key = {'Neuroblastoma': ['HPRT1', 'GAPD', 'SDHA', 'UBC', 'HMBS', 'YWHAZ', 'TBP', 'ACTB', 'RPL13A', 'B2M'],
           'Fib': ['HPRT1', 'GAPD', 'YWHAZ', 'UBC', 'ACTB', 'TBP', 'SDHA', 'RPL13A', 'B2M', 'HMBS'],
           'Leukocyte': ['UBC', 'YWHAZ', 'B2M', 'GAPD', 'RPL13A', 'TBP', 'SDHA', 'HPRT1', 'HMBS', 'ACTB'],
           'BM': ['UBC', 'RPL13A', 'YWHAZ', 'HPRT1', 'GAPD', 'SDHA', 'TBP', 'HMBS', 'B2M', 'ACTB'],
           'Pool': ['SDHA', 'GAPD', 'HMBS', 'HPRT1', 'TBP', 'UBC', 'RPL13A', 'YWHAZ', 'ACTB', 'B2M']}

        for tissue in self.d:
            ranked = rank_targets(self.d[tissue], self.gene_names, self.d[tissue].ix[0, 'Sample'])
            # no preference between the two best genes
            self.assertIn(ranked.ix[0, 'Target'], key[tissue][:2])
            self.assertIn(ranked.ix[1, 'Target'], key[tissue][:2])
            self.assertEqual(list(ranked.ix[2:, 'Target']), key[tissue][2:])

    def test_nfs_frame(self):
        comparison_vs = {'Fib': (3, 0.109409), 'BM': (2, 0.113745), 'Leukocyte': (3, 0.116988),
                'Pool': (2, 0.202805), 'Neuroblastoma': (4, 0.138337)}
        for tissue in self.d:
            ranked = rank_targets(self.d[tissue], self.gene_names, self.d[tissue].ix[0, 'Sample'])
            nfs = calculate_all_nfs(self.d[tissue], ranked['Target'], self.d[tissue].ix[0, 'Sample'])
            vs = calculate_v(nfs)
            test_v, test_value = comparison_vs[tissue]
            self.assertAlmostEqual(vs[test_v], test_value, places=5)

    def test_expression_nf(self):
        ref_sample = self.d['Fib'].ix[0, 'Sample']
        ranked = rank_targets(self.d['Fib'], self.gene_names, ref_sample)
        nfs = calculate_all_nfs(self.d['Fib'], ranked['Target'], ref_sample)
        nf3 = nfs[3]
        # old = expression_nf(self.d['Fib'], nf3, ref_sample)
        mynew = expression_nf(self.d['Fib'], nf3, ref_sample)
        self.d['Fib']['RelExp'] = mynew
        #print self.d['Fib']
        #g = self.d['Fib'].groupby(['Target', 'Sample'])['RelExp'].mean()
        #print old['ACTB']['FIB2'], g['ACTB', 'FIB2'] # 0.788928477632
        #print old['HMBS']['FIB11'], g['HMBS', 'FIB11'] # 1.63007647118

class TestExPd(unittest.TestCase):
    def test_validation(self):
        # empty frame
        a = pd.DataFrame()
        self.assertRaises(TypeError, validate_sample_frame, ['a', 'b', 'c'])
        self.assertRaises(TypeError, validate_sample_frame, None)
        self.assertRaises(ValueError, validate_sample_frame, a)

        # valid minimal frame
        b = pd.DataFrame({'foo': [0], 'Cq': [1.0], 'Sample': ['bar'], 'Target': ['baz']})
        self.assertIs(validate_sample_frame(b), True)

        # Integer Cq column should fail
        c = pd.DataFrame({'foo': [0], 'Cq': [1], 'Sample': ['bar'], 'Target': ['baz']})
        self.assertRaises(ValueError, validate_sample_frame, c)

        # Invalid sample types (Content field) should fail
        # d = pd.DataFrame({'foo': [0, 1], 'Cq': [1.0, 2.0], 'Sample': ['bar', 'bar'], 'Target': ['baz', 'blip'], 'Content': ['Unknown', 'NTC']})
        # e = pd.DataFrame({'foo': [0, 1], 'Cq': [1.0, 2.0], 'Sample': ['bar', 'bar'], 'Target': ['baz', 'blip'], 'Content': ['Unknown', 'blah']})
        # self.assertIs(validate_sample_frame(d), True)
        # self.assertRaises(ValueError, validate_sample_frame, e)

def make_sample_dict(sample_frame):
    d = {}
    g = sample_frame.groupby(['Target', 'Sample'])
    for (target, sample), h in g:
        d.setdefault(target, {})[sample] = list(h['Cq'])
    return d

if __name__ == '__main__':
    unittest.main()


text:
USING_NS_CC;
USING_NS_CC_EXT;

CCScene* LoginScene::scene()
{
    CCScene *scene = CCScene::create();
    LoginScene *layer = LoginScene::create();

    scene->addChild(layer);

    return scene;
}

bool LoginScene::init()
{
    if ( !CCLayer::init() )
    {
        return false;
    }

    //buttons
    CCMenuItemImage *pRegister = CCMenuItemImage::create(
                                                    "wkszLogin/register.png",
                                                    "wkszLogin/register_p.png",
                                                    this,
                                                    menu_selector(LoginScene::registerCB) );
    CCMenuItemImage *pLogin = CCMenuItemImage::create(
                                                     "wkszLogin/login.png",
                                                     "wkszLogin/login_p.png",
                                                     this,
                                                     menu_selector(LoginScene::loginCB) );
    CCMenuItemImage *pSurfer = CCMenuItemImage::create(
                                                    "wkszLogin/surfer.png",
                                                    "wkszLogin/surfer_p.png",
                                                    this,
                                                    menu_selector(LoginScene::surferCB) );

    pRegister->setPosition( ccp(500, 100) );
    pLogin->setPosition( ccp(650, 450) );
    pSurfer->setPosition( ccp(650, 380) );

    CCMenu* pMenu = CCMenu::create(pRegister,pLogin,pSurfer,NULL);
    pMenu->setPosition( CCPointZero );
    this->addChild(pMenu);

    //editbox
    CCScale9Sprite * ssp1 = CCScale9Sprite::create("wkszLogin/editboxBG.png");
    ssp1->setPreferredSize(CCSizeMake(500, 20));
    ssp1->setAnchorPoint(ccp(0.5, 0.5));
    pEditBox = CCEditBox::create(CCSizeMake(200,40),ssp1);
    pEditBox->setPlaceHolder("输入用户名");
    pEditBox->setFontColor(ccc3(255, 0, 255));
    pEditBox->setPosition(ccp(450, 450));
    this->addChild(pEditBox);

    CCScale9Sprite * ssp2 = CCScale9Sprite::create("wkszLogin/editboxBG.png");
    ssp2->setPreferredSize(CCSizeMake(500, 20));
    ssp2->setAnchorPoint(ccp(0.5, 0.5));
    pEditBoxPWD = CCEditBox::create(CCSizeMake(200,40),ssp2);
    pEditBoxPWD->setPlaceHolder("输入密码");
    pEditBoxPWD->setFontColor(ccc3(255, 0, 255));
    pEditBoxPWD->setPosition(ccp(450, 380));
    pEditBoxPWD->setInputFlag(kEditBoxInputFlagPassword);
    this->addChild(pEditBoxPWD);

    //mssages
    CCLabelTTF* pLabel = CCLabelTTF::create("Hello World", "Thonburi", 34);
    CCSize size = CCDirector::sharedDirector()->getWinSize();
    pLabel->setPosition( ccp(size.width / 2, size.height - 20) );
    this->addChild(pLabel, 1);

    swfBg = CCSWFNode::create("wkszLogin/swfBg.swf");
    swfBg->setPosition(ccp(size.width/2+30, size.height/2-100));
    swfBg->setScale(0.8f);
    swfBg->runAction();
    swfBg->setRepeat(true);
    this->addChild(swfBg,-9);

    swfWK = CCSWFNode::create("wkszLogin/swfWK.swf");
    swfWK->setPosition(ccp(800, 280));
    swfWK->runAction();
    swfWK->setRepeat(true);
    this->addChild(swfWK,-8);

    CCSprite *sptmp = CCSprite::create("wkszLogin/tree.png");
    sptmp->setPosition(ccp(920,80));
    this->addChild(sptmp,-7);

    swfMovie = NULL;
    flag = 0;
    return true;
}
void LoginScene::registerCB(CCObject* pSender)
{
    if (NULL != swfMovie) {
        CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic();
        delete swfMovie, swfMovie = NULL;
    }else{
        swfMovie = CCSWFNode::create("wkszLogin/yf3.swf");
        swfMovie->setPosition(ccp(400,400));
        swfMovie->runAction();
        swfMovie->setRepeat(false);
        swfMovie->addFrameListener(-1, this,menu_selector(LoginScene::registerCB));
        this->addChild(swfMovie,0);

        CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("wkszLogin/yf3.mp3", false);
    }

 }
void LoginScene::loginCB(CCObject* pSender)
{
    CCScene *pScene = MapScene::scene();
    CCDirector::sharedDirector()->replaceScene(pScene);
}

void LoginScene::surferCB(CCObject* pSender)
{

//    CCLOG("UID: %s, PWD: %s",pEditBox->getText(),pEditBoxPWD->getText());

//    CCBReader* pReader = new CCBReader( CCNodeLoaderLibrary::sharedCCNodeLoaderLibrary() );
//    pReader->autorelease();
//    CCDirector::sharedDirector()->replaceScene( pReader->createSceneWithNodeGraphFromFile( "MapScene.ccbi" ) );

//    CCNodeLoaderLibrary::sharedCCNodeLoaderLibrary()->registerCCNodeLoader( "Map1Layer", Map1LayerLoader::loader());
//    CCBReader* reader = new CCBReader( CCNodeLoaderLibrary::sharedCCNodeLoaderLibrary() );
//    reader->autorelease();
//    CCDirector::sharedDirector()->replaceScene( reader->createSceneWithNodeGraphFromFile( "MapScene.ccbi" ) );
//    CCNode* node = reader->readNodeGraphFromFile("MapScene.ccbi");
//    addChild(node);
//    node->setPosition(ccp(0,0));

    CCScene *pScene = DrawView::scene();
//    CCScene *pScene = Study1::scene();
    CCDirector::sharedDirector()->replaceScene(pScene);

}


text:
Softwareproductkeys

				Posted on

				by

    	No Softwareproductkeys yet, why don't you create one?


text:
static const int extended_data_key;

/// Free disk space in bytes.
static int64_t _YYDiskSpaceFree() {
    NSError *error = nil;
    NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error];
    if (error) return -1;
    int64_t space =  [[attrs objectForKey:NSFileSystemFreeSize] longLongValue];
    if (space < 0) space = -1;
    return space;
}

/// String's md5 hash.
static NSString *_YYNSStringMD5(NSString *string) {
    if (!string) return nil;
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(data.bytes, (CC_LONG)data.length, result);
    return [NSString stringWithFormat:
                @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                result[0],  result[1],  result[2],  result[3],
                result[4],  result[5],  result[6],  result[7],
                result[8],  result[9],  result[10], result[11],
                result[12], result[13], result[14], result[15]
            ];
}

/// weak reference for all instances
static NSMapTable *_globalInstances;
static dispatch_semaphore_t _globalInstancesLock;

static void _YYDiskCacheInitGlobal() {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _globalInstancesLock = dispatch_semaphore_create(1);
        _globalInstances = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
    });
}

static YYDiskCache *_YYDiskCacheGetGlobal(NSString *path) {
    if (path.length == 0) return nil;
    _YYDiskCacheInitGlobal();
    dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
    id cache = [_globalInstances objectForKey:path];
    dispatch_semaphore_signal(_globalInstancesLock);
    return cache;
}

static void _YYDiskCacheSetGlobal(YYDiskCache *cache) {
    if (cache.path.length == 0) return;
    _YYDiskCacheInitGlobal();
    dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
    [_globalInstances setObject:cache forKey:cache.path];
    dispatch_semaphore_signal(_globalInstancesLock);
}

@implementation YYDiskCache {
    YYKVStorage *_kv;
    dispatch_semaphore_t _lock;
    dispatch_queue_t _queue;
}

- (void)_trimRecursively {
    __weak typeof(self) _self = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_autoTrimInterval * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        __strong typeof(_self) self = _self;
        if (!self) return;
        [self _trimInBackground];
        [self _trimRecursively];
    });
}

- (void)_trimInBackground {
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        if (!self) return;
        Lock();
        [self _trimToCost:self.costLimit];
        [self _trimToCount:self.countLimit];
        [self _trimToAge:self.ageLimit];
        [self _trimToFreeDiskSpace:self.freeDiskSpaceLimit];
        Unlock();
    });
}

- (void)_trimToCost:(NSUInteger)costLimit {
    if (costLimit >= INT_MAX) return;
    [_kv removeItemsToFitSize:(int)costLimit];

}

- (void)_trimToCount:(NSUInteger)countLimit {
    if (countLimit >= INT_MAX) return;
    [_kv removeItemsToFitCount:(int)countLimit];
}

- (void)_trimToAge:(NSTimeInterval)ageLimit {
    if (ageLimit <= 0) {
        [_kv removeAllItems];
        return;
    }
    long timestamp = time(NULL);
    if (timestamp <= ageLimit) return;
    long age = timestamp - ageLimit;
    if (age >= INT_MAX) return;
    [_kv removeItemsEarlierThanTime:(int)age];
}

- (void)_trimToFreeDiskSpace:(NSUInteger)targetFreeDiskSpace {
    if (targetFreeDiskSpace == 0) return;
    int64_t totalBytes = [_kv getItemsSize];
    if (totalBytes <= 0) return;
    int64_t diskFreeBytes = _YYDiskSpaceFree();
    if (diskFreeBytes < 0) return;
    int64_t needTrimBytes = targetFreeDiskSpace - diskFreeBytes;
    if (needTrimBytes <= 0) return;
    int64_t costLimit = totalBytes - needTrimBytes;
    if (costLimit < 0) costLimit = 0;
    [self _trimToCost:(int)costLimit];
}

- (NSString *)_filenameForKey:(NSString *)key {
    NSString *filename = nil;
    if (_customFileNameBlock) filename = _customFileNameBlock(key);
    if (!filename) filename = _YYNSStringMD5(key);
    return filename;
}

#pragma mark - public

- (instancetype)init {
    @throw [NSException exceptionWithName:@"YYDiskCache init error" reason:@"YYDiskCache must be initialized with a path. Use 'initWithPath:' or 'initWithPath:inlineThreshold:' instead." userInfo:nil];
    return [self initWithPath:@"" inlineThreshold:0];
}

- (instancetype)initWithPath:(NSString *)path {
    return [self initWithPath:path inlineThreshold:1024 * 20]; // 20KB
}

- (instancetype)initWithPath:(NSString *)path
             inlineThreshold:(NSUInteger)threshold {
    self = [super init];
    if (!self) return nil;

    YYDiskCache *globalCache = _YYDiskCacheGetGlobal(path);
    if (globalCache) return globalCache;

    YYKVStorageType type;
    if (threshold == 0) {
        type = YYKVStorageTypeFile;
    } else if (threshold == NSUIntegerMax) {
        type = YYKVStorageTypeSQLite;
    } else {
        type = YYKVStorageTypeMixed;
    }

    YYKVStorage *kv = [[YYKVStorage alloc] initWithPath:path type:type];
    if (!kv) return nil;

    _kv = kv;
    _path = path;
    _lock = dispatch_semaphore_create(1);
    _queue = dispatch_queue_create("com.ibireme.cache.disk", DISPATCH_QUEUE_CONCURRENT);
    _inlineThreshold = threshold;
    _countLimit = NSUIntegerMax;
    _costLimit = NSUIntegerMax;
    _ageLimit = DBL_MAX;
    _freeDiskSpaceLimit = 0;
    _autoTrimInterval = 60;

    [self _trimRecursively];
    _YYDiskCacheSetGlobal(self);
    return self;
}

- (BOOL)containsObjectForKey:(NSString *)key {
    if (!key) return NO;
    Lock();
    BOOL contains = [_kv itemExistsForKey:key];
    Unlock();
    return contains;
}

- (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL contains))block {
    if (!block) return;
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        BOOL contains = [self containsObjectForKey:key];
        block(key, contains);
    });
}

- (id<NSCoding>)objectForKey:(NSString *)key {
    if (!key) return nil;
    Lock();
    YYKVStorageItem *item = [_kv getItemForKey:key];
    Unlock();
    if (!item.value) return nil;

    id object = nil;
    if (_customUnarchiveBlock) {
        object = _customUnarchiveBlock(item.value);
    } else {
        @try {
            object = [NSKeyedUnarchiver unarchiveObjectWithData:item.value];
        }
        @catch (NSException *exception) {
            // nothing to do...
        }
    }
    if (object && item.extendedData) {
        [YYDiskCache setExtendedData:item.extendedData toObject:object];
    }
    return object;
}

- (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id<NSCoding> object))block {
    if (!block) return;
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        id<NSCoding> object = [self objectForKey:key];
        block(key, object);
    });
}

- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key {
    if (!key) return;
    if (!object) {
        [self removeObjectForKey:key];
        return;
    }

    NSData *extendedData = [YYDiskCache getExtendedDataFromObject:object];
    NSData *value = nil;
    if (_customArchiveBlock) {
        value = _customArchiveBlock(object);
    } else {
        @try {
            value = [NSKeyedArchiver archivedDataWithRootObject:object];
        }
        @catch (NSException *exception) {
            // nothing to do...
        }
    }
    if (!value) return;
    NSString *filename = nil;
    if (_kv.type != YYKVStorageTypeSQLite) {
        if (value.length > _inlineThreshold) {
            filename = [self _filenameForKey:key];
        }
    }

    Lock();
    [_kv saveItemWithKey:key value:value filename:filename extendedData:extendedData];
    Unlock();
}

- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(void))block {
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        [self setObject:object forKey:key];
        if (block) block();
    });
}

- (void)removeObjectForKey:(NSString *)key {
    if (!key) return;
    Lock();
    [_kv removeItemForKey:key];
    Unlock();
}

- (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block {
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        [self removeObjectForKey:key];
        if (block) block(key);
    });
}

- (void)removeAllObjects {
    Lock();
    [_kv removeAllItems];
    Unlock();
}

- (void)removeAllObjectsWithBlock:(void(^)(void))block {
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        [self removeAllObjects];
        if (block) block();
    });
}

- (void)removeAllObjectsWithProgressBlock:(void(^)(int removedCount, int totalCount))progress
                                 endBlock:(void(^)(BOOL error))end {
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        if (!self) {
            if (end) end(YES);
            return;
        }
        Lock();
        [_kv removeAllItemsWithProgressBlock:progress endBlock:end];
        Unlock();
    });
}

- (NSInteger)totalCount {
    Lock();
    int count = [_kv getItemsCount];
    Unlock();
    return count;
}

- (void)totalCountWithBlock:(void(^)(NSInteger totalCount))block {
    if (!block) return;
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        NSInteger totalCount = [self totalCount];
        block(totalCount);
    });
}

- (NSInteger)totalCost {
    Lock();
    int count = [_kv getItemsSize];
    Unlock();
    return count;
}

- (void)totalCostWithBlock:(void(^)(NSInteger totalCost))block {
    if (!block) return;
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        NSInteger totalCost = [self totalCost];
        block(totalCost);
    });
}

- (void)trimToCount:(NSUInteger)count {
    Lock();
    [self _trimToCount:count];
    Unlock();
}

- (void)trimToCount:(NSUInteger)count withBlock:(void(^)(void))block {
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        [self trimToCount:count];
        if (block) block();
    });
}

- (void)trimToCost:(NSUInteger)cost {
    Lock();
    [self _trimToCost:cost];
    Unlock();
}

- (void)trimToCost:(NSUInteger)cost withBlock:(void(^)(void))block {
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        [self trimToCost:cost];
        if (block) block();
    });
}

- (void)trimToAge:(NSTimeInterval)age {
    Lock();
    [self _trimToAge:age];
    Unlock();
}

- (void)trimToAge:(NSTimeInterval)age withBlock:(void(^)(void))block {
    __weak typeof(self) _self = self;
    dispatch_async(_queue, ^{
        __strong typeof(_self) self = _self;
        [self trimToAge:age];
        if (block) block();
    });
}

+ (NSData *)getExtendedDataFromObject:(id)object {
    if (!object) return nil;
    return (NSData *)objc_getAssociatedObject(object, &extended_data_key);
}

+ (void)setExtendedData:(NSData *)extendedData toObject:(id)object {
    if (!object) return;
    objc_setAssociatedObject(object, &extended_data_key, extendedData, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)description {
    if (_name) return [NSString stringWithFormat:@"<%@: %p> (%@:%@)", self.class, self, _name, _path];
    else return [NSString stringWithFormat:@"<%@: %p> (%@)", self.class, self, _path];
}

@end


text:
package com.alexvasilkov.gestures.sample.ex.animations.cross;

class CrossEvents {

    static final String SHOW_IMAGE = "show_image";
    static final String POSITION_CHANGED = "position_changed";

    private CrossEvents() {}

}


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

<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V1.1//EN" "../dtd/document-v11.dtd">

<document>

        <title>POI-HPBF - A Guide to the Publisher File Format</title>
        <subtitle>Overview</subtitle>
        <authors>
            <person name="Nick Burch" email="nick at torchbox dot com"/>
        </authors>

<title>Document Streams</title>

		The file is made up of a number of POIFS streams. A typical
        file will be made up as follows:

<source>
Root Entry -
  Objects -
    (no children)
  SummaryInformation <(0x05)SummaryInformation>
  DocumentSummaryInformation <(0x05)DocumentSummaryInformation>
  Escher -
    EscherStm
    EscherDelayStm
  Quill -
    QuillSub -
      CONTENTS
      CompObj <(0x01)CompObj>
  Envelope
  Contents
  Internal <(0x03)Internal>
  CompObj <(0x01)CompObj>
  VBA -
    (no children)
</source>

<title>Changing Text</title>

If you make a change to the text of a file, but not change
          how much text there is, then the CONTENTS stream
          will undergo a small change, and the Contents stream
          will undergo a large change.

If you make a change to the text of a file, and change the
          amount of text there is, then both the Contents and
          the CONTENTS streams change.

<title>Changing Shapes</title>

If you alter the size of a textbox, but make no text changes,
          then both Contents and CONTENTS streams
          change. There are no changes to the Escher streams.

If you set the background colour of a textbox, but make
          no changes to the text, (to finish off)

<title>Structure of CONTENTS</title>

First we have "CHNKINK ", followed by 24 bytes.

Next we have 20 sequences of 24 bytes each. If the first two bytes
         at 0x1800, then that sequence entry exists, but if it's 0x0000 then
         the entry doesn't exist. If it does exist, we then have 4 bytes of
         upper case ASCII text, followed by three little endian shorts.
         The first of these seems to be the count of that type, the second is
         usually 1, the third is usually zero. The we have another 4 bytes of
         upper case ASCII text, normally but not always the same as the first
         text. Finally, we have an unsigned little endian 32 bit offset to
         the start of the data for this, then an unsigned little endian
         32 bit offset of the length of this section.

Normally, the first sequence entry is for TEXT, and the text data
         will start at 0x200. After that is normally two or three STSH entries
         (so the first short has values 0, then 1, then 2). After that it
         seems to vary.

At 0x200 we have the text, stored as little endian 16 bit unicode.

After the text comes all sorts of other stuff, presumably as
         described by the sequences.

For a contents stream of length 7168 / 0x1c00 bytes, the start
         looks something like:

<source>
CHNKINK       // "CHNKINK "
04 00 07 00   // Normally 04 00 07 00
13 00 00 03   // Normally ## 00 00 03
00 02 00 00   // Normally 00 ## 00 00
00 1c 00 00   // Normally length of the stream
f8 01 13 00   // Normally f8 01 11/13 00
ff ff ff ff   // Normally seems to be ffffffff

18 00
TEXT 00 00 01 00 00 00       // TEXT 0 1 0
TEXT 00 02 00 00 d0 03 00 00 // TEXT from: 200 (512), len: 3d0 (976)
18 00
STSH 00 00 01 00 00 00       // STSH 0 1 0
STSH d0 05 00 00 1e 00 00 00 // STSH from: 5d0 (1488), len: 1e (30)
18 00
STSH 01 00 01 00 00 00       // STSH 1 1 0
STSH ee 05 00 00 b8 01 00 00 // STSH from: 5ee (1518), len: 1b8 (440)
18 00
STSH 02 00 01 00 00 00       // STSH 2 1 0
STSH a6 07 00 00 3c 00 00 00 // STSH from: 7a6 (1958), len: 3c (60)
18 00
FDPP 00 00 01 00 00 00       // FDPP 0 1 0
FDPP 00 08 00 00 00 02 00 00 // FDPP from: 800 (2048), len: 200 (512)
18 00
FDPC 00 00 01 00 00 00       // FDPC 0 1 0
FDPC 00 0a 00 00 00 02 00 00 // FDPC from: a00 (2560), len: 200 (512)
18 00
FDPC 01 00 01 00 00 00       // FDPC 1 1 0
FDPC 00 0c 00 00 00 02 00 00 // FDPC from: c00 (3072), len: 200 (512)
18 00
SYID 00 00 01 00 00 00       // SYID 0 1 0
SYID 00 0e 00 00 20 00 00 00 // SYID from: e00 (3584), len: 20 (32)
18 00
SGP  00 00 01 00 00 00       // SGP  0 1 0
SGP  20 0e 00 00 0a 00 00 00 // SGP  from: e20 (3616), len: a (10)
18 00
INK  00 00 01 00 00 00       // INK  0 1 0
INK  2a 0e 00 00 04 00 00 00 // INK  from: e2a (3626), len: 4 (4)
18 00
BTEP 00 00 01 00 00 00       // BTEP 0 1 0
PLC  2e 0e 00 00 18 00 00 00 // PLC  from: e2e (3630), len: 18 (24)
18 00
BTEC 00 00 01 00 00 00       // BTEC 0 1 0
PLC  46 0e 00 00 20 00 00 00 // PLC  from: e46 (3654), len: 20 (32)
18 00
FONT 00 00 01 00 00 00       // FONT 0 1 0
FONT 66 0e 00 00 48 03 00 00 // FONT from: e66 (3686), len: 348 (840)
18 00
TCD  03 00 01 00 00 00       // TCD  3 1 0
PLC  ae 11 00 00 24 00 00 00 // PLC  from: 11ae (4526), len: 24 (36)
18 00
TOKN 04 00 01 00 00 00       // TOKN 4 1 0
PLC  d2 11 00 00 0a 01 00 00 // PLC  from: 11d2 (4562), len: 10a (266)
18 00
TOKN 05 00 01 00 00 00       // TOKN 5 1 0
PLC  dc 12 00 00 2a 01 00 00 // PLC  from: 12dc (4828), len: 12a (298)
18 00
STRS 00 00 01 00 00 00       // STRS 0 1 0
PLC  06 14 00 00 46 00 00 00 // PLC  from: 1406 (5126), len: 46 (70)
18 00
MCLD 00 00 01 00 00 00       // MCLD 0 1 0
MCLD 4c 14 00 00 16 06 00 00 // MCLD from: 144c (5196), len: 616 (1558)
18 00
PL   00 00 01 00 00 00       // PL   0 1 0
PL   62 1a 00 00 48 00 00 00 // PL   from: 1a62 (6754), len: 48 (72)
00 00                        // Blank entry follows
00 00 00 00 00 00
00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00

(the text will then start)
</source>

We think that the first 4 bytes of text describes the
		 the function of the data at the offset. The first short is
		 then the count of that type, eg the 2nd will have 1. We
		 think that the second 4 bytes of text describes the format
		 of data block at the offset. The format of the text block
		 is easy, but we're still trying to figure out the others.

<title>Structure of TEXT bit</title>

This is very simple. All the text for the document is
            stored in a single bit of the Quill CONTENTS. The text
            is stored as little endian 16 bit unicode strings.

<title>Structure of PLC bit</title>

The first four bytes seem to hold the count of the
            entries in the bit, and the second four bytes seem to hold
            the type. There is then some pre-data, and then data for
            each of the entries, the exact format dependant on the type.

Type 0 has 4 2 byte unsigned ints, then a pair of 2 byte
            unsigned ints for each entry.

Type 4 has 4 2 byte unsigned ints, then a pair of 4 byte
            unsigned ints for each entry.

Type 8 has 7 2 byte unsigned ints, then a pair of 4 byte
            unsigned ints for each entry.

Type 12 holds hyperlinks, and is very much more complex.
            See org.apache.poi.hpbf.model.qcbits.QCPLCBit
            for our best guess as to how the contents match up.

</document>


text:
import diventi.accounts.models
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0146_auto_20190516_0901'),
    ]

    operations = [
        migrations.AlterModelManagers(
            name='diventiuser',
            managers=[
                ('objects', diventi.accounts.models.DiventiUserManager()),
            ],
        ),
    ]


text:
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import logging
import os
import time
from collections import defaultdict
from types import GeneratorType

from pants.base.exceptions import TaskError
from pants.base.project_tree import Dir, File, Link
from pants.build_graph.address import Address
from pants.engine.addressable import SubclassesOf
from pants.engine.fs import FileContent, FilesContent, Path, PathGlobs, Snapshot
from pants.engine.isolated_process import ExecuteProcessRequest, ExecuteProcessResult
from pants.engine.native import Function, TypeConstraint, TypeId
from pants.engine.nodes import Return, State, Throw
from pants.engine.rules import RuleIndex, SingletonRule, TaskRule
from pants.engine.selectors import Select, SelectDependencies, SelectVariant, constraint_for
from pants.engine.struct import HasProducts, Variants
from pants.util.contextutil import temporary_file_path
from pants.util.objects import datatype

logger = logging.getLogger(__name__)

class ExecutionRequest(datatype('ExecutionRequest', ['roots', 'native'])):
  """Holds the roots for an execution, which might have been requested by a user.

  To create an ExecutionRequest, see `LocalScheduler.build_request` (which performs goal
  translation) or `LocalScheduler.execution_request`.

  :param roots: Roots for this request.
  :type roots: list of tuples of subject and product.
  """

class ExecutionResult(datatype('ExecutionResult', ['error', 'root_products'])):
  """Represents the result of a single execution."""

  @classmethod
  def finished(cls, root_products):
    """Create a success or partial success result from a finished run.

    Runs can either finish with no errors, satisfying all promises, or they can partially finish
    if run in fail-slow mode producing as many products as possible.
    :param root_products: List of ((subject, product), State) tuples.
    :rtype: `ExecutionResult`
    """
    return cls(error=None, root_products=root_products)

  @classmethod
  def failure(cls, error):
    """Create a failure result.

    A failure result represent a run with a fatal error.  It presents the error but no
    products.

    :param error: The execution error encountered.
    :type error: :class:`pants.base.exceptions.TaskError`
    :rtype: `ExecutionResult`
    """
    return cls(error=error, root_products=None)

class ExecutionError(Exception):
  pass

class WrappedNativeScheduler(object):
  def __init__(self, native, build_root, work_dir, ignore_patterns, rule_index):
    self._native = native
    # TODO: The only (?) case where we use inheritance rather than exact type unions.
    has_products_constraint = SubclassesOf(HasProducts)
    self._root_subject_types = sorted(rule_index.roots)

    # Create the ExternContext, and the native Scheduler.
    self._tasks = native.new_tasks()
    self._register_rules(rule_index)

    self._scheduler = native.new_scheduler(
      self._tasks,
      self._root_subject_types,
      build_root,
      work_dir,
      ignore_patterns,
      Snapshot,
      FileContent,
      FilesContent,
      Path,
      Dir,
      File,
      Link,
      ExecuteProcessResult,
      has_products_constraint,
      constraint_for(Address),
      constraint_for(Variants),
      constraint_for(PathGlobs),
      constraint_for(Snapshot),
      constraint_for(FilesContent),
      constraint_for(Dir),
      constraint_for(File),
      constraint_for(Link),
      constraint_for(ExecuteProcessRequest),
      constraint_for(ExecuteProcessResult),
      constraint_for(GeneratorType),
    )

  def _root_type_ids(self):
    return self._to_ids_buf(sorted(self._root_subject_types))

  def graph_trace(self, execution_request):
    with temporary_file_path() as path:
      self._native.lib.graph_trace(self._scheduler, execution_request, bytes(path))
      with open(path) as fd:
        for line in fd.readlines():
          yield line.rstrip()

  def assert_ruleset_valid(self):
    raw_value = self._native.lib.validator_run(self._scheduler)
    value = self._from_value(raw_value)

    if isinstance(value, Exception):
      raise ValueError(str(value))

  def _to_value(self, obj):
    return self._native.context.to_value(obj)

  def _from_value(self, val):
    return self._native.context.from_value(val)

  def _to_id(self, typ):
    return self._native.context.to_id(typ)

  def _to_key(self, obj):
    return self._native.context.to_key(obj)

  def _from_id(self, cdata):
    return self._native.context.from_id(cdata)

  def _from_key(self, cdata):
    return self._native.context.from_key(cdata)

  def _to_constraint(self, type_or_constraint):
    return TypeConstraint(self._to_key(constraint_for(type_or_constraint)))

  def _to_ids_buf(self, types):
    return self._native.to_ids_buf(types)

  def _to_utf8_buf(self, string):
    return self._native.context.utf8_buf(string)

  def _register_rules(self, rule_index):
    """Record the given RuleIndex on `self._tasks`."""
    registered = set()
    for product_type, rules in rule_index.rules.items():
      # TODO: The rules map has heterogeneous keys, so we normalize them to type constraints
      # and dedupe them before registering to the native engine:
      #   see: https://github.com/pantsbuild/pants/issues/4005
      output_constraint = self._to_constraint(product_type)
      for rule in rules:
        key = (output_constraint, rule)
        if key in registered:
          continue
        registered.add(key)

        if type(rule) is SingletonRule:
          self._register_singleton(output_constraint, rule)
        elif type(rule) is TaskRule:
          self._register_task(output_constraint, rule)
        else:
          raise ValueError('Unexpected Rule type: {}'.format(rule))

  def _register_singleton(self, output_constraint, rule):
    """Register the given SingletonRule.

    A SingletonRule installed for a type will be the only provider for that type.
    """
    self._native.lib.tasks_singleton_add(self._tasks,
                                         self._to_value(rule.value),
                                         output_constraint)

  def _register_task(self, output_constraint, rule):
    """Register the given TaskRule with the native scheduler."""
    func = rule.func
    self._native.lib.tasks_task_begin(self._tasks, Function(self._to_key(func)), output_constraint)
    for selector in rule.input_selectors:
      selector_type = type(selector)
      product_constraint = self._to_constraint(selector.product)
      if selector_type is Select:
        self._native.lib.tasks_add_select(self._tasks, product_constraint)
      elif selector_type is SelectVariant:
        key_buf = self._to_utf8_buf(selector.variant_key)
        self._native.lib.tasks_add_select_variant(self._tasks,
                                                  product_constraint,
                                                  key_buf)
      elif selector_type is SelectDependencies:
        self._native.lib.tasks_add_select_dependencies(self._tasks,
                                                       product_constraint,
                                                       self._to_constraint(selector.dep_product),
                                                       self._to_utf8_buf(selector.field),
                                                       self._to_ids_buf(selector.field_types))
      else:
        raise ValueError('Unrecognized Selector type: {}'.format(selector))
    for get in rule.input_gets:
      self._native.lib.tasks_add_get(self._tasks,
                                     self._to_constraint(get.product),
                                     TypeId(self._to_id(get.subject)))
    self._native.lib.tasks_task_end(self._tasks)

  def visualize_graph_to_file(self, execution_request, filename):
    self._native.lib.graph_visualize(self._scheduler, execution_request, bytes(filename))

  def visualize_rule_graph_to_file(self, filename):
    self._native.lib.rule_graph_visualize(
      self._scheduler,
      self._root_type_ids(),
      bytes(filename))

  def rule_graph_visualization(self):
    with temporary_file_path() as path:
      self.visualize_rule_graph_to_file(path)
      with open(path) as fd:
        for line in fd.readlines():
          yield line.rstrip()

  def rule_subgraph_visualization(self, root_subject_type, product_type):
    root_type_id = TypeId(self._to_id(root_subject_type))

    product_type_id = TypeConstraint(self._to_key(constraint_for(product_type)))
    with temporary_file_path() as path:
      self._native.lib.rule_subgraph_visualize(
        self._scheduler,
        root_type_id,
        product_type_id,
        bytes(path))
      with open(path) as fd:
        for line in fd.readlines():
          yield line.rstrip()

  def invalidate(self, filenames):
    filenames_buf = self._native.context.utf8_buf_buf(filenames)
    return self._native.lib.graph_invalidate(self._scheduler, filenames_buf)

  def graph_len(self):
    return self._native.lib.graph_len(self._scheduler)

  def exec_reset(self):
    self._native.lib.execution_reset(self._scheduler)

  def add_root_selection(self, execution_request, subject, product):
    res = self._native.lib.execution_add_root_select(self._scheduler,
                                                     execution_request,
                                                     self._to_key(subject),
                                                     self._to_constraint(product))
    if res.is_throw:
      raise self._from_value(res.value)

  def visualize_to_dir(self):
    return self._native.visualize_to_dir

  def to_keys(self, subjects):
    return list(self._to_key(subject) for subject in subjects)

  def pre_fork(self):
    self._native.lib.scheduler_pre_fork(self._scheduler)

  def run_and_return_roots(self, execution_request):
    raw_roots = self._native.lib.execution_execute(self._scheduler, execution_request)
    try:
      roots = []
      for raw_root in self._native.unpack(raw_roots.nodes_ptr, raw_roots.nodes_len):
        if raw_root.state_tag is 1:
          state = Return(self._from_value(raw_root.state_value))
        elif raw_root.state_tag in (2, 3, 4):
          state = Throw(self._from_value(raw_root.state_value))
        else:
          raise ValueError(
            'Unrecognized State type `{}` on: {}'.format(raw_root.state_tag, raw_root))
        roots.append(state)
    finally:
      self._native.lib.nodes_destroy(raw_roots)
    return roots

  def lease_files_in_graph(self):
    self._native.lib.lease_files_in_graph(self._scheduler)

  def garbage_collect_store(self):
    self._native.lib.garbage_collect_store(self._scheduler)

class LocalScheduler(object):
  """A scheduler that expands a product Graph by executing user defined Rules."""

  def __init__(self,
               work_dir,
               goals,
               rules,
               project_tree,
               native,
               include_trace_on_error=True):
    """
    :param goals: A dict from a goal name to a product type. A goal is just an alias for a
           particular (possibly synthetic) product.
    :param rules: A set of Rules which is used to compute values in the product graph.
    :param project_tree: An instance of ProjectTree for the current build root.
    :param work_dir: The pants work dir.
    :param native: An instance of engine.native.Native.
    :param include_trace_on_error: Include the trace through the graph upon encountering errors.
    :type include_trace_on_error: bool
    """
    self._products_by_goal = goals
    self._project_tree = project_tree
    self._include_trace_on_error = include_trace_on_error
    self._run_count = 0

    # Create the ExternContext, and the native Scheduler.
    self._execution_request = None

    # Validate and register all provided and intrinsic tasks.
    rules = list(rules)
    rule_index = RuleIndex.create(rules)
    self._scheduler = WrappedNativeScheduler(native,
                                             project_tree.build_root,
                                             work_dir,
                                             project_tree.ignore_patterns,
                                             rule_index)

    # If configured, visualize the rule graph before asserting that it is valid.
    if self._scheduler.visualize_to_dir() is not None:
      rule_graph_name = 'rule_graph.dot'
      self.visualize_rule_graph_to_file(os.path.join(self._scheduler.visualize_to_dir(), rule_graph_name))

    self._scheduler.assert_ruleset_valid()

  def graph_len(self):
    return self._scheduler.graph_len()

  def trace(self, execution_request):
    """Yields a stringified 'stacktrace' starting from the scheduler's roots."""
    for line in self._scheduler.graph_trace(execution_request.native):
      yield line

  def visualize_graph_to_file(self, execution_request, filename):
    """Visualize a graph walk by writing graphviz `dot` output to a file.

    :param ExecutionRequest execution_request: A set of roots to visualize from.
    :param str filename: The filename to output the graphviz output to.
    """
    self._scheduler.visualize_graph_to_file(execution_request.native, filename)

  def visualize_rule_graph_to_file(self, filename):
    self._scheduler.visualize_rule_graph_to_file(filename)

  def build_request(self, goals, subjects):
    """Translate the given goal names into product types, and return an ExecutionRequest.

    :param goals: The list of goal names supplied on the command line.
    :type goals: list of string
    :param subjects: A list of Spec and/or PathGlobs objects.
    :type subject: list of :class:`pants.base.specs.Spec`, `pants.build_graph.Address`, and/or
      :class:`pants.engine.fs.PathGlobs` objects.
    :returns: An ExecutionRequest for the given goals and subjects.
    """
    return self.execution_request([self._products_by_goal[goal_name] for goal_name in goals],
                                  subjects)

  def execution_request(self, products, subjects):
    """Create and return an ExecutionRequest for the given products and subjects.

    The resulting ExecutionRequest object will contain keys tied to this scheduler's product Graph, and
    so it will not be directly usable with other scheduler instances without being re-created.

    An ExecutionRequest for an Address represents exactly one product output, as does SingleAddress. But
    we differentiate between them here in order to normalize the output for all Spec objects
    as "list of product".

    :param products: A list of product types to request for the roots.
    :type products: list of types
    :param subjects: A list of Spec and/or PathGlobs objects.
    :type subject: list of :class:`pants.base.specs.Spec`, `pants.build_graph.Address`, and/or
      :class:`pants.engine.fs.PathGlobs` objects.
    :returns: An ExecutionRequest for the given products and subjects.
    """
    roots = tuple((s, p) for s in subjects for p in products)
    native_execution_request = self._scheduler._native.new_execution_request()
    for subject, product in roots:
      self._scheduler.add_root_selection(native_execution_request, subject, product)
    return ExecutionRequest(roots, native_execution_request)

  def invalidate_files(self, direct_filenames):
    """Calls `Graph.invalidate_files()` against an internal product Graph instance."""
    # NB: Watchman no longer triggers events when children are created/deleted under a directory,
    # so we always need to invalidate the direct parent as well.
    filenames = set(direct_filenames)
    filenames.update(os.path.dirname(f) for f in direct_filenames)
    invalidated = self._scheduler.invalidate(filenames)
    logger.info('invalidated %d nodes for: %s', invalidated, filenames)
    return invalidated

  def node_count(self):
    return self._scheduler.graph_len()

  def pre_fork(self):
    self._scheduler.pre_fork()

  def schedule(self, execution_request):
    """Yields batches of Steps until the roots specified by the request have been completed.

    This method should be called by exactly one scheduling thread, but the Step objects returned
    by this method are intended to be executed in multiple threads, and then satisfied by the
    scheduling thread.
    """
    start_time = time.time()
    roots = zip(execution_request.roots,
                self._scheduler.run_and_return_roots(execution_request.native))

    if self._scheduler.visualize_to_dir() is not None:
      name = 'run.{}.dot'.format(self._run_count)
      self._run_count += 1
      self.visualize_graph_to_file(execution_request,
                                   os.path.join(self._scheduler.visualize_to_dir(), name))

    logger.debug(
      'computed %s nodes in %f seconds. there are %s total nodes.',
      len(roots),
      time.time() - start_time,
      self._scheduler.graph_len()
    )

    return roots

  def execute(self, execution_request):
    """Executes the requested build and returns the resulting root entries.

    TODO: Merge with `schedule`.
    TODO2: Use of TaskError here is... odd.

    :param execution_request: The description of the goals to achieve.
    :type execution_request: :class:`ExecutionRequest`
    :returns: The result of the run.
    :rtype: :class:`Engine.Result`
    """
    try:
      return ExecutionResult.finished(self.schedule(execution_request))
    except TaskError as e:
      return ExecutionResult.failure(e)

  def products_request(self, products, subjects):
    """Executes a request for multiple products for some subjects, and returns the products.

    :param list products: A list of product type for the request.
    :param list subjects: A list of subjects for the request.
    :returns: A dict from product type to lists of products each with length matching len(subjects).
    """
    request = self.execution_request(products, subjects)
    result = self.execute(request)
    if result.error:
      raise result.error

    # State validation.
    unknown_state_types = tuple(
      type(state) for _, state in result.root_products if type(state) not in (Throw, Return)
    )
    if unknown_state_types:
      State.raise_unrecognized(unknown_state_types)

    # Throw handling.
    # TODO: See https://github.com/pantsbuild/pants/issues/3912
    throw_root_states = tuple(state for root, state in result.root_products if type(state) is Throw)
    if throw_root_states:
      if self._include_trace_on_error:
        cumulative_trace = '\n'.join(self.trace(request))
        raise ExecutionError('Received unexpected Throw state(s):\n{}'.format(cumulative_trace))

      unique_exceptions = set(t.exc for t in throw_root_states)
      if len(unique_exceptions) == 1:
        raise throw_root_states[0].exc
      else:
        raise ExecutionError('Multiple exceptions encountered:\n  {}'
                             .format('\n  '.join('{}: {}'.format(type(t).__name__, str(t))
                                                                 for t in unique_exceptions)))

    # Everything is a Return: we rely on the fact that roots are ordered to preserve subject
    # order in output lists.
    product_results = defaultdict(list)
    for (_, product), state in result.root_products:
      product_results[product].append(state.value)
    return product_results

  def product_request(self, product, subjects):
    """Executes a request for a single product for some subjects, and returns the products.

    :param class product: A product type for the request.
    :param list subjects: A list of subjects for the request.
    :returns: A list of the requested products, with length match len(subjects).
    """
    return self.products_request([product], subjects)[product]

  def lease_files_in_graph(self):
    self._scheduler.lease_files_in_graph()

  def garbage_collect_store(self):
    self._scheduler.garbage_collect_store()


text:
/*****************************************************************************
 * name:		be_ai_gen.c
 *
 * desc:		genetic selection
 *
 * $Archive: /MissionPack/code/botlib/be_ai_gen.c $
 *
 *****************************************************************************/

#include "../qcommon/q_shared.h"
#include "l_memory.h"
#include "l_log.h"
#include "l_utils.h"
#include "l_script.h"
#include "l_precomp.h"
#include "l_struct.h"
#include "aasfile.h"
#include "botlib.h"
#include "be_aas.h"
#include "be_aas_funcs.h"
#include "be_interface.h"
#include "be_ai_gen.h"

//===========================================================================
//
// Parameter:			-
// Returns:				-
// Changes Globals:		-
//===========================================================================
int GeneticSelection(int numranks, float *rankings)
{
	float sum;
	int i, index;

	sum = 0;
	for (i = 0; i < numranks; i++)
	{
		if (rankings[i] < 0) continue;
		sum += rankings[i];
	} //end for
	if (sum > 0)
	{
		//select a bot where the ones with the higest rankings have
		//the highest chance of being selected
		//sum *= random();
		for (i = 0; i < numranks; i++)
		{
			if (rankings[i] < 0) continue;
			sum -= rankings[i];
			if (sum <= 0) return i;
		} //end for
	} //end if
	//select a bot randomly
	index = random() * numranks;
	for (i = 0; i < numranks; i++)
	{
		if (rankings[index] >= 0) return index;
		index = (index + 1) % numranks;
	} //end for
	return 0;
} //end of the function GeneticSelection
//===========================================================================
//
// Parameter:			-
// Returns:				-
// Changes Globals:		-
//===========================================================================
int GeneticParentsAndChildSelection(int numranks, float *ranks, int *parent1, int *parent2, int *child)
{
	float rankings[256], max;
	int i;

	if (numranks > 256)
	{
		botimport.Print(PRT_WARNING, "GeneticParentsAndChildSelection: too many bots\n");
		*parent1 = *parent2 = *child = 0;
		return qfalse;
	} //end if
	for (max = 0, i = 0; i < numranks; i++)
	{
		if (ranks[i] < 0) continue;
		max++;
	} //end for
	if (max < 3)
	{
		botimport.Print(PRT_WARNING, "GeneticParentsAndChildSelection: too few valid bots\n");
		*parent1 = *parent2 = *child = 0;
		return qfalse;
	} //end if
	Com_Memcpy(rankings, ranks, sizeof(float) * numranks);
	//select first parent
	*parent1 = GeneticSelection(numranks, rankings);
	rankings[*parent1] = -1;
	//select second parent
	*parent2 = GeneticSelection(numranks, rankings);
	rankings[*parent2] = -1;
	//reverse the rankings
	max = 0;
	for (i = 0; i < numranks; i++)
	{
		if (rankings[i] < 0) continue;
		if (rankings[i] > max) max = rankings[i];
	} //end for
	for (i = 0; i < numranks; i++)
	{
		if (rankings[i] < 0) continue;
		rankings[i] = max - rankings[i];
	} //end for
	//select child
	*child = GeneticSelection(numranks, rankings);
	return qtrue;
} //end of the function GeneticParentsAndChildSelection


text:
import sbt._
import Keys._

import com.typesafe.tools.mima.plugin.MimaKeys.mimaPreviousArtifacts

object BuildSettings {
  val buildSettings: Seq[Setting[_]] = Seq(
    organization := "com.socrata",
    scalaVersion := "2.13.10",
    crossScalaVersions := Seq("2.12.17", scalaVersion.value),
    externalResolvers ++= Seq("socrata artifactory" at "https://repo.socrata.com/artifactory/libs-release")
  )

  def projectSettings(assembly: Boolean = false): Seq[Setting[_]] = buildSettings ++ Seq(
    // Haven't made a stable release of this yet
    mimaPreviousArtifacts := Set(/* "com.socrata" % (name.value + "_" + scalaBinaryVersion.value) % "0.1.0" */),
    Test/testOptions ++= Seq(
      Tests.Argument(TestFrameworks.ScalaTest, "-oFD")
    ),
    scalacOptions ++= Seq(
      "-language:implicitConversions",
      "-deprecation",
      "-feature"
    ),
    libraryDependencies ++= Seq(
      "org.slf4j" % "slf4j-api" % slf4jVersion,
      "org.slf4j" % "jcl-over-slf4j" % slf4jVersion,
      "org.scalatest" %% "scalatest" % "3.0.8" % "test",
      "org.scala-lang.modules" %% "scala-parser-combinators" % "2.1.0",
      "org.scala-lang.modules" %% "scala-xml"                % "2.0.1",
      "org.scala-lang.modules" %% "scala-collection-compat"  % "2.5.0"
    )
  )

  val slf4jVersion = "1.7.5"
}


text:
class CreateProfessors < ActiveRecord::Migration
  def change
    create_table :professors do |t|
      t.string :name
      t.text :picture
      t.timestamps null: false
    end
  end
end


text:
<!DOCTYPE html>

    <title></title>
    <link href="JavaScript-ConsoleStyle.css" rel="stylesheet" />

    <input type="text" id="a" placeholder="a" />
    <input type="text" id="b" placeholder="b" />
    <input type="text" id="c" placeholder="c" />
    <button id="check">Check</button>


text:
<?php
/**
 * GetContractsRequestTest
 *
 * PHP version 5
 *
 * @category Class
 * @package  Swagger\Client
 * @author   Swagger Codegen team
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * MINDBODY Public API
 *
 * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
 *
 * OpenAPI spec version: v6
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 * Swagger Codegen version: 2.4.6
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Please update the test case below to test the model.
 */

namespace Swagger\Client;

/**
 * GetContractsRequestTest Class Doc Comment
 *
 * @category    Class
 * @description GetContractsRequest
 * @package     Swagger\Client
 * @author      Swagger Codegen team
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class GetContractsRequestTest extends \PHPUnit_Framework_TestCase
{

    /**
     * Setup before running any test case
     */
    public static function setUpBeforeClass()
    {
    }

    /**
     * Setup before running each test case
     */
    public function setUp()
    {
    }

    /**
     * Clean up after running each test case
     */
    public function tearDown()
    {
    }

    /**
     * Clean up after running all test cases
     */
    public static function tearDownAfterClass()
    {
    }

    /**
     * Test "GetContractsRequest"
     */
    public function testGetContractsRequest()
    {
    }

    /**
     * Test attribute "contract_ids"
     */
    public function testPropertyContractIds()
    {
    }

    /**
     * Test attribute "sold_online"
     */
    public function testPropertySoldOnline()
    {
    }

    /**
     * Test attribute "location_id"
     */
    public function testPropertyLocationId()
    {
    }

    /**
     * Test attribute "consumer_id"
     */
    public function testPropertyConsumerId()
    {
    }

    /**
     * Test attribute "limit"
     */
    public function testPropertyLimit()
    {
    }

    /**
     * Test attribute "offset"
     */
    public function testPropertyOffset()
    {
    }
}


text:
QUnit.test('method.parseDate', function (assert) {
  var $input = window.createInput();

  assert.equal($input.datepicker('parseDate', '02/14/2014').getTime(), new Date(2014, 1, 14).getTime());
});


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab5wednesdayjunittesting;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author Bais
 */
public class Lab5WednesdayJUnitTestingTest {

    public Lab5WednesdayJUnitTestingTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    /**
     * Test of main method, of class Lab5WednesdayJUnitTesting.
     */
    @Test
    public void testMain() {
        System.out.println("main");
        String[] args = null;
        Lab5WednesdayJUnitTesting.main(args);
        // TODO review the generated test code and remove the default call to fail.
        assertNull(args);
        //fail("The test case is a prototype.");
    }
}