text:
import { ElementRef, Renderer, EventEmitter, DynamicComponentLoader, KeyValueDiffers, OnInit, OnDestroy, DoCheck } from 'angular2/core';
export interface NgGridConfig {
    margins?: number[];
    draggable?: boolean;
    resizable?: boolean;
    max_cols?: number;
    max_rows?: number;
    visible_cols?: number;
    visible_rows?: number;
    min_cols?: number;
    min_rows?: number;
    col_width?: number;
    row_height?: number;
    cascade?: string;
    min_width?: number;
    min_height?: number;
    fix_to_grid?: boolean;
    auto_style?: boolean;
    auto_resize?: boolean;
}
export declare class NgGrid implements OnInit, DoCheck, OnDestroy {
    private _differs;
    private _ngEl;
    private _renderer;
    private _loader;
    dragStart: EventEmitter<any>;
    drag: EventEmitter<any>;
    dragStop: EventEmitter<any>;
    resizeStart: EventEmitter<any>;
    resize: EventEmitter<any>;
    resizeStop: EventEmitter<any>;
    colWidth: number;
    rowHeight: number;
    minCols: number;
    minRows: number;
    marginTop: number;
    marginRight: number;
    marginBottom: number;
    marginLeft: number;
    isDragging: boolean;
    isResizing: boolean;
    autoStyle: boolean;
    resizeEnable: boolean;
    dragEnable: boolean;
    cascade: string;
    private _items;
    private _draggingItem;
    private _resizingItem;
    private _resizeDirection;
    private _itemGrid;
    private _containerWidth;
    private _containerHeight;
    private _maxCols;
    private _maxRows;
    private _visibleCols;
    private _visibleRows;
    private _minWidth;
    private _minHeight;
    private _setWidth;
    private _setHeight;
    private _posOffset;
    private _adding;
    private _placeholderRef;
    private _fixToGrid;
    private _autoResize;
    private _differ;
    private _destroyed;
    private static CONST_DEFAULT_CONFIG;
    private _config;
    config: NgGridConfig;
    constructor(_differs: KeyValueDiffers, _ngEl: ElementRef, _renderer: Renderer, _loader: DynamicComponentLoader);
    ngOnInit(): void;
    ngOnDestroy(): void;
    setConfig(config: NgGridConfig): void;
    getItemPosition(index: number): {
        col: number;
        row: number;
    };
    getItemSize(index: number): {
        x: number;
        y: number;
    };
    ngDoCheck(): boolean;
    setMargins(margins: Array<string>): void;
    enableDrag(): void;
    disableDrag(): void;
    enableResize(): void;
    disableResize(): void;
    addItem(ngItem: NgGridItem): void;
    removeItem(ngItem: NgGridItem): void;
    triggerCascade(): void;
    private _onResize(e);
    private _applyChanges(changes);
    private _onMouseDown(e);
    private _resizeStart(e);
    private _dragStart(e);
    private _onMouseMove(e);
    private _drag(e);
    private _resize(e);
    private _onMouseUp(e);
    private _dragStop(e);
    private _resizeStop(e);
    private _maxGridSize(w, h);
    private _calculateGridSize(width, height);
    private _calculateGridPosition(left, top);
    private _hasGridCollision(pos, dims);
    private _getCollisions(pos, dims);
    private _fixGridCollisions(pos, dims);
    private _cascadeGrid(pos?, dims?);
    private _fixGridPosition(pos, dims);
    private _isWithinBoundsX(pos, dims);
    private _isWithinBoundsY(pos, dims);
    private _isWithinBounds(pos, dims);
    private _addToGrid(item);
    private _removeFromGrid(item);
    private _updateSize(col?, row?);
    private _filterGrid();
    private _getMaxRow();
    private _getMaxCol();
    private _getMousePosition(e);
    private _getAbsoluteMousePosition(e);
    private _getItemFromPosition(position);
    private _createPlaceholder(pos, dims);
}
export interface NgGridItemConfig {
    col?: number;
    row?: number;
    sizex?: number;
    sizey?: number;
    dragHandle?: string;
    resizeHandle?: string;
    fixed?: boolean;
    draggable?: boolean;
    resizable?: boolean;
    borderSize?: number;
}
export interface NgGridItemEvent {
    col: number;
    row: number;
    sizex: number;
    sizey: number;
    width: number;
    height: number;
    left: number;
    top: number;
}
export declare class NgGridItem implements OnInit, OnDestroy {
    private _ngEl;
    private _renderer;
    private _ngGrid;
    itemChange: EventEmitter<NgGridItemEvent>;
    dragStart: EventEmitter<NgGridItemEvent>;
    drag: EventEmitter<NgGridItemEvent>;
    dragStop: EventEmitter<NgGridItemEvent>;
    resizeStart: EventEmitter<NgGridItemEvent>;
    resize: EventEmitter<NgGridItemEvent>;
    resizeStop: EventEmitter<NgGridItemEvent>;
    private static CONST_DEFAULT_CONFIG;
    gridPosition: {
        'col': number;
        'row': number;
    };
    gridSize: {
        'x': number;
        'y': number;
    };
    isFixed: boolean;
    isDraggable: boolean;
    isResizable: boolean;
    private _col;
    private _row;
    private _sizex;
    private _sizey;
    private _config;
    private _dragHandle;
    private _resizeHandle;
    private _borderSize;
    private _elemWidth;
    private _elemHeight;
    private _elemLeft;
    private _elemTop;
    private _added;
    config: NgGridItemConfig;
    constructor(_ngEl: ElementRef, _renderer: Renderer, _ngGrid: NgGrid);
    ngOnInit(): void;
    canDrag(e: any): boolean;
    canResize(e: any): string;
    onMouseMove(e: any): void;
    ngOnDestroy(): void;
    getElement(): ElementRef;
    getDragHandle(): string;
    getResizeHandle(): string;
    getDimensions(): {
        width: number;
        height: number;
    };
    getSize(): {
        x: number;
        y: number;
    };
    getPosition(): {
        left: number;
        top: number;
    };
    getGridPosition(): {
        col: number;
        row: number;
    };
    setConfig(config: NgGridItemConfig): void;
    setSize(x: number, y: number): void;
    setGridPosition(col: number, row: number): void;
    getEventOutput(): NgGridItemEvent;
    setPosition(x: number, y: number): void;
    setDimensions(w: number, h: number): void;
    startMoving(): void;
    stopMoving(): void;
    recalculateSelf(): void;
    private _recalculatePosition();
    private _recalculateDimensions();
    private _getMousePosition(e);
}
export declare class NgGridPlaceholder implements OnInit {
    private _ngEl;
    private _renderer;
    private _ngGrid;
    private _sizex;
    private _sizey;
    private _col;
    private _row;
    constructor(_ngEl: ElementRef, _renderer: Renderer, _ngGrid: NgGrid);
    ngOnInit(): void;
    setSize(x: number, y: number): void;
    setGridPosition(col: number, row: number): void;
    private _setPosition(x, y);
    private _setDimensions(w, h);
    private _recalculatePosition();
    private _recalculateDimensions();
}


text:
module Slack::Message
  def send_goal_announcement(goal, new_goal)
    client = Slack::Web::Client.new(token: goal.kudos_meter.team.slack_bot_access_token)

    current_goal_message = ":tada: We've just reached goal '#{goal.name}' at #{goal.amount} Kudos :tada:"
    blocks = [create_markdown_block(current_goal_message)]

    next_goal_message = "Our next goal is '#{new_goal.name}' at #{new_goal.amount} Kudos, " +
        "so keep the Kudos coming and we'll be there in no time! :muscle:"

    blocks << create_markdown_block(next_goal_message)

    client.chat_postMessage(channel: goal.kudos_meter.team.channel_id, blocks: blocks)
  end

  def send_post_announcement(post)
    client = Slack::Web::Client.new(token: post.team.slack_bot_access_token)

    sender_string = post.sender.slack_id == nil ? "#{post.sender.name}" : "<@#{post.sender.slack_id}>"

    message = "#{sender_string} just gave #{post.amount} kudos to #{get_post_receivers(post)} for #{post.message}"
    blocks = [create_markdown_block(message)]

    post.images.each do |image|
      blocks << create_markdown_image_block(Rails.application.routes.url_helpers.rails_blob_url(image, only_path: false));
    end

    blocks << create_post_subscript(post.id)

    client.chat_postMessage(channel: post.team.channel_id, blocks: blocks)
  end

  def list_guidelines(slack_team_id)
    team = find_team(slack_team_id)

    guidelines = Guideline.where(:team => team).order(:kudos)

    if guidelines.none?
      return [create_markdown_block("No guidelines")]
    else
      return [create_markdown_block(guidelines_to_list(guidelines))]
    end
  end

  private

  def send_ephemeral_message(team, channel, user, message)
    client = Slack::Web::Client.new(token: team.slack_bot_access_token)

    client.chat_postEphemeral(channel: channel, user: user, text: message)
  end

  def create_message(slack_client, slack_message)
    message = "saying: '#{slack_message['text']}'"
    mentioned_users = message.scan(/(?=<).*?(?<=>)/)

    mentioned_users.each do |mentioned_user|
      user_info = slack_client.users_info(user: mentioned_user.tr('<>@', ''))
      message[mentioned_user] = user_info['user']['name']
    end

    message
  end

  def update_message_to_post(channel_id, message, post)
    user = User.find_by_slack_id(message[:user])
    client = Slack::Web::Client.new(token: user.slack_access_token)

    blocks = [create_markdown_block(message[:text])]
    blocks << create_post_subscript(post.id)

    client.chat_update(channel: channel_id, ts: message[:ts], blocks: blocks)
  end

  def send_welcome_message(team)
    client = Slack::Web::Client.new(token: team.slack_bot_access_token)

    client.chat_postMessage(channel: team.channel_id, text: "Is it a bird? is it a plane? It's Kudo-O-Matic!")
  end

  def create_markdown_block(text)
    {
        type: "section",
        text: {
            type: "mrkdwn",
            text: text
        }
    }
  end

  def create_markdown_image_block(url)
    {
        type: "image",
        alt_text: "Kudo-o-matic afbeelding",
        image_url: url
    }
  end

  def message_is_kudo_o_matic_post?(message)
    return false unless message['blocks']

    last_block = message['blocks'].last

    Post.exists?(id: last_block['block_id'])
  end

  def create_post_subscript(post_id)
    {
        type: 'context',
        block_id: post_id.to_s,
        elements: [
            type: 'mrkdwn',
            text: '_This message is a Kudo-O-Matic post_'
        ]
    }
  end

  def get_post_receivers(post)
    receiver_string = ""
    post.receivers.each_with_index do |receiver, index|
      receiver_string += receiver.slack_id == nil ? "#{receiver.name}" : "<@#{receiver.slack_id}>"

      if post.receivers.count > 1 && index != post.receivers.count - 1
        receiver_string += (index == (post.receivers.count - 2)) ? ' and ' : ', '
      end
    end

    receiver_string
  end

end

redpajama_set_name: RedPajamaGithub


text:
var QUOTES = [
    ['I like school and fighting with my sister Aubrielle Carlino ', 'Maddox Carlino'],
    ['I love math, reading, and of course piano!', 'Aubrielle Carlino'],
    ['Life is about making an impact, not making an income.', 'Kevin Kruse'],
    ['Whatever the mind of man can conceive and believe, it can achieve.', 'Napoleon Hill'],
    ['Strive not to be a success, but rather to be of value.', 'Albert Einstein'],
    ['Two roads diverged in a wood, and I—I took the one less traveled by, And that has made all the difference.', 'Robert Frost'],
    ['I attribute my success to this: I never gave or took any excuse.', 'Florence Nightingale'],
    ['You miss 100% of the shots you don't take.', 'Wayne Gretzky'],
    ['I\'ve missed more than 9000 shots in my career. I\'ve lost almost 300 games. 26 times I\'ve been trusted to take the game winning shot and missed. I\'ve failed over and over and over again in my life. And that is why I succeed.', 'Michael Jordan'],
    ['The most difficult thing is the decision to act, the rest is merely tenacity.', 'Amelia Earhart'],
    ['Every strike brings me closer to the next home run.', 'Babe Ruth'],
    ['Definiteness of purpose is the starting point of all achievement.', 'W. Clement Stone'],
    ['Life isn\'t about getting and having, it\'s about giving and being.', 'Kevin Kruse'],
    ['Life is what happens to you while you're busy making other plans.', 'John Lennon'],
    ['We become what we think about.', 'Earl Nightingale'],
    ['Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do, so throw off the bowlines, sail away from safe harbor, catch the trade winds in your sails.  Explore, Dream, Discover.', 'Mark Twain'],
    ['Life is 10% what happens to me and 90% of how I react to it.', 'Charles Swindoll']
]

function rand_num(min, max) {
  return Math.floor(Math.random() * (max-min)) + min;
}

function get_quote() {
  var quote_i = rand_num(0, QUOTES.length);
  return ['"' + QUOTES[quote_i][0] + '"

~' + QUOTES[quote_i][1] + '~', quote_i];
}

function build_twitter_params(index) {
  return 'https://twitter.com/intent/tweet?text=' + encodeURIComponent(QUOTES[index][0] + ' -' + QUOTES[index][1]);
}

$(document).ready(function() {
  var quote = get_quote()
  $('.quote-box p').html(quote[0]);
  $('.quote-box a').attr('href', build_twitter_params(quote[1]));
  $('.quote-box button').click(function() {
    var quote = get_quote();
    $('.quote-box p').fadeOut('slow', function() {
      $('.quote-box p').html(quote[0]).fadeIn('slow');
      $('.quote-box a').attr('href', build_twitter_params(quote[1]));
    });
  });
});


text:
import java.util.*;

public class Renovation
{
    public Renovation (boolean debug)
    {
        _debug = debug;
    }

    public Vector<Coordinate> getBlackTiles (Vector<String> lines)
    {
        Vector<Coordinate> blackTiles = new Vector<Coordinate>();

        for (int i = 0; i < lines.size(); i++)
        {
            Coordinate coord = tilePosition(lines.elementAt(i));

            if (!blackTiles.contains(coord))
                blackTiles.add(coord);
            else
                blackTiles.remove(coord);
        }

        return blackTiles;
    }

    private Coordinate tilePosition (String line)
    {
        Coordinate coord = new Coordinate(0, 0);
        int index = 0;
        String remainder = line;

        while (index < line.length())
        {
            int directionSize = 2;

            if ((remainder.startsWith(Directions.EAST)) || (remainder.startsWith(Directions.WEST)))
                directionSize = 1;

            String direction = remainder.substring(0, directionSize);

            remainder = remainder.substring(directionSize);
            index += directionSize;

            if (_debug)
            {
                System.out.println("Direction: "+direction);
                System.out.println("Remainder: "+remainder);
            }

            coord = Directions.getCoordinate(direction, coord);
        }

        return coord;
    }

    private boolean _debug;
}


text:
import numpy as np

class WindSpeedFromUV():

    def __init__(self):
        self.name = "Wind Speed Function"
        self.description = "This function computes wind Speed given u/v components of wind."

    def getParameterInfo(self):
        return [
            {
                'name': 'u',
                'dataType': 'raster',
                'value': None,
                'required': True,
                'displayName': "U component of wind Raster",
                'description': "A single-band raster where pixel values represent the u component of wind in metres per second."
            },
            {
                'name': 'v',
                'dataType': 'raster',
                'value': None,
                'required': True,
                'displayName': "V component of wind Raster",
                'description': "A single-band raster where pixel values represent the v component of wind in metres per second."
            },
        ]

    def getConfiguration(self, **scalars):
        return {
          'inheritProperties': 4 | 8,               # inherit all but the pixel type and NoData from the input raster
          'invalidateProperties': 2 | 4 | 8,        # invalidate statistics & histogram on the parent dataset because we modify pixel values.
          'inputMask': False                        # Don't need input raster mask in .updatePixels(). Simply use the inherited NoData.
        }

    def updateRasterInfo(self, **kwargs):
        kwargs['output_info']['bandCount'] = 1      # output is a single band raster
        kwargs['output_info']['statistics'] = ({'minimum': 0, 'maximum': 150}, )
        kwargs['output_info']['histogram'] = ()     # we know nothing about the histogram of the outgoing raster.
        kwargs['output_info']['pixelType'] = 'f4'
        return kwargs

    def updatePixels(self, tlc, size, props, **pixelBlocks):
        u = np.array(pixelBlocks['u_pixels'], dtype='f4')
        v = np.array(pixelBlocks['v_pixels'], dtype='f4')

        outBlock = np.sqrt(np.square(u) + np.square(v))
        pixelBlocks['output_pixels'] = outBlock.astype(props['pixelType'])
        return pixelBlocks

    def updateKeyMetadata(self, names, bandIndex, **keyMetadata):
        if bandIndex == -1:
            keyMetadata['datatype'] = 'Scientific'
            keyMetadata['datatype'] = 'WindSpeed'
        elif bandIndex == 0:
            keyMetadata['wavelengthmin'] = None     # reset inapplicable band-specific key metadata
            keyMetadata['wavelengthmax'] = None
            keyMetadata['bandname'] = 'WindSpeed'
        return keyMetadata


text:
import { Angulartics2 } from '../../core/angulartics2';
export declare class Angulartics2BaiduAnalytics {
    private angulartics2;
    constructor(angulartics2: Angulartics2);
    pageTrack(path: string): void;
    eventTrack(action: string, properties: any): void;
    setUsername(userId: string): void;
    setUserProperties(properties: any): void;
}


text:
from app.tests.test_app import AAFoodTestCase
from app.models import db, Term, Category, Termcategories, Photo
class ModelTestCase(AAFoodTestCase):

    def test_categories(self):

        for x in Category.query.all():
            print(x.name, x.parent)

        term = Term.query.filter_by(english="pikachu", chinese="皮卡丘").first()
        print(term)

        print(list(map(lambda x: x.name, term.categories.all())))
        print(list(map(lambda x: x.content, term.descriptions.all())))
        print(list(map(lambda x: x.as_dict(), term.photos.all())))


text:
package com.lightcrafts.ui.editor;

import com.lightcrafts.ui.operation.OpStack;

import javax.swing.*;
import java.awt.*;

/**
 * The top-level layout container for the Editor tools area.
 */
class ToolsContainer extends JPanel {

    ToolsContainer(OpStack stack) {
        super(new BorderLayout());
        OpsToolbar toolbar = new OpsToolbar(stack);
        add(toolbar, BorderLayout.NORTH);
        add(new OpsScroll(stack));
    }

    ToolsContainer() {
        super(new BorderLayout());
        OpsToolbar toolbar = new OpsToolbar();
        add(toolbar, BorderLayout.NORTH);
    }
}


text:
import select
import socket

from .logger import log

class SelectError(Exception):
	def __init__(self, message=None, abort_loop=False, bad_fds=None):
		Exception.__init__(self, message)
		self.abort_loop = abort_loop
		self.bad_fds = bad_fds

class SelectCall:
	'wraps calls to select'

	def __init__(self):
		pass

	def execute(self, in_list, out_list):
		readable = writeable = exceptions = None

		try:
			readable, writeable, exceptions = select.select(in_list, out_list, in_list + out_list)

		except TypeError as e:
			log.error(str(e))
			raise SelectError(abort_loop=True)

		except socket.error as e:
			log.error('select socket error\n' + str(e))

			bad_fds = []
			for fd in list(set(in_list + out_list)):
				try:
					fd.fileno()
				except socket.error:
					bad_fds.append(fd)

			raise SelectError(bad_fds=bad_fds)

		except ValueError as e:
			log.error(str(e))
			raise SelectError(abort_loop=True)

		return readable, writeable, exceptions


text:
class List
  attr_accessor :name, :body, :steps

  def initialize(file)
    fname = File.basename(file)
    @name = fname.sub(File.extname(fname), '')
    @body = File.read(file)
    @steps = parse_steps(@body)
    @current_step = 0
  end

  def header
    return if @body.lines.to_a.empty?
    if line = @body.lines.first.strip
      line if line =~ /#/
    end
  end

  def to_h
    {name: @name, steps: @steps.map(&:to_h)}
  end

  private

  def parse_steps(body)
    steps = []
    current_step = nil
    body.lines.each do |line|
      next if line.strip.empty?
      if line =~ /^-/
        current_name = line.sub(/^-/,'').strip
        current_step = Step.new(current_name)
        steps << current_step
      elsif current_step
        current_step.body << line
      end
    end
    steps
  end

  class Step
    attr_accessor :name, :body, :commands

    def initialize(name, body = '')
      @name = name
      @body = body
    end

    def commands
      @body.scan(/`([^`]+)`/).map do |match,_|
        match
      end
    end

    def to_h
      {name: @name, body: @body}
    end
  end
end


text:
package org.apache.pulsar.zookeeper;

import java.util.concurrent.ScheduledExecutorService;

import org.apache.bookkeeper.common.util.OrderedScheduler;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Per ZK client ZooKeeper cache supporting ZNode data and children list caches. A cache entry is identified, accessed
 * and invalidated by the ZNode path. For the data cache, ZNode data parsing is done at request time with the given
 * {@link Deserializer} argument.
 *
 * @param <T>
 */
public class LocalZooKeeperCache extends ZooKeeperCache {

    private static final Logger LOG = LoggerFactory.getLogger(LocalZooKeeperCache.class);

    public LocalZooKeeperCache(final ZooKeeper zk, final OrderedScheduler executor,
            ScheduledExecutorService scheduledExecutor) {
        super(zk, executor, scheduledExecutor);
    }

    @Override
    public <T> void process(WatchedEvent event, final CacheUpdater<T> updater) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Got Local ZooKeeper WatchedEvent: EventType: {}, KeeperState: {}, Path: {}", event.getType(),
                    event.getState(), event.getPath());
        }
        if (event.getType() == Event.EventType.None) {
            switch (event.getState()) {
            case Expired:
                // in case of expired, the zkSession is no longer good
                LOG.warn("Lost connection from local ZK. Invalidating the whole cache.");
                dataCache.synchronous().invalidateAll();
                childrenCache.invalidateAll();
                return;
            default:
                break;
            }
        }
        super.process(event, updater);
    }
}


text:
PBXAggregateTarget::~PBXAggregateTarget() {
}

PBXAggregateTarget::PBXAggregateTarget() {
}

PBXAggregateTarget* PBXAggregateTarget::createFromPlist(const String& id, const Plist::dictionary_type& plist, const PBXDocument* pbxDoc) {
    PBXAggregateTarget* ret = new PBXAggregateTarget;
    ret->initFromPlist(id, plist, pbxDoc);
    return ret;
}


text:
Sequel.migration do
  up do
    create_table :story_comments do
      primary_key :id
      Numeric :story_id
      String :content
      String :commentee
      DateTime :created_at
    end
  end

  down do
    drop_table :story_comments
  end
end


text:
package com.atteo.jello.klass;

import com.atteo.jello.index.Index;
import com.atteo.jello.schema.SchemaManager;

public interface KlassManager {
	public void addKlass(String klassName);

	public void commit();

	public void create();

	public int getIdFor(String klassName);

	public Index getIndexFor(String klassName);

	public SchemaManager getSchemaManagerFor(String klassName);

	public boolean isKlassManaged(String klassName);

	public boolean load();

	public void removeKlass(String klassName);
}


text:
jQuery Practice 00
==========

Simple Hot or Cold app
Using:
- jQuery
- Jade
- SCSS
- Yeoman/Grunt


text:
#include <cstdlib>
#include <iostream>
#include <unistd.h>

#include "sys/SystemInfo.h"

#include "trace/model/LogPersistThread.h"
#include "trace/model/LogSharedContainer.h"
#include "trace/backend/ILogBackEnd.h"

namespace
{
    /* Max time in ms to wait for the LogEntry */
    const uint32_t NEW_ENTRY_TIMEOUT_MS = 100U;

    /* Let the thread sleep a bit while reading */
    const uint32_t GET_ENTRIES_LOOP_SLEEP_US = 25U;
};

namespace trace
{
namespace model
{
LogPersistThread::LogPersistThread ( model::LogSharedContainer& traceContainer )
    : ::sys::AbstractThread( "LogPersistence" )
    , m_traceContainer( traceContainer )
    , m_backEnd( NULL )
    , m_entries()
{

}

void LogPersistThread::setBackEnd( backend::ILogBackEnd* backEnd )
{
    m_backEnd = backEnd;
}

void LogPersistThread::run()
{
    ::esys::TString63 backendRegistered;
    backendRegistered.c_format( "Backend '%s' registered", m_backEnd->getName().c_str() );

    m_backEnd->onRegister( ::sys::SystemInfo::getOwnProcessId() );
    m_backEnd->add( entry::LogEntry( LogLevel_Internal, backendRegistered.c_str() ) );

    bool assertion = false;
    size_t count = 0U;

    do
    {
        if ( m_traceContainer.waitForEntries( ::NEW_ENTRY_TIMEOUT_MS ) )
        {
            do
            {
                count = m_traceContainer.getEntries( m_entries, LOG_PERSIST_THREAD_CACHE );

                for ( size_t i = 0U; i < count; i++ )
                {
                    assertion = m_entries[ i ].isLevel( LogLevel_Assert );
                    m_backEnd->add( m_entries[ i ] );
                }

                /* Let the feeding thread in */
                sleepUs( ::GET_ENTRIES_LOOP_SLEEP_US );
            }
            while( count != 0U );
        }

        /* Exit the thread loop in case of ASSERT level entry */
        if ( assertion )
        {
            break;
        }
    }
    while ( !isStopRequested() );

    /* Add the closing entry and shutdown the LogBackEnd */
    m_backEnd->add( entry::LogEntry( LogLevel_Internal, "Shutdown the BackEnd" ) );
    m_backEnd->onShutdown();

    /* Here the LogBackEnd is switched off, all entries are expected to be persisted.
     * It is safe to call the AssertHandler. */
    if ( assertion )
    {
        abort();
    }
}

LogPersistThread::~LogPersistThread()
{

}
};
};


text:
%% PRT Classification Objects
% One of the most powerful features of the Pattern Recognition Toolbox is
% classification objects, implemented as <./functionReference/prtClass.html prtClass>
% objects. Classification objects allow you to develop algorithms which
% will label data into discrete clases. prtClass objects are all
% supervised, meaning they require labeled training data during training.
%
%% Classification object methods and properties.
% All prtClass objects inherit the TRAIN, RUN, CROSSVALIDATE and KFOLDS
% functions from the prtAction object, for more information on these
% methods, refer to section on the  <./prtDocEngine.html prtEngine>.
%
% In addition to the inherited methods, prtClass objects also have a few
% important properties. The isNativeMary field indicates whether or not the
% particular classifier natively handles binary and/or M-ary
% classification. Binary classifiers can only label data as being in class
% 0 or 1, whereas native M-ary classifiers can label data into an arbitrary
% number of classes.
%
%% Using classifiers
% You use classifiers in the same manner as any prtAction object. The
% following example shows how to create a generalized likelihood ratio
% classifier, and perform kfolds validation on it.

ds = prtDataGenUnimodal;   % Load a dataset to use
classifier = prtClassGlrt;  % Create a generalized likelihood ratio test
                           % classifier

result = classifier.kfolds(ds,2);% Perform a simple 2-fold cross-validation

result.getX(1:5)
result.getY(1:5)

%%
% Note that the data stored in the observations of result correspond to the
% likelihood values. Also note that since ds was a labeled dataset, the
% original labels are copied over into the targets property of the results
% dataset.

%% Internal Deciders
% Another important property of prtClass objects is the internalDecider.
% Ordinarily, a prtClass object outputs raw statistics based on the
% classification algorithm. However, you might just want the classification
% object to make class decisions based on these outputs. This can be done
% by setting the internalDecider property to be a prtDecisionBinaryMinPe
% object:

classifier.internalDecider = prtDecisionBinaryMinPe;
result = classifier.kfolds(ds,2); %Perform a simple 2-fold cross-validation

result.getX(1:5)
result.getY(1:5)

% Note that now the data stored in the observations of result are class
% labels. They are likely all of class 0 in this example. By setting the
% internalDecider to prtDecisionBinaryPe, an threshold was found during
% training that would result in the minimum probability of error.

%% Plotting
% Finally, prtClass objects all have an additional plot function, which can
% help you visulize the classifiers decision regions. To plot the
% classification object, it first needs to be trained.

classifier = classifier.train(ds);   % For example purposes,
                                     % train with all the data
classifier.plot();                   % Alternatively, plot(classifier)

%%
% In the resulting plot, you will see all the data members used to train
% the data. If the internalDecider is set, as in the above example, you
% will see the decision region boundaries. If the internalDecider is not
% set, you will instead see an intensity plot, indicating how likely it is
% that a particular point would belong to class 0 or 1, as shown below.

classifier.internalDecider = [];   % Clear the internalDecider
classifier = classifier.train(ds); % Re-train
classifier.plot()

%%
% All classification objects in the Pattern Recognition Toolbox have the
% same API as discussed above. The only difference is the underlying
% algorithms used to train and run the classifier. For a list of all the
% different classification algorithms, and links to their individual help
% entries, <./prtDocFunctionList.html A list of commonly used functions>


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

/**
 * @fileoverview Defines a class useful for handling functions that must be
 * invoked after a delay, especially when that delay is frequently restarted.
 * Examples include delaying before displaying a tooltip, menu hysteresis,
 * idle timers, etc.
 * @author brenneman@google.com (Shawn Brenneman)
 * @see ../demos/timers.html
 */

goog.provide('goog.Delay');
goog.provide('goog.async.Delay');

goog.require('goog.Disposable');
goog.require('goog.Timer');

/**
 * A Delay object invokes the associated function after a specified delay. The
 * interval duration can be specified once in the constructor, or can be defined
 * each time the delay is started. Calling start on an active delay will reset
 * the timer.
 *
 * @param {Function} listener Function to call when the delay completes.
 * @param {number=} opt_interval The default length of the invocation delay (in
 *     milliseconds).
 * @param {Object=} opt_handler The object scope to invoke the function in.
 * @constructor
 * @extends {goog.Disposable}
 * @final
 */
goog.async.Delay = function(listener, opt_interval, opt_handler) {
  goog.Disposable.call(this);

  /**
   * The function that will be invoked after a delay.
   * @type {Function}
   * @private
   */
  this.listener_ = listener;

  /**
   * The default amount of time to delay before invoking the callback.
   * @type {number}
   * @private
   */
  this.interval_ = opt_interval || 0;

  /**
   * The object context to invoke the callback in.
   * @type {Object|undefined}
   * @private
   */
  this.handler_ = opt_handler;

  /**
   * Cached callback function invoked when the delay finishes.
   * @type {Function}
   * @private
   */
  this.callback_ = goog.bind(this.doAction_, this);
};
goog.inherits(goog.async.Delay, goog.Disposable);

/**
 * A deprecated alias.
 * @deprecated Use goog.async.Delay instead.
 * @constructor
 * @final
 */
goog.Delay = goog.async.Delay;

/**
 * Identifier of the active delay timeout, or 0 when inactive.
 * @type {number}
 * @private
 */
goog.async.Delay.prototype.id_ = 0;

/**
 * Disposes of the object, cancelling the timeout if it is still outstanding and
 * removing all object references.
 * @override
 * @protected
 */
goog.async.Delay.prototype.disposeInternal = function() {
  goog.async.Delay.superClass_.disposeInternal.call(this);
  this.stop();
  delete this.listener_;
  delete this.handler_;
};

/**
 * Starts the delay timer. The provided listener function will be called after
 * the specified interval. Calling start on an active timer will reset the
 * delay interval.
 * @param {number=} opt_interval If specified, overrides the object's default
 *     interval with this one (in milliseconds).
 */
goog.async.Delay.prototype.start = function(opt_interval) {
  this.stop();
  this.id_ = goog.Timer.callOnce(
      this.callback_,
      goog.isDef(opt_interval) ? opt_interval : this.interval_);
};

/**
 * Stops the delay timer if it is active. No action is taken if the timer is not
 * in use.
 */
goog.async.Delay.prototype.stop = function() {
  if (this.isActive()) {
    goog.Timer.clear(this.id_);
  }
  this.id_ = 0;
};

/**
 * Fires delay's action even if timer has already gone off or has not been
 * started yet; guarantees action firing. Stops the delay timer.
 */
goog.async.Delay.prototype.fire = function() {
  this.stop();
  this.doAction_();
};

/**
 * Fires delay's action only if timer is currently active. Stops the delay
 * timer.
 */
goog.async.Delay.prototype.fireIfActive = function() {
  if (this.isActive()) {
    this.fire();
  }
};

/**
 * @return {boolean} True if the delay is currently active, false otherwise.
 */
goog.async.Delay.prototype.isActive = function() {
  return this.id_ != 0;
};

/**
 * Invokes the callback function after the delay successfully completes.
 * @private
 */
goog.async.Delay.prototype.doAction_ = function() {
  this.id_ = 0;
  if (this.listener_) {
    this.listener_.call(this.handler_);
  }
};


text:
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const vscode = require("vscode");
const types_1 = require("../common/types");
const proxy = require("./jediProxy");
const providerUtilities_1 = require("./providerUtilities");
class DocumentPosition {
    constructor(document, position) {
        this.document = document;
        this.position = position;
    }
    static fromObject(item) {
        // tslint:disable-next-line:no-any
        return item._documentPosition;
    }
    attachTo(item) {
        // tslint:disable-next-line:no-any
        item._documentPosition = this;
    }
}
class CompletionSource {
    constructor(jediFactory, serviceContainer, itemInfoSource) {
        this.serviceContainer = serviceContainer;
        this.itemInfoSource = itemInfoSource;
        this.jediFactory = jediFactory;
    }
    getVsCodeCompletionItems(document, position, token) {
        return __awaiter(this, void 0, void 0, function* () {
            const result = yield this.getCompletionResult(document, position, token);
            if (result === undefined) {
                return Promise.resolve([]);
            }
            return this.toVsCodeCompletions(new DocumentPosition(document, position), result, document.uri);
        });
    }
    getDocumentation(completionItem, token) {
        return __awaiter(this, void 0, void 0, function* () {
            const documentPosition = DocumentPosition.fromObject(completionItem);
            if (documentPosition === undefined) {
                return;
            }
            // Supply hover source with simulated document text where item in question was 'already typed'.
            const document = documentPosition.document;
            const position = documentPosition.position;
            const wordRange = document.getWordRangeAtPosition(position);
            const leadingRange = wordRange !== undefined
                ? new vscode.Range(new vscode.Position(0, 0), wordRange.start)
                : new vscode.Range(new vscode.Position(0, 0), position);
            const itemString = completionItem.label;
            const sourceText = `${document.getText(leadingRange)}${itemString}`;
            const range = new vscode.Range(leadingRange.end, leadingRange.end.translate(0, itemString.length));
            return this.itemInfoSource.getItemInfoFromText(document.uri, document.fileName, range, sourceText, token);
        });
    }
    getCompletionResult(document, position, token) {
        return __awaiter(this, void 0, void 0, function* () {
            if (position.character <= 0 ||
                providerUtilities_1.isPositionInsideStringOrComment(document, position)) {
                return undefined;
            }
            const type = proxy.CommandType.Completions;
            const columnIndex = position.character;
            const source = document.getText();
            const cmd = {
                command: type,
                fileName: document.fileName,
                columnIndex: columnIndex,
                lineIndex: position.line,
                source: source
            };
            return this.jediFactory.getJediProxyHandler(document.uri).sendCommand(cmd, token);
        });
    }
    toVsCodeCompletions(documentPosition, data, resource) {
        return data && data.items.length > 0 ? data.items.map(item => this.toVsCodeCompletion(documentPosition, item, resource)) : [];
    }
    toVsCodeCompletion(documentPosition, item, resource) {
        const completionItem = new vscode.CompletionItem(item.text);
        completionItem.kind = item.type;
        const configurationService = this.serviceContainer.get(types_1.IConfigurationService);
        const pythonSettings = configurationService.getSettings(resource);
        if (pythonSettings.autoComplete.addBrackets === true &&
            (item.kind === vscode.SymbolKind.Function || item.kind === vscode.SymbolKind.Method)) {
            completionItem.insertText = new vscode.SnippetString(item.text).appendText('(').appendTabstop().appendText(')');
        }
        // Ensure the built in members are at the bottom.
        completionItem.sortText = (completionItem.label.startsWith('__') ? 'z' : (completionItem.label.startsWith('_') ? 'y' : '__')) + completionItem.label;
        documentPosition.attachTo(completionItem);
        return completionItem;
    }
}
exports.CompletionSource = CompletionSource;
//# sourceMappingURL=completionSource.js.map


text:
void apply_op(level_type * level, int Ax_id, int x_id, double a, double b){  // y=Ax
  // exchange the boundary of x in preparation for Ax
  exchange_boundary(level,x_id,stencil_is_star_shaped());
          apply_BCs(level,x_id);

  // now do Ax proper...
  uint64_t _timeStart = CycleTime();
  int box;

  PRAGMA_THREAD_ACROSS_BOXES(level,box)
  for(box=0;box<level->num_my_boxes;box++){
    int i,j,k;
    const int jStride = level->my_boxes[box].jStride;
    const int kStride = level->my_boxes[box].kStride;
    const int  ghosts = level->my_boxes[box].ghosts;
    const int     dim = level->my_boxes[box].dim;
    const double h2inv = 1.0/(level->h*level->h);
    const double * __restrict__ x      = level->my_boxes[box].vectors[         x_id] + ghosts*(1+jStride+kStride); // i.e. [0] = first non ghost zone point
          double * __restrict__ Ax     = level->my_boxes[box].vectors[        Ax_id] + ghosts*(1+jStride+kStride);
    const double * __restrict__ alpha  = level->my_boxes[box].vectors[VECTOR_ALPHA ] + ghosts*(1+jStride+kStride);
    const double * __restrict__ beta_i = level->my_boxes[box].vectors[VECTOR_BETA_I] + ghosts*(1+jStride+kStride);
    const double * __restrict__ beta_j = level->my_boxes[box].vectors[VECTOR_BETA_J] + ghosts*(1+jStride+kStride);
    const double * __restrict__ beta_k = level->my_boxes[box].vectors[VECTOR_BETA_K] + ghosts*(1+jStride+kStride);
    const double * __restrict__  valid = level->my_boxes[box].vectors[VECTOR_VALID ] + ghosts*(1+jStride+kStride);

    PRAGMA_THREAD_WITHIN_A_BOX(level,i,j,k)
    for(k=0;k<dim;k++){
    for(j=0;j<dim;j++){
    for(i=0;i<dim;i++){
      int ijk = i + j*jStride + k*kStride;
      Ax[ijk] = apply_op_ijk(x);
    }}}
  }
  level->cycles.apply_op += (uint64_t)(CycleTime()-_timeStart);
}
//------------------------------------------------------------------------------------------------------------------------------


text:
require "spec_helper"

describe Doorkeeper::AccessGrant do
  let(:client) { FactoryBot.build_stubbed(:application) }
  let(:clazz) { Doorkeeper::AccessGrant }

  subject { FactoryBot.build(:access_grant, application: client) }

  it { expect(subject).to be_valid }

  it_behaves_like "an accessible token"
  it_behaves_like "a revocable token"
  it_behaves_like "a unique token" do
    let(:factory_name) { :access_grant }
  end

  context "with hashing enabled" do
    let(:grant) { FactoryBot.create :access_grant }
    include_context "with token hashing enabled"

    it "holds a volatile plaintext token when created" do
      expect(grant.plaintext_token).to be_a(String)
      expect(grant.token)
        .to eq(hashed_or_plain_token_func.call(grant.plaintext_token))

      # Finder method only finds the hashed token
      loaded = clazz.find_by(token: grant.token)
      expect(loaded).to eq(grant)
      expect(loaded.plaintext_token).to be_nil
      expect(loaded.token).to eq(grant.token)
    end

    it "does not find_by plain text tokens" do
      expect(clazz.find_by(token: grant.plaintext_token)).to be_nil
    end

    describe "with having a plain text token" do
      let(:plain_text_token) { "plain text token" }

      before do
        # Assume we have a plain text token from before activating the option
        grant.update_column(:token, plain_text_token)
      end

      context "without fallback lookup" do
        it "does not provide lookups with either through by_token" do
          expect(clazz.by_token(plain_text_token)).to eq(nil)
          expect(clazz.by_token(grant.token)).to eq(nil)

          # And it does not touch the token
          grant.reload
          expect(grant.token).to eq(plain_text_token)
        end
      end

      context "with fallback lookup" do
        include_context "with token hashing and fallback lookup enabled"

        it "upgrades a plain token when falling back to it" do
          # Side-effect: This will automatically upgrade the token
          expect(clazz).to receive(:upgrade_fallback_value).and_call_original
          expect(clazz.by_token(plain_text_token)).to eq(grant)

          # Will find subsequently by hashing the token
          expect(clazz.by_token(plain_text_token)).to eq(grant)

          # And it modifies the token value
          grant.reload
          expect(grant.token).not_to eq(plain_text_token)
          expect(clazz.find_by(token: plain_text_token)).to eq(nil)
          expect(clazz.find_by(token: grant.token)).not_to be_nil
        end
      end
    end
  end

  describe "validations" do
    it "is invalid without resource_owner_id" do
      subject.resource_owner_id = nil
      expect(subject).not_to be_valid
    end

    it "is invalid without application_id" do
      subject.application_id = nil
      expect(subject).not_to be_valid
    end

    it "is invalid without token" do
      subject.save
      subject.token = nil
      expect(subject).not_to be_valid
    end

    it "is invalid without expires_in" do
      subject.expires_in = nil
      expect(subject).not_to be_valid
    end
  end

  describe ".revoke_all_for" do
    let(:resource_owner) { double(id: 100) }
    let(:application) { FactoryBot.create :application }
    let(:default_attributes) do
      {
        application: application,
        resource_owner_id: resource_owner.id,
      }
    end

    it "revokes all tokens for given application and resource owner" do
      FactoryBot.create :access_grant, default_attributes

      described_class.revoke_all_for(application.id, resource_owner)

      described_class.all.each do |token|
        expect(token).to be_revoked
      end
    end

    it "matches application" do
      access_grant_for_different_app = FactoryBot.create(
        :access_grant,
        default_attributes.merge(application: FactoryBot.create(:application))
      )

      described_class.revoke_all_for(application.id, resource_owner)

      expect(access_grant_for_different_app.reload).not_to be_revoked
    end

    it "matches resource owner" do
      access_grant_for_different_owner = FactoryBot.create(
        :access_grant,
        default_attributes.merge(resource_owner_id: 90)
      )

      described_class.revoke_all_for application.id, resource_owner

      expect(access_grant_for_different_owner.reload).not_to be_revoked
    end
  end
end


text:
#include "limit.h"
#include "graph.h"

struct BasicEdge
{
	int u,v;
};

struct BasicSnapshot{
   BasicEdge* edges;//remain edges
   int* index;//indexs
};

class BasicStaticGreedy
{
	static int n,m,top;
	static int size;
	static int set[SET_SIZE];
	//static Edge edges[MAX_EDGE];
	static Edge myEdges[MAX_EDGE];
	static int index[MAX_NODE];
	static double average_norelate[MAX_NODE];

	//static int Check();
	//static void Generate();
	static void qsort_edges(int h, int t);

public:
	static double d[MAX_NODE];
	static int list[MAX_NODE];
	static void Build();
	//static int CheckSet(int s, int *arr);
	//static int* GetSeedsFromUGraphForUIC(int R, int k);
	static void GenerateSnapshot(BasicSnapshot* snapshots, int R);
	static int* GetSeeds(int R, int k);
	static double GetInfluenceSpreadFromSnapshot(int R, int k, int* set, BasicSnapshot* snapshots);
	//static double AveSize(int i);
};

#endif


text:
use strict;
use Data::Dumper;
use Carp;

#
# This is a SAS Component
#

=head1 NAME

all_entities_Reaction

=head1 SYNOPSIS

all_entities_Reaction [-a] [--fields fieldlist] > entity-data

=head1 DESCRIPTION

Return all instances of the Reaction entity.

A reaction is a chemical process that converts one set of
compounds (substrate) to another set (products).

Example:

    all_entities_Reaction -a

would retrieve all entities of type Reaction and include all fields
in the entities in the output.

=head2 Related entities

The Reaction entity has the following relationship links:

=over 4

=item Involves LocalizedCompound

=item IsDisplayedOn Diagram

=item IsExecutedAs ReactionInstance

=item IsStepOf Complex

=item ParticipatesIn Scenario

=item UsesAliasForReaction Source

=back

=head1 COMMAND-LINE OPTIONS

Usage: all_entities_Reaction [arguments] > entity.data

    --fields list   Choose a set of fields to return. List is a comma-separated list of strings.
    -a		    Return all available fields.
    --show-fields   List the available fields.

The following fields are available:

=over 4

=item mod_date

date and time of the last modification to this reaction's definition

=item name

descriptive name of this reaction

=item source_id

ID of this reaction in the resource from which it was added

=item abbr

abbreviated name of this reaction

=item direction

direction of this reaction (> for forward-only, < for backward-only, = for bidirectional)

=item deltaG

Gibbs free-energy change for the reaction calculated using the group contribution method (units are kcal/mol)

=item deltaG_error

uncertainty in the [b]deltaG[/b] value (units are kcal/mol)

=item thermodynamic_reversibility

computed reversibility of this reaction in a pH-neutral environment

=item default_protons

number of protons absorbed by this reaction in a pH-neutral environment

=item status

string indicating additional information about this reaction, generally indicating whether the reaction is balanced and/or lumped

=back

=head1 AUTHORS

L<The SEED Project|http://www.theseed.org>

=cut

use Bio::KBase::CDMI::CDMIClient;
use Getopt::Long;

#Default fields

my @all_fields = ( 'mod_date', 'name', 'source_id', 'abbr', 'direction', 'deltaG', 'deltaG_error', 'thermodynamic_reversibility', 'default_protons', 'status' );
my %all_fields = map { $_ => 1 } @all_fields;

our $usage = <<'END';
Usage: all_entities_Reaction [arguments] > entity.data

    --fields list   Choose a set of fields to return. List is a comma-separated list of strings.
    -a		    Return all available fields.
    --show-fields   List the available fields.

The following fields are available:

    mod_date
        date and time of the last modification to this reaction's definition
    name
        descriptive name of this reaction
    source_id
        ID of this reaction in the resource from which it was added
    abbr
        abbreviated name of this reaction
    direction
        direction of this reaction (> for forward-only, < for backward-only, = for bidirectional)
    deltaG
        Gibbs free-energy change for the reaction calculated using the group contribution method (units are kcal/mol)
    deltaG_error
        uncertainty in the [b]deltaG[/b] value (units are kcal/mol)
    thermodynamic_reversibility
        computed reversibility of this reaction in a pH-neutral environment
    default_protons
        number of protons absorbed by this reaction in a pH-neutral environment
    status
        string indicating additional information about this reaction, generally indicating whether the reaction is balanced and/or lumped
END

my $a;
my $f;
my @fields;
my $show_fields;
my $help;
my $geO = Bio::KBase::CDMI::CDMIClient->new_get_entity_for_script("a" 		=> \$a,
								  "show-fields" => \$show_fields,
								  "h" 		=> \$help,
								  "fields=s"    => \$f);

if ($help)
{
    print $usage;
    exit 0;
}

if ($show_fields)
{
    print "Available fields:\n";
    print "\t$_\n" foreach @all_fields;
    exit 0;
}

if (@ARGV != 0 || ($a && $f))
{
    print STDERR $usage, "\n";
    exit 1;
}

if ($a)
{
    @fields = @all_fields;
}
elsif ($f) {
    my @err;
    for my $field (split(",", $f))
    {
	if (!$all_fields{$field})
	{
	    push(@err, $field);
	}
	else
	{
	    push(@fields, $field);
	}
    }
    if (@err)
    {
	print STDERR "all_entities_Reaction: unknown fields @err. Valid fields are: @all_fields\n";
	exit 1;
    }
}

my $start = 0;
my $count = 1_000_000;

my $h = $geO->all_entities_Reaction($start, $count, \@fields );

while (%$h)
{
    while (my($k, $v) = each %$h)
    {
	print join("\t", $k, map { ref($_) eq 'ARRAY' ? join(",", @$_) : $_ } @$v{@fields}), "\n";
    }
    $start += $count;
    $h = $geO->all_entities_Reaction($start, $count, \@fields);
}


text:
/**
 * This widget renders the visualization defined by a VisualizationModel onto
 * a canvas element that will fill the parent element.
 */
cinema.views.VisualizationCanvasWidget = Backbone.View.extend({
    // Expose primitive events from the canvas for building interactors
    events: {
        'click .c-vis-render-canvas': function (e) {
            this.trigger('c:click', e);
        },
        'dblclick .c-vis-render-canvas': function (e) {
            this.trigger('c:dblclick', e);
        },
        'mousedown .c-vis-render-canvas': function (e) {
            this.trigger('c:mousedown', e);
        },
        'mousemove .c-vis-render-canvas': function (e) {
            this.trigger('c:mousemove', e);
        },
        'mouseup .c-vis-render-canvas': function (e) {
            this.trigger('c:mouseup', e);
        },
        'mousewheel .c-vis-render-canvas': function (e) {
            this.trigger('c:mousewheel', e);
        },
        'DOMMouseScroll .c-vis-render-canvas': function (e) {
            this.trigger('c:mousewheel', e);
        },
        'keypress .c-vis-render-canvas': function (e) {
            this.trigger('c:keypress', e);
        },
        'contextmenu .c-vis-render-canvas': function (e) {
            e.preventDefault();
        }
    },

    //subclass uses to extend
    _privateInit: function (settings) {
    },

    /**
     * This widget should be initialized with a visModel as the model parameter
     * and optionally a pre-existing CompositeImageManager.
     *
     * @param model The VisualizationModel being rendered.
     * @param [layers] A LayerModel to use. If none is passed, creates one
     *        internally.
     * @param [compositeManager] A CompositeImageManager to use. If none is
     *        passed, uses the one that is set as the imageManager property of
     *        the visModel. If that is not set, creates one internally.
     */
    initialize: function (settings) {
        this.controlModel = settings.viewpoint.controlModel;
        this.viewpoint = settings.viewpoint;

        if (!this.model.loaded()) {
            this.listenToOnce(this.model, 'change', function () {
                this.initialize(settings);
            });
            return;
        }

        this._privateInit(settings);
        this.compositeModel = new cinema.decorators.Composite(this.model);
        this.layers = settings.layers || new cinema.models.LayerModel(this.compositeModel.getDefaultPipelineSetup());
        this.backgroundColor = settings.backgroundColor || '#ffffff';
        this.orderMapping = {};
        this.compositeCache = {};
        this._controls = {};

        this.compositeManager = settings.compositeManager ||
            new cinema.utilities.CompositeImageManager({
                visModel: this.model
            });

        this._computeLayerOffset();
        this._first = true;

        this.averageElapsedMillis = 0.0;
        this.totalElapsedMillis = 0.0;
        this.compositeCount = 0;

        this.listenTo(this.compositeManager, 'c:error', function (e) {
            this.trigger('c:error', e);
        });
        this.listenTo(this.compositeManager, 'c:data.ready', function (data, controls) {
            if (_.isEqual(controls, this._controls)) {
                var startMillis = Date.now();

                this._writeCompositeBuffer(data);
                if (this._first) {
                    this._first = false;
                    this.resetCamera();
                }
                this.drawImage();

                var elapsedMillis = Date.now() - startMillis;
                this.compositeCount += 1;
                this.totalElapsedMillis += elapsedMillis;
                this.averageElapsedMillis = this.totalElapsedMillis / this.compositeCount;

                var curFps = Math.floor((1.0 / elapsedMillis) * 1000);
                var avgFps = Math.floor((1.0 / this.averageElapsedMillis) * 1000);

                cinema.events.trigger('c:fpsupdate', {'curFps': curFps, 'avgFps': avgFps});
            }
        });
        this.listenTo(this.layers, 'change', this.updateQuery);
        cinema.bindWindowResizeHandler(this, this.drawImage, 200);

    },

    render: function () {
        this.$el.html(cinema.templates.visCanvas());

        return this;
    },

    _computeOffset: function (order) {
        for (var i = 0; i < order.length; i += 1) {
            var offset = this.layerOffset[order[i]];
            if (offset > -1) {
                return offset;
            }
        }
        return -1;
    },

    _computeLayerOffset: function () {
        var query;

        this.layerOffset = {};

        query = this.layers.serialize();
        for (var i = 0; i < query.length; i += 2) {
            var layer = query[i];

            if (query[i + 1] === '_') {
                this.layerOffset[layer] = -1;
            } else {
                this.layerOffset[layer] = this.compositeModel.getSpriteSize() -
                    this.compositeModel.getOffset()[query.substr(i, 2)];
            }
        }
    },

    _computeCompositeInfo: function (data) {
        var composite = data.json['pixel-order'].split('+'),
            count = composite.length;
        /*jshint -W016 */
        while (count--) {
            var str = composite[count];
            if (str[0] === '@') {
                composite[count] = Number(str.substr(1));
            } else if (!_.has(this.orderMapping, str)) {
                this.orderMapping[str] = this._computeOffset(str);
            }
        }

        this.compositeCache[data.key] = composite;
    },

    /**
     * Computes the composite image and writes it into the composite buffer.
     * @param data The payload from the composite image manager c:data.ready
     * callback. This will write computed composite data back into that
     * cache entry so it won't have to recompute it.
     */
    _writeCompositeBuffer: function (data) {
        if (!_.has(this.compositeCache, data.key)) {
            this._computeCompositeInfo(data);
        }

        var renderCanvas = this.$('.c-vis-render-canvas')[0],
            compositeCanvas = this.$('.c-vis-composite-buffer')[0],
            spriteCanvas = this.$('.c-vis-spritesheet-buffer')[0],
            dim = this.compositeModel.getImageSize(),
            spritesheetDim = this.compositeModel.getSpriteImageSize(),
            spriteCtx = spriteCanvas.getContext('2d'),
            compositeCtx = compositeCanvas.getContext('2d'),
            composite = this.compositeCache[data.key];

        $(spriteCanvas).attr({
            width: spritesheetDim[0],
            height: spritesheetDim[1]
        });
        $(compositeCanvas).attr({
            width: dim[0],
            height: dim[1]
        });

        // Fill full spritesheet buffer with raw image data
        spriteCtx.drawImage(data.image, 0, 0);

        var pixelBuffer = spriteCtx.getImageData(0, 0,
                  spritesheetDim[0], spritesheetDim[1]).data,
            frontBuffer,
            pixelIdx = 0;

        // Fill the background if backgroundColor is specified
        if (this.backgroundColor) {
            compositeCtx.fillStyle = this.backgroundColor;
            compositeCtx.fillRect(0, 0, dim[0], dim[1]);
            frontBuffer = compositeCtx.getImageData(0, 0, dim[0], dim[1]);
        } else { // Otherwise use the bottom spritesheet image as a background
            frontBuffer = spriteCtx.getImageData(
                0, this.compositeModel.getSpriteSize() * dim[1], dim[0], dim[1]);
        }

        var frontPixels = frontBuffer.data;

        for (var i = 0; i < composite.length; i += 1) {
            var order = composite[i];
            if (order > 0) {
                pixelIdx += order;
            } else {
                var offset = this.orderMapping[order];

                if (offset > -1) {
                    var localIdx = 4 * pixelIdx;
                    offset *= dim[0] * dim[1] * 4;
                    offset += localIdx;
                    frontPixels[localIdx] = pixelBuffer[offset];
                    frontPixels[localIdx + 1] = pixelBuffer[offset + 1];
                    frontPixels[localIdx + 2] = pixelBuffer[offset + 2];
                    frontPixels[localIdx + 3] = 255;
                }
                pixelIdx += 1;
            }
        }

        // Draw buffer to composite canvas
        compositeCtx.putImageData(frontBuffer, 0, 0);
        this.trigger('c:composited');
    },

    /**
     * Call this after data has been successfully rendered onto the composite
     * canvas, and it will draw it with the correct scale, zoom, and center
     * onto the render canvas.
     */
    drawImage: function () {
        var renderCanvas = this.$('.c-vis-render-canvas')[0],
            compositeCanvas = this.$('.c-vis-composite-buffer')[0],
            w = this.$el.width(),
            h = this.$el.height(),
            iw = compositeCanvas.width,
            ih = compositeCanvas.height;

        $(renderCanvas).attr({
            width: w,
            height: h
        });
        renderCanvas.getContext('2d').clearRect(0, 0, w, h);

        var zoomLevel = this.viewpoint.get('zoom'),
            drawingCenter = this.viewpoint.get('center');

        var tw = Math.floor(iw * zoomLevel),
            th = Math.floor(ih * zoomLevel);

        var tx = drawingCenter[0] - (tw / 2),
            ty = drawingCenter[1] - (th / 2);

        renderCanvas.getContext('2d').drawImage(
            compositeCanvas,
            0,   0, iw, ih,  // Source image   [Location,Size]
            tx, ty, tw, th); // Target drawing [Location,Size]

        this.trigger('c:drawn');
    },

    /**
     * Reset the zoom level and drawing center such that the image is
     * centered and zoomed to fit within the parent container.
     */
    resetCamera: function () {
        var w = this.$el.width(),
            h = this.$el.height(),
            iw = this.$('.c-vis-composite-buffer').width(),
            ih = this.$('.c-vis-composite-buffer').height();

        this.viewpoint.set({
            zoom: Math.min(w / iw, h / ih),
            center: [w / 2, h / 2]
        });
        return this;
    },

    /**
     * Change the viewpoint to show a different image.
     * @param viewpoint An object containing "time", "phi", and "theta" keys. If you
     * do not pass this, simply renders the current this.viewpoint value.
     * @return this, for chainability
     */
    showViewpoint: function (forced, controlModel) {
        var changed = false,
            controls = controlModel || this.controlModel.getControls();

        // Search for change
        for (var key in controls) {
            if (_.has(this._controls, key)) {
                if (this._controls[key] !== controls[key]) {
                    changed = true;
                }
            } else {
                changed = true;
            }
        }
        this._controls = _.extend(this._controls, controls);
        if (changed || forced) {
            this.compositeManager.downloadData(this._controls);
        } else {
            this.drawImage();
        }
        return this;
    },

    getImage: function () {
        var image = new Image(),
            compositeCanvas = this.$('.c-vis-composite-buffer')[0];
        image.src = compositeCanvas.toDataURL("image/png");
        return image;
    },

    updateQuery: function () {
        this.orderMapping = {};
        this.compositeCache = {};
        this._computeLayerOffset();
        this._controls = {}; // force redraw
        this.showViewpoint();
    },

    updateTheQuery: function (query, viewpoint) {
        this.orderMapping = {};
        this.compositeCache = {};
        this.layerOffset = {};

        for (var i = 0; i < query.length; i += 2) {
            var layer = query[i];

            if (query[i + 1] === '_') {
                this.layerOffset[layer] = -1;
            } else {
                this.layerOffset[layer] = this.compositeModel.getSpriteSize() -
                    this.compositeModel.getOffset()[query.substr(i, 2)];
            }
        }
        this.showViewpoint(true, viewpoint);
    },

    /**
     * Maps an [x, y] value relative to the canvas element to an [x, y] value
     * relative to the image being rendered on the canvas.
     * @param coords 2-length list representing [x, y] offset into the canvas
     * element.
     * @returns the corresponding [x, y] value of the image being rendered on
     * the canvas, respecting zoom level and drawing center, or null if the
     * input coordinates are on a part of the canvas outside of the image render
     * bounds. If not null, this will be a value bounded in each dimension by
     * the length of the composited image in that dimension.
     */
    mapToImageCoordinates: function (coords) {
        // TODO
    }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<simple-methods xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://ofbiz.apache.org/Simple-Method" xsi:schemaLocation="http://ofbiz.apache.org/Simple-Method http://ofbiz.apache.org/dtds/simple-methods.xsd">

    <simple-method method-name="facilityPermissionCheck" short-description="Check user has facility Manager permission">
        <set field="primaryPermission" value="FACILITY"/>
        <call-simple-method method-name="genericBasePermissionCheck" xml-resource="component://common/minilang/permission/CommonPermissionServices.xml"/>
    </simple-method>
</simple-methods>


text:
package org.gluu.service.el;

import javax.el.ExpressionFactory;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;

/**
 * @author Yuriy Movchan Date: 05/22/2017
 */
@ApplicationScoped
public class ExpressionFactoryProducer {

    @Produces
    @ApplicationScoped
    public ExpressionFactory createExpressionFactory() {
        return ExpressionFactory.newInstance();
    }

}


text:
package org.springframework.content.commons.utils;

import java.lang.reflect.Field;
import java.util.UUID;

import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;

import org.springframework.data.mongodb.core.mapping.DBRef;

public final class ContentPropertyUtils {

    private static boolean IS_JPA_PRESENT = false;
    private static boolean IS_MONGO_PRESENT = false;

    static {
        try {
            IS_JPA_PRESENT = Class.forName("javax.persistence.OneToOne") != null;
            IS_MONGO_PRESENT = Class.forName("org.springframework.data.mongodb.core.mapping.DBRef") != null;
        } catch (ClassNotFoundException e) {
        }
    }

    private ContentPropertyUtils() {}

    public static boolean isPrimitiveContentPropertyClass(Class<?> clazz) {
        return clazz.isPrimitive() || clazz.equals(UUID.class) || clazz.equals(String.class);
    }

    public static boolean isWrapperType(Class<?> type) {

        if (Boolean.class.equals(type) ||
            Byte.class.equals(type) ||
            Character.class.equals(type) ||
            Double.class.equals(type) ||
            Float.class.equals(type) ||
            Integer.class.equals(type) ||
            Long.class.equals(type) ||
            Short.class.equals(type)) {
            return true;
        }

        return false;
    }

    public static boolean isRelationshipField(Field f) {

        if (IS_JPA_PRESENT) {
            if (f.getAnnotation(OneToOne.class) != null ||
                f.getAnnotation(OneToMany.class) != null ||
                f.getAnnotation(ManyToOne.class) != null ||
                f.getAnnotation(ManyToMany.class) != null) {
                return true;
            }
        }
        if (IS_MONGO_PRESENT) {
            if (f.getAnnotation(DBRef.class) != null) {
                return true;
            }
        }
        return false;
    }
}


text:
/* @test
 * @bug 4115696

 * @summary synopsis: cannot use socket factories with Activatable objects
 * @author Ann Wollrath
 *
 * @library ../../../../testlibrary
 * @build Echo
 * @build EchoImpl
 * @build EchoImpl_Stub
 * @build UseCustomSocketFactory
 * @run main/othervm/policy=security.policy/timeout=360 UseCustomSocketFactory
 */

import java.io.*;
import java.rmi.*;
import java.rmi.activation.*;
import java.rmi.server.*;
import java.rmi.registry.*;

public class UseCustomSocketFactory {

    final static int REGISTRY_PORT = 2006;
    static String[] protocol = new String[] { "", "compress", "xor" };

    public static void main(String[] args) {

        System.out.println("\nRegression test for bug 4115696\n");

        TestLibrary.suggestSecurityManager("java.rmi.RMISecurityManager");

        try {
            LocateRegistry.createRegistry(REGISTRY_PORT);
        } catch (Exception e) {
            TestLibrary.bomb("creating registry", e);
        }

        RMID rmid = null;

        try {
            rmid = RMID.createRMID(true);
            rmid.addArguments(new String[] {
                "-C-Djava.security.policy=" +
                    TestParams.defaultGroupPolicy +
                    " -C-Djava.security.manager=java.rmi.RMISecurityManager "});
            rmid.start();

            Echo[] echo = spawnAndTest();
            reactivateAndTest(echo);
        } catch (IOException e) {
            TestLibrary.bomb("creating rmid", e);
        } finally {
            if (rmid != null)
                rmid.destroy();
        }
    }

    private static Echo[] spawnAndTest() {

        System.err.println("\nCreate Test-->");

        Echo[] echo = new Echo[protocol.length];

        for (int i = 0; i < protocol.length; i++) {

            JavaVM serverVM = new JavaVM("EchoImpl",
                                         "-Djava.security.policy=" +
                                         TestParams.defaultPolicy,
                                         protocol[i]);

            System.err.println("\nusing protocol: " +
                               (protocol[i] == "" ? "none" : protocol[i]));

            try {
                /* spawn VM for EchoServer */
                serverVM.start();

                /* lookup server */
                int tries = 12;        // need enough tries for slow machine.
                echo[i] = null;
                do {
                    try {
                        echo[i] = (Echo) Naming.lookup("//:" + REGISTRY_PORT +
                                                       "/EchoServer");
                        break;
                    } catch (NotBoundException e) {
                        try {
                            Thread.sleep(2000);
                        } catch (Exception ignore) {
                        }
                        continue;
                    }
                } while (--tries > 0);

                if (echo[i] == null)
                    TestLibrary.bomb("server not bound in 12 tries", null);

                /* invoke remote method and print result*/
                System.err.println("Bound to " + echo[i]);
                byte[] data = ("Greetings, citizen " +
                               System.getProperty("user.name") + "!"). getBytes();
                byte[] result = echo[i].echoNot(data);
                for (int j = 0; j < result.length; j++)
                    result[j] = (byte) ~result[j];
                System.err.println("Result: " + new String(result));
                echo[i].shutdown();

            } catch (Exception e) {
                TestLibrary.bomb("test failed", e);

            } finally {
                serverVM.destroy();
                try {
                    Naming.unbind("//:" + REGISTRY_PORT + "/EchoServer");
                } catch (Exception e) {
                    TestLibrary.bomb("unbinding EchoServer", e);

                }
            }
        }
        return echo;
    }

    private static void reactivateAndTest(Echo[] echo) {

        System.err.println("\nReactivate Test-->");

        for (int i = 0; i < echo.length; i++) {
            try {
                System.err.println("\nusing protocol: " +
                                   (protocol[i] == "" ? "none" : protocol[i]));
                byte[] data = ("Greetings, citizen " +
                               System.getProperty("user.name") + "!").getBytes();
                byte[] result = echo[i].echoNot(data);
                for (int j = 0; j < result.length; j++)
                    result[j] = (byte) ~result[j];
                System.err.println("Result: " + new String(result));
                echo[i].shutdown();
            } catch (Exception e) {
                TestLibrary.bomb("activating EchoServer for protocol " + protocol[i], e);
            }
        }
    }
}


text:
  window.fbAsyncInit = function() {
    //Initiallize the facebook using the facebook javascript sdk
     FB.init({
       appId:'<?php echo $this->config->item('appId'); ?>', // App ID
       cookie:true, // enable cookies to allow the server to access the session
       status:true, // check login status
       xfbml:true, // parse XFBML
       oauth : true //enable Oauth
     });
  };
 //Read the baseurl from the config.php file
 (function(d){
   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
   js.src = "//connect.facebook.net/en_US/all.js";
   ref.parentNode.insertBefore(js, ref);
 }(document));

  //Onclick for fb login
 $('#feis').click(function(e) {
    FB.login(function(response) {
    if(response.authResponse) {
      parent.location ='<?php echo $b; ?>bb/fblogin'; //redirect uri after closing the facebook popup
    }
 },{scope: 'email,read_stream,publish_stream,user_birthday,user_location,user_work_history,user_hometown,user_photos'}); //permissions for facebook
});


text:
static const NSInteger kDefaultCacheMaxCacheAge = 60 * 60 * 24 * 7; // 1 week

@interface YYHDiskCache ()

@property (nonatomic, copy, readwrite) NSString *name;
@property (nonatomic, copy, readwrite) NSURL *cacheURL;
@property (nonatomic, strong) NSFileManager *fileManager;
@property (nonatomic, assign) NSInteger maxCacheAge;

@property (nonatomic, strong) NSLock *lock;
@property (nonatomic, strong) dispatch_queue_t asyncQueue;;

@end

@implementation YYHDiskCache

- (instancetype)init {

    NSAssert(0, @"initWithName: or initWithName: rootPath:");
    return nil;
}

- (instancetype)initWithName:(NSString *)name {

    return [self initWithName:name rootPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
}

- (instancetype)initWithName:(NSString *)name rootPath:(NSString *)rootPath {

    if (!name) {
        name = @"";
    }
    if (!rootPath) {
        rootPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    }
    if (self = [super init]) {

        _maxCacheAge = kDefaultCacheMaxCacheAge;
        _autoTrimInterval = 10*60;  //10 miminute
        NSString *pathComponent = [[NSString alloc] initWithFormat:@"%@.%@", YYHDiskCachePrefix, name];
        _cacheURL = [NSURL fileURLWithPathComponents:@[rootPath, pathComponent]];
        _fileManager = [NSFileManager new];

        if (![_fileManager fileExistsAtPath:[_cacheURL path]]) {
            [_fileManager createDirectoryAtURL:_cacheURL
                   withIntermediateDirectories:YES
                                    attributes:nil
                                         error:nil];
        }

        _lock = [NSLock new];
        _asyncQueue = dispatch_queue_create("com.yahua.diskCache", DISPATCH_QUEUE_CONCURRENT); //并行队列

        //清除过期的缓存文件
        [self p_trimRecurrence];
    }

    return self;
}

#pragma mark - Public

- (BOOL)containsObjectForKey:(NSString *)key {

    if (!key) return NO;
    BOOL bContains = NO;
    NSString *path = [[self p_fileNameWithKey:key] path];

    [_lock lock];
    bContains = [_fileManager fileExistsAtPath:path];
    [_lock unlock];

    return bContains;
}

- (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL bContains))block {

    if (!block) {
        return;
    }
    __weak __typeof(self)weakSelf = self;
    dispatch_async(_asyncQueue, ^{
        __strong __typeof(weakSelf)self = weakSelf;
        BOOL bContains = [self containsObjectForKey:key];
        block(key, bContains);
    });
}

- (id<NSCoding>)objectForKey:(NSString *)key {

    if (!key) {
        return nil;
    }
    id<NSCoding> object = nil;
    [_lock lock];
    NSData *data = [NSData dataWithContentsOfURL:[self p_fileNameWithKey:key]];
    if (!data) {
        [_lock unlock];
        return nil;
    }
    @try {
        object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    }
    @catch (NSException *exception) {
        NSAssert(0, @"不是NSCoding");
    }
    [_lock unlock];

    return object;
}

- (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id<NSCoding> object))block {

    if (!block) {
        return;
    }
    __weak __typeof(self)weakSelf = self;
    dispatch_async(_asyncQueue, ^{
        __strong __typeof(weakSelf)self = weakSelf;
        id<NSCoding> object = [self objectForKey:key];
        block(key, object);
    });
}

- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key {

    if (!key) return;

    if (!object) {
        [self removeObjectForKey:key];
    }else {
        [_lock lock];
        NSData *value;
        @try {
            value = [NSKeyedArchiver archivedDataWithRootObject:object];
        }
        @catch (NSException *exception) {
            NSAssert(0, @"不是NSCoding");
        }

        [value writeToURL:[self p_fileNameWithKey:key] atomically:NO];
        [_lock unlock];
    }
}

- (void)setObject:(id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(NSString *key))block {

    if (!block) {
        return;
    }
    __weak __typeof(self)weakSelf = self;
    dispatch_async(_asyncQueue, ^{
        __strong __typeof(weakSelf)self = weakSelf;
        [self setObject:object forKey:key];
        block(key);
    });
}

- (void)removeObjectForKey:(NSString *)key {

    if (!key) return;

    NSError *error= nil;
    NSURL *path = [self p_fileNameWithKey:key];
    [_lock lock];
    [_fileManager removeItemAtURL:path error:&error];
    [_lock unlock];
    if (error) {
        NSAssert(0, @"文件移除失败");
    }
}

- (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block {

    if (!block) {
        return;
    }
    __weak __typeof(self)weakSelf = self;
    dispatch_async(_asyncQueue, ^{
        __strong __typeof(weakSelf)self = weakSelf;
        [self removeObjectForKey:key];
        block(key);
    });
}

- (void)removeAllObjects {

    NSError *error = nil;
    [_lock lock];
    [_fileManager removeItemAtURL:_cacheURL error:&error];
    [_lock unlock];
    if (error) {
        NSAssert(0, @"文件移除失败");
    }
}

- (void)removeAllObjectsWithBlock:(void(^)())block {

    if (!block) {
        return;
    }
    __weak __typeof(self)weakSelf = self;
    dispatch_async(_asyncQueue, ^{
        __strong __typeof(weakSelf)self = weakSelf;
        [self removeAllObjects];
        block();
    });
}

- (void)cacheSize:(void(^)(NSUInteger size))block; {

    if (!block) {
        return;
    }
    __weak __typeof(self)weakSelf = self;
    dispatch_async(self.asyncQueue, ^{
        __strong __typeof(weakSelf)self = weakSelf;
        NSDirectoryEnumerator *fileEnumerator = [self.fileManager enumeratorAtPath:[self.cacheURL path]];
        NSUInteger size = 0;
        for (NSString *fileName in fileEnumerator) {
            NSString *filePath = [[self.cacheURL path] stringByAppendingPathComponent:fileName];
            NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
            size += [attrs fileSize];
        }
        block(size);
    });
}

#pragma mark - Private

- (NSURL *)p_fileNameWithKey:(NSString *)key {

    NSAssert(key, @"key 不能为nil");
    return [_cacheURL URLByAppendingPathComponent:key];
}

- (void)p_trimRecurrence {  //循环调用

    __weak __typeof(self)weakSelf = self;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_autoTrimInterval * NSEC_PER_SEC)),
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        __strong __typeof(weakSelf)self = weakSelf;
        if (!self) return;
        [self p_trimInBackGround];
        [self p_trimRecurrence];
    });
}

- (void)p_trimInBackGround { //清楚过期缓存

    __weak __typeof(self)weakSelf = self;
    dispatch_async(_asyncQueue, ^{

        __strong __typeof(weakSelf)self = weakSelf;
        NSArray *resourceKeys = @[NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey];

        [self lock];
        // This enumerator prefetches useful properties for our cache files.
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtURL:_cacheURL
                                                   includingPropertiesForKeys:resourceKeys
                                                                      options:NSDirectoryEnumerationSkipsHiddenFiles
                                                                 errorHandler:NULL];

        NSDate *expirationDate = [NSDate dateWithTimeIntervalSinceNow:-self.maxCacheAge];

        // Enumerate all of the files in the cache directory.  This loop has two purposes:
        //
        //  1. Removing files that are older than the expiration date.
        //  2. Storing file attributes for the size-based cleanup pass.
        NSMutableArray *urlsToDelete = [[NSMutableArray alloc] init];
        for (NSURL *fileURL in fileEnumerator) {
            NSDictionary *resourceValues = [fileURL resourceValuesForKeys:resourceKeys error:NULL];

            // Skip directories.
            if ([resourceValues[NSURLIsDirectoryKey] boolValue]) {
                continue;
            }

            // Remove files that are older than the expiration date;
            NSDate *modificationDate = resourceValues[NSURLContentModificationDateKey];
            if ([[modificationDate laterDate:expirationDate] isEqualToDate:expirationDate]) {
                [urlsToDelete addObject:fileURL];
                continue;
            }

        }

        for (NSURL *fileURL in urlsToDelete) {
            [_fileManager removeItemAtURL:fileURL error:nil];
        }
        [self.lock unlock];
    });
}

@end


text:
this=${0##*/}
echo ":: Running Vagrant provisioning script $this"

echo ":: Installation errors will be logged to $this.log"
exec 2> >(tee -a /vagrant/$this.log >&2)

echo ":: Updating the package manager"
sudo apt-get update

echo ":: Setting locales"
export LANGUAGE=en_US.UTF-8
export LANG=en_US.UTF-8
export LC_ALL=en_US.UTF-8
sudo locale-gen en_US.UTF-8

echo ":: Setting timezone to Europe/Helsinki"
sudo ln -sf /usr/share/zoneinfo/Europe/Helsinki /etc/localtime

echo ":: Installing dependencies available via apt-get"
sudo apt-get install -y nginx apache2 libapache2-mod-wsgi libpq5

if [ ! -f /home/vagrant/python-ckan_2.2_amd64.deb ]; then
	echo ":: Downloading the CKAN 2.2 package since not existing"
	wget -q http://packaging.ckan.org/python-ckan_2.2_amd64.deb
fi

echo ":: Installing the CKAN 2.2 package"
sudo dpkg -i /home/vagrant/python-ckan_2.2_amd64.deb

echo ":: Changing Apache 2 configuration for CKAN defaults"
sudo cp /vagrant/provision/apache2_ckan_default.conf /etc/apache2/sites-available/ckan_default

echo ":: Restarting Apache2"
sudo service apache2 restart

echo ":: Install postgresql-9.1, jetty and openjdk-6"
sudo apt-get install -y postgresql-9.1 solr-jetty openjdk-6-jdk

echo ":: Copying jetty configuration file"
sudo cp /vagrant/provision/jetty.conf /etc/default/jetty
sudo mkdir -p /var/lib/ckan/storage
sudo chown jetty:jetty -R /var/lib/ckan/

echo ":: Creating CKAN resource directory"
sudo mkdir /var/lib/ckan/resources
chown jetty:jetty /var/lib/ckan/resources

echo ":: Create a CKAN database in postgresql"
sudo -u postgres createuser -S -D -R ckan_default
sudo -u postgres psql -c "ALTER USER ckan_default PASSWORD 'pass'"
sudo -u postgres createdb -O ckan_default ckan_default

echo ":: Handling Solr schema files and copying CKAN configuration"
sudo mv /etc/solr/conf/schema.xml /etc/solr/conf/schema.xml.bak
sudo ln -s /usr/lib/ckan/default/src/ckan/ckan/config/solr/schema-2.0.xml /etc/solr/conf/schema.xml
sudo cp /vagrant/provision/ckan.ini /etc/ckan/default/production.ini

echo ":: Starting Jetty"
sudo service jetty start

echo ":: Initialize CKAN database"
sudo ckan db init

echo ":: Creating an admin user"
source /usr/lib/ckan/default/bin/activate
paster --plugin=ckan user add admin email=example@email.org password=pass -c /etc/ckan/default/production.ini
paster --plugin=ckan sysadmin add admin -c /etc/ckan/default/production.ini

echo ":: CKAN running in http://localhost:8765 or 192.168.13.37:8080"


text:
#pragma once
#include <aws/gamelift/GameLift_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace GameLift
{
namespace Model
{
  /**
   *
Represents the returned data in response to a request action.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_GAMELIFT_API ResolveAliasResult
  {
  public:
    ResolveAliasResult();
    ResolveAliasResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    ResolveAliasResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Fleet identifier that is associated with the requested alias.

     */
    inline const Aws::String& GetFleetId() const{ return m_fleetId; }

    /**
     *
Fleet identifier that is associated with the requested alias.

     */
    inline void SetFleetId(const Aws::String& value) { m_fleetId = value; }

    /**
     *
Fleet identifier that is associated with the requested alias.

     */
    inline void SetFleetId(Aws::String&& value) { m_fleetId = std::move(value); }

    /**
     *
Fleet identifier that is associated with the requested alias.

     */
    inline void SetFleetId(const char* value) { m_fleetId.assign(value); }

    /**
     *
Fleet identifier that is associated with the requested alias.

     */
    inline ResolveAliasResult& WithFleetId(const Aws::String& value) { SetFleetId(value); return *this;}

    /**
     *
Fleet identifier that is associated with the requested alias.

     */
    inline ResolveAliasResult& WithFleetId(Aws::String&& value) { SetFleetId(std::move(value)); return *this;}

    /**
     *
Fleet identifier that is associated with the requested alias.

     */
    inline ResolveAliasResult& WithFleetId(const char* value) { SetFleetId(value); return *this;}

  private:

    Aws::String m_fleetId;
  };

} // namespace Model
} // namespace GameLift
} // namespace Aws


text:
from __future__ import division
import yaml
import numpy as np
import numpy.random as npr
import pdb

from ..utils.cython_bbox import bbox_overlaps, bbox_intersections

# TODO: make fast_rcnn irrelevant
# >>>> obsolete, because it depends on sth outside of this project
from ..fast_rcnn.config import cfg
from ..fast_rcnn.bbox_transform import bbox_transform
# <<<< obsolete

DEBUG = False

def proposal_target_layer(rpn_rois, gt_boxes, gt_ishard, dontcare_areas, _num_classes):
    """
    Assign object detection proposals to ground-truth targets. Produces proposal
    classification labels and bounding-box regression targets.
    Parameters
    ----------
    rpn_rois:  (1 x H x W x A, 5) [0, x1, y1, x2, y2]
    gt_boxes: (G, 5) [x1 ,y1 ,x2, y2, class] int
    gt_ishard: (G, 1) {0 | 1} 1 indicates hard
    dontcare_areas: (D, 4) [ x1, y1, x2, y2]
    _num_classes
    ----------
    Returns
    ----------
    rois: (1 x H x W x A, 5) [0, x1, y1, x2, y2]
    labels: (1 x H x W x A, 1) {0,1,...,_num_classes-1}
    bbox_targets: (1 x H x W x A, K x4) [dx1, dy1, dx2, dy2]
    bbox_inside_weights: (1 x H x W x A, Kx4) 0, 1 masks for the computing loss
    bbox_outside_weights: (1 x H x W x A, Kx4) 0, 1 masks for the computing loss
    """

    # Proposal ROIs (0, x1, y1, x2, y2) coming from RPN
    # (i.e., rpn.proposal_layer.ProposalLayer), or any other source
    all_rois = rpn_rois
    # TODO(rbg): it's annoying that sometimes I have extra info before
    # and other times after box coordinates -- normalize to one format

    # Include ground-truth boxes in the set of candidate rois
    if cfg.TRAIN.PRECLUDE_HARD_SAMPLES and gt_ishard is not None and gt_ishard.shape[0] > 0:
        assert gt_ishard.shape[0] == gt_boxes.shape[0]
        gt_ishard = gt_ishard.astype(int)
        gt_easyboxes = gt_boxes[gt_ishard != 1, :]
    else:
        gt_easyboxes = gt_boxes

    """
    add the ground-truth to rois will cause zero loss! not good for visuallization
    """
    jittered_gt_boxes = _jitter_gt_boxes(gt_easyboxes)
    zeros = np.zeros((gt_easyboxes.shape[0] * 2, 1), dtype=gt_easyboxes.dtype)
    all_rois = np.vstack((all_rois, \
         np.hstack((zeros, np.vstack((gt_easyboxes[:, :-1], jittered_gt_boxes[:, :-1]))))))

    # Sanity check: single batch only
    assert np.all(all_rois[:, 0] == 0), \
            'Only single item batches are supported'

    num_images = 1
    rois_per_image = cfg.TRAIN.BATCH_SIZE // num_images
    fg_rois_per_image = int(np.round(cfg.TRAIN.FG_FRACTION * rois_per_image))

    # Sample rois with classification labels and bounding box regression
    # targets
    labels, rois, bbox_targets, bbox_inside_weights = _sample_rois(
        all_rois, gt_boxes, gt_ishard, dontcare_areas, fg_rois_per_image,
        rois_per_image, _num_classes)

    # _count = 1
    # if DEBUG:
    #     if _count == 1:
    #         _fg_num, _bg_num = 0, 0
    #     print 'num fg: {}'.format((labels > 0).sum())
    #     print 'num bg: {}'.format((labels == 0).sum())
    #     _count += 1
    #     _fg_num += (labels > 0).sum()
    #     _bg_num += (labels == 0).sum()
    #     print 'num fg avg: {}'.format(_fg_num / _count)
    #     print 'num bg avg: {}'.format(_bg_num / _count)
    #     print 'ratio: {:.3f}'.format(float(_fg_num) / float(_bg_num))

    rois = rois.reshape(-1, 5)
    labels = labels.reshape(-1, 1)
    bbox_targets = bbox_targets.reshape(-1, _num_classes*4)
    bbox_inside_weights = bbox_inside_weights.reshape(-1, _num_classes*4)

    bbox_outside_weights = np.array(bbox_inside_weights > 0).astype(np.float32)

    return rois, labels, bbox_targets, bbox_inside_weights, bbox_outside_weights

def _sample_rois(all_rois, gt_boxes, gt_ishard, dontcare_areas, fg_rois_per_image, rois_per_image, num_classes):
    """Generate a random sample of RoIs comprising foreground and background
    examples.
    """
    # overlaps: R x G
    overlaps = bbox_overlaps(
        np.ascontiguousarray(all_rois[:, 1:5], dtype=np.float),
        np.ascontiguousarray(gt_boxes[:, :4], dtype=np.float))
    gt_assignment = overlaps.argmax(axis=1) # R
    max_overlaps = overlaps.max(axis=1) # R
    labels = gt_boxes[gt_assignment, 4]

    # preclude hard samples
    ignore_inds = np.empty(shape = (0), dtype=int)
    if cfg.TRAIN.PRECLUDE_HARD_SAMPLES and gt_ishard is not None and gt_ishard.shape[0] > 0:
        gt_ishard = gt_ishard.astype(int)
        gt_hardboxes = gt_boxes[gt_ishard == 1, :]
        if gt_hardboxes.shape[0] > 0:
            # R x H
            hard_overlaps = bbox_overlaps(
                np.ascontiguousarray(all_rois[:, 1:5], dtype=np.float),
                np.ascontiguousarray(gt_hardboxes[:, :4], dtype=np.float))
            hard_max_overlaps = hard_overlaps.max(axis=1) # R x 1
            # hard_gt_assignment = hard_overlaps.argmax(axis=0)  # H
            ignore_inds = np.append(ignore_inds, \
                                    np.where(hard_max_overlaps >= cfg.TRAIN.FG_THRESH)[0])
            # if DEBUG:
            #     if ignore_inds.size > 1:
            #         print 'num hard: {:d}:'.format(ignore_inds.size)
            #         print 'hard box:', gt_hardboxes
            #         print 'rois: '
            #         print all_rois[ignore_inds]

    # preclude dontcare areas
    if dontcare_areas is not None and dontcare_areas.shape[0] > 0:
        # intersec shape is D x R
        intersecs = bbox_intersections(
            np.ascontiguousarray(dontcare_areas, dtype=np.float),  # D x 4
            np.ascontiguousarray(all_rois[:, 1:5], dtype=np.float)  # R x 4
        )
        intersecs_sum = intersecs.sum(axis=0)  # R x 1
        ignore_inds = np.append(ignore_inds, \
                                np.where(intersecs_sum > cfg.TRAIN.DONTCARE_AREA_INTERSECTION_HI)[0])
        # if ignore_inds.size >= 1:
        #     print 'num dontcare: {:d}:'.format(ignore_inds.size)
        #     print 'dontcare box:', dontcare_areas.astype(int)
        #     print 'rois: '
        #     print all_rois[ignore_inds].astype(int)

    # Select foreground RoIs as those with >= FG_THRESH overlap
    fg_inds = np.where(max_overlaps >= cfg.TRAIN.FG_THRESH)[0]
    fg_inds = np.setdiff1d(fg_inds, ignore_inds)
    # Guard against the case when an image has fewer than fg_rois_per_image
    # foreground RoIs
    fg_rois_per_this_image = min(fg_rois_per_image, fg_inds.size)
    # Sample foreground regions without replacement
    if fg_inds.size > 0:
        fg_inds = npr.choice(fg_inds, size=fg_rois_per_this_image, replace=False)

    # Select background RoIs as those within [BG_THRESH_LO, BG_THRESH_HI)
    bg_inds = np.where((max_overlaps < cfg.TRAIN.BG_THRESH_HI) &
                       (max_overlaps >= cfg.TRAIN.BG_THRESH_LO))[0]
    bg_inds = np.setdiff1d(bg_inds, ignore_inds)
    # Compute number of background RoIs to take from this image (guarding
    # against there being fewer than desired)
    bg_rois_per_this_image = rois_per_image - fg_rois_per_this_image
    bg_rois_per_this_image = min(bg_rois_per_this_image, bg_inds.size)
    # Sample background regions without replacement
    if bg_inds.size > 0:
        bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False)

    # The indices that we're selecting (both fg and bg)
    keep_inds = np.append(fg_inds, bg_inds)
    # Select sampled values from various arrays:
    labels = labels[keep_inds]
    # Clamp labels for the background RoIs to 0
    labels[fg_rois_per_this_image:] = 0
    rois = all_rois[keep_inds]

    bbox_target_data = _compute_targets(
        rois[:, 1:5], gt_boxes[gt_assignment[keep_inds], :4], labels)

    # bbox_target_data (1 x H x W x A, 5)
    # bbox_targets <- (1 x H x W x A, K x 4)
    # bbox_inside_weights <- (1 x H x W x A, K x 4)
    bbox_targets, bbox_inside_weights = \
        _get_bbox_regression_labels(bbox_target_data, num_classes)

    return labels, rois, bbox_targets, bbox_inside_weights

def _get_bbox_regression_labels(bbox_target_data, num_classes):
    """Bounding-box regression targets (bbox_target_data) are stored in a
    compact form N x (class, tx, ty, tw, th)

    This function expands those targets into the 4-of-4*K representation used
    by the network (i.e. only one class has non-zero targets).

    Returns:
        bbox_target (ndarray): N x 4K blob of regression targets
        bbox_inside_weights (ndarray): N x 4K blob of loss weights
    """

    clss = bbox_target_data[:, 0]
    bbox_targets = np.zeros((clss.size, 4 * num_classes), dtype=np.float32)
    bbox_inside_weights = np.zeros(bbox_targets.shape, dtype=np.float32)
    inds = np.where(clss > 0)[0]
    for ind in inds:
        cls = int(clss[ind])
        start = 4 * cls
        end = start + 4
        bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
        bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
    return bbox_targets, bbox_inside_weights

def _compute_targets(ex_rois, gt_rois, labels):
    """Compute bounding-box regression targets for an image."""

    assert ex_rois.shape[0] == gt_rois.shape[0]
    assert ex_rois.shape[1] == 4
    assert gt_rois.shape[1] == 4

    targets = bbox_transform(ex_rois, gt_rois)
    if cfg.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED:
        # Optionally normalize targets by a precomputed mean and stdev
        targets = ((targets - np.array(cfg.TRAIN.BBOX_NORMALIZE_MEANS))
                / np.array(cfg.TRAIN.BBOX_NORMALIZE_STDS))
    return np.hstack(
            (labels[:, np.newaxis], targets)).astype(np.float32, copy=False)

def _jitter_gt_boxes(gt_boxes, jitter=0.05):
    """ jitter the gtboxes, before adding them into rois, to be more robust for cls and rgs
    gt_boxes: (G, 5) [x1 ,y1 ,x2, y2, class] int
    """
    jittered_boxes = gt_boxes.copy()
    ws = jittered_boxes[:, 2] - jittered_boxes[:, 0] + 1.0
    hs = jittered_boxes[:, 3] - jittered_boxes[:, 1] + 1.0
    width_offset = (np.random.rand(jittered_boxes.shape[0]) - 0.5) * jitter * ws
    height_offset = (np.random.rand(jittered_boxes.shape[0]) - 0.5) * jitter * hs
    jittered_boxes[:, 0] += width_offset
    jittered_boxes[:, 2] += width_offset
    jittered_boxes[:, 1] += height_offset
    jittered_boxes[:, 3] += height_offset

    return jittered_boxes