text:
import {
  Component,
  forwardRef,
  NgModule,
  Input,
  Output,
  ChangeDetectorRef,
  OnInit,
  OnDestroy,
  ContentChildren,
  QueryList,
  Optional,
  EventEmitter,
  ChangeDetectionStrategy,
  NgZone,
  ViewChild,
  ElementRef,
  Renderer2,
  AfterViewInit
} from '@angular/core';
import {
  NG_VALUE_ACCESSOR,
  ControlValueAccessor,
  FormsModule,
} from '@angular/forms';
import { CommonModule } from '@angular/common';
import {
  LyCommonModule,
  LyTheme2,
  LyCoreStyles,
  toBoolean,
  mixinDisableRipple,
  ThemeVariables,
  LyFocusState,
  LY_COMMON_STYLES,
  lyl, StyleCollection,
  LyClasses,
  StyleTemplate,
  ThemeRef,
  StyleRenderer} from '@alyle/ui';
import { Platform } from '@angular/cdk/platform';

export interface LyRadioTheme {
  /** Styles for Radio Component */
  root?: StyleCollection<((classes: LyClasses<typeof STYLES>) => StyleTemplate)>
    | ((classes: LyClasses<typeof STYLES>) => StyleTemplate);
}

export interface LyRadioVariables {
  radio?: LyRadioTheme;
}

const STYLE_PRIORITY = -2;
const DEFAULT_DISABLE_RIPPLE = false;
const DEFAULT_COLOR = 'accent';

export const LY_RADIO_CONTROL_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => LyRadioGroup),
  multi: true
};

let idx = 0;

export class UndefinedValue {
  constructor() { }
}

export const STYLES = (theme: ThemeVariables & LyRadioVariables, ref: ThemeRef) => {
  const radio = ref.selectorsOf(STYLES);
  const { after, before } = theme;
  return {
    $priority: STYLE_PRIORITY,
    /** ly-radio-group */
    root: ( ) => lyl `{
      display: inline-block
      {
        ...${
          (theme.radio
            && theme.radio.root
            && (theme.radio.root instanceof StyleCollection
              ? theme.radio.root.setTransformer(fn => fn(radio))
              : theme.radio.root(radio))
          )
        }
      }
    }`,
    radio: ( ) => lyl `{
      display: inline-block
      -webkit-tap-highlight-color: transparent
      &${radio.checked} {
        ${radio.container} {
          div:nth-child(1) {
            transform: scale(1.25)
          }
          div:nth-child(2) {
            transform: scale(0.8)
          }
        }
      }
      &${radio.onFocusByKeyboard} ${radio.container}::after {
        box-shadow: 0 0 0 12px
        background: currentColor
        opacity: .13
        border-radius: 50%
      }
    }`,
    label: lyl `{
      user-select: none
      cursor: pointer
      white-space: nowrap
      position: relative
      display: flex
      align-items: baseline
    }`,
    labelContent: null,
    container: lyl `{
      position: relative
      margin-${before}: .125em
      margin-${after}: .5em
      margin-top: auto
      margin-bottom: auto
      width: 16px
      height: 16px
      div {
        margin: auto
        border-radius: 50%
        width: 1em
        height: 1em
        box-sizing: border-box
      }
      &::after {
        content: ''
        ...${LY_COMMON_STYLES.fill}
        width: 16px
        height: 16px
        margin: auto
      }
      div:nth-child(2) {
        background: currentColor
        transform: scale(0)
      }
      div:nth-child(1) {
        transform: scale(1)
        border: solid .08em currentColor
        color: ${theme.text.disabled}
      }
    }`,
    checked: null,
    _animations: ( ) => lyl `{
      ${radio.container} div {
        transition: transform cubic-bezier(.1, 1, 0.5, 1)
        transition-duration: 250ms
      }
    }`,
    onFocusByKeyboard: null,
    disabled: ( ) => lyl `{
      color: ${theme.disabled.contrast}
      ${radio.container} div {
        color: ${theme.disabled.contrast}!important
      }
    }`
  };
};

@Component({
  selector: 'ly-radio-group',
  template: `<ng-content></ng-content>`,
  providers: [LY_RADIO_CONTROL_VALUE_ACCESSOR],
  changeDetection: ChangeDetectionStrategy.OnPush,
  preserveWhitespaces: false,
  exportAs: 'lyRadioGroup'
})
export class LyRadioGroup implements ControlValueAccessor {
  /** @docs-private */
  static readonly и = 'LyRadioGroup';
  /** @docs-private */
  readonly classes = this._theme.renderStyleSheet(STYLES);
  private _value: any;
  /** @docs-private */
  name = `ly-radio-name-${idx++}`;

  @Input()
  set value(val: any) {
    if (this._value !== val) {
      if (this._radios) {
        this._updateCheckFromValue(val);
      }
    }
  }
  get value() {
    return this._value;
  }

  @Output() readonly change: EventEmitter<void> = new EventEmitter<void>();

  @Input() color = 'accent';
  @ContentChildren(forwardRef(() => LyRadio)) _radios: QueryList<LyRadio>;

  /** The method to be called in order to update ngModel */
  _controlValueAccessorChangeFn: (value: any) => void = () => {};

  /**
   * onTouch function registered via registerOnTouch (ControlValueAccessor).
   * @docs-private
   */
  onTouched: () => any = () => {};

  /**
   * Mark this group as being "touched" (for ngModel). Meant to be called by the contained
   * radio buttons upon their blur.
   */
  _touch() {
    if (this.onTouched) {
      this.onTouched();
    }
  }

  /** @docs-private */
  writeValue(value: any) {
    if (!!this._radios) {
      this.value = value;
      this._markForCheck();
    }
  }

  /**
   * Registers a callback to be triggered when the model value changes.
   * Implemented as part of ControlValueAccessor.
   * @param fn Callback to be registered.
   * @docs-private
   */
  registerOnChange(fn: (value: any) => void) {
    this._controlValueAccessorChangeFn = fn;
  }

  /**
   * Registers a callback to be triggered when the control is touched.
   * Implemented as part of ControlValueAccessor.
   * @param fn Callback to be registered.
   * @docs-private
   */
  registerOnTouched(fn: any) {
    this.onTouched = fn;
  }

  /**
   * Sets the disabled state of the control. Implemented as a part of ControlValueAccessor.
   * @param _isDisabled Whether the control should be disabled.
   * @docs-private
   */
  setDisabledState(_isDisabled: boolean) {
    // this.disabled = isDisabled;
    this._markForCheck();
  }

  constructor(
    elementRef: ElementRef,
    renderer: Renderer2,
    private _theme: LyTheme2,
    private _cd: ChangeDetectorRef
  ) {
    renderer.addClass(elementRef.nativeElement, this.classes.root);
  }

  _updateCheckFromValue(val: any) {
    let newChecked: boolean;
    this._radios.forEach(radioButton => {
      if (val === radioButton.value) {
        this.updatevalue(val);
        newChecked = true;
        radioButton.checked = true;
      } else if (radioButton.checked) {
        radioButton.checked = false;
      }
    });
    if (!newChecked!) {
      /** when val not exist in radio button !==  */
      this._controlValueAccessorChangeFn(null);
      if (this._value != null) {
        this._value = null;
      }
    }
  }
  /** @docs-private */
  updatevalue(value: any) {
    this._value = value;
    this._controlValueAccessorChangeFn(value);
    this.change.emit();
    this._markForCheck();
  }

  _markForCheck() {
    this._cd.markForCheck();
  }

  _radioResetChecked() {
    this._radios.forEach(_ => _._setCheckedToFalsy());
  }

}

/** @docs-private */
export class LyRadioBase {
  constructor(
    public _theme: LyTheme2,
    public _ngZone: NgZone,
    public _platform: Platform
  ) { }
}

/** @docs-private */
export const LyRadioMixinBase = mixinDisableRipple(LyRadioBase);

@Component({
  selector: 'ly-radio',
  templateUrl: 'radio.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
  preserveWhitespaces: false,
  inputs: [
    'disableRipple'
  ],
  providers: [
    StyleRenderer
  ]
})
export class LyRadio extends LyRadioMixinBase implements OnInit, AfterViewInit, OnDestroy {
  /** @docs-private */
  static readonly и = 'LyRadio';
  /** @docs-private */
  readonly classes = this.radioGroup.classes;
  /** @docs-private */
  id = `ly-radio-id-${idx++}`;
  /** @docs-private */
  name = '';
  private _value = null;
  private _checked = false;
  private _color: string;
  private _animClass: string;
  private _disabled: boolean;
  private _disabledClass?: string;
  @ViewChild('_input') _input: ElementRef;
  @ViewChild('_radioContainer') private _radioContainer: ElementRef;
  @ViewChild('_labelContainer') _labelContainer: ElementRef;
  @Output() change = new EventEmitter<boolean>();

  @Input()
  set value(val) {
    if (this._value !== val) {
      this._value = val;
    }
  }
  get value() { return this._value; }

  @Input()
  set color(val) {
    if (this._color !== val) {
      this._color = val;
      this[0x1] = this._styleRenderer.add(
        `${LyRadio.и}--color-${val}`,
        (theme: ThemeVariables, ref) => {
          const {
            checked,
            container
          } = ref.selectorsOf(STYLES);
          return lyl `{
            &${checked} ${container}, &${checked} ${container} div:nth-child(1), & ${container} div:nth-child(2) {
              color: ${theme.colorOf(val)}
            }
          }`;
        },
        STYLE_PRIORITY,
        this[0x1]
      );
    }
  }
  get color() { return this._color; }
  [0x1]: string;

  @Input()
  set checked(val: boolean) {
    const newCheckedState = toBoolean(val);
    const before = this._checked;
    if (before !== newCheckedState) {
      this._checked = newCheckedState;
      if (!before && newCheckedState) {
        /** Add class checked */
        this._renderer.addClass(this._elementRef.nativeElement, this.classes.checked);

        if (this.value !== this.radioGroup.value) {
          /** update Value */
          this.radioGroup.updatevalue(this.value);
        }
      } else {
        /** Remove class checked */
        this._renderer.removeClass(this._elementRef.nativeElement, this.classes.checked);
      }
      this._markForCheck();
    }
  }

  get checked() {
    return this._checked;
  }

  /** @docs-private */
  get inputId(): string {
    return `${this.id}-input`;
  }

  @Input()
  get disabled(): boolean { return this._disabled; }
  set disabled(value) {
    const newVal = toBoolean(value);
    if (newVal) {
      this._renderer.addClass(this._elementRef.nativeElement, this.classes.disabled);
      this._disabledClass = this.classes.disabled;
    } else if (this._disabledClass) {
      this._renderer.removeClass(this._elementRef.nativeElement, this.classes.disabled);
      this._disabledClass = undefined;
    }
    this._disabled = toBoolean(value);
    this._markForCheck();
  }

  constructor(
    /** @docs-private */
    @Optional() public radioGroup: LyRadioGroup,
    private _elementRef: ElementRef,
    private _renderer: Renderer2,
    theme: LyTheme2,
    private changeDetectorRef: ChangeDetectorRef,
    ngZone: NgZone,
    public _coreStyles: LyCoreStyles,
    private _focusState: LyFocusState,
    private _styleRenderer: StyleRenderer,
    platform: Platform
  ) {
    super(theme, ngZone, platform);
    this._triggerElement = this._elementRef;
    this._rippleConfig = {
      centered: true,
      radius: 'containerSize',
      percentageToIncrease: 150
    };
    _renderer.addClass(_elementRef.nativeElement, radioGroup.classes.radio);
  }

  ngOnInit() {
    if (this.radioGroup) {
      // Copy name from parent radio group
      this.name = this.radioGroup.name;
    }
    if (!this.color) {
      this.color = this.radioGroup.color || DEFAULT_COLOR;
    }
  }

  ngAfterViewInit() {
    this._rippleContainer = this._radioContainer;

    // set default disable ripple
    if (this.disableRipple == null) {
      this.disableRipple = DEFAULT_DISABLE_RIPPLE;
    }
    const focusState = this._focusState.listen(this._input, this._elementRef);
    if (focusState) {
      focusState.subscribe((event) => {
        if (event === 'keyboard') {
          this._renderer.addClass(this._elementRef.nativeElement, this.classes.onFocusByKeyboard);
        } else if (event == null) {
          this._renderer.removeClass(this._elementRef.nativeElement, this.classes.onFocusByKeyboard);
        }
      });
    }
  }

