text:
@implementation WDToolButton

@synthesize tool = tool_;
@synthesize tools = tools_;

+ (float) dimension
{
    return 42;
}

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];

    if (!self) {
        return nil;
    }

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(activeToolChanged:) name:WDActiveToolDidChange object:nil];

    return self;
}

- (void) dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void) dismissSubtoolsAnimated:(BOOL)animated
{
    if (subtoolsPopover_) {
        [subtoolsPopover_ dismissPopoverAnimated:animated];
        subtoolsPopover_ = nil;
    }
}

- (void) canvasStartedTracking:(NSNotification *)aNotification
{
    [self dismissSubtoolsAnimated:NO];
}

- (void) paletteMoved:(NSNotification *)aNotification
{
    [self dismissSubtoolsAnimated:NO];
}

- (void) activeToolChanged:(NSNotification *)aNotification
{
    if (tools_) {
        WDTool *tool = [[WDToolManager sharedInstance] activeTool];

        if (![tools_ containsObject:tool]) {
            [self dismissSubtoolsAnimated:NO];
            self.selected = NO;
            return;
        }

        self.tool = tool;
    }

    self.selected = ([WDToolManager sharedInstance].activeTool == self.tool) ? YES : NO;
}

- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event
{
    if (subtoolsPopover_) {
        [self dismissSubtoolsAnimated:NO];
    }

    return [super beginTrackingWithTouch:touch withEvent:event];
}

- (UIColor *) toolTintColor
{
    return [UIColor colorWithRed:(66.0f / 255) green:(102.0f / 255) blue:(151.0f / 255) alpha:1.0f];
}

- (UIColor *) toolSelectedBackgroundColor
{
    return [UIColor colorWithRed:0.0f green:(118.0f / 255) blue:1.0f alpha:1.0f];
}

- (void) drawDisclosueInContext:(CGContextRef)ctx
{
    float midX = 4, midY = 11;

    CGContextMoveToPoint(ctx, [WDToolButton dimension] - (midX + 3), [WDToolButton dimension] - (midY + 3));
    CGContextAddLineToPoint(ctx, [WDToolButton dimension] - midX, [WDToolButton dimension] - midY);
    CGContextAddLineToPoint(ctx, [WDToolButton dimension] - (midX + 3), [WDToolButton dimension] - (midY - 3));
    CGContextSetLineCap(ctx, kCGLineCapButt);
    CGContextSetLineWidth(ctx, 2.0f);
    CGContextStrokePath(ctx);
}

- (UIImage *) backgroundImageWithRenderBlock:(void (^)(CGContextRef ctx))renderBlock
{
    UIGraphicsBeginImageContextWithOptions(CGSizeMake([WDToolButton dimension], [WDToolButton dimension]), NO, 0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    renderBlock(ctx);
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return result;
}

- (UIImage *) disclosureBackground
{
    UIImage *disclosure = [self backgroundImageWithRenderBlock:^(CGContextRef ctx) {
        [[self toolTintColor] set];
        [self drawDisclosueInContext:ctx];
    }];

    return [disclosure imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
}

- (UIImage *) selectedBackgroundWithDisclosure:(BOOL)drawDisclosure
{
    CGRect buttonRect = CGRectMake(0, 0, [WDToolButton dimension], [WDToolButton dimension]);

    return [self backgroundImageWithRenderBlock:^(CGContextRef ctx) {
        [[self toolSelectedBackgroundColor] set];
        CGContextFillRect(ctx, buttonRect);

        if (drawDisclosure) {
            [[UIColor whiteColor] set];
            [self drawDisclosueInContext:ctx];
        }
    }];
}

- (void) setTool:(WDTool *)tool
{
    tool_ = tool;

    UIImage *tinted = [tool.icon imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    [self setImage:tinted forState:UIControlStateNormal];
    self.tintColor = [self toolTintColor];
    [self setImage:tool.icon forState:UIControlStateSelected];

    if (!tools_) {
        [self setBackgroundImage:[self selectedBackgroundWithDisclosure:NO] forState:UIControlStateSelected];
    }
}

- (void) popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    if (popoverController == subtoolsPopover_) {
        subtoolsPopover_ = nil;
    }
}

- (void) didChooseTool:(WDToolView *)toolView
{
    [self dismissSubtoolsAnimated:YES];
}

- (void) showTools:(id)sender
{
    [self sendActionsForControlEvents:UIControlEventTouchUpInside];

    if (!subtoolsPopover_) {
        WDToolView *subtools = [[WDToolView alloc] initWithTools:tools_];
        subtools.owner = self;

        UIViewController *vc = [[UIViewController alloc] initWithNibName:nil bundle:[NSBundle bundleForClass:[self class]]];
        vc.preferredContentSize = subtools.frame.size;
        vc.view = subtools;

        subtoolsPopover_ = [[UIPopoverController alloc] initWithContentViewController:vc];
        subtoolsPopover_.delegate = self;

        WDToolView *parent = (WDToolView *)self.superview;
        subtoolsPopover_.passthroughViews = @[self.superview, parent.canvas];

        [subtoolsPopover_ presentPopoverFromRect:self.bounds inView:self permittedArrowDirections:UIPopoverArrowDirectionAny animated:NO];
    }
}

- (void) setTools:(NSArray *)tools
{
    tools_ = tools;

    for (WDTool *tool in tools) {
        if ([tool isDefaultForKind]) {
            self.tool = tool;
            break;
        }
    }

    [self setBackgroundImage:[self disclosureBackground] forState:UIControlStateNormal];
    [self setBackgroundImage:[self selectedBackgroundWithDisclosure:YES] forState:UIControlStateSelected];

    UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(showTools:)];
    longTap.minimumPressDuration = 0.25f;
    [self addGestureRecognizer:longTap];

    // if the palette moves we need to hide our popover
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(paletteMoved:)
                                                 name:WDPaletteMovedNotification
                                               object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(canvasStartedTracking:)
                                                 name:WDCanvasBeganTrackingTouches
                                               object:nil];
}

@end


text:
package com.fitpay.android.api.models.card;

import com.fitpay.android.Steps;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CreditCardTest {

    private static Steps steps = null;

    @BeforeClass
    public static void init() {
        steps = new Steps(CreditCardTest.class);
    }

    @AfterClass
    public static void tearDown() throws InterruptedException {
        steps.destroy();
        steps = null;
    }

    @Test
    public void test00_createUser() throws InterruptedException {
        steps.createUser();
    }

    @Test
    public void test01_loginUser() throws InterruptedException {
        steps.login();
    }

    @Test
    public void test02_getUser() throws InterruptedException {
        steps.getUser();
    }

    @Test
    public void test03_addDevice() throws InterruptedException {
        steps.createDevice();
    }

    @Test
    public void test04_createCard() throws InterruptedException {
        steps.createCard();
    }

    @Test
    public void test05_acceptCard() throws InterruptedException {
        steps.acceptTerms();
        steps.selfCard();
    }

    @Test
    public void test06_selectCard() throws InterruptedException {
        steps.selectCard();
        steps.selfCard();
    }

    @Test
    public void test07_verifyCard() throws InterruptedException {
        steps.verifyCard();
        steps.waitForActivation();
    }

    @Test
    public void test08_getTransactions() throws InterruptedException {
        steps.getTransactions();
    }

    @Test
    public void test09_updateCard() throws InterruptedException {
        steps.updateCard();
    }

    @Test
    public void test10_deactivateCard() throws InterruptedException {
        steps.deactivateCard();
    }

    @Test
    public void test11_reactivateCard() throws InterruptedException {
        steps.reactivateCard();
    }

    @Test
    public void test12_createCard() throws InterruptedException {
        steps.createCard("9999411111111116");
    }

    @Test
    public void test13_acceptCard() throws InterruptedException {
        steps.acceptTerms();
        steps.selfCard();
    }

    @Test
    public void test15_selectCard() throws InterruptedException {
        steps.selectCard();
        steps.selfCard();
    }

    @Test
    public void test16_verifyCard() throws InterruptedException {
        steps.verifyCard();
        steps.waitForActivation();
    }

    @Test
    public void test17_makeDefault() throws InterruptedException {
        steps.makeDefault();
    }

    @Test
    public void test18_declineTerms() throws InterruptedException {
        steps.createCard("9999411111111115");
        steps.declineTerms();
    }

    @Test
    public void test99_deleteTestCards() throws InterruptedException {
        steps.deleteTestCards();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<form id='frm' role='form' class='form-horizontal' onsubmit='return push();'>
	<input type='hidden' name='id' id='frm_id' value='$!doc.id'>

		公告标题

			<input type='text' class='input-large' id='frm_title' name='title' value='$!doc.title' />

		公告内容

#formatHtml($!{doc.content})

		<button class='btn btn-info' type='submit'>

			提交
		</button>

		<button class='btn' type='reset'>

			重置
		</button>

</form>


text:
<?php

namespace App\BlogBundle\Tests;

use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Loader;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

/**
 * Class DoctrineTestCase
 *
 * This is the base class to load doctrine fixtures using the symfony configuration
 */
class DoctrineTestCase extends WebTestCase
{
    /**
     * @var \Symfony\Component\DependencyInjection\Container
     */
    protected $container;

    /**
     * @var \Doctrine\ORM\EntityManager
     */
    protected $em;

    /**
     * @var string
     */
    protected $environment = 'test';

    /**
     * @var bool
     */
    protected $debug = true;

    /**
     * @var string
     */
    protected $entityManagerServiceId = 'doctrine.orm.entity_manager';

    /**
     * Constructor
     *
     * @param string|null $name Test name
     * @param array $data Test data
     * @param string $dataName Data name
     */
    public function __construct($name = null, array $data = array(), $dataName = '')
    {
        parent::__construct($name, $data, $dataName);

        if (!static::$kernel) {
            static::$kernel = self::createKernel(array(
                'environment' => $this->environment,
                'debug' => $this->debug
            ));
            static::$kernel->boot();
        }

        $this->container = static::$kernel->getContainer();
        $this->em = $this->getEntityManager();
    }

    /**
     * Executes fixtures
     *
     * @param \Doctrine\Common\DataFixtures\Loader $loader
     */
    protected function executeFixtures(Loader $loader)
    {
        $purger = new ORMPurger();
        $executor = new ORMExecutor($this->em, $purger);
        $executor->execute($loader->getFixtures());
    }

    /**
     * Load and execute fixtures from a directory
     *
     * @param string $directory
     */
    protected function loadFixturesFromDirectory($directory)
    {
        $loader = new Loader();
        $loader->loadFromDirectory($directory);
        $this->executeFixtures($loader);
    }

    /**
     * Returns the doctrine orm entity manager
     *
     * @return object
     */
    protected function getEntityManager()
    {
        return $this->container->get($this->entityManagerServiceId);
    }
}


text:
      {{ if isset .Site.Params "gravatarHash" }}

      {{ end }}
      {{ with .Site.Author.name }}
{{ . | markdownify }}
{{ end }}
      {{ with .Site.Params.tagline }}
{{ . | markdownify }}
{{ end }}

{{ if isset .Site.Params "home"}}{{ .Site.Params.home }}{{ else }}Blog{{ end }}

      {{ range .Site.Menus.main }}

{{ .Pre }}{{ .Name }}

      {{end}}

      {{ with .Site.Params.github }}{{ end }}
      {{ with .Site.Params.bitbucket }}{{ end }}
      {{ with .Site.Params.stackOverflow }}{{ end }}
      {{ with .Site.Params.linkedin }}{{ end }}
      {{ with .Site.Params.googleplus }}{{ end }}
      {{ with .Site.Params.facebook }}{{ end }}
      {{ with .Site.Params.twitter }}{{ end }}
      {{ with .Site.Params.youtube }}{{ end }}
      {{ if .Site.Params.rss }}{{ end }}

    {{ if isset .Site.Params "flattr" }}

    {{ end }}

Some Rights Reserved © {{ .Now.Format "2006" }}

      Proudly powered by Hugo

      Theme: Customized Hyde-X


text:
package at.or.vogt.oe1downloader.download;

import java.time.format.DateTimeFormatter;
import java.util.Calendar;

import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mpatric.mp3agic.ID3v1;
import com.mpatric.mp3agic.ID3v1Tag;
import com.mpatric.mp3agic.ID3v2;
import com.mpatric.mp3agic.ID3v23Tag;
import com.mpatric.mp3agic.Mp3File;

public class MP3FileUtil {

	/** Logger. */
	private final Logger logger = LoggerFactory.getLogger(MP3FileUtil.class);

	ID3v1 setId3v1Tag(final Mp3File mp3file, final RecordVO record) {
		final String methodname = "setId3v1Tag(): ";
		logger.info(methodname);

		final ID3v1 id3v1Tag = new ID3v1Tag();
		setID3Tag(id3v1Tag, record);
		mp3file.setId3v1Tag(id3v1Tag);

		return id3v1Tag;
	}

	ID3v2 setId3v2Tag(final Mp3File mp3file, final RecordVO record) {

		final String methodname = "setId3v1Tag(): ";
		logger.info(methodname);

		final ID3v2 id3v2Tag = new ID3v23Tag();

		setID3Tag(id3v2Tag, record);
		mp3file.setId3v2Tag(id3v2Tag);

		return id3v2Tag;
	}

	private void setID3Tag(final ID3v1 id3v1Tag, final RecordVO record) {
		final String methodname = "setID3Tag(): ";
		logger.info(methodname);

		id3v1Tag.setArtist("OE1");
		final String date = record.getScheduledStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
		final String title = record.getProgramTitle() + " " + record.getTitle();
		id3v1Tag.setTitle(date + " " + title.trim());
		id3v1Tag.setAlbum(date);
		id3v1Tag.setTrack(record.getIndex());
		id3v1Tag.setGenre(12);
		id3v1Tag.setComment(Jsoup.parse(record.getSubtitle()).text());
		id3v1Tag.setYear("" + Calendar.getInstance().get(Calendar.YEAR));

		logger.info(methodname + "id3v1Tag = {}", id3v1Tag);
	}

}


text:
<?php

namespace Faker\Provider\ne_NP;

class Internet extends \Faker\Provider\Internet
{
    protected static $freeEmailDomain = array('gmail.com', 'yahoo.com', 'hotmail.com');
    protected static $tld = array('com', 'com', 'com', 'net', 'org');

    protected static $emailFormats = array(
        '{{userName}}@{{domainName}}',
        '{{userName}}@{{domainName}}',
        '{{userName}}@{{freeEmailDomain}}',
        '{{userName}}@{{domainName}}.np',
        '{{userName}}@{{domainName}}.np',
        '{{userName}}@{{domainName}}.np',
    );

    protected static $urlFormats = array(
        'http://www.{{domainName}}.np/',
        'http://www.{{domainName}}.np/',
        'http://{{domainName}}.np/',
        'http://{{domainName}}.np/',
        'http://www.{{domainName}}.np/{{slug}}',
        'http://www.{{domainName}}.np/{{slug}}.html',
        'http://{{domainName}}.np/{{slug}}',
        'http://{{domainName}}.np/{{slug}}',
        'http://{{domainName}}/{{slug}}.html',
        'http://www.{{domainName}}/',
        'http://{{domainName}}/',
    );
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>HostGator Web Hosting Website Startup Guide</title>
<link rel="stylesheet" href="http://www.hostgatorsupport.com/style.css" type="text/css" />

    cPanel Login

    Webmail Login

        Getting Started

        Billing / Invoices

        Video Tutorials

        Purchase / Transfer Domain Name

        Knowledgebase

        Ticket System

        Online Forums

        Contact US

    | HostGator.com Web Hosting |

  Copyright 2014 © HostGator.com


text:
import { BuilderUtil } from "../context";
import { FinalAsset, FinalModule, Packager } from "../../types";
import StringBuilder from "../../utils/string-builder";
import { chunkInit } from "../../runtime/create-runtime";
import { get } from "../../utils/get";

const importLazy = require("import-lazy")(require);
const path = require("path");
const generate = importLazy("@babel/generator");

const PACKAGER_NAME = "quase_builder_js_packager";

async function render(
  module: FinalModule,
  hashIds: ReadonlyMap<string, string>,
  ctx: BuilderUtil
) {
  if (module.type !== "js") {
    throw new Error(`Module ${module.id} is not of type 'js'`);
  }

  const { data, map, ast } = ctx.deserializeAsset(module.asset);
  const program = ast && ast.program;

  if (!program) {
    throw new Error(`${PACKAGER_NAME}: No AST? ${module.id}`);
  }

  const meta = program._meta;

  if (!meta) {
    throw new Error(`${PACKAGER_NAME}: No metadata in AST? ${module.id}`);
  }

  for (const { source, stringLiteral } of meta.imports) {
    const m = module.dependencies.get(source);
    const newSource = m ? get(hashIds, m.id) : source;
    if (newSource !== stringLiteral.value) {
      stringLiteral.value = newSource;
    }
  }

  const optimization = ctx.builderOptions.optimization;

  const opts = {
    filename: module.relativePath,
    sourceFileName: module.path,
    sourceMaps: !!optimization.sourceMaps, // sourceMaps can be "inline", just make sure we pass a boolean to babel
    comments: !optimization.minify,
    minified: optimization.minify,
  };

  const generateResult = generate.default(
    program,
    opts,
    ctx.dataToString(data)
  );

  return {
    code: generateResult.code,
    map:
      optimization.sourceMaps &&
      (await ctx.joinSourceMaps([map, generateResult.map])),
    quaseApiVar: meta.quaseApiVar,
  };
}

export const packager: Packager = {
  async pack(
    _options,
    asset: FinalAsset,
    _,
    hashIds: ReadonlyMap<string, string>,
    ctx: BuilderUtil
  ) {
    const { module: entryModule, relativeDest } = asset;

    if (entryModule.type !== "js") {
      return null;
    }

    const build = new StringBuilder({
      sourceMap: ctx.builderOptions.optimization.sourceMaps,
      cwd: ctx.builderOptions.cwd,
      file: path.basename(relativeDest),
    });

    build.append(`${chunkInit}.p({`);

    let first = true;

    for (const module of asset.srcs.values()) {
      const { code, map, quaseApiVar } = await render(module, hashIds, ctx);

      build.append(
        `${first ? "" : ","}\n${ctx.wrapInJsPropKey(
          get(hashIds, module.id)
        )}:function(${quaseApiVar.value}){`
      );
      build.append(code, ctx.isFakePath(module.path) ? null : map);
      build.append("\n}");

      first = false;
    }

    build.append("}");

    // Runtime info
    if (asset.runtime.manifest) {
      build.append(`,${JSON.stringify(asset.runtime.manifest)}`);
    }

    build.append(");");

    const runtimeCode = asset.runtime.code;
    if (runtimeCode) {
      build.append(
        runtimeCode.replace(
          /;?$/,
          `(${ctx.wrapInJsString(get(hashIds, entryModule.id))});`
        )
      );
    }

    return build.finish();
  },
};

export default packager;


text:
"""An implementation of the Federated Averaging algorithm.

This code delegates most of its implementation to TFF defaults.
"""
import collections
from typing import Callable, Optional

import tensorflow as tf
import tensorflow_federated as tff

DEFAULT_CLIENT_OPTIMIZER_FN = lambda: tf.keras.optimizers.SGD(learning_rate=0.1)

def _unpack_data_label(batch):
  if isinstance(batch, collections.abc.Mapping):
    return batch['x'], batch['y']
  elif isinstance(batch, (tuple, list)):
    if len(batch) < 2:
      raise ValueError('Expecting both data and label from a batch.')
    return batch[0], batch[1]
  else:
    raise ValueError('Unrecognized batch data.')

@tf.function
def keras_evaluate(model, test_data, metrics):
  """Evaluates a Keras model against `test_data`, for each `metric`."""
  for metric in metrics:
    metric.reset_states()
  # Force autograph to generate a while+scan pattern, which TF may be able to
  # more easily partition across multiple GPUs.
  for batch in iter(test_data):
    batch_x, batch_y = _unpack_data_label(batch)
    preds = model(batch_x, training=False)
    for metric in metrics:
      metric.update_state(y_true=batch_y, y_pred=preds)
  return tf.nest.map_structure(lambda x: x.result(), metrics)

def build_dpftrl_fedavg_process(
    model_fn: Callable[[], tff.learning.Model],
    client_optimizer_fn: Callable[
        [], tf.keras.optimizers.Optimizer] = DEFAULT_CLIENT_OPTIMIZER_FN,
    *,  # Require named (non-positional) parameters for the following kwargs:
    server_learning_rate: float = .1,
    server_momentum: float = .9,
    server_nesterov: bool = False,
    use_experimental_simulation_loop: bool = False,
    dp_aggregator_factory: Optional[
        tff.aggregators.DifferentiallyPrivateFactory] = None,
) -> tff.learning.templates.LearningProcess:
  """Builds an iterative process that performs federated averaging with differential privacy.

  This function creates a `tff.learning.templates.LearningProcess`. The server
  optimizer is DP-FTRL, as described in:

  "Practical and Private (Deep) Learning without Sampling or Shuffling".

  Args:
    model_fn: A no-arg function that returns a `tff.learning.Model`. This method
      must *not* capture TensorFlow tensors or variables and use them. The model
      must be constructed entirely from scratch on each invocation, returning
      the same pre-constructed model each call will result in an error.
    client_optimizer_fn: A no-arg callable that returns a `tf.keras.Optimizer`.
    server_learning_rate: The learning rate of server DP-FTRL optimizer.
    server_momentum: The momentum of server DP-FTRL optimizer.
    server_nesterov: If true, use Nesterov momentum instead of heavyball.
    use_experimental_simulation_loop: Controls the reduce loop function for
      input dataset. An experimental reduce loop is used for simulation. It is
      currently necessary to set this flag to True for performant GPU
      simulations.
    dp_aggregator_factory: Optional instance of
      `tff.aggregators.DifferentiallyPrivateFactory` to use as aggregator. If
      `None`, TFF's default aggregator (weighted mean, with no privacy) is used.

  Returns:
    A `tff.templates.IterativeProcess`.
  """

  def server_optimizer_fn():
    return tf.keras.optimizers.SGD(
        learning_rate=server_learning_rate,
        momentum=server_momentum,
        nesterov=server_nesterov)

  return tff.learning.algorithms.build_unweighted_fed_avg(
      model_fn,
      client_optimizer_fn,
      server_optimizer_fn,
      model_aggregator=dp_aggregator_factory,
      use_experimental_simulation_loop=use_experimental_simulation_loop)


text:
package com.thms.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.core.convert.converter.Converter;

public class StringToIntegerConverter implements Converter<String, Integer> {

	@Override
	public Integer convert(String str) {
		if(StringUtils.isNotEmpty(str)){
			return Integer.valueOf(str);
		}
		return null;
	}
}


text:
<?php

namespace SMSApi\Api\Action\Phonebook;

use SMSApi\Api\Action\AbstractAction;
use SMSApi\Proxy\Uri;

/**
 * Class GroupGet
 * @package SMSApi\Api\Action\Phonebook
 */
class GroupGet extends AbstractAction {

	/**
	 * @param $data
	 * @return \SMSApi\Api\Response\GroupResponse
	 */
	protected function response( $data ) {

		return new \SMSApi\Api\Response\GroupResponse( $data );
	}

	/**
	 * @return Uri
	 */
	public function uri() {

		$query = "";

		$query .= $this->paramsLoginToQuery();

		$query .= $this->paramsOther();

		return new Uri( $this->proxy->getProtocol(), $this->proxy->getHost(), $this->proxy->getPort(), "/api/phonebook.do", $query );
	}

	/**
	 * @deprecated since v1.0.0
	 * @param $groupName
	 * @return $this
	 */
	public function setGroup( $groupName ) {
		return $this->filterByGroupName($groupName);
	}

	/**
	 * Set group name to find.
	 *
	 * @param string $groupName group name
	 * @return $this
	 */
	public function filterByGroupName( $groupName ) {
		$this->params[ "get_group" ] = $groupName;
		return $this;
	}

}


text:
<?php
namespace App\Model;

use Nette,
	Nette\Application\UI,
	Nette\Database\Context,
	Tracy\Debugger as Debugger;

class Language extends Nette\Object  {

	public static $lang = 'cs';

	public static $_cachePrefix = array();

	public static $Request = null;

	public static $languages = array(
		'cs', 'en'
	);

	public function __construct(Nette\Http\Request $Request) {
		$lang = false;
		$url  = trim($Request->getUrl()->getPath(), '/');
		foreach(explode('/', $url) as $path) {
			if (preg_match('#[a-z]{2}#', $path) && in_array($path, self::$languages)) {
				$lang = $path;
				break;
			}

			break;
		}

		self::$lang = $lang ? $lang : 'cs';
	}

	public static function set($lang) {
		self::$lang = $lang;
	}

	public static function get($prefix = null) {
		if (!$prefix) {
			return self::$lang;
		}

		if (isset(self::$_cachePrefix[$prefix])) {
			return self::$_cachePrefix[$prefix];
		}

		return self::$_cachePrefix[$prefix] = $prefix . strtoupper(self::$lang);
	}

	public function getLang() {
		return self::$lang;
	}

}


text:
namespace ash {
namespace network_diagnostics {

namespace {

// TODO(https://crbug.com/1164001): remove when migrated to namespace ash.
namespace mojom = ::chromeos::network_diagnostics::mojom;

constexpr mojom::RoutineVerdict kInitialVerdict =
    mojom::RoutineVerdict::kNotRun;
constexpr mojom::RoutineVerdict kVerdict = mojom::RoutineVerdict::kNoProblem;

constexpr mojom::RoutineType kType = mojom::RoutineType::kHttpFirewall;

}  // namespace

class NetworkDiagnosticsRoutineTest : public ::testing::Test {
 public:
  // Minimal definition for an inherited NetworkDiagnosticsRoutine class.
  class TestNetworkDiagnosticsRoutine : public NetworkDiagnosticsRoutine {
   public:
    TestNetworkDiagnosticsRoutine() = default;
    TestNetworkDiagnosticsRoutine(const TestNetworkDiagnosticsRoutine&) =
        delete;
    TestNetworkDiagnosticsRoutine& operator=(
        const TestNetworkDiagnosticsRoutine&) = delete;
    ~TestNetworkDiagnosticsRoutine() override {}

    // NetworkDiagnosticRoutine:
    mojom::RoutineType Type() override { return kType; }
    void Run() override { ExecuteCallback(); }
    void AnalyzeResultsAndExecuteCallback() override {}
  };

  NetworkDiagnosticsRoutineTest() {
    test_network_diagnostics_routine_ =
        std::make_unique<TestNetworkDiagnosticsRoutine>();
  }

  TestNetworkDiagnosticsRoutine* test_network_diagnostics_routine() {
    return test_network_diagnostics_routine_.get();
  }

  void set_verdict(mojom::RoutineVerdict verdict) {
    test_network_diagnostics_routine()->set_verdict(verdict);
  }

  void set_problems(mojom::RoutineProblemsPtr problems) {
    test_network_diagnostics_routine()->set_problems(problems.Clone());
  }

  void set_can_run(bool can_run) { can_run_ = can_run; }

 private:
  std::unique_ptr<TestNetworkDiagnosticsRoutine>
      test_network_diagnostics_routine_;
  bool can_run_ = true;

  base::test::TaskEnvironment task_environment_;
};

TEST_F(NetworkDiagnosticsRoutineTest, TestDefaultRoutine) {
  TestNetworkDiagnosticsRoutine* routine = test_network_diagnostics_routine();
  set_verdict(kVerdict);
  base::RunLoop run_loop;

  routine->RunRoutine(
      base::BindLambdaForTesting([&](mojom::RoutineResultPtr result) {
        EXPECT_EQ(result->verdict, kVerdict);
        EXPECT_FALSE(result->timestamp.is_null());
        run_loop.Quit();
      }));

  run_loop.Run();
}

TEST_F(NetworkDiagnosticsRoutineTest, NotRunRoutine) {
  TestNetworkDiagnosticsRoutine* routine = test_network_diagnostics_routine();
  set_can_run(false);
  base::RunLoop run_loop;

  routine->RunRoutine(
      base::BindLambdaForTesting([&](mojom::RoutineResultPtr result) {
        EXPECT_EQ(result->verdict, kInitialVerdict);
        EXPECT_FALSE(result->timestamp.is_null());
        run_loop.Quit();
      }));

  run_loop.Run();
}

}  // namespace network_diagnostics
}  // namespace ash


text:
export HADOOP_LOG_DIR=${HDFS_LOG_DIR}
export HADOOP_PID_DIR=${HDFS_PID_DIR}

python /tmp/zk_wait.py datanode

su - ${HDFS_USER} -p -c "${HADOOP_HOME}/sbin/hadoop-daemon.sh --config ${HADOOP_CONF_DIR} start datanode"

# FIXME
python /tmp/zk_set.py datanode up

echo "Log is  ${HDFS_LOG_DIR}/*datanode-${HOSTNAME}.out"

tail -f ${HDFS_LOG_DIR}/*datanode-${HOSTNAME}.out


text:
namespace {

views::MessageBoxView::InitParams GetInitParams(
    const string16& message,
    content::WebContents* web_contents) {
  views::MessageBoxView::InitParams params(message);
  if (web_contents) {
    if (Browser* browser = chrome::FindBrowserWithWebContents(web_contents)) {
      params.clipboard_source_tag =
        content::BrowserContext::GetMarkerForOffTheRecordContext(
            browser->profile());
    }
  }
  return params;
}

} // namespace

// static
TabModalConfirmDialog* TabModalConfirmDialog::Create(
    TabModalConfirmDialogDelegate* delegate,
    content::WebContents* web_contents) {
  return new TabModalConfirmDialogViews(
      delegate, web_contents);
}

//////////////////////////////////////////////////////////////////////////////
// TabModalConfirmDialogViews, constructor & destructor:

TabModalConfirmDialogViews::TabModalConfirmDialogViews(
    TabModalConfirmDialogDelegate* delegate,
    content::WebContents* web_contents)
    : delegate_(delegate),
      message_box_view_(new views::MessageBoxView(
          GetInitParams(delegate->GetMessage(), web_contents))),
      dialog_(NULL),
      browser_context_(web_contents->GetBrowserContext()) {
  WebContentsModalDialogManager* web_contents_modal_dialog_manager =
      WebContentsModalDialogManager::FromWebContents(web_contents);
  dialog_ = CreateWebContentsModalDialogViews(
      this,
      web_contents->GetView()->GetNativeView(),
      web_contents_modal_dialog_manager->delegate()->
          GetWebContentsModalDialogHost());
  web_contents_modal_dialog_manager->ShowDialog(dialog_->GetNativeView());
  delegate_->set_close_delegate(this);
}

TabModalConfirmDialogViews::~TabModalConfirmDialogViews() {
}

void TabModalConfirmDialogViews::AcceptTabModalDialog() {
  GetDialogClientView()->AcceptWindow();
}

void TabModalConfirmDialogViews::CancelTabModalDialog() {
  GetDialogClientView()->CancelWindow();
}

void TabModalConfirmDialogViews::CloseDialog() {
  dialog_->Close();
}

//////////////////////////////////////////////////////////////////////////////
// TabModalConfirmDialogViews, views::DialogDelegate implementation:

string16 TabModalConfirmDialogViews::GetWindowTitle() const {
  return delegate_->GetTitle();
}

string16 TabModalConfirmDialogViews::GetDialogButtonLabel(
    ui::DialogButton button) const {
  if (button == ui::DIALOG_BUTTON_OK)
    return delegate_->GetAcceptButtonTitle();
  if (button == ui::DIALOG_BUTTON_CANCEL)
    return delegate_->GetCancelButtonTitle();
  return string16();
}

bool TabModalConfirmDialogViews::Cancel() {
  delegate_->Cancel();
  return true;
}

bool TabModalConfirmDialogViews::Accept() {
  delegate_->Accept();
  return true;
}

///////////////////////////////////////////////////////////////////////////////
// TabModalConfirmDialogViews, views::WidgetDelegate implementation:

views::View* TabModalConfirmDialogViews::GetContentsView() {
  return message_box_view_;
}

// TODO(wittman): Remove this override once we move to the new style frame view
// on all dialogs.
views::NonClientFrameView* TabModalConfirmDialogViews::CreateNonClientFrameView(
    views::Widget* widget) {
  return CreateConstrainedStyleNonClientFrameView(widget, browser_context_);
}

views::Widget* TabModalConfirmDialogViews::GetWidget() {
  return message_box_view_->GetWidget();
}

const views::Widget* TabModalConfirmDialogViews::GetWidget() const {
  return message_box_view_->GetWidget();
}

void TabModalConfirmDialogViews::DeleteDelegate() {
  delete this;
}

ui::ModalType TabModalConfirmDialogViews::GetModalType() const {
#if defined(USE_ASH)
  return ui::MODAL_TYPE_CHILD;
#else
  return views::WidgetDelegate::GetModalType();
#endif
}


text:
namespace MMS.ServiceBus.Pipeline.Incoming
{
    using System.Threading.Tasks;

    public class IncomingPipelineFactory : IIncomingPipelineFactory
    {
        private readonly IHandlerRegistry registry;
        private readonly IMessageSerializer serializer;

        public IncomingPipelineFactory(IHandlerRegistry registry, IMessageSerializer serializer)
        {
            this.registry = registry;
            this.serializer = serializer;
        }

        public Task WarmupAsync()
        {
            return Task.FromResult(0);
        }

        public IncomingPipeline Create()
        {
            var pipeline = new IncomingPipeline();

            pipeline.Transport
                .Register(new DeadLetterMessagesWhichCantBeDeserializedStep())
                .Register(new DeserializeTransportMessageStep(this.serializer));

            pipeline.Logical
                .Register(new DeadLetterMessagesWhenDelayedRetryCountIsReachedStep())
                .Register(new DelayMessagesWhenImmediateRetryCountIsReachedStep())
                .Register(new DeadletterMessageImmediatelyExceptionStep())
                .Register(new LoadMessageHandlersStep(this.registry))
                .Register(new InvokeHandlerStep());

            return pipeline;
        }

        public Task CooldownAsync()
        {
            return Task.FromResult(0);
        }
    }
}


text:
class GURL;
struct FrameHostMsg_DidFailProvisionalLoadWithError_Params;
struct FrameHostMsg_OpenURL_Params;
struct FrameMsg_Navigate_Params;

namespace base {
class FilePath;
class ListValue;
}

namespace content {

class CrossProcessFrameConnector;
class CrossSiteTransferringRequest;
class FrameTree;
class FrameTreeNode;
class RenderFrameHostDelegate;
class RenderProcessHost;
class RenderViewHostImpl;
struct ContextMenuParams;
struct GlobalRequestID;
struct Referrer;

class CONTENT_EXPORT RenderFrameHostImpl : public RenderFrameHost {
 public:
  static RenderFrameHostImpl* FromID(int process_id, int routing_id);

  virtual ~RenderFrameHostImpl();

  // RenderFrameHost
  virtual int GetRoutingID() OVERRIDE;
  virtual SiteInstance* GetSiteInstance() OVERRIDE;
  virtual RenderProcessHost* GetProcess() OVERRIDE;
  virtual RenderFrameHost* GetParent() OVERRIDE;
  virtual bool IsCrossProcessSubframe() OVERRIDE;
  virtual GURL GetLastCommittedURL() OVERRIDE;
  virtual gfx::NativeView GetNativeView() OVERRIDE;
  virtual void DispatchBeforeUnload(bool for_cross_site_transition) OVERRIDE;
  virtual void NotifyContextMenuClosed(
      const CustomContextMenuContext& context) OVERRIDE;
  virtual void ExecuteCustomContextMenuCommand(
      int action, const CustomContextMenuContext& context) OVERRIDE;
  virtual void Cut() OVERRIDE;
  virtual void Copy() OVERRIDE;
  virtual void Paste() OVERRIDE;
  virtual void InsertCSS(const std::string& css) OVERRIDE;
  virtual void ExecuteJavaScript(
      const base::string16& javascript) OVERRIDE;
  virtual void ExecuteJavaScript(
      const base::string16& javascript,
      const JavaScriptResultCallback& callback) OVERRIDE;
  virtual RenderViewHost* GetRenderViewHost() OVERRIDE;

  // IPC::Sender
  virtual bool Send(IPC::Message* msg) OVERRIDE;

  // IPC::Listener
  virtual bool OnMessageReceived(const IPC::Message& msg) OVERRIDE;

  void Init();
  int routing_id() const { return routing_id_; }
  void OnCreateChildFrame(int new_routing_id,
                          const std::string& frame_name);

  RenderViewHostImpl* render_view_host() { return render_view_host_; }
  RenderFrameHostDelegate* delegate() { return delegate_; }
  FrameTreeNode* frame_tree_node() { return frame_tree_node_; }

  // This function is called when this is a swapped out RenderFrameHost that
  // lives in the same process as the parent frame. The
  // |cross_process_frame_connector| allows the non-swapped-out
  // RenderFrameHost for a frame to communicate with the parent process
  // so that it may composite drawing data.
  //
  // Ownership is not transfered.
  void set_cross_process_frame_connector(
      CrossProcessFrameConnector* cross_process_frame_connector) {
    cross_process_frame_connector_ = cross_process_frame_connector;
  }

  // Returns a bitwise OR of bindings types that have been enabled for this
  // RenderFrameHostImpl's RenderView. See BindingsPolicy for details.
  // TODO(creis): Make bindings frame-specific, to support cases like <webview>.
  int GetEnabledBindings();

  // Called on the pending RenderFrameHost when the network response is ready to
  // commit.  We should ensure that the old RenderFrameHost runs its unload
  // handler and determine whether a transfer to a different RenderFrameHost is
  // needed.
  void OnCrossSiteResponse(
      const GlobalRequestID& global_request_id,
      scoped_ptr<CrossSiteTransferringRequest> cross_site_transferring_request,
      const std::vector<GURL>& transfer_url_chain,
      const Referrer& referrer,
      PageTransition page_transition,
      bool should_replace_current_entry);

  // Hack to get this subframe to swap out, without yet moving over all the
  // SwapOut state and machinery from RenderViewHost.
  void SwapOut();
  void OnSwappedOut(bool timed_out);
  bool is_swapped_out() { return is_swapped_out_; }
  void set_swapped_out(bool is_swapped_out) {
    is_swapped_out_ = is_swapped_out;
  }

  // Sets the RVH for |this| as pending shutdown. |on_swap_out| will be called
  // when the SwapOutACK is received.
  void SetPendingShutdown(const base::Closure& on_swap_out);

  // TODO(nasko): This method is public so RenderViewHostImpl::Navigate can
  // call it directly. It should be made private once Navigate moves here.
  void OnDidStartLoading();

  // Sends the given navigation message. Use this rather than sending it
  // yourself since this does the internal bookkeeping described below. This
  // function takes ownership of the provided message pointer.
  //
  // If a cross-site request is in progress, we may be suspended while waiting
  // for the onbeforeunload handler, so this function might buffer the message
  // rather than sending it.
  void Navigate(const FrameMsg_Navigate_Params& params);

  // Load the specified URL; this is a shortcut for Navigate().
  void NavigateToURL(const GURL& url);

 protected:
  friend class RenderFrameHostFactory;

  // TODO(nasko): Remove dependency on RenderViewHost here. RenderProcessHost
  // should be the abstraction needed here, but we need RenderViewHost to pass
  // into WebContentsObserver::FrameDetached for now.
  RenderFrameHostImpl(RenderViewHostImpl* render_view_host,
                      RenderFrameHostDelegate* delegate,
                      FrameTree* frame_tree,
                      FrameTreeNode* frame_tree_node,
                      int routing_id,
                      bool is_swapped_out);

 private:
  friend class TestRenderFrameHost;
  friend class TestRenderViewHost;

  // IPC Message handlers.
  void OnDetach();
  void OnFrameFocused();
  void OnOpenURL(const FrameHostMsg_OpenURL_Params& params);
  void OnDidStartProvisionalLoadForFrame(int parent_routing_id,
                                         bool main_frame,
                                         const GURL& url);
  void OnDidFailProvisionalLoadWithError(
      const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params);
  void OnDidFailLoadWithError(
      const GURL& url,
      bool is_main_frame,
      int error_code,
      const base::string16& error_description);
  void OnDidRedirectProvisionalLoad(int32 page_id,
                                    const GURL& source_url,
                                    const GURL& target_url);
  void OnNavigate(const IPC::Message& msg);
  void OnDidStopLoading();
  void OnBeforeUnloadACK(
      bool proceed,
      const base::TimeTicks& renderer_before_unload_start_time,
      const base::TimeTicks& renderer_before_unload_end_time);
  void OnSwapOutACK();
  void OnContextMenu(const ContextMenuParams& params);
  void OnJavaScriptExecuteResponse(int id, const base::ListValue& result);

  // Returns whether the given URL is allowed to commit in the current process.
  // This is a more conservative check than RenderProcessHost::FilterURL, since
  // it will be used to kill processes that commit unauthorized URLs.
  bool CanCommitURL(const GURL& url);

  // For now, RenderFrameHosts indirectly keep RenderViewHosts alive via a
  // refcount that calls Shutdown when it reaches zero.  This allows each
  // RenderFrameHostManager to just care about RenderFrameHosts, while ensuring
  // we have a RenderViewHost for each RenderFrameHost.
  // TODO(creis): RenderViewHost will eventually go away and be replaced with
  // some form of page context.
  RenderViewHostImpl* render_view_host_;

  RenderFrameHostDelegate* delegate_;

  // |cross_process_frame_connector_| passes messages from an out-of-process
  // child frame to the parent process for compositing.
  //
  // This is only non-NULL when this is the swapped out RenderFrameHost in
  // the same site instance as this frame's parent.
  //
  // See the class comment above CrossProcessFrameConnector for more
  // information.
  //
  // This will move to RenderFrameProxyHost when that class is created.
  CrossProcessFrameConnector* cross_process_frame_connector_;

  // Reference to the whole frame tree that this RenderFrameHost belongs to.
  // Allows this RenderFrameHost to add and remove nodes in response to
  // messages from the renderer requesting DOM manipulation.
  FrameTree* frame_tree_;

  // The FrameTreeNode which this RenderFrameHostImpl is hosted in.
  FrameTreeNode* frame_tree_node_;

  // The mapping of pending JavaScript calls created by
  // ExecuteJavaScript and their corresponding callbacks.
  std::map<int, JavaScriptResultCallback> javascript_callbacks_;

  int routing_id_;
  bool is_swapped_out_;

  // When the last BeforeUnload message was sent.
  base::TimeTicks send_before_unload_start_time_;

  DISALLOW_COPY_AND_ASSIGN(RenderFrameHostImpl);
};

}  // namespace content

#endif  // CONTENT_BROWSER_FRAME_HOST_RENDER_FRAME_HOST_IMPL_H_


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

#include <zcl/debug.h>
#include <zcl/byteslice.h>
#include <zcl/string.h>

int z_byte_slice_strcmp (const z_byte_slice_t *self, const char *str) {
  z_byte_slice_t other;
  z_byte_slice_set(&other, str, z_strlen(str));
  return(z_byte_slice_compare(self, &other));
}

int z_byte_slice_compare (const z_byte_slice_t *self, const z_byte_slice_t *other) {
  if (self->size != other->size) {
    int cmp = z_memcmp(self->data, other->data, z_min(self->size, other->size));
    return((cmp != 0) ? cmp : (self->size - other->size));
  }
  return(z_memcmp(self->data, other->data, self->size));
}


text:
package me.calebjones.spacelaunchnow.common.ui.supporter;

import static com.anjlab.android.iab.v3.Constants.*;

public class BillingErrorProcessor {
    public static String getResponseCodeDescription(int errorCode){
        switch (errorCode){
            case BILLING_RESPONSE_RESULT_OK:
                return "Success.";
            case BILLING_RESPONSE_RESULT_USER_CANCELED:
                return "User pressed back or canceled a dialog.";
            case BILLING_RESPONSE_RESULT_SERVICE_UNAVAILABLE:
                return "Network connection is down";
            case BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE:
                return "Billing API version is not supported for the type requested.";
            case BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE:
                return "Requested product is not available for purchase.";
            case BILLING_RESPONSE_RESULT_DEVELOPER_ERROR:
                return "Unknown Developer Error.";
            case BILLING_RESPONSE_RESULT_ERROR:
                return "Fatal error during the API action.";
            case BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED:
                return "Failure to purchase since item is already owned.";
            case BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED:
                return "Failure to consume since item is not owned.";
            default:
                return "Unknown error encountered.";
        }
    }
}


text:
<div class="dvs-permission-group" data-operator="<?= (isset($operator)) ? $operator : 'and' ?>">
    <button class="dvs-remove-group dvs-button dvs-button-solid dvs-button-danger" <?= (!isset($subgroup)) ? 'style="display:none"' : '' ?> type="button">- Subgroup</button>
    <button class="dvs-add-group dvs-button dvs-button-solid" type="button">+ Subgroup</button>
    <button class="dvs-add-rule dvs-button dvs-button-solid" type="button">+ Rule</button>
    Operator<?= Form::select('condition', ['and' => 'And','or' => 'Or'], (isset($operator)) ? $operator : null, array('class' => 'operator-types')) ?>

        @if(isset($rules))
            <?php $counter = 1 ?>
            @foreach($rules as $ruleName => $params)
                @include('devise::admin.permissions._rule', array('ruleName'=>$ruleName, 'params' => $params))
                @if(count($rules) > 1 && $counter++ != count($rules))
                    @include('devise::admin.permissions._operator')
                @endif
            @endforeach
        @else
            @include('devise::admin.permissions._rule')
        @endif

    @if(isset($groups))
        @foreach($groups as $operator => $groupData)
            @include('devise::admin.permissions._group', array('rules' => array_except($groupData,['or','and']), 'groups' => array_only($groupData,['or','and'])))
        @endforeach
    @endif


text:
"""
plantweb executable module entry point.
"""

from sys import exit

def run():

    # Parse arguments
    from .args import InvalidArguments, parse_args
    try:
        args = parse_args()
    except InvalidArguments:
        exit(1)

    # Run program
    from .main import main
    exit(main(args))

if __name__ == '__main__':
    run()

__all__ = []


text:
namespace blink::origin_trials {

bool IsTrialPersistentToNextResponse(base::StringPiece trial_name) {
  static base::StringPiece const kPersistentTrials[] = {
      // Enable the FrobulatePersistent* trials as a persistent trials for
      // tests.
      "FrobulatePersistent",
      "FrobulatePersistentExpiryGracePeriod",
  };
  return base::Contains(kPersistentTrials, trial_name);
}

}  // namespace blink::origin_trials


text:
[![Gitter chat](https://badges.gitter.im/gitterHQ/gitter.png)](https://gitter.im/GalaxyProteomics/omicron-galaxy)

# omicron-galaxy
A Docker container for Omicron, a proteogenomics-oriented Galaxy flavor developed by the Zhang Lab at Vanderbilt.


text:
/* eslint-disable no-var */
var jsdom = require('jsdom');

// browser globals
global.document = jsdom.jsdom('<!doctype html>');
global.window = document.defaultView;
global.navigator = global.window.navigator;

process.env.NODE_ENV = 'test';

// Disable webpack-specific features for tests since
// Mocha doesn't know what to do with them.
['.css', '.scss', '.png', '.jpg'].forEach(ext => {
  require.extensions[ext] = () => null;
});

// Register babel so that it will transpile ES6 to ES5
// before our tests run.
require('babel-register')();


text:
"use strict";
var core_1 = require('@angular/core');
var Ui = (function () {
    function Ui() {
    }
    Ui = __decorate([
        core_1.Component({
            selector: 'ui',
            styles: [],
            template: "<router-outlet></router-outlet>"
        }),
        __metadata('design:paramtypes', [])
    ], Ui);
    return Ui;
}());
exports.Ui = Ui;
//# sourceMappingURL=ui.component.js.map


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>totalWidth - YC.PrettyPrinter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <meta name="description" content=""/>
    <meta name="author" content="Andrey Bulgakov"/>

    <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"/>

    <link type="text/css" rel="stylesheet" href="/YC.PrettyPrinter/content/style.css" />

fsharp.org

github page

YC.PrettyPrinter

totalWidth

  Namespace: YC.PrettyPrinter

  Parent Module: Format

YC.PrettyPrinter

Home page

Get Library via NuGet

Source Code on GitHub

License

Release Notes

Getting started

Sample tutorial

Documentation

API Reference


text:
/*
 * vim:ts=8:sw=3:sts=8:noexpandtab:cino=>5n-3f0^-2{2
 */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <string.h>

#include "Ecore.h"
#include "Ecore_Input.h"

#include "Ecore_Input_Evas.h"
#include "ecore_input_evas_private.h"

int _ecore_input_evas_log_dom = -1;

typedef struct _Ecore_Input_Window Ecore_Input_Window;
struct _Ecore_Input_Window
{
   Evas *evas;
   void *window;
   Ecore_Event_Mouse_Move_Cb move_mouse;
   int ignore_event;
};

static int _ecore_event_evas_init_count = 0;
static Ecore_Event_Handler *ecore_event_evas_handlers[8];
static Eina_Hash *_window_hash = NULL;

EAPI void
ecore_event_evas_modifier_lock_update(Evas *e, unsigned int modifiers)
{
   if (modifiers & ECORE_EVENT_MODIFIER_SHIFT)
     evas_key_modifier_on(e, "Shift");
   else evas_key_modifier_off(e, "Shift");

   if (modifiers & ECORE_EVENT_MODIFIER_CTRL)
     evas_key_modifier_on(e, "Control");
   else evas_key_modifier_off(e, "Control");

   if (modifiers & ECORE_EVENT_MODIFIER_ALT)
     evas_key_modifier_on(e, "Alt");
   else evas_key_modifier_off(e, "Alt");

   if (modifiers & ECORE_EVENT_MODIFIER_WIN)
     {
	evas_key_modifier_on(e, "Super");
	evas_key_modifier_on(e, "Hyper");
     }
   else
     {
	evas_key_modifier_off(e, "Super");
	evas_key_modifier_off(e, "Hyper");
     }

   if (modifiers & ECORE_EVENT_LOCK_SCROLL)
     evas_key_lock_on(e, "Scroll_Lock");
   else evas_key_lock_off(e, "Scroll_Lock");

   if (modifiers & ECORE_EVENT_LOCK_NUM)
     evas_key_lock_on(e, "Num_Lock");
   else evas_key_lock_off(e, "Num_Lock");

   if (modifiers & ECORE_EVENT_LOCK_CAPS)
     evas_key_lock_on(e, "Caps_Lock");
   else evas_key_lock_off(e, "Caps_Lock");
}

EAPI void
ecore_event_window_register(Ecore_Window id, void *window, Evas *evas, Ecore_Event_Mouse_Move_Cb move_mouse)
{
   Ecore_Input_Window *w;

   w = calloc(1, sizeof(Ecore_Input_Window));
   if (!w) return;

   w->evas = evas;
   w->window = window;
   w->move_mouse = move_mouse;
   w->ignore_event = 0;

   eina_hash_add(_window_hash, &id, w);

   evas_key_modifier_add(evas, "Shift");
   evas_key_modifier_add(evas, "Control");
   evas_key_modifier_add(evas, "Alt");
   evas_key_modifier_add(evas, "Meta");
   evas_key_modifier_add(evas, "Hyper");
   evas_key_modifier_add(evas, "Super");
   evas_key_lock_add(evas, "Caps_Lock");
   evas_key_lock_add(evas, "Num_Lock");
   evas_key_lock_add(evas, "Scroll_Lock");
}

EAPI void
ecore_event_window_unregister(Ecore_Window id)
{
   eina_hash_del(_window_hash, &id, NULL);
}

EAPI void *
ecore_event_window_match(Ecore_Window id)
{
   Ecore_Input_Window *lookup;

   lookup = eina_hash_find(_window_hash, &id);
   if (lookup) return lookup->window;
   return NULL;
}

EAPI void
ecore_event_window_ignore_events(Ecore_Window id, int ignore_event)
{
   Ecore_Input_Window *lookup;

   lookup = eina_hash_find(_window_hash, &id);
   if (!lookup) return;
   lookup->ignore_event = ignore_event;
}

static Ecore_Input_Window*
_ecore_event_window_match(Ecore_Window id)
{
   Ecore_Input_Window *lookup;

   lookup = eina_hash_find(_window_hash, &id);
   if (!lookup) return NULL;
   if (lookup->ignore_event) return NULL; /* Pass on event. */
   return lookup;
}

static Eina_Bool
_ecore_event_evas_key(Ecore_Event_Key *e, Ecore_Event_Press press)
{
   Ecore_Input_Window *lookup;

   lookup = _ecore_event_window_match(e->window);
   if (!lookup) return ECORE_CALLBACK_RENEW;
   ecore_event_evas_modifier_lock_update(lookup->evas, e->modifiers);
   if (press == ECORE_DOWN)
     evas_event_feed_key_down(lookup->evas, e->keyname, e->key, e->string, e->compose, e->timestamp, NULL);
   else
     evas_event_feed_key_up(lookup->evas, e->keyname, e->key, e->string, e->compose, e->timestamp, NULL);
   return ECORE_CALLBACK_RENEW;
}

static Eina_Bool
_ecore_event_evas_mouse_button(Ecore_Event_Mouse_Button *e, Ecore_Event_Press press)
{
   Ecore_Input_Window *lookup;
   Evas_Button_Flags flags = EVAS_BUTTON_NONE;

   lookup = _ecore_event_window_match(e->window);
   if (!lookup) return ECORE_CALLBACK_RENEW;
   if (e->double_click) flags |= EVAS_BUTTON_DOUBLE_CLICK;
   if (e->triple_click) flags |= EVAS_BUTTON_TRIPLE_CLICK;
   if (e->multi.device == 0)
     {
        ecore_event_evas_modifier_lock_update(lookup->evas, e->modifiers);
        if (press == ECORE_DOWN)
          evas_event_feed_mouse_down(lookup->evas, e->buttons, flags, e->timestamp, NULL);
        else
          evas_event_feed_mouse_up(lookup->evas, e->buttons, flags, e->timestamp, NULL);
     }
   else
     {
        if (press == ECORE_DOWN)
          evas_event_feed_multi_down(lookup->evas, e->multi.device, e->x, e->y, e->multi.radius, e->multi.radius_x, e->multi.radius_y, e->multi.pressure, e->multi.angle, e->multi.x, e->multi.y, flags, e->timestamp, NULL);
        else
          evas_event_feed_multi_up(lookup->evas, e->multi.device, e->x, e->y, e->multi.radius, e->multi.radius_x, e->multi.radius_y, e->multi.pressure, e->multi.angle, e->multi.x, e->multi.y, flags, e->timestamp, NULL);
     }
   return ECORE_CALLBACK_RENEW;
}

EAPI Eina_Bool
ecore_event_evas_mouse_move(void *data __UNUSED__, int type __UNUSED__, void *event)
{
   Ecore_Event_Mouse_Move *e;
   Ecore_Input_Window *lookup;

   e = event;
   lookup = _ecore_event_window_match(e->window);
   if (!lookup) return ECORE_CALLBACK_RENEW;
   if (e->multi.device == 0)
     {
        ecore_event_evas_modifier_lock_update(lookup->evas, e->modifiers);
        lookup->move_mouse(lookup->window, e->x, e->y, e->timestamp);
     }
   else
     {
        evas_event_feed_multi_move(lookup->evas, e->multi.device, e->x, e->y, e->multi.radius, e->multi.radius_x, e->multi.radius_y, e->multi.pressure, e->multi.angle, e->multi.x, e->multi.y, e->timestamp, NULL);
     }
   return ECORE_CALLBACK_RENEW;
}

EAPI Eina_Bool
ecore_event_evas_mouse_button_down(void *data __UNUSED__, int type __UNUSED__, void *event)
{
   return _ecore_event_evas_mouse_button((Ecore_Event_Mouse_Button *)event, ECORE_DOWN);
}

EAPI Eina_Bool
ecore_event_evas_mouse_button_up(void *data __UNUSED__, int type __UNUSED__, void *event)
{
   return _ecore_event_evas_mouse_button((Ecore_Event_Mouse_Button *)event, ECORE_UP);
}

static Eina_Bool
_ecore_event_evas_mouse_io(Ecore_Event_Mouse_IO *e, Ecore_Event_IO io)
{
   Ecore_Input_Window *lookup;

   lookup = _ecore_event_window_match(e->window);
   if (!lookup) return ECORE_CALLBACK_RENEW;
   ecore_event_evas_modifier_lock_update(lookup->evas, e->modifiers);
   switch (io)
     {
      case ECORE_IN:
	 evas_event_feed_mouse_in(lookup->evas, e->timestamp, NULL);
	 break;
      case ECORE_OUT:
	 evas_event_feed_mouse_out(lookup->evas, e->timestamp, NULL);
	 break;
      default:
	 break;
     }

   lookup->move_mouse(lookup->window, e->x, e->y, e->timestamp);
   return ECORE_CALLBACK_RENEW;
}

EAPI Eina_Bool
ecore_event_evas_key_down(void *data __UNUSED__, int type __UNUSED__, void *event)
{
   return _ecore_event_evas_key((Ecore_Event_Key *)event, ECORE_DOWN);
}

EAPI Eina_Bool
ecore_event_evas_key_up(void *data __UNUSED__, int type __UNUSED__, void *event)
{
   return _ecore_event_evas_key((Ecore_Event_Key *)event, ECORE_UP);
}

EAPI Eina_Bool
ecore_event_evas_mouse_wheel(void *data __UNUSED__, int type __UNUSED__, void *event)
{
   Ecore_Event_Mouse_Wheel *e;
   Ecore_Input_Window *lookup;

   e = event;
   lookup = _ecore_event_window_match(e->window);
   if (!lookup) return ECORE_CALLBACK_RENEW;
   ecore_event_evas_modifier_lock_update(lookup->evas, e->modifiers);
   evas_event_feed_mouse_wheel(lookup->evas, e->direction, e->z, e->timestamp, NULL);
   return ECORE_CALLBACK_RENEW;
}

EAPI Eina_Bool
ecore_event_evas_mouse_in(void *data __UNUSED__, int type __UNUSED__, void *event)
{
   return _ecore_event_evas_mouse_io((Ecore_Event_Mouse_IO *)event, ECORE_IN);
}

EAPI Eina_Bool
ecore_event_evas_mouse_out(void *data __UNUSED__, int type __UNUSED__, void *event)
{
   return _ecore_event_evas_mouse_io((Ecore_Event_Mouse_IO *)event, ECORE_OUT);
}

EAPI int
ecore_event_evas_init(void)
{
   if (++_ecore_event_evas_init_count !=  1)
     return _ecore_event_evas_init_count;

   _ecore_input_evas_log_dom = eina_log_domain_register("EcoreInputEvas",  ECORE_INPUT_EVAS_DEFAULT_LOG_COLOR);
   if (_ecore_input_evas_log_dom < 0)
     {
        EINA_LOG_ERR("Impossible to create a log domain for the ecore input evas_module.");
        return --_ecore_event_evas_init_count;
     }

   if (!ecore_init())
     {
	return --_ecore_event_evas_init_count;
     }

   if (!ecore_event_init())
     {
	goto shutdown_ecore;
     }

   ecore_event_evas_handlers[0] = ecore_event_handler_add(ECORE_EVENT_KEY_DOWN,
							  ecore_event_evas_key_down,
							  NULL);
   ecore_event_evas_handlers[1] = ecore_event_handler_add(ECORE_EVENT_KEY_UP,
							  ecore_event_evas_key_up,
							  NULL);
   ecore_event_evas_handlers[2] = ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_DOWN,
							  ecore_event_evas_mouse_button_down,
							  NULL);
   ecore_event_evas_handlers[3] = ecore_event_handler_add(ECORE_EVENT_MOUSE_BUTTON_UP,
							  ecore_event_evas_mouse_button_up,
							  NULL);
   ecore_event_evas_handlers[4] = ecore_event_handler_add(ECORE_EVENT_MOUSE_MOVE,
							  ecore_event_evas_mouse_move,
							  NULL);
   ecore_event_evas_handlers[5] = ecore_event_handler_add(ECORE_EVENT_MOUSE_WHEEL,
							  ecore_event_evas_mouse_wheel,
							  NULL);
   ecore_event_evas_handlers[6] = ecore_event_handler_add(ECORE_EVENT_MOUSE_IN,
							  ecore_event_evas_mouse_in,
							  NULL);
   ecore_event_evas_handlers[7] = ecore_event_handler_add(ECORE_EVENT_MOUSE_OUT,
							  ecore_event_evas_mouse_out,
							  NULL);

   _window_hash = eina_hash_pointer_new(free);

   return _ecore_event_evas_init_count;

   shutdown_ecore:
   ecore_shutdown();

   return --_ecore_event_evas_init_count;
}

EAPI int
ecore_event_evas_shutdown(void)
{
   size_t i;

   if (--_ecore_event_evas_init_count != 0)
     return _ecore_event_evas_init_count;

   eina_hash_free(_window_hash);
   _window_hash = NULL;
   for (i = 0; i < sizeof(ecore_event_evas_handlers) / sizeof(Ecore_Event_Handler *); i++)
     {
	ecore_event_handler_del(ecore_event_evas_handlers[i]);
	ecore_event_evas_handlers[i] = NULL;
     }

   ecore_event_shutdown();
   ecore_shutdown();

   eina_log_domain_unregister(_ecore_input_evas_log_dom);
   _ecore_input_evas_log_dom = -1;

   return _ecore_event_evas_init_count;
}


text:
import tensorflow as tf
from tensorflow.python.ops import tensor_array_ops
from tensorflow.python.framework import ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import math_ops
#from tensorflow_sparsemax.kernel import sparsemax, sparsemax_loss

# NOTE:
# importing custom tf kernel containing sparsemax op.
# assumes existance of a ../../tensorflow_sparsemax/kernel
# containing a compiled sparsemax kernel
import os.path as path
import sys

thisdir = path.dirname(path.realpath("__file__"))
sys.path.append(path.join(thisdir, '../../tensorflow_sparsemax'))

from kernel import sparsemax, sparsemax_loss

###
# custom loss function, similar to tensorflows but uses 3D tensors
# instead of a list of 2D tensors
def sequence_loss_tensor(logits, targets, weights, num_classes,
                         average_across_timesteps=True,
                         softmax_loss_function=None, name=None):
    """Weighted cross-entropy loss for a sequence of logits (per example).
    """
    with ops.op_scope([logits, targets, weights], name, "sequence_loss_by_example"):
        logits_flat = tf.reshape(logits, [-1, num_classes])
        logits_flat += 1e-6
        targets = tf.reshape(targets, [-1])

        crossent = nn_ops.sparse_softmax_cross_entropy_with_logits(logits_flat, targets)

        crossent = crossent * tf.reshape(weights, [-1])
        crossent = tf.reduce_sum(crossent)
        total_size = math_ops.reduce_sum(weights)
        total_size += 1e-12 # to avoid division by zero
        crossent /= total_size
        return crossent

###
# a custom masking function, takes sequence lengths and makes masks
def mask(sequence_lengths):
    # based on this SO answer: http://stackoverflow.com/a/34138336/118173
    batch_size = tf.shape(sequence_lengths)[0]
    max_len = tf.reduce_max(sequence_lengths)

    lengths_transposed = tf.expand_dims(sequence_lengths, 1)

    rng = tf.range(max_len)
    rng_row = tf.expand_dims(rng, 0)

    return tf.less(rng_row, lengths_transposed)

###
# decoder with attention

def attention_decoder(attention_input, attention_lengths, initial_state,
                      target_input, target_input_lengths, num_units,
                      num_attn_units, embeddings, W_out, b_out, attention_fn,
                      name='decoder', swap=False):
    """Decoder with attention.
    Note that the number of units in the attention decoder must always
    be equal to the size of the initial state/attention input.
    """
    with tf.variable_scope(name):
        target_dims = target_input.get_shape()[2]
        attention_dims = attention_input.get_shape()[2]
        attn_len = tf.shape(attention_input)[1]
        max_sequence_length = tf.reduce_max(target_input_lengths)

        weight_initializer = tf.truncated_normal_initializer(stddev=0.1)
        # map initial state to num_units
        W_s = tf.get_variable('W_s',
                              shape=[attention_dims, num_units],
                              initializer=weight_initializer)
        b_s = tf.get_variable('b_s',
                              shape=[num_units],
                              initializer=tf.constant_initializer())

        # GRU
        W_z = tf.get_variable('W_z',
                              shape=[target_dims+num_units+attention_dims, num_units],
                              initializer=weight_initializer)
        W_r = tf.get_variable('W_r',
                              shape=[target_dims+num_units+attention_dims, num_units],
                              initializer=weight_initializer)
        W_c = tf.get_variable('W_c',
                              shape=[target_dims+num_units+attention_dims, num_units],
                              initializer=weight_initializer)
        b_z = tf.get_variable('b_z',
                              shape=[num_units],
                              initializer=tf.constant_initializer(1.0))
        b_r = tf.get_variable('b_r',
                              shape=[num_units],
                              initializer=tf.constant_initializer(1.0))
        b_c = tf.get_variable('b_c',
                              shape=[num_units],
                              initializer=tf.constant_initializer())

        # for attention
        W_a = tf.get_variable('W_a',
                              shape=[attention_dims, num_attn_units],
                              initializer=weight_initializer)
        U_a = tf.get_variable('U_a',
                              shape=[1, 1, attention_dims, num_attn_units],
                              initializer=weight_initializer)
        b_a = tf.get_variable('b_a',
                              shape=[num_attn_units],
                              initializer=tf.constant_initializer())
        v_a = tf.get_variable('v_a',
                              shape=[num_attn_units],
                              initializer=weight_initializer)

        # project initial state
        initial_state = tf.nn.tanh(tf.matmul(initial_state, W_s) + b_s)

        # TODO: don't use convolutions!
        # TODO: fix the bias (b_a)
        hidden = tf.reshape(attention_input, tf.pack([-1, attn_len, 1, attention_dims]))
        part1 = tf.nn.conv2d(hidden, U_a, [1, 1, 1, 1], "SAME")
        part1 = tf.squeeze(part1, [2])  # squeeze out the third dimension

        inputs = tf.transpose(target_input, perm=[1, 0, 2])
        input_ta = tensor_array_ops.TensorArray(tf.float32, size=1, dynamic_size=True)
        input_ta = input_ta.unpack(inputs)

        def decoder_cond(time, state, output_ta_t, attention_tracker):
            return tf.less(time, max_sequence_length)

        def decoder_body_builder(feedback=False):
            def decoder_body(time, old_state, output_ta_t, attention_tracker):
                if feedback:
                    def from_previous():
                        prev_1 = tf.matmul(old_state, W_out) + b_out
                        return tf.gather(embeddings, tf.argmax(prev_1, 1))
                    x_t = tf.cond(tf.greater(time, 0), from_previous, lambda: input_ta.read(0))
                else:
                    x_t = input_ta.read(time)

                # attention
                part2 = tf.matmul(old_state, W_a) + b_a
                part2 = tf.expand_dims(part2, 1)
                john = part1 + part2
                e = tf.reduce_sum(v_a * tf.tanh(john), [2])
                alpha = attention_fn(e)
                alpha = tf.to_float(mask(attention_lengths)) * alpha
                alpha = alpha / tf.reduce_sum(alpha, [1], keep_dims=True)
                attention_tracker = attention_tracker.write(time, alpha)
                context = tf.reduce_sum(tf.expand_dims(alpha, 2) * tf.squeeze(hidden), [1])

                # GRU
                con = tf.concat(1, [x_t, old_state, context])
                z = tf.sigmoid(tf.matmul(con, W_z) + b_z)
                r = tf.sigmoid(tf.matmul(con, W_r) + b_r)
                con = tf.concat(1, [x_t, r*old_state, context])
                c = tf.tanh(tf.matmul(con, W_c) + b_c)
                new_state = (1-z)*c + z*old_state

                output_ta_t = output_ta_t.write(time, new_state)

                return (time + 1, new_state, output_ta_t, attention_tracker)
            return decoder_body

        output_ta = tensor_array_ops.TensorArray(tf.float32, size=1, dynamic_size=True, infer_shape=False)
        attention_tracker = tensor_array_ops.TensorArray(tf.float32, size=1, dynamic_size=True, infer_shape=False)
        time = tf.constant(0)
        loop_vars = [time, initial_state, output_ta, attention_tracker]

        _, state, output_ta, _ = tf.while_loop(decoder_cond,
                                               decoder_body_builder(),
                                               loop_vars,
                                               swap_memory=swap)
        _, valid_state, valid_output_ta, valid_attention_tracker = tf.while_loop(decoder_cond,
                                                        decoder_body_builder(feedback=True),
                                                        loop_vars,
                                                        swap_memory=swap)

        dec_out = tf.transpose(output_ta.pack(), perm=[1, 0, 2])
        valid_dec_out = tf.transpose(valid_output_ta.pack(), perm=[1, 0, 2])
        valid_attention_tracker = tf.transpose(valid_attention_tracker.pack(), perm=[1, 0, 2])

        return dec_out, valid_dec_out, valid_attention_tracker


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.artirigo.kontaktio">

    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Ranging/monitoring beacons -->
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <!-- Connecting to beacons -->
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    <!-- Communicating with the Kontakt.io Proximity REST API -->
    <!--<uses-permission android:name="android.permission.INTERNET" />-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <!-- Since Marshmallow -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <!-- or -->
    <!-- <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> -->

    <!-- <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="22" /> -->

</manifest>


text:
using System;
using System.IO;
using DotSpatial.Projections.Nad;

namespace DotSpatial.Projections
{
    /// <summary>
    /// This is a special case of a NadTable and has specific reading techniques that need to be handled
    /// </summary>
    public class GsbNadTable : NadTable
    {
        #region Private Variables

        #endregion

        #region Constructors

        /// <summary>
        /// Creates a new instance of GsbNadTable
        /// </summary>
        public GsbNadTable(string resourceLocation, long offset)
            : base(resourceLocation, offset, true)
        {
        }

        /// <summary>
        /// Creates a new instance of GsbNadTable
        /// </summary>
        public GsbNadTable(string location, long offset, bool embedded, bool requiresDecompression)
            : base(location, offset, embedded, requiresDecompression)
        {
            Format = GridShiftTableFormat.GSB;
        }

        #endregion

        #region Methods

        /// <inheritdoc/>
        public override void ReadHeader()
        {
            // If the DataOffset is 0, figure out the sub-table structure,
            // otherwise we are reading a subtable.
            if (DataOffset == 0)
            {
                Initialize();
                return;
            }
            ReadSubGrid();
        }

        /// <summary>
        /// This handles the creation of the
        /// </summary>
        private void Initialize()
        {
            byte[] overviewHeader = new byte[176];
            using (Stream str = GetStream())
            {
                if (str == null) return;
                str.Read(overviewHeader, 0, 176);
            }
            byte[] bCount = new byte[4];
            Array.Copy(overviewHeader, 8 + 32, bCount, 0, 4);
            if (!BitConverter.IsLittleEndian) Array.Reverse(bCount);
            int numGrids = BitConverter.ToInt32(bCount, 0);
            long offset = 176;
            for (int iGrid = 0; iGrid < numGrids; iGrid++)
            {
                string location = FileIsEmbedded ? ManifestResourceString : GridFilePath;
                NadTable sub = new GsbNadTable(location, offset, FileIsEmbedded, RequiresDecompression);
                sub.ReadHeader();
                offset += 176 + sub.NumPhis * sub.NumLambdas * 16;
                SubGrids.Add(sub);
            }
        }

        private void ReadSubGrid()
        {
            byte[] header = new byte[176];
            using (Stream str = GetStream())
            {
                if (str == null) return;
                using (BinaryReader br = new BinaryReader(str))
                {
                    str.Seek(DataOffset, SeekOrigin.Begin);
                    br.Read(header, 0, 176);
                }
            }

            PhiLam ll;
            ll.Phi = GetDouble(header, 4 * 16 + 8);
            ll.Lambda = -GetDouble(header, 7 * 16 + 8);

            double urPhi = GetDouble(header, 5 * 16 + 8);
            double urLam = -GetDouble(header, 6 * 16 + 8);

            PhiLam cs;
            cs.Phi = GetDouble(header, 8 * 16 + 8);
            cs.Lambda = GetDouble(header, 9 * 16 + 8);
            CellSize = cs;

            NumLambdas = (int)(Math.Abs(urLam - ll.Lambda) / cs.Lambda + .5) + 1;
            NumPhis = (int)(Math.Abs(urPhi - ll.Phi) / cs.Phi + .5) + 1;

            ll.Lambda *= DEG_TO_RAD;
            ll.Phi *= DEG_TO_RAD;
            LowerLeft = ll;

            cs.Lambda *= DEG_TO_RAD;
            cs.Phi *= DEG_TO_RAD;
            CellSize = cs;
        }

        /// <inheritdoc/>
        public override void FillData()
        {
            using (Stream str = GetStream())
            {
                if (str == null) return;
                using (BinaryReader br = new BinaryReader(str))
                {
                    str.Seek(DataOffset, SeekOrigin.Begin);
                    str.Seek(176, SeekOrigin.Current);

                    int numPhis = NumPhis;
                    int numLambdas = NumLambdas;
                    PhiLam[][] cvs = new PhiLam[numPhis][];

                    // Skip past rest of header
                    for (int row = 0; row < numPhis; row++)
                    {
                        cvs[row] = new PhiLam[NumLambdas];
                        // NTV order is flipped compared with a normal CVS table
                        for (int col = numLambdas - 1; col >= 0; col--)
                        {
                            // shift values are given in "arc-seconds" and need to be converted to radians.
                            cvs[row][col].Phi = ReadDouble(br) * (Math.PI / 180) / 3600;
                            cvs[row][col].Lambda = ReadDouble(br) * (Math.PI / 180) / 3600;
                        }
                    }
                    Cvs = cvs;
                }
            }
        }

        /// <summary>
        /// Gets the double value from the specified position in the byte array
        /// Using BigEndian format.
        /// </summary>
        /// <param name="array"></param>
        /// <param name="offset"></param>
        /// <returns></returns>
        protected override double GetDouble(byte[] array, int offset)
        {
            byte[] bValue = new byte[8];
            Array.Copy(array, offset, bValue, 0, 8);
            if (!BitConverter.IsLittleEndian) Array.Reverse(bValue);
            double temp = BitConverter.ToDouble(bValue, 0);
            return temp;
        }

        #endregion
    }
}


text:
package present

import (
	"github.com/concourse/concourse/atc"
	"github.com/concourse/concourse/atc/api/accessor"
	"github.com/concourse/concourse/atc/db"
)

func Job(
	teamName string,
	job db.Job,
	access accessor.Access,
	inputs []atc.JobInput,
	outputs []atc.JobOutput,
	finishedBuild db.Build,
	nextBuild db.Build,
	transitionBuild db.Build,
) atc.Job {
	var presentedNextBuild, presentedFinishedBuild, presentedTransitionBuild *atc.Build

	if nextBuild != nil {
		presented := Build(nextBuild, job, access)
		presentedNextBuild = &presented
	}

	if finishedBuild != nil {
		presented := Build(finishedBuild, job, access)
		presentedFinishedBuild = &presented
	}

	if transitionBuild != nil {
		presented := Build(transitionBuild, job, access)
		presentedTransitionBuild = &presented
	}

	sanitizedInputs := []atc.JobInput{}
	for _, input := range inputs {
		sanitizedInputs = append(sanitizedInputs, atc.JobInput{
			Name:     input.Name,
			Resource: input.Resource,
			Passed:   input.Passed,
			Trigger:  input.Trigger,
		})
	}

	sanitizedOutputs := []atc.JobOutput{}
	for _, output := range outputs {
		sanitizedOutputs = append(sanitizedOutputs, atc.JobOutput{
			Name:     output.Name,
			Resource: output.Resource,
		})
	}

	atcJob := atc.Job{
		ID: job.ID(),

		Name:                 job.Name(),
		PipelineID:           job.PipelineID(),
		PipelineName:         job.PipelineName(),
		PipelineInstanceVars: job.PipelineInstanceVars(),
		TeamName:             teamName,
		DisableManualTrigger: job.DisableManualTrigger(),
		Paused:               job.Paused(),
		PausedBy:             job.PausedBy(),
		FirstLoggedBuildID:   job.FirstLoggedBuildID(),
		FinishedBuild:        presentedFinishedBuild,
		NextBuild:            presentedNextBuild,
		TransitionBuild:      presentedTransitionBuild,
		HasNewInputs:         job.HasNewInputs(),

		Inputs:  sanitizedInputs,
		Outputs: sanitizedOutputs,

		Groups: job.Tags(),
	}

	if !job.PausedAt().IsZero() {
		atcJob.PausedAt = job.PausedAt().Unix()
	}

	return atcJob
}


text:
package org.talkingpuffin.snippet

import java.text.NumberFormat
import scala.collection.JavaConversions._
import xml.{Elem, NodeSeq, Text}
import twitter4j.TwitterException
import net.liftweb.widgets.flot.Flot
import net.liftweb.common.Full
import net.liftweb.util.Helpers._
import net.liftweb.http.{RequestVar, SHtml, S}
import net.liftweb.http.js.JsCmds._
import org.talkingpuffin.snippet.GeneralUserInfo.ScreenNames
import org.talkingpuffin.apix.PartitionedTweets
import org.talkingpuffin.apix.RichStatus._
import org.talkingpuffin.user.UserAnalysis
import org.talkingpuffin.snippet.LineCollector.InfoLine
import org.talkingpuffin.util._
import org.apache.commons.lang.StringEscapeUtils
import java.net.UnknownHostException

/**
 * Snippets for user analysis
 */
class UserAnalyzer extends RedirectorWithRequestParms with Loggable {

  private object screenName        extends RequestVar[Option[String]](None)
  private object partitionedTweets extends RequestVar[Option[PartitionedTweets]](None)

  def nameForm(content: NodeSeq) = {
    SessionState.twitter.is match {
      case Some(tw) =>
        S.param("user") match {
          case Full(u) => setScreenName(u)
          case _ =>
            if (! screenName.is.isDefined) {
              screenName(Some(tw.getScreenName))
            }
        }
        bind("nameForm", content,
          "name"   -> SHtml.text(screenName.is.getOrElse(""), setScreenName(_)),
          "submit" -> SHtml.submit("Analyze", () => {}))
      case _ => S.redirectTo("index" + makeUserParm)
    }
  }

  def headForGraph (xhtml: NodeSeq) = Flot.renderHead()

  def followUnfollow = {
    val tw = SessionState.twitter.is.get

    def check(screenName: String)(on: Boolean) = {
      try {
        if (on) tw.createFriendship(screenName) else tw.destroyFriendship(screenName)
        S.notice(if (on) "Followed" else "Unfollowed")
      } catch {
        case te: TwitterException =>
          S.warning(te.getMessage)
          Nil
      }
      Noop
    }

    screenName.is match {
      case Some(screenName) if screenName != tw.getScreenName =>
        try {
          val rel = tw.showFriendship(tw.getScreenName, screenName)
          List(SHtml.ajaxCheckbox(rel.isTargetFollowedBySource, check(screenName)), Text("following"))
        } catch {
          case te: TwitterException =>
            // Error will appear to user from elsewhere
            Nil
        }
      case _ => Nil
    }
  }

  def generalInfo = {
    val tw = SessionState.twitter.is.get
    val emptyRows = List[Elem]()
    val emptyImage = Nil

    val (rows, image) = screenName.is match {
      case Some(screenName) =>
        info(tw.getScreenName + " is analyzing " + screenName)
        try {
          val pt = PartitionedTweets(tw, screenName)
          partitionedTweets(Some(pt))
          val uinfo = tw.lookupUsers(Array(screenName)).get(0)
          val (gnlLines, ua) =
            if (pt.tweets.isEmpty)
              (List(InfoLine("Number of tweets", "0")), None)
            else {
              val uan = UserAnalysis(pt)
              (GeneralUserInfo.create(uinfo, screenName, pt, uan), Some(uan))
            }
          SessionState.userAnalysis(ua)
          val image =
          (makeGnlRows(gnlLines), image)
        } catch {
          case te: TwitterException =>
            val failureMsg = "Unable to fetch data for that user (may be temporary Twitter problem). Status code: " +
              te.getStatusCode
            info(failureMsg)
            S.warning(failureMsg)
            (emptyRows, emptyImage)
        }
      case _ => (emptyRows, emptyImage)
    }
    "#row" #> rows &
    "#image" #> image
  }

  def generalScreenNameFreq = fillFreqs(GeneralUserInfo.createScreenNameFreq)

  def generalWordFreq = fillFreqs(GeneralUserInfo.createWordFreq)

  def generalHashtagFreq = fillFreqs(GeneralUserInfo.createHashtagFreq)

  def links = "#item" #> (SessionState.userAnalysis.is match {
      case Some(ua) =>
        val guiLinks = GeneralUserInfo.links(ua)
        val start = System.currentTimeMillis
        val spans = Parallelizer.run(30, guiLinks, expandLink, "Expand link").map(expanded =>
          GeneralUserInfo.Link(expanded)).sortBy(_.toString.toLowerCase).map(link =>
          {link.toString}

        )
        info("Processed " + guiLinks.size + " links in " +
          NumberFormat.getInstance.format(System.currentTimeMillis - start) + " ms")
        spans
      case _ => List[Elem]()
    })

  def tweets = {
    val rows: List[Elem] = partitionedTweets.is match {
      case Some(pt) => pt.tweets.toList.map(tw =>

          {xml.Unparsed(TimeUtil2.formatAge(tw.createdAt, false).replace(" ", " "))}
          {tw.retweet match {
            case Some(status) => hyperlinkScreenName(status.getUser.getScreenName)
            case None => Text("")
          }}
          {tw.inReplyToScreenName match {
            case Some(screenName) => hyperlinkScreenName(screenName)
            case None => Text("")
          }
          }
          {xml.Unparsed(LinkExtractor.createLinks(StringEscapeUtils.escapeHtml(
            LinkExtractor.getWithoutUser(tw.text))).replaceAll("\n", "
"))}

)
      case _ => List[Elem]()
    }
    "id=tweetRow" #> rows
  }

  def plot(xhtml: NodeSeq): NodeSeq =
    if (tweetsAvailable)
      Script(UserTimelinePlotRenderer.render(partitionedTweets.is.get, screenName.is.get))
    else
      Nil

  private def setScreenName(sn: String) {
    screenName(sn.trim match {
      case screenName if screenName.length > 0 => Some(screenName)
      case _ => None
    })
  }

  private def hyperlinkScreenName(screenName: String) =
    {screenName}

  private def createNameLinks(names: List[String]) =
    names.flatMap(name =>
      {name} ++ Text(", ")
    ).dropRight(1)

  private def makeGnlRows(gnlLines: scala.List[InfoLine]) =
    gnlLines.map(il =>

        {il.heading}

          {il.value match {
          case ScreenNames(sn) => createNameLinks(sn)
          case s => s
        }}

)

  private def fillFreqs(freqProvider: (UserAnalysis) => List[InfoLine]) = {
    "id=row" #> (SessionState.userAnalysis.is match {
      case Some(ua) => makeGnlRows(freqProvider(ua))
      case _ => List[Elem]()
    })
  }

  private def expandLink(l: GeneralUserInfo.Link) = {
    val url = l.url.toString
    val result = try {
      UrlExpander.expand(url)
    } catch {
      case ex =>
        info(ex.toString)
        if (! ex.isInstanceOf[UnknownHostException])
          info(ex.getStackTraceString)
        url
    }
    result
  }

  private def tweetsAvailable = // partitionedTweets.is is not defined if error fetching user
    screenName.is.isDefined && partitionedTweets.is.isDefined && ! partitionedTweets.is.get.tweets.isEmpty
}


text:
'use strict';

var angular = require('angular');

var module = angular.module('sba-applications-environment', ['sba-applications']);
global.sbaModules.push(module.name);

module.controller('environmentCtrl', require('./controllers/environmentCtrl.js'));

module.component('sbaEnvironmentManager', require('./components/environmentManager.js'));

module.config(function ($stateProvider) {
  $stateProvider.state('applications.environment', {
    url: '/environment',
    templateUrl: 'applications-environment/views/environment.html',
    controller: 'environmentCtrl'
  });
});

module.run(function (ApplicationViews, $sce) {
  ApplicationViews.register({
    order: 10,
    title: $sce.trustAsHtml('<i class="fa fa-server fa-fw"></i>Environment'),
    state: 'applications.environment',
    show: function (application) {
      return application.managementUrl && application.statusInfo.status !== null && application.statusInfo.status !== 'OFFLINE';
    }
  });
});