text: packageSearchIndex = [{"l":"dollar"},{"l":"dollar.internal.runtime.script"},{"l":"dollar.json"}]

redpajama_set_name: RedPajamaGithub


text:
package io.digitallibrary.bookapi.model.domain

import io.digitallibrary.bookapi.BookApiProperties
import scalikejdbc._

case class Person(id: Option[Long],
                  revision: Option[Int],
                  name: String,
                  gdlId: Option[String])

object Person extends SQLSyntaxSupport[Person] {
  implicit val formats = org.json4s.DefaultFormats
  override val tableName = "person"
  override val schemaName = Some(BookApiProperties.MetaSchema)
  override val columns = Seq("id", "revision", "name", "gdl_id")

  def apply(p: SyntaxProvider[Person])(rs: WrappedResultSet): Person = apply(p.resultName)(rs)

  def apply(p: ResultName[Person])(rs: WrappedResultSet) = new Person(
    rs.longOpt(p.id),
    rs.intOpt(p.revision),
    rs.string(p.name),
    rs.stringOpt(p.gdlId)
  )

  def opt(p: SyntaxProvider[Person])(rs: WrappedResultSet): Option[Person] =
    rs.longOpt(p.resultName.id).map(_ => Person(p)(rs))

}


text:
package Perl::Critic::Utils::Perl;

use 5.006001;
use strict;
use warnings;

use base 'Exporter';

our $VERSION = '1.118';

#-----------------------------------------------------------------------------

our @EXPORT_OK = qw(
    symbol_without_sigil
);

our %EXPORT_TAGS = (
    all => \@EXPORT_OK,
);

#-----------------------------------------------------------------------------

sub symbol_without_sigil {
    my ($symbol) = @_;

    (my $without_sigil = $symbol) =~ s< \A [\$@%*&] ><>xms;

    return $without_sigil;
}

#-----------------------------------------------------------------------------

1;

__END__

=pod

=for stopwords

=head1 NAME

Perl::Critic::Utils::Perl - Utility functions for dealing with Perl language issues.

=head1 SYNOPSIS

    use Perl::Critic::Utils::Perl qw< :all >;

    my $name = symbol_without_sigil('$foo');    # $name is "foo".

=head1 DESCRIPTION

This handles various issues with Perl, the language, that aren't necessarily
L<PPI|PPI> related.

=head1 INTERFACE SUPPORT

This is considered to be a public module.  Any changes to its
interface will go through a deprecation cycle.

=head1 IMPORTABLE SUBROUTINES

=over

=item C<symbol_without_sigil( $symbol )>

Returns the name of the specified symbol with any sigil at the front.
The parameter can be a vanilla Perl string or a L<PPI::Element|PPI::Element>.

=back

=head1 AUTHOR

Elliot Shank <perl@galumph.com>

=head1 COPYRIGHT

Copyright (c) 2007-2011 Elliot Shank.

This program is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.  The full text of this license
can be found in the LICENSE file included with this module.

=cut

# Local Variables:
#   mode: cperl
#   cperl-indent-level: 4
#   fill-column: 78
#   indent-tabs-mode: nil
#   c-indentation-style: bsd
# End:
# ex: set ts=8 sts=4 sw=4 tw=78 ft=perl expandtab shiftround :


text:
html,
body {
  min-height: 100%;
  margin: 0px;
  padding: 0px;
}
body {
  background-image: url("../img/fabric_of_squares_gray.png");
  /*    background-color: rgb(233, 229, 212);
    background-image: repeating-linear-gradient(
    	40deg,
    	transparent,
    	transparent 7px,
    	rgba(255,255,255,.2) 7px,
    	rgba(255,255,255,.2) 10px);*/
}
.contents {
  padding-top: 10px;
}
#chart_div {
  margin: 0 auto;
}
.listDiv[displaytype="grid"] > .listItemGroup > .listItem > .content .thumbnail {
  display: block;
  overflow-y: hidden;
  overflow-x: hidden;
  position: relative;
  -webkit-transition: background-color 300ms linear;
  -moz-transition: background-color 300ms linear;
  -o-transition: background-color 300ms linear;
  transition: background-color 300ms linear;
}
.listDiv[displaytype="grid"] > .listItemGroup > .listItem > .content .thumbnail > .thumbImg {
  display: block;
  margin-left: auto;
  margin-right: auto;
  background-color: white;
  width: calc(90%);
}
.listDiv[displaytype="grid"] > .listItemGroup > .listItem > .content .subTitle {
  display: block;
  font-family: Georgia, "Times New Roman", Times, serif;
  font-style: italic;
  font-weight: 400;
  color: gray;
  font-size: 0.8em;
  text-align: left;
}
.listDiv[displaytype="grid"] > .listItemGroup > .listItem > .content .title {
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-top: 2px;
  text-align: left;
  font-size: 0.9em;
  font-family: 'Helvetica Neue Custom', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-weight: 700;
}
.listDiv[displaytype="grid"] > .listItemGroup > .listItem:hover .thumbImg {
  box-shadow: 0px 0px 4px black;
}
.listDiv[displaytype="grid"] > .listItemGroup > .listItem[highlight=true] > .content .thumbnail {
  background-color: orangered;
}
.pageTitle {
  margin-top: 10px;
  font-family: 'Montserrat', sans-serif;
  font-size: 1.8em;
  text-shadow: 2px 2px 0px lightgray;
  text-transform: capitalize;
}
.pageSubtitle {
  text-align: center;
  font-family: 'Montserrat', sans-serif;
  margin-top: 10px;
  margin-bottom: 5px;
  font-size: 0.9em;
  font-weight: 300;
  line-height: 1.5em;
}
.meny {
  display: none;
  padding: 20px;
  overflow: auto;
  background: #333;
  color: white;
  background-color: #222;
  background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAYAAACp8Z5+AAAAGklEQVQIW2NkYGD4D8SMQAwGcAY2AbBKDBUAVuYCBQPd34sAAAAASUVORK5CYII=);
  background-repeat: repeat;
  font-family: 'Lato', Helvetica, sans-serif;
  font-size: 16px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
.meny div.credit {
  right: 10px;
  text-align: right;
  position: absolute;
  bottom: 10px;
  font-weight: 300;
  font-size: 0.8em;
}
.meny div.credit a {
  color: #aa8585;
}
.meny .developed {
  font-weight: 300;
  font-size: 0.9em;
  position: absolute;
  bottom: 80px;
}
.meny .developed .projectName {
  font-weight: 500;
  font-size: 1.3em;
  color: red;
}
.meny .developed .me {
  font-size: 1em;
  font-weight: 700;
  margin-top: 10px;
  display: inline-block;
}
.meny .developed .source_code {
  display: block;
  font-size: 0.8em;
}
.meny .developed .source_code .descr {
  width: 140px;
  line-height: 1.8em;
  padding: 5px;
  display: inline-block;
}
.meny .developed .source_code iframe {
  float: right;
  margin-top: 5px;
  clear: right;
}
.meny .developed a {
  color: #C7C3B5;
}
.meny .developed .hcil_img {
  margin-top: 10px;
  width: 90px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}
/**
 * Hint graphic that appears while menu is inactive
 */
.meny-arrow {
  position: absolute;
  z-index: 10;
  border: 20px solid transparent;
  -webkit-transition: opacity 0.4s ease 0.4s;
  -moz-transition: opacity 0.4s ease 0.4s;
  -ms-transition: opacity 0.4s ease 0.4s;
  -o-transition: opacity 0.4s ease 0.4s;
  transition: opacity 0.4s ease 0.4s;
}
.meny-left .meny-arrow {
  left: 14px;
  top: 50%;
  margin-top: -25px;
  border-left: 25px solid #333;
}
.meny-right .meny-arrow {
  right: 14px;
  top: 50%;
  margin-top: -25px;
  border-right: 25px solid #333;
}
.meny-top .meny-arrow {
  left: 50%;
  top: 14px;
  margin-left: -25px;
  border-top: 25px solid #333;
}
.meny-bottom .meny-arrow {
  left: 50%;
  bottom: 14px;
  margin-left: -25px;
  border-bottom: 25px solid #333;
}
.meny-active .meny-arrow {
  opacity: 0;
  -webkit-transition: opacity 0.2s ease;
  -moz-transition: opacity 0.2s ease;
  -ms-transition: opacity 0.2s ease;
  -o-transition: opacity 0.2s ease;
  transition: opacity 0.2s ease;
}
#infobox {
  width: 100%;
  left: 0%;
  position: fixed;
  text-align: center;
  font-weight: 300;
  font-family: sans-serif;
  font-size: 0.8em;
  bottom: 0px;
  padding: 3px;
  background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgeG1sbnM9Imh0d…g9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNsZXNzaGF0LWdlbmVyYXRlZCkiIC8+PC9zdmc+);
  background-image: -webkit-linear-gradient(bottom, #dfd2a9 0%, rgba(255, 255, 255, 0) 80%);
  background-image: -moz-linear-gradient(bottom, #dfd2a9 0%, rgba(255, 255, 255, 0) 80%);
  background-image: -o-linear-gradient(bottom, #dfd2a9 0%, rgba(255, 255, 255, 0) 80%);
  background-image: linear-gradient(to top, #dfd2a9 0%, rgba(255, 255, 255, 0) 80%);
}
#infobox a {
  color: black !important;
  font-weight: 500;
}
#infobox .fa {
  color: gray;
}
.comment_popup {
  position: fixed;
  top: 5px;
  left: 5px;
  cursor: pointer;
}
.comment_popup .fa-stack {
  float: left;
  clear: left;
  height: 1.5em;
  margin-top: -15px;
  margin-left: -15px;
  font-size: 2em;
}
.comment_popup .fa-comment {
  color: #ffcd2e;
}
.comment_popup .texttt {
  font-family: sans-serif;
  font-weight: 300;
  font-size: 0.8em;
}
.comment_popup:hover .texttt {
  color: orangered;
}
.comment_popup:hover .fa-comment {
  color: orangered;
}
.forkongithub {
  position: fixed;
  display: block;
  z-index: 0;
}
.forkongithub a.fork-ribbon {
  background: #000;
  color: #fff;
  text-decoration: none;
  font-family: arial, sans-serif;
  text-align: center;
  font-weight: bold;
  padding: 5px 40px;
  font-size: 0.8rem;
  line-height: 1.5rem;
  position: relative;
  transition: 0.5s;
}
.forkongithub a.fork-ribbon::before,
.forkongithub a.fork-ribbon::after {
  width: 100%;
  display: block;
  position: absolute;
  top: 1px;
  left: 0;
  height: 1px;
  background: #fff;
  content: "";
}
.forkongithub a.fork-ribbon::after {
  bottom: 1px;
  top: auto;
}
.forkongithub a.fork-ribbon:hover {
  background: orangered;
  color: #fff;
}
@media screen and (min-width: 800px) {
  .forkongithub {
    width: 150px;
    height: 150px;
  }
  .forkongithub.fork-bottom {
    bottom: 0;
  }
  .forkongithub.fork-right {
    right: 0;
  }
  .forkongithub.fork-right a.fork-ribbon {
    font-size: 1.1em;
    -webkit-transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    transform: rotate(-45deg);
  }
  .forkongithub.fork-left {
    left: -70px;
    bottom: -10px;
  }
  .forkongithub.fork-left a.fork-ribbon {
    -webkit-transform: rotate(45deg);
    -moz-transform: rotate(45deg);
    -o-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
    right: auto;
    left: 0px;
  }
  .forkongithub a.fork-ribbon {
    width: 150px;
    position: absolute;
    top: 80px;
    right: -60px;
    box-shadow: 4px 4px 10px rgba(0, 0, 0, 0.8);
  }
}


text:
package com.tencent.utils;

import java.net.Socket;
import java.security.KeyStore;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.http.conn.ssl.SSLSocketFactory;

public class a extends SSLSocketFactory
{

    private SSLContext a;

    public Socket createSocket()
    {
        return a.getSocketFactory().createSocket();
    }

    public Socket createSocket(Socket socket, String s, int i, boolean flag)
    {
        return a.getSocketFactory().createSocket(socket, s, i, flag);
    }

    public (KeyStore keystore)
    {
        super(keystore);
        a = SSLContext.getInstance("TLS");
         ;
        try
        {
             = new t>();
        }
        catch (Exception exception)
        {
             = null;
        }
        a.init(null, new TrustManager[] {

        }, null);
    }
}


text:
<?php

/**
 * Bootstrap carousel widget.
 */
class BootCarousel extends CWidget
{
	/**
	 * @var string the previous button content.
	 */
	public $prev = '‹';
	/**
	 * @var string the next button content.
	 */
	public $next = '›';
	/**
	 * @var array the carousel items configuration.
	 */
	public $items = array();
	/**
	 * @var array the options for the Bootstrap JavaScript plugin.
	 */
	public $options = array();
	/**
	 * @var string[] the JavaScript event handlers.
	 */
	public $events = array();
	/**
	 * @var array the HTML attributes for the widget container.
	 */
	public $htmlOptions = array();

	/**
	 * Initializes the widget.
	 */
	public function init()
	{
		if (!isset($this->htmlOptions['id']))
			$this->htmlOptions['id'] = $this->getId();

		$classes = 'carousel';
		if (isset($this->htmlOptions['class']))
			$this->htmlOptions['class'] .= ' '.$classes;
		else
			$this->htmlOptions['class'] = $classes;

	}

	/**
	 * Runs the widget.
	 */
	public function run()
	{
		$id = $this->id;

		echo CHtml::openTag('div', $this->htmlOptions);
		echo '
';
		$this->renderItems($this->items);
		echo '
';
		echo ''.$this->prev.'';
		echo ''.$this->next.'';
		echo '
';

		/** @var CClientScript $cs */
		$cs = Yii::app()->getClientScript();
		$options = !empty($this->options) ? CJavaScript::encode($this->options) : '';
		$cs->registerScript(__CLASS__.'#'.$id, "jQuery('#{$id}').carousel({$options});");

		foreach ($this->events as $name => $handler)
		{
			$handler = CJavaScript::encode($handler);
			$cs->registerScript(__CLASS__.'#'.$id.'_'.$name, "jQuery('#{$id}').on('".$name."', {$handler});");
		}
	}

	/**
	 * Renders the carousel items.
	 * @param array $items the item configuration.
	 */
	protected function renderItems($items)
	{
		foreach ($items as $i => $item)
		{
			if (!is_array($item))
				continue;

			if (!isset($item['itemOptions']))
				$item['itemOptions'] = array();

			$classes = array('item');

			if ($i === 0)
				$classes[] = 'active';

			$classes = implode(' ', $classes);
			if (isset($item['itemOptions']['class']))
				$item['itemOptions']['class'] .= ' '.$classes;
			else
				$item['itemOptions']['class'] = $classes;

			echo CHtml::openTag('div', $item['itemOptions']);

			if (isset($item['image']))
			{
				if (!isset($item['alt']))
					$item['alt'] = '';

				if (!isset($item['imageOptions']))
					$item['imageOptions'] = array();

				echo CHtml::image($item['image'], $item['alt'], $item['imageOptions']);
			}

			if (isset($item['label']) || isset($item['caption']))
			{
				if (!isset($item['captionOptions']))
					$item['captionOptions'] = array();

				$classes = 'carousel-caption';
				if (isset($item['captionOptions']['class']))
					$item['captionOptions']['class'] .= ' '.$classes;
				else
					$item['captionOptions']['class'] = $classes;

				echo CHtml::openTag('div', $item['captionOptions']);

				if (isset($item['label']))
					echo '
'.$item['label'].'
';

				if (isset($item['caption']))
					echo '
'.$item['caption'].'
';

				echo '
';
			}

			echo '
';
		}
	}
}


text:
class node {
    public static TYPE_INITIAL = "INITIAL";
    public static TYPE_NORMAL = "NORMAL";
    public static TYPE_FINAL = "FINAL";
    public id : number;
    public type : string;
    public token : string;
    public backtrack : boolean;
    public edges : edge[];

    private _getLabel() {
        if(this.type == node.TYPE_FINAL) {
            return this.id + " [" + this.token + "] B:" + (this.backtrack ? "yes" : "no");
        }
        return this.id;
    }

    private _getGroup() {
        if(this.type == node.TYPE_INITIAL) {
            return "initial";
        } else if(this.type == node.TYPE_NORMAL) {
            return "normal";
        } else if(this.type == node.TYPE_FINAL) {
            return this.backtrack ? "final_backtrack" : "final";
        }
        return "";
    }

    public object() : any {
        return {
            id: this.id,
            label: this._getLabel(),
            group: this._getGroup(),
            shape: 'box'
        };
    }

    public json() : any {
        let json = {};
        json["type"] = this.type;
        json["id"] = this.id;
        if(this.type == node.TYPE_FINAL) {
            json["token"] = this.token;
            json["backtrack"] = this.backtrack;
        }
        return json;
    }
}


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("OperationResult.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OperationResult.Tests")]
[assembly: AssemblyCopyright("Copyright © Dmitry Panyushkin 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("fd2552cc-7b2e-40dc-a0ce-b7946972d6f5")]

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

cr.define('ntp', function() {
  'use strict';

  var Tile = ntp.Tile;
  var TilePage = ntp.TilePage;
  var APP_LAUNCH = ntp.APP_LAUNCH;

  // Histogram buckets for UMA tracking of where a DnD drop came from.
  var DRAG_SOURCE = {
    SAME_APPS_PANE: 0,
    OTHER_APPS_PANE: 1,
    MOST_VISITED_PANE: 2,
    BOOKMARKS_PANE: 3,
    OUTSIDE_NTP: 4
  };
  var DRAG_SOURCE_LIMIT = DRAG_SOURCE.OUTSIDE_NTP + 1;

  /**
   * App context menu. The class is designed to be used as a singleton with
   * the app that is currently showing a context menu stored in this.app_.
   * @constructor
   */
  function AppContextMenu() {
    this.__proto__ = AppContextMenu.prototype;
    this.initialize();
  }
  cr.addSingletonGetter(AppContextMenu);

  AppContextMenu.prototype = {
    initialize: function() {
      var menu = new cr.ui.Menu;
      cr.ui.decorate(menu, cr.ui.Menu);
      menu.classList.add('app-context-menu');
      this.menu = menu;

      this.launch_ = this.appendMenuItem_();
      this.launch_.addEventListener('activate', this.onLaunch_.bind(this));

      menu.appendChild(cr.ui.MenuItem.createSeparator());
      this.launchRegularTab_ = this.appendMenuItem_('applaunchtyperegular');
      this.launchPinnedTab_ = this.appendMenuItem_('applaunchtypepinned');
      if (!cr.isMac)
        this.launchNewWindow_ = this.appendMenuItem_('applaunchtypewindow');
      this.launchFullscreen_ = this.appendMenuItem_('applaunchtypefullscreen');

      var self = this;
      this.forAllLaunchTypes_(function(launchTypeButton, id) {
        launchTypeButton.addEventListener('activate',
            self.onLaunchTypeChanged_.bind(self));
      });

      menu.appendChild(cr.ui.MenuItem.createSeparator());
      this.options_ = this.appendMenuItem_('appoptions');
      this.details_ = this.appendMenuItem_('appdetails');
      this.disableNotifications_ =
          this.appendMenuItem_('appdisablenotifications');
      this.uninstall_ = this.appendMenuItem_('appuninstall');
      this.options_.addEventListener('activate',
                                     this.onShowOptions_.bind(this));
      this.details_.addEventListener('activate',
                                     this.onShowDetails_.bind(this));
      this.disableNotifications_.addEventListener(
          'activate', this.onDisableNotifications_.bind(this));
      this.uninstall_.addEventListener('activate',
                                       this.onUninstall_.bind(this));

      if (!cr.isMac && !cr.isChromeOS) {
        menu.appendChild(cr.ui.MenuItem.createSeparator());
        this.createShortcut_ = this.appendMenuItem_('appcreateshortcut');
        this.createShortcut_.addEventListener(
            'activate', this.onCreateShortcut_.bind(this));
      }

      document.body.appendChild(menu);
    },

    /**
     * Appends a menu item to |this.menu|.
     * @param {?String} textId If non-null, the ID for the localized string
     *     that acts as the item's label.
     */
    appendMenuItem_: function(textId) {
      var button = cr.doc.createElement('button');
      this.menu.appendChild(button);
      cr.ui.decorate(button, cr.ui.MenuItem);
      if (textId)
        button.textContent = loadTimeData.getString(textId);
      return button;
    },

    /**
     * Iterates over all the launch type menu items.
     * @param {function(cr.ui.MenuItem, number)} f The function to call for each
     *     menu item. The parameters to the function include the menu item and
     *     the associated launch ID.
     */
    forAllLaunchTypes_: function(f) {
      // Order matters: index matches launchType id.
      var launchTypes = [this.launchPinnedTab_,
                         this.launchRegularTab_,
                         this.launchFullscreen_,
                         this.launchNewWindow_];

      for (var i = 0; i < launchTypes.length; ++i) {
        if (!launchTypes[i])
          continue;

        f(launchTypes[i], i);
      }
    },

    /**
     * Does all the necessary setup to show the menu for the given app.
     * @param {App} app The App object that will be showing a context menu.
     */
    setupForApp: function(app) {
      this.app_ = app;

      this.launch_.textContent = app.data.title;

      this.forAllLaunchTypes_(function(launchTypeButton, id) {
        launchTypeButton.disabled = false;
        launchTypeButton.checked = app.data.launch_type == id;
      });

      this.options_.disabled = !app.data.optionsUrl || !app.data.enabled;
      this.details_.disabled = !app.data.detailsUrl;
      this.uninstall_.disabled = !app.data.mayDisable;

      this.disableNotifications_.hidden = true;
      var notificationsDisabled = app.data.notifications_disabled;
      if (typeof notificationsDisabled != 'undefined') {
        this.disableNotifications_.hidden = false;
        this.disableNotifications_.checked = notificationsDisabled;
      }
    },

    /**
     * Handlers for menu item activation.
     * @param {Event} e The activation event.
     * @private
     */
    onLaunch_: function(e) {
      chrome.send('launchApp', [this.app_.appId, APP_LAUNCH.NTP_APPS_MENU]);
    },
    onLaunchTypeChanged_: function(e) {
      var pressed = e.currentTarget;
      var app = this.app_;
      this.forAllLaunchTypes_(function(launchTypeButton, id) {
        if (launchTypeButton == pressed) {
          chrome.send('setLaunchType', [app.appId, id]);
          // Manually update the launch type. We will only get
          // appsPrefChangeCallback calls after changes to other NTP instances.
          app.data.launch_type = id;
        }
      });
    },
    onShowOptions_: function(e) {
      window.location = this.app_.data.optionsUrl;
    },
    onShowDetails_: function(e) {
      var url = this.app_.data.detailsUrl;
      url = appendParam(url, 'utm_source', 'chrome-ntp-launcher');
      window.location = url;
    },
    onDisableNotifications_: function(e) {
      var app = this.app_;
      app.removeBubble();
      // Toggle the current disable setting.
      var newSetting = !this.disableNotifications_.checked;
      app.data.notifications_disabled = newSetting;
      chrome.send('setNotificationsDisabled', [app.data.id, newSetting]);
    },
    onUninstall_: function(e) {
      chrome.send('uninstallApp', [this.app_.data.id]);
    },
    onCreateShortcut_: function(e) {
      chrome.send('createAppShortcut', [this.app_.data.id]);
    },
  };

  /**
   * Creates a new App object.
   * @param {Object=} opt_data The data representing the app.
   * @constructor
   * @extends {HTMLDivElement}
   */
  function App(opt_data) {
    var el = cr.doc.createElement('div');
    el.__proto__ = App.prototype;
    el.initialize_();

    if (opt_data)
      el.data = opt_data;

    return el;
  }

  App.prototype = Tile.subclass({
    __proto__: HTMLDivElement.prototype,

    /**
     * Initialize the app object.
     * @private
     */
    initialize_: function() {
      Tile.prototype.initialize.apply(this, arguments);

      this.classList.add('app');
      this.classList.add('focusable');
    },

    /**
     * Formats this app according to |data|.
     * @param {Object} data The data object that describes the app.
     * @private
     */
    formatApp_: function(data) {
      assert(this.data_.id, 'Got an app without an ID');
      this.id = this.data_.id;
      this.setAttribute('role', 'menuitem');

      if (!this.data_.icon_big_exists && this.data_.icon_small_exists)
        this.useSmallIcon_ = true;

      // TODO(pedrosimonetti): Fix crbug.com/165612
      if (!this.appContents_) {
        this.appContents_ = this.useSmallIcon_ ?
            $('app-small-icon-template').cloneNode(true) :
            $('app-large-icon-template').cloneNode(true);
        this.appContents_.id = '';
        this.appendChild(this.appContents_);
      }

      this.appImgContainer_ = this.querySelector('.app-img-container');
      this.appImg_ = this.appImgContainer_.querySelector('img');
      this.setIcon();

      var appTitle;
      if (this.useSmallIcon_) {
        this.classList.add('small-icon');
        this.imgDiv_ = this.querySelector('.app-icon-div');
        this.addLaunchClickTarget_(this.imgDiv_);
        this.imgDiv_.title = this.data_.title;
        appTitle = formatTitle(this.data_.title);
        chrome.send('getAppIconDominantColor', [this.id]);
      } else {
        this.classList.remove('small-icon');
        this.addLaunchClickTarget_(this.appImgContainer_);
        this.appImgContainer_.title = this.data_.title;
        appTitle = this.data_.title;
      }

      var appSpan = this.appContents_.querySelector('.title');
      appSpan.textContent = appTitle;
      appSpan.title = this.data_.title;
      this.addLaunchClickTarget_(appSpan);

      var notification = this.data_.notification;
      var hasNotification = typeof notification != 'undefined' &&
                            typeof notification['title'] != 'undefined' &&
                            typeof notification['body'] != 'undefined' &&
                            !this.data_.notifications_disabled;
      if (hasNotification)
        this.setupNotification_(notification);

      this.addEventListener('keydown', cr.ui.contextMenuHandler);
      this.addEventListener('keyup', cr.ui.contextMenuHandler);

      // This hack is here so that appContents.contextMenu will be the same as
      // this.contextMenu.
      var self = this;
      this.appContents_.__defineGetter__('contextMenu', function() {
        return self.contextMenu;
      });
      this.appContents_.addEventListener('contextmenu',
                                         cr.ui.contextMenuHandler);

      this.addEventListener('mousedown', this.onMousedown_, true);
      this.addEventListener('keydown', this.onKeydown_);
      this.addEventListener('keyup', this.onKeyup_);
    },

    /**
     * Sets the color of the favicon dominant color bar.
     * @param {string} color The css-parsable value for the color.
     */
    set stripeColor(color) {
      this.querySelector('.color-stripe').style.backgroundColor = color;
    },

    /**
     * Removes the app tile from the page. Should be called after the app has
     * been uninstalled.
     */
    remove: function(opt_animate) {
      // Unset the ID immediately, because the app is already gone. But leave
      // the tile on the page as it animates out.
      this.id = '';

      if (opt_animate) {
        var cell = this.tileCell;
        var tilePage = cell.tilePage;
        tilePage.dataList_.splice(cell.index, 1);
        tilePage.animateTileRemoval(cell.index, tilePage.dataList_);
      } else {
        this.tileCell.doRemove(opt_animate);
      }
    },

    /**
     * Set the URL of the icon from |this.data_|. This won't actually show the
     * icon until loadIcon() is called (for performance reasons; we don't want
     * to load icons until we have to).
     */
    setIcon: function() {
      var src = this.useSmallIcon_ ? this.data_.icon_small :
                                     this.data_.icon_big;
      if (!this.data_.enabled ||
          (!this.data_.offlineEnabled && !navigator.onLine)) {
        src += '?grayscale=true';
      }

      this.appImgSrc_ = src;
      this.classList.add('icon-loading');
    },

    /**
     * Shows the icon for the app. That is, it causes chrome to load the app
     * icon resource.
     */
    loadIcon: function() {
      if (this.appImgSrc_) {
        this.appImg_.src = this.appImgSrc_;
        this.appImg_.classList.remove('invisible');
        this.appImgSrc_ = null;
      }

      this.classList.remove('icon-loading');
    },

    /**
     * Creates a bubble node.
     * @param {Object} notification The notification to show in the bubble.
     * @param {boolean} full Whether we want the headline or just the content.
     * @private
     */
    createBubbleNode_: function(notification, full) {
      if (!full) {
        var titleItem = this.ownerDocument.createElement('span');
        titleItem.textContent = notification['title'];
        return titleItem;
      } else {
        var container = this.ownerDocument.createElement('div');

        var messageItem = this.ownerDocument.createElement('div');
        messageItem.textContent = notification['body'];
        container.appendChild(messageItem);

        if (notification['linkUrl'] && notification['linkText']) {
          var anchor = this.ownerDocument.createElement('a');
          anchor.href = notification['linkUrl'];
          anchor.textContent = notification['linkText'];
          container.appendChild(anchor);
        }

        return container;
      }
    },

    /**
     * Sets up a notification for the app icon.
     * @param {Object} notification The notification to show in the bubble.
     * @private
     */
    setupNotification_: function(notification) {
      if (notification) {
        var infoBubble;
        if (!this.currentBubbleShowing_) {
          // Create a new bubble.
          infoBubble = new cr.ui.ExpandableBubble;
          infoBubble.anchorNode = this;
          infoBubble.appId = this.data_.id;
          infoBubble.handleCloseEvent = function() {
            chrome.send('closeNotification', [this.appId]);
            infoBubble.hide();
          };
        } else {
          // Reuse the old bubble instead of popping up a new bubble over
          // the old one.
          infoBubble = this.currentBubbleShowing_;
          infoBubble.collapseBubble_();
        }
        infoBubble.contentTitle = this.createBubbleNode_(notification, false);
        infoBubble.content = this.createBubbleNode_(notification, true);
        infoBubble.show();
        infoBubble.resizeAndReposition();

        this.currentBubbleShowing_ = infoBubble;
      }
    },

    /**
     *  Removes the info bubble if there is one.
     */
    removeBubble: function() {
      if (this.currentBubbleShowing_) {
        this.currentBubbleShowing_.hide();
        this.currentBubbleShowing_ = null;
      }
    },

    /**
     * Invoked when an app is clicked.
     * @param {Event} e The click event.
     * @private
     */
    onClick_: function(e) {
      var url = !this.data_.is_webstore ? '' :
          appendParam(this.data_.url,
                      'utm_source',
                      'chrome-ntp-icon');

      chrome.send('launchApp',
                  [this.appId, APP_LAUNCH.NTP_APPS_MAXIMIZED, url,
                   e.button, e.altKey, e.ctrlKey, e.metaKey, e.shiftKey]);

      // Don't allow the click to trigger a link or anything
      e.preventDefault();
    },

    /**
     * Invoked when the user presses a key while the app is focused.
     * @param {Event} e The key event.
     * @private
     */
    onKeydown_: function(e) {
      if (e.keyIdentifier == 'Enter') {
        chrome.send('launchApp',
                    [this.appId, APP_LAUNCH.NTP_APPS_MAXIMIZED, '',
                     0, e.altKey, e.ctrlKey, e.metaKey, e.shiftKey]);
        e.preventDefault();
        e.stopPropagation();
      }
      this.onKeyboardUsed_(e.keyCode);
    },

    /**
     * Invoked when the user releases a key while the app is focused.
     * @param {Event} e The key event.
     * @private
     */
    onKeyup_: function(e) {
      this.onKeyboardUsed_(e.keyCode);
    },

    /**
     * Called when the keyboard has been used (key down or up). The .click-focus
     * hack is removed if the user presses a key that can change focus.
     * @param {number} keyCode The key code of the keyboard event.
     * @private
     */
    onKeyboardUsed_: function(keyCode) {
      switch (keyCode) {
        case 9:  // Tab.
        case 37:  // Left arrow.
        case 38:  // Up arrow.
        case 39:  // Right arrow.
        case 40:  // Down arrow.
          this.classList.remove('click-focus');
      }
    },

    /**
     * Adds a node to the list of targets that will launch the app. This list
     * is also used in onMousedown to determine whether the app contents should
     * be shown as active (if we don't do this, then clicking anywhere in
     * appContents, even a part that is outside the ideally clickable region,
     * will cause the app icon to look active).
     * @param {HTMLElement} node The node that should be clickable.
     */
    addLaunchClickTarget_: function(node) {
      node.classList.add('launch-click-target');
      node.addEventListener('click', this.onClick_.bind(this));
    },

    /**
     * Handler for mousedown on the App. Adds a class that allows us to
     * not display as :active for right clicks and clicks on app notifications
     * (specifically, don't pulse on these occasions). Also, we don't pulse
     * for clicks that aren't within the clickable regions.
     * @param {Event} e The mousedown event.
     */
    onMousedown_: function(e) {
      if (e.button == 2 ||
          !findAncestorByClass(e.target, 'launch-click-target')) {
        this.appContents_.classList.add('suppress-active');
      } else {
        this.appContents_.classList.remove('suppress-active');
      }

      // This class is here so we don't show the focus state for apps that
      // gain keyboard focus via mouse clicking.
      this.classList.add('click-focus');
    },

    /**
     * Change the data and update the appearance of the app.
     * @param {Object} data The new data object that describes the app.
     */
    replaceAppData: function(data) {
      assert(data);
      this.data = data;
      this.setIcon();
      this.loadIcon();
    },

    /**
     * The data and preferences for this app.
     * @type {Object}
     */
    set data(data) {
      Object.getOwnPropertyDescriptor(Tile.prototype, 'data').set.apply(this,
          arguments);

      this.formatApp_(data);
    },
    get data() {
      return this.data_;
    },

    get appId() {
      return this.data_.id;
    },

    /**
     * Returns a pointer to the context menu for this app. All apps share the
     * singleton AppContextMenu. This function is called by the
     * ContextMenuHandler in response to the 'contextmenu' event.
     * @type {cr.ui.Menu}
     */
    get contextMenu() {
      var menu = AppContextMenu.getInstance();
      menu.setupForApp(this);
      return menu.menu;
    },

    /**
     * Returns whether this element can be 'removed' from chrome (i.e. whether
     * the user can drag it onto the trash and expect something to happen).
     * @return {boolean} True if the app can be uninstalled.
     */
    canBeRemoved: function() {
      return this.data_.mayDisable;
    },

    /**
     * Uninstalls the app after it's been dropped on the trash.
     */
    removeFromChrome: function() {
      chrome.send('uninstallApp', [this.data_.id, true]);
      this.tile.tilePage.removeTile(this.tile, true);
      if (this.currentBubbleShowing_)
        this.currentBubbleShowing_.hide();
    },
  });

  /**
   * Creates a new AppsPage object.
   * @constructor
   * @extends {TilePage}
   */
  function AppsPage() {
    var el = new TilePage();
    el.__proto__ = AppsPage.prototype;
    el.initialize();

    return el;
  }

  AppsPage.prototype = {
    __proto__: TilePage.prototype,

    /**
     * Reference to the Tile subclass that will be used to create the tiles.
     * @constructor
     * @extends {Tile}
     */
    TileClass: App,

    // The config object should be defined by a TilePage subclass if it
    // wants the non-default behavior.
    config: {
      // The width of a cell.
      cellWidth: 70,
      // The start margin of a cell (left or right according to text direction).
      cellMarginStart: 20,
      // The maximum number of Tiles to be displayed.
      maxTileCount: 512,
      // Whether the TilePage content will be scrollable.
      scrollable: true,
    },

    initialize: function() {
      TilePage.prototype.initialize.apply(this, arguments);

      this.classList.add('apps-page');

      this.addEventListener('cardselected', this.onCardSelected_);
      // Add event listeners for two events, so we can temporarily suppress
      // the app notification bubbles when the app card slides in and out of
      // view.
      this.addEventListener('carddeselected', this.onCardDeselected_);
      this.addEventListener('cardSlider:card_change_ended',
                            this.onCardChangeEnded_);

      this.addEventListener('tilePage:tile_added', this.onTileAdded_);
    },

    /**
     * Highlight a newly installed app as it's added to the NTP.
     * @param {Object} data The data object that describes the app.
     */
    insertAndHighlightApp: function(data) {
      ntp.getCardSlider().selectCardByValue(this);
      this.insertApp(data, true);
    },

    /**
     * Inserts an App into the TilePage, preserving the alphabetical order.
     * @param {Object} data The data that describes the app.
     * @param {boolean} animate Whether to animate the insertion.
     */
    insertApp: function(data, animate) {
      var index = this.tiles_.length;
      for (var i = 0; i < this.tiles_.length; i++) {
        if (data.title.toLocaleLowerCase() <
            this.tiles_[i].data.title.toLocaleLowerCase()) {
          index = i;
          break;
        }
      }

      if (animate) {
        this.dataList_.splice(index, 0, data);
        this.animateTileRestoration(index, this.dataList_);
      } else {
        var app = new App(data);
        this.addTileAt(app, index);
      }
    },

    /**
     * Handler for 'cardselected' event, fired when |this| is selected. The
     * first time this is called, we load all the app icons.
     * @private
     */
    onCardSelected_: function(e) {
      var apps = this.querySelectorAll('.app.icon-loading');
      for (var i = 0; i < apps.length; i++) {
        apps[i].loadIcon();
        if (apps[i].currentBubbleShowing_)
          apps[i].currentBubbleShowing_.suppressed = false;
      }
    },

    /**
     * Handler for tile additions to this page.
     * @param {Event} e The tilePage:tile_added event.
     */
    onTileAdded_: function(e) {
      assert(e.currentTarget == this);
      assert(e.addedTile instanceof App);
      if (this.classList.contains('selected-card'))
        e.addedTile.loadIcon();
    },

    /**
     * Handler for the when this.cardSlider ends change its card. If animated,
     * this happens when the -webkit-transition is done, otherwise happens
     * immediately (but after cardSlider:card_changed).
     * @private
     */
    onCardChangeEnded_: function(e) {
      for (var i = 0; i < this.tiles_.length; i++) {
        var app = this.tiles_[i];
        assert(app instanceof App);
        if (app.currentBubbleShowing_)
          app.currentBubbleShowing_.suppressed = false;
      }
    },

    /**
     * Handler for the 'carddeselected' event, fired when the user switches
     * to another 'card' than the App 'card' on the NTP (|this| gets
     * deselected).
     * @private
     */
    onCardDeselected_: function(e) {
      for (var i = 0; i < this.tiles_.length; i++) {
        var app = this.tiles_[i];
        assert(app instanceof App);
        if (app.currentBubbleShowing_)
          app.currentBubbleShowing_.suppressed = true;
      }
    },

    /** @override */
    onScroll: function() {
      TilePage.prototype.onScroll.apply(this, arguments);

      for (var i = 0; i < this.tiles_.length; i++) {
        var app = this.tiles_[i];
        assert(app instanceof App);
        if (app.currentBubbleShowing_)
          app.currentBubbleShowing_.resizeAndReposition();
        }
    },

    /**
     * Creates a new crx-less app manifest and installs it.
     * @param {Object} data The data object describing the link. Must have |url|
     *     and |title| members.
     */
    generateAppForLink: function(data) {
      assert(data.url != undefined);
      assert(data.title != undefined);
      chrome.send('generateAppForLink', [data.url, data.title, 0]);
    },
  };

  /**
   * Launches the specified app using the APP_LAUNCH_NTP_APP_RE_ENABLE
   * histogram. This should only be invoked from the AppLauncherHandler.
   * @param {String} appID The ID of the app.
   */
  function launchAppAfterEnable(appId) {
    chrome.send('launchApp', [appId, APP_LAUNCH.NTP_APP_RE_ENABLE]);
  }

  function appNotificationChanged(id, notification) {
    var app = $(id);
    // The app might have been uninstalled, or notifications might be disabled.
    if (app && !app.data.notifications_disabled)
      app.setupNotification_(notification);
  }

  /**
   * Formats titles by removing the leading 'http://www.' part of the URL,
   * and the last slash, so 'http://www.test.com/' becomes 'test.com'.
   * @param {string} title Page's title.
   * @return {string} The formatted title.
   */
  function formatTitle(title) {
    return title.replace(/^(https?\:\/\/)?(www\.)?|\/$/gi, '');
  }

  return {
    appNotificationChanged: appNotificationChanged,
    AppsPage: AppsPage,
    launchAppAfterEnable: launchAppAfterEnable,
  };
});


text:
package com.edian.www.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

import com.edian.www.R;
import com.edian.www.auth.AuthApp;
import com.edian.www.base.BaseApp;
import com.edian.www.base.BaseHandler;
import com.edian.www.base.BaseMessage;
import com.edian.www.base.BaseTask;
import com.edian.www.base.C;
import com.edian.www.list.ShareList;
import com.edian.www.list.UserList;
import com.edian.www.model.Share;
import com.edian.www.model.User;
import com.edian.www.sqlite.ShareSqlite;
import com.edian.www.util.AppCache;
import com.edian.www.util.ExitApplication;
import com.edian.www.util.StringUtils;
import com.edian.www.util.shareSortByCreateTime;
import com.edian.www.widget.PullToRefreshListView;

public class ShareIndex extends AuthApp implements OnScrollListener {
	private final String TAG = "ShareIndex";
	private PullToRefreshListView sharelistview;
	private List<Share> sharelist = new ArrayList<Share>();
	private ShareList sharelistadapter;
	private ShareSqlite sharesqlite;
	private boolean isfirstload = true;
	private int pageindex = 1;
	private int visibleItemCount = 0;
	private int visibleLastIndex = 0;

    private View lvShare_footer;
    private TextView lvShare_foot_more;
    private ProgressBar lvShare_foot_progress;
	@Override
	public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        this.setContentView(R.layout.share_index);
        //top button
		ImageButton ib = (ImageButton) this.findViewById(R.id.top_share);
		ib.setImageResource(R.drawable.share_2);
		this.setHandler(new ShareHandler(this));
		sharesqlite = new ShareSqlite(this);
		sharelistview = (PullToRefreshListView)findViewById(R.id.share_listview);
		lvShare_footer = this.getLayoutInflater().inflate(R.layout.listview_footer, null);
		lvShare_foot_more = (TextView)lvShare_footer.findViewById(R.id.listview_foot_more);
		lvShare_foot_progress = (ProgressBar)lvShare_footer.findViewById(R.id.listview_foot_progress);
		sharelistview.addFooterView(lvShare_footer);
		sharelistadapter = new ShareList(this,(ArrayList)sharelist);
		sharelistview.setAdapter(sharelistadapter);
		sharelistview.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos, long id){
				Bundle bd = new Bundle();
				Log.v(TAG, "pos:"+pos);
				bd.putString("shareid",sharelist.get(pos-1).getId());
				overlay(ShareContent.class,bd);
			}
		});
		sharelistview.setOnScrollListener(this);
		sharelistview.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {

			@Override
			public void onRefresh() {
				isfirstload = true;
				pageindex = 1;
				loadShare("1");
			}
		});
		loadShare("1");
	}

	@Override
	public void onTaskComplete(int taskId,BaseMessage message){
    	super.onTaskComplete(taskId, message);
    	Log.v(TAG,"getshare task completed");
    	switch(taskId){
    	case C.task.sharelist:
    		try{
    			lvShare_foot_progress.setVisibility(View.GONE);
    			lvShare_footer.setVisibility(View.GONE);
    			@SuppressWarnings("unchecked")
    			String retcode = message.getCode();
    			if(retcode.equals(C.errcode.NOT_LOGIN)){
    				forward(AppLogin.class);
    			}
    			if(retcode.equals(C.errcode.EMPTY)){
					Log.v(TAG, "sharelist is empty!");
					lvShare_foot_more.setText(R.string.load_empty);
					lvShare_foot_more.setVisibility(View.GONE);
					sharelistview.setTag(C.list.LISTVIEW_DATA_FULL);
    			}else{
    				this.pageindex++;
	    			final ArrayList<Share> nsharelist = (ArrayList<Share>)message.getResultList("Share");
	    			for(Share share:nsharelist){
	    				Log.i("share",share.getId()+"|"+share.getAuthor()+"|"+share.getFace()+"|"+share.getContent()+"|"+share.getCreatetime()+"|"+share.getClick());
	    				//loadImage(share.getFace());
	    				sharesqlite.updateShare(share);
	    			}
	    			if(isfirstload){
	    				sharelistview.onRefreshComplete();
	    				sharelist.clear();
	    				Collections.sort(sharelist,new shareSortByCreateTime());
	    				sharelist.addAll(nsharelist);
	    				sharelistview.setTag(C.list.LISTVIEW_DATA_MORE);
	    				isfirstload = false;
	    			}else{
	    				lvShare_foot_more.setVisibility(View.GONE);
	    				sharelistview.setTag(C.list.LISTVIEW_DATA_MORE);
	    				Collections.sort(nsharelist,new shareSortByCreateTime());
	    				sharelist.addAll(nsharelist);
	    				sharelistadapter.notifyDataSetChanged();
	    			}
    			}
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    }

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {
		this.visibleItemCount = visibleItemCount;
		this.visibleLastIndex = firstVisibleItem+totalItemCount-1;
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		Log.v(TAG, "scroll!");
		sharelistview.onScrollStateChanged(view, scrollState);
		//数据为空--不用继续下面代码了
		if(sharelistadapter.getCount()<=0) return;

		//判断是否滚动到底部
		boolean scrollEnd = false;
		int lastelem = view.getLastVisiblePosition();
		Log.v(TAG, "lastelem:"+lastelem);
		try {
			if(view.getPositionForView(lvShare_footer) == lastelem)
				scrollEnd = true;
		} catch (Exception e) {
			scrollEnd = false;
		}
		int lvDataState = StringUtils.toInt(sharelistview.getTag());
		Log.v(TAG, "scrollEnd:"+scrollEnd+",lvDataState:"+lvDataState);
		if(scrollEnd && lvDataState==C.list.LISTVIEW_DATA_MORE)
		{
			int pos = sharelistadapter.getCount()-1;
			if(pos>=C.list.LIST_MAX-1)return;
			Share share = sharelistadapter.getItem(pos);
			sharelistview.setTag(C.list.LISTVIEW_DATA_LOADING);
			lvShare_foot_more.setText(R.string.load_ing);
			lvShare_foot_progress.setVisibility(View.VISIBLE);
			loadShare(Integer.toString(this.pageindex));
		}
	}

    @Override
    public void onNetworkError(int taskId){
    	super.onNetworkError(taskId);
    	toast("网络错误,请重试");
    }

	public void loadShare(String page){
		this.loadShare("0", "20", page);
	}

	public void loadShare(String uid,String num,String page){
		Log.i(TAG, "load shares");
        HashMap<String,String> para = new HashMap<String,String>(2);
        para.put("uid", uid);
        para.put("num", num);
        para.put("page", page);
        Log.i(TAG, "[EdianIndex]taskArg1:"+para.get("cat")+"|taskArg2:"+para.get("timeline"));
        doTaskAsync(C.task.sharelist, C.api.sharelist, para);
	}

	public void pubShare(View v){
		Bundle type = new Bundle();
		type.putString("pubtype", C.intent.action.PUBSHARE);
		this.overlay(Publish.class, type);
	}

	public ListView getListView(){
		return sharelistview;
	}
	private class ShareHandler extends BaseHandler {
		public ShareHandler(BaseApp app) {
			super(app);
		}
		@Override
		public void handleMessage(Message msg) {
			Log.v(TAG, "handleMessage");
			super.handleMessage(msg);
			try {
				switch (msg.what) {
					case BaseTask.LOAD_IMAGE:
						Bundle bd = msg.getData();
						String url = bd.getString("url");
						ImageView iv = (ImageView)sharelistview.findViewWithTag(url);
						Bitmap face = AppCache.getImage(url);
						iv.setImageBitmap(face);
						break;
				}
			} catch (Exception e) {
				e.printStackTrace();
				app.toast(e.getMessage());
			}
		}
	}
}


text:
'use strict';

var Tsearch2 = function (keywords) {
  var pattern = /!{0,1}\w+(:[a|b|c|d]){0,1}/g;
  this.keywords = keywords.toLowerCase().replace(/\-+/, '!').match(pattern);
};

var p = Tsearch2.prototype;

p.headline = function (fields, options) {
  options = options || {};
  return fields.map(function (field) {
    return "ts_headline(options.config || 'english', " + field + ", query) AS " + field;
  }).join(', ');
};

p.andSearch = function () {
  return this.keywords.join(' & ');
};

p.orSearch = function () {
  return this.keywords.join(' | ');
};

module.exports = Tsearch2;


text:
require 'spec_helper'

describe Conduit::Driver::Fusion::CheckMdnPortability::Parser do
  include ServerResponse

  subject { described_class.new(server_response) }

  context 'successful check mdn portability' do
    let(:response_file)   { %w(check_mdn_portability success.xml) }
    it_should_behave_like 'parser success response'

    let(:expected) do
      {
        eligible_for_porting: 'Y',
        message: 'PTN is eligible for porting in',
        old_service_provider: 'SPRINT',
        port_csa: nil,
        desired_due_date: nil
      }
    end

    it 'parses the response correctly' do
      expect(subject.serializable_hash).to eql(expected)
    end
  end

  context 'unsuccessful check mdn portability' do
    let(:response_file)   { %w(check_mdn_portability failure.xml) }
    it_should_behave_like 'parser failure response'
  end

  context 'server error' do
    let(:response_file)   { %w(failure.xml) }
    it_should_behave_like 'parser error response'
  end
end


text:
package com.management.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.management.bean.StudentProject;
import com.management.bean.calculate.StudentProjectCalc;
import com.management.bean.calculate.StudentProjectCalcs;
import com.management.service.calcs.StudentProjectCalcBusinessService;

public class StuProCalcsServlet extends HttpServlet {

	private StudentProjectCalcBusinessService bs = new StudentProjectCalcBusinessService();
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String mod = request.getParameter("mod");
		if(mod==null || !mod.equals("true")) {
			List<StudentProjectCalc> stuprocalcs = bs.find();
			request.setAttribute("stuprocalcs", stuprocalcs);
			request.getRequestDispatcher("calcs/stuprocalcs.jsp").forward(request, response);
		} else {
			StudentProjectCalc pc = new StudentProjectCalc();
			for(int i=1; i<=3; i++) {
				pc.setId(Integer.valueOf(request.getParameter("id"+i)));
				pc.setCategory(request.getParameter("category"+i));
				pc.setPoint(Double.valueOf(request.getParameter("point"+i)));
				bs.update(pc);
			}
			request.setAttribute("message", "更新成功");
			request.setAttribute("to", "calculate_standard.jsp");
			request.getRequestDispatcher("message.jsp").forward(request, response);
		}
	}

}


text:
from threading import Thread
import cv2

class WebcamVideoStream:
    def __init__(self, src=0):
        # initialize the video camera stream and read the first frame
        # from the stream
        self.stream = cv2.VideoCapture(src)
        (self.grabbed, self.frame) = self.stream.read()

        # initialize the variable used to indicate if the thread should
        # be stopped
        self.stopped = False

    def start(self):
        # start the thread to read frames from the video stream
        t = Thread(target=self.update, args=())
        t.daemon = True
        t.start()
        return self

    def update(self):
        # keep looping infinitely until the thread is stopped
        while True:
            # if the thread indicator variable is set, stop the thread
            if self.stopped:
                return

            # otherwise, read the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
        # return the frame most recently read
        return (self.grabbed, self.frame)

    def stop(self):
        # indicate that the thread should be stopped
        self.stopped = True

    def isOpened(self):
        return self.stream.isOpened()

    def release(self):
        self.stop()
        self.stream.release()


text:
require 'spec_helper'
module Alf
  module Relvar
    describe Virtual, "heading" do

      let(:expr){ Algebra::Operand::Named.new(:aname, self) }
      let(:rv)  { Virtual.new(expr)                         }

      def heading(name)
        "a heading for #{name}"
      end

      subject{ rv.heading }

      it 'delegates to the expression' do
        subject.should eq("a heading for aname")
      end

    end
  end
end


text:
  Chaveyriat est
       un village
       situé dans le département de l'Ain en Rhône-Alpes. Elle comptait 885 habitants en 2008.

Le parc d'habitations, à Chaveyriat, se décomposait en 2011 en 16 appartements et 386 maisons soit
 un marché relativement équilibré.

Si vous envisagez de emmenager à Chaveyriat, vous pourrez facilement trouver une maison à acheter.

À Chaveyriat, la valorisation moyenne à la vente d'un appartement s'évalue à zero € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 1 814 € du m². À la location la valorisation moyenne se situe à 6,69 € du m² mensuel.

La commune compte quelques  équipements, elle propose entre autres un terrain de sport.

À coté de Chaveyriat sont positionnées géographiquement les villes de
Condeissiat localisée à 4 km, 733 habitants,
Confrançon à 7 km, 1 048 habitants,
Polliat située à 7 km, 2 296 habitants,
Vandeins localisée à 2 km, 580 habitants,
Montracol localisée à 4 km, 860 habitants,
Vonnas localisée à 5 km, 2 623 habitants,
 entre autres. De plus, Chaveyriat est située à seulement douze km de Bourg-en-Bresse.


text:
angular.module('bookApp', [])
  .controller('SearchBookController', function($http, $filter, $scope) {
    var bookSearch = this;

    function SetFields(options, inputName) {
      if (typeof options === 'undefined') { return; }
      $("#" + inputName).closest("div").addClass("is-dirty");
      return options.constructor.toString().indexOf('Array') >= 0 ? options[0] : options;
    }

    bookSearch.search = function() {
      bookSearch.state = "loading...";
      $http.get("/api/isbn/" + bookSearch.isbn)
        .success(function(response){
          bookSearch.result = response;
          bookSearch.state = "";

          bookSearch.Title = SetFields(bookSearch.result.searchData.Title, "title");
          bookSearch.SubTitle = SetFields(bookSearch.result.searchData.SubTitle, "subtitle");
          bookSearch.Author = SetFields(bookSearch.result.searchData.Author, "author");
          bookSearch.ImageUrl = SetFields(bookSearch.result.searchData.ImageUrl, "imageUrl");
          bookSearch.Language = SetFields(bookSearch.result.searchData.Language, "language");
          bookSearch.Publisher = SetFields(bookSearch.result.searchData.Publisher, "publisher");
          bookSearch.Pages = SetFields(bookSearch.result.searchData.Pages, "pages");
          bookSearch.PublishDate = $filter('date')(SetFields(bookSearch.result.searchData.PublishDate, "publishDate"), "yyyy-MM-dd");
          bookSearch.Series = SetFields(bookSearch.result.searchData.Series, "series");
          bookSearch.Spec = SetFields(bookSearch.result.searchData.Spec, "spec");

          console.log(bookSearch.result);
        });
      //bookSearch.isbn = '';
    };

    bookSearch.save = function () {
      bookSearch.result.Title = bookSearch.Title;
      bookSearch.result.SubTitle = bookSearch.SubTitle;
      bookSearch.result.Author = bookSearch.Author;
      bookSearch.result.ImageUrl = bookSearch.ImageUrl;
      bookSearch.result.Language = bookSearch.Language;
      bookSearch.result.Publisher = bookSearch.Publisher;
      bookSearch.result.Pages = bookSearch.Pages;
      bookSearch.result.PublishDate = bookSearch.PublishDate;
      bookSearch.result.Series = bookSearch.Series;
      bookSearch.result.Spec = bookSearch.Spec;

      //todo: save it to db
      console.log(bookSearch.result);
      $http.post("/api/isbn/" + bookSearch.isbn, bookSearch.result).
        then(function(response) {
          //success
          alert("saved");
        }, function(response) {
          //error
          console.error(response);
        });
    };

    bookSearch.setOption = function (field, data) {
      if (field === "PublishDate") {
        bookSearch[field] = $filter('date')(data, "yyyy-MM-dd");
      }
      else {
        bookSearch[field] = data;
      }
    };
  });


text:
package ca.concordia.cssanalyser.migration.topreprocessors.mixin;

public interface MixinValue {

}


text:
<resources>
    <string name="app_name">base-adapter-helper-recyclerview-master</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_normal">NormalActivity</string>
</resources>


text:
  Nouvelle Recette
  Gérer mes Recette
  Gérer mes Tags

    {{recette.titre}}

    {{tag.nom}}

  <form name="form" ng-submit="addTag(contenuText)" >

        Saisir le nom du nouveau tag :
        <input class="form-control" type="text" ng-model="tag.nom"></input>

          Choisir la photo du nouveau tag :
          <input type = "file" ngf-select name="file" ng-model="picFile" accept="image/*" ngf-max-size="2MB"></input>
          <button type="button" ng-click="uploadPic(picFile)" class="btn btn-default">Upload</button>

    Enregistrer le tag
  </form>


text:
"""
Multiclass-classification by taking the max over a set of one-against-rest
logistic classifiers.
"""
__authors__ = "Ian Goodfellow"
__copyright__ = "Copyright 2010-2012, Universite de Montreal"
__credits__ = ["Ian Goodfellow"]
__license__ = "3-clause BSD"
__maintainer__ = "LISA Lab"
__email__ = "pylearn-dev@googlegroups"

import logging
try:
    from sklearn.linear_model import LogisticRegression
except ImportError:
    LogisticRegression = None
import numpy as np
from theano.compat.six.moves import xrange

logger = logging.getLogger(__name__)

class IndependentMulticlassLogistic:
    """
    Fits a separate logistic regression classifier for each class, makes
    predictions based on the max output: during training, views a one-hot label
    vector as a vector of independent binary labels, rather than correctly
    modeling them as one-hot like softmax would do.

    This is what Jia+Huang used to get state of the art on CIFAR-100

    Parameters
    ----------
    C : WRITEME
    """

    def __init__(self, C):
        self.C = C

    def fit(self, X, y):
        """
        Fits the model to the given training data.

        Parameters
        ----------
        X : ndarray
            2D array, each row is one example
        y : ndarray
            vector of integer class labels
        """

        if LogisticRegression is None:
            raise RuntimeError("sklearn not available.")

        min_y = y.min()
        max_y = y.max()

        assert min_y == 0

        num_classes = max_y + 1
        assert num_classes > 1

        logistics = []

        for c in xrange(num_classes):

            logger.info('fitting class {0}'.format(c))
            cur_y = (y == c).astype('int32')

            logistics.append(LogisticRegression(C = self.C).fit(X,cur_y))

        return Classifier(logistics)

class Classifier:
    """
    .. todo::

        WRITEME

    Parameters
    ----------
    logistics : WRITEME
    """
    def __init__(self, logistics):
        assert len(logistics) > 1

        num_classes = len(logistics)
        num_features = logistics[0].coef_.shape[1]

        self.W = np.zeros((num_features, num_classes))
        self.b = np.zeros((num_classes,))

        for i in xrange(num_classes):
            self.W[:,i] = logistics[i].coef_
            self.b[i] = logistics[i].intercept_

    def predict(self, X):
        """
        .. todo::

            WRITEME
        """

        return np.argmax(self.b + np.dot(X,self.W), 1)


text:
<?php
// mediaBase
/*        $serverhost="192.168.2.111";
        $db_user="mediaBase";
        $db_pass="mediaBase";
        $db_database="mediaBase";
*/
// DMS
//        $serverhost="192.168.2.111";
	$serverhost="localhost";
	$db_user="test";
	$db_pass="test";
	$db_database="piwigo";

	$verbindung = mysql_connect ($serverhost,$db_user,$db_pass) or die ("keine Verbindung möglich. Benutzername oder Passwort sind falsch");

	mysql_select_db($db_database) or die ("Die Datenbank existiert nicht.");
	mysql_query("SET CHARACTER SET utf8");
	mysql_query("SET NAMES utf8");
	header("Content-type:text/html; charset=utf8");
?>


text:
=====================================
Extended Formatter Functions
=====================================

.. important::

  This sample uses a Nablarch 1.4 compliant API.

  When combining with versions later than Nablarch 1.4 series, customize as necessary.

.. toctree::
  :maxdepth: 1

  0401_ExtendedDataFormatter
  0402_ExtendedFieldType

`Source code <https://github.com/nablarch/nablarch-biz-sample-all>`_


text:
@extends('stand-ci::layouts.master')

@section('content')

      @if ($isLock)
        <button id="build-btn" type="button" class="btn btn-primary btn-lg" disabled>Now Building</button>
      @else
        <button id="build-btn" type="button" class="btn btn-primary btn-lg">Build</button>
      @endif

Build History

Build

Status

Duration

Finished

          @foreach ($builds as $build)

              @if ($build->status === Ngmy\StandCi\Repo\Build\BuildInterface::SUCCESS)
                {!! link_to(config('ngmy-stand-ci')['route_prefix'].'/builds/'.$build->id, $build->id) !!}
                Success
                {!! $build->finished_at->diffTimeForHumans($build->started_at) !!}
                {!! $build->finished_at->diffForHumans() !!}
              @elseif ($build->status === Ngmy\StandCi\Repo\Build\BuildInterface::FAILURE)
                {!! link_to(config('ngmy-stand-ci')['route_prefix'].'/builds/'.$build->id, $build->id) !!}
                Failure
                {!! $build->finished_at->diffTimeForHumans($build->started_at) !!}
                {!! $build->finished_at->diffForHumans() !!}
              @else
                {!! $build->id !!}
                Building
                {!! Ngmy\StandCi\Library\StandCiCarbon::now()->diffTimeForHumans($build->started_at) !!}
                {!! $build->finished_at !!}
              @endif

          @endforeach

      {!! $builds->render() !!}

@stop

@section('scripts')

@stop


text:
package net.ssehub.easy.varModel.cstEvaluation;

import net.ssehub.easy.varModel.confModel.IAssignmentState;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.model.values.Value;

/**
 * Is called when the {@link EvaluationVisitor} changes a value in the configuration.
 *
 * @author Holger Eichelberger
 */
public interface IValueChangeListener {

    /**
     * Indicates the kind of the change.
     *
     * @author Holger Eichelberger
     */
    public enum ChangeKind {

        /**
         * The default mode, the change affects the variable, its nested elements, its parents and its context
         * (regarding constraints).
         */
        FULL,

        /**
         * The change focuses on the variable itself, so constraint context selection shall be focused on that.
         */
        VARIABLE_ONLY;

    }

    /**
     * Called if the value of a variable has been modified.
     *
     * @param variable the modified variable
     * @param oldValue the value of variable before the change (may be null)
     * @param oldState the old state of the variable before the change
     * @param kind the change kind
     */
    public void notifyChanged(IDecisionVariable variable, Value oldValue, IAssignmentState oldState, ChangeKind kind);

    /**
     * Called if an assignment to the given variable failed as the defining
     * expression cannot be evaluated, e.g., due to an undefined variable.
     *
     * @param variable the variable that the evaluator was about to modify
     */
    public void notifyUnresolved(IDecisionVariable variable);
}


text:
 Introduction

The current model uses 1.1 million tokens as training data and 15,000 testing tokens. We use the previous context of a word 10 timesteps in the past or we look at 10 words in the past for gathering context information. The vocabulary size used for generating vector representations of the input is 50,000.

The results of the training procedure on the data:

Total Accuracy: 83.78%

Average F1 Score: 45.52%

The classification task is:

1. Class 1 - First character is capital F1-score:83.23%

2. Class 2 - First character is capital and token is followed by period F1-score:0.0%

3. Class 3 - First character is capital and token is followed by comma F1-score:18.58%

4. Class 4 - Token is followed by period F1-score:40.43%

5. Class 5 - Token is followed by comma F1-score:39.85%

6. Class 6 - No Change 91.04%

Features:
1. Word Features : Using [[Word Embeddings]](http://arxiv.org/abs/1512.05287)

Libraries Used:
1. [[Keras]](https://github.com/fchollet/keras) - A Python wrapper on Theano Deep Learning library

Tools: numpy, keras, theano, scipy, sklearn

 Datasource - Europarl: A Parallel Corpus for Statistical Machine Translation (German Language Version)

1. [[Europarl Dataset]](http://www.statmt.org/europarl/)
2. Traininig Data - X_train.npy & Y_train.npy contains first 50,000 lines of Europarl Dataset German version
3. Testing Data - X_test.npy & Y_test.npy contains line numbers 50,000 to 60,000 from the same dataset

 Programs

1. lstm_short.py - the lstm model takes training and testing numpy files and trains the model on that data
2. lstm.py - Generates word vectors and creates starting and ending markers for tokens at an interval of 10 tokens
3. lstm_data.py - Extracts the output labels and the word tokens given as input to lstm.py from the file tags.txt


text:
namespace extensions {

namespace switches {

// Allows non-https URL for background_page for hosted apps.
const char kAllowHTTPBackgroundPage[] = "allow-http-background-page";

// Allows the browser to load extensions that lack a modern manifest when that
// would otherwise be forbidden.
const char kAllowLegacyExtensionManifests[] =
    "allow-legacy-extension-manifests";

// Enables extensions to be easily installed from sites other than the web
// store. Without this flag, they can still be installed, but must be manually
// dragged onto chrome://extensions/.
const char kEasyOffStoreExtensionInstall[] = "easy-off-store-extension-install";

// Enables extension APIs that are in development.
const char kEnableExperimentalExtensionApis[] =
    "enable-experimental-extension-apis";

// Enables extensions to hide bookmarks UI elements.
const char kEnableOverrideBookmarksUI[] = "enable-override-bookmarks-ui";

// Allows the ErrorConsole to collect runtime and manifest errors, and display
// them in the chrome:extensions page.
const char kErrorConsole[] = "error-console";

// The time in milliseconds that an extension event page can be idle before it
// is shut down.
const char kEventPageIdleTime[] = "event-page-idle-time";

// The time in milliseconds that an extension event page has between being
// notified of its impending unload and that unload happening.
const char kEventPageSuspendingTime[] = "event-page-unloading-time";

// Marks a renderer as extension process.
const char kExtensionProcess[] = "extension-process";

// Enables extensions running scripts on chrome:// URLs.
// Extensions still need to explicitly request access to chrome:// URLs in the
// manifest.
const char kExtensionsOnChromeURLs[] = "extensions-on-chrome-urls";

// Whether to force developer mode extensions highlighting.
const char kForceDevModeHighlighting[] = "force-dev-mode-highlighting";

// Enables setting global commands through the Extensions Commands API.
const char kGlobalCommands[] = "global-commands";

// Makes component extensions appear in chrome://settings/extensions.
const char kShowComponentExtensionOptions[] =
    "show-component-extension-options";

}  // namespace switches

}  // namespace extensions


text:
using Microsoft.AspNet.Identity.EntityFramework;
using OnlineSmartPhoneShop_DbContext.Migrations;
using OnlineSmartPhoneShop_Entities.Models;
using OnlineSmartphonesShop.Models;
using System.Data.Entity;

namespace OnlineSmartPhoneShop_DbContext
{
    public class ApplicationDbContext : IdentityDbContext<User>
    {
        public virtual IDbSet<Smartphone> Smartphones { get; set; }
        public virtual IDbSet<Order> Orders { get; set; }

        public ApplicationDbContext()
            //: base("OnlineShopConnection", throwIfV1Schema: false)
            : base("OnlineShopConnection-Production", throwIfV1Schema: false)

        {
           Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
           // this.Configuration.LazyLoadingEnabled = false;
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

    }
}


text:
<?php

use Twig\Node\IfNode;

class_exists('Twig\Node\IfNode');

@trigger_error(sprintf('Using the "Twig_Node_If" class is deprecated since Twig version 2.7, use "Twig\Node\IfNode" instead.'), E_USER_DEPRECATED);

if (\false) {
    /** @deprecated since Twig 2.7, use "Twig\Node\IfNode" instead */
    class Twig_Node_If extends IfNode
    {
    }
}


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"strconv"

	"github.com/geetarista/vindinium-starter-go/vindinium"
)

var (
	client vindinium.Client
	count  string
	games  int
)

func init() {
	flag.StringVar(&client.Server, "s", "http://vindinium.org", "server")
	flag.StringVar(&client.Key, "k", "", "api key")
	flag.StringVar(&client.Mode, "m", "arena", "mode (arena or training)")
	flag.StringVar(&client.BotName, "b", "fighter", "name of bot to use")
	flag.StringVar(&count, "c", "1", "number of games or turns to play")
	flag.BoolVar(&client.RandomMap, "r", true, "use random map (useful for training against same map)")
	flag.BoolVar(&client.Debug, "d", false, "debug output")
	flag.Usage = func() {
		fmt.Printf("Usage %s [FLAGS]\n", os.Args[0])
		flag.PrintDefaults()
	}
	flag.Parse()
}

func main() {
	if client.Key == "" {
		fmt.Println("API key required. Pass using the -k flag. Use -h to view help.")
		os.Exit(1)
	}

	if client.Mode == "training" {
		games = 1
		client.Turns = count
	} else {
		games, _ = strconv.Atoi(count)
		client.Turns = "300"
	}

	client.Setup()
	for i := 0; i < games; i++ {
		if err := client.Start(); err != nil {
			panic(err.Error())
		}
		if err := client.Play(); err != nil {
			panic(err.Error())
		}
	}
	fmt.Printf("Finished %d games.\n", games)
}


text:
/**
@file iOSStringIO.h
@author NDark
@date 20170507 . file started.

*/

// Converts C style string to NSString
NSString* CToNSString (const char* string) ;

// Helper method to create C string copy
char* StringCopy (const char* string) ;


text:
<?php

namespace yii\authclient\clients;

use yii\authclient\OAuth1;

/**
 * Twitter allows authentication via Twitter OAuth.
 *
 * In order to use Twitter OAuth you must register your application at <https://dev.twitter.com/apps/new>.
 *
 * Example application configuration:
 *
 * ~~~
 * 'components' => [
 *     'authClientCollection' => [
 *         'class' => 'yii\authclient\Collection',
 *         'clients' => [
 *             'twitter' => [
 *                 'class' => 'yii\authclient\clients\Twitter',
 *                 'consumerKey' => 'twitter_consumer_key',
 *                 'consumerSecret' => 'twitter_consumer_secret',
 *             ],
 *         ],
 *     ]
 *     ...
 * ]
 * ~~~
 *
 * @see https://dev.twitter.com/apps/new
 * @see https://dev.twitter.com/docs/api
 *
 * @author Paul Klimov <klimov.paul@gmail.com>
 * @since 2.0
 */
class Twitter extends OAuth1
{
	/**
	 * @inheritdoc
	 */
	public $authUrl = 'https://api.twitter.com/oauth/authorize';
	/**
	 * @inheritdoc
	 */
	public $requestTokenUrl = 'https://api.twitter.com/oauth/request_token';
	/**
	 * @inheritdoc
	 */
	public $requestTokenMethod = 'POST';
	/**
	 * @inheritdoc
	 */
	public $accessTokenUrl = 'https://api.twitter.com/oauth/access_token';
	/**
	 * @inheritdoc
	 */
	public $accessTokenMethod = 'POST';
	/**
	 * @inheritdoc
	 */
	public $apiBaseUrl = 'https://api.twitter.com/1.1';

	/**
	 * @inheritdoc
	 */
	protected function initUserAttributes()
	{
		return $this->api('account/verify_credentials.json', 'GET');
	}

	/**
	 * @inheritdoc
	 */
	protected function defaultName()
	{
		return 'twitter';
	}

	/**
	 * @inheritdoc
	 */
	protected function defaultTitle()
	{
		return 'Twitter';
	}
}


text:
package luddite

import (
	"net/http"
	"strconv"
)

type versionHandler struct {
	minVersion int
	maxVersion int
}

func (v *versionHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
	// Parse the client's requested API version
	version := v.maxVersion
	if s := req.Header.Get(HeaderSpirentApiVersion); s != "" {
		i, err := strconv.Atoi(s)
		if err != nil || i < 1 {
			e := NewError(nil, EcodeApiVersionInvalid)
			_ = WriteResponse(rw, http.StatusBadRequest, e)
			return
		}
		version = i
	}

	// Range check the requested API version and reject requests that fall
	// outside supported version numbers
	if version < v.minVersion {
		e := NewError(nil, EcodeApiVersionTooOld, v.minVersion)
		_ = WriteResponse(rw, http.StatusGone, e)
		return
	}
	if version > v.maxVersion {
		e := NewError(nil, EcodeApiVersionTooNew, v.maxVersion)
		_ = WriteResponse(rw, http.StatusNotImplemented, e)
		return
	}

	// Add the requested API version to response headers (useful for clients
	// when a default version was negotiated)
	rw.Header().Add(HeaderSpirentApiVersion, strconv.Itoa(version))

	// Add the requested API version to handler context so that downstream
	// handlers can dispatch correctly
	d := contextHandlerDetails(req.Context())
	d.apiVersion = version

	next(rw, req)
}


text:
namespace Volante
{
    using System;
    using System.Collections;
    using System.IO;

    public class TestBlobResult : TestResult
    {
        public TimeSpan InsertTime;
        public TimeSpan ReadTime;
    }

    public class TestBlob : ITest
    {
        static string IsSrcImpl(string d)
        {
            d = Path.Combine(d, "src");
            if (Directory.Exists(d))
                return Path.Combine(d, "impl");
            return null;
        }

        static string FindSrcImplDirectory()
        {
            string curr = "";
            for (int i=0; i<6; i++)
            {
                string d = IsSrcImpl(curr);
                if (null != d)
                    return d;
                curr = Path.Combine("..", curr);
            }
            return null;
        }

        void InsertFiles(TestConfig config, string[] files)
        {
            int rc;
            byte[] buf = new byte[1024];
            IDatabase db = config.GetDatabase();
            IIndex<string, IBlob> root = (IIndex<string, IBlob>)db.Root;
            Tests.Assert(root == null);
            root = db.CreateIndex<string, IBlob>(IndexType.Unique);
            db.Root = root;
            foreach (string file in files)
            {
                FileStream fin = new FileStream(file, FileMode.Open, FileAccess.Read);
                IBlob blob = db.CreateBlob();
                Stream bout = blob.GetStream();
                while ((rc = fin.Read(buf, 0, buf.Length)) > 0)
                {
                    bout.Write(buf, 0, rc);
                }
                root[file] = blob;
                fin.Close();
                bout.Close();
            }
            db.Close();
        }

        void VerifyFiles(TestConfig config, string[] files)
        {
            int rc;
            byte[] buf = new byte[1024];
            IDatabase db = config.GetDatabase(false);
            IIndex<string, IBlob> root = (IIndex<string, IBlob>)db.Root;
            Tests.Assert(root != null);
            foreach (string file in files)
            {
                byte[] buf2 = new byte[1024];
                IBlob blob = root[file];
                Tests.Assert(blob != null);
                Stream bin = blob.GetStream();
                FileStream fin = new FileStream(file, FileMode.Open, FileAccess.Read);
                while ((rc = fin.Read(buf, 0, buf.Length)) > 0)
                {
                    int rc2 = bin.Read(buf2, 0, buf2.Length);
                    Tests.Assert(rc == rc2);
                    if (rc != rc2)
                        break;
                    while (--rc >= 0 && buf[rc] == buf2[rc]) ;
                    Tests.Assert(rc < 0);
                    if (rc >= 0)
                        break;
                }
                fin.Close();
                bin.Close();
            }
            db.Commit();
            db.Close();
        }

        public void TestBlobImpl(TestConfig config)
        {
            int n;
            IDatabase db = config.GetDatabase(false);
            IBlob blob = db.CreateBlob();
            Stream blobStrm = blob.GetStream();

            byte[] b = new byte[] { 1, 2, 3, 4, 5, 6};
            byte[] b2 = new byte[6];
            blobStrm.Write(b, 0, b.Length);
            Tests.Assert(blobStrm.CanRead);
            Tests.Assert(blobStrm.CanSeek);
            Tests.Assert(blobStrm.CanWrite);
            long len = 6;
            long pos = 3;
            Tests.Assert(blobStrm.Length == len);
            blobStrm.Flush();
            Tests.Assert(6 == blobStrm.Position);
            blobStrm.Position = pos;
            Tests.Assert(pos == blobStrm.Position);
            Tests.AssertException<ArgumentException>(() =>
                { blobStrm.Position = -1; });
            blobStrm.Seek(0, SeekOrigin.Begin);
            Tests.Assert(0 == blobStrm.Position);
            n = blobStrm.Read(b2, 0, 6);
            Tests.Assert(n == 6);
            Tests.Assert(Tests.ByteArraysEqual(b, b2));
            Tests.Assert(6 == blobStrm.Position);
            n = blobStrm.Read(b2, 0, 1);
            Tests.Assert(n == 0);
            blobStrm.Seek(0, SeekOrigin.Begin);
            blobStrm.Seek(3, SeekOrigin.Current);
            Tests.Assert(3 == blobStrm.Position);
            blobStrm.Read(b2, 0, 3);
            Tests.Assert(6 == blobStrm.Position);
            Tests.Assert(b2[0] == 4);
            blobStrm.Seek(-3, SeekOrigin.End);
            Tests.Assert(3 == blobStrm.Position);
            Tests.AssertException<ArgumentException>(() =>
                { blobStrm.Seek(-10, SeekOrigin.Current); });
            blobStrm.Seek(0, SeekOrigin.End);
            Tests.Assert(len == blobStrm.Position);
            blobStrm.Write(b, 0, b.Length);
            len += b.Length;
            Tests.Assert(blobStrm.Length == len);
            blobStrm.SetLength(8);
            Tests.Assert(blobStrm.Length == 8);
            blobStrm.SetLength(20);
            Tests.Assert(blobStrm.Length == 20);
            blob.Deallocate();
        }

        public void Run(TestConfig config)
        {
            var res = new TestBlobResult();
            config.Result = res;
            string dir = FindSrcImplDirectory();
            if (null == dir)
            {
                res.Ok = false;
                return;
            }
            string[] files = Directory.GetFiles(dir, "*.cs");
            res.Count = files.Length;

            var start = DateTime.Now;
            InsertFiles(config, files);
            res.InsertTime = DateTime.Now - start;

            start = DateTime.Now;
            VerifyFiles(config, files);
            res.ReadTime = DateTime.Now - start;

            TestBlobImpl(config);
        }
    }

}


text:
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <!-- <script type="text/javascript" src="/mini/assets/js/bootstrap.min.js"></script> -->

  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<!--  <script type="text/javascript" src="/mini/assets/js/prettify.js"></script> -->

<script src="https://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js"></script>

  <script type="text/javascript">$(function() { prettyPrint(); });</script>


text:
import { Directive, ElementRef, HostBinding, Input, Renderer } from '@angular/core';

import { isTrueProperty } from '../../util/util';
import { Config } from '../../config/config';
import { Ion } from '../ion';

/**
 * @name Icon
 * @description
 * Icons can be used on their own, or inside of a number of Ionic components.
 * For a full list of available icons, check out the
 * [Ionicons docs](../../../../ionicons).
 *
 * One feature of Ionicons in Ionic is when icon names are set, the actual icon
 * which is rendered can change slightly depending on the mode the app is
 * running from. For example, by setting the icon name of `alarm`, on iOS the
 * icon will automatically apply `ios-alarm`, and on Material Design it will
 * automatically apply `md-alarm`. This allows the developer to write the
 * markup once while Ionic applies the appropriate icon based on the mode.
 *
 * @usage
 * ```html
 * <!-- automatically uses the correct "star" icon depending on the mode -->
 * <ion-icon name="star"></ion-icon>
 *
 * <!-- explicity set the icon for each mode -->
 * <ion-icon ios="ios-home" md="md-home"></ion-icon>
 *
 * <!-- always use the same icon, no matter what the mode -->
 * <ion-icon name="ios-clock"></ion-icon>
 * <ion-icon name="logo-twitter"></ion-icon>
 * ```
 *
 * @demo /docs/demos/src/icon/
 * @see {@link /docs/components#icons Icon Component Docs}
 *
 */
@Directive({
  selector: 'ion-icon',
  host: {
    'role': 'img'
  }
})
export class Icon extends Ion {
  /** @hidden */
  _iconMode: string;
  /** @hidden */
  _isActive: boolean = true;
  /** @hidden */
  _name: string = '';
  /** @hidden */
  _ios: string = '';
  /** @hidden */
  _md: string = '';
  /** @hidden */
  _css: string = '';

  constructor(
    config: Config,
    elementRef: ElementRef,
    renderer: Renderer
  ) {
    super(config, elementRef, renderer, 'icon');
    this._iconMode = config.get('iconMode');
  }

  /**
   * @hidden
   */
  ngOnDestroy() {
    if (this._css) {
      this.setElementClass(this._css, false);
    }
  }

  /**
   * @input {string} Specifies which icon to use. The appropriate icon will be used based on the mode.
   * For more information, see [Ionicons](/docs/ionicons/).
   */
  @Input()
  get name(): string {
    return this._name;
  }

  set name(val: string) {
    if (!(/^md-|^ios-|^logo-/.test(val))) {
      // this does not have one of the defaults
      // so lets auto add in the mode prefix for them
      this._name = this._iconMode + '-' + val;
    } else {
      this._name = val;
    }
    this.update();
  }

  /**
   * @input {string} Specifies which icon to use on `ios` mode.
   */
  @Input()
  get ios(): string {
    return this._ios;
  }

  set ios(val: string) {
    this._ios = val;
    this.update();
  }

  /**
   * @input {string} Specifies which icon to use on `md` mode.
   */
  @Input()
  get md(): string {
    return this._md;
  }

  set md(val: string) {
    this._md = val;
    this.update();
  }

  /**
   * @input {boolean} If true, the icon is styled with an "active" appearance.
   * An active icon is filled in, and an inactive icon is the outline of the icon.
   * The `isActive` property is largely used by the tabbar. Only affects `ios` icons.
   */
  @Input()
  get isActive(): boolean {
    return this._isActive;
  }

  set isActive(val: boolean) {
    this._isActive = isTrueProperty(val);
    this.update();
  }

  /**
   * @hidden
   */
  @HostBinding('class.hide') _hidden: boolean = false;

  /**
   * @hidden
   */
  update() {
    let iconName: string;

    if (this._ios && this._iconMode === 'ios') {
      iconName = this._ios;
    } else if (this._md && this._iconMode === 'md') {
      iconName = this._md;
    } else {
      iconName = this._name;
    }
    let hidden = this._hidden = (iconName === null);
    if (hidden) {
      return;
    }

    let iconMode = iconName.split('-', 2)[0];
    if (
      iconMode === 'ios' &&
      !this._isActive &&
      iconName.indexOf('logo-') < 0 &&
      iconName.indexOf('-outline') < 0) {
      iconName += '-outline';
    }

    let css = 'ion-' + iconName;
    if (this._css === css) {
      return;
    }
    if (this._css) {
      this.setElementClass(this._css, false);
    }
    this._css = css;
    this.setElementClass(css, true);

    let label = iconName
      .replace('ios-', '')
      .replace('md-', '')
      .replace('-', ' ');
    this.setElementAttribute('aria-label', label);
  }

}


text:
\documentclass{amsbook}
\usepackage[english]{babel}
\usepackage{graphicx}
\usepackage[pdfborder={0,0,0},colorlinks=true,linkcolor=blue,urlcolor=red]{hyperref}
\begin{document}
\title{ECO32 User Manual}
\author{Martin Geisse}
\maketitle

\newcommand{\mylabel}[1]{\label{#1}}
\newcommand{\myref}[2]{\hyperref[#2]{Chapter #1, Section \ref{#2}}}

\newcommand{\definition}[1]{{\it #1}}
\newcommand{\name}[1]{{\it #1}}

\newcommand{\eco}{{\sc ECO32} }
\newcommand{\ecox}{{\sc ECO32}}
\newcommand{\pc}{{\sc PC} }
\newcommand{\pcx}{{\sc PC}}
\newcommand{\psw}{{\sc PSW} }
\newcommand{\pswx}{{\sc PSW}}
\newcommand{\mmu}{{\sc MMU} }
\newcommand{\mmux}{{\sc MMU}}

\tableofcontents
\input{intro}
\input{architecture}
\input{isa/isa}
\input{signals}
\input{demosoc}
\input{ownsoc}
\input{toolchain}
\input{impl}
\input{mybib}

\end{document}


text:
package org.apache.bookkeeper.tls;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
import lombok.Getter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Holder class to validate file modification.
 */
public class FileModifiedTimeUpdater {
    @Getter
    String fileName;
    @Getter
    FileTime lastModifiedTime;

    public FileModifiedTimeUpdater(String fileName) {
        this.fileName = fileName;
        this.lastModifiedTime = updateLastModifiedTime();
    }

    private FileTime updateLastModifiedTime() {
        if (fileName != null) {
            Path p = Paths.get(fileName);
            try {
                return Files.getLastModifiedTime(p);
            } catch (IOException e) {
                LOG.error("Unable to fetch lastModified time for file {}: ", fileName, e);
            }
        }
        return null;
    }

    public boolean checkAndRefresh() {
        FileTime newLastModifiedTime = updateLastModifiedTime();
        if (newLastModifiedTime != null && !newLastModifiedTime.equals(lastModifiedTime)) {
            this.lastModifiedTime = newLastModifiedTime;
            return true;
        }
        return false;
    }

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


text:
<?php
    require_once('../config.php');
    session_start();
    set_time_limit (3600);

    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
      $bash_install_dir = getenv('BASH_INSTALL_DIR');
      $deploy_command = $bash_install_dir . ' script.sh';
      echo $deploy_command;
      shell_exec($deploy_command);
    } else if (null !== OPENSHIFT_MYSQL_DB_HOST) {
      define('JEKYLL_ROOT', $_SERVER['DOCUMENT_ROOT']."/admin/jekyll-cms/");
      define('ADMIN_ROOT', $_SERVER['DOCUMENT_ROOT']."/admin/");

      $deploy_command = 'export LD_LIBRARY_PATH=/opt/rh/mysql55/root/usr/lib64:/opt/rh/ror40/root/usr/lib64:/opt/rh/ruby200/root/usr/lib64 && export PATH=~/.gem/bin:/opt/rh/ruby200/root/usr/bin:$PATH && gem install bundle && cd '.JEKYLL_ROOT.' && bundle install && bundle exec jekyll build && cp _site/. ../.. -R && rm -rf _site';
      exec($deploy_command);
    } else {
      $deploy_command = './script.sh';
      exec($deploy_command);
    }
    $_SESSION['dirty']=false;
?>


text:
namespace spvtools {
namespace fuzz {
namespace {

TEST(TransformationAddTypeArrayTest, BasicTest) {
  std::string shader = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeFloat 32
          %7 = OpTypeInt 32 1
          %8 = OpTypeVector %6 2
          %9 = OpTypeVector %6 3
         %10 = OpTypeVector %6 4
         %11 = OpTypeVector %7 2
         %12 = OpConstant %7 3
         %13 = OpConstant %7 0
         %14 = OpConstant %7 -1
         %15 = OpTypeInt 32 0
         %16 = OpConstant %15 5
         %17 = OpConstant %15 0
         %18 = OpConstant %6 1
          %4 = OpFunction %2 None %3
          %5 = OpLabel
               OpReturn
               OpFunctionEnd
  )";

  const auto env = SPV_ENV_UNIVERSAL_1_4;
  const auto consumer = nullptr;
  const auto context = BuildModule(env, consumer, shader, kFuzzAssembleOption);
  spvtools::ValidatorOptions validator_options;
  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));
  TransformationContext transformation_context(
      MakeUnique<FactManager>(context.get()), validator_options);
  // Id already in use
  ASSERT_FALSE(TransformationAddTypeArray(4, 10, 16).IsApplicable(
      context.get(), transformation_context));
  // %1 is not a type
  ASSERT_FALSE(TransformationAddTypeArray(100, 1, 16)
                   .IsApplicable(context.get(), transformation_context));

  // %3 is a function type
  ASSERT_FALSE(TransformationAddTypeArray(100, 3, 16)
                   .IsApplicable(context.get(), transformation_context));

  // %2 is not a constant
  ASSERT_FALSE(TransformationAddTypeArray(100, 11, 2)
                   .IsApplicable(context.get(), transformation_context));

  // %18 is not an integer
  ASSERT_FALSE(TransformationAddTypeArray(100, 11, 18)
                   .IsApplicable(context.get(), transformation_context));

  // %13 is signed 0
  ASSERT_FALSE(TransformationAddTypeArray(100, 11, 13)
                   .IsApplicable(context.get(), transformation_context));

  // %14 is negative
  ASSERT_FALSE(TransformationAddTypeArray(100, 11, 14)
                   .IsApplicable(context.get(), transformation_context));

  // %17 is unsigned 0
  ASSERT_FALSE(TransformationAddTypeArray(100, 11, 17)
                   .IsApplicable(context.get(), transformation_context));

  {
    // %100 = OpTypeArray %10 %16
    TransformationAddTypeArray transformation(100, 10, 16);
    ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(100));
    ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(100));
    ASSERT_TRUE(
        transformation.IsApplicable(context.get(), transformation_context));
    ApplyAndCheckFreshIds(transformation, context.get(),
                          &transformation_context);
    ASSERT_EQ(spv::Op::OpTypeArray,
              context->get_def_use_mgr()->GetDef(100)->opcode());
    ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsArray());
  }

  {
    // %101 = OpTypeArray %7 %12
    TransformationAddTypeArray transformation(101, 7, 12);
    ASSERT_EQ(nullptr, context->get_def_use_mgr()->GetDef(101));
    ASSERT_EQ(nullptr, context->get_type_mgr()->GetType(101));
    ASSERT_TRUE(
        transformation.IsApplicable(context.get(), transformation_context));
    ApplyAndCheckFreshIds(transformation, context.get(),
                          &transformation_context);
    ASSERT_EQ(spv::Op::OpTypeArray,
              context->get_def_use_mgr()->GetDef(100)->opcode());
    ASSERT_NE(nullptr, context->get_type_mgr()->GetType(100)->AsArray());
  }

  ASSERT_TRUE(fuzzerutil::IsValidAndWellFormed(context.get(), validator_options,
                                               kConsoleMessageConsumer));

  std::string after_transformation = R"(
               OpCapability Shader
          %1 = OpExtInstImport "GLSL.std.450"
               OpMemoryModel Logical GLSL450
               OpEntryPoint Fragment %4 "main"
               OpExecutionMode %4 OriginUpperLeft
               OpSource ESSL 310
          %2 = OpTypeVoid
          %3 = OpTypeFunction %2
          %6 = OpTypeFloat 32
          %7 = OpTypeInt 32 1
          %8 = OpTypeVector %6 2
          %9 = OpTypeVector %6 3
         %10 = OpTypeVector %6 4
         %11 = OpTypeVector %7 2
         %12 = OpConstant %7 3
         %13 = OpConstant %7 0
         %14 = OpConstant %7 -1
         %15 = OpTypeInt 32 0
         %16 = OpConstant %15 5
         %17 = OpConstant %15 0
         %18 = OpConstant %6 1
        %100 = OpTypeArray %10 %16
        %101 = OpTypeArray %7 %12
          %4 = OpFunction %2 None %3
          %5 = OpLabel
               OpReturn
               OpFunctionEnd
  )";
  ASSERT_TRUE(IsEqual(env, after_transformation, context.get()));
}

}  // namespace
}  // namespace fuzz
}  // namespace spvtools


text:
<?php
/**
* Theme Customizer Library Template
*
* @link https://developer.wordpress.org/themes/advanced-topics/customizer-api/
*/

add_action( 'customize_register', 'medula_theme_customizer' );

function medula_theme_customizer( $wp_customize ) {
  // $wp_customize calls go here.
  //
  // Uncomment the below lines to remove the default customize sections

  // $wp_customize->remove_section('title_tagline');
  // $wp_customize->remove_section('colors');
  // $wp_customize->remove_section('background_image');
  // $wp_customize->remove_section('static_front_page');
  // $wp_customize->remove_section('nav');

  // Uncomment the below lines to remove the default controls
  // $wp_customize->remove_control('blogdescription');

  // Uncomment the following to change the default section titles
  // $wp_customize->get_section('colors')->title = __( 'Theme Colors' );
  // $wp_customize->get_section('background_image')->title = __( 'Images' );
}