text:
require_relative "lib/hub_indexer/version"
require 'aws-sdk'
require 'yaml'
require 'open-uri'
require 'rest_client'

HubIndexer::APP_CONFIG = YAML.load_file("#{Dir.pwd}/config/hub_indexer.yml")
Dir[File.dirname(__FILE__) + "/lib/*.rb"].each {|file| require_relative file}

HubIndexer::PROFILE = YAML.load_file("#{Dir.pwd}/config/#{HubIndexer::OPTS[:profile_name]}")

redpajama_set_name: RedPajamaGithub


text:
name 'dimod-testartifact'
version '0.0.1'


text:
// *****************************************************************************

// *****************************************************************************
#ifndef nowarning_migrated_inciter_decl_h
#define nowarning_migrated_inciter_decl_h

#include "Macro.hpp"

#if defined(__clang__)
  #pragma clang diagnostic push
  #pragma clang diagnostic ignored "-Wunused-parameter"
  #pragma clang diagnostic ignored "-Wextra-semi"
  #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant"
  #pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(STRICT_GNUC)
  #pragma GCC diagnostic push
  #pragma GCC diagnostic ignored "-Wunused-parameter"
#endif

#include "../UnitTest/migrated_inciter.decl.h"

#if defined(__clang__)
  #pragma clang diagnostic pop
#elif defined(STRICT_GNUC)
  #pragma GCC diagnostic pop
#endif

#endif // nowarning_migrated_inciter_decl_h


text:
using namespace boost::intrusive;

class MyClass : public bs_set_base_hook<>
{
   int int_;

   public:
   //This is a member hook
   bs_set_member_hook<> member_hook_;

   MyClass(int i)
      :  int_(i)
      {}
   friend bool operator< (const MyClass &a, const MyClass &b)
      {  return a.int_ < b.int_;  }
   friend bool operator> (const MyClass &a, const MyClass &b)
      {  return a.int_ > b.int_;  }
   friend bool operator== (const MyClass &a, const MyClass &b)
      {  return a.int_ == b.int_;  }
};

//Define an sg_set using the base hook that will store values in reverse order
//and won't execute floating point operations.
typedef sg_set
   < MyClass, compare<std::greater<MyClass> >, floating_point<false> >   BaseSet;

//Define an multiset using the member hook
typedef member_hook<MyClass, bs_set_member_hook<>, &MyClass::member_hook_> MemberOption;
typedef sg_multiset< MyClass, MemberOption>   MemberMultiset;

int main()
{
   typedef std::vector<MyClass>::iterator VectIt;
   typedef std::vector<MyClass>::reverse_iterator VectRit;

   //Create several MyClass objects, each one with a different value
   std::vector<MyClass> values;
   for(int i = 0; i < 100; ++i)  values.push_back(MyClass(i));

   BaseSet baseset;
   MemberMultiset membermultiset;

   //Now insert them in the reverse order in the base hook sg_set
   for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it){
      baseset.insert(*it);
      membermultiset.insert(*it);
   }

   //Change balance factor
   membermultiset.balance_factor(0.9f);

   //Now test sg_sets
   {
      BaseSet::reverse_iterator rbit(baseset.rbegin()), rbitend(baseset.rend());
      MemberMultiset::iterator mit(membermultiset.begin()), mitend(membermultiset.end());
      VectIt it(values.begin()), itend(values.end());

      //Test the objects inserted in the base hook sg_set
      for(; it != itend; ++it, ++rbit)
         if(&*rbit != &*it)   return 1;

      //Test the objects inserted in the member hook sg_set
      for(it = values.begin(); it != itend; ++it, ++mit)
         if(&*mit != &*it) return 1;
   }
   return 0;
}
//]


text:
{-# LANGUAGE TupleSections #-}

-- | Basic types for dictionary handling.

module NLP.Nerf.Dict.Base
(
-- * Lexicon entry
  NeType
, Form
, isMultiWord
, Entry (..)

-- * Dictionary
, Label
, DAWG
, Dict
, fromPairs
, fromEntries
, siftDict
, saveDict
, loadDict

-- * Merging dictionaries
, merge
, diff
) where

import Control.Applicative ((<$>), (<*>))
import Data.Binary (encodeFile, decodeFile)
import Data.Text.Binary ()
import qualified Data.Text as T
import qualified Data.Set as S
import qualified Data.DAWG.Static as D
import qualified Data.DAWG.Trans.Vector as D

-- | A type of named entity.
type NeType = T.Text

-- | A orthographic form.
type Form = T.Text

-- | Is the form a multiword one?
isMultiWord :: Form -> Bool
isMultiWord = (>1) . length . T.words

-- | A Named Entity entry from the LMF dictionary.
data Entry = Entry
    { neOrth :: !Form	-- ^ Orthographic form of the NE
    , neType :: !NeType -- ^ Type of the NE
    } deriving (Show, Read, Eq, Ord)

-- | Dictionary label.
type Label = T.Text

-- | A 'Dict' is a map from forms to labels.  Each form may be annotated
-- with multiple labels.  The map is represented using the directed acyclic
-- word graph.
-- type Dict = D.DAWG (S.Set Label)
type DAWG = D.DAWG D.Trans Char ()
type Dict = DAWG (S.Set Label)

-- | Construct dictionary from the list of form/label pairs.
fromPairs :: [(Form, Label)] -> Dict
fromPairs xs = D.fromListWith S.union
    [ ( T.unpack x
      , S.singleton y)
    | (x, y) <- xs ]

-- | Construct dictionary from the list of entries.
fromEntries :: [Entry] -> Dict
fromEntries = fromPairs . map ((,) <$> neOrth <*> neType)

-- | Remove dictionary entries which do not satisfy the predicate.
siftDict :: (Form -> S.Set Label -> Bool) -> Dict -> Dict
siftDict f dict = D.fromList [(k, v) | (k, v) <- D.assocs dict, f (T.pack k) v]

-- | Save the dictionary in the file.
saveDict :: FilePath -> Dict -> IO ()
saveDict = encodeFile

-- | Load the dictionary from the file.
loadDict :: FilePath -> IO Dict
loadDict = decodeFile

-- | Merge dictionary resources.
merge :: [Dict] -> Dict
merge = unionsWith S.union

-- | Replacement implementation of unionsWith while there is
-- no such function in dawg library.
unionsWith :: Ord a => (a -> a -> a) -> [DAWG a] -> DAWG a
unionsWith f = foldl (unionWith f) D.empty

-- | Replacement implementation of unionWith while there is
-- no such function in dawg library.
unionWith :: Ord a => (a -> a -> a) -> DAWG a -> DAWG a -> DAWG a
unionWith f d d' = D.fromListWith f (D.assocs d ++ D.assocs d')

-- | Differentiate labels from separate dictionaries using
-- dictionary-unique prefixes.
diff :: [Dict] -> [Dict]
diff ds =
    [ mapS (addPrefix i) `mapD` dict
    | (i, dict) <- zip [0..] ds ]

-- | Map function over the DAWG elements.
mapD :: Ord b => (a -> b) -> DAWG a -> DAWG b
mapD f d = D.fromList [(x, f y) | (x, y) <- D.assocs d]

-- | Map function over the set.
mapS :: Ord b => (a -> b) -> S.Set a -> S.Set b
mapS f s = S.fromList [f x | x <- S.toList s]

-- | Add integer prefix.
addPrefix :: Int -> T.Text -> T.Text
addPrefix = T.append . T.pack . show


text:
define(
({
	'bold': 'Halvfet',
	'copy': 'Kopiera ',
	'cut': 'Klipp ut ',
	'delete': 'Ta bort ',
	'indent': 'Indrag',
	'insertHorizontalRule': 'Horisontell linje',
	'insertOrderedList': 'Numrerad lista',
	'insertUnorderedList': 'Punktlista',
	'italic': 'Kursiv',
	'justifyCenter': 'Justera centrerat',
	'justifyFull': 'Justera',
	'justifyLeft': 'Justera till vänster',
	'justifyRight': 'Justera till höger',
	'outdent': 'Utdrag',
	'paste': 'Klistra in',
	'redo': 'Gör om',
	'removeFormat': 'Ta bort format',
	'selectAll': 'Markera allt',
	'strikethrough': 'Genomstrykning',
	'subscript': 'Nedsänkt',
	'superscript': 'Upphöjt',
	'underline': 'Understrykning',
	'undo': 'Ångra',
	'unlink': 'Ta bort länk',
	'createLink': 'Skapa länk',
	'toggleDir': 'Växla riktning',
	'insertImage': 'Infoga bild',
	'insertTable': 'Infoga/redigera tabell',
	'toggleTableBorder': 'Växla tabellkantlinjer',
	'deleteTable': 'Ta bort tabell',
	'tableProp': 'Tabellegenskap',
	'htmlToggle': 'HTML-källa',
	'foreColor': 'Förgrundsfärg',
	'hiliteColor': 'Bakgrundsfärg',
	'plainFormatBlock': 'Styckeformat',
	'formatBlock': 'Styckeformat',
	'fontSize': 'Teckenstorlek',
	'fontName': 'Teckensnitt',
	'tabIndent': 'Indrag tabb',
	"fullScreen": "Växla fullskärm",
	"viewSource": "Visa HTML-kod",
	"print": "Skriv ut",
	"newPage": "Ny sida",
	/* Error messages */
	'systemShortcut': 'Åtgärden ${0} är endast tillgänglig i webbläsaren via ett tangentbordskommando. Använd ${1}.',
	'ctrlKey':'Ctrl+${0}',
	'appleKey':'\u2318${0}' // "command" or open-apple key on Macintosh
})
);


text:
package org.gradle.api.internal.artifacts.ivyservice.modulecache;

import org.gradle.api.artifacts.ResolvedModuleVersion;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ModuleComponentRepository;
import org.gradle.internal.component.external.model.ModuleComponentResolveMetadata;
import org.gradle.internal.component.model.ModuleSources;

import javax.annotation.Nullable;
import java.time.Duration;

public interface ModuleMetadataCache {
    CachedMetadata cacheMissing(ModuleComponentRepository repository, ModuleComponentIdentifier id);

    CachedMetadata cacheMetaData(ModuleComponentRepository repository, ModuleComponentIdentifier id, ModuleComponentResolveMetadata metaData);

    CachedMetadata getCachedModuleDescriptor(ModuleComponentRepository repository, ModuleComponentIdentifier id);

    interface CachedMetadata {
        ResolvedModuleVersion getModuleVersion();

        ModuleComponentResolveMetadata getMetadata();

        Duration getAge();

        boolean isMissing();

        ModuleSources getModuleSources();

        /**
         * The metadata after being processed by component metadata rules.
         * Will be null the first time an entry is read from the filesystem cache during a build invocation.
         *
         * @param key the hash of the rules
         */
        @Nullable
        ModuleComponentResolveMetadata getProcessedMetadata(int key);

        /**
         * Set the processed metadata to be cached in-memory only.
         */
        void putProcessedMetadata(int key, ModuleComponentResolveMetadata processedMetadata);

        /**
         * Returns a copy of this cached metadata where the module metadata is safe to store
         * in-memory, cross-build. That is to say it shouldn't contain any reference to projects,
         * for example.
         */
        ModuleMetadataCache.CachedMetadata dehydrate();
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<meta name="generator" content="JDiff v1.1.1">

<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
Field Differences Index
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="../stylesheet-jdiff.css" TITLE="Style">

All Fields

Removals

Additions

Changes

Bold is New, strike is deleted

N
 TOP

<nobr>NO_SCOPE
</nobr>


text:
'use strict';

/**
 * Properties that describe a base image dependency.
 *
 */
class BaseImageDependency {
  /**
   * Create a BaseImageDependency.
   * @property {string} [type] The type of the base image dependency. Possible
   * values include: 'BuildTime', 'RunTime'
   * @property {string} [registry] The registry login server.
   * @property {string} [repository] The repository name.
   * @property {string} [tag] The tag name.
   * @property {string} [digest] The sha256-based digest of the image manifest.
   */
  constructor() {
  }

  /**
   * Defines the metadata of BaseImageDependency
   *
   * @returns {object} metadata of BaseImageDependency
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'BaseImageDependency',
      type: {
        name: 'Composite',
        className: 'BaseImageDependency',
        modelProperties: {
          type: {
            required: false,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          registry: {
            required: false,
            serializedName: 'registry',
            type: {
              name: 'String'
            }
          },
          repository: {
            required: false,
            serializedName: 'repository',
            type: {
              name: 'String'
            }
          },
          tag: {
            required: false,
            serializedName: 'tag',
            type: {
              name: 'String'
            }
          },
          digest: {
            required: false,
            serializedName: 'digest',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = BaseImageDependency;


text:
package com.intellij.ide.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.colors.impl.AbstractColorsScheme;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author max
 */
public class QuickChangeColorSchemeAction extends QuickSwitchSchemeAction {
  @Override
  protected void fillActions(Project project, @NotNull DefaultActionGroup group, @NotNull DataContext dataContext) {
    EditorColorsScheme current = EditorColorsManager.getInstance().getGlobalScheme();
    for (EditorColorsScheme scheme : EditorColorsManager.getInstance().getAllSchemes()) {
      addScheme(group, current, scheme, false);
    }
  }

  private static void addScheme(final DefaultActionGroup group,
                                final EditorColorsScheme current,
                                final EditorColorsScheme scheme,
                                final boolean addScheme) {
    group.add(new DumbAwareAction(AbstractColorsScheme.getDisplayName(scheme), "", scheme == current ? ourCurrentAction : ourNotCurrentAction) {
      @Override
      public void actionPerformed(@Nullable AnActionEvent e) {
        if (addScheme) {
          EditorColorsManager.getInstance().addColorsScheme(scheme);
        }
        EditorColorsManager.getInstance().setGlobalScheme(scheme);
      }
    });
  }

  @Override
  protected boolean isEnabled() {
    return EditorColorsManager.getInstance().getAllSchemes().length > 1;
  }
}


text:
class BeerSong
  def verses(start = 99, stop = 0)
    start.downto(stop).map do |verse_num|
      verse(verse_num)
    end.join("\n") + "\n"
  end
  alias sing verses

  def verse(num)
    [prefix(num), suffix(num)].join("\n") + "\n"
  end

  private

  def prefix(num)
    "#{quantity(num).capitalize} #{container(num)} of beer on the wall, "\
    "#{quantity(num)} #{container(num)} of beer."
  end

  def suffix(num)
    return last_line if num == 0
    "Take #{cardinality(num)} down and pass it around, #{quantity(num - 1)} "\
      "#{container(num - 1)} of beer on the wall."
  end

  def last_line
    'Go to the store and buy some more, 99 bottles of beer on the wall.'
  end

  def container(num)
    num == 1 ? 'bottle' : 'bottles'
  end

  def quantity(num)
    num == 0 ? 'no more' : num.to_s
  end

  def cardinality(num)
    num == 1 ? 'it' : 'one'
  end
end


text:
/**
* Tae Won Ha
* http://qvacua.com
* https://github.com/qvacua
*
* See LICENSE
*/

#import <objc/runtime.h>

#import "NSObject+TBCacao.h"
#import "TBObjcProperty.h"

@implementation NSObject (TBCacao)

+ (NSString *)classAsString {
  return [NSString stringWithUTF8String:class_getName([self class])];
}

+ (NSArray *)objcProperties {
  NSArray *result = [self objcPropertiesWithoutSuperclass];

  Class superclass = class_getSuperclass(self);

  if (superclass == [NSObject class]) {
    return result;
  }

  return [result arrayByAddingObjectsFromArray:[superclass objcProperties]];
}

+ (NSArray *)objcPropertiesWithoutSuperclass {
  unsigned int nrOfProps;
  objc_property_t *properties = class_copyPropertyList(self, &nrOfProps);

  NSMutableArray *result = [NSMutableArray arrayWithCapacity:nrOfProps];
  for (int i = 0; i < nrOfProps; i++) {
    TBObjcProperty *property = [[TBObjcProperty alloc] initWithProperty:properties[i]];
    [result addObject:property];
  }

  free(properties);

  return result;
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.starproductions.starmotion.starmotion">

    <application
        android:allowBackup="true"
        android:fullBackupContent="@xml/backup_descriptor"
        android:icon="@drawable/starmotion_icon"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:hardwareAccelerated="true">
        <activity
            android:name=".MainActivity.MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".GameActivity.GameActivity"
            android:screenOrientation="portrait"></activity>
    </application>

</manifest>


text:
<?php
namespace Pulu\PalstaBundle\Entity;

use \Pulu\PalstaBundle\Entity\Article;

class Module {

    const TYPE_ADMIN_BEER_TASTING = 1;
    const TYPE_ADMIN_MUNICIPALITY = 2;

    protected $id;
    protected $article;
    protected $name;
    protected $type;

    public function __construct() {
    }

    public function getId() {
        return $this->id;
    }

    public function getArticle() {
        return $this->article;
    }

    public function setArticle(Article $article) {
        $this->article = $article;
        return $this;
    }

    public function getType() {
        return $this->type;
    }

    public function setType($type) {
        $this->type = $type;
        return $this;
    }

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
        return $this;
    }

}


text:
<?php declare(strict_types = 1);

namespace Apitte\Core\DI\Plugin;

use Nette\DI\ContainerBuilder;
use Nette\DI\InvalidConfigurationException;
use Nette\PhpGenerator\ClassType;
use Nette\Schema\Context;
use Nette\Schema\Expect;
use Nette\Schema\Processor;
use Nette\Schema\Schema;
use Nette\Schema\ValidationException;
use stdClass;

abstract class Plugin
{

	/** @var PluginCompiler */
	protected $compiler;

	/** @var stdClass|mixed[] */
	protected $config;

	abstract public static function getName(): string;

	protected function getConfigSchema(): Schema
	{
		return Expect::structure([]);
	}

	public function __construct(PluginCompiler $compiler)
	{
		$this->compiler = $compiler;
	}

	/**
	 * Process and validate config
	 *
	 * @param mixed[] $config
	 */
	public function setupPlugin(array $config = []): void
	{
		$name = $this->compiler->getExtension()->getName() . ' > plugins > ' . static::class;
		$this->setupConfig($this->getConfigSchema(), $config, $name);
	}

	/**
	 * @param mixed[] $config
	 */
	protected function setupConfig(Schema $schema, array $config, string $name): void
	{
		$processor = new Processor();
		$processor->onNewContext[] = function (Context $context) use ($name): void {
			$context->path = [$name];
		};
		try {
			$this->config = $processor->process($schema, $config);
		} catch (ValidationException $exception) {
			throw  new InvalidConfigurationException($exception->getMessage());
		}
	}

	public function loadPluginConfiguration(): void
	{
	}

	public function beforePluginCompile(): void
	{
	}

	public function afterPluginCompile(ClassType $class): void
	{
	}

	protected function prefix(string $id): string
	{
		return $this->compiler->getExtension()->prefix(static::getName() . '.' . $id);
	}

	protected function extensionPrefix(string $id): string
	{
		return $this->compiler->getExtension()->prefix($id);
	}

	protected function getContainerBuilder(): ContainerBuilder
	{
		return $this->compiler->getExtension()->getContainerBuilder();
	}

}


text:
/*
 * Class FieldBreakpoint
 * @author Jeka
 */
package com.intellij.debugger.ui.breakpoints;

import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.SourcePosition;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.SuspendContextImpl;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.jdi.VirtualMachineProxy;
import com.intellij.debugger.engine.requests.RequestManagerImpl;
import com.intellij.debugger.impl.PositionUtil;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.Processor;
import com.intellij.util.text.CharArrayUtil;
import com.intellij.xdebugger.XDebuggerUtil;
import com.sun.jdi.*;
import com.sun.jdi.event.AccessWatchpointEvent;
import com.sun.jdi.event.LocatableEvent;
import com.sun.jdi.event.ModificationWatchpointEvent;
import com.sun.jdi.request.AccessWatchpointRequest;
import com.sun.jdi.request.ModificationWatchpointRequest;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.util.List;

public class FieldBreakpoint extends BreakpointWithHighlighter {
  private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.FieldBreakpoint");
  public boolean WATCH_MODIFICATION = true;
  public boolean WATCH_ACCESS       = false;
  private boolean myIsStatic;
  private String myFieldName;

  @NonNls public static final Key<FieldBreakpoint> CATEGORY = BreakpointCategory.lookup("field_breakpoints");

  protected FieldBreakpoint(Project project) {
    super(project);
  }

  private FieldBreakpoint(Project project, RangeHighlighter highlighter, @NotNull String fieldName) {
    super(project, highlighter);
    myFieldName = fieldName;
  }

  public boolean isStatic() {
    return myIsStatic;
  }

  public String getFieldName() {
    return myFieldName;
  }

  @Override
  protected Icon getDisabledIcon(boolean isMuted) {
    final Breakpoint master = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().findMasterBreakpoint(this);
    if (isMuted) {
      return master == null? AllIcons.Debugger.Db_muted_disabled_field_breakpoint : AllIcons.Debugger.Db_muted_dep_field_breakpoint;
    }
    else {
      return master == null? AllIcons.Debugger.Db_disabled_field_breakpoint : AllIcons.Debugger.Db_dep_field_breakpoint;
    }
  }

  @Override
  protected Icon getSetIcon(boolean isMuted) {
    return isMuted? AllIcons.Debugger.Db_muted_field_breakpoint : AllIcons.Debugger.Db_field_breakpoint;
  }

  @Override
  protected Icon getInvalidIcon(boolean isMuted) {
    return isMuted? AllIcons.Debugger.Db_muted_invalid_field_breakpoint : AllIcons.Debugger.Db_invalid_field_breakpoint;
  }

  @Override
  protected Icon getVerifiedIcon(boolean isMuted) {
    return isMuted? AllIcons.Debugger.Db_muted_verified_field_breakpoint : AllIcons.Debugger.Db_verified_field_breakpoint;
  }

  @Override
  protected Icon getVerifiedWarningsIcon(boolean isMuted) {
    return isMuted? AllIcons.Debugger.Db_muted_field_warning_breakpoint : AllIcons.Debugger.Db_field_warning_breakpoint;
  }

  @Override
  public Key<FieldBreakpoint> getCategory() {
    return CATEGORY;
  }

  public PsiField getPsiField() {
    final SourcePosition sourcePosition = getSourcePosition();
    final PsiField field = ApplicationManager.getApplication().runReadAction(new Computable<PsiField>() {
      @Override
      public PsiField compute() {
        final PsiClass psiClass = getPsiClassAt(sourcePosition);
        return psiClass != null ? psiClass.findFieldByName(myFieldName, true) : null;
      }
    });
    if (field != null) {
      return field;
    }
    return PositionUtil.getPsiElementAt(getProject(), PsiField.class, sourcePosition);
  }

  @Override
  protected void reload(PsiFile psiFile) {
    super.reload(psiFile);
    PsiField field = PositionUtil.getPsiElementAt(getProject(), PsiField.class, getSourcePosition());
    if(field != null) {
      myFieldName = field.getName();
      myIsStatic = field.hasModifierProperty(PsiModifier.STATIC);
    }
    if (myIsStatic) {
      INSTANCE_FILTERS_ENABLED = false;
    }
  }

  @Override
  public boolean moveTo(@NotNull SourcePosition position) {
    final PsiField field = PositionUtil.getPsiElementAt(getProject(), PsiField.class, position);
    return field != null && super.moveTo(SourcePosition.createFromElement(field));
  }

  @Override
  protected ObjectReference getThisObject(SuspendContextImpl context, LocatableEvent event) throws EvaluateException {
    if (event instanceof ModificationWatchpointEvent) {
      ModificationWatchpointEvent modificationEvent = (ModificationWatchpointEvent)event;
      ObjectReference reference = modificationEvent.object();
      if (reference != null) {  // non-static
        return reference;
      }
    }
    else if (event instanceof AccessWatchpointEvent) {
      AccessWatchpointEvent accessEvent = (AccessWatchpointEvent)event;
      ObjectReference reference = accessEvent.object();
      if (reference != null) { // non-static
        return reference;
      }
    }

    return super.getThisObject(context, event);
  }

  @Override
  public void createRequestForPreparedClass(DebugProcessImpl debugProcess,
                                            ReferenceType refType) {
    VirtualMachineProxy vm = debugProcess.getVirtualMachineProxy();
    try {
      Field field = refType.fieldByName(myFieldName);
      if (field == null) {
        debugProcess.getRequestsManager().setInvalid(this, DebuggerBundle.message("error.invalid.breakpoint.missing.field.in.class", myFieldName, refType.name()));
        return;
      }
      RequestManagerImpl manager = debugProcess.getRequestsManager();
      if (WATCH_MODIFICATION && vm.canWatchFieldModification()) {
        ModificationWatchpointRequest request = manager.createModificationWatchpointRequest(this, field);
        debugProcess.getRequestsManager().enableRequest(request);
        if (LOG.isDebugEnabled()) {
          LOG.debug("Modification request added");
        }
      }
      if (WATCH_ACCESS && vm.canWatchFieldAccess()) {
        AccessWatchpointRequest request = manager.createAccessWatchpointRequest(this, field);
        debugProcess.getRequestsManager().enableRequest(request);
        if (LOG.isDebugEnabled()) {
          LOG.debug("Access request added field = "+field.name() + "; refType = "+refType.name());
        }
      }
    }
    catch (ObjectCollectedException ex) {
      LOG.debug(ex);
    }
    catch (Exception ex) {
      LOG.debug(ex);
    }
  }

  @Override
  public String getEventMessage(final LocatableEvent event) {
    final Location location = event.location();
    final String locationQName = location.declaringType().name() + "." + location.method().name();
    String locationFileName;
    try {
      locationFileName = location.sourceName();
    }
    catch (AbsentInformationException e) {
      locationFileName = getSourcePosition().getFile().getName();
    }
    final int locationLine = location.lineNumber();

    if (event instanceof ModificationWatchpointEvent) {
      final ModificationWatchpointEvent modificationEvent = (ModificationWatchpointEvent)event;
      final ObjectReference object = modificationEvent.object();
      final Field field = modificationEvent.field();
      if (object != null) {
        return DebuggerBundle.message(
          "status.field.watchpoint.reached.modification",
          field.declaringType().name(),
          field.name(),
          modificationEvent.valueCurrent(),
          modificationEvent.valueToBe(),
          locationQName,
          locationFileName,
          locationLine,
          object.uniqueID()
        );
      }
      return DebuggerBundle.message(
        "status.static.field.watchpoint.reached.modification",
        field.declaringType().name(),
        field.name(),
        modificationEvent.valueCurrent(),
        modificationEvent.valueToBe(),
        locationQName,
        locationFileName,
        locationLine
      );
    }
    if (event instanceof AccessWatchpointEvent) {
      AccessWatchpointEvent accessEvent = (AccessWatchpointEvent)event;
      final ObjectReference object = accessEvent.object();
      final Field field = accessEvent.field();
      if (object != null) {
        return DebuggerBundle.message(
          "status.field.watchpoint.reached.access",
          field.declaringType().name(),
          field.name(),
          locationQName,
          locationFileName,
          locationLine,
          object.uniqueID()
        );
      }
      return DebuggerBundle.message(
        "status.static.field.watchpoint.reached.access",
        field.declaringType().name(),
        field.name(),
        locationQName,
        locationFileName,
        locationLine
      );
    }
    return null;
  }

  @Override
  public String getDisplayName() {
    if(!isValid()) {
      return DebuggerBundle.message("status.breakpoint.invalid");
    }
    final String className = getClassName();
    return className != null && !className.isEmpty() ? className + "." + myFieldName : myFieldName;
  }

  public static FieldBreakpoint create(@NotNull Project project, @NotNull Document document, int lineIndex, String fieldName) {
    FieldBreakpoint breakpoint = new FieldBreakpoint(project, createHighlighter(project, document, lineIndex), fieldName);
    return (FieldBreakpoint)breakpoint.init();
  }

  @Override
  public boolean canMoveTo(final SourcePosition position) {
    return super.canMoveTo(position) && PositionUtil.getPsiElementAt(getProject(), PsiField.class, position) != null;
  }

  @Override
  public boolean isValid() {
    return super.isValid() && getPsiField() != null;
  }

  @Override
  public boolean isAt(@NotNull Document document, int offset) {
    PsiField field = findField(myProject, document, offset);
    return field == getPsiField();
  }

  protected static FieldBreakpoint create(@NotNull Project project, @NotNull Field field, ObjectReference object) {
    String fieldName = field.name();
    int line = 0;
    Document document = null;
    try {
      List locations = field.declaringType().allLineLocations();
      if(!locations.isEmpty()) {
        Location location = (Location)locations.get(0);
        line = location.lineNumber();
        VirtualFile file = VirtualFileManager.getInstance().findFileByUrl(location.sourcePath());
        if(file != null) {
          PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
          if(psiFile != null) {
            document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
          }
        }
      }
    }
    catch (AbsentInformationException e) {
      LOG.debug(e);
    }
    catch (InternalError e) {
      LOG.debug(e);
    }

    if(document == null) return null;

    FieldBreakpoint fieldBreakpoint = new FieldBreakpoint(project, createHighlighter(project, document, line), fieldName);
    if (!fieldBreakpoint.isStatic()) {
      fieldBreakpoint.addInstanceFilter(object.uniqueID());
    }
    return (FieldBreakpoint)fieldBreakpoint.init();
  }

  public static PsiField findField(Project project, Document document, int offset) {
    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(document);
    if(file == null) return null;
    offset = CharArrayUtil.shiftForward(document.getCharsSequence(), offset, " \t");
    PsiElement element = file.findElementAt(offset);
    if(element == null) return null;
    PsiField field = PsiTreeUtil.getParentOfType(element, PsiField.class, false);
    int line = document.getLineNumber(offset);
    if(field == null) {
      final PsiField[] fld = {null};
      XDebuggerUtil.getInstance().iterateLine(project, document, line, new Processor<PsiElement>() {
        @Override
        public boolean process(PsiElement element) {
          PsiField field = PsiTreeUtil.getParentOfType(element, PsiField.class, false);
          if(field != null) {
            fld[0] = field;
            return false;
          }
          return true;
        }
      });
      field = fld[0];
    }

    return field;
  }

  @Override
  public void readExternal(@NotNull Element breakpointNode) throws InvalidDataException {
    super.readExternal(breakpointNode);
    //noinspection HardCodedStringLiteral
    myFieldName = breakpointNode.getAttributeValue("field_name");
    if(myFieldName == null) {
      throw new InvalidDataException("No field name for field breakpoint");
    }
  }

  @Override
  @SuppressWarnings({"HardCodedStringLiteral"})
  public void writeExternal(@NotNull Element parentNode) throws WriteExternalException {
    super.writeExternal(parentNode);
    parentNode.setAttribute("field_name", getFieldName());
  }

  @Override
  public PsiElement getEvaluationElement() {
    return getPsiClass();
  }
}


text:
/* JScriptRender alias */
if (!window.hasOwnProperty('JScriptRender'))
   JScriptRender = {};

/* Namespace */
if (!JScriptRender.hasOwnProperty('jquery'))
   JScriptRender.jquery = new Object();

/* Animation class */
JScriptRender.jquery.Animation = new Function();

JScriptRender.jquery.Animation.prototype =
{
    slider: function(slide, settings)
        {
        var set = settings || {};

        set.effect = set.effect || "fade";
        set.keys = set.keys || false;

        // Right button functionality
        slide.children(".toolbar").children(".button-right").click(function()
        {
            var cssHeight = slide.css("height");
            slide.css("height", cssHeight);
            setTimeout(function(){slide.css("height", "")},1000);

            var items = [];
            $.each(slide.children(".item"),function(){
               items.push($(this));
            });

            iters = items.length;
            for (var i = 0; i < iters; i++) {
                /* Detects if the current element is visible and if exists an next element. If there is,
                 * the visible element is hidden and the next element is displayed. */
                if (items[i].css("display") != "none" && (i+1) in items) {
                    items[i].hide(set.effect,{direction: "left"},400);
                    var nextElement = items[i+1];
                        nextElement.delay(400).show(set.effect,{direction: "right"},400);
                    break;
                }
                /* If the visible element is the last element, the first element is displayed */
                else if (items[i].css("display") != "none") {
                    items[i].hide(set.effect,{direction: "right"},400);
                        items[0].delay(400).show(set.effect,{direction: "left"},400);
                }
            }
        });

        // Left button functionality
        slide.children(".toolbar").children(".button-left").click(function()
        {
            var cssHeight = slide.css("height");
            slide.css("height", cssHeight);
            setTimeout(function(){slide.css("height", "")},1000);

            var items = [];
            $.each(slide.children(".item"),function(){
               items.push($(this));
            });

            iters = items.length;
            for (var i=0;i<iters;i++) {
                /* Detects if the current element is visible and if exists an before element. If there is,
                 * the visible element is hidden and the before element is displayed. */
                if (items[i].css("display") != "none" && (i-1) in items) {
                    items[i].hide(set.effect,{direction: "right"},400);
                    var nextElement = items[i-1];
                    nextElement.delay(400).show(set.effect,{direction: "left"},400);
                    break;
                }
                /* If the visible element is the first element, the last element is displayed */
                else if (items[i].css("display") != "none") {
                    items[i].hide(set.effect,{direction: "left"},400);
                    items[items.length-1].delay(400).show(set.effect,{direction: "right"},400);
                    break;      // Es necesario, puesto que se detecta el primer elemento y no el último
                }
            }
        });

        // Down button functionality
        slide.children(".button-down").click(function(){

            var slide = $(".slide");

            if (slide[0].style.height != "auto") {
                slide.css({"height": "auto"});
                $(this).children("span").removeClass("glyphicon-chevron-down");
                $(this).children("span").addClass("glyphicon-chevron-up");
            }
            else {
                slide.animate({height: "400px"},1300);
                $(this).children("span").removeClass("glyphicon-chevron-up");
                $(this).children("span").addClass("glyphicon-chevron-down");
            }
        });

        // Keys functionality
        if (set.keys) {
            $("body").keydown(function(event){
                var keycode = event.which;
                if (keycode == 37)
                    slide.children(".toolbar").children(".button-left").trigger("click");
                if (keycode == 39)
                    slide.children(".toolbar").children(".button-right").trigger("click");
            });
        }
    }
}


text:
<select ng-attr-id="{{ fieldId }}"
        ng-disabled="disabled"
        guac-focus="focused"
        ng-model="model"
        ng-options="option as getFieldOption(option) | translate for option in field.options | orderBy: value"></select>


text:
<?php

namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler;

use Monolog\Processor\ProcessorInterface;
use Symfony\Component\DependencyInjection\Argument\BoundArgument;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

/**
 * Injects the session tracker enabler in "security.context_listener" + binds "security.untracked_token_storage" to ProcessorInterface instances.
 *
 * @author Nicolas Grekas <p@tchwork.com>
 *
 * @internal
 */
class RegisterTokenUsageTrackingPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->has('security.untracked_token_storage')) {
            return;
        }

        $processorAutoconfiguration = $container->registerForAutoconfiguration(ProcessorInterface::class);
        $processorAutoconfiguration->setBindings($processorAutoconfiguration->getBindings() + [
            TokenStorageInterface::class => new BoundArgument(new Reference('security.untracked_token_storage'), false),
        ]);

        if (!$container->has('session.factory')) {
            $container->setAlias('security.token_storage', 'security.untracked_token_storage')->setPublic(true);
            $container->getDefinition('security.untracked_token_storage')->addTag('kernel.reset', ['method' => 'reset']);
        } elseif ($container->hasDefinition('security.context_listener')) {
            $tokenStorageClass = $container->getParameterBag()->resolveValue($container->findDefinition('security.token_storage')->getClass());

            if (method_exists($tokenStorageClass, 'enableUsageTracking')) {
                $container->getDefinition('security.context_listener')
                    ->setArgument(6, [new Reference('security.token_storage'), 'enableUsageTracking']);
            }
        }
    }
}


text:
package com.hood.transcoder.persistence;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.AmazonClientException;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
import com.hood.transcoder.domain.movie.Movie;
import com.hood.transcoder.domain.movie.MovieId;
import com.hood.transcoder.domain.movie.MovieNotStoredException;
import com.hood.transcoder.domain.movie.MovieRepository;

public class S3MovieRepository implements MovieRepository
{
    private static final Logger logger = LoggerFactory.getLogger( S3MovieRepository.class );
    private static final String S3_BUCKET_HOOD_ETS_SOURCE = "hood-ets-source";

    private final TransferManager transferManager;

    public S3MovieRepository( final TransferManager transferManager )
    {
        this.transferManager = transferManager;
    }

    @Override
    public Movie get( final MovieId movieId )
    {
        final String key = movieId.getMovieId();
        logger.debug( "Downloading {} from S3", key );
        final GetObjectRequest getObjectRequest = new GetObjectRequest( S3_BUCKET_HOOD_ETS_SOURCE, key );
        try
        {
            final Path outputPath = Files.createTempFile( "movie", key );
            final File outputFile = outputPath.toFile();
            this.transferManager.getAmazonS3Client().getObject( getObjectRequest, outputFile );
            return new Movie( new MovieId( outputFile.getAbsolutePath() ), outputPath );
        }
        catch ( final Exception e )
        {
            logger.error( "Exception while downloading", e );
        }
        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.hood.transcoder.MovieRepository#store(com.hood.transcoder.Movie)
     */
    @Override
    public void store( final Movie movie ) throws MovieNotStoredException
    {
        final String key = movie.getMovieId().getMovieId();
        logger.info( "Uploading {} to S3 key {}", movie, key );
        final File movieFile = movie.getPath().toFile();
        final PutObjectRequest putObjectRequest = new PutObjectRequest( S3_BUCKET_HOOD_ETS_SOURCE, key, movieFile );
        final ProgressListener progressListener = new S3ProgressListener( key, movieFile.length() );
        try
        {
            final Upload upload = this.transferManager.upload( putObjectRequest );
            upload.addProgressListener( progressListener );
            upload.waitForCompletion();
        }
        catch ( AmazonClientException | InterruptedException e )
        {
            this.transferManager.abortMultipartUploads( S3_BUCKET_HOOD_ETS_SOURCE, new Date() );
            throw new MovieNotStoredException( movie, e );
        }
        logger.info( "Upload complete." );
    }

    /*
     * (non-Javadoc)
     *
     * @see com.hood.transcoder.MovieRepository#remove(com.hood.transcoder.Movie)
     */
    @Override
    public void remove( final Movie movie )
    {
        final String key = movie.getMovieId().getMovieId();
        logger.info( "Deleting file: {}", key );
        this.transferManager.getAmazonS3Client().deleteObject( S3_BUCKET_HOOD_ETS_SOURCE, key );
    }
}


text:
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

const API_URI = (env) => {
  return (env === 'development') ? `http://localhost:${process.env.API_PORT || 3000}` : ''
}
const api = axios.create({
  baseURL: `${API_URI(process.env.NODE_ENV)}/api/v1`,
})

const state = {
  list: [],
}

const getters = {
  all(state) {
    return state.list.sort((itemA, itemB) => {
      if (itemA.isDone === itemB.isDone) return 0
      return itemA.isDone ? 1 : -1
    })
  },
  complete(state) {
    return state.list.filter((item) => {
      return item.isDone
    })
  },
  incomplete(state) {
    return state.list.filter((item) => {
      return !item.isDone
    })
  },
}

const mutations = {
  updateList(state, payload) {
    state.list = payload.list
  },
  addTodo(state, { todo }) {
    state.list.push(todo)
  },
  updateTodo(state, { updatedTodo }) {
    let before = state.list.find((beforeItem) => {
      return beforeItem.id === updatedTodo.id
    })
    Object.keys(before).forEach((key) => {
      before[key] = updatedTodo[key]
    })
  },
  deleteTodo(state, { deletedId }) {
    const idx = state.list.findIndex((item) => {
      return item.id === deletedId
    })
    state.list.splice(idx, 1)
  },
}

const actions = {
  updateList(context) {
    return api
      .get('/todos')
      .then((result) => {
        context.commit('updateList', {list: result.data})
        Promise.resolve(result)
      })
  },
  createTodo(context, newTodo) {
    return api
      .post(`/todos`, newTodo)
      .then((result) => {
        context.commit('addTodo', {todo: result.data})
        Promise.resolve(result)
      })
  },
  updateTodo(context, { id, patch }) {
    return api
      .patch(`/todos/${id}`, patch)
      .then((result) => {
        context.commit('updateTodo', {updatedTodo: result.data})
        Promise.resolve(result)
      })
  },
  deleteTodo(context, { id }) {
    return api
      .delete(`/todos/${id}`)
      .then((result) => {
        context.commit('deleteTodo', {deletedId: id})
        Promise.resolve(result)
      })
  },
}

Vue.use(Vuex)
export default new Vuex.Store({
  state,
  getters,
  mutations,
  actions,
})


text:
namespace base {
namespace trace_event {
class ConvertableToTraceFormat;
}
}

namespace blink {
namespace scheduler {
class AutoAdvancingVirtualTimeDomain;
class RenderWidgetSchedulingState;
class WebViewSchedulerImpl;
class TaskQueueThrottler;

class BLINK_PLATFORM_EXPORT RendererSchedulerImpl
    : public RendererScheduler,
      public IdleHelper::Delegate,
      public SchedulerHelper::Observer,
      public RenderWidgetSignals::Observer,
      public TaskTimeObserver,
      public QueueingTimeEstimator::Client,
      public base::trace_event::TraceLog::AsyncEnabledStateObserver {
 public:
  // Keep RendererScheduler::UseCaseToString in sync with this enum.
  enum class UseCase {
    // No active use case detected.
    NONE,
    // A continuous gesture (e.g., scroll, pinch) which is being driven by the
    // compositor thread.
    COMPOSITOR_GESTURE,
    // An unspecified touch gesture which is being handled by the main thread.
    // Note that since we don't have a full view of the use case, we should be
    // careful to prioritize all work equally.
    MAIN_THREAD_CUSTOM_INPUT_HANDLING,
    // A continuous gesture (e.g., scroll, pinch) which is being driven by the
    // compositor thread but also observed by the main thread. An example is
    // synchronized scrolling where a scroll listener on the main thread changes
    // page layout based on the current scroll position.
    SYNCHRONIZED_GESTURE,
    // A gesture has recently started and we are about to run main thread touch
    // listeners to find out the actual gesture type. To minimize touch latency,
    // only input handling work should run in this state.
    TOUCHSTART,
    // The page is loading.
    LOADING,
    // A continuous gesture (e.g., scroll) which is being handled by the main
    // thread.
    MAIN_THREAD_GESTURE,
    // Must be the last entry.
    USE_CASE_COUNT,
    FIRST_USE_CASE = NONE,
  };
  static const char* UseCaseToString(UseCase use_case);
  static const char* RAILModeToString(v8::RAILMode rail_mode);

  RendererSchedulerImpl(scoped_refptr<SchedulerTqmDelegate> main_task_runner);
  ~RendererSchedulerImpl() override;

  // RendererScheduler implementation:
  std::unique_ptr<WebThread> CreateMainThread() override;
  scoped_refptr<TaskQueue> DefaultTaskRunner() override;
  scoped_refptr<SingleThreadIdleTaskRunner> IdleTaskRunner() override;
  scoped_refptr<TaskQueue> CompositorTaskRunner() override;
  scoped_refptr<TaskQueue> LoadingTaskRunner() override;
  scoped_refptr<TaskQueue> TimerTaskRunner() override;
  scoped_refptr<TaskQueue> NewLoadingTaskRunner(
      TaskQueue::QueueType queue_type) override;
  scoped_refptr<TaskQueue> NewTimerTaskRunner(
      TaskQueue::QueueType queue_type) override;
  scoped_refptr<TaskQueue> NewUnthrottledTaskRunner(
      TaskQueue::QueueType queue_type) override;
  std::unique_ptr<RenderWidgetSchedulingState> NewRenderWidgetSchedulingState()
      override;
  void WillBeginFrame(const cc::BeginFrameArgs& args) override;
  void BeginFrameNotExpectedSoon() override;
  void DidCommitFrameToCompositor() override;
  void DidHandleInputEventOnCompositorThread(
      const WebInputEvent& web_input_event,
      InputEventState event_state) override;
  void DidHandleInputEventOnMainThread(
      const WebInputEvent& web_input_event) override;
  void DidAnimateForInputOnCompositorThread() override;
  void OnRendererBackgrounded() override;
  void OnRendererForegrounded() override;
  void SuspendRenderer() override;
  void ResumeRenderer() override;
  void AddPendingNavigation(WebScheduler::NavigatingFrameType type) override;
  void RemovePendingNavigation(WebScheduler::NavigatingFrameType type) override;
  void OnNavigationStarted() override;
  bool IsHighPriorityWorkAnticipated() override;
  bool ShouldYieldForHighPriorityWork() override;
  bool CanExceedIdleDeadlineIfRequired() const override;
  void AddTaskObserver(base::MessageLoop::TaskObserver* task_observer) override;
  void RemoveTaskObserver(
      base::MessageLoop::TaskObserver* task_observer) override;
  void Shutdown() override;
  void SuspendTimerQueue() override;
  void ResumeTimerQueue() override;
  void SetTimerQueueSuspensionWhenBackgroundedEnabled(bool enabled) override;
  void SetTopLevelBlameContext(
      base::trace_event::BlameContext* blame_context) override;
  void SetRAILModeObserver(RAILModeObserver* observer) override;

  // RenderWidgetSignals::Observer implementation:
  void SetAllRenderWidgetsHidden(bool hidden) override;
  void SetHasVisibleRenderWidgetWithTouchHandler(
      bool has_visible_render_widget_with_touch_handler) override;

  // SchedulerHelper::Observer implementation:
  void OnUnregisterTaskQueue(const scoped_refptr<TaskQueue>& queue) override;
  void OnTriedToExecuteBlockedTask(const TaskQueue& queue,
                                   const base::PendingTask& task) override;

  // TaskTimeObserver implementation:
  void ReportTaskTime(TaskQueue* task_queue,
                      double start_time,
                      double end_time) override;

  // QueueingTimeEstimator::Client implementation:
  void OnQueueingTimeForWindowEstimated(base::TimeDelta queueing_time) override;

  // Returns a task runner where tasks run at the highest possible priority.
  scoped_refptr<TaskQueue> ControlTaskRunner();

  void RegisterTimeDomain(TimeDomain* time_domain);
  void UnregisterTimeDomain(TimeDomain* time_domain);

  // Tells the scheduler that all TaskQueues should use virtual time.
  void EnableVirtualTime();

  void AddWebViewScheduler(WebViewSchedulerImpl* web_view_scheduler);
  void RemoveWebViewScheduler(WebViewSchedulerImpl* web_view_scheduler);

  void AddTaskTimeObserver(TaskTimeObserver* task_time_observer);
  void RemoveTaskTimeObserver(TaskTimeObserver* task_time_observer);

  // Snapshots this RendererScheduler for tracing.
  void CreateTraceEventObjectSnapshot() const;

  // Called when one of associated WebView schedulers has changed audio
  // state.
  void OnAudioStateChanged();

  // Test helpers.
  SchedulerHelper* GetSchedulerHelperForTesting();
  TaskCostEstimator* GetLoadingTaskCostEstimatorForTesting();
  TaskCostEstimator* GetTimerTaskCostEstimatorForTesting();
  IdleTimeEstimator* GetIdleTimeEstimatorForTesting();
  base::TimeTicks CurrentIdleTaskDeadlineForTesting() const;
  void RunIdleTasksForTesting(const base::Closure& callback);
  void EndIdlePeriodForTesting(const base::Closure& callback,
                               base::TimeTicks time_remaining);
  bool PolicyNeedsUpdateForTesting();

  base::TickClock* tick_clock() const;

  RealTimeDomain* real_time_domain() const {
    return helper_.real_time_domain();
  }

  AutoAdvancingVirtualTimeDomain* GetVirtualTimeDomain();

  TimeDomain* GetActiveTimeDomain();

  TaskQueueThrottler* task_queue_throttler() const {
    return task_queue_throttler_.get();
  }

  // base::trace_event::TraceLog::EnabledStateObserver implementation:
  void OnTraceLogEnabled() override;
  void OnTraceLogDisabled() override;

 private:
  friend class RendererSchedulerImplTest;
  friend class RendererSchedulerImplForTest;
  friend class RenderWidgetSchedulingState;

  enum class ExpensiveTaskPolicy { RUN, BLOCK, THROTTLE };

  enum class TimeDomainType {
    REAL,
    THROTTLED,
    VIRTUAL,
  };

  static const char* TimeDomainTypeToString(TimeDomainType domain_type);

  struct TaskQueuePolicy {
    TaskQueuePolicy()
        : is_enabled(true),
          priority(TaskQueue::NORMAL_PRIORITY),
          time_domain_type(TimeDomainType::REAL) {}

    bool is_enabled;
    TaskQueue::QueuePriority priority;
    TimeDomainType time_domain_type;

    bool operator==(const TaskQueuePolicy& other) const {
      return is_enabled == other.is_enabled && priority == other.priority &&
             time_domain_type == other.time_domain_type;
    }

    void AsValueInto(base::trace_event::TracedValue* state) const;
  };

  struct Policy {
    TaskQueuePolicy compositor_queue_policy;
    TaskQueuePolicy loading_queue_policy;
    TaskQueuePolicy timer_queue_policy;
    TaskQueuePolicy default_queue_policy;
    v8::RAILMode rail_mode = v8::PERFORMANCE_ANIMATION;
    bool should_disable_throttling = false;

    bool operator==(const Policy& other) const {
      return compositor_queue_policy == other.compositor_queue_policy &&
             loading_queue_policy == other.loading_queue_policy &&
             timer_queue_policy == other.timer_queue_policy &&
             default_queue_policy == other.default_queue_policy &&
             rail_mode == other.rail_mode &&
             should_disable_throttling == other.should_disable_throttling;
    }

    void AsValueInto(base::trace_event::TracedValue* state) const;
  };

  class PollableNeedsUpdateFlag {
   public:
    PollableNeedsUpdateFlag(base::Lock* write_lock);
    ~PollableNeedsUpdateFlag();

    // Set the flag. May only be called if |write_lock| is held.
    void SetWhileLocked(bool value);

    // Returns true iff the flag is set to true.
    bool IsSet() const;

   private:
    base::subtle::Atomic32 flag_;
    base::Lock* write_lock_;  // Not owned.

    DISALLOW_COPY_AND_ASSIGN(PollableNeedsUpdateFlag);
  };

  // IdleHelper::Delegate implementation:
  bool CanEnterLongIdlePeriod(
      base::TimeTicks now,
      base::TimeDelta* next_long_idle_period_delay_out) override;
  void IsNotQuiescent() override {}
  void OnIdlePeriodStarted() override;
  void OnIdlePeriodEnded() override;

  void EndIdlePeriod();

  // Returns the serialized scheduler state for tracing.
  std::unique_ptr<base::trace_event::ConvertableToTraceFormat> AsValue(
      base::TimeTicks optional_now) const;
  std::unique_ptr<base::trace_event::ConvertableToTraceFormat> AsValueLocked(
      base::TimeTicks optional_now) const;
  void CreateTraceEventObjectSnapshotLocked() const;

  static bool ShouldPrioritizeInputEvent(const WebInputEvent& web_input_event);

  // The amount of time which idle periods can continue being scheduled when the
  // renderer has been hidden, before going to sleep for good.
  static const int kEndIdleWhenHiddenDelayMillis = 10000;

  // The amount of time for which loading tasks will be prioritized over
  // other tasks during the initial page load.
  static const int kRailsInitialLoadingPrioritizationMillis = 1000;

  // The amount of time in milliseconds we have to respond to user input as
  // defined by RAILS.
  static const int kRailsResponseTimeMillis = 50;

  // The amount of time to wait before suspending shared timers after the
  // renderer has been backgrounded. This is used only if background suspension
  // of shared timers is enabled.
  static const int kSuspendTimersWhenBackgroundedDelayMillis = 5 * 60 * 1000;

  // The time we should stay in a priority-escalated mode after a call to
  // DidAnimateForInputOnCompositorThread().
  static const int kFlingEscalationLimitMillis = 100;

  // Schedules an immediate PolicyUpdate, if there isn't one already pending and
  // sets |policy_may_need_update_|. Note |any_thread_lock_| must be
  // locked.
  void EnsureUrgentPolicyUpdatePostedOnMainThread(
      const tracked_objects::Location& from_here);

  // Update the policy if a new signal has arrived. Must be called from the main
  // thread.
  void MaybeUpdatePolicy();

  // Locks |any_thread_lock_| and updates the scheduler policy.  May early
  // out if the policy is unchanged. Must be called from the main thread.
  void UpdatePolicy();

  // Like UpdatePolicy, except it doesn't early out.
  void ForceUpdatePolicy();

  enum class UpdateType {
    MAY_EARLY_OUT_IF_POLICY_UNCHANGED,
    FORCE_UPDATE,
  };

  // The implelemtation of UpdatePolicy & ForceUpdatePolicy.  It is allowed to
  // early out if |update_type| is MAY_EARLY_OUT_IF_POLICY_UNCHANGED.
  virtual void UpdatePolicyLocked(UpdateType update_type);

  // Helper for computing the use case. |expected_usecase_duration| will be
  // filled with the amount of time after which the use case should be updated
  // again. If the duration is zero, a new use case update should not be
  // scheduled. Must be called with |any_thread_lock_| held. Can be called from
  // any thread.
  UseCase ComputeCurrentUseCase(
      base::TimeTicks now,
      base::TimeDelta* expected_use_case_duration) const;

  // An input event of some sort happened, the policy may need updating.
  void UpdateForInputEventOnCompositorThread(WebInputEvent::Type type,
                                             InputEventState input_event_state);

  // Helpers for safely suspending/resuming the timer queue after a
  // background/foreground signal.
  void SuspendTimerQueueWhenBackgrounded();
  void ResumeTimerQueueWhenForegroundedOrResumed();

  // The task cost estimators and the UserModel need to be reset upon page
  // nagigation. This function does that. Must be called from the main thread.
  void ResetForNavigationLocked();

  // Estimates the maximum task length that won't cause a jank based on the
  // current system state. Must be called from the main thread.
  base::TimeDelta EstimateLongestJankFreeTaskDuration() const;

  // Report an intervention to all WebViews in this process.
  void BroadcastIntervention(const std::string& message);

  void ApplyTaskQueuePolicy(TaskQueue* task_queue,
                            const TaskQueuePolicy& old_task_queue_policy,
                            const TaskQueuePolicy& new_task_queue_policy) const;

  static const char* ExpensiveTaskPolicyToString(
      ExpensiveTaskPolicy expensive_task_policy);

  bool ShouldDisableThrottlingBecauseOfAudio(base::TimeTicks now);

  SchedulerHelper helper_;
  IdleHelper idle_helper_;
  std::unique_ptr<TaskQueueThrottler> task_queue_throttler_;
  RenderWidgetSignals render_widget_scheduler_signals_;

  const scoped_refptr<TaskQueue> control_task_runner_;
  const scoped_refptr<TaskQueue> compositor_task_runner_;
  std::set<scoped_refptr<TaskQueue>> loading_task_runners_;
  std::set<scoped_refptr<TaskQueue>> timer_task_runners_;
  std::set<scoped_refptr<TaskQueue>> unthrottled_task_runners_;
  scoped_refptr<TaskQueue> default_loading_task_runner_;
  scoped_refptr<TaskQueue> default_timer_task_runner_;

  // Note |virtual_time_domain_| is lazily created.
  std::unique_ptr<AutoAdvancingVirtualTimeDomain> virtual_time_domain_;

  base::Closure update_policy_closure_;
  DeadlineTaskRunner delayed_update_policy_runner_;
  CancelableClosureHolder end_renderer_hidden_idle_period_closure_;
  CancelableClosureHolder suspend_timers_when_backgrounded_closure_;

  // We have decided to improve thread safety at the cost of some boilerplate
  // (the accessors) for the following data members.

  struct MainThreadOnly {
    MainThreadOnly(RendererSchedulerImpl* renderer_scheduler_impl,
                   const scoped_refptr<TaskQueue>& compositor_task_runner,
                   base::TickClock* time_source,
                   base::TimeTicks now);
    ~MainThreadOnly();

    TaskCostEstimator loading_task_cost_estimator;
    TaskCostEstimator timer_task_cost_estimator;
    QueueingTimeEstimator queueing_time_estimator;
    IdleTimeEstimator idle_time_estimator;
    ThreadLoadTracker background_main_thread_load_tracker;
    ThreadLoadTracker foreground_main_thread_load_tracker;
    UseCase current_use_case;
    Policy current_policy;
    base::TimeTicks current_policy_expiration_time;
    base::TimeTicks estimated_next_frame_begin;
    base::TimeDelta compositor_frame_interval;
    base::TimeDelta longest_jank_free_task_duration;
    base::Optional<base::TimeTicks> last_audio_state_change;
    int timer_queue_suspend_count;  // TIMER_TASK_QUEUE suspended if non-zero.
    int navigation_task_expected_count;
    ExpensiveTaskPolicy expensive_task_policy;
    bool renderer_hidden;
    bool renderer_backgrounded;
    bool renderer_suspended;
    bool timer_queue_suspension_when_backgrounded_enabled;
    bool timer_queue_suspended_when_backgrounded;
    bool was_shutdown;
    bool loading_tasks_seem_expensive;
    bool timer_tasks_seem_expensive;
    bool touchstart_expected_soon;
    bool have_seen_a_begin_main_frame;
    bool have_reported_blocking_intervention_in_current_policy;
    bool have_reported_blocking_intervention_since_navigation;
    bool has_visible_render_widget_with_touch_handler;
    bool begin_frame_not_expected_soon;
    bool in_idle_period_for_testing;
    bool use_virtual_time;
    bool is_audio_playing;
    std::set<WebViewSchedulerImpl*> web_view_schedulers;  // Not owned.
    RAILModeObserver* rail_mode_observer;                 // Not owned.
  };

  struct AnyThread {
    AnyThread();
    ~AnyThread();

    base::TimeTicks last_idle_period_end_time;
    base::TimeTicks rails_loading_priority_deadline;
    base::TimeTicks fling_compositor_escalation_deadline;
    UserModel user_model;
    bool awaiting_touch_start_response;
    bool in_idle_period;
    bool begin_main_frame_on_critical_path;
    bool last_gesture_was_compositor_driven;
    bool default_gesture_prevented;
    bool have_seen_touchstart;
  };

  struct CompositorThreadOnly {
    CompositorThreadOnly();
    ~CompositorThreadOnly();

    WebInputEvent::Type last_input_type;
    std::unique_ptr<base::ThreadChecker> compositor_thread_checker;

    void CheckOnValidThread() {
#if DCHECK_IS_ON()
      // We don't actually care which thread this called from, just so long as
      // its consistent.
      if (!compositor_thread_checker)
        compositor_thread_checker.reset(new base::ThreadChecker());
      DCHECK(compositor_thread_checker->CalledOnValidThread());
#endif
    }
  };

  // Don't access main_thread_only_, instead use MainThreadOnly().
  MainThreadOnly main_thread_only_;
  MainThreadOnly& MainThreadOnly() {
    helper_.CheckOnValidThread();
    return main_thread_only_;
  }
  const struct MainThreadOnly& MainThreadOnly() const {
    helper_.CheckOnValidThread();
    return main_thread_only_;
  }

  mutable base::Lock any_thread_lock_;
  // Don't access any_thread_, instead use AnyThread().
  AnyThread any_thread_;
  AnyThread& AnyThread() {
    any_thread_lock_.AssertAcquired();
    return any_thread_;
  }
  const struct AnyThread& AnyThread() const {
    any_thread_lock_.AssertAcquired();
    return any_thread_;
  }

  // Don't access compositor_thread_only_, instead use CompositorThreadOnly().
  CompositorThreadOnly compositor_thread_only_;
  CompositorThreadOnly& CompositorThreadOnly() {
    compositor_thread_only_.CheckOnValidThread();
    return compositor_thread_only_;
  }

  PollableThreadSafeFlag policy_may_need_update_;
  base::WeakPtrFactory<RendererSchedulerImpl> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(RendererSchedulerImpl);
};

}  // namespace scheduler
}  // namespace blink

#endif  // THIRD_PARTY_WEBKIT_SOURCE_PLATFORM_SCHEDULER_RENDERER_RENDERER_SCHEDULER_IMPL_H_


text:
package patterns.factories.abstractFactory;

class ConcreteProductOneSecond implements ProductOne {
}


text:
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
use ::test::run_test;

#[test]
fn andn_1() {
    run_test(&Instruction { mnemonic: Mnemonic::ANDN, operand1: Some(Direct(ESP)), operand2: Some(Direct(EBP)), operand3: Some(Direct(ECX)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 80, 242, 225], OperandSize::Dword)
}

#[test]
fn andn_2() {
    run_test(&Instruction { mnemonic: Mnemonic::ANDN, operand1: Some(Direct(ESP)), operand2: Some(Direct(ESP)), operand3: Some(IndirectScaledIndexed(EDI, EBX, Four, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 88, 242, 36, 159], OperandSize::Dword)
}

#[test]
fn andn_3() {
    run_test(&Instruction { mnemonic: Mnemonic::ANDN, operand1: Some(Direct(EBP)), operand2: Some(Direct(EBP)), operand3: Some(Direct(ECX)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 80, 242, 233], OperandSize::Qword)
}

#[test]
fn andn_4() {
    run_test(&Instruction { mnemonic: Mnemonic::ANDN, operand1: Some(Direct(EBP)), operand2: Some(Direct(EBP)), operand3: Some(IndirectScaledDisplaced(RBX, Four, 40544682, Some(OperandSize::Dword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 80, 242, 44, 157, 170, 169, 106, 2], OperandSize::Qword)
}

#[test]
fn andn_5() {
    run_test(&Instruction { mnemonic: Mnemonic::ANDN, operand1: Some(Direct(RSP)), operand2: Some(Direct(RBX)), operand3: Some(Direct(RDI)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 224, 242, 231], OperandSize::Qword)
}

#[test]
fn andn_6() {
    run_test(&Instruction { mnemonic: Mnemonic::ANDN, operand1: Some(Direct(RDI)), operand2: Some(Direct(RBX)), operand3: Some(Indirect(RBX, Some(OperandSize::Qword), None)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 226, 224, 242, 59], OperandSize::Qword)
}


text:
package com.jtanks.view.arena;

import java.awt.Color;
import java.util.List;

import com.jtanks.model.BasicEntity;
import com.jtanks.model.MovingEntity;
import com.jtanks.model.MovingEntityWithTrail;
import com.jtanks.util.Euclid;
import com.jtanks.util.Point;

public class CircleStyleEntityPainter implements EntityPainter {
    public void paintBaseShape(BasicEntity entity, Drawable drawable) {
        Point position = entity.getPosition();
        double size = entity.getSize();
        Color color = entity.getColor();

        drawable.setColor(color);
        if (entity.isDestroyed()) {
            drawable.drawCircle(position, size);
        } else{
            drawable.fillCircle(position, size);
        }
    }

    public void paintSmallHighlight(BasicEntity entity, Drawable drawable) {
        Point position = entity.getPosition();
        double size = entity.getSize();

        drawable.setColor(Color.DARK_GRAY);
        drawable.fillCircle(position, size/2);
    }

    public void paintTrail(MovingEntityWithTrail entity, Drawable drawable) {
        List<Point> trailPoints = entity.getTrail();
        Color color = entity.getColor().darker().darker();

        drawable.setColor(color);
        for (Point trailPoint : trailPoints) {
            drawable.drawPoint(trailPoint);
        }
    }

    public void paintRangeCircle(BasicEntity entity, Drawable drawable, int range) {
        if (entity.isDestroyed()) { return; }

        Point position = entity.getPosition();
        Color color = entity.getColor().darker().darker();

        drawable.setColor(color);
        drawable.drawCircle(position, range * 2);
    }

    public void paintCannon(MovingEntity entity, Drawable drawable, double cannonLength) {
        Point position = entity.getPosition();
        Color color = entity.getColor().brighter().brighter();
        double heading = entity.getHeading();

        Point cannonEnd = Euclid.getPointAtDistanceAndHeading(position, cannonLength, heading);
        drawable.setColor(color);
        drawable.drawLine(position, cannonEnd);
    }
}


text:
permalink: "/project/dhodu/"
title: Dhodu
subtitle: Android App & Server
layout: portfolio
date: 2015-07-18
img: dhodu_banner.png
thumbnail: thumb.png
alt: image-alt
category: Mobile Development
project:
  id: dhodu
  date: April 2014
  client: Dhodu
  client-url: http://Dhodu.com
  summary: A 24 hours on demand laundry startup.

---


text:
from __future__ import absolute_import

import string

from struct import unpack

from vertica_python.vertica.messages.message import BackendMessage

class ParameterStatus(BackendMessage):

    def __init__(self, data):
        null_byte = string.find(data, '\x00')
        unpacked = unpack('{0}sx{1}sx'.format(null_byte - 1, len(data) - null_byte - 1), data)
        self.name = unpacked[0]
        self.value = unpacked[1]

ParameterStatus._message_id('S')


text:
name: Bug report
about: Found a bug? Tell us about it!
---

Before you open an issue, please check if a similar one already exists or has been closed before. Detailed information about the process of contributing can be found in [CONTRIBUTING.md](https://github.com/vazco/uniforms/blob/master/.github/CONTRIBUTING.md).

Let us know what is happening. Do provide us with:

- Affected versions of the core, bridge, and theme packages you are aware of.
  - Include other versions as well, if you think it may help (React, browser, etc.).
- Steps to reproduce. If possible, include a reproduction using our [playground](https://uniforms.tools/playground) or [CodeSandbox template](https://codesandbox.io/s/github/vazco/uniforms/tree/master/reproductions).
- Possible workarounds, if you've found any.


text:
from __future__ import print_function, division

import os
from ..hdf5 import dendro_import_hdf5

DATA = os.path.join(os.path.dirname(__file__), 'data')

def test_import_old():
    # Check that we are backward-compatible
    dendro_import_hdf5(os.path.join(DATA, 'dendro_old.hdf5'))

def test_import():
    dendro_import_hdf5(os.path.join(DATA, 'dendro.hdf5'))


text:
function successToast(msg) {
  var $toastContent = $('
 Success!

' + msg + '
');
  Materialize.toast($toastContent, 2000);
}

function notificationToast(header, msg) {
  var $toastContent = $('
 ' + header + '

' + msg + '
');
  Materialize.toast($toastContent, 8000);
}

function failToast(msg) {
  var $toastContent = $('
 Failure!

' + msg + '
');
  Materialize.toast($toastContent, 8000);
}

// Load the comments initially via AJAX
$( document ).ready(function() {
    // TODO: Just break out this JS file into form helpers and simulator helpers
    if (!isNewSim() && window.location.pathname.substr(0, 11) == "/simulator/") {
        refreshCommentsList();
        refreshRatings();
    } else {
        $("#comment-load-gif").hide();
    }
});

function formPost(path, parameters, successMessage) {
  var fd = new FormData(document.forms[0]);
  var xhr = new XMLHttpRequest();
  xhr.open('POST', path);

  if (isNewSim()) {
    xhr.onload = function() { // After the post is done, redirect
      if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) {
          successToast(successMessage);
          window.location = xhr.responseText; // Redirects to saved simulation link
        } else {
          failToast(xhr.responseText);
        }
      }
    };
  } else {
    xhr.onload = function() { // Show toasts
      if (xhr.readyState === xhr.DONE) {
        if (xhr.status === 200) {
          if ($("#save-button").size() > 0) {
            $("#save-button").removeClass( "blue" )
            $("#save-button").addClass( "green" )
          }
          successToast(successMessage);
          window.location.reload(); // Necessary to get new image save form "action" attribute
        } else {
          failToast(xhr.responseText);
        }
      }
    };
  }

  for (var i = 0; i < parameters.length; i++) {
    fd.append(parameters[i].name, parameters[i].value);
  }

  // Post data
  xhr.send(fd);
}

// Saves the simulation, whether new or existing
// if a new simulation it does NOT use ajax to allow
// for a page redirect to simulator/{simulatorId}
function saveSimulation(){
  var postURLRequestPath = "/api/simulator/blobpath";
  if (GlobalKeyNames.Simulation) {
    postURLRequestPath = "/api/simulator/" + GlobalKeyNames.Simulation + "/blobpath";
  }

  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", function() {
    var postURL = this.responseText;

    simObject = [
      {name: "Name",        value: $("#simulation-name").val(),                type: "text"},
      {name: "Contents",    value: exportToJson(),                             type: "text"},
      {name: "Description", value: $("#simulation-description").val(),         type: "text"},
      {name: "IsPrivate",   value: $("#simulation-is-private").is(":checked"), type: "text"},
      {name: "Thumbnail",   value: dataURItoBlob(canvasToImage()),             type: "file"},
    ];

    formPost(postURL, simObject, "Simulation saved successfully!");

    losefocus();
  });

  xhr.open("GET", postURLRequestPath);
  xhr.send();
}

function deleteSimulation(simUrl, redirectUrl, element) {
  if (!confirm("Are you sure you want to delete this simulation?")) {
    return;
  }

  $.ajax({
      url: simUrl,
      type: 'DELETE',
      success: function(result) {
        if (redirectUrl) {
          // Redirect
          window.location.href = redirectUrl;
        } else {
          // Show toast and remove from list..
          successToast("Simulation was deleted");
          $(element).hide();
        }
      },
      error: function(xhr, textStatus, errorThrown) {
        failToast(xhr.responseText);
      }
  });
}

function validateUserImageSelection() {
  var uploadMessage = $('#image-upload-message')[0];

  var imageFiles = document.getElementById("user-profile-image").files;
  if (imageFiles && imageFiles[0].size < 500000) { // 500kB
    uploadMessage.text = "Just click \"UPDATE!\" to upload " + imageFiles[0].name;
  } else {
    uploadMessage.text = "This image might be too large! The max file size is 500KB";
  }
}

function saveUser() {
  var postURLRequestPath = "/api/user/" + GlobalKeyNames.User + "/blobpath";

  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", function() {
    var postURL = this.responseText;

    var imageFiles = document.getElementById("user-profile-image").files;
    if (imageFiles && imageFiles[0]) {
      if (imageFiles[0].size < 500000) { // 500KB
        userObject = [
          {name: "DisplayName",  value: $("#user-display-name").val(), type: "text"},
          {name: "Interests",    value: $("#user-interests").val(),    type: "text"},
          {name: "ProfileImage", value: imageFiles[0],                 type: "file"},
        ];

        formPost(postURL, userObject, "Information saved successfully!");
      } else {
        failToast("This image might be too large! The max file size is 500KB");
      }
    } else {
      userObject = [
        {name: "DisplayName",  value: $("#user-display-name").val(), type: "text"},
        {name: "Interests",    value: $("#user-interests").val(),    type: "text"},
      ];

      formPost(postURL, userObject, "Information saved successfully!");
    }
  });

  xhr.open("GET", postURLRequestPath);
  xhr.send();
}

// Save new comment to the datastore
// and refresh the comment list
function saveComment() {
    commentObj = { Contents: $("#comment-contents").val() };

    $("#comment-load-gif").show();
    $.post("/api/simulator/" + GlobalKeyNames.Simulation + "/comments", commentObj)
      .done(function() {
        refreshCommentsList();
        successToast('Comment saved successfully!');
      })
      .fail(function(xhr, textStatus, errorThrown) {
        $("#comment-load-gif").hide();
        failToast(xhr.responseText);
      });
}

// Save new rating to the datastore
// and refresh the ratings
function saveRating() {
  ratingObj = { Score: 1 };

  if (GlobalKeyNames.Simulation) {
    $.post("/api/simulator/" + GlobalKeyNames.Simulation + "/ratings", ratingObj)
      .done(function() {
        refreshRatings();
        successToast('Rating updated successfully!');
      })
        .fail(function(xhr, textStatus, errorThrown) {
        failToast(xhr.responseText);
    });
  }
}

// Called after saveComment() has finished
// posting a new comment OR on initial page load
function refreshCommentsList() {
  $.get("/api/simulator/" + GlobalKeyNames.Simulation + "/comments", function(json) {
    var result = "";
    json = JSON.parse(json);
    if (json) {
      for (var i = 0; i < json.length; i++) {
        var comment = json[i];
        var displayName = 'Anonymous';
        if (comment.AuthorName) {
          displayName = comment.AuthorName;
        }

        var imgDisplay = "";
        if (comment.AuthorImageSrcUrl) {
          imgDisplay = ""
        }

        result += "
";
        result +=   "
";
        result +=     "
";
        result +=       "
";
        result +=         "
";
        result +=           "" + imgDisplay + "";
        result +=         "
";
        result +=         "
";
        result +=           "" + displayName + "";
        result +=         "
";
        result +=         "
";
        result +=           "" + comment.PrettyCreationDate + "";
        result +=         "
";
        result +=       "
";
        result +=       "
";
        result +=         "";
        result +=           comment.Contents
        result +=         "";
        result +=       "
";
        result +=     "
";
        result +=   "
";
        result += "
";
      }
    }

    if ((json === null || json.length === 0) && GlobalKeyNames.User === "") {
      $("#comments-frag").hide();
    }

    $("#comments").html(result);
    $("#comment-load-gif").hide();
    $("#comment-contents").val("");
  })
  .fail(function() {
    $("#comment-load-gif").hide();
  });
}

// Called after saveRating() has finished
// posting a new rating OR on initial page load
function refreshRatings() {
    $.get("/api/simulator/" + GlobalKeyNames.Simulation + "/ratings", function(response) {
      json = JSON.parse(response);

      var rater = false;

      if (json.Ratings) {
        for (var i = 0; i < json.Ratings.length; i++) {
          if (json.Ratings[i].AuthorKeyName == GlobalKeyNames.User) {
            rater = true;
          }
        }
      }

      if (rater) {
        $("#star-icon").removeClass("fa-star-o");
        $("#star-icon").addClass("fa-star");
      } else {
        $("#star-icon").removeClass("fa-star");
        $("#star-icon").addClass("fa-star-o");
      }
      $("#ratings").attr("data-tooltip", json.TotalScore + " Stars");
    })
    .fail(function() {
    });
}

// Determines from the url if the simulation
// is a new simulation or an existing simulation
function isNewSim(){
  if (typeof GlobalKeyNames !== 'undefined') {
    if (!GlobalKeyNames.Simulation) {
      return true;
    }

    return GlobalKeyNames.Simulation == null || GlobalKeyNames.Simulation == "";
  } else {
    return false;
  }
}

function getfocus() {
    //document.getElementById("simulation-name").focus();
    //document.getElementById("simulation-name-label").style.display = "initial";
}

function losefocus() {
    //document.getElementById("simulation-name").blur();
    //document.getElementById("simulation-name-label").style.display = "none";
}


text:
function GeoHash() {
  this.BITS = [16, 8, 4, 2, 1]
  this.MAX_PRECISION = 11

  this.BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz"
  var NEIGHBORS = { right  : { even :  "bc01fg45238967deuvhjyznpkmstqrwx" },
                left   : { even :  "238967debc01fg45kmstqrwxuvhjyznp" },
                top    : { even :  "p0r21436x8zb9dcf5h7kjnmqesgutwvy" },
                bottom : { even :  "14365h7k9dcfesgujnmqp0r2twvyx8zb" } }
  var BORDERS   = { right  : { even : "bcfguvyz" },
                left   : { even : "0145hjnp" },
                top    : { even : "prxz" },
                bottom : { even : "028b" } }

  NEIGHBORS.bottom.odd = NEIGHBORS.left.even
  NEIGHBORS.top.odd = NEIGHBORS.right.even
  NEIGHBORS.left.odd = NEIGHBORS.bottom.even
  NEIGHBORS.right.odd = NEIGHBORS.top.even

  BORDERS.bottom.odd = BORDERS.left.even
  BORDERS.top.odd = BORDERS.right.even
  BORDERS.left.odd = BORDERS.bottom.even
  BORDERS.right.odd = BORDERS.top.even

  this.NEIGHBORS = NEIGHBORS
  this.BORDERS = BORDERS

  var dimensionTables = this.buildLengthToDimensionTables(this.MAX_PRECISION)
  this.latitudeHeights = dimensionTables.latitudeHeights
  this.longitudeWidths = dimensionTables.longitudeWidths
}

GeoHash.prototype.refineInterval = function (interval, cd, mask) {
  if (cd&mask) interval[0] = (interval[0] + interval[1])/2
  else interval[1] = (interval[0] + interval[1])/2
}

GeoHash.prototype.encode = function (latitude, longitude) {
  var self = this
  var isEven = 1
  var i = 0
  var lat = []
  var lon = []
  var bit = 0
  var ch = 0
  geohash = ""

  lat[0] = -90.0
  lat[1] = 90.0
  lon[0] = -180.0
  lon[1] = 180.0

  while (geohash.length < self.MAX_PRECISION) {
    if (isEven) {
      mid = (lon[0] + lon[1]) / 2
      if (longitude > mid) {
        ch |= self.BITS[bit]
        lon[0] = mid
      } else
        lon[1] = mid
    } else {
      mid = (lat[0] + lat[1]) / 2
      if (latitude > mid) {
        ch |= self.BITS[bit]
        lat[0] = mid
      } else
        lat[1] = mid
    }

    isEven = !isEven
    if (bit < 4)
      bit++
    else {
      geohash += self.BASE32[ch]
      bit = 0
      ch = 0
    }
  }
  return geohash
}

GeoHash.prototype.decode =  function (geohash) {
  var self = this
  var isEven = 1
  var lat = []
  var lon = []
  lat[0] = -90.0
  lat[1] = 90.0
  lon[0] = -180.0
  lon[1] = 180.0
  lat_err = 90.0
  lon_err = 180.0

  for (i = 0; i < geohash.length; i++) {
    c = geohash[i]
    cd = self.BASE32.indexOf(c)
    for (j = 0; j < 5; j++) {
      mask = self.BITS[j]
      if (isEven) {
        lon_err /= 2
        self.refineInterval(lon, cd, mask)
      } else {
        lat_err /= 2
        self.refineInterval(lat, cd, mask)
      }
      isEven = !isEven
    }
  }
  lat[2] = (lat[0] + lat[1])/2
  lon[2] = (lon[0] + lon[1])/2

  return { latitude: lat, longitude: lon}
}

GeoHash.prototype.adjacent = function (srcHash, dir) {
  var self = this
  srcHash = srcHash.toLowerCase()
  var lastChr = srcHash.charAt(srcHash.length-1)
  var type = (srcHash.length % 2) ? 'odd' : 'even'
  var base = srcHash.substring(0, srcHash.length - 1)
  if (self.BORDERS[dir][type].indexOf(lastChr) != -1)
    base = self.adjacent(base, dir)
  return base + self.BASE32[self.NEIGHBORS[dir][type].indexOf(lastChr)]
}

GeoHash.prototype.neighbors = function (srcHash) {
  var self = this
  var neighbors = []
  var directions = [['top', 'right'], ['right', 'bottom'], ['bottom', 'left'], ['left', 'top']]
  directions.forEach(function(dir) {
    var point = self.adjacent(srcHash, dir[0])
    neighbors.push(point)
    neighbors.push(self.adjacent(point, dir[1]))
  })
  return neighbors
}

GeoHash.prototype.buildLengthToDimensionTables = function(precision) {
  var self = this
  var hashLenToLatHeight = []
  var hashLenToLonWidth = []
  hashLenToLatHeight[0] = 90 * 2
  hashLenToLonWidth[0] = 180 * 2
  var even = false
  for(var i = 1; i <= precision; i++) {
    hashLenToLatHeight[i] = hashLenToLatHeight[i-1] / (even ? 8 : 4)
    hashLenToLonWidth[i] = hashLenToLonWidth[i-1] / (even ? 4 : 8 )
    even = !even
  }
  return {latitudeHeights: hashLenToLatHeight, longitudeWidths: hashLenToLonWidth}
}

GeoHash.prototype.hashLength = function(width, height) {
  var self = this
  //loop through hash length arrays from beginning till we find one.
  var length = false
  for(var len = 1; len <= self.MAX_PRECISION; len++) {
    var latHeight = self.latitudeHeights[len]
    var lonWidth = self.longitudeWidths[len]
    if (latHeight < height || lonWidth < width) {
      length = len - 1 //previous length is big enough to encompass specified width & height
      len = self.MAX_PRECISION
    }
  }
  if (length) return length
  return self.MAX_PRECISION
}

GeoHash.prototype.degreesSizeForHashLength = function(length) {
  return [this.latitudeHeights[length], this.longitudeWidths[length]]
}

GeoHash.prototype.subs = function (baseGeohash) {
  var self = this
  var hashes = []
  for (var i = 0; i < self.BASE32.length; i++) {
    var c = self.BASE32[i]
    hashes.push(baseGeohash + c)
  }
  return hashes
}

module.exports = new GeoHash()


text:
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using uWebshop.Common;
using uWebshop.Domain;
using uWebshop.Domain.Businesslogic;
using uWebshop.Domain.Interfaces;
using uWebshop.Newtonsoft.Json;

namespace uWebshop.API
{
	[DataContract(Name = "Discount", Namespace= "")]
	internal class AppliedOrderDiscountAdaptor : IAppliedOrderDiscount
	{
		private readonly Domain.Interfaces.IOrderDiscount _discount;
		private readonly OrderInfo _order;

		public AppliedOrderDiscountAdaptor(Domain.Interfaces.IOrderDiscount discount, OrderInfo order)
		{
			_discount = discount;
			_order = order;
		}

		[IgnoreDataMember]
		public IVatPrice AmountForOrder
		{
			get
			{
				// todo: test
				var applicableOrderLines = !_discount.AffectedOrderlines.Any() ? _order.OrderLines : _order.OrderLines.Where(line => _discount.AffectedOrderlines.Contains(line.ProductInfo.Id) || _discount.AffectedOrderlines.Contains(line.ProductInfo.ProductVariants.Select(v => v.Id).FirstOrDefault())).ToList();
				var weightedAverageVat = applicableOrderLines.Sum(line => line.AmountInCents * line.ProductInfo.Vat) / applicableOrderLines.Sum(line => line.AmountInCents);
				return Price.CreateSimplePrice(IO.Container.Resolve<IDiscountCalculationService>().DiscountAmountForOrder(_discount, _order), _order.PricesAreIncludingVAT, weightedAverageVat, _order.Localization);
			}
		}
		[DataMember(Name = "AmountForOrder")]
		[JsonProperty(PropertyName = "AmountForOrder")]
		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public FlatVatPrice AmountForOrderFlat { get { return new FlatVatPrice(AmountForOrder); } set { } }

		#region Pure interface forward

		[DataMember]
		public string Description { get { return _discount.Description; } set { } }

		[DataMember]
		public bool OncePerCustomer { get { return _discount.OncePerCustomer; } set { } }
		[DataMember]
		public bool CounterEnabled { get { return _discount.CounterEnabled; } set { } }
		[IgnoreDataMember]
		public DiscountType Type { get { return _discount.Type; } set { } }
		[DataMember(Name = "Type")]
		public string TypeText { get { return Type.ToString(); } set { } }
		[DataMember]
		public List<int> RequiredItemIds { get { return _discount.RequiredItemIds; } set { } }
		[DataMember]
		public DiscountOrderCondition Condition { get { return _discount.Condition; } set { } }
		[DataMember]
		public int NumberOfItemsCondition { get { return _discount.NumberOfItemsCondition; } set { } }
		[DataMember]
		public int DiscountValue { get { return _discount.DiscountValue; } set { } }
		[DataMember]
		public List<Range> Ranges { get { return _discount.Ranges; } set { } }

		[DataMember]
		public string CouponCode
		{
			get
			{

				var coupons = IO.Container.Resolve<ICouponCodeService>().GetAllForDiscount(_discount.OriginalId);
				if (coupons.Any()) //
				{
					var availableCoupons = coupons.Where(c => c.NumberAvailable > 0).Select(c => c.CouponCode);
					return availableCoupons.Intersect(_order.CouponCodes).FirstOrDefault();
				}
				return null;
			}
			set { }
		}

		[DataMember]
		public int OriginalId { get { return _discount.OriginalId; } set { } }

		[IgnoreDataMember]
		public DiscountType DiscountType { get { return _discount.Type; } set { } }
		[DataMember(Name = "DiscountType")]
		public string DiscountTypeText { get { return Type.ToString(); } set { } }

		[DataMember]
		public List<string> MemberGroups { get { return _discount.MemberGroups; } set { } }
		[DataMember]
		public List<int> AffectedOrderlines { get { return _discount.AffectedOrderlines; } set { } }
		[DataMember]
		public IEnumerable<string> AffectedProductTags { get { return _discount.AffectedProductTags; } set{} }

		[DataMember]
		public string Title { get { return _discount.Title; } set { } }

		[DataMember]
		public bool IncludeShippingInOrderDiscountableAmount { get { return _discount.IncludeShippingInOrderDiscountableAmount; } set { } }

		[IgnoreDataMember]
		public IVatPrice MinimumOrderAmount { get { return _discount.MinimumOrderAmount; } }
		[DataMember(Name = "MinimumOrderAmount")]
		[JsonProperty(PropertyName = "MinimumOrderAmount")]
		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public FlatVatPrice MinimumOrderAmountFlat { get { return new FlatVatPrice(MinimumOrderAmount); } set { } }

		#endregion

	}
}


text:
/*
	Table creation script for the aggregation tables.  These should be
	loaded into the AGGREGATI0N schema.   They are used when doing
	aggregation of responses from multple systems that come in on separate
	threads.

	This script was intended to be run on MySQL.
*/

DROP TABLE IF EXISTS aggregator.agg_transaction CASCADE;
CREATE TABLE aggregator.agg_transaction (
    TransactionId VARCHAR(32) NOT NULL COMMENT 'This will be a UUID',
    ServiceType VARCHAR(64) NOT NULL,
    TransactionStartTime DATETIME COMMENT 'Format of YYYYMMDDHHMMSS',
  PRIMARY KEY(TransactionId)
);

DROP TABLE IF EXISTS aggregator.agg_message_results CASCADE;
CREATE TABLE aggregator.agg_message_results (
    MessageId VARCHAR(32) NOT NULL COMMENT 'This will be a UUID.',
    TransactionId VARCHAR(32) NOT NULL COMMENT 'This will be a UUID. - Foreign Key to the agg_transaction table.',
    MessageKey VARCHAR(1000) NOT NULL COMMENT 'This is the key used to tie the response to the original request.',
    MessageOutTime DATETIME COMMENT 'This is the date/time when the outbound request was recorded.  Format of YYYYMMDDHHMMSS',
    ResponseReceivedTime DATETIME COMMENT 'This is the date/time when the response was recorded.  Format of YYYYMMDDHHMMSS',
    ResponseMessageType VARCHAR(100) COMMENT 'This is the name of the outer layer JAXB class for the response message.',
    ResponseMessage LONGTEXT COMMENT 'The response message in XML - Based on marshalling using JAXB',
  PRIMARY KEY (MessageId)
);


text:
.. IoTPy documentation master file, created by
   sphinx-quickstart on Tue Jun 03 14:28:18 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to IoTPy's documentation!
=================================

.. toctree::
   :maxdepth: 2

   about
   install
   tutorial
   reference

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
[tooltip](http://damnhipster.github.io/tooltip/)  [![Circle CI](https://circleci.com/gh/skyglobal/tooltip/tree/master.svg?style=svg)](https://circleci.com/gh/skyglobal/tooltip/tree/master)
========================

> Please take a look at the [demo page](http://skyglobal.github.io/tooltip/)

## Quick-Start

Include the Share assets in your project either as **Static Resources**

```html
<link rel="stylesheet" href="http://web-toolkit.global.sky.com/components/tooltip/0.0.0/css/tooltip.css" />
<script type="text/javascript" src="http://web-toolkit.global.sky.com/components/tooltip/0.0.0/js/tooltip.min.js"></script>
```

or alternatively, **Via Bower**

 * Run: `bower install --save-dev bskyb-tooltip`
 * Include Sass: `@import 'bower_components/bskyb-tooltip/src/scss/tooltip';`
 * Include JS: `var share = require('../../bower_components/bskyb-tooltip/src/js/tooltip');`

#### Dependencies

This component relies on other components and you must also include these in your project.

 * [Dependency Name](https://github.com/skyglobal/DependencyName)

#### Developer Notes

Choose a type of tooltip component and copy the relevant html.
 * [example](demo/_includes/example.html)
 * [example](demo/_includes/example.html),

#### Initialise

To enable --descrition here--, the JS must be initialised:

```html
<script type="text/javascript">
  skyComponents.tooltip.init();
</script>
```

## Contribution

Components depends on collaboration between developers. Contributions of any size are actively encouraged.

[Read More >](CONTRIBUTING.md)

## Browser Support

 * IE8 +
 * Safari 5 +
 * Latest Firefox
 * Latest Chrome
 * Latest Mobile Safari
 * Latest Mobile Chrome


text:
package rabbit.zip;

/** A class that can pack gzip streams in chunked mode.
 *
 * @author Robert Olofsson
 */
public class GZipPacker {
    private GZipPackState state;

    /** Create a gzip packer that sends events to the given listener.
     * @param listener the listener that will be notifiec when data has
     *        been packed.
     */
    public GZipPacker (GZipPackListener listener) {
	state = new HeaderWriter (listener);
    }

    /** Check if the unpacker currently needs more data
     * @return true if more input data is currently needed
     */
    public boolean needsInput () {
	return state.needsInput ();
    }

    /** Add more compressed data to the unpacker.
     * @param buf the array holding the new data
     * @param off the start offset of the data to use
     * @param len the length of the data
     */
    public void setInput (byte[] buf, int off, int len) {
	state.handleBuffer (this, buf, off, len);
    }

    /** Tell the packer that it has reached the end of data.
     */
    public void finish () {
	state.finish ();
    }

    /** Check if the packer is finished.
     * @return true if packing has finished
     */
    public boolean finished () {
	return state.finished ();
    }

    /** Handle the next block of the current data.
     */
    public void handleCurrentData () {
	state.handleCurrentData (this);
    }

    /** Change the internal gzip state to the given state.
     * @param state the new internal state of the gzip packer.
     */
    public void setState (GZipPackState state) {
	this.state = state;
    }
}


text:
#region Header
// --------------------------------------------------------------------------
// Tethys.Throbbers
// ==========================================================================
//
// A custom control library for WPF applications.
//
// ==========================================================================
// <copyright file="MainWindow.xaml.cs" company="Tethys">
// Copyright  2017 by T. Graf
//            All rights reserved.
//            Licensed under the Apache License, Version 2.0.
//            Unless required by applicable law or agreed to in writing,
//            software distributed under the License is distributed on an
//            "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
//            either express or implied.
// </copyright>
//
// System ... Microsoft .Net Framework 4.5.2
// Tools .... Microsoft Visual Studio 2017
//
// ---------------------------------------------------------------------------
#endregion

namespace Tethys.Throbbers.Demo
{
    /// <summary>
    /// Interaction logic for MainWindow.
    /// </summary>
    public partial class MainWindow
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="MainWindow"/> class.
        /// </summary>
        public MainWindow()
        {
            this.InitializeComponent();
        } // MainWindow()
    } // MainWindow
}


text:
package com.mystore.shop.domain.model.productitem;

import javax.persistence.Embeddable;

@Embeddable
public class ProductItemId {

	public static final String ID = "id";

	private long id;

	protected ProductItemId() {
		super();
	}

	public ProductItemId(long id) {
		super();
		setId(id);
	}

	public long getId() {
		return id;
	}

	protected void setId(long id) {
		this.id = id;
	}

	public boolean equals(ProductItemId productItemId) {
		if (this.id == productItemId.getId()) {
			return true;
		}
		return false;
	}
}


text:
App.ChemotaxisPermanent = DS.Model.extend( App.savingMixin, {
	description: DS.attr('string'),
	chemicalCategory: DS.attr('string'),
	osmoticRing: DS.belongsTo('osmoticRing', {async: true}),
	staticPointSourceConf: DS.belongsTo('staticPointSource', {async: true}),
	chemotaxisQuadrants1: DS.belongsTo('chemotaxisQuadrants1', {async: true}),
	chemotaxisQuadrants2: DS.belongsTo('chemotaxisQuadrants2', {async: true}),
	chemotaxisQuadrants4: DS.belongsTo('chemotaxisQuadrants4', {async: true}),
});


text:
extern crate core;
extern crate docopt;
extern crate serde;
extern crate serde_hjson;
extern crate serde_json;

use serde_hjson::Value;
use docopt::Docopt;

use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::io;

const VERSION: &'static str = env!("CARGO_PKG_VERSION");
const USAGE: &'static str = "
Hjson, the Human JSON.

Usage:
  hjson [options]
  hjson [options] <input>
  hjson (-h | --help)
  hjson (-V | --version)

Options:
  -h --help     Show this screen.
  -j            Output as formatted JSON.
  -c            Output as JSON.
  -V --version  Show version.
";

fn main() {

    let args = Docopt::new(USAGE)
                      .and_then(|dopt| dopt.parse())
                      .unwrap_or_else(|e| e.exit());

    if args.get_bool("--version") {
        println!("Hjson CLI {}", VERSION);
        return;
    }

    let input = args.get_str("<input>");
    let mut buffer = String::new();

    if input != "" {
        let mut f = File::open(&Path::new(input)).unwrap();
        f.read_to_string(&mut buffer).unwrap();
    } else {
        io::stdin().read_to_string(&mut buffer).unwrap();
    }

    let data : Value = serde_hjson::from_str(&buffer).unwrap();

    if args.get_bool("-j") {
        println!("{}", serde_json::to_string_pretty(&data).unwrap());
    } else if args.get_bool("-c") {
        println!("{}", serde_json::to_string(&data).unwrap());
    } else {
        println!("{}", serde_hjson::to_string(&data).unwrap());
    }
}