text:
package com.annimon.ownlang.modules.std;

import com.annimon.ownlang.lib.Arguments;
import com.annimon.ownlang.lib.ArrayValue;
import com.annimon.ownlang.lib.NumberValue;
import com.annimon.ownlang.lib.StringValue;
import com.annimon.ownlang.lib.Value;
import java.io.UnsupportedEncodingException;

public final class StringFunctions {

    private StringFunctions() { }

    static ArrayValue getBytes(Value[] args) {
        Arguments.checkOrOr(1, 2, args.length);
        final String charset = (args.length == 2) ? args[1].asString() : "UTF-8";
        try {
            return ArrayValue.of(args[0].asString().getBytes(charset));
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException(uee);
        }
    }

    static Value parseInt(Value[] args) {
        Arguments.checkOrOr(1, 2, args.length);
        final int radix = (args.length == 2) ? args[1].asInt() : 10;
        return NumberValue.of(Integer.parseInt(args[0].asString(), radix));
    }

    static Value parseLong(Value[] args) {
        Arguments.checkOrOr(1, 2, args.length);
        final int radix = (args.length == 2) ? args[1].asInt() : 10;
        return NumberValue.of(Long.parseLong(args[0].asString(), radix));
    }

    static Value stripMargin(Value[] args) {
        Arguments.checkOrOr(1, 2, args.length);
        final String input = args[0].asString();
        final String marginPrefix = (args.length == 2) ? args[1].asString() : "|";
        if (!input.contains(marginPrefix)) {
            return args[0];
        }
        final String[] lines = input.split("\\r?\\n");

        // First blank line is omitted
        final StringBuilder sb = new StringBuilder();
        final int firstLineIndex = (isBlank(lines[0])) ? 1 : 0;
        final int lastLineIndex = lines.length - 1;
        int index = firstLineIndex;
        while (true) {
            sb.append(strip(lines[index], marginPrefix));
            if (++index >= lastLineIndex) break;
            sb.append('\n');
        }
        // Process last line
        if (lastLineIndex >= (firstLineIndex + 1) && !isBlank(lines[lastLineIndex])) {
            sb.append('\n').append(strip(lines[lastLineIndex], marginPrefix));
        }
        return new StringValue(sb.toString());
    }

    private static String strip(String str, String marginPrefix) {
        final int nonBlankIndex = firstNonBlankIndex(str);
        if (str.startsWith(marginPrefix, nonBlankIndex)) {
            return str.substring(nonBlankIndex + marginPrefix.length());
        } else {
            return str;
        }
    }

    private static boolean isBlank(String str) {
        return firstNonBlankIndex(str) == str.length();
    }

    private static int firstNonBlankIndex(String str) {
        final int length = str.length();
        for (int index = 0; index < length; index++) {
            final char ch = str.charAt(index);
            if (ch != ' ' && ch != '\t' && !Character.isWhitespace(ch)) {
                return index;
            }
        }
        return length;
    }
}


text:
<?php
/**
 * File: Utility.php
 * User: zacharydubois
 * Date: 2016-01-02
 * Time: 00:57
 * Project: Digital-Footprint-Profile
 */

namespace dfp;

class Utility {

    /**
     * Generates Session ID
     *
     * Generates a session ID to use. Checks existing sessions to avoid conflict.
     *
     * @return string
     */
    public static function generateSID() {
        $key = null;

        while (Session::isSession($key) || $key === null) {
            $key = sha1(time() . '-' . microtime(true) . '-' . rand(0, PHP_INT_MAX) . filter_input(INPUT_SERVER, 'HTTP_USER_AGENT'));
        }

        return $key;
    }

    /**
     * Build Full Link
     *
     * Builds full link using protocol, host and base.
     *
     * @param Config $config
     * @param bool $relative
     * @param string $endpoint
     * @return string
     */
    public static function buildFullLink(Config $config, $relative = false, $endpoint = null) {
        $proto = $config->get('server', 'protocol');
        $host = $config->get('server', 'domain');
        $base = $config->get('server', 'base');

        if ($relative === true) {
            if ($base === false) {
                $link = '/' . $endpoint;
            } else {
                $link = '/' . $base . '/' . $endpoint;
            }
        } else {
            if ($base === false) {
                $link = $proto . $host . '/' . $endpoint;
            } else {
                $link = $proto . $host . '/' . $base . '/' . $endpoint;
            }
        }

        return $link;
    }

    /**
     * Brings User Home
     *
     * Sends location header to send user to root.
     *
     * @param Config $config
     * @return bool
     */
    public static function goHome(Config $config) {
        header("Location: " . static::buildFullLink($config));

        return true;
    }

    /**
     * HTTPS Bool
     *
     * Gets HTTPS status in bool form
     *
     * @param Config $config
     * @return bool
     * @throws Exception
     */
    public static function httpsBool(Config $config) {
        if ($config->get('server', 'protocol') === 'https://') {
            return true;
        } elseif ($config->get('server', 'protocol') === 'http://') {
            return false;
        }

        throw new Exception("Protocol is not known. " . $config->get('server', 'protocol') === 'https://');
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React,{Component} from 'react'
import { Card, CardText} from 'material-ui/Card'

import YouTubeChannelBtn from './YouTubeChannelBtn'

import './Profile.css'

class SNSCard extends Component {
  render() {
    return (

          <Card style={{width:'250px',height:'150px'}}>
            <CardText style={{textAlign:'left'}}>

                {
                  this.props.youtubeId===undefined
                  ?

                  :<YouTubeChannelBtn youtubeLink={"https://www.youtube.com/channel/"+this.props.youtubeId}/>
                }

            </CardText>
          </Card>

    )
  }
}
export default SNSCard


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

<title>GraphSeriesSelector (Apache JMeter API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache JMeter

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.jmeter.report.processor.graph

Interface GraphSeriesSelector

All Superinterfaces:

SampleSelector<Iterable<String>>

All Known Implementing Classes:

AbstractSeriesSelector, CodeSeriesSelector, NameSeriesSelector, StaticSeriesSelector, StatusSeriesSelector

public interface GraphSeriesSelector
extends SampleSelector<Iterable<String>>

The interface GraphSeriesSelector provides a projection from a sample to the
 series it belongs in a graph.

Since:

3.0

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

boolean
allowsControllersDiscrimination()

Indicates whether this selector allows controllers discrimination,
 which allows on graphs to only show transaction controllers

Methods inherited from interface org.apache.jmeter.report.core.SampleSelector

select

Method Detail

allowsControllersDiscrimination

boolean allowsControllersDiscrimination()

Indicates whether this selector allows controllers discrimination,
 which allows on graphs to only show transaction controllers

Returns:

true, if this selector allows controllers discrimination; false otherwise

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache JMeter

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 1998-2017 Apache Software Foundation. All Rights Reserved.


text:
namespace v8 {
namespace internal {

LocalHeap::LocalHeap(Heap* heap,
                     std::unique_ptr<PersistentHandles> persistent_handles)
    : heap_(heap),
      state_(ThreadState::Running),
      safepoint_requested_(false),
      allocation_failed_(false),
      prev_(nullptr),
      next_(nullptr),
      handles_(new LocalHandles),
      persistent_handles_(std::move(persistent_handles)),
      old_space_allocator_(this, heap->old_space()) {
  heap_->safepoint()->AddLocalHeap(this);
  if (persistent_handles_) {
    persistent_handles_->Attach(this);
  }
}

LocalHeap::~LocalHeap() {
  // Give up LAB before parking thread
  old_space_allocator_.FreeLinearAllocationArea();

  // Park thread since removing the local heap could block.
  EnsureParkedBeforeDestruction();

  heap_->safepoint()->RemoveLocalHeap(this);
}

Handle<Object> LocalHeap::NewPersistentHandle(Address value) {
  if (!persistent_handles_) {
    persistent_handles_.reset(
        heap_->isolate()->NewPersistentHandles().release());
  }
  return persistent_handles_->NewHandle(value);
}

std::unique_ptr<PersistentHandles> LocalHeap::DetachPersistentHandles() {
  if (persistent_handles_) persistent_handles_->Detach();
  return std::move(persistent_handles_);
}

bool LocalHeap::IsParked() {
  base::MutexGuard guard(&state_mutex_);
  return state_ == ThreadState::Parked;
}

void LocalHeap::Park() {
  base::MutexGuard guard(&state_mutex_);
  CHECK(state_ == ThreadState::Running);
  state_ = ThreadState::Parked;
  state_change_.NotifyAll();
}

void LocalHeap::Unpark() {
  base::MutexGuard guard(&state_mutex_);
  CHECK(state_ == ThreadState::Parked);
  state_ = ThreadState::Running;
}

void LocalHeap::EnsureParkedBeforeDestruction() {
  base::MutexGuard guard(&state_mutex_);
  state_ = ThreadState::Parked;
  state_change_.NotifyAll();
}

void LocalHeap::RequestSafepoint() {
  safepoint_requested_.store(true, std::memory_order_relaxed);
}

bool LocalHeap::IsSafepointRequested() {
  return safepoint_requested_.load(std::memory_order_relaxed);
}

void LocalHeap::Safepoint() {
  if (IsSafepointRequested()) {
    ClearSafepointRequested();
    EnterSafepoint();
  }
}

void LocalHeap::ClearSafepointRequested() {
  safepoint_requested_.store(false, std::memory_order_relaxed);
}

void LocalHeap::EnterSafepoint() { heap_->safepoint()->EnterFromThread(this); }

void LocalHeap::FreeLinearAllocationArea() {
  old_space_allocator_.FreeLinearAllocationArea();
}

void LocalHeap::MakeLinearAllocationAreaIterable() {
  old_space_allocator_.MakeLinearAllocationAreaIterable();
}

}  // namespace internal
}  // namespace v8


text:
.. _authentication:

Authentication & Permissions
============================

It's up to the responsibility of the user to implement permissions by
providing their own :class:`~flask_kibble.Authenticator` subclass.

.. module:: flask_kibble

.. autoclass:: Authenticator
   :members:

.. autoclass:: GAEAuthenticator
   :members:


text:
using System;
using System.Collections.Generic;
using RemoteFortressReader;
using System.Text.RegularExpressions;

public class GeneratedCreatureTranslator
{
    static string[] templateList = new string[]
    {
        "blob",        "quadruped",       "humanoid",     "silverfish",    "mayfly",        "dragonfly",   "damselfly",    "stonefly",
        "earwig",      "grasshopper",     "cricket",      "stick insect",  "cockroach",     "termite",     "mantis",       "louse",
        "thrips",      "aphid",           "cicada",       "assassin bug",  "wasp",          "hornet",      "tiger beetle", "ladybug",
        "weevil",      "darkling beetle", "click beetle", "firefly",       "scarab beetle", "stag beetle", "dung beetle",  "rhinoceros beetle",
        "rove beetle", "snakefly",        "lacewing",     "antlion larva", "mosquito",      "flea",        "scorpionfly",  "caddisfly",
        "butterfly",   "moth",            "caterpillar",  "maggot",        "spider",        "tarantula",   "scorpion",     "tick",
        "mite",        "shrimp",          "lobster",      "crab",          "nematode",      "snail",       "slug",         "earthworm",
        "leech",       "bristleworm",     "ribbon worm",  "flat worm",     "toad",          "frog",        "salamander",   "newt",
        "alligator",   "crocodile",       "lizard",       "chameleon",     "iguana",        "gecko",       "skink",        "gila monster",
        "monitor",     "serpent",         "viper",        "rattlesnake",   "cobra",         "python",      "anaconda",     "turtle",
        "tortoise",    "pterosaur",       "dimetrodon",   "sauropod",      "theropod",      "iguanodont",  "hadrosaurid",  "stegosaurid",
        "ceratopsid",  "ankylosaurid",    "duck",         "goose",         "swan",          "turkey",      "grouse",       "chicken",
        "quail",       "pheasant",        "gull",         "loon",          "grebe",         "albatross",   "petrel",       "penguin",
        "pelican",     "stork",           "vulture",      "flamingo",      "falcon",        "kestrel",     "condor",       "osprey",
        "buzzard",     "eagle",           "harrier",      "kite",          "crane",         "dove",        "pigeon",       "parrot",
        "cockatoo",    "cuckoo",          "nightjar",     "swift",         "hummingbird",   "kingfisher",  "hornbill",     "quetzal",
        "toucan",      "woodpecker",      "lyrebird",     "thornbill",     "honeyeater",    "oriole",      "fantail",      "shrike",
        "crow",        "raven",           "magpie",       "kinglet",       "lark",          "swallow",     "martin",       "bushtit",
        "warbler",     "thrush",          "oxpecker",     "starling",      "mockingbird",   "wren",        "nuthatch",     "sparrow",
        "tanager",     "cardinal",        "bunting",      "finch",         "titmouse",      "chickadee",   "waxwing",      "flycatcher",
        "opossum",     "koala",           "wombat",       "kangaroo",      "sloth",         "anteater",    "armadillo",    "squirrel",
        "marmot",      "beaver",          "gopher",       "mouse",         "porcupine",     "chinchilla",  "cavy",         "capybara",
        "rabbit",      "hare",            "lemur",        "loris",         "monkey",        "hedgehog",    "shrew",        "mole",
        "fruit bat",   "wolf",            "coyote",       "jackal",        "raccoon",       "coati",       "weasel",       "otter",
        "badger",      "skunk",           "bear",         "panda",         "panther",       "mongoose",    "hyena",        "civet",
        "walrus",      "pangolin",        "elephant",     "mammoth",       "horse",         "zebra",       "tapir",        "rhinoceros",
        "warthog",     "hippopotamus",    "camel",        "llama",         "giraffe",       "deer",        "moose",        "antelope",
        "sheep",       "goat",            "bison",        "buffalo",       "bull",          "ape",         "ant",          "bat",
        "owl",         "pig",             "bee",          "fly",           "hawk",          "jay",         "rat",          "fox",
        "cat",         "ass",             "elk"
    };

    internal static CreatureRaw[] GetCreatureRaw(string race)
    {
        var creatureRaw = CreatureRaws.Instance.CreatureList.FindAll(x => x.creature_id == race);
        if (creatureRaw == null)
            creatureRaw = new List<CreatureRaw>();
        var tokenParts = race.Split('_');
        switch (tokenParts[0])
        {
            case "ANGEL":
                creatureRaw.AddRange( CreatureRaws.Instance.CreatureList.FindAll(x => x.creature_id.StartsWith("HF") && Regex.IsMatch(x.caste[0].description.Split('.')[0], "\\b" + tokenParts[1] + "\\b", RegexOptions.IgnoreCase)));
                break;
            case "DEMON":
                creatureRaw.AddRange(CreatureRaws.Instance.CreatureList.FindAll(x => x.creature_id.StartsWith("DEMON") && Regex.IsMatch(x.caste[0].description.Split('.')[0], "\\b" + tokenParts[1] + "\\b", RegexOptions.IgnoreCase)));
                break;
            case "FB":
                creatureRaw.AddRange(CreatureRaws.Instance.CreatureList.FindAll(x => x.creature_id.StartsWith("FORGOTTEN_BEAST") && Regex.IsMatch(x.caste[0].description.Split('.')[0], "\\b" + tokenParts[1] + "\\b", RegexOptions.IgnoreCase)));
                break;
            case "TITAN":
                creatureRaw.AddRange(CreatureRaws.Instance.CreatureList.FindAll(x => x.creature_id.StartsWith("TITAN") && Regex.IsMatch(x.caste[0].description.Split('.')[0], "\\b" + tokenParts[1] + "\\b", RegexOptions.IgnoreCase)));
                break;
            case "WERE":
                creatureRaw.AddRange(CreatureRaws.Instance.CreatureList.FindAll(x => x.name[0].ToUpper() == ("were" + tokenParts[1]).ToUpper()));
                break;
            default:
                break;
        }
        return creatureRaw.ToArray();
    }
    static int count;
    internal static void AddFakeCreaturesToList(Dictionary<MatPairStruct, MaterialDefinition> creatures)
    {
        count = -2;
        AddFakeCreaturesToList(creatures, "ANGEL");
        AddFakeCreaturesToList(creatures, "DEMON");
        AddFakeCreaturesToList(creatures, "FB");
        AddFakeCreaturesToList(creatures, "TITAN");
        AddFakeCreaturesToList(creatures, "WERE");
    }
    internal static void AddFakeCreaturesToList(Dictionary<MatPairStruct, MaterialDefinition> creatures, string prefix)
    {
        foreach (string template in templateList)
        {
            MatPairStruct creatureCaste = new MatPairStruct(count, -1);
            MaterialDefinition creatureDef = new MaterialDefinition();
            creatureDef.mat_pair = creatureCaste;
            creatureDef.id = prefix.ToUpper() + "_" + template.ToUpper() + ":DEFAULT";
            creatureDef.name = prefix.ToLower() + " " + template.ToLower();
            creatures[creatureCaste] = creatureDef;
            count--;
        }
    }
}


text:
package limelight.util;

import org.junit.Test;

import static org.junit.Assert.*;

public class StringUtilTest
{
  @Test
  public void join() throws Exception
  {
    String result = StringUtil.join(",", "one", "two", "three");
    assertEquals("one,two,three", result);
    result = StringUtil.join(",", "one", "two", "three");
    assertEquals("one,two,three", result);

    result = StringUtil.join(",");
    assertEquals("", result);

    result = StringUtil.join(",", "one");
    assertEquals("one", result);
  }

  @Test
  public void convertingStringsIntoTitles() throws Exception
  {
    assertEquals("Class Name", StringUtil.titleCase("Class Name"));
    assertEquals("Class Name", StringUtil.titleCase("class_name"));
    assertEquals("Once Upon A Time", StringUtil.titleCase("once_upon_a_time"));
    assertEquals("Once Upon A Time", StringUtil.titleCase("once-upon-a-time"));
    assertEquals("Ab C E Fg Hi J", StringUtil.titleCase("AbC-eFg-hiJ"));
    assertEquals("Ab C E Fg Hi J", StringUtil.titleCase("AbC_eFg_hiJ"));
    assertEquals("With Spaces", StringUtil.titleCase("with spaces"));
    assertEquals("Some Title", StringUtil.titleCase("Some Title"));
    assertEquals("Some Title", StringUtil.titleCase("SomeTitle"));
  }

  @Test
  public void camalizeStrings() throws Exception
  {
    assertEquals("defaultSceneName", StringUtil.camelCase("defaultSceneName"));
    assertEquals("setDefaultSceneName", StringUtil.camelCase("set defaultSceneName"));
    assertEquals("className", StringUtil.camelCase("class_name"));
    assertEquals("onceUponATime", StringUtil.camelCase("once_upon_a_time"));
    assertEquals("withSpaces", StringUtil.camelCase("with spaces"));
    assertEquals("withDash", StringUtil.camelCase("with-dash"));
    assertEquals("startingCapital", StringUtil.camelCase("starting Capital"));
  }

  @Test
  public void capitalCamalizeStrings() throws Exception
  {
    assertEquals("DefaultSceneName", StringUtil.capitalCamelCase("DefaultSceneName"));
    assertEquals("DefaultSceneName", StringUtil.capitalCamelCase("defaultSceneName"));
    assertEquals("ClassName", StringUtil.capitalCamelCase("class_name"));
    assertEquals("OnceUponATime", StringUtil.capitalCamelCase("once_upon_a_time"));
    assertEquals("WithSpaces", StringUtil.capitalCamelCase("with spaces"));
    assertEquals("WithDash", StringUtil.capitalCamelCase("with-dash"));
  }

  @Test
  public void underscore() throws Exception
  {
    assertEquals("class_name", StringUtil.snakeCase("class_name"));
    assertEquals("class_name", StringUtil.snakeCase("ClassName"));
    assertEquals("one_two_three", StringUtil.snakeCase("OneTwoThree"));
    assertEquals("one", StringUtil.snakeCase("One"));
    assertEquals("one_two_three", StringUtil.snakeCase("one-two-three"));
    assertEquals("one_two_three", StringUtil.snakeCase("one two three"));
  }

  @Test
  public void spearcase() throws Exception
  {
    assertEquals("class-name", StringUtil.spearCase("class_name"));
    assertEquals("class-name", StringUtil.spearCase("ClassName"));
    assertEquals("one-two-three", StringUtil.spearCase("OneTwoThree"));
    assertEquals("one", StringUtil.spearCase("One"));
    assertEquals("one-two-three", StringUtil.spearCase("one_two-three"));
    assertEquals("one-two-three", StringUtil.spearCase("one two three"));
  }
}


text:
Decided to start porting my old C++ game LuftAttack to a JS version.

C++ version can be seen here: https://www.youtube.com/watch?v=zTfvsdBqkdo

## Development

The game is built with [Phaser](http://phaser.io/).

It is being written in ES6, and is then transpiled to ES5 with babelify.

### Setup

#### Get dependencies

    $ npm install

#### Build files

    $ grunt

or

    $ grunt watch

#### Serve

    $ cd build && http-server


text:
class Professor < ActiveRecord::Base
  class << self
    def TBA
      where(name: "TBA").first_or_create
    end
  end
end


text:
PROTOTYPE! Browserify-like behavior for adding require() functionality to ASP.NET bundles.

## Usage

Add a script tag referencing the bundle path to your HTML:

`<script type="text/javascript" src="/bundles/browserified"></script>`

Then add to your BundleConfig.cs file:

```
bundles.AddBrowserifyBundle(
  new ScriptBundle("~/bundles/browserified")
  .IncludeDependency("~/scripts/uniq.js", "uniq")
  .IncludeDependency("~/scripts/jquery-{version}.js", "jquery") // supports the {version} tag too!
  .IncludeInputFile("~/scripts/main.js")
);
```

Current limitation is that you must call IncludeDependency manually for any dependencies your input files or dependencies require. Call IncludeInputFile for any of your main app files.

Example main.js:

```
var unique = require('uniq');
var jQuery = require('jquery');

var data = [1, 2, 2, 3, 4, 5, 5, 5, 6];

jQuery(function () {
    alert("jQuery is loaded by browserify!");
});

console.log(unique(data));
```

## WARNING

This code is not production-ready! This is currently a prototype only. Pull requests and issues accepted.


text:
/*
https://oj.leetcode.com/problems/lru-cache/

LRU Cache

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.
*/

#include "04_lru_cache.h"
using namespace std;

LRUCache::LRUCache(int capacity){
	entries = new LRUCacheEntry[capacity];
	for (int i=0; i<capacity; i++)
		_freeEntries.push_back(entries+i);
	head = new LRUCacheEntry;
	tail = new LRUCacheEntry;
	head->prev = NULL;
	head->next = tail;
	tail->next = NULL;
	tail->prev = head;
}

LRUCache::~LRUCache()
{
	delete head;
	delete tail;
	delete [] entries;
}

int LRUCache::get(int key){
	LRUCacheEntry* node = _mapping[key];
	if(node)
	{
		detach(node);
		attach(node);
		return node->data;
	}
	else return -1;
}

void LRUCache::set(int key, int data){
	LRUCacheEntry* node = _mapping[key];
	if(node)
	{
		// refresh the link list
		detach(node);
		node->data = data;
		attach(node);
	}
	else{
		if ( _freeEntries.empty() )
		{
			node = tail->prev;
			detach(node);
			_mapping.erase(node->key);
			node->data = data;
			node->key = key;
			_mapping[key] = node;
			attach(node);
		}
		else{
			node = _freeEntries.back();
			_freeEntries.pop_back();
			node->key = key;
			node->data = data;
			_mapping[key] = node;
			attach(node);
		}
	}
}

void LRUCache::detach(LRUCacheEntry* node)
{
	node->prev->next = node->next;
	node->next->prev = node->prev;
}

void LRUCache::attach(LRUCacheEntry* node)
{
	node->next = head->next;
	node->prev = head;
	head->next = node;
	node->next->prev = node;
}


text:
package ru.VirtaMarketAnalyzer.data;

import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
 * Created by cobr123 on 25.02.16.
 */
public final class UnitType {
    @SerializedName("i")
    final private String id;
    @SerializedName("c")
    final private String caption;
    @SerializedName("iu")
    final private String imgUrl;
    @SerializedName("s")
    final private List<UnitTypeSpec> specializations;

    public UnitType(final String id, final String caption, final String imgUrl, final List<UnitTypeSpec> specializations) {
        this.id = id;
        this.caption = caption;
        this.imgUrl = imgUrl;
        this.specializations = specializations;
    }

    public String getId() {
        return id;
    }

    public String getCaption() {
        return caption;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public List<UnitTypeSpec> getSpecializations() {
        return specializations;
    }

    public String getUnitTypeImgSrc() {
        if (imgUrl.equalsIgnoreCase("/img/unit_types/restaurant.gif")) {
            return imgUrl;
        } else if (imgUrl.equalsIgnoreCase("/img/unit_types/repair.gif")) {
            return imgUrl;
        } else {
            return "/img/unit_types/service_light.gif";
        }
    }
}


text:
package org.apache.hadoop.metrics2.source;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.lang.management.GarbageCollectorMXBean;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.hadoop.classification.VisibleForTesting;
import org.apache.hadoop.util.Preconditions;
import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.CommonConfigurationKeys;
import org.apache.hadoop.metrics2.MetricsCollector;
import org.apache.hadoop.metrics2.MetricsInfo;
import org.apache.hadoop.metrics2.MetricsRecordBuilder;
import org.apache.hadoop.metrics2.MetricsSource;
import org.apache.hadoop.metrics2.MetricsSystem;
import org.apache.hadoop.metrics2.lib.DefaultMetricsSystem;
import org.apache.hadoop.metrics2.lib.Interns;
import static org.apache.hadoop.metrics2.source.JvmMetricsInfo.*;
import static org.apache.hadoop.metrics2.impl.MsInfo.*;

import org.apache.hadoop.util.GcTimeMonitor;
import org.apache.hadoop.util.JvmPauseMonitor;

/**
 * JVM and logging related metrics.
 * Mostly used by various servers as a part of the metrics they export.
 */
@InterfaceAudience.Private
public class JvmMetrics implements MetricsSource {
  enum Singleton {
    INSTANCE;

    JvmMetrics impl;

    synchronized JvmMetrics init(String processName, String sessionId) {
      if (impl == null) {
        impl = create(processName, sessionId, DefaultMetricsSystem.instance());
      }
      return impl;
    }

    synchronized void shutdown() {
      DefaultMetricsSystem.instance().unregisterSource(JvmMetrics.name());
      impl = null;
    }
  }

  @VisibleForTesting
  public synchronized void registerIfNeeded(){
    // during tests impl might exist, but is not registered
    MetricsSystem ms = DefaultMetricsSystem.instance();
    if (ms.getSource("JvmMetrics") == null) {
      ms.register(JvmMetrics.name(), JvmMetrics.description(), this);
    }
  }

  static final float M = 1024*1024;
  static public final float MEMORY_MAX_UNLIMITED_MB = -1;

  final MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
  final List<GarbageCollectorMXBean> gcBeans =
      ManagementFactory.getGarbageCollectorMXBeans();
  private ThreadMXBean threadMXBean;
  final String processName, sessionId;
  private JvmPauseMonitor pauseMonitor = null;
  final ConcurrentHashMap<String, MetricsInfo[]> gcInfoCache =
      new ConcurrentHashMap<String, MetricsInfo[]>();
  private GcTimeMonitor gcTimeMonitor = null;

  @VisibleForTesting
  JvmMetrics(String processName, String sessionId, boolean useThreadMXBean) {
    this.processName = processName;
    this.sessionId = sessionId;
    if (useThreadMXBean) {
      this.threadMXBean = ManagementFactory.getThreadMXBean();
    }
  }

  public void setPauseMonitor(final JvmPauseMonitor pauseMonitor) {
    this.pauseMonitor = pauseMonitor;
  }

  public void setGcTimeMonitor(GcTimeMonitor gcTimeMonitor) {
    Preconditions.checkNotNull(gcTimeMonitor);
    this.gcTimeMonitor = gcTimeMonitor;
  }

  public static JvmMetrics create(String processName, String sessionId,
                                  MetricsSystem ms) {
    // Reloading conf instead of getting from outside since it's redundant in
    // code level to update all the callers across lots of modules,
    // this method is called at most once for components (NN/DN/RM/NM/...)
    // so that the overall cost is not expensive.
    boolean useThreadMXBean = new Configuration().getBoolean(
        CommonConfigurationKeys.HADOOP_METRICS_JVM_USE_THREAD_MXBEAN,
        CommonConfigurationKeys.HADOOP_METRICS_JVM_USE_THREAD_MXBEAN_DEFAULT);
    return ms.register(JvmMetrics.name(), JvmMetrics.description(),
                       new JvmMetrics(processName, sessionId, useThreadMXBean));
  }

  public static void reattach(MetricsSystem ms, JvmMetrics jvmMetrics) {
    ms.register(JvmMetrics.name(), JvmMetrics.description(), jvmMetrics);
  }

  public static JvmMetrics initSingleton(String processName, String sessionId) {
    return Singleton.INSTANCE.init(processName, sessionId);
  }

  /**
   * Shutdown the JvmMetrics singleton. This is not necessary if the JVM itself
   * is shutdown, but may be necessary for scenarios where JvmMetrics instance
   * needs to be re-created while the JVM is still around. One such scenario
   * is unit-testing.
   */
  public static void shutdownSingleton() {
    Singleton.INSTANCE.shutdown();
  }

  @Override
  public void getMetrics(MetricsCollector collector, boolean all) {
    MetricsRecordBuilder rb = collector.addRecord(JvmMetrics)
        .setContext("jvm").tag(ProcessName, processName)
        .tag(SessionId, sessionId);
    getMemoryUsage(rb);
    getGcUsage(rb);
    if (threadMXBean != null) {
      getThreadUsage(rb);
    } else {
      getThreadUsageFromGroup(rb);
    }
  }

  private void getMemoryUsage(MetricsRecordBuilder rb) {
    MemoryUsage memNonHeap = memoryMXBean.getNonHeapMemoryUsage();
    MemoryUsage memHeap = memoryMXBean.getHeapMemoryUsage();
    Runtime runtime = Runtime.getRuntime();
    rb.addGauge(MemNonHeapUsedM, memNonHeap.getUsed() / M)
      .addGauge(MemNonHeapCommittedM, memNonHeap.getCommitted() / M)
      .addGauge(MemNonHeapMaxM, calculateMaxMemoryUsage(memNonHeap))
      .addGauge(MemHeapUsedM, memHeap.getUsed() / M)
      .addGauge(MemHeapCommittedM, memHeap.getCommitted() / M)
      .addGauge(MemHeapMaxM, calculateMaxMemoryUsage(memHeap))
      .addGauge(MemMaxM, runtime.maxMemory() / M);
  }

  private float calculateMaxMemoryUsage(MemoryUsage memHeap) {
    long max =  memHeap.getMax() ;

     if (max == -1) {
       return MEMORY_MAX_UNLIMITED_MB;
     }

    return max / M;
  }

  private void getGcUsage(MetricsRecordBuilder rb) {
    long count = 0;
    long timeMillis = 0;
    for (GarbageCollectorMXBean gcBean : gcBeans) {
      long c = gcBean.getCollectionCount();
      long t = gcBean.getCollectionTime();
      MetricsInfo[] gcInfo = getGcInfo(gcBean.getName());
      rb.addCounter(gcInfo[0], c).addCounter(gcInfo[1], t);
      count += c;
      timeMillis += t;
    }
    rb.addCounter(GcCount, count)
      .addCounter(GcTimeMillis, timeMillis);

    if (pauseMonitor != null) {
      rb.addCounter(GcNumWarnThresholdExceeded,
          pauseMonitor.getNumGcWarnThresholdExceeded());
      rb.addCounter(GcNumInfoThresholdExceeded,
          pauseMonitor.getNumGcInfoThresholdExceeded());
      rb.addCounter(GcTotalExtraSleepTime,
          pauseMonitor.getTotalGcExtraSleepTime());
    }

    if (gcTimeMonitor != null) {
      rb.addGauge(GcTimePercentage,
          gcTimeMonitor.getLatestGcData().getGcTimePercentage());
    }
  }

  private MetricsInfo[] getGcInfo(String gcName) {
    MetricsInfo[] gcInfo = gcInfoCache.get(gcName);
    if (gcInfo == null) {
      gcInfo = new MetricsInfo[2];
      gcInfo[0] = Interns.info("GcCount" + gcName, "GC Count for " + gcName);
      gcInfo[1] = Interns
          .info("GcTimeMillis" + gcName, "GC Time for " + gcName);
      MetricsInfo[] previousGcInfo = gcInfoCache.putIfAbsent(gcName, gcInfo);
      if (previousGcInfo != null) {
        return previousGcInfo;
      }
    }
    return gcInfo;
  }

  private void getThreadUsage(MetricsRecordBuilder rb) {
    int threadsNew = 0;
    int threadsRunnable = 0;
    int threadsBlocked = 0;
    int threadsWaiting = 0;
    int threadsTimedWaiting = 0;
    int threadsTerminated = 0;
    long threadIds[] = threadMXBean.getAllThreadIds();
    for (ThreadInfo threadInfo : threadMXBean.getThreadInfo(threadIds, 0)) {
      if (threadInfo == null) continue; // race protection
      switch (threadInfo.getThreadState()) {
        case NEW:           threadsNew++;           break;
        case RUNNABLE:      threadsRunnable++;      break;
        case BLOCKED:       threadsBlocked++;       break;
        case WAITING:       threadsWaiting++;       break;
        case TIMED_WAITING: threadsTimedWaiting++;  break;
        case TERMINATED:    threadsTerminated++;    break;
      }
    }
    rb.addGauge(ThreadsNew, threadsNew)
      .addGauge(ThreadsRunnable, threadsRunnable)
      .addGauge(ThreadsBlocked, threadsBlocked)
      .addGauge(ThreadsWaiting, threadsWaiting)
      .addGauge(ThreadsTimedWaiting, threadsTimedWaiting)
      .addGauge(ThreadsTerminated, threadsTerminated);
  }

  private void getThreadUsageFromGroup(MetricsRecordBuilder rb) {
    int threadsNew = 0;
    int threadsRunnable = 0;
    int threadsBlocked = 0;
    int threadsWaiting = 0;
    int threadsTimedWaiting = 0;
    int threadsTerminated = 0;
    ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
    Thread[] threads = new Thread[threadGroup.activeCount()];
    threadGroup.enumerate(threads);
    for (Thread thread : threads) {
      if (thread == null) {
        // race protection
        continue;
      }
      switch (thread.getState()) {
      case NEW:           threadsNew++;           break;
      case RUNNABLE:      threadsRunnable++;      break;
      case BLOCKED:       threadsBlocked++;       break;
      case WAITING:       threadsWaiting++;       break;
      case TIMED_WAITING: threadsTimedWaiting++;  break;
      case TERMINATED:    threadsTerminated++;    break;
      default:
      }
    }
    rb.addGauge(ThreadsNew, threadsNew)
        .addGauge(ThreadsRunnable, threadsRunnable)
        .addGauge(ThreadsBlocked, threadsBlocked)
        .addGauge(ThreadsWaiting, threadsWaiting)
        .addGauge(ThreadsTimedWaiting, threadsTimedWaiting)
        .addGauge(ThreadsTerminated, threadsTerminated);
  }

}


text:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

/*
  Generated class for the Information page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-information',
  templateUrl: 'information.html'
})
export class InformationPage {

  constructor(public navCtrl: NavController) {}

  ionViewDidLoad() {
    console.log('Hello InformationPage Page');
  }

}


text:
from .response import json_response, JsonResponse
from .time import format_publish_time
from .request import require_method
from .markdown import BlogContentRenderer


text:
<?php

namespace Graze\DataFile\Format\Parser;

use ArrayIterator;
use Graze\DataFile\Format\JsonFormatInterface;
use Graze\DataFile\Helper\LineStreamIterator;
use Graze\DataFile\Helper\MapIterator;
use Iterator;
use RuntimeException;

class JsonParser implements ParserInterface
{
    const JSON_DEFAULT_DEPTH = 512;

    /** @var JsonFormatInterface */
    private $format;

    /**
     * JsonFormatter constructor.
     *
     * @param JsonFormatInterface $format
     */
    public function __construct(JsonFormatInterface $format)
    {
        $this->format = $format;
    }

    /**
     * @param resource $stream
     *
     * @return Iterator
     */
    public function parse($stream)
    {
        if ($this->format->isEachLine()) {
            $iterator = new LineStreamIterator(
                $stream,
                [
                    LineStreamIterator::OPTION_ENDING         => "\n",
                    LineStreamIterator::OPTION_IGNORE_BLANK   => $this->format->isIgnoreBlankLines(),
                    LineStreamIterator::OPTION_INCLUDE_ENDING => false,
                ]
            );
            $iterator->setIgnoreBlank($this->format->isIgnoreBlankLines());
            return new MapIterator($iterator, [$this, 'decodeJson']);
        } else {
            $json = $this->decodeJson(stream_get_contents($stream));
            if (is_array($json)) {
                return new ArrayIterator($json);
            } else {
                throw new RuntimeException("Expecting a json array to parse, unknown format detected");
            }
        }
    }

    /**
     * @param string $string
     *
     * @return mixed
     */
    public function decodeJson($string)
    {
        return json_decode(
            $string,
            $this->format->isJsonDecodeAssoc(),
            static::JSON_DEFAULT_DEPTH,
            $this->format->getJsonDecodeOptions()
        );
    }
}


text:
@component("wedding-gift-list")
class WeddingGiftList extends polymer.Base {

    @property({ type: Object })
    route: Object;

    constructor() {
        super();

    }

    _weddingNight(e: any): void {
        window.location.href = "/cota-para-noite-de-nupcias";
    }

    _honeyMoon(e: any): void {
        window.location.href = "/cota-para-lua-de-mel";
    }

}

WeddingGiftList.register();


text:
<?php

namespace Concrete\Core\Entity\File;

use Carbon\Carbon;
use Concrete\Core\Attribute\Category\AbstractCategory;
use Concrete\Core\Attribute\Key\Category;
use Concrete\Core\File\Image\Thumbnail\Type\Type;
use Concrete\Core\File\Importer;
use Concrete\Core\Tree\Node\Node;
use Concrete\Core\Tree\Node\Type\FileFolder;
use Doctrine\Common\Collections\ArrayCollection;
use FileSet;
use League\Flysystem\AdapterInterface;
use Loader;
use Core;
use User;
use Events;
use Page;
use PermissionKey;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(
 *     name="Files",
 *     indexes={
 *     @ORM\Index(name="uID", columns={"uID"}),
 *     @ORM\Index(name="fslID", columns={"fslID"}),
 *     @ORM\Index(name="ocID", columns={"ocID"}),
 *     @ORM\Index(name="fOverrideSetPermissions", columns={"fOverrideSetPermissions"}),
 *     }
 * )
 */
class File implements \Concrete\Core\Permission\ObjectInterface
{
    const CREATE_NEW_VERSION_THRESHOLD = 300;

    /**
     * @ORM\Id @ORM\Column(type="integer", options={"unsigned": true})
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    public $fID;

    /**
     * @ORM\Column(type="datetime")
     */
    public $fDateAdded = null;

    /**
     * @ORM\Column(type="string", nullable=true)
     */
    public $fPassword;

    /**
     * @ORM\OneToMany(targetEntity="Version", mappedBy="file", cascade={"persist"})
     * @ORM\JoinColumn(name="fID")
     */
    public $versions;

    /**
     * @ORM\Column(type="boolean")
     */
    public $fOverrideSetPermissions = false;

    /**
     * Originally placed on which page.
     *
     * @ORM\Column(type="integer", options={"unsigned": true})
     */
    public $ocID = 0;

    /**
     * @ORM\ManyToOne(targetEntity="\Concrete\Core\Entity\User\User")
     * @ORM\JoinColumn(name="uID", referencedColumnName="uID")
     **/
    public $author;

    /**
     * @ORM\Column(type="integer", options={"unsigned": true})
     */
    public $folderTreeNodeID = 0;

    /**
     * @ORM\ManyToOne(targetEntity="\Concrete\Core\Entity\File\StorageLocation\StorageLocation", inversedBy="files")
     * @ORM\JoinColumn(name="fslID", referencedColumnName="fslID")
     **/
    public $storageLocation;

    public function __construct()
    {
        $this->versions = new ArrayCollection();
    }

    /**
     * For all methods that file does not implement, we pass through to the currently active file version object.
     */
    public function __call($nm, $a)
    {
        $fv = $this->getApprovedVersion();
        if (is_null($fv)) {
            return;
        }

        return call_user_func_array([$fv, $nm], $a);
    }

    public function getPermissionResponseClassName()
    {
        return '\\Concrete\\Core\\Permission\\Response\\FileResponse';
    }

    public function getPermissionAssignmentClassName()
    {
        return '\\Concrete\\Core\\Permission\\Assignment\\FileAssignment';
    }

    public function getPermissionObjectKeyCategoryHandle()
    {
        return 'file';
    }

    public function getPermissionObjectIdentifier()
    {
        return $this->getFileID();
    }

    public function getPassword()
    {
        return $this->fPassword;
    }

    public function getStorageLocationID()
    {
        return $this->getFileStorageLocationObject()->getID();
    }

    /**
     * @return \Concrete\Core\Entity\File\StorageLocation\StorageLocation
     */
    public function getFileStorageLocationObject()
    {
        return $this->storageLocation;
    }

    /**
     * @return \Concrete\Core\Entity\File\Version[]
     */
    public function getFileVersions()
    {
        return $this->versions;
    }

    /**
     * Reindex the attributes on this file.
     */
    public function reindex()
    {
        $category = \Core::make('Concrete\Core\Attribute\Category\FileCategory');
        $indexer = $category->getSearchIndexer();
        $values = $category->getAttributeValues($this);
        foreach ($values as $value) {
            $indexer->indexEntry($category, $value, $this);
        }
    }

    protected function save()
    {
        $em = \ORM::entityManager();
        $em->persist($this);
        $em->flush();
    }

    public function setStorageLocation(\Concrete\Core\Entity\File\StorageLocation\StorageLocation $location)
    {
        $this->storageLocation = $location;
    }

    public function setFileStorageLocation(\Concrete\Core\Entity\File\StorageLocation\StorageLocation $newLocation)
    {
        $fh = Loader::helper('concrete/file');
        $currentLocation = $this->getFileStorageLocationObject();
        if ($newLocation->getID() == $currentLocation->getID()) {
            return false;
        }

        $currentFilesystem = $currentLocation->getFileSystemObject();

        $newFileSystem = $newLocation->getFileSystemObject();

        $list = $this->getVersionList();
        try {
            foreach ($list as $fv) {
                $manager = new \League\Flysystem\MountManager([
                    'current' => $currentFilesystem,
                    'new' => $newFileSystem,
                ]);
                $fp = $fh->prefix($fv->getPrefix(), $fv->getFilename());
                $manager->move('current://'.$fp, 'new://'.$fp);

                $thumbs = Type::getVersionList();
                foreach ($thumbs as $type) {
                    $fv->updateThumbnailStorageLocation($type, $newLocation);
                }
            }
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }

        $this->setStorageLocation($newLocation);
        $this->save();
    }

    public function setPassword($pw)
    {
        $fe = new \Concrete\Core\File\Event\FileWithPassword($this);
        $fe->setFilePassword($pw);
        Events::dispatch('on_file_set_password', $fe);

        $this->fPassword = $pw;
        $this->save();
    }

    public function setOriginalPage($ocID)
    {
        if ($ocID < 1) {
            return false;
        }
        $this->ocID = $ocID;
        $this->save();
    }

    public function getOriginalPageObject()
    {
        if ($this->ocID > 0) {
            $c = Page::getByID($this->ocID);
            if (is_object($c) && !$c->isError()) {
                return $c;
            }
        }
    }

    public function overrideFileFolderPermissions()
    {
        return $this->fOverrideSetPermissions;
    }

    public function resetPermissions($fOverrideSetPermissions = 0)
    {
        $db = Loader::db();
        $db->Execute('delete from FilePermissionAssignments where fID = ?', [$this->fID]);
        if ($fOverrideSetPermissions) {
            $permissions = PermissionKey::getList('file');
            foreach ($permissions as $pk) {
                $pk->setPermissionObject($this);
                $pk->copyFromFileSetToFile();
            }
        }
        $this->fOverrideSetPermissions = (bool) $fOverrideSetPermissions;
        $this->save();
    }

    /**
     * Returns the user ID of the author of the file (if available).
     *
     * @return int|null
     */
    public function getUserID()
    {
        return $this->author ? $this->author->getUserID() : null;
    }

    public function setUser(\Concrete\Core\Entity\User\User $user)
    {
        $this->author = $user;
        $this->save();
    }

    public function getFileSets()
    {
        $db = Loader::db();
        $fsIDs = $db->Execute('select fsID from FileSetFiles where fID = ?', [$this->getFileID()]);
        $filesets = [];
        while ($row = $fsIDs->FetchRow()) {
            $fs = FileSet::getByID($row['fsID']);
            if (is_object($fs)) {
                $filesets[] = $fs;
            }
        }

        return $filesets;
    }

    public function isStarred($u = false)
    {
        if (!$u) {
            $u = new User();
        }
        $db = Loader::db();
        $r = $db->GetOne(
            'select fsfID from FileSetFiles fsf inner join FileSets fs on fs.fsID = fsf.fsID where fsf.fID = ? and fs.uID = ? and fs.fsType = ?',
            [$this->getFileID(), $u->getUserID(), FileSet::TYPE_STARRED]
        );

        return $r > 0;
    }

    public function setDateAdded($fDateAdded)
    {
        $this->fDateAdded = $fDateAdded;
    }

    public function getDateAdded()
    {
        return $this->fDateAdded;
    }

    public function createNewVersion($copyUnderlyingFile = false)
    {
        $fv = $this->getRecentVersion();
        $fav = $this->getApprovedVersion();
        $fv2 = $fv->duplicate();

        if ($fv->getFileVersionID() == $fav->getFileVersionID()) {
            $fv2->approve();
        }

        if ($copyUnderlyingFile) {
            $fv2->duplicateUnderlyingFile();
        }

        return $fv2;
    }

    /**
     * Returns a file version object that is to be written to. Computes whether we can use the current most recent version, OR a new one should be created.
     */
    public function getVersionToModify($forceCreateNew = false)
    {
        $u = new User();
        $createNew = false;

        $fv = $this->getRecentVersion();
        $fav = $this->getApprovedVersion();

        // first test. Does the user ID of the most recent version match ours? If not, then we create new
        if ($u->getUserID() != $fv->getAuthorUserID()) {
            $createNew = true;
        }

        // second test. If the date the version was added is older than File::CREATE_NEW_VERSION_THRESHOLD, we create new
        $diff = time() - $fv->getDateAdded()->getTimestamp();
        if ($diff > self::CREATE_NEW_VERSION_THRESHOLD) {
            $createNew = true;
        }

        if ($forceCreateNew) {
            $createNew = true;
        }

        if ($createNew) {
            $fv2 = $fv->duplicate();

            // Are the recent and active versions the same? If so, we approve this new version we just made
            if ($fv->getFileVersionID() == $fav->getFileVersionID()) {
                $fv2->approve();
            }

            return $fv2;
        } else {
            return $fv;
        }
    }

    public function getFileID()
    {
        return $this->fID;
    }

    public function setFileFolder(FileFolder $folder)
    {
        $db = Loader::db();
        $em = \ORM::entityManager('core');

        $this->folderTreeNodeID = $folder->getTreeNodeID();

        $em->persist($this);
        $em->flush();
    }

    public function getFileFolderObject()
    {
        return Node::getByID($this->folderTreeNodeID);
    }

    public function getFileNodeObject()
    {
        $db = \Database::connection();
        $treeNodeID = $db->GetOne('select treeNodeID from TreeFileNodes where fID = ?', [$this->getFileID()]);

        return Node::getByID($treeNodeID);
    }

    public function duplicate()
    {
        $db = Loader::db();
        $em = \ORM::entityManager();

        $versions = $this->versions;

        // duplicate the core file object
        $nf = clone $this;
        $dh = Loader::helper('date');
        $date = $dh->getOverridableNow();
        $nf->fDateAdded = new Carbon($date);

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

        $folder = $this->getFileFolderObject();
        $folderNode = \Concrete\Core\Tree\Node\Type\File::add($nf, $folder);
        $nf->folderTreeNodeID = $folderNode->getTreeNodeID();

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

        // clear out the versions
        $nf->versions = new ArrayCollection();

        $fi = Core::make('helper/file');
        $cf = Core::make('helper/concrete/file');
        $importer = new Importer();
        $filesystem = $this->getFileStorageLocationObject()->getFileSystemObject();
        foreach ($versions as $version) {
            if ($version->isApproved()) {
                $cloneVersion = clone $version;
                $cloneVersion->setFileVersionID(1);
                $cloneVersion->setFile($nf);

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

                $cloneVersion->duplicateUnderlyingFile();

                foreach ($version->getAttributes() as $value) {
                    $value = clone $value;
                    $value->setVersion($cloneVersion);
                    $em->persist($value);
                }

                $em->flush();

                do {
                    $prefix = $importer->generatePrefix();
                    $path = $cf->prefix($prefix, $version->getFilename());
                } while ($filesystem->has($path));
                $filesystem->write($path, $version->getFileResource()->read(), [
                    'visibility' => AdapterInterface::VISIBILITY_PUBLIC,
                    'mimetype' => Core::make('helper/mime')->mimeFromExtension($fi->getExtension($version->getFilename())),
                ]);
                $cloneVersion->updateFile($version->getFilename(), $prefix);
                $nf->versions->add($cloneVersion);
            }
        }

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

        $v = [$this->fID];
        $q = 'select fID, paID, pkID from FilePermissionAssignments where fID = ?';
        $r = $db->query($q, $v);
        while ($row = $r->fetchRow()) {
            $v = [$nf->getFileID(), $row['paID'], $row['pkID']];
            $q = 'insert into FilePermissionAssignments (fID, paID, pkID) values (?, ?, ?)';
            $db->query($q, $v);
        }

        $fe = new \Concrete\Core\File\Event\DuplicateFile($this);
        $fe->setNewFileObject($nf);
        Events::dispatch('on_file_duplicate', $fe);

        return $nf;
    }

    public function getApprovedVersion()
    {
        // Ideally, doctrine's caching would handle this. Unfortunately, something is wrong with the $file
        // object going into the query, so none of them are ever marked as cacheable, which means we always
        // run the query even though we've run it multiple times in the same request. So we're going to
        // step between doctrine this time.
        $cache = \Core::make('cache/request');
        $item = $cache->getItem('file/version/approved/'.$this->getFileID());
        if (!$item->isMiss()) {
            return $item->get();
        }

        $em = \ORM::entityManager();
        $r = $em->getRepository('\Concrete\Core\Entity\File\Version');
        $fv = $r->findOneBy(['file' => $this, 'fvIsApproved' => true]);

        $cache->save($item->set($fv));

        return $fv;
    }

    public function inFileSet($fs)
    {
        $db = Loader::db();
        $r = $db->GetOne(
            'select fsfID from FileSetFiles where fID = ? and fsID = ?',
            [$this->getFileID(), $fs->getFileSetID()]
        );

        return $r > 0;
    }

    /**
     * Removes a file, including all of its versions.
     */
    public function delete($removeNode = true)
    {
        // first, we remove all files from the drive
        $db = Loader::db();
        $em = $db->getEntityManager();

        // fire an on_page_delete event
        $fve = new \Concrete\Core\File\Event\DeleteFile($this);
        $fve = Events::dispatch('on_file_delete', $fve);
        if (!$fve->proceed()) {
            return false;
        }

        // Delete the tree node for the file.
        if ($removeNode) {
            $nodeID = $db->fetchColumn('select treeNodeID from TreeFileNodes where fID = ?', [$this->getFileID()]);
            if ($nodeID) {
                $node = Node::getByID($nodeID);
                $node->delete();
            }
        }

        $versions = $this->getVersionList();
        foreach ($versions as $fv) {
            $fv->delete(true);
        }

        $db->Execute('delete from FileSetFiles where fID = ?', [$this->fID]);
        $db->Execute('delete from FileSearchIndexAttributes where fID = ?', [$this->fID]);
        $db->Execute('delete from DownloadStatistics where fID = ?', [$this->fID]);
        $db->Execute('delete from FilePermissionAssignments where fID = ?', [$this->fID]);
        $db->Execute('delete from FileImageThumbnailPaths where fileID = ?', [$this->fID]);

        $query = $em->createQuery('select fav from Concrete\Core\Entity\Attribute\Value\Value\ImageFileValue fav inner join fav.file f where f.fID = :fID');
        $query->setParameter('fID', $this->getFileID());
        $values = $query->getResult();
        foreach ($values as $genericValue) {
            foreach (Category::getList() as $category) {
                $category = $category->getController();
                /*
                 * @var $category AbstractCategory
                 */
                $values = $category->getAttributeValueRepository()->findBy(['generic_value' => $genericValue]);
                foreach ($values as $attributeValue) {
                    $category->deleteValue($attributeValue);
                }
            }
        }

        $db->Execute('delete from Files where fID = ?', [$this->fID]);
    }

    /**
     * returns the most recent FileVersion object.
     *
     * @return Version
     */
    public function getRecentVersion()
    {
        $em = \ORM::entityManager();
        $r = $em->getRepository('\Concrete\Core\Entity\File\Version');

        return $r->findOneBy(
            ['file' => $this],
            ['fvID' => 'desc']
        );
    }

    /**
     * returns the FileVersion object for the provided fvID
     * if none provided returns the approved version.
     *
     * @param int $fvID
     *
     * @return Version
     */
    public function getVersion($fvID = null)
    {
        if (!$fvID) {
            return $this->getApprovedVersion();
        }

        $em = \ORM::entityManager();
        $r = $em->getRepository('\Concrete\Core\Entity\File\Version');

        return $r->findOneBy(['file' => $this, 'fvID' => $fvID]);
    }

    /**
     * Returns an array of all FileVersion objects owned by this file.
     */
    public function getVersionList()
    {
        return $this->getFileVersions();
    }

    public function getTotalDownloads()
    {
        $db = Loader::db();

        return $db->GetOne('select count(*) from DownloadStatistics where fID = ?', [$this->getFileID()]);
    }

    public function getDownloadStatistics($limit = 20)
    {
        $db = Loader::db();
        $limitString = '';
        if ($limit != false) {
            $limitString = 'limit '.intval($limit);
        }

        if (is_object($this) && $this instanceof self) {
            return $db->getAll(
                "SELECT * FROM DownloadStatistics WHERE fID = ? ORDER BY timestamp desc {$limitString}",
                [$this->getFileID()]
            );
        } else {
            return $db->getAll("SELECT * FROM DownloadStatistics ORDER BY timestamp desc {$limitString}");
        }
    }

    /**
     * Tracks File Download, takes the cID of the page that the file was downloaded from.
     *
     * @param int $rcID
     */
    public function trackDownload($rcID = null)
    {
        $u = new User();
        $uID = intval($u->getUserID());
        $fv = $this->getApprovedVersion();
        $fvID = $fv->getFileVersionID();
        if (!isset($rcID) || !is_numeric($rcID)) {
            $rcID = 0;
        }

        $fve = new \Concrete\Core\File\Event\FileAccess($fv);
        Events::dispatch('on_file_download', $fve);

        $config = Core::make('config');
        if ($config->get('concrete.statistics.track_downloads')) {
            $db = Loader::db();
            $db->Execute(
                'insert into DownloadStatistics (fID, fvID, uID, rcID) values (?, ?, ?, ?)',
                [$this->fID, intval($fvID), $uID, $rcID]
            );
        }
    }

    /**
     * @deprecated
     */
    public function isError()
    {
        return false;
    }
}


text:
package org.jbpm.runtime.manager.impl.deploy;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlTransient;

import org.kie.internal.runtime.conf.AuditMode;
import org.kie.internal.runtime.conf.BuilderHandler;
import org.kie.internal.runtime.conf.DeploymentDescriptor;
import org.kie.internal.runtime.conf.DeploymentDescriptorBuilder;
import org.kie.internal.runtime.conf.NamedObjectModel;
import org.kie.internal.runtime.conf.ObjectModel;
import org.kie.internal.runtime.conf.PersistenceMode;
import org.kie.internal.runtime.conf.RuntimeStrategy;
/*
 * NOTE: Whenever adding new fields that represent actual item of deployment descriptor always update:
 * - isEmpty method
 * - clearClone method
 * - Builder
 */
@XmlRootElement(name="deployment-descriptor")
@XmlAccessorType(XmlAccessType.NONE)
public class DeploymentDescriptorImpl implements DeploymentDescriptor, Serializable {

	private static final long serialVersionUID = 1L;

	@XmlElement(name="persistence-unit")
	@XmlSchemaType(name="string")
	private String persistenceUnit;

	@XmlElement(name="audit-persistence-unit")
	@XmlSchemaType(name="string")
	private String auditPersistenceUnit;

	@XmlElement(name="audit-mode")
	private AuditMode auditMode = AuditMode.JPA;

	@XmlElement(name="persistence-mode")
	private PersistenceMode persistenceMode = PersistenceMode.JPA;

	@XmlElement(name="runtime-strategy")
	private RuntimeStrategy runtimeStrategy = RuntimeStrategy.SINGLETON;

	@XmlElement(name="marshalling-strategy")
	@XmlElementWrapper(name="marshalling-strategies")
	private Set<ObjectModel> marshallingStrategies = new LinkedHashSet<ObjectModel>();

	@XmlElement(name="event-listener")
	@XmlElementWrapper(name="event-listeners")
	private Set<ObjectModel> eventListeners = new LinkedHashSet<ObjectModel>();

	@XmlElement(name="task-event-listener")
	@XmlElementWrapper(name="task-event-listeners")
	private Set<ObjectModel> taskEventListeners = new LinkedHashSet<ObjectModel>();

	@XmlElement(name="global")
	@XmlElementWrapper(name="globals")
	private Set<NamedObjectModel> globals = new LinkedHashSet<NamedObjectModel>();

	@XmlElement(name="work-item-handler")
	@XmlElementWrapper(name="work-item-handlers")
	private Set<NamedObjectModel> workItemHandlers = new LinkedHashSet<NamedObjectModel>();

	@XmlElement(name="environment-entry")
	@XmlElementWrapper(name="environment-entries")
	private Set<NamedObjectModel> environmentEntries = new LinkedHashSet<NamedObjectModel>();

	@XmlElement(name="configuration")
	@XmlElementWrapper(name="configurations")
	private Set<NamedObjectModel> configuration = new LinkedHashSet<NamedObjectModel>();

	@XmlElement(name="required-role")
	@XmlElementWrapper(name="required-roles")
	private Set<String> requiredRoles = new LinkedHashSet<String>();

	@XmlElement(name="remoteable-class")
	@XmlElementWrapper(name="remoteable-classes")
	private List<String> classes = new ArrayList<String>();

	@XmlElement(name="limit-serialization-classes")
	private Boolean limitSerializationClasses = true;

	@XmlTransient
	private Map<String, Set<String>> mappedRoles;

	protected void mapRequiredRoles() {
		if (mappedRoles != null) {
			return;
		}
		mappedRoles = new HashMap<String, Set<String>>();

		Set<String> typeAll = new LinkedHashSet<String>();
		Set<String> typeView = new LinkedHashSet<String>();
		Set<String> typeExecute = new LinkedHashSet<String>();

		mappedRoles.put(TYPE_ALL, typeAll);
		mappedRoles.put(TYPE_VIEW, typeView);
		mappedRoles.put(TYPE_EXECUTE, typeExecute);

		if (requiredRoles != null && !requiredRoles.isEmpty()) {

			for (String roleString : requiredRoles) {
				String rolePrefix = null;
				String role = roleString;

				if (roleString.indexOf(":") != -1) {
					String[] roleInfo = roleString.split(":");

					rolePrefix = roleInfo[0];
					role = roleInfo[1];

					mappedRoles.get(rolePrefix).add(role);
					typeAll.add(role);
				} else {
					typeAll.add(role);
					typeView.add(role);
					typeExecute.add(role);
				}
			}

		}

	}

	public DeploymentDescriptorImpl() {
		// fox jaxb only
	}

	public DeploymentDescriptorImpl(String defaultPU) {
		this.persistenceUnit = defaultPU;
		this.auditPersistenceUnit = defaultPU;
	}

	@Override
	public String getPersistenceUnit() {
		return persistenceUnit;
	}

	@Override
	public String getAuditPersistenceUnit() {
		return auditPersistenceUnit;
	}

	@Override
	public AuditMode getAuditMode() {
		return auditMode;
	}

	@Override
	public PersistenceMode getPersistenceMode() {
		return persistenceMode;
	}

	@Override
	public RuntimeStrategy getRuntimeStrategy() {
		return runtimeStrategy;
	}

	@Override
	public List<ObjectModel> getMarshallingStrategies() {
		return new ArrayList<ObjectModel>(cleanSet(marshallingStrategies));
	}

	@Override
	public List<ObjectModel> getEventListeners() {
		return new ArrayList<ObjectModel>(cleanSet(eventListeners));
	}

	@Override
	public List<NamedObjectModel> getGlobals() {
		return new ArrayList<NamedObjectModel>(cleanNamedSet(globals));
	}

	@Override
	public List<NamedObjectModel> getWorkItemHandlers() {
		return new ArrayList<NamedObjectModel>(cleanNamedSet(workItemHandlers));
	}

	@Override
	public List<ObjectModel> getTaskEventListeners() {
		return new ArrayList<ObjectModel>(cleanSet(taskEventListeners));
	}

	@Override
	public List<NamedObjectModel> getEnvironmentEntries() {
		return new ArrayList<NamedObjectModel>(cleanNamedSet(environmentEntries));
	}

	@Override
	public List<NamedObjectModel> getConfiguration() {
		return new ArrayList<NamedObjectModel>(cleanNamedSet(configuration));
	}

	@Override
	public List<String> getRequiredRoles() {
		return new ArrayList<String>(requiredRoles);
	}
	@Override
	public List<String> getRequiredRoles(String type) {
		mapRequiredRoles();
		Set<String> roles = mappedRoles.get(type);
		if (roles == null) {
			return new ArrayList<String>();
		} else {
			return new ArrayList<String>(roles);
		}
	}

	@Override
	public List<String> getClasses() {
		if (classes == null) {
			return new ArrayList<String>();
		}
		return new ArrayList<String>(classes);
	}

	public void setPersistenceUnit(String persistenceUnit) {
		this.persistenceUnit = persistenceUnit;
	}

	public void setAuditPersistenceUnit(String auditPersistenceUnit) {
		this.auditPersistenceUnit = auditPersistenceUnit;
	}

	public void setAuditMode(AuditMode auditMode) {
		this.auditMode = auditMode;
	}

	public void setPersistenceMode(PersistenceMode persistenceMode) {
		this.persistenceMode = persistenceMode;
	}

	public void setRuntimeStrategy(RuntimeStrategy runtimeStrategy) {
		this.runtimeStrategy = runtimeStrategy;
	}

	public void setMarshallingStrategies(List<ObjectModel> marshallingStrategies) {
		if (marshallingStrategies != null) {
			this.marshallingStrategies = new HashSet<ObjectModel>(marshallingStrategies);
		}
	}

	public void setEventListeners(List<ObjectModel> eventListeners) {
		if (eventListeners != null) {
			this.eventListeners = new HashSet<ObjectModel>(eventListeners);
		}
	}

	public void setTaskEventListeners(List<ObjectModel> taskEventListeners) {
		if (taskEventListeners != null) {
			this.taskEventListeners = new HashSet<ObjectModel>(taskEventListeners);
		}
	}

	public void setGlobals(List<NamedObjectModel> globals) {
		if (globals != null) {
			this.globals = new HashSet<NamedObjectModel>(globals);
		}
	}

	public void setWorkItemHandlers(List<NamedObjectModel> workItemHandlers) {
		if (workItemHandlers != null) {
			this.workItemHandlers = new HashSet<NamedObjectModel>(workItemHandlers);
		}
	}

	public void setEnvironmentEntries(List<NamedObjectModel> environmentEntires) {
		if (environmentEntires != null) {
			this.environmentEntries = new HashSet<NamedObjectModel>(environmentEntires);
		}
	}

	public void setConfiguration(List<NamedObjectModel> configuration) {
		if (configuration != null) {
			this.configuration = new HashSet<NamedObjectModel>(configuration);
		}
	}

	public void setRequiredRoles(List<String> requiredRoles) {
		if (requiredRoles != null) {
			this.requiredRoles = new HashSet<String>(requiredRoles);
		}
	}

	public void setClasses(List<String> classes) {
		if (classes != null) {
			this.classes = new ArrayList<String>(classes);
		}
	}

    public Boolean getLimitSerializationClasses() {
        return limitSerializationClasses;
    }

    public void setLimitSerializationClasses( Boolean limitSerializationClasses ) {
        this.limitSerializationClasses = limitSerializationClasses;
    }

    protected Set<NamedObjectModel> cleanNamedSet(Set<NamedObjectModel> input) {
        input.remove(null);

        return input;
	}

    protected Set<ObjectModel> cleanSet(Set<ObjectModel> input) {
        input.remove(null);

        return input;
    }

    protected void removeTransient(Set<?> input) {
        Iterator<?> it = input.iterator();

        while (it.hasNext()) {
            Object object = (Object) it.next();
            if (object instanceof TransientNamedObjectModel
                    || object instanceof TransientObjectModel) {
                it.remove();
            }
        }
    }

    public DeploymentDescriptor clearClone() throws CloneNotSupportedException {
	    DeploymentDescriptorImpl clone = new DeploymentDescriptorImpl();

	     clone.getBuilder()
	    .setClasses(getClasses())
	    .setConfiguration(getConfiguration())
	    .setEnvironmentEntries(getEnvironmentEntries())
	    .setEventListeners(getEventListeners())
	    .setGlobals(getGlobals())
	    .setMarshalingStrategies(getMarshallingStrategies())
	    .setRequiredRoles(getRequiredRoles())
	    .setTaskEventListeners(getTaskEventListeners())
	    .setWorkItemHandlers(getWorkItemHandlers())
	    .auditMode(getAuditMode())
	    .auditPersistenceUnit(getAuditPersistenceUnit())
	    .persistenceMode(getPersistenceMode())
	    .persistenceUnit(getPersistenceUnit())
	    .runtimeStrategy(getRuntimeStrategy())
	    .setLimitSerializationClasses(getLimitSerializationClasses());

	     removeTransient(clone.configuration);
	     removeTransient(clone.environmentEntries);
	     removeTransient(clone.eventListeners);
	     removeTransient(clone.globals);
	     removeTransient(clone.marshallingStrategies);
	     removeTransient(clone.taskEventListeners);
	     removeTransient(clone.workItemHandlers);

	     return clone;
    }

    public boolean isEmpty() {
        boolean empty = true;

        if (persistenceUnit != null) {
            return false;
        }
        if (auditPersistenceUnit != null) {
            return false;
        }
        if (auditMode != AuditMode.JPA) {
            return false;
        }
        if (persistenceMode != PersistenceMode.JPA) {
            return false;
        }
        if (runtimeStrategy != RuntimeStrategy.SINGLETON) {
            return false;
        }
        if ( marshallingStrategies != null && !marshallingStrategies.isEmpty()) {
            return false;
        }
        if (eventListeners != null && !eventListeners.isEmpty()) {
            return false;
        }
        if (taskEventListeners != null && !taskEventListeners.isEmpty()) {
            return false;
        }
        if (globals != null && !globals.isEmpty()) {
            return false;
        }
        if (workItemHandlers != null && !workItemHandlers.isEmpty()) {
            return false;
        }
        if (environmentEntries != null && !environmentEntries.isEmpty()) {
            return false;
        }
        if (configuration != null && !configuration.isEmpty()) {
            return false;
        }
        if (requiredRoles != null && !requiredRoles.isEmpty()) {
            return false;
        }
        if (classes != null && !classes.isEmpty()) {
            return false;
        }
        if (!limitSerializationClasses) {
            return false;
        }

        return empty;
    }

    @Override
	public DeploymentDescriptorBuilder getBuilder() {

		return new DeploymentDescriptorBuilder() {

			private BuilderHandler handler = new BuilderHandler() {

				@Override
				public boolean accepted(Object value) {
					return true;
				}
			};

			private DeploymentDescriptorImpl descriptor = DeploymentDescriptorImpl.this;

			@Override
			public DeploymentDescriptorBuilder runtimeStrategy(RuntimeStrategy strategy) {
				if (handler.accepted(strategy)) {
					descriptor.setRuntimeStrategy(strategy);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder persistenceUnit(String pu) {
				if (handler.accepted(pu)) {
					descriptor.setPersistenceUnit(pu);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder persistenceMode(PersistenceMode mode) {
				if (handler.accepted(mode)) {
					descriptor.setPersistenceMode(mode);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder auditPersistenceUnit(String pu) {
				if (handler.accepted(pu)) {
					descriptor.setAuditPersistenceUnit(pu);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder auditMode(AuditMode mode) {
				if (handler.accepted(mode)) {
					descriptor.setAuditMode(mode);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addWorkItemHandler(NamedObjectModel model) {
				if (handler.accepted(model)) {
					if (!descriptor.workItemHandlers.add(model)) {
						descriptor.workItemHandlers.remove(model);
						descriptor.workItemHandlers.add(model);
					}
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addTaskEventListener(ObjectModel model) {
				if (handler.accepted(model)) {
					if (!descriptor.taskEventListeners.add(model)) {
						descriptor.taskEventListeners.remove(model);
						descriptor.taskEventListeners.add(model);
					}
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addMarshalingStrategy(ObjectModel model) {
				if (handler.accepted(model)) {
					if (!descriptor.marshallingStrategies.add(model)) {
						descriptor.marshallingStrategies.remove(model);
						descriptor.marshallingStrategies.add(model);
					}
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addGlobal(NamedObjectModel model) {
				if (handler.accepted(model)) {
					if (!descriptor.globals.add(model)) {
						descriptor.globals.remove(model);
						descriptor.globals.add(model);
					}
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addEventListener(ObjectModel model) {
				if (handler.accepted(model)) {
					if (!descriptor.eventListeners.add(model)) {
						descriptor.eventListeners.remove(model);
						descriptor.eventListeners.add(model);
					}
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addEnvironmentEntry(NamedObjectModel model) {
				if (handler.accepted(model)) {
					if (!descriptor.environmentEntries.add(model)) {
						descriptor.environmentEntries.remove(model);
						descriptor.environmentEntries.add(model);
					}
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addConfiguration(NamedObjectModel model) {
				if (handler.accepted(model)) {
					if (!descriptor.configuration.add(model)) {
						descriptor.configuration.remove(model);
						descriptor.configuration.add(model);
					}
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addRequiredRole(String role) {
				if (handler.accepted(role)) {
					descriptor.requiredRoles.add(role);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder addClass(String clazz) {
				if (handler.accepted(clazz)) {
					descriptor.classes.add(clazz);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setConfiguration(List<NamedObjectModel> models) {
				if (handler.accepted(models)) {
					descriptor.setConfiguration(models);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setEnvironmentEntries(List<NamedObjectModel> models) {
				if (handler.accepted(models)) {
					descriptor.setEnvironmentEntries(models);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setWorkItemHandlers(List<NamedObjectModel> models) {
				if (handler.accepted(models)) {
					descriptor.setWorkItemHandlers(models);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setGlobals(List<NamedObjectModel> models) {
				if (handler.accepted(models)) {
					descriptor.setGlobals(models);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setEventListeners(List<ObjectModel> models) {
				if (handler.accepted(models)) {
					descriptor.setEventListeners(models);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setTaskEventListeners(List<ObjectModel> models) {
				if (handler.accepted(models)) {
					descriptor.setTaskEventListeners(models);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setMarshalingStrategies(List<ObjectModel> models) {
				if (handler.accepted(models)) {
					descriptor.setMarshallingStrategies(models);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setRequiredRoles(List<String> roles) {
				if (handler.accepted(roles)) {
					descriptor.setRequiredRoles(roles);
				}
				return this;
			}

			@Override
			public DeploymentDescriptorBuilder setClasses(List<String> classes) {
				if (handler.accepted(classes)) {
					descriptor.setClasses(classes);
				}
				return this;
			}

			@Override
            public DeploymentDescriptorBuilder setLimitSerializationClasses(Boolean limit) {
				if (handler.accepted(limit)) {
				    descriptor.setLimitSerializationClasses(limit);
				}
                return this;
            }

			@Override
			public void setBuildHandler(BuilderHandler handler) {
				this.handler = handler;
			}

			@Override
			public DeploymentDescriptor get() {
				return descriptor;
			}

		};
	}

	@Override
	public String toXml() {
		return DeploymentDescriptorIO.toXml(this);
	}

}


text:
@class BasicCollectionViewDataSource;

@interface BasicCollectionViewAdapter : BasicAdapter<UICollectionViewDelegate,UICollectionViewDataSource>

-(NSInteger)numberOfItemsInSection:(NSInteger)section;

-(UICollectionViewCell *)cellForItemAtIndexPath:(NSIndexPath *)indexPath;

- (CGSize)sizeForItemAtIndexPath:(NSIndexPath *)indexPath;

@property (strong , nonatomic) BasicCollectionView *view;

@property (strong,nonatomic) BasicCollectionViewDataSource *basicDataSource;

@end


text:
Simple Cache
========================

[![Build Status](https://travis-ci.org/SimpleSoftwareIO/simple-cache.svg?branch=master)](https://travis-ci.org/SimpleSoftwareIO/simple-cache)
[![Latest Stable Version](https://poser.pugx.org/simplesoftwareio/simple-cache/v/stable.svg)](https://packagist.org/packages/simplesoftwareio/simple-cache)
[![Latest Unstable Version](https://poser.pugx.org/simplesoftwareio/simple-cache/v/unstable.svg)](https://packagist.org/packages/simplesoftwareio/simple-cache)
[![License](https://poser.pugx.org/simplesoftwareio/simple-cache/license.svg)](https://packagist.org/packages/simplesoftwareio/simple-cache)
[![Total Downloads](https://poser.pugx.org/simplesoftwareio/simple-cache/downloads.svg)](https://packagist.org/packages/simplesoftwareio/simple-cache)

- [Introduction](#docs-introduction)
- [Configuration](#docs-configuration)
- [Usage](#docs-usage)

## Try our dead simple, free file transfer service [keep.sh](https://keep.sh)

## Configuration

#### Composer

First, add the Simple Cache package to your `require` in your `composer.json` file:

	"require": {
		"simplesoftwareio/simple-cache": "~1"
	}

Next, run the `composer update` command.

## Usage

The cacheable trait may be used by adding the trait to the Eloquent model of your choice.

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use SimpleSoftwareIO\Cache\Cacheable;

    class User extends Model
    {
        use Cacheable;
    }

Yes, it really is that simple to use.  The settings will use the default Cache store set up in your Laravel application.  Further, models will be cached for 30 minutes by default.

### Properties

#### cacheLength

You may adjust the default cache length by modifying the `cacheLength` property on the model.

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use SimpleSoftwareIO\Cache\Cacheable;

    class User extends Model
    {
        use Cacheable;
        protected $cacheLength = 60; //Will cache for 60 minutes
    }

#### cacheStore

The configured cache store may also be adjusted by modifying the `cacheStore` property.  The cache store will need to be set up in your application's `config/cache.php` configuration file.

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use SimpleSoftwareIO\Cache\Cacheable;

    class User extends Model
    {
        use Cacheable;
        protected $cacheStore = 'redis'; //Will use the configured `redis` store set up in your `config/cache.php` file.
    }

#### cacheBusting

Cache busting will automatically invalid the cache when an `insert/update/delete` command is ran by your models.  You can enable this feature by setting the `cacheBusting` property to `true` on your Eloquent model.  By default this feature is disabled.

    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;
    use SimpleSoftwareIO\Cache\Cacheable;

    class User extends Model
    {
        use Cacheable;
        protected $cacheBusting = true;

    }

>Be careful!  Eloquent Model's with a high amount of insert/update/delete traffic should not use the cache busting feature.  The large amount of changes will invalid the model too often and cause the cache to be useless.  It is better to set a lower cache length to invalid the results frequently if up to date data is required.

### Methods

#### flush()

The `flush` method will flush the cache for a model.

    (new User)->flush()  //Cache is flushed for the `User` model.

#### isBusting()

`isBusting` will return the current status of the `cacheBusting` property.

    if((new User)->isBusting()) {
        // Is cache busting
    }

#### remember($length)

`remember` will set the length of time in minutes to remember an Eloquent query.

    User::remember(45)->where('id', 4')->get();

#### rememberForever()

`rememberForever` will remember a query forever.  Well, technically 10 years but lets pretend it is forever eh?

    User::rememberForever()->where('id', 4')->get();

#### dontRemember()

And lastly, `dontRemember` will not cache a query result.

    User::dontRemember(0)->where('id', 4')->get();


text:
package org.jsonschema2pojo;

import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import com.sun.codemodel.JPackage;
import com.sun.codemodel.util.UnicodeEscapeWriter;

/**
 * A writer that honours the given character encoding (workaround for an issue
 * with {@link com.sun.codemodel.util.EncoderFactory#createEncoder(String)} that
 * causes the given encoding to be ignored).
 */
public class FileCodeWriterWithEncoding extends com.sun.codemodel.writer.FileCodeWriter {

    public FileCodeWriterWithEncoding(File target, String encoding) throws IOException {
        super(target, encoding);
    }

    @Override
    public Writer openSource(JPackage pkg, String fileName) throws IOException {
        final Writer bw = new OutputStreamWriter(openBinary(pkg, fileName), encoding);

        return new UnicodeEscapeWriter(bw) {
            private final CharsetEncoder encoder = Charset.forName(encoding).newEncoder();

            @Override
            protected boolean requireEscaping(int ch) {
                // control characters
                if (ch < 0x20 && " \t\r\n".indexOf(ch) == -1) {
                    return true;
                }
                // ASCII chars
                if (ch < 0x80) {
                    return false;
                }
                return !encoder.canEncode((char) ch);
            }
        };
    }

}


text:
package teamwap.wap;

/**
 * Created by Tabi on 2016-12-16.
 */

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;

public class ListViewBtnAdapter extends ArrayAdapter implements View.OnClickListener {

    // 버튼 클릭 이벤트를 위한 Listener 인터페이스 정의
    public interface  ListBtnClickListener{
        void onListBtnClick(int position);
    }

    // 생성자로 부터 전달된 두 변수 지정
    int resourceId;
    private ListBtnClickListener listBtnClickListener;

    // ListViewBtnAdapter 생성자. 마지막에 ListBtnClickListener 추가
    ListViewBtnAdapter(Context context, int resource, ArrayList<ListViewBtnItem> list, ListBtnClickListener clickListener){
        super(context, resource, list);

        // resource id 값 복사
        this.resourceId = resource;
        this.listBtnClickListener = clickListener;
    }

    // 새롭게 만든 Layout을 위한 View를 생성하는 코드
    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        final int pos = position;
        final Context context = parent.getContext();

        // 생성자로부터 저장된 resourceId에 해당하는 Layout을 inflate하여 convertView 참조
        if (convertView == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(this.resourceId, parent, false);
        }

        // 화면에 표시될 View로부터 위젯에 대한 참조 획득
        final ImageView iconImageView = (ImageView) convertView.findViewById(R.id.imageView1);
        // 텍스트뷰 추가시 사용
        final TextView textTextView = (TextView) convertView.findViewById(R.id.textView1);

        // Data Set(listViewItemList)에서 position에 위치한 데이터 참조 획득
        final ListViewBtnItem listViewItem = (ListViewBtnItem) getItem(position);

        // 아이템 내 각 위젯에 데이터 반영
        iconImageView.setImageDrawable(listViewItem.getIcon());
        textTextView.setText(listViewItem.getText());

        // TAG에 position값 지정. Adapter를 click listener로 지정.
        Button button1 = (Button) convertView.findViewById(R.id.buttonb);
        button1.setTag(position);
        button1.setOnClickListener(this);

        return convertView;
    }

    // MainActivity에 있는 리스너랑 상호작용 하는 코드임
    public void onClick(View v){
        if (this.listBtnClickListener != null){
            this.listBtnClickListener.onListBtnClick((int)v.getTag());
        }
    }
}


text:
Super simple CLI tool to post messages to Campfire

## Installation

Install the gem on your system

    $ gem install fitzcamping

Set the environment variables

    export CAMPFIRE_SITE=<your site name>
    export CAMPFIRE_ROOM=<room name>
    export CAMPFIRE_TOKEN=<your campfire API token>

And then execute:

    $ camper "Hello world in campfire"

## Usage

Run from command line

    $ camper "message"

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
#ifndef CRYPTOPP_AES_H
#define CRYPTOPP_AES_H

/** \file
	AES winner announced on 10/2/2000
*/

#include "rijndael.h"

NAMESPACE_BEGIN(CryptoPP)

#ifdef CRYPTOPP_DOXYGEN_PROCESSING	// Use inheritance instead of typedef to get a seperate API reference page for AES
//! AES
class AES : public Rijndael, public BlockCipherDocumentation {};
#else
typedef Rijndael AES;
#endif

typedef RijndaelEncryption AESEncryption;
typedef RijndaelDecryption AESDecryption;

NAMESPACE_END

#endif


text:
<?php

declare(strict_types=1);

namespace Sylius\Behat\Service;

/**
 * @author Arkadiusz Krakowiak <arkadiusz.krakowiak@lakion.com>
 */
interface ResponseLoaderInterface
{
    /**
     * @param string $source
     *
     * @return array
     */
    public function getMockedResponse($source);

    /**
     * @param string $source
     *
     * @return array
     */
    public function getExpectedResponse($source);
}


text:
"""
Calculate combined Say and VP delegate scores.

"""

def say_scores(sheet, correct):
    """Calculate and compile list of Say scores."""
    active_sheet(sheet)
    delegates = []
    # Set data start row.
    row = 2
    # Loop through rows until empty row is found.
    data_present = True
    while data_present:
        # Append nested list to 'delegates' list containing delegate PIN,
        # answers and initialised score.
        if sheet in ('asthma', 'copd', 'ipf'):
            delegates.append(
                [Cell(row, 'C').value,
                CellRange((row, 'D'), (row, 'F')).value, 0])
        elif sheet == 'walkabout_1':
            delegates.append(
                [int(Cell(row, 'A').value[1:]),
                CellRange((row, 'C'), (row, 'E')).value, 0])
        elif sheet == 'walkabout_2':
            delegates.append(
                [int(Cell(row, 'A').value[1:]), [Cell(row, 'C').value], 0])
        else:
            delegates.append(
                [int(Cell(row, 'A').value[1:]), [Cell(row, 'B').value], 0])
        # Compare delegate answers to correct answers, add 10 to score for each
        # match.
        i = 0
        for answer in correct:
            if answer == delegates[-1][1][i]:
                delegates[-1][2] += 10
            i += 1
        # Write delegate score to sheet.
        Cell(row, 'H').value = delegates[-1][2]
        row += 1
        # Check next row for data.
        data_present = Cell(row, 'A').value
    # Add column header.
    Cell(1, 'H').value = 'Score'
    return delegates

def vp_scores(sheet):
    """Compile list of VP scores."""
    active_sheet(sheet)
    delegates = []
    # Set data start row.
    row = 6
    # Loop through rows until empty row is found.
    data_present = True
    while data_present:
        # Append nested list to 'delegates' list containing delegate PIN and
        # score.
        delegates.append(CellRange((row, 'H'), (row, 'I')).value)
        row += 1
        # Check next row for data.
        data_present = Cell(row, 'A').value
    return delegates

def scoreboard():
    """Calculate and compile combined delegate scores."""
    active_sheet('scores')
    # Read delegate list from sheet.
    delegates = CellRange((2, 'A'), (192, 'A')).value
    totals = []
    i = 0
    print 'BEGUN'
    # Add delegate scores from each sheet.
    for delegate in delegates:
        # Initialise delegate total score.
        total = 0
        # If there's data on the sheet, add sheet score to total. Say correct
        # answers given in second argument to 'say_scores'.
        if Cell('asthma', 1, "A").value:
            total = add_say(say_scores('asthma', [3, 1, 2]), delegate, total)
        if Cell('copd', 1, "A").value:
            total = add_say(say_scores('copd', [4, 1, 5]), delegate, total)
        if Cell('ipf', 1, "A").value:
            total = add_say(say_scores('ipf', [1, 4, 2]), delegate, total)
        if Cell('walkabout_1', 1, "A").value:
            total = add_say(say_scores('walkabout_1', [2, 2, 3]), delegate, total)
        if Cell('walkabout_2', 1, "A").value:
            total = add_say(say_scores('walkabout_2', [1]), delegate, total)
        if Cell('walkabout_4', 1, "A").value:
            total = add_say(say_scores('walkabout_4', [3]), delegate, total)
        if Cell('walkabout_7', 1, "A").value:
            total = add_say(say_scores('walkabout_7', [2]), delegate, total)
        if Cell('walkabout_12', 1, "A").value:
            total = add_say(say_scores('walkabout_12', [3]), delegate, total)
        if Cell('walkabout_13', 1, "A").value:
            total = add_say(say_scores('walkabout_13', [1]), delegate, total)
        if Cell('vp_1', 1, "A").value:
            total = add_vp(vp_scores('vp_1'), delegate, total)
        if Cell('vp_2', 1, "A").value:
            total = add_vp(vp_scores('vp_2'), delegate, total)
        if Cell('vp_3', 1, "A").value:
            total = add_vp(vp_scores('vp_3'), delegate, total)
        # Add delegate's total score to 'totals' list.
        totals.append(total)
        i += 1
        print i, 'PROCESSED'
    # Write 'totals' list to sheet.
    CellRange('scores', (2, 'E'), (192, 'E')).value = totals

def add_say(project, delegate, total):
    """Add delegate Say scores to total."""
    for pin, answers, score in project:
        if delegate == pin:
            total += score
            break
    return total

def add_vp(day, delegate, total):
    """Add delegate VP scores to total."""
    for pin, score in day:
        if pin:
            if delegate == int(pin):    # VP outputs 'pin' as a string.
                total += score
                break
    return total

scoreboard()

raw_input('COMPLETE')


text:
package jauter

import scala.collection.JavaConverters._
import org.scalatest._

class ReverseRoutingSpec extends FlatSpec with Matchers {
  import StringMethodRouter.router

  "A reverse router" should "handle method" in {
    router.path(Method.GET, "index") should be ("/articles")

    router.path(Method.GET,  "show", "id", "123") should be ("/articles/123")

    router.path(Method.GET,  "any") should be ("/any")
    router.path(Method.POST, "any") should be ("/any")
    router.path(Method.PUT,  "any") should be ("/any")
  }

  "A reverse router" should "handle empty params" in {
    router.path("index") should be ("/articles")
  }

  "A reverse router" should "handle map params" in {
    router.path("show", Map("id" -> 123).asJava) should be ("/articles/123")
  }

  "A reverse router" should "handle varargs" in {
    router.path("download", "*", "foo/bar.png") should be ("/download/foo/bar.png")
  }

  "A reverse router" should "return path with minimum number of params in the query" in {
    router.path("show", Map("id" -> 123, "format" -> "json").asJava) should be ("/articles/123/json")

    Seq("/articles/123/json?x=1&y=2", "/articles/123/json?y=2&x=1") should contain(
      router.path("show", Map("id" -> 123, "format" -> "json", "x" -> 1, "y" -> 2).asJava)
    )
  }

  "A reverse router" should "handle class" in {
    trait Action
    class Index extends Action
    class Show  extends Action

    val router = new MethodlessRouter[Object]
    val index  = new Index
    router.pattern("/articles",     index)
    router.pattern("/articles/:id", classOf[Show])

    router.path(index)          should be ("/articles")
    router.path(classOf[Index]) should be ("/articles")

    router.path(new Show)                   should be (null)
    router.path(classOf[Show], "id", "123") should be ("/articles/123")

    router.path(classOf[Action]) shouldNot be (null)
  }
}


text:
import unittest
import pinq

class queryable_concat_tests(unittest.TestCase):

    def setUp(self):
        self.queryable1 = pinq.as_queryable(range(1, 11))
        self.queryable2 = pinq.as_queryable(range(11, 21))

    def test_concat_list(self):
        self.assertEqual(list(self.queryable1.concat(
            [11, 12, 13])), list(range(1, 14)))

    def test_concat_queryable(self):
        self.assertEqual(list(self.queryable1.concat(
            self.queryable2)), list(range(1, 21)))

    def test_concat_other_type_error(self):
        self.assertRaises(TypeError, self.queryable1.concat, 100)


text:
using System;
using EasyNetQ;
using Nancy;
using StartupApp.Models;

namespace StartupApp.Modules
{
    public class HomeModule : NancyModule
    {
        public HomeModule()
        {
            Get["/", true] = async (x, ct) =>
            {
                var model = new Result();
                try
                {
                    using (var myBus = RabbitHutch.CreateBus("host=rabbitmq"))
                    {
                        if (myBus.IsConnected)
                        {
                            model.RabbitMqState = TestState.Successful;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    model.RabbitMqState = TestState.Failed;
                }

                return View["Home", model];

            };
        }
    }
}


text:
module Google
  module Cloud
    module SecurityCenter
      module V1
        # File information about the related binary/library used by an executable, or
        # the script used by a script interpreter
        # @!attribute [rw] path
        #   @return [::String]
        #     Absolute path of the file as a JSON encoded string.
        # @!attribute [rw] size
        #   @return [::Integer]
        #     Size of the file in bytes.
        # @!attribute [rw] sha256
        #   @return [::String]
        #     SHA256 hash of the first hashed_size bytes of the file encoded as a
        #     hex string.  If hashed_size == size, sha256 represents the SHA256 hash
        #     of the entire file.
        # @!attribute [rw] hashed_size
        #   @return [::Integer]
        #     The length in bytes of the file prefix that was hashed.  If
        #     hashed_size == size, any hashes reported represent the entire
        #     file.
        # @!attribute [rw] partially_hashed
        #   @return [::Boolean]
        #     True when the hash covers only a prefix of the file.
        # @!attribute [rw] contents
        #   @return [::String]
        #     Prefix of the file contents as a JSON encoded string.
        #     (Currently only populated for Malicious Script Executed findings.)
        class File
          include ::Google::Protobuf::MessageExts
          extend ::Google::Protobuf::MessageExts::ClassMethods
        end
      end
    end
  end
end


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace L3E\ConsolidadosBundle\EntityRepository;

use Doctrine\ORM\EntityRepository;
/**
 * Description of CursoRepository
 *
 * @author sistemas1
 */
class CursoRepository extends EntityRepository
{
    /**
     *
     * @param type $id_paquete
     * @return type
     */
    public function asignaturasPorPeriodo($id_paquete)
    {
        $sql = "SELECT * FROM asignaturaxexamen axe INNER JOIN asignatura asi "
                . "ON axe.asigidn = asi.asigidn"
                . " WHERE axe.examidn IN ("
                . "SELECT cal.examidn FROM calificacion cal WHERE cal.cal_caliidn = :id_paquete)";
        $resultset = $this->getEntityManager()->getConnection()
                ->prepare($sql);
        $resultset->bindValue('id_paquete', $id_paquete);
        $resultset->execute();
        return $resultset->fetchAll();
    }

    /**
     *
     * @param type $paquete_curso
     * @return type
     */
    public function paquetesPorCurso($paquete_curso)
    {
        $sql = "SELECT caliidn, examnombrev, cal_caliidn, examen_examidn, caliestadon, califechad, calipremarcan "
                . "FROM v_calificacion WHERE cal_caliidn = :paquete_curso";
        $resultset = $this->getEntityManager()->getConnection()
                ->prepare($sql);
        $resultset->bindValue('paquete_curso', $paquete_curso);
        $resultset->execute();
        return $resultset->fetchAll();
    }
}