  _markForCheck() {
    this.changeDetectorRef.markForCheck();
  }

  ngOnDestroy() {
    this._focusState.unlisten(this._elementRef);
    this._removeRippleEvents();
  }

  _onInputChange(event: any) {
    event.stopPropagation();
    this.radioGroup._updateCheckFromValue(this.value);
    this.radioGroup._touch();
    this._addAnim();
  }

  private _addAnim() {
    if (!this._animClass) {
      this._renderer.addClass(this._elementRef.nativeElement, this.classes._animations);
      this._animClass = this.classes._animations;
    }
  }

  _onInputClick(event: Event) { event.stopPropagation(); }

  _setCheckedToFalsy() {
    this.checked = false;
  }

}

@NgModule({
  imports: [CommonModule, FormsModule, LyCommonModule],
  exports: [LyRadioGroup, LyRadio],
  declarations: [LyRadioGroup, LyRadio],
})
export class LyRadioModule { }


text:
require "json"
require "typhoeus"

module RevisioneerRails
  class Deployment < Struct.new(:sha, :deployed_at, :messages)
    def self.load page = 1, limit = 20
      url = ::RevisioneerRails.config.url + "/deployments"
      request = Typhoeus::Request.new(
        url,
        method: :get,
        headers: { "API-TOKEN" => ::RevisioneerRails.config.api_token }
      )
      response = request.run
      json = ::JSON.parse response.body

      json.map { |deploy_data|
        self.new(deploy_data["sha"], Time.parse(deploy_data["deployed_at"]), deploy_data["messages"])
      }
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
package hbone

import (
	"context"
	"crypto/tls"
	"fmt"
	"io"
	"net"
	"net/http"
	"strings"
	"sync"
	"time"

	"golang.org/x/net/http2"
	"golang.org/x/net/proxy"

	"istio.io/istio/security/pkg/pki/util"
	istiolog "istio.io/pkg/log"
)

var log = istiolog.RegisterScope("hbone", "", 0)

// Config defines the configuration for a given dialer. All fields other than ProxyAddress are optional
type Config struct {
	// ProxyAddress defines the address of the HBONE proxy we are connecting to
	ProxyAddress string
	Headers      http.Header
	TLS          *tls.Config
}

type Dialer interface {
	proxy.Dialer
	proxy.ContextDialer
}

// NewDialer creates a Dialer that proxies connections over HBONE to the configured proxy.
func NewDialer(cfg Config) Dialer {
	var transport *http2.Transport
	if cfg.TLS != nil {
		transport = &http2.Transport{
			TLSClientConfig: cfg.TLS,
		}
	} else {
		transport = &http2.Transport{
			// For h2c
			AllowHTTP: true,
			DialTLS: func(network, addr string, cfg *tls.Config) (net.Conn, error) {
				return net.Dial(network, addr)
			},
		}
	}
	return &dialer{
		cfg:       cfg,
		transport: transport,
	}
}

type dialer struct {
	cfg       Config
	transport *http2.Transport
}

// DialContext connects to `address` via the HBONE proxy.
func (d *dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
	if network != "tcp" {
		return net.Dial(network, address)
	}
	// TODO: use context
	c, s := net.Pipe()
	err := d.proxyTo(s, d.cfg, address)
	if err != nil {
		return nil, err
	}
	return c, nil
}

func (d dialer) Dial(network, address string) (c net.Conn, err error) {
	return d.DialContext(context.Background(), network, address)
}

func (d *dialer) proxyTo(conn io.ReadWriteCloser, req Config, address string) error {
	t0 := time.Now()

	url := "http://" + req.ProxyAddress
	if req.TLS != nil {
		url = "https://" + req.ProxyAddress
	}
	// Setup a pipe. We could just pass `conn` to `http.NewRequest`, but this has a few issues:
	// * Less visibility into i/o
	// * http will call conn.Close, which will close before we want to (finished writing response).
	pr, pw := io.Pipe()
	r, err := http.NewRequest(http.MethodConnect, url, pr)
	if err != nil {
		return fmt.Errorf("new request: %v", err)
	}
	r.Host = address

	// Initiate CONNECT.
	log.Infof("initiate CONNECT to %v via %v", r.Host, url)

	resp, err := d.transport.RoundTrip(r)
	if err != nil {
		return fmt.Errorf("round trip: %v", err)
	}
	var remoteID string
	if resp.TLS != nil && len(resp.TLS.PeerCertificates) > 0 {
		ids, _ := util.ExtractIDs(resp.TLS.PeerCertificates[0].Extensions)
		if len(ids) > 0 {
			remoteID = ids[0]
		}
	}
	log.WithLabels("host", r.Host, "remote", remoteID).Info("CONNECT established")
	go func() {
		defer conn.Close()
		defer resp.Body.Close()

		wg := sync.WaitGroup{}
		wg.Add(1)
		go func() {
			// handle upstream (hbone server) --> downstream (app)
			copyBuffered(conn, resp.Body, log.WithLabels("name", "body to conn"))
			wg.Done()
		}()
		// Copy from conn into the pipe, which will then be sent as part of the request
		// handle upstream (hbone server) <-- downstream (app)
		copyBuffered(pw, conn, log.WithLabels("name", "conn to pipe"))

		wg.Wait()
		log.Info("stream closed in ", time.Since(t0))
	}()

	return nil
}

// TLSDialWithDialer is an implementation of tls.DialWithDialer that accepts a generic Dialer
func TLSDialWithDialer(dialer Dialer, network, addr string, config *tls.Config) (*tls.Conn, error) {
	return tlsDial(context.Background(), dialer, network, addr, config)
}

func tlsDial(ctx context.Context, netDialer Dialer, network, addr string, config *tls.Config) (*tls.Conn, error) {
	rawConn, err := netDialer.DialContext(ctx, network, addr)
	if err != nil {
		return nil, err
	}

	colonPos := strings.LastIndex(addr, ":")
	if colonPos == -1 {
		colonPos = len(addr)
	}
	hostname := addr[:colonPos]

	if config == nil {
		config = &tls.Config{MinVersion: tls.VersionTLS12}
	}
	// If no ServerName is set, infer the ServerName
	// from the hostname we're connecting to.
	if config.ServerName == "" {
		// Make a copy to avoid polluting argument or default.
		c := config.Clone()
		c.ServerName = hostname
		config = c
	}

	conn := tls.Client(rawConn, config)
	if err := conn.HandshakeContext(ctx); err != nil {
		_ = rawConn.Close()
		return nil, err
	}
	return conn, nil
}


text: Docker PG 9.5.2 with uuid-ossp and btree_gist


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TravelAgent.Web.dataDeal
{
    public partial class ValidateOrModifyMobile : TravelAgent.Web.UI.mBasePage
    {
        private static readonly TravelAgent.BLL.Club ClubBll = new TravelAgent.BLL.Club();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["mobile"] != null)
            {
                string strmobile = Request["mobile"];
                string strcode = Request["validateCode"];
                int clubid = Convert.ToInt32(Request["clubid"]);
                int count = ClubBll.GetCount("clubMobile='" + strmobile + "' and id<>" + clubid);
                if (count > 0)
                {
                    Response.Write("已经被注册");
                    Response.End();
                }
                if (strcode.Equals(TravelAgent.Tool.CookieHelper.GetCookieValue("smsyzm")))
                {
                    string strsql = "update Club set clubMobile='" + strmobile + "',mobileIsValid=1 where Id="+clubid;
                    //Access
                    //if (TravelAgent.Tool.DbHelperOleDb.ExecuteSql(strsql) > 0)
                    //SQL
                    if (TravelAgent.Tool.DbHelperSQL.ExecuteSql(strsql) > 0)
                    {
                        Response.Write("success");
                        Response.End();
                    }
                    else
                    {
                        Response.Redirect("/Opr.aspx?t=error&msg=opr");
                    }
                }
                else
                {
                    Response.Write("验证码");
                    Response.End();
                }
            }
        }
    }
}


text:
var mousePos = require('../data/mousePos');

var scene = document.getElementById('scene');
var svg = function (name) { return document.createElementNS('http://www.w3.org/2000/svg', name); };
var arrowsCount = 1000;
var arrows = createArrows(arrowsCount);

var g = svg('g');
scene.appendChild(g);

var points = arrows.map(function (arrow) {
  var path = svg('path');
  path.setAttributeNS(null, 'marker-end', 'url(#ArrowTriangle)');
  path.setAttributeNS(null, 'stroke', 'deepskyblue');
  g.appendChild(path);
  var source = arrow.from;
  var dest = arrow.to;

  var fromSeg = path.createSVGPathSegMovetoAbs(source.x, source.y);
  var toSeg = path.createSVGPathSegLinetoAbs(dest.x, dest.y);
  path.pathSegList.appendItem(fromSeg);
  path.pathSegList.appendItem(toSeg);
  return {
    model: arrow,
    source: source,
    dest: dest,
    fromSeg: fromSeg,
    toSeg: toSeg
  };
});

render();

function render() {
  requestAnimationFrame(render);
  points.forEach(move);
}

function move(point) {
  point.model.move(mousePos);
  point.fromSeg.x = point.source.x;
  point.fromSeg.y = point.source.y;
  point.toSeg.x = point.dest.x;
  point.toSeg.y = point.dest.y;
}

function createArrows(n) {
  var ArrowModel = require('../data/arrowModel');

  var arrows = [];
  for (var i = 0; i < n; ++i) {
    var arrow = new ArrowModel();
    arrows.push(arrow);
  }

  return arrows;
}


text:
# Import blockchain library
from blockchain import statistics

# Original block reward for miners was 50 BTC
start_block_reward = 50
# 210000 is around every 4 years with a 10 minute block interval
reward_interval = 210000

def max_money(a):
    multiplier = 1
    if a == "Satoshis":
        multiplier = 10**8

    # 50 BTC = 50 0000 0000 Satoshis
    current_reward = 50 * multiplier
    total = 0

    while current_reward > 0:
        total += reward_interval * current_reward
        current_reward /= 2
    return total

# get the stats object
stats = statistics.get()

btcmined = stats.btc_mined / 10000

percent_mined = (btcmined / max_money("Bitcoin")) * 100

print("Total SAT to ever be created:", max_money("Satoshis"), "Satoshis")
print("Total BTC to ever be created:", max_money("Bitcoin"), "Bitcoin")

print("Bitcoin Mined: %s (*10000)\n" % stats.btc_mined)

print("Percent bitcoins mined: %s", percent_mined)


text:
namespace base {
class WaitableEvent;
}

namespace webkit {
struct WebPluginInfo;
}

namespace content {

class BrowserContext;

class CONTENT_EXPORT PluginDataRemover {
 public:
  static PluginDataRemover* Create(content::BrowserContext* browser_context);
  virtual ~PluginDataRemover() {}

  // Starts removing plug-in data stored since |begin_time|.
  virtual base::WaitableEvent* StartRemoving(base::Time begin_time) = 0;

  // Returns a list of all plug-ins that support removing LSO data. This method
  // will use cached plugin data. Call PluginService::GetPlugins() if the latest
  // data is needed.
  static void GetSupportedPlugins(std::vector<webkit::WebPluginInfo>* plugins);
};

}  // namespace content

#endif  // CONTENT_PUBLIC_BROWSER_PLUGIN_DATA_REMOVER_H_


text:
package com.persinity.common.collection;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.util.HashSet;
import java.util.Set;

import org.jgrapht.DirectedGraph;
import org.jgrapht.EdgeFactory;

/**
 * @author Ivan Dachev
 */
@SuppressWarnings("unchecked")
public class TestGraphUtils {
    public static EdgeFactory<Integer, DirectedEdge<Integer, Integer>> TEST_EDGE_FACTORY = new EdgeFactory<Integer, DirectedEdge<Integer, Integer>>() {
        @Override
        public DirectedEdge<Integer, Integer> createEdge(final Integer sourceVertex, final Integer targetVertex) {
            return new DirectedEdge<>(sourceVertex, targetVertex);
        }
    };

    public static <V, E> void addVertexes(final DirectedGraph<V, E> graph, final V... vs) {
        for (V v : vs) {
            graph.addVertex(v);
        }
    }

    public static <V, E> void verifyVertexes(final DirectedGraph<V, E> graph, final V... vs) {
        assertEquals(vs.length, graph.vertexSet().size());
        for (V v : vs) {
            assertTrue(graph.containsVertex(v));
        }
    }

    public static <V, E extends DirectedEdge<V, V>> void verifyDirectedEdges(final DirectedGraph<V, E> graph,
            final V... evs) {
        assertEquals(evs.length, graph.edgeSet().size() * 2);
        for (int i = 0; i < evs.length; i += 2) {
            assertTrue(graph.containsEdge((E) new DirectedEdge<V, V>(evs[i], evs[i + 1])));
        }
    }

    public static <V, E extends DirectedEdge<V, V>> void addDirectedEdges(final DirectedGraph<V, E> graph,
            final V... evs) {
        for (int i = 0; i < evs.length; i += 2) {
            final V srcV = evs[i];
            final V dstV = evs[i + 1];
            graph.addEdge(srcV, dstV, (E) new DirectedEdge<V, V>(srcV, dstV));
        }
    }

    public static <T> Set<DirectedEdge<T, T>> buildDirectedEdgeSet(T... vertices) {
        Set<DirectedEdge<T, T>> result = new HashSet<>();
        for (int i = 0; i < vertices.length; i += 2) {
            final T srcV = vertices[i];
            final T dstV = vertices[i + 1];
            result.add(new DirectedEdge<>(srcV, dstV));
        }
        return result;
    }

}


text:
module Rsbe
  module Client
    class SearchResults
      def initialize(api_response)
        @api_response = api_response
        # init json
        json
      end

      def success?
        @api_response.status == 200
      end

      def num_found
        response['numFound']
      end

      def results
        @results ||= urls.collect {|u| Rsbe::Client.find(u)}
      end

      private

      def response
        @response ||= json['response']
      end

      def json
        @json ||= JSON.parse(@api_response.body)
      end

      def docs
        @docs ||= response['docs']
      end

      def urls
        @urls ||= docs.collect {|d| d['url']}
      end
    end
  end
end


text:
package io.skysail.server.forms.test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;

import java.util.Date;
import java.util.List;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.restlet.Request;
import org.restlet.data.Form;

import io.skysail.api.doc.ApiMetadata;
import io.skysail.api.links.LinkRelation;
import io.skysail.core.app.SkysailApplicationService;
import io.skysail.core.resources.SkysailServerResource;
import io.skysail.domain.Entity;
import io.skysail.domain.GenericIdentifiable;
import io.skysail.domain.html.InputType;
import io.skysail.server.domain.jvm.ResourceType;
import io.skysail.server.forms.FormField;

public class FormFieldTest {

    public String test;

    @io.skysail.domain.html.Field
    public String simpleString;

    @io.skysail.domain.html.Field
    public Date simpleDate;

    @io.skysail.domain.html.Field(inputType = InputType.TEXTAREA)
    public String textarea;

    @io.skysail.domain.html.Field
    public List<GenericIdentifiable> listCollection;

    @io.skysail.domain.html.Field
    public Set<GenericIdentifiable> setCollection;

    private SkysailServerResource<?> resource;

    private Request theRequest = Mockito.mock(Request.class);

    private org.restlet.data.Reference originalRef;

    private Form form;

    @Before
    public void setUp() {
        resource = new SkysailServerResource<Entity>() {

            @Override
            public Entity getEntity() {
                return null;
            }

            @Override
            public LinkRelation getLinkRelation() {
                return null;
            }

            @Override
            public ResourceType getResourceType() {
                return null;
            }

            @Override
            public Request getRequest() {
                return theRequest;
            }

			@Override
			public ApiMetadata getApiMetadata() {
				return null;
			}
        };
        form = new Form();
        originalRef = Mockito.mock(org.restlet.data.Reference.class);
        when(theRequest.getOriginalRef()).thenReturn(originalRef);

        when(originalRef.hasQuery()).thenReturn(true);
        when(originalRef.getQuery()).thenReturn(form.getQueryString());
        when(originalRef.getQueryAsForm()).thenReturn(form);
        when(originalRef.getHierarchicalPart()).thenReturn("");
    }

    @Test
    public void simple_String_setup_works() {
        FormField formField = createFormField("simpleString");

        assertThat(formField.getId()).isEqualTo("io.skysail.server.forms.test.FormFieldTest|simpleString");
        //assertThat(formField.getName()).isSameAs("simpleString");
        assertThat(formField.getInputType().name()).isSameAs(InputType.TEXT.name());
        //        assertThat(formField.getEntityClass(),is(("")));
        assertThat(formField.getType().getName()).isSameAs(String.class.getName());
        assertThat(formField.getEntityType().getTypeName()).isSameAs(String.class.getName());
    }

    @Test
    public void simple_Date_setup_works() {
        FormField formField = createFormField("simpleDate");

        assertThat(formField.getId()).isEqualTo("io.skysail.server.forms.test.FormFieldTest|simpleDate");
       // assertThat(formField.getName()).isSameAs("simpleDate");
        assertThat(formField.getInputType().name()).isSameAs(InputType.TEXT.name());
        assertThat(formField.getType().getName()).isSameAs(Date.class.getName());
        assertThat(formField.getEntityType().getTypeName()).isSameAs(Date.class.getName());
    }

    @Test
    public void textarea_setup_works() {
        FormField formField = createFormField("textarea");
        assertThat(formField.getInputType().name()).isSameAs(InputType.TEXTAREA.name());
        assertThat(formField.getType().getName()).isSameAs(String.class.getName());
    }

    @Test
    public void listCollection_setup_works() {
        FormField formField = createFormField("listCollection");
        assertThat(formField.getInputType().name()).isSameAs(InputType.TEXT.name());
        assertThat(formField.getType().getName()).isSameAs(List.class.getName());
        assertThat(formField.getEntityType().getTypeName()).isSameAs(GenericIdentifiable.class.getName());
    }

    @Test
    public void setCollection_setup_works() {
        FormField formField = createFormField("setCollection");
        assertThat(formField.getInputType().name()).isSameAs(InputType.TEXT.name());
        assertThat(formField.getType().getName()).isSameAs(Set.class.getName());
    }

    private FormField createFormField(String name) {
        try {
            SkysailApplicationService service = Mockito.mock(SkysailApplicationService.class);
            return new FormField(FormFieldTest.class.getField(name), resource.getCurrentEntity(), service);
        } catch (NoSuchFieldException | SecurityException e) {
            throw new RuntimeException(e);
        }
    }

//    @Test
//    public void test_is_not_a_selectionProvider() throws Exception {
//        Field field = FormFieldTest.class.getField("test");
//        FormField formField = new FormField(field, resource.getCurrentEntity(), null);
//        assertThat(formField.isSelectionProvider(), org.hamcrest.Matchers.is(false));
//    }
//
//    @Test
//    public void testReference_is_selectionProvider() throws Exception {
//        Field field = FormFieldTest.class.getField("a");
//        FormField formField = new FormField(field, resource.getCurrentEntity(), null);
//        assertThat(formField.isSelectionProvider(), is(true));
//    }

    // @Test
    // public void testReference_gets_selectionOptions() throws Exception {
    // Field field = FormFieldTest.class.getField("a");
    // FormField formField = new FormField(field, resource);
    // assertThat(formField.getSelectionProviderOptions().size(), is(1));
    // }

    // @Test
    // public void toggle_sort_link_toggles_from_empty_to_ASC() throws Exception
    // {
    // Field field = FormFieldTest.class.getField("a");
    // Mockito.when(originalRef.hasQuery()).thenReturn(false);
    //
    // FormField formField = new FormField(field, resource.getCurrentEntity());
    //
    // assertThat(formField.getToggleSortLink(), is("?_s=a%3BASC"));
    //
    // }
    //
    // @Test
    // public void toggle_sort_link_toggles_from_ASC_to_DESC() throws Exception
    // {
    // Field field = FormFieldTest.class.getField("a");
    // form.add(new Parameter("_s", "a;ASC"));
    //
    // FormField formField = new FormField(field, resource.getCurrentEntity());
    //
    // assertThat(formField.getToggleSortLink(), is("?_s=a%3BDESC"));
    // }

    // @Test
    // public void toggle_sort_link_toggles_from_DESC_to_empty() throws
    // Exception {
    // Field field = FormFieldTest.class.getField("a");
    // form.add(new Parameter("_s", "a;DESC"));
    //
    // Mockito.when(originalRef.hasQuery()).thenReturn(true);
    // Mockito.when(originalRef.getQuery()).thenReturn(form.getQueryString());
    // Mockito.when(originalRef.getQueryAsForm()).thenReturn(form);
    //
    // FormField formField = new FormField(field, resource.getCurrentEntity());
    //
    // assertThat(formField.getToggleSortLink(), is(""));
    // }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace DesertOctopus.Utilities
{
    /// <summary>
    /// Helper class for Queryable MethodInfo
    /// </summary>
    internal static class QueryableMih
    {
        /// <summary>
        /// Calls Queryable.AsQueryable
        /// </summary>
        /// <param name="elementType">Type used for AsQueryable</param>
        /// <returns>The method info for Queryable.AsQueryable</returns>
        public static MethodInfo AsQueryable(Type elementType)
        {
            return typeof(Queryable).GetMethod(nameof(Queryable.AsQueryable), BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(IEnumerable<>).MakeGenericType(elementType) }, new ParameterModifier[0]);
        }
    }
}


text:
<?php

namespace ItePHP\Action;

use ItePHP\Core\Response;
use ItePHP\Core\ExecuteActionEvent;
use ItePHP\Core\Request;
use Pactum\ConfigContainer;

/**
 * Event for support authenticate user
 *
 * @author Michal Tomczak (michal.tomczak@itephp.com)
 */
class AuthenticateEvent{

	/**
	 *
	 * @var int
	 */
	private $maxTime=0;

    /**
     * AuthenticateEvent constructor.
     * @param ConfigContainer $config
     */
	public function __construct(ConfigContainer $config){
        /**
         * @var ConfigContainer[] $authenticate
         */
		$authenticate=$config->getObject('authenticate');
        $this->maxTime=$authenticate->getValue('max-time');

	}

	/**
	 * Detect config authenticate.
	 *
	 * @param ExecuteActionEvent $event
	 */
	public function onExecuteAction(ExecuteActionEvent $event){
		$request=$event->getRequest();
		$authenticate=$request->getConfig()->getObject('authenticate');
		if($authenticate){
			$this->execute($event,$authenticate);
		}
	}

	/**
	 * Check authenticate.
	 *
	 * @param ExecuteActionEvent $event
	 * @param ConfigContainer $config
	 * @throws ValueNotFoundException
	 * @throws PermissionDeniedException
	 */
	private function execute(ExecuteActionEvent $event,$config){
		$request=$event->getRequest();
		$session=$request->getSession();

		try{
			$session->get('authenticate.user_id');
			if($this->maxTime>0){

				if($session->get('authenticate.epoch')<time()){ //deprecated session
					$session->clear();
					throw new ValueNotFoundException('authenticate.epoch');
				}
				$session->set('authenticate.epoch',time()+$this->maxTime);
			}

			if($config->getValue('auth-redirect')!==false){
				$response=$this->createResponseRedirect($config->getValue('auth-redirect'),$request);
				$event->setResponse($response);

			}
		}
		catch(ValueNotFoundException $e){
			if($config->getValue('unauth-redirect')!==false){
				$response=$this->createResponseRedirect($config->getValue('unauth-redirect'),$request);
				$event->setResponse($response);
			}
			else if($config->getValue('auth-redirect')!==false){
				//ignore
			}
			else{
				throw new PermissionDeniedException();
			}
		}

	}

	/**
	 * Check authenticate.
	 *
	 * @param string $redirect
	 * @param Request $request
	 * @return Response
	 */
	private function createResponseRedirect($redirect,Request $request){
		$response=new Response();
		if($request->isAjax()){
			$response->setStatusCode(401);
			$response->setHeader('X-Location',$redirect);
		}
		else{
			$response->redirect($redirect);
		}
		return $response;
	}

}


text:
package amery.collection;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;

public class AlgorithmExample {

    public static void main(String[] args) {
        LinkedList link = new LinkedList();
        link.add(new Integer(10));
        link.add(new Integer(35));
        link.add(new Integer(23));
        link.add(new Integer(54));
        link.add(new Integer(36));
        Comparator cmp = Collections.reverseOrder();
        Collections.sort(link, cmp);
        Iterator it = link.iterator();
        System.out.println("逆序排序的列表为: ");
        while (it.hasNext()) {
            System.out.println(it.next());
        }
        System.out.println("给定列表中的最大值为:" + Collections.max(link));
        System.out.println("给定列表中的最小值为:" + Collections.min(link));
    }
}


text:
<title>Farrago HOWTO Guides</title>
<link rel="stylesheet" type="text/css" href="../stylesheet.css" />

Farrago HOWTO Guides

For users:

Accessing metadata managed by MDR

Configuring Farrago repository storage

For developers:

Getting started

Setting up a private branch

Implementing Fennel execution streams

Adding extended instructions to the Fennel calculator

      End $Id$


text:
// ============================================================================
// ==                   Copyright (c) 2015, Smirnov Denis                    ==
// ==                  See license.txt for more information                  ==
// ============================================================================
#pragma once
#ifndef World_h__
#define World_h__

#include <unordered_map>
#include <glm/glm.hpp>
#include "Sector.h"
#include "../Graphic/Render/RenderSector.h"
#include "SectorLoader.h"
#include "Player.h"
#include "Timer.h"

namespace std
{
  template <>
  struct hash<glm::ivec3>
  {
    std::size_t operator()(glm::ivec3 const& v) const
    {
      std::size_t h1 = std::hash<int>()(v.x);
      std::size_t h2 = std::hash<int>()(v.y);
      std::size_t h3 = std::hash<int>()(v.z);
      return ((h1 ^ (h2 << 1)) >> 1) ^ (h3 << 1);
    }
  };
}

class World
{
public:
  World();
  ~World();

  void LoadSector(const glm::ivec3 &pos);

  void UnloadSector(const glm::ivec3 &pos);

  void Update();

  void Draw();

  void AddPlayer(Player &player);

  /// Вернуть позицию сектора по мировой позиции.
  glm::ivec3 GetSectorPos(const glm::vec3 &pos);

private:

  struct WorldSector
  {
    WorldSector(const glm::ivec3 &pos)
      : sector(pos)
    {};
    Sector sector;
    unsigned int refCount = 1;
    Timer timer;

  private:
    WorldSector(const WorldSector &) = delete;
    WorldSector& operator=(const WorldSector &) = delete;
  };

  std::unordered_map<glm::ivec3, WorldSector> mMap;

  struct WorldPlayer
  {
    WorldPlayer(Player &p, World &world)
      : player(p), sectorLoader(world, world.GetSectorPos(p.GetPosition()), 5)
    {}
    Player &player;
    SectorLoader sectorLoader;
  private:
    WorldPlayer(const WorldPlayer &) = delete;
    WorldPlayer& operator=(const WorldPlayer &) = delete;
  };

  std::list<WorldPlayer> mPlayers;

private:
  World(const World &) = delete;
  World& operator=(const World &) = delete;

};

#endif // World_h__


text:
import subprocess
import os
import ccmlib.repository

from ccmlib.common import is_win, get_version_from_build

class DTestConfig:
    def __init__(self):
        self.use_vnodes = True
        self.use_off_heap_memtables = False
        self.num_tokens = -1
        self.data_dir_count = -1
        self.force_execution_of_resource_intensive_tests = False
        self.skip_resource_intensive_tests = False
        self.cassandra_dir = None
        self.cassandra_version = None
        self.cassandra_version_from_build = None
        self.delete_logs = False
        self.execute_upgrade_tests = False
        self.execute_upgrade_tests_only = False
        self.disable_active_log_watching = False
        self.keep_test_dir = False
        self.enable_jacoco_code_coverage = False
        self.jemalloc_path = find_libjemalloc()

    def setup(self, request):
        self.use_vnodes = request.config.getoption("--use-vnodes")
        self.use_off_heap_memtables = request.config.getoption("--use-off-heap-memtables")
        self.num_tokens = request.config.getoption("--num-tokens")
        self.data_dir_count = request.config.getoption("--data-dir-count-per-instance")
        self.force_execution_of_resource_intensive_tests = request.config.getoption("--force-resource-intensive-tests")
        self.skip_resource_intensive_tests = request.config.getoption("--skip-resource-intensive-tests")
        cassandra_dir = request.config.getoption("--cassandra-dir") or request.config.getini("cassandra_dir")
        if cassandra_dir is not None:
            self.cassandra_dir = os.path.expanduser(cassandra_dir)
        self.cassandra_version = request.config.getoption("--cassandra-version")

        self.cassandra_version_from_build = self.get_version_from_build()

        self.delete_logs = request.config.getoption("--delete-logs")
        self.execute_upgrade_tests = request.config.getoption("--execute-upgrade-tests")
        self.execute_upgrade_tests_only = request.config.getoption("--execute-upgrade-tests-only")
        self.disable_active_log_watching = request.config.getoption("--disable-active-log-watching")
        self.keep_test_dir = request.config.getoption("--keep-test-dir")
        self.enable_jacoco_code_coverage = request.config.getoption("--enable-jacoco-code-coverage")

    def get_version_from_build(self):
        # There are times when we want to know the C* version we're testing against
        # before we do any cluster. In the general case, we can't know that -- the
        # test method could use any version it wants for self.cluster. However, we can
        # get the version from build.xml in the C* repository specified by
        # CASSANDRA_VERSION or CASSANDRA_DIR.
        if self.cassandra_version is not None:
            ccm_repo_cache_dir, _ = ccmlib.repository.setup(self.cassandra_version)
            return get_version_from_build(ccm_repo_cache_dir)
        elif self.cassandra_dir is not None:
            return get_version_from_build(self.cassandra_dir)

# Determine the location of the libjemalloc jar so that we can specify it
# through environment variables when start Cassandra.  This reduces startup
# time, making the dtests run faster.
def find_libjemalloc():
    if is_win():
        # let the normal bat script handle finding libjemalloc
        return ""

    this_dir = os.path.dirname(os.path.realpath(__file__))
    script = os.path.join(this_dir, "findlibjemalloc.sh")
    try:
        p = subprocess.Popen([script], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        if stderr or not stdout:
            return "-"  # tells C* not to look for libjemalloc
        else:
            return stdout
    except Exception as exc:
        print("Failed to run script to prelocate libjemalloc ({}): {}".format(script, exc))
        return ""


text:
package org.apache.wink.itest.cache;

import javax.xml.bind.annotation.XmlRegistry;

@XmlRegistry
public class ObjectFactory {

    public NewsStory createNewsStory() {
        return new NewsStory();
    }

}


text:
/*
Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.2.0
Version: 1.4.0
Author: Sean Ngu
Website: http://www.seantheme.com/color-admin-v1.4/
*/

.btn.btn-theme {
    background: #348fe2;
    border-color: #348fe2;
    color: #fff;
}
.btn.btn-theme:hover,
.btn.btn-theme:focus {
    background: #2a72b5;
    border-color: #2a72b5;
}
.header.navbar .navbar-nav > li.active > a,
.header.navbar .navbar-nav > li > a:hover,
.header.navbar .navbar-nav > li > a:focus,
.header.navbar.navbar-default .navbar-nav > li.active > a,
.header.navbar.navbar-default .navbar-nav > li > a:hover,
.header.navbar.navbar-default .navbar-nav > li > a:focus,
.header.navbar.navbar-transparent .navbar-nav > li.active > a,
.header.navbar.navbar-transparent .navbar-nav > li > a:hover,
.header.navbar.navbar-transparent .navbar-nav > li > a:focus,
.header.navbar.navbar-inverse .navbar-nav > li.active > a,
.header.navbar.navbar-inverse .navbar-nav > li > a:hover,
.header.navbar.navbar-inverse .navbar-nav > li > a:focus,
.header.navbar.navbar-transparent.navbar-small .navbar-nav > li.active > a,
.header.navbar.navbar-transparent.navbar-small .navbar-nav > li > a:hover,
.header.navbar.navbar-transparent.navbar-small .navbar-nav > li > a:focus,
.text-theme,
.navbar-nav .dropdown-menu > li.active > a,
.navbar-nav .dropdown-menu > li > a:hover,
.navbar-nav .dropdown-menu > li > a:focus,
.pricing-table .price .price-number,
a {
    color: #348fe2;
}
a:hover,
a:focus {
    color: #2a72b5;
}
.pricing-table .highlight h3,
.pace-progress {
    background: #2a72b5;
}
.pricing-table .highlight .price {
    background: #348fe2;
}
.pace .pace-activity {
    border-top-color: #348fe2;
    border-left-color: #348fe2;
}
.brand-logo,
.footer .footer-brand-logo {
    border-color: #2F83CF #2a72b5 #1f5688;
}


text:
# Hello TypeScript Library Starter

A sample project for TypeScript Library Starter.

[![Build Status](https://travis-ci.org/tonysneed/hello-ts-lib-starter.svg?branch=master)](https://travis-ci.org/tonysneed/hello-ts-lib-starter)
[![Coverage Status](https://coveralls.io/repos/github/tonysneed/hello-ts-lib-starter/badge.svg?branch=master)](https://coveralls.io/github/tonysneed/hello-ts-lib-starter?branch=master)
[![Greenkeeper badge](https://badges.greenkeeper.io/tonysneed/hello-ts-lib-starter.svg)](https://greenkeeper.io/)

Docs published to: <https://tonysneed.github.io/hello-ts-lib-starter>

### Source

Using: **typescript-library-starter**
- GitHub Repo: <https://github.com/alexjoverm/typescript-library-starter>.
- Blog post: <https://dev.to/alexjoverm/write-a-library-using-typescript-library-starter>

### Customization

- Linting:
  + Copy tslint.json from angular project.
  + Install packages.

  ```
  npm i --save-dev codelyzer @angular/compiler @angular/core zone.js
  ```

  + Remove Prettier (conflicts with TSLint) by
    removing *precommit*, *lint-staged* from package.json
  + Update *lint* script in package.json to include --type-check.

  ```json
  "lint": "tslint --type-check -p tsconfig.json codeFrame 'src/**/*.ts'"
  ```

- Exports:
  + Add ts file with same name as project
  + Add exports for modules

  ```js
  export { HelloWorld } from './hello-world';
  export { ItalianHelloWorld } from './italian-hello-world';
  ```

- TypeScript:
  + Target es2015 in tsconfig.json.
  + Remove target with *dest: pkg.main* in rollup.config.js.
  + Remove *main* section in package.json.
  + Remove es5 suffix in *module* in package.json

- Update **.gitignore** from an Angular project.
  + Remove *.vscode* entry

- Debugging:
  + Add **launch.json** to **.vscode* folder for debugging Jest tests.

  ```json
  {
    "version": "0.2.0",
    "configurations": [
      {
        "name": "Tests",
        "type": "node",
        "request": "launch",
        "program": "${workspaceRoot}/node_modules/jest/bin/jest.js",
        "sourceMaps": true,
        "runtimeArgs": [
          "-i"
        ],
        "env": {
          "NODE_ENV": "development"
        },
        "outFiles": [
          "${workspaceRoot}/dist/**/*"
        ],
        "cwd": "${workspaceRoot}"
      }
    ]
  }
  ```

- Tasks:
  + Add **tasks.json** to **.vscode** folder for binding to keyboard shortcuts for
  *build*, *test* and *lint* tasks.

  ```json
  {
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "type": "npm",
            "script": "build",
            "presentation": {
                "reveal": "always"
            },
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "problemMatcher": [
                "$tsc"
            ]
        },
        {
            "label": "test",
            "type": "npm",
            "script": "test:watch",
            "presentation": {
                "reveal": "always"
            },
            "group": {
                "kind": "test",
                "isDefault": true
            }
        },
        {
            "taskName": "lint",
            "type": "shell",
            "command": "npm run lint",
            "problemMatcher": [
                "$tsc"
            ]
        }
    ]
  }
  ```

### Setup

- Open repo in [GitHub Desktop](https://desktop.github.com) and publish repo to GitHub.
  + Open in GitHub, copy the clone url.
  + Paste into the *url* property of *repository* in package.json.

- Link repo to [Travis CI](https://travis-ci.org) account.
 + Copy markdown for *Build Status* badge into README.md.

- Link repo to [Coveralls](https://coveralls.io) account.
  + Copy markdown for *Coverage Status* into README.md.

- Link repo to [Greenkeeper](https://greenkeeper.io) account.
  + Merge PR created by the Greenkeeper bot.
  + Add markdown for *Greenkeeper* badge to README.md.

 ### Docs

- Push or merge PR to master to publish docs.
  + Docs for this repo published to: <https://tonysneed.github.io/hello-ts-lib-starter>

- To locate generated docs, open repo on GitHub
  + Go to Settings for the repo, GitHub Pages section
  + Uses TypeDoc: http://typedoc.org

- Configure project to exclude tests from docs.
  + Update build script to add: `--exclude '**/*.spec.ts'`

- Use JavaDoc tags to document classes, methods, etc.
  + See http://typedoc.org/guides/doccomments/
  + Use jsdoc comments extension for VS Code: https://marketplace.visualstudio.com/items?itemName=stevencl.addDocComments
  + Example:

  ```js
  /**
  * Class representing a greeter.
  */
  export class HelloWorld {
    /**
    * Greet someone by name.
    * @param  {string} name
    * @returns A friendly greeting.
    */
    greet(name: string): string {
      return `Hello ${name}`;
    }
  }
  ```

### Workflow

- Create develop branch and push to origin
  + Leave master as the default branch

- Create feature branch: @feature/my-new-feature.
  + Push branch to origin - husky will run prepush (tests, bundling, docs, etc)
  + PR into develop
  + Travis will kick off a CI build.
  + Coveralls will perform a code coverage check.

- When code review has completed, squash into one commit and force push feature branch.
  + Force push feature branch: `git push -f origin`

- On GitHub, rebase PR into develop with "Rebase and merge" button
  + Travis CI will kick off a build

- When ready for release, merge develop into master
  + Create a release branch: @release/v1.0.0-beta1
  + Include issues/PR's in the release notes
  + Create or update CHANGELOG.md
  + Update the version in package.json
  + Publish to NPM: `npm publish --tag beta1` (omit tag for non-prerelease version)


text:
PlayState ={};
function hero(game,x,y) {
	//call Phaser.Sprite constructor
	Phaser.Sprite.call(this, game, x, y,'hero');
	this.anchor.set(0.5, 0.5);
	this.game.physics.enable(this);
	this.body.collideWorldBounds=true;
	this.animations.add('stop', [0]);
	this.animations.add('run', [1, 2], 8, true);//8fps looped
	this.animations.add('jump', [3]);
	this.animations.add('fall', [4]);
}
// inherit from Phraser.Sprite
hero.prototype = Object.create(Phaser.Sprite.prototype);
hero.prototype.constructor= hero;

hero.prototype.move=function(direction){
	const SPEED = 200;
	this.body.velocity.x=direction * SPEED;
	if (this.body.velocity.x < 0) {
		this.scale.x = -1;
	}
	else if (this.body.velocity.x > 0) {
		this.scale.x =1;
	}
};

hero.prototype.jump=function(){
	const JUMP_SPEED= 600;
	let canJump=this.body.touching.down;

	if (canJump){
	this.body.velocity.y= -JUMP_SPEED;
	}
	return canJump;
};

hero.prototype.bounce=function(){
	const BOUNCE_SPEED =200;
	this.body.velocity.y = -BOUNCE_SPEED;
}

hero.prototype._getAnimationName=function(){
	let name= 'stop';// default animation

	//jumping
	if(this.body.velocity.y < 0) {
		name = 'jump';
	}
	//falling
	else if (this.body.velocity.y >= 0 && !this.body.touching.down) {
		name = 'fall';
	}
	else if (this.body.velocity.x !== 0 && this.body.touching.down) {
		name = 'run';
	}

	return name;
};

hero.prototype.update=function(){
	//update sprite animation, if it needs changing
	let animationName=this._getAnimationName();
	if(this.animations.name !==animationName) {
		this.animations.play(animationName);
	}
};

function Spider(game, x, y) {
	Phaser.Sprite.call(this, game, x, y, 'spider');

	//anchor
	this.anchor.set(0.5);
	//animation
	this.animations.add('crawl', [0, 1, 2], 8, true);
	this.animations.add('die', [0, 4, 0, 4, 0, 4, 3, 3, 3, 3, 3, 3], 12);
	this.animations.play('crawl');

	//physics properties
	this.game.physics.enable(this);
	this.body.collideWorldBounds=true;
	this.body.velocity.x=Spider.SPEED;
}

Spider.SPEED =100;

//inherit from Phaser.Sprite
Spider.prototype=Object.create(Phaser.Sprite.prototype);
Spider.prototype.constructor=Spider;

Spider.prototype.update=function(){
	//check against walls and reverse direction if necessary
	if (this.body.touching.right || this.body.blocked.right){
		this.body.velocity.x = -Spider.SPEED; //turn left
	}
	else if (this.body.touching.left || this.body.blocked.left){
		this.body.velocity.x = Spider.SPEED;//turn right
	}
};

Spider.prototype.die = function(){
	this.body.enable = false;

	this.animations.play('die').onComplete.addOnce(function(){
		this.kill();
	}, this);
}

const LEVEL_COUNT =3;

PlayState.init=function(data){
	this.game.renderer.renderSession.roundPixels=true;
	this.keys=this.game.input.keyboard.addKeys({
		left:Phaser.KeyCode.LEFT,
		right:Phaser.KeyCode.RIGHT,
		up:Phaser.KeyCode.UP
	});
	this.keys.up.onDown.add(function (){
	    let didJump=this.hero.jump();
	    if (didJump){
	    	this.sfx.jump.play();
		}
	}, this);
	this.coinPickupCount =0;
	this.hasKey = false;
	this.level = (data.level || 0) % LEVEL_COUNT;
};

//load game assests here
PlayState.preload = function() {
	this.game.load.json('level:0', 'data/level00.json');
	this.game.load.json('level:1', 'data/level01.json');
	this.game.load.json('leve1:2', 'data/level02.json');
	this.game.load.image('background','images/background.png');
	this.game.load.image('ground', 'images/ground.png');
	this.game.load.image('block:8x1', 'images/block_8x1.png');
	this.game.load.image('block:6x1', 'images/block_6x1.png');
	this.game.load.image('block:4x1', 'images/block_4x1.png');
	this.game.load.image('block:2x1', 'images/block_2x1.png');
	this.game.load.image('block:1x1', 'images/block_1x1.png');
	this.game.load.spritesheet('hero', 'images/hero.png', 36, 42);
	this.game.load.audio('sfx:jump', 'audio/jump.wav');
	this.game.load.spritesheet('coin','images/coin_animated.png',22,22);
	this.game.load.audio('sfx:coin', 'audio/coin.wav');
	this.game.load.image('icon:coin', 'images/coin_icon.png');
	this.game.load.image('font:numbers', 'images/numbers.png');
	this.game.load.image('invisible-wall', 'images/invisible_wall.png');
	this.game.load.spritesheet('spider','images/spider.png', 42, 32);
	this.game.load.audio('sfx:stomp', 'audio/stomp.wav');
	this.game.load.spritesheet('door', 'images/door.png', 42,66);
	this.game.load.image('key', 'images/key.png');
	this.game.load.audio('sfx:key', 'audio/key.wav');
	this.game.load.audio('sfx:door', 'audio/door.wav');
	this.game.load.spritesheet('icon:key', 'images/key_icon.png', 34, 30);

}

//create game entities and set up world here
PlayState.create= function(){
	//create sound entities
	this.sfx={
		key: this.game.add.audio('sfx:key'),
		door: this.game.add.audio('sfx:door'),
		jump:this.game.add.audio('sfx:jump'),
		coin:this.game.add.audio('sfx:coin'),
		stomp: this.game.add.audio('sfx:stomp')
	};
   this.game.add.image(0,0,'background');
   this._loadLevel(this.game.cache.getJSON(`level:${this.level}`));
   this._createHud();
};

PlayState.update= function(){
	this._handleCollisions();
	this._handleInput();
	this.coinFont.text = `x${this.coinPickupCount}`;
	this.keyIcon.frame = this.hasKey ? 1 : 0;
};

PlayState._handleCollisions=function(){
	this.game.physics.arcade.collide(this.spiders, this.platforms);
	this.game.physics.arcade.collide(this.spiders, this.enemyWalls);
	this.game.physics.arcade.collide(this.hero, this.platforms);
	this.game.physics.arcade.overlap(this.hero, this.coins, this._onHeroVsCoin,
		 null, this );
	this.game.physics.arcade.overlap(this.hero, this.spiders,
		this._onHeroVsEnemy, null, this);
	this.game.physics.arcade.overlap(this.hero, this.key, this._onHeroVsKey,
		null, this)
	this.game.physics.arcade.overlap(this.hero, this.door, this._onHeroVsDoor,
		//ignore if there is no key or the player is on air
		function (hero, door) {
			return this.hasKey && hero.body.touching.down;
		}, this);
};

PlayState._handleInput=function(){
	if (this.keys.left.isDown) {// move hero left
		this.hero.move(-1);
	}
	else if (this.keys.right.isDown) {// move hero right
			 this.hero.move(1);
    }
    else{//stop
    	this.hero.move(0);
    }
};

PlayState._createHud=function(){
	this.keyIcon = this.game.make.image(0, 19, 'icon:key');
	this.keyIcon.anchor.set(0, 0.5);
	let coinIcon = this.game.make.image(this.keyIcon.width + 7, 0, 'icon:coin');
	const NUMBERS_STR='0123456789X';
	this.coinFont=this.game.add.retroFont('font:numbers', 20, 26,
		NUMBERS_STR, 6);
	let coinScoreImg =this.game.make.image(coinIcon.x + coinIcon.width,
		coinIcon.height / 2, this.coinFont);
	coinScoreImg.anchor.set(0, 0.5);

	this.hud=this.game.add.group();
	this.hud.add(coinIcon);
	this.hud.position.set(10, 10);
	this.hud.add(coinScoreImg);
	this.hud.add(this.keyIcon);
}

PlayState._loadLevel = function (data)  {
	this.bgDecoration = this.game.add.group();
	//create all the groups/layers that we need
	this.platforms= this.game.add.group();
	this.coins=this.game.add.group();
	this.spiders=this.game.add.group();
	this.enemyWalls=this.game.add.group();
	this.enemyWalls.visible=false;

	// spawn all platforms
	data.platforms.forEach(this._spawnPlatform, this);

	// spawn important objects
	data.coins.forEach(this._spawnCoin, this);

	this._spawnDoor(data.door.x, data.door.y);
	this._spawnKey(data.key.x, data.key.y);

	//enable gravity
	const GRAVITY=1200;
	this.game.physics.arcade.gravity.y=GRAVITY;

	//spawn  and enemies
	this._spawnCharacters({hero: data.hero, spiders:data.spiders});

};

PlayState._spawnDoor = function (x,y){
	this.door = this.bgDecoration.create(x,y, 'door');
	this.door.anchor.setTo(0.5, 1);
	this.game.physics.enable(this.door);
	this.door.body.allowGravity = false;
};

PlayState._spawnKey = function (x, y) {
	this.key = this.bgDecoration.create(x, y, 'key');
	this.key.anchor.set(0.5, 0.5);
	this.game.physics.enable(this.key);
	this.key.body.allowGravity = false;
	this.key.y -= 3;
	this.game.add.tween(this.key)
		.to({y:this.key.y + 6}, 800, Phaser.Easing.Sinusoidal.InOut)
		.yoyo(true)
		.loop()
		.start();
};

PlayState._spawnCharacters = function(data){
	//spawn hero
	this.hero=new hero(this.game, data.hero.x, data.hero.y);
	this.game.add.existing(this.hero);
	//spawn spiders
	data.spiders.forEach(function (spider){
		let sprite=new Spider(this.game, spider.x, spider.y);
		this.spiders.add(sprite);
	}, this);
};

PlayState._spawnPlatform = function (platform){
	let sprite=this.platforms.create(
		platform.x, platform.y, platform.image);

	this.game.physics.enable(sprite);
	sprite.body.allowGravity=false;
	sprite.body.immovable=true;
	this._spawnEnemyWall(platform.x, platform.y, 'left');
	this._spawnEnemyWall(platform.x+sprite.width, platform.y, 'right');
};

PlayState._spawnCoin = function(coin){
	let sprite= this.coins.create(coin.x, coin.y, 'coin');
	sprite.anchor.set(0.5,0.5);
	sprite.animations.add('rotate', [0,1,2,1], 6, true);
	sprite.animations.play('rotate');
	this.game.physics.enable(sprite);
	sprite.body.allowGravity= false;
};

PlayState._spawnEnemyWall=function (x, y, side){
	let sprite = this.enemyWalls.create(x, y, 'invisible-wall');
	// anchor and y displacement
	sprite.anchor.set(side === 'left' ? 1: 0, 1);

	//physic properties
	this.game.physics.enable(sprite);
	sprite.body.immovable=true;
	sprite.body.allowGravity=false;
}

PlayState._onHeroVsDoor = function (hero, door) {
	this.sfx.door.play();
	this.game.state.restart(true, false, {level: this.level +1 });
};

PlayState._onHeroVsKey = function (hero, key) {
	this.sfx.key.play();
	key.kill();
	this.hasKey = true;
};

PlayState._onHeroVsCoin= function(hero, coin){
	this.sfx.coin.play();
	coin.kill();
	this.coinPickupCount++;
};
PlayState._onHeroVsEnemy=function (hero, enemy){
	if (hero.body.velocity.y > 0){//kill enemies when hero is falling
		hero.bounce();
		enemy.die();
		this.sfx.stomp.play();
	}
	else{//game over -> restart the game
		this.sfx.stomp.play();
		this.game.state.restart(true, false, {level: this.level});
	}
};

window.onload = function(){
	let game = new Phaser.Game(960,600,Phaser.AUTO,'game');
	game.state.add('play',PlayState);
	game.state.start('play' , true, false, {level:0});
};


text:
<?php

/**
 * An application plugin resource for connecting to a MongoDB server
 */
class ZFE_Resource_Mongo extends Zend_Application_Resource_ResourceAbstract
{
    private $connection;

    private $socket = false;
    private $host;
    private $port;
    private $username;
    private $password;
    private $database;

    private $mapping = array();

    /**
     * Initialize the plugin
     *
     * When no application options have been specified in the config.ini, then
     * it will use the default values from php.ini
     */
    public function init()
    {
        $o = $this->getOptions();

        if (empty($o['database']))
        {
            throw new Zend_Application_Resource_Exception('Please specify at least the Mongo database to use: resources.mongo.database');
        }

        if (isset($o['socket'])) $this->socket = $o['socket'];

        $this->host = isset($o['host']) ? $o['host'] : ini_get('mongo.default_host');
        $this->port = isset($o['port']) ? $o['port'] : ini_get('mongo.default_port');
        $this->username = isset($o['username']) && !empty($o['username']) ? $o['username'] : null;
        $this->password = isset($o['password']) && !empty($o['password']) ? $o['password'] : null;
        $this->authSource = isset($o['authSource']) && !empty($o['authSource']) ? $o['authSource'] : null;
        $this->database = $o['database'];

        if (isset($o['mapping']) && is_array($o['mapping'])) {
            $this->mapping = array_merge($this->mapping, $o['mapping']);
        }

        return $this;
    }

    /**
     * Creates the connection URI, the MongoClient instance, and returns
     * the MongoDB instance from it.
     *
     * The PECL Mongo PHP library already does persistent connections since
     * version 1.2, but here it is just for saving the process of composing
     * the URI every time.
     */
    public function getDatabase()
    {
        if (is_null($this->connection)) {
            $uri = "mongodb://";
            $options = array("connect" => TRUE);
            if ($this->username && $this->password) {
                $options["username"] = $this->username;
                $options["password"] = $this->password;
                $options["db"] = $this->database;
                if ($this->authSource) {
                    $options["authSource"] = $this->authSource;
                }
            }

            $uri .= $this->socket ? $this->socket : $this->host . ":" . $this->port;
            $this->connection = new MongoClient($uri, $options);
        }

        return $this->connection->{$this->database};
    }

    /**
     * Returns the class name for the given collection name.
     * If it is mentioned in the mapping configuration, it will use
     * the mapping's setting for not-so-obvious mappings. This can be
     * configured in the application's configuration file.
     */
    public function getClass($collectionName)
    {
        if (isset($this->mapping[$collectionName])) {
            $cls = $this->mapping[$collectionName];
        } else {
            $cls = ZFE_Environment::getResourcePrefix('model') . '_' . ucfirst($collectionName);
        }

        return $cls;
    }

    public function addMapping($collectionName, $className)
    {
        $this->mapping[$collectionName] = $className;
    }

    public function addMappings($mappings)
    {
        foreach($mappings as $coll => $cls) {
            $this->addMapping($coll, $cls);
        }
    }
}


text:
using System;
using System.Linq.Expressions;
using NJasmine.Core.Elements;
using NJasmine.Core.FixtureVisitor;

namespace NJasmine.Core.Execution
{
    public class NJasmineTestRunner : ISpecPositionVisitor
    {
        NJasmineTestRunContext _runContext;

        public NJasmineTestRunner(NJasmineTestRunContext runContext)
        {
            _runContext = runContext;
        }

        public void visitFork(ForkElement element, TestPosition position)
        {
            _runContext.State.visitFork(element, position);
        }

        public TArranged visitBeforeAll<TArranged>(BeforeAllElement<TArranged> element, TestPosition position)
        {
            return _runContext.State.visitBeforeAll(element, position);
        }

        public void visitAfterAll(AfterAllElement element, TestPosition position)
        {
            _runContext.State.visitAfterAll(element, position);
        }

        public TArranged visitBeforeEach<TArranged>(BeforeEachElement<TArranged> element, TestPosition position)
        {
            return _runContext.State.visitBeforeEach<TArranged>(element, position);
        }

        public void visitAfterEach(SpecificationElement element, Action action, TestPosition position)
        {
            _runContext.State.visitAfterEach(element, action, position);
        }

        public void visitTest(TestElement element, TestPosition position)
        {
            _runContext.State.visitTest(element, position);
        }

        public void visitIgnoreBecause(IgnoreElement element, TestPosition position)
        {
            _runContext.State.visitIgnoreBecause(element, position);
        }

        public void visitExpect(ExpectElement element, TestPosition position)
        {
            _runContext.State.visitExpect(element, position);
        }

        public void visitWaitUntil(WaitUntilElement element, TestPosition position)
        {
            _runContext.State.visitWaitUntil(element, position);
        }

        public void visitWithCategory(WithCategoryElement element, TestPosition position)
        {
            _runContext.State.visitWithCategory(element, position);
        }

        public void visitTrace(TraceElement element, TestPosition position)
        {
            _runContext.State.visitTrace(element, position);
        }

        public void visitLeakDisposable(LeakDisposableElement element, TestPosition position)
        {
            _runContext.State.visitLeakDisposable(element, position);
        }
    }
}


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace MagicTower.Components.Unit
{
    public class JumpWord : MonoBehaviour
    {
        // Start is called before the first frame update
        private void Start()
        {
            totalTime = 0f;
        }

        // Update is called once per frame
        private void Update()
        {
            totalTime += Time.deltaTime;
            if (totalTime < jumpSeconds)
            {
                var jumpPercent = Time.deltaTime / jumpSeconds;
                if(Direction == Present.Player.Controller.Direction.Left)
                {
                    transform.localPosition += new Vector3(-jumpWidth * jumpPercent, jumpHeight * jumpPercent, 0);
                }
                else
                {
                    transform.localPosition += new Vector3(jumpWidth * jumpPercent, jumpHeight * jumpPercent, 0);
                }
            }
            if(totalTime < scaleSeconds)
            {
                var scale = scaleTimesFirst + (scaleTimesLast - scaleTimesFirst) * totalTime / scaleSeconds;
                transform.localScale = new Vector3(scale, scale, 0);
            }
            if(totalTime > showSeconds)
            {
                Destroy(gameObject);
            }
        }

        public string Word {
            get => txtWord.text;
            set => txtWord.text = value;
        }

        public Present.Player.Controller.Direction Direction {
            get;set;
        }

        public Text txtWord;

        private float totalTime;

        /// <summary> 纵向条约距离 </summary>
        private const float jumpHeight = 35f;
        /// <summary> 横向条约距离 </summary>
        private const float jumpWidth = 80f;
        /// <summary> 跳跃耗时 </summary>
        private const float jumpSeconds = 0.4f;
        /// <summary> 初始缩放 </summary>
        private const float scaleTimesFirst = 0.1f;
        /// <summary> 最终缩放 </summary>
        private const float scaleTimesLast = 0.8f;
        /// <summary> 缩放耗时 </summary>
        private const float scaleSeconds = 0.5f;
        /// <summary> 消失时间 </summary>
        private const float showSeconds = 0.7f;
    }

}


text:
package sk.upjs.ics.todo.dao;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;
import org.springframework.jdbc.core.JdbcTemplate;
import sk.upjs.ics.todo.entity.Notifikacia;
import sk.upjs.ics.todo.rowmappery.NotifikaciaRowMapper;

public class DatabazovyNotifikaciaDao implements NotifikaciaDao {

    private final JdbcTemplate jdbcTemplate;
    private static final NotifikaciaRowMapper mapovacNotifikacii = new NotifikaciaRowMapper();
    private static final String nazovTabulky = "NOTIFIKACIE";

    /**
     * Konstruktor, ktory si sam vyrobi JdbcTemplate - kvoli tomu, aby sme na
     * serveri nepotrebovali Factory
     */
    public DatabazovyNotifikaciaDao() {
        jdbcTemplate = new JdbcTemplate(dataSource());
    }

    /**
     * UlohaDao vyuziva NotifikaciaDao, a tak urobime aj taky konstruktor, ktory
     * vie pouzit aj jdbcTemplate z Factory
     *
     * @param jdbcTemplate
     */
    public DatabazovyNotifikaciaDao(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * Vsetky notifikacie joinuje aj s udajmi o ulohe a pouzivatelovi, aby sme
     * mali vsetky informacie pre odoslanie emailu
     *
     * @return zoznam vsetkych notifikacii
     */
    @Override
    public List<Notifikacia> dajVsetkyNotifikacie() {
        return jdbcTemplate.query("SELECT * FROM " + nazovTabulky + " n \n"
                + " JOIN ULOHY u ON n.id_ulohy = u.uloha_id \n"
                + " JOIN UZIVATELIA p ON u.vlastnik = p.Meno \n",
                mapovacNotifikacii);
    }

    /**
     * Prida notifikaciu do databazy
     *
     * @param idUlohy id ulohy, na ktoru sa viaze notifikacia
     */
    @Override
    public void pridajNotifikaciu(long idUlohy) {
        // pri uprave ulohy tiez vkladame notifikaciu, lebo sa mohlo stat, ze uz
        // bola odoslana, ale pouzivatel zmenil cas ulohy a bude ju treba poslat znovu,
        // preto najprv vymazeme tu, ktora uz mozno existuje a nahradime ju novou
        vymazNotifikaciu(idUlohy);
        String sqlNotifikacia = "INSERT INTO " + nazovTabulky + " \n"
                + "(id_ulohy)\n"
                + "VALUES(?)\n";
        jdbcTemplate.update(sqlNotifikacia, idUlohy);
    }

    /**
     * Vymaze notifikaciu z databazy
     *
     * @param idUlohy id ulohy, na ktoru sa viaze notifikacia
     */
    @Override
    public void vymazNotifikaciu(long idUlohy) {
        String sqlNotifikacia = "DELETE FROM " + nazovTabulky + " \n"
                + "WHERE id_ulohy = ?";
        jdbcTemplate.update(sqlNotifikacia, idUlohy);
    }

    /**
     * Pri behu na serveri by bolo zbytocne pouzivat Factory, tak si vytvorime
     * novy DataSource
     *
     * @return dataSource
     */
    private MysqlDataSource dataSource() {
        Properties properties = getProperties();
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setURL((String) properties.get("dataServer"));
        dataSource.setUser((String) properties.get("dataLogin"));
        dataSource.setPassword((String) properties.get("dataPass"));

        return dataSource;
    }

    /**
     * @return properties pre pripojenie k databaze
     */
    private Properties getProperties() {
        try {
            String propertiesFile;

            propertiesFile = "/home/todo/todo.properties";

            InputStream in;

            try {
                // ak sme tu, tak sme u Martina
                in = new FileInputStream(propertiesFile);
            } catch (FileNotFoundException e1) {
                // ak sme tu, tak sme u Alice alebo na serveri
                // skusime najprv server
                propertiesFile = "/home/akacengova/todo/todo.properties";
            }

            try {
                // ak sme tu, tak sme na serveri
                in = new FileInputStream(propertiesFile);
            } catch (FileNotFoundException e2) {
                // ak sme tu, tak sme u Alice
                // Alica sa sklonuje podla vzoru ulica, takze ziadne "u Alici" !!! :D
                propertiesFile = "C:/todo/todo.properties";
            }

            in = new FileInputStream(propertiesFile);

            Properties properties = new Properties();
            properties.load(in);

            return properties;
        } catch (IOException e) {
            throw new IllegalStateException("Nenašiel sa konfiguračný súbor!");
        }
    }
}


text:
package meshconfig

import (
	"io"
	"io/ioutil"
	"sync"

	"istio.io/api/mesh/v1alpha1"
	"istio.io/istio/pkg/config/mesh"
	"istio.io/pkg/filewatcher"
	"istio.io/pkg/log"
)

var scope = log.RegisterScope("meshconfig", "meshconfig watcher/reader", 0)

// Cache is an interface for getting a cached copy of mesh.
type Cache interface {
	// Get returns the cached copy of mesh config.
	Get() v1alpha1.MeshConfig
}

// FsCache is a Cache implementation that reads mesh from file.
type FsCache struct {
	path string
	fw   filewatcher.FileWatcher

	cachedMutex sync.Mutex
	cached      v1alpha1.MeshConfig
}

var _ Cache = &FsCache{}
var _ io.Closer = &FsCache{}

var DefaultMeshConfig = func() v1alpha1.MeshConfig {
	meshconfig := mesh.DefaultMeshConfig()
	meshconfig.IngressClass = "istio"
	meshconfig.IngressControllerMode = v1alpha1.MeshConfig_STRICT
	return meshconfig
}()

// NewCacheFromFile returns a new mesh cache, based on watching a file.
func NewCacheFromFile(path string) (*FsCache, error) {
	fw := filewatcher.NewWatcher()

	err := fw.Add(path)
	if err != nil {
		return nil, err
	}

	c := &FsCache{
		path:   path,
		fw:     fw,
		cached: DefaultMeshConfig,
	}

	c.reload()

	go func() {
		for range fw.Events(path) {
			c.reload()
		}
	}()

	return c, nil
}

// Get returns the cached copy of mesh config.
func (c *FsCache) Get() v1alpha1.MeshConfig {
	c.cachedMutex.Lock()
	defer c.cachedMutex.Unlock()
	return c.cached
}

func (c *FsCache) reload() {
	by, err := ioutil.ReadFile(c.path)
	if err != nil {
		scope.Errorf("Error loading mesh config (path: %s): %v", c.path, err)
		return
	}

	cfg, err := mesh.ApplyMeshConfig(string(by), DefaultMeshConfig)
	if err != nil {
		scope.Errorf("Error reading mesh config as json: %v", err)
		return
	}

	c.cachedMutex.Lock()
	defer c.cachedMutex.Unlock()
	c.cached = *cfg
	scope.Infof("Reloaded mesh config: \n%s\n", string(by))
}

// Close closes this cache.
func (c *FsCache) Close() error {
	return c.fw.Close()
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Loki: Graphical Class Hierarchy</title>
<link href="tabs.css" rel="stylesheet" type="text/css">
<link href="doxygen.css" rel="stylesheet" type="text/css">

Main Page

Modules

Namespaces

Classes

Files

      <form action="search.php" method="get">

             Search for
            <input type="text" name="query" value="" size="20" accesskey="s"/>

      </form>

Class List

Class Index

Class Hierarchy

Class Members

Graphical Class Hierarchy
Go to the textual class hierarchy

<address style="text-align: right;">Generated on Thu Jan 29 18:51:41 2009 for Loki by

 1.5.8 </address>


text:
const path = require(`path`)
const gatsbyPath = path.resolve(
  __dirname,
  `..`,
  `www`,
  `node_modules`,
  `gatsby`,
  `dist`
)
const explorer = require(path.resolve(
  gatsbyPath,
  `commands`,
  `data-explorer.js`
))

const port = process.env.PORT || 8080
const host = `0.0.0.0`
const directory = path.join(__dirname, `..`, `www`)
const sitePackageJson = require(path.join(directory, `package.json`))

explorer({
  port,
  host,
  directory,
  sitePackageJson,
  // make Gatsby think this is a normal `gatsby build` command
  _: [`build`],
})


text:
package com.goodworkalan.strata;

/**
 * Determine if the root inner tier should be filled with contents of a single
 * remaining child inner tier. The root inner tier is filled with the contents
 * of a single child when the single child is merged from two remaining
 * children. When an root inner tier has only one inner tier child, the contents
 * of that inner tier child becomes the root of the b-tree.
 *
 * @author Alan Gutierrez
 *
 * @param <T>
 *            The value type of the b+tree objects.
 * @param <A>
 *            The address type used to identify an inner or leaf tier.
 */
final class ShouldFillRoot<T, A>
implements RootDecision<T, A> {
    /**
     * Determine if the root inner tier has only two remaining children and if
     * those children are going to merge to form a single remaining child.
     *
     * @param mutation
     *            The mutation state container.
     * @param rootLevel
     *            The per level mutation state for the root level.
     * @param root
     *            The root inner tier.
     * @return True if the operations performed by this root decision are
     *         applicable.
     */
    public boolean test(Mutation<T, A> mutation, Level<T, A> rootLevel, Tier<T, A> root) {
        if (!root.isChildLeaf() && root.getSize() == 2) {
            Structure<T, A> structure = mutation.getStructure();
            Tier<T, A> first = structure.getStorage().load(mutation.getStash(), root.getChildAddress(0));
            Tier<T, A> second = structure.getStorage().load(mutation.getStash(), root.getChildAddress(1));
            // FIXME These numbers are off.
            return first.getSize() + second.getSize() == structure.getInnerSize();
        }
        return false;
    }

    /**
     * Add the fill root operation to the list of operations in the per level
     * mutation state container.
     *
     * @param mutation
     *            The mutation state container.
     * @param rootLevel
     *            The per level mutation state for the root level.
     * @param root
     *            The root inner tier.
     */
    public void operation(Mutation<T, A> mutation, Level<T, A> rootLevel, Tier<T, A> root) {
        rootLevel.operations.add(new FillRoot<T, A>(root));
    }
}


text:
<?php

/** Zend_Controller_Router_Route_Abstract */
require_once 'Zend/Controller/Router/Route/Abstract.php';

/**
 * StaticRoute is used for managing static URIs.
 *
 * It's a lot faster compared to the standard Route implementation.
 *
 * @package    Zend_Controller
 * @subpackage Router
 * @copyright  Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Controller_Router_Route_Static extends Zend_Controller_Router_Route_Abstract
{

    protected $_route = null;
    protected $_defaults = array();

    public function getVersion() {
        return 1;
    }

    /**
     * Instantiates route based on passed Zend_Config structure
     *
     * @param Zend_Config $config Configuration object
     */
    public static function getInstance(Zend_Config $config)
    {
        $defs = ($config->defaults instanceof Zend_Config) ? $config->defaults->toArray() : array();
        return new self($config->route, $defs);
    }

    /**
     * Prepares the route for mapping.
     *
     * @param string $route Map used to match with later submitted URL path
     * @param array $defaults Defaults for map variables with keys as variable names
     */
    public function __construct($route, $defaults = array())
    {
        $this->_route = trim($route, '/');
        $this->_defaults = (array) $defaults;
    }

    /**
     * Matches a user submitted path with a previously defined route.
     * Assigns and returns an array of defaults on a successful match.
     *
     * @param string $path Path used to match against this routing map
     * @return array|false An array of assigned values or a false on a mismatch
     */
    public function match($path)
    {
        if (trim($path, '/') == $this->_route) {
            return $this->_defaults;
        }
        return false;
    }

    /**
     * Assembles a URL path defined by this route
     *
     * @param array $data An array of variable and value pairs used as parameters
     * @return string Route path with user submitted parameters
     */
    public function assemble($data = array(), $reset = false, $encode = false)
    {
        return $this->_route;
    }

    /**
     * Return a single parameter of route's defaults
     *
     * @param string $name Array key of the parameter
     * @return string Previously set default
     */
    public function getDefault($name) {
        if (isset($this->_defaults[$name])) {
            return $this->_defaults[$name];
        }
        return null;
    }

    /**
     * Return an array of defaults
     *
     * @return array Route defaults
     */
    public function getDefaults() {
        return $this->_defaults;
    }

}


text:
<?php
get_header();

if($wp_query->query_vars['category_name']=='professor'){
  include(get_template_directory() . "/list.professor.php");
}elseif($wp_query->query_vars['category_name']=='aluno'){
  include(get_template_directory() . "/list.aluno.php");
}else{

    if(have_posts() || $wp_query->query['post_type']=="notcias"): ?>
    <link rel='stylesheet' href='<?php echo get_template_directory_uri (); ?>/css/j.css' type='text/css'>
    <link rel='stylesheet' href='<?php echo get_template_directory_uri (); ?>/css/page.css' type='text/css'>

    <div class="second-header" style="background-image:url('<?php echo imagem(''); ?>');">

<?php echo $wp_query->queried_object->labels->name; ?>

        <?php

          if($wp_query->query_vars['post_type']=="docentes"){
            include(get_template_directory() . "/list.docentes.php");
          }elseif($wp_query->query_vars['post_type']=="notcias"){
            include(get_template_directory() . "/list.noticias.php");
          }elseif($wp_query->query_vars['post_type']=="datasimportantes"){
            include(get_template_directory() . "/list.datasimportantes.php");
          }elseif(substr($wp_query->query['post_type'],0,6)=='cursos'){
            include(get_template_directory() . "/list.cursos.php");
          }else{
            while (have_posts()) : the_post();
              ?><a href="<?php echo get_permalink();?>"><?php the_title(); ?> - (<?php the_date(); ?>)

              <?php
            endwhile;
          }
          if (will_paginate()): ?>

<?php posts_nav_link() ?>

        <?php endif; ?>

    <?php

    elseif(substr($wp_query->query['category_name'],0,6)=='cursos'):
        include(get_template_directory() . "/list.cursos.php");
    elseif($wp_query->query['category_name']=='professor'):
        include(get_template_directory() . "/list.professor.php");
    elseif($wp_query->query['category_name']=='aluno'):
        include(get_template_directory() . "/list.aluno.php");
    else:
    ?>

 <?php echo __("Sorry, no such page."); ?>

  <?php
    endif;

}
get_footer();

?>


text:
<?php

if (!defined('IN_CKFINDER')) exit;

/**
 * @package CKFinder
 * @subpackage CommandHandlers
 * @copyright CKSource - Frederico Knabben
 */

/**
 * Include base XML command handler
 */
require_once CKFINDER_CONNECTOR_LIB_DIR . "/CommandHandler/XmlCommandHandlerBase.php";

/**
 * Handle GetFolders command
 *
 * @package CKFinder
 * @subpackage CommandHandlers
 * @copyright CKSource - Frederico Knabben
 */
class CKFinder_Connector_CommandHandler_GetFolders extends CKFinder_Connector_CommandHandler_XmlCommandHandlerBase
{
    /**
     * Command name
     *
     * @access private
     * @var string
     */
    private $command = "GetFolders";

    /**
     * handle request and build XML
     * @access protected
     *
     */
    protected function buildXml()
    {
        $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");
//        if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FOLDER_VIEW)) {
//            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
//        }

        // Map the virtual path to the local server path.
        $_sServerDir = substr($this->_currentFolder->getServerPath(), 1);

//        if (!is_dir($_sServerDir)) {
//            $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FOLDER_NOT_FOUND);
//        }

        // Create the "Folders" node.
        $oFoldersNode = new Ckfinder_Connector_Utils_XmlNode("Folders");
        $this->_connectorNode->addChild($oFoldersNode);

        $files = array();

        global $config;

        $s3 = s3_con();
        $items = $s3->getBucket($config['AmazonS3']['Bucket'], $_sServerDir, null, null, '/', true);

        foreach ($items as $key=>$val) {
            if (array_key_exists('prefix', $val)) {
                //TODO: Replace the base directory in this URL
                $files[] = substr(str_replace($_sServerDir, "", $key), 0, -1);
                //$files[] = substr($key, 3, strlen($key) - 4);
            }
        }

        $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();

        if (sizeof($files)>0) {
            natcasesort($files);
            $i=0;
            foreach ($files as $file) {
                $oAcl = $_config->getAccessControlConfig();
                $folderPath = $this->_currentFolder->getClientPath() . $file . '/';
                $aclMask = $oAcl->getComputedMask($this->_currentFolder->getResourceTypeName(), $folderPath);

                if (($aclMask & CKFINDER_CONNECTOR_ACL_FOLDER_VIEW) != CKFINDER_CONNECTOR_ACL_FOLDER_VIEW) {
                    continue;
                }
                if ($resourceTypeInfo->checkIsHiddenFolder($file)) {
                    continue;
                }

                // Create the "Folder" node.
                $oFolderNode[$i] = new Ckfinder_Connector_Utils_XmlNode("Folder");
                $oFoldersNode->addChild($oFolderNode[$i]);
                $oFolderNode[$i]->addAttribute("name", CKFinder_Connector_Utils_FileSystem::convertToConnectorEncoding($file));
                $oFolderNode[$i]->addAttribute("hasChildren", CKFinder_Connector_Utils_FileSystem::hasChildren($folderPath, $resourceTypeInfo) ? "true" : "false");
                $oFolderNode[$i]->addAttribute("acl", $aclMask);

                $i++;
            }
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

    public enum Side
    {
        TOP,
        BOTTOM
    }
    public Side side;
    public PlayerController other;

	public KeyCode jumpKey1;
	public KeyCode jumpKey2;

    public float jumpForce;
	private float _distanceToGround;
	public float margin;
	private float _horizontalVelocity;
	private float _playerVelocity;
	private float _gravityVelocity;
	public float gravitySpeed;
	public float returnSpeed = 0.01f;
	private float _initialCoord;
	private int _currentSide;
	public float eps = 0.001f;
	private bool _needsReturn = false;
    public MeshRenderer phantomRenderer;
    bool phantomMode = false;
    public float phantomDuration;

    bool isDead = false;

    public GameObject explosionParticles;
    public SpriteRenderer sprite;

    public AudioClip soundDie;
    public AudioClip soundPickup;

	void Start () {
		_distanceToGround = collider.bounds.extents.y;
		_initialCoord = transform.position.x;
	}

	int CheckSide()
	{
		if (_initialCoord > transform.position.x)
			return 1;
		else return -1;
	}

	public bool IsGrounded()
	{
		return Physics.Raycast(transform.position, -Vector3.up, _distanceToGround + margin, 1<<8);
	}

	void Update () {
		if (Mathf.Abs(transform.position.x - _initialCoord) > eps)
		{
			transform.position = new Vector3(transform.position.x + CheckSide() * returnSpeed, transform.position.y, transform.position.z);
			_currentSide = CheckSide();
			_needsReturn = true;
		}

		if (IsGrounded ())
		{
			_playerVelocity = 0;
			_gravityVelocity = 0;
		    if (Input.GetKey(jumpKey1) || Input.GetKey(jumpKey2))
	        {
				_playerVelocity += jumpForce;
	        }
		}
		else
		{
			_gravityVelocity += gravitySpeed;
		}

        if (phantomMode)
            _gravityVelocity = 0;

		rigidbody.velocity = new Vector3 (rigidbody.velocity.x, _playerVelocity + _gravityVelocity, rigidbody.velocity.z);
		if (CheckSide() != _currentSide && _needsReturn)
		{
			transform.position = new Vector3(_initialCoord, transform.position.y, transform.position.z);
			_needsReturn = false;
		}
	}

    public void Die()
    {
        if (!isDead)
        {
            isDead = true;
            StartCoroutine( _Die() );
        }
    }

    IEnumerator _Die()
    {
        audio.PlayOneShot(soundDie);
        GameObject.Instantiate(explosionParticles, transform.position, Quaternion.identity);
        sprite.enabled = false;

        GameManager gm = GameObject.Find("_GameManager").GetComponent<GameManager>();
        PlayerPrefs.SetFloat("score", gm.GetScore());

        yield return new WaitForSeconds(1f);

        Application.LoadLevel("End Scene");
    }

    public void GoPhantom()
    {
        StartCoroutine( _GoPhantom() );
    }

    IEnumerator _GoPhantom()
    {
        GetComponent<CapsuleCollider>().enabled = false;
        phantomRenderer.enabled = true;
        RigidbodyConstraints currConstraints = rigidbody.constraints;
        transform.Translate( new Vector3(0, 0.3f, 0) );
        rigidbody.constraints = currConstraints | RigidbodyConstraints.FreezePositionY;
        phantomMode = true;

        yield return new WaitForSeconds(phantomDuration);

        rigidbody.constraints = currConstraints;
        GetComponent<CapsuleCollider>().enabled = true;
        phantomRenderer.enabled = false;
        phantomMode = false;
		rigidbody.constraints = currConstraints;
    }

    public void PlayPickupSound()
    {
        audio.PlayOneShot(soundPickup);
    }

}


text:
using content::BrowserThread;
using extensions::Extension;

namespace {

const char kUnpackedExtensionsBlacklistedError[] =
    "Loading of unpacked extensions is disabled by the administrator.";

// Manages an ExtensionInstallPrompt for a particular extension.
class SimpleExtensionLoadPrompt : public ExtensionInstallPrompt::Delegate {
 public:
  SimpleExtensionLoadPrompt(Profile* profile,
                            base::WeakPtr<ExtensionService> extension_service,
                            const Extension* extension);
  ~SimpleExtensionLoadPrompt();

  void ShowPrompt();

  // ExtensionInstallUI::Delegate
  virtual void InstallUIProceed() OVERRIDE;
  virtual void InstallUIAbort(bool user_initiated) OVERRIDE;

 private:
  base::WeakPtr<ExtensionService> service_weak_;
  scoped_ptr<ExtensionInstallPrompt> install_ui_;
  scoped_refptr<const Extension> extension_;
};

SimpleExtensionLoadPrompt::SimpleExtensionLoadPrompt(
    Profile* profile,
    base::WeakPtr<ExtensionService> extension_service,
    const Extension* extension)
    : service_weak_(extension_service),
      extension_(extension) {
  install_ui_.reset(
      ExtensionInstallUI::CreateInstallPromptWithProfile(profile));
}

SimpleExtensionLoadPrompt::~SimpleExtensionLoadPrompt() {
}

void SimpleExtensionLoadPrompt::ShowPrompt() {
  install_ui_->ConfirmInstall(this, extension_);
}

void SimpleExtensionLoadPrompt::InstallUIProceed() {
  if (service_weak_.get()) {
    extensions::PermissionsUpdater perms_updater(service_weak_->profile());
    perms_updater.GrantActivePermissions(extension_, false);
    service_weak_->OnExtensionInstalled(
        extension_, false, StringOrdinal());  // Not from web store.
  }
  delete this;
}

void SimpleExtensionLoadPrompt::InstallUIAbort(bool user_initiated) {
  delete this;
}

}  // namespace

namespace extensions {

// static
scoped_refptr<UnpackedInstaller> UnpackedInstaller::Create(
    ExtensionService* extension_service) {
  return scoped_refptr<UnpackedInstaller>(
      new UnpackedInstaller(extension_service));
}

UnpackedInstaller::UnpackedInstaller(ExtensionService* extension_service)
    : service_weak_(extension_service->AsWeakPtr()),
      prompt_for_plugins_(true) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}

UnpackedInstaller::~UnpackedInstaller() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
        BrowserThread::CurrentlyOn(BrowserThread::FILE));
}

void UnpackedInstaller::Load(const FilePath& path_in) {
  extension_path_ = path_in;
  BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
      base::Bind(&UnpackedInstaller::GetAbsolutePath, this));
}

void UnpackedInstaller::LoadFromCommandLine(const FilePath& path_in) {
  if (!service_weak_.get())
    return;
  // Load extensions from the command line synchronously to avoid a race
  // between extension loading and loading an URL from the command line.
  base::ThreadRestrictions::ScopedAllowIO allow_io;

  extension_path_ = path_in;
  file_util::AbsolutePath(&extension_path_);

  if (!IsLoadingUnpackedAllowed()) {
    ReportExtensionLoadError(kUnpackedExtensionsBlacklistedError);
    return;
  }

  std::string id = Extension::GenerateIdForPath(extension_path_);
  bool allow_file_access =
      Extension::ShouldAlwaysAllowFileAccess(Extension::LOAD);
  if (service_weak_->extension_prefs()->HasAllowFileAccessSetting(id))
    allow_file_access = service_weak_->extension_prefs()->AllowFileAccess(id);

  int flags = Extension::REQUIRE_MODERN_MANIFEST_VERSION;
  if (allow_file_access)
    flags |= Extension::ALLOW_FILE_ACCESS;

  std::string error;
  scoped_refptr<const Extension> extension(extension_file_util::LoadExtension(
      extension_path_,
      Extension::LOAD,
      flags | Extension::FOLLOW_SYMLINKS_ANYWHERE,
      &error));

  if (!extension) {
    ReportExtensionLoadError(error);
    return;
  }

  OnLoaded(extension);
}

bool UnpackedInstaller::IsLoadingUnpackedAllowed() const {
  if (!service_weak_)
    return true;
  // If there is a "*" in the extension blacklist, then no extensions should be
  // allowed at all (except explicitly whitelisted extensions).
  return !service_weak_->extension_prefs()->ExtensionsBlacklistedByDefault();
}

void UnpackedInstaller::GetAbsolutePath() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));

  file_util::AbsolutePath(&extension_path_);

  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      base::Bind(&UnpackedInstaller::CheckExtensionFileAccess, this));
}

void UnpackedInstaller::CheckExtensionFileAccess() {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!service_weak_)
    return;

  if (!IsLoadingUnpackedAllowed()) {
    ReportExtensionLoadError(kUnpackedExtensionsBlacklistedError);
    return;
  }

  std::string id = Extension::GenerateIdForPath(extension_path_);
  // Unpacked extensions default to allowing file access, but if that has been
  // overridden, don't reset the value.
  bool allow_file_access =
      Extension::ShouldAlwaysAllowFileAccess(Extension::LOAD);
  if (service_weak_->extension_prefs()->HasAllowFileAccessSetting(id))
    allow_file_access = service_weak_->extension_prefs()->AllowFileAccess(id);

  BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
      base::Bind(
          &UnpackedInstaller::LoadWithFileAccess,
          this, allow_file_access));
}

void UnpackedInstaller::LoadWithFileAccess(bool allow_file_access) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  int flags = Extension::REQUIRE_MODERN_MANIFEST_VERSION;
  if (allow_file_access)
    flags |= Extension::ALLOW_FILE_ACCESS;
  std::string error;
  scoped_refptr<const Extension> extension(extension_file_util::LoadExtension(
      extension_path_,
      Extension::LOAD,
      flags | Extension::FOLLOW_SYMLINKS_ANYWHERE,
      &error));

  if (!extension) {
    BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
        base::Bind(
            &UnpackedInstaller::ReportExtensionLoadError,
            this, error));
    return;
  }

  BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
      base::Bind(
          &UnpackedInstaller::OnLoaded,
          this, extension));
}

void UnpackedInstaller::ReportExtensionLoadError(const std::string &error) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!service_weak_.get())
    return;
  service_weak_->ReportExtensionLoadError(extension_path_, error, true);
}

void UnpackedInstaller::OnLoaded(
    const scoped_refptr<const Extension>& extension) {
  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!service_weak_.get())
    return;
  const ExtensionSet* disabled_extensions =
      service_weak_->disabled_extensions();
  if (service_weak_->show_extensions_prompts() &&
      prompt_for_plugins_ &&
      !extension->plugins().empty() &&
      !disabled_extensions->Contains(extension->id())) {
    SimpleExtensionLoadPrompt* prompt = new SimpleExtensionLoadPrompt(
        service_weak_->profile(),
        service_weak_,
        extension);
    prompt->ShowPrompt();
    return;  // continues in SimpleExtensionLoadPrompt::InstallPrompt*
  }

  PermissionsUpdater perms_updater(service_weak_->profile());
  perms_updater.GrantActivePermissions(extension, false);
  service_weak_->OnExtensionInstalled(extension,
                                      false,  // Not from web store.
                                      StringOrdinal());
}

}  // namespace extensions