text:
from .base import BaseTestCase

from . import utils

from webapp import utils as wutils

class UtilsTestCase(BaseTestCase):

    # Issue
    def test_get_prev_issue(self):
        """
        Teste da função utils.get_prev_issue().

        IMPORTANTE: A lista é invertida.
        """

        issue1 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '1', 'order': '1', })
        issue2 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '2', 'order': '2', })
        issue3 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '3', 'order': '3', })

        # criando uma lista de números ordenada
        issues = [issue1, issue2, issue3]

        prev_issue = wutils.get_prev_issue(issues, issue2)

        self.assertEqual(prev_issue, issue3)

    def test_get_next_issue(self):
        """
        Teste da função utils.get_next_issue().

        IMPORTANTE: A lista é invertida.
        """

        issue1 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '1', 'order': '1', })
        issue2 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '2', 'order': '2', })
        issue3 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '3', 'order': '3', })

        # criando uma lista de números ordenada
        issues = [issue1, issue2, issue3]

        next_issue = wutils.get_next_issue(issues, issue2)

        self.assertEqual(next_issue, issue1)

    def test_get_prev_issue_with_one_item(self):
        """
        Teste da função utils.get_prev_issue() without itens, deve retorna None.
        """

        issue1 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '1', 'order': '1', })

        issue = utils.makeOneIssue()

        # criando uma lista de números vazia
        issues = [issue1]

        prev_issue = wutils.get_prev_issue(issues, issue)

        self.assertIsNone(prev_issue)

    def test_get_next_issue_with_one_item(self):
        """
        Teste da função utils.get_next_issue() without itens, deve retorna None.
        """

        issue1 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '1', 'order': '1', })

        issue = utils.makeOneIssue()

        # criando uma lista de números vazia
        issues = [issue1]

        next_issue = wutils.get_next_issue(issues, issue)

        self.assertIsNone(next_issue)

    def test_get_prev_issue_when_the_last_issue(self):
        """
        Testando o get_prev_issue quando é acessado um índice inexistente, deve
        retorna None.

        Acessando o a um índice inexistente, o último item da lista irá retornar
        None pois não existe o índice [último] + 1 (Lembrando que a lista de
        número é invertida)

        Portanto a função get_prev_issue soma 1.

        IMPORTANTE: A lista é invertida.
        """

        issue1 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '1', 'order': '1', })
        issue2 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '2', 'order': '2', })
        issue3 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '3', 'order': '3', })
        issue4 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '4', 'order': '4', })

        # criando uma lista de números ordenada
        issues = [issue1, issue2, issue3, issue4]

        prev_issue = wutils.get_prev_issue(issues, issue4)

        self.assertIsNone(prev_issue)

    def test_get_next_issue_when_first_item(self):
        """
        Testando o get_next_issue quando é acessado o primiero índice, deve
        retorna None.

        Acessando o primiero item da lista irá retornar None.

        IMPORTANTE: A lista é invertida.
        """

        issue1 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '1', 'order': '1', })
        issue2 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '2', 'order': '2', })
        issue3 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '3', 'order': '3', })
        issue4 = utils.makeOneIssue({'year': '2016', 'volume': '1',
                                     'number': '4', 'order': '4', })

        # criando uma lista de números ordenada
        issues = [issue1, issue2, issue3, issue4]

        next_issue = wutils.get_next_issue(issues, issue1)

        self.assertIsNone(next_issue)

    # Article
    def test_get_prev_article(self):
        """
        Teste da função utils.get_prev_article().
        """

        article1 = utils.makeOneArticle({'order': '1', })
        article2 = utils.makeOneArticle({'order': '2', })
        article3 = utils.makeOneArticle({'order': '3', })

        # criando uma lista de artigos ordenada
        articles = [article1, article2, article3]

        prev_article = wutils.get_prev_article(articles, article2)

        self.assertEqual(prev_article, article1)

    def test_get_next_article(self):
        """
        Teste da função utils.get_next_article().
        """

        article1 = utils.makeOneArticle({'order': '1', })
        article2 = utils.makeOneArticle({'order': '2', })
        article3 = utils.makeOneArticle({'order': '3', })

        # criando uma lista de artigos ordenada
        articles = [article1, article2, article3]

        next_article = wutils.get_next_article(articles, article2)

        self.assertEqual(next_article, article3)

    def test_get_next_article_when_last_article(self):
        """
        Teste da função utils.get_next_article(), quando é o último artigo
        deve retorna None.
        """

        article1 = utils.makeOneArticle({'order': '1', })
        article2 = utils.makeOneArticle({'order': '2', })
        article3 = utils.makeOneArticle({'order': '3', })

        # criando uma lista de artigos ordenada
        articles = [article1, article2, article3]

        next_article = wutils.get_next_article(articles, article3)

        self.assertIsNone(next_article)

    def test_get_prev_article_when_first_article(self):
        """
        Teste da função utils.get_prev_article(), quando é o primeiro artigo
        deve retorna None.
        """

        article1 = utils.makeOneArticle({'order': '1', })
        article2 = utils.makeOneArticle({'order': '2', })
        article3 = utils.makeOneArticle({'order': '3', })

        # criando uma lista de artigos ordenada
        articles = [article1, article2, article3]

        prev_article = wutils.get_prev_article(articles, article1)

        self.assertIsNone(prev_article)


text:
<?php

$current_path = dirname(__FILE__);
$path = $current_path . PATH_SEPARATOR . $current_path . '/libs/PEAR'. PATH_SEPARATOR . dirname($current_path);
set_include_path($path . PATH_SEPARATOR . get_include_path());

?>

redpajama_set_name: RedPajamaGithub


text:
import * as Lint from "../lint";

describe("<curly>", () => {
    const fileName = "rules/curly.test.ts";
    const CurlyRule = Lint.Test.getRule("curly");
    let actualFailures: Lint.RuleFailure[];

    before(() => {
        actualFailures = Lint.Test.applyRuleOnFile(fileName, CurlyRule);
    });

    it("ensures if statements are always braced", () => {
        const failureString = CurlyRule.IF_FAILURE_STRING;
        const expectedFailure = Lint.Test.createFailure(fileName, [10, 5], [11, 26], failureString);
        Lint.Test.assertContainsFailure(actualFailures, expectedFailure);
    });

    it("ensures for statements are always braced", () => {
        const failureString = CurlyRule.FOR_FAILURE_STRING;
        const expectedFailure1 = Lint.Test.createFailure(fileName, [22, 3], [23, 24], failureString);
        const expectedFailure2 = Lint.Test.createFailure(fileName, [25, 1], [26, 22], failureString);
        const expectedFailure3 = Lint.Test.createFailure(fileName, [67, 1], [68, 20], failureString);

        Lint.Test.assertContainsFailure(actualFailures, expectedFailure1);
        Lint.Test.assertContainsFailure(actualFailures, expectedFailure2);
        Lint.Test.assertContainsFailure(actualFailures, expectedFailure3);
    });

    it("ensures while statements are always braced", () => {
        const failureString = CurlyRule.WHILE_FAILURE_STRING;
        const expectedFailure1 = Lint.Test.createFailure(fileName, [37, 1], [38, 22], failureString);
        Lint.Test.assertContainsFailure(actualFailures, expectedFailure1);
    });

    it("ensures do statements are always braced", () => {
        const failureString = CurlyRule.DO_FAILURE_STRING;
        const expectedFailure1 = Lint.Test.createFailure(fileName, [50, 1], [52, 16], failureString);
        Lint.Test.assertContainsFailure(actualFailures, expectedFailure1);
    });

    it("ensures else statements are always braced", () => {
        const failureString = CurlyRule.ELSE_FAILURE_STRING;
        const expectedFailure = Lint.Test.createFailure(fileName, [56, 3], [56, 25], failureString);
        Lint.Test.assertContainsFailure(actualFailures, expectedFailure);
    });

    it("does not have false positives", () => {
        assert.lengthOf(actualFailures, 7);
    });
});


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Class org.apache.hadoop.yarn.state.Graph (hadoop-yarn-common 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
org.apache.hadoop.yarn.state.Graph

Packages that use Graph

org.apache.hadoop.yarn.state

Uses of Graph in org.apache.hadoop.yarn.state

Methods in org.apache.hadoop.yarn.state that return Graph

 Graph
StateMachineFactory.generateStateGraph(String name)

          Generate a graph represents the state graph of this StateMachine

static Graph
VisualizeStateMachine.getGraphFromClasses(String graphName,
                    List<String> classes)

 Graph
Graph.getParent()

 Graph
Graph.Node.getParent()

 Graph
Graph.newSubGraph(String name)

Methods in org.apache.hadoop.yarn.state with parameters of type Graph

 void
Graph.addSubGraph(Graph graph)

Constructors in org.apache.hadoop.yarn.state with parameters of type Graph

Graph(String name,
      Graph parent)

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2015 Apache Software Foundation. All Rights Reserved.


text:
using System;
using System.Collections;
using System.Text;

using Hyena;

namespace Lastfm
{
    public class Account
    {
        public event EventHandler Updated;

        // Only used during the authentication process
        private string authentication_token;

        private string username;
        public string UserName {
            get { return username; }
            set { username = value; }
        }

        private string session_key;
        public string SessionKey {
            get { return session_key; }
            set { session_key = value; }
        }

        private bool subscriber;
        public bool Subscriber {
            get { return subscriber; }
            set { subscriber = value; }
        }

        private string scrobble_url;
        public string ScrobbleUrl {
            get { return scrobble_url; }
            set { scrobble_url = value; }
        }

        public string SignUpUrl {
            get { return "http://www.last.fm/join"; }
        }

        public void SignUp ()
        {
            Browser.Open (SignUpUrl);
        }

        public void VisitUserProfile (string username)
        {
            Browser.Open (String.Format ("http://last.fm/user/{0}", username));
        }

        public string HomePageUrl {
            get { return "http://www.last.fm/"; }
        }

        public void VisitHomePage ()
        {
            Browser.Open (HomePageUrl);
        }

        public virtual void Save ()
        {
            OnUpdated ();
        }

        public StationError RequestAuthorization ()
        {
            try {
                LastfmRequest get_token = new LastfmRequest ("auth.getToken", RequestType.Read, ResponseFormat.Json);
                get_token.Send ();

                var response = get_token.GetResponseObject ();
                object error_code;
                if (response.TryGetValue ("error", out error_code)) {
                    Log.WarningFormat ("Lastfm error {0} : {1}", (int)error_code, (string)response["message"]);
                    return (StationError) error_code;
                }

                authentication_token = (string)response["token"];
                Browser.Open (String.Format ("http://www.last.fm/api/auth?api_key={0}&token={1}", LastfmCore.ApiKey, authentication_token));

                return StationError.None;
            } catch (Exception e) {
                Log.Exception ("Error in Lastfm.Account.RequestAuthorization", e);
                return StationError.Unknown;
            }
        }

        public StationError FetchSessionKey ()
        {
            if (authentication_token == null) {
                return StationError.TokenNotAuthorized;
            }

            try {
                LastfmRequest get_session = new LastfmRequest ("auth.getSession", RequestType.SessionRequest, ResponseFormat.Json);
                get_session.AddParameter ("token", authentication_token);
                get_session.Send ();
                var response = get_session.GetResponseObject ();
                object error_code;
                if (response.TryGetValue ("error", out error_code)) {
                    Log.WarningFormat ("Lastfm error {0} : {1}", (int)error_code, (string)response["message"]);
                    return (StationError) error_code;
                }

                var session = (Hyena.Json.JsonObject)response["session"];
                UserName = (string)session["name"];
                SessionKey = (string)session["key"];
                Subscriber = session["subscriber"].ToString ().Equals ("1");

                // The authentication token is only valid once, and for a limited time
                authentication_token = null;

                return StationError.None;
            } catch (Exception e) {
                Log.Exception ("Error in Lastfm.Account.FetchSessionKey", e);
                return StationError.Unknown;
            }
        }

        protected void OnUpdated ()
        {
            EventHandler handler = Updated;
            if (handler != null) {
                handler (this, EventArgs.Empty);
            }
        }
    }
}


text:
#tagRepContainer svg {
    display: block;
    margin: auto;
}

/* CSS for toggler buttons */
.fill_bar
{
    height: 60%;
    top: 20%;
    bottom: auto;
}

/* CSS from html_formatter styles.css */
.html_formatter
{
    font-size: 16px;
    line-height: 24px;
    /* Someday the above sizing hacks won't be necessary:
       http://dev.w3.org/csswg/css4-text/#white-space-collapsing
     */
    /* white-space-collapse: discard; */
    padding: 20px;
}

.html_formatter .line > span
{
    font-size: 16px;
    line-height: 24px;
    white-space: pre-wrap;
    cursor: pointer;
    border-radius: 2px;
    /*border-top: 2px solid transparent;
    border-bottom: 2px solid transparent;*/
}

/*.html_formatter .line > span:not(data-key~="!UNTAGGED"]) {*/
    /*cursor: not-allowed !important;*/
    /*background: red !important;*/
/*}*/

.html_formatter .line > span {
    border-radius: 4px;
    border: 1px solid transparent;
    margin: -1px;
}

.html_formatter .line > span:hover,
.html_formatter .line > span.active,
.html_formatter .line > span.highlight,
.html_formatter .line > span.highlight-red
{
    border-color: #a6a6a6;
    background-color: #d9d9d9;
    /*box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15), 0 0 0 4px rgba(0, 0, 0, 0.15) !important;*/
    /*text-shadow: 0 1px 0 rgba(255,255,255,0.15), 0 -1px 0 rgba(255,255,255,0.15), -1px 0 0 rgba(255,255,255,0.15), 1px 0 0 rgba(255,255,255,0.15), 0 1px 2px rgba(255,255,255,0.35) !important;*/
    /*position: relative;*/
    /*z-index: 2;*/
}

/*.html_formatter .line > span:hover,
.html_formatter .line > span.active
{
    background-color: #808080;
    background-color: rgba(128,128,128,0.35);
}*/

.html_formatter .line > span.active
{
    /*box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15), 0 0 0 4px rgba(0, 0, 0, 0.35) !important;*/
}

.html_formatter .line > span.highlight
{
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15), 0 0 0 4px rgba(255, 255, 0, 0.65) !important;
}

.html_formatter .line > span.highlight-red
{
/*    -webkit-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15), 0 0 4px 2px rgba(255, 0, 0, 0.35) !important;
    -moz-box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15), 0 0 4px 2px rgba(255, 0, 0, 0.35) !important;*/
    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.15), 0 0 4px 2px rgba(255, 0, 0, 0.35) !important;
}

.html_formatter .line > span[data-active-tag~='!MULTIPLE'],
.html_formatter .line > span[data-active-tag~='!MULTIPLE_1']
{
    background-color: #969696 !important;
}

.html_formatter .line > span[data-active-tag~='!MULTIPLE_0']
{
    background-color: #D9D9D9 !important;
}

.html_formatter .line > span[data-active-tag~='!MULTIPLE_2']
{
    background-color: #525252 !important;
}

/*.html_formatter .line > span.highlight >span.tag-class
{
    display: none;
}*/

.html_formatter .line > span.highlight-red
{
    border: 3px solid #ff0000;
    margin: -3px;
}

/*.tags .line > span.tagged-token {*/
    /*background: green;*/
/*}*/

body.debug.testing .html_formatter .line > span.tag {
    outline: 1px solid green;
}

body.debug.testing .html_formatter .line > span.token {
    outline: 1px solid yellow;
}

body.debug.testing .html_formatter .line > span.str {
    outline: 1px solid red;
}

/*.html_formatter .line > span
{
    display: inline-block;
    line-height: 18px;
    margin: 1px 0;
}*/

/*.html_formatter .line > span .line > span.tag-class
{
    position: absolute;
    border-radius: 5px;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
}

.html_formatter .line > span .line > span.tag-class[class$="_4"]
{
    z-index: 4;
}

.html_formatter .line > span .line > span.tag-class[class$="_3"]
{
    z-index: 3;
}

.html_formatter .line > span .line > span.tag-class[class$="_2"]
{
    z-index: 2;
}

.html_formatter .line > span .line > span.tag-class[class$="_1"]
{
    z-index: 1;
}

.html_formatter .line > span .line > span.tag-class[class$="_0"]
{
    z-index: 1;
}

.html_formatter .line > span .line > span:not(.tag-class)
{
    position: relative;
    z-index: 5;
}

.html_formatter .line > span .line > span.tag-class
{
    display: none;
}
*/

.btn-group.tags_top_only .btn,
.btn-group.color_ramps .btn
{
    background-repeat: no-repeat;
    background-position: center;
    background-size: auto 100%;
    width: 265px;
    height: 172px;
}

.btn-group.tags_top_only .btn.btn-tags_top_only_off
{
    background-image: url('/static/img/tags_top_only_off_color_ramps_off.png');
    background-image: -webkit-image-set(url('/static/img/tags_top_only_off_color_ramps_off.png') 1x, url('/static/img/tags_top_only_off_color_ramps_off@2x.png') 2x);
}

.btn-group.tags_top_only .btn.btn-tags_top_only_on
{
    background-image: url('/static/img/tags_top_only_on_color_ramps_off.png');
    background-image: -webkit-image-set(url('/static/img/tags_top_only_on_color_ramps_off.png') 1x, url('/static/img/tags_top_only_on_color_ramps_off@2x.png') 2x);
}

.btn-group.tags_top_only .btn.btn-tags_top_only_on.color_ramps_on
{
    background-image: url('/static/img/tags_top_only_on_color_ramps_on.png');
    background-image: -webkit-image-set(url('/static/img/tags_top_only_on_color_ramps_on.png') 1x, url('/static/img/tags_top_only_on_color_ramps_on@2x.png') 2x);
}

.btn-group.tags_top_only .btn.btn-tags_top_only_off.color_ramps_on
{
    background-image: url('/static/img/tags_top_only_off_color_ramps_on.png');
    background-image: -webkit-image-set(url('/static/img/tags_top_only_off_color_ramps_on.png') 1x, url('/static/img/tags_top_only_off_color_ramps_on@2x.png') 2x);
}

.btn-group.color_ramps .btn
{
    height: 96px;
}

.btn-group.color_ramps .btn.color_ramps_off
{
    background-image: url('/static/img/color_ramps_off_tags_top_only_off.png');
    background-image: -webkit-image-set(url('/static/img/color_ramps_off_tags_top_only_off.png') 1x, url('/static/img/color_ramps_off_tags_top_only_off@2x.png') 2x);
}

.btn-group.color_ramps .btn.color_ramps_on
{
    background-image: url('/static/img/color_ramps_on_tags_top_only_off.png');
    background-image: -webkit-image-set(url('/static/img/color_ramps_on_tags_top_only_off.png') 1x, url('/static/img/color_ramps_on_tags_top_only_off@2x.png') 2x);
}

.btn-group.color_ramps .btn.color_ramps_off.tags_top_only_on
{
    background-image: url('/static/img/color_ramps_off_tags_top_only_on.png');
    background-image: -webkit-image-set(url('/static/img/color_ramps_off_tags_top_only_on.png') 1x, url('/static/img/color_ramps_off_tags_top_only_on@2x.png') 2x);
}

.btn-group.color_ramps .btn.color_ramps_on.tags_top_only_on
{
    background-image: url('/static/img/color_ramps_on_tags_top_only_on.png');
    background-image: -webkit-image-set(url('/static/img/color_ramps_on_tags_top_only_on.png') 1x, url('/static/img/color_ramps_on_tags_top_only_on@2x.png') 2x);
}


text:
package barf

import (
	"errors"
	"strings"
)

var (
	errorBadPath             = errors.New("Unable to parse provided path.")
	errorUnsupportedProtocol = errors.New("Unsupported filesystem.")
	errorNoBucket            = errors.New("No bucket specified.")
)

func parseSrc(srcPath string) (string, string, error) {
	// first check if empty
	if srcPath == "" {
		return "", "", errorBadPath
	}
	parts := strings.Split(srcPath, "://")
	if len(parts) == 2 {
		// ok, we have a supplied protocol!
		// now need to check if protocol we support.
		switch parts[0] {
		case "s3":
			return "s3", parts[1], nil
		case "fs":
			return "fs", parts[1], nil
		default:
			return "", "", errorUnsupportedProtocol
		}
	} else if len(parts) < 2 {
		// so no protocol specified, so assume filesystem
		return "fs", parts[0], nil
	} else {
		return "", "", errorBadPath
	}
}

func parseBucket(bucketPath string) (string, string, error) {
	if bucketPath == "" {
		return "", "", errorNoBucket
	}
	parts := strings.Split(bucketPath, "/")
	if parts[0] == "" {
		return "", "", errorNoBucket
	}
	// return prefix if we have it
	if len(parts) > 1 {
		return parts[0], strings.Join(parts[1:], "/"), nil
	}

	return parts[0], "", nil

}

// parses compression from s3 file keys
func parseCompression(key string) string {
	possible := []string{".gz", ".bz2"}
	for _, ending := range possible {
		// does key end in one of possible endings
		i := strings.Index(key, ending)
		if i == len(key)-len(ending) {
			return strings.TrimPrefix(ending, ".") // return file ending but without "."
		}
	}
	// no compression detected
	return ""
}


text:
# Example 02

##### Create a ContentType group

```php
namespace Application\Migrations;

use Kreait\EzPublish\MigrationsBundle\Migrations\EzPublishMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Creates a new content type group
 */
class Version20140508144959 extends EzPublishMigration
{
    /**
     * @var string
     */
    protected $groupName = 'My Custom Groupname';

    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        $contentTypeService = $this->repository->getContentTypeService();

        // Check if the group already exists
        $existingGroups = $contentTypeService->loadContentTypeGroups();
        foreach ($existingGroups as $g) {
            $this->skipIf($g->identifier == $this->groupName, "The group '{$this->groupName}' already exists");
        }

        // Create the group
        $contentTypeService->createContentTypeGroup(
            $contentTypeService->newContentTypeGroupCreateStruct($this->groupName)
        );
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // We don't delete existing ContentType groups so that we don't break things
    }
}
```


text:
package io.reark.reark.network.fetchers;

import android.content.Intent;
import android.support.annotation.NonNull;

/**
 * Interface for implementing Fetchers. A Fetcher is a class that fetches and stores data, usually
 * matching a single backend API endpoint.
 *
 * @param <T> Type of the Service Uri used by the application.
 */
public interface Fetcher<T> {

    /**
     * Starts a new fetch operation.
     *
     * @param intent Details of the fetch.
     * @param listenerId Id of the request status listener.
     */
    void fetch(@NonNull final Intent intent, int listenerId);

    /**
     * Returns a Service Uri of this fetcher. Service Uri is an identifier for the endpoint
     * to which this fetcher connects.
     *
     * @return Service Uri of this fetcher
     */
    @NonNull
    T getServiceUri();
}


text:
package org.camunda.bpm.spring.boot.starter.property;

import static org.camunda.bpm.spring.boot.starter.property.CamundaBpmProperties.joinOn;

public class FilterProperty {

  private String create;

  public String getCreate() {
    return create;
  }

  public void setCreate(String create) {
    this.create = create;
  }

  @Override
  public String toString() {
    return joinOn(this.getClass())
      .add("create=" + create)
      .toString();
  }

}


text:
@implementation ZPURLResponseConnectionOperation

- (void)connection:(NSURLConnection *)__unused connection didReceiveResponse:(NSHTTPURLResponse *)response
{
    [super connection:connection didReceiveResponse:response];

    _fileLength = response.expectedContentLength;
    _responseStatusCode = response.statusCode;

    [self cancel];
}

@end


text:
namespace Digiseller.Client.Core.Interfaces.CategoryGoods
{
    /// <summary>
    /// ISubcategory
    /// </summary>
    public interface ISubcategory
    {
        /// <summary>
        /// Id
        /// </summary>
        int Id { get; }

        /// <summary>
        /// Name
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Count of goods in current category
        /// </summary>
        int GoodsCount { get; }
    }
}


text:
composer install --prefer-dist --no-interaction

# Generate application key
php artisan key:generate

# Verify environment config
cat .env

# Install dependencies
npm install
npm run dev

# Execute PHPUnit tests
vendor/bin/phpunit


text:
"""
For detailed documentation and examples, see the README.
"""

import os

from .base import *
from .parallel import *

from .distributions import *
from .kmeans import Kmeans
from .gmm import GeneralMixtureModel
from .NaiveBayes import NaiveBayes
from .BayesClassifier import BayesClassifier
from .MarkovChain import MarkovChain
from .hmm import HiddenMarkovModel
from .BayesianNetwork import BayesianNetwork
from .MarkovNetwork import MarkovNetwork
from .FactorGraph import FactorGraph

__version__ = '0.14.8'

os.environ['OMP_NUM_THREADS'] = '1'
os.environ['MKL_NUM_THREADS'] = '1'

def from_json(s):
	"""A robust loading method.

	This method can load an appropriately formatted JSON object from any model
	in pomegranate and return the appropriate object. This relies mostly on the
	'class' attribute in the JSON.

	Parameters
	----------
	s : str
		Either the filename of a JSON object or a string that is JSON formatted,
		as produced by any of the `to_json` methods in pomegranate.
	"""

	try:
		d = json.loads(s)
	except:
		try:
			with open(s, 'r') as f:
				d = json.load(f)
		except:
			raise IOError("String must be properly formatted JSON or filename of properly formatted JSON.")

	if d['class'] == 'Distribution':
		return Distribution.from_json(s)
	elif d['class'] == 'GeneralMixtureModel':
		return GeneralMixtureModel.from_json(s)
	elif d['class'] == 'HiddenMarkovModel':
		return HiddenMarkovModel.from_json(s)
	elif d['class'] == 'NaiveBayes':
		return NaiveBayes.from_json(s)
	elif d['class'] == 'BayesClassifier':
		return BayesClassifier.from_json(s)
	elif d['class'] == 'BayesianNetwork':
		return BayesianNetwork.from_json(s)
	elif d['class'] == 'MarkovChain':
		return MarkovChain.from_json(s)
	elif d['class'] == 'MarkovNetwork':
		return MarkovNetwork.from_json(s)
	elif d['class'] == 'FactorGraph':
		return FactorGraph.from_json(s)
	else:
		raise ValueError("Must pass in an JSON with a valid model name.")


text:
(function(){
	"use strict";

	KC3StrategyTabs.ships = new KC3StrategyTab("ships");

	KC3StrategyTabs.ships.definition = {
		tabSelf: KC3StrategyTabs.ships,

		isLoading: false,
		shipCache:[],
		// Formatted settings to be stored into localStorage
		settings: {},
		// Default properties of sorters and views
		defaultSettings: {
			// default sorting method to Level
			currentSorters: [{name:"lv", reverse:false}],
			// default options of view
			equipMode: 0,
			multiKey: false,
			pageNo: false,
			scrollList: false,
			heartLockMode: 0,
			className: false,
			showTooltip: false,
			// a special filter for quick search by show name
			showNameFilter: "",
			// default values of filters are defined at `prepareFilters`
		},
		// All pre-defined filters instances
		newFilterRep: {},
		// All pre-defined sorters instances
		sorters: {},
		sorterDescCtrl: null,
		viewElements: {},

		/* INIT
		Prepares static data needed
		---------------------------------*/
		init :function(){
			$.extend(true, this, this.defaultSettings);
			this.prepareSorters();
		},

		/* RELOAD
		Prepares latest ships data
		---------------------------------*/
		reload :function(){
			PlayerManager.loadFleets();
			KC3ShipManager.load();
			KC3GearManager.load();
			// Cache pre-processed ship info
			this.shipCache = [];
			for(let key in KC3ShipManager.list){
				let shipData = KC3ShipManager.list[key];
				let preparedData = this.prepareShipData(shipData);
				this.shipCache.push(preparedData);
			}
		},

		/* EXECUTE
		Places data onto the interface
		---------------------------------*/
		execute :function(){
			var self = this;

			// Binding click event starts
			$(".filters_label").on("click", function(){
				$(".filters .ship_types").slideToggle(300);
				$(".filters .show_name_filter").slideToggle(300);
				$(".filters .massSelect").slideToggle(300, function(){
					$(".fold_button").toggleClass("glyph_minus", $(this).is(":visible"));
					$(".fold_button").toggleClass("glyph_plus", !$(this).is(":visible"));
					if(self.scrollList){
						self.toggleTableScrollbar(true);
					}
				});
			});
			$(".pages_yes").on("click", function(){
				if(!self.pageNo){
					self.pageNo = true;
					self.saveSettings();
				}
				self.refreshShowNameFilter();
			});
			$(".pages_no").on("click", function(){
				if(self.pageNo){
					self.pageNo = false;
					self.saveSettings();
				}
				self.refreshShowNameFilter();
			});
			$(".scroll_fix").on("click", function(){
				self.toggleTableScrollbar(true);
				if(!self.scrollList){
					self.scrollList = true;
					self.saveSettings();
				}
			});
			$(".scroll_none").on("click", function(){
				self.toggleTableScrollbar(false);
				if(self.scrollList){
					self.scrollList = false;
					self.saveSettings();
				}
				KC3StrategyTabs.reloadTab(undefined, false);
			});
			$(".lock_none").on("click", function(){
				$(".ship_list .ship_lock").hide();
				if(!!self.heartLockMode){
					self.heartLockMode = 0;
					self.saveSettings();
				}
			});
			$(".lock_yes").on("click", function(){
				if(self.heartLockMode !== 1){
					self.heartLockMode = 1;
					self.saveSettings();
				}
				KC3StrategyTabs.reloadTab(undefined, false);
			});
			$(".lock_no").on("click", function(){
				if(self.heartLockMode !== 2){
					self.heartLockMode = 2;
					self.saveSettings();
				}
				KC3StrategyTabs.reloadTab(undefined, false);
			});
			$(".class_yes").on("click", function(){
				if(!self.className){
					self.className = true;
					self.saveSettings();
				}
				KC3StrategyTabs.reloadTab(undefined, false);
			});
			$(".class_no").on("click", function(){
				if(self.className){
					self.className = false;
					self.saveSettings();
				}
				KC3StrategyTabs.reloadTab(undefined, false);
			});
			$(".tooltip_yes").on("click", function(){
				if(!self.showTooltip){
					self.showTooltip = true;
					self.saveSettings();
				}
				KC3StrategyTabs.reloadTab(undefined, false);
			});
			$(".tooltip_no").on("click", function(){
				if(self.showTooltip){
					self.showTooltip = false;
					self.saveSettings();
				}
				KC3StrategyTabs.reloadTab(undefined, false);
			});
			$(".ship_export .export_to_kanmusu_list").on("click", function() {
				// Export currently visible ships
				var selectedShips = self.shipCache.filter(function(x) {
					return self.executeFilters(x);
				});
				selectedShips.sort( function(a, b) {
					return RemodelDb.originOf(a.bid) - RemodelDb.originOf(b.bid)
						|| b.ship.level - a.ship.level;
				});

				var previousId = 0;
				var importString = ".2";
				// Format .2|shipId:shipLevel|shipId2:shipLevel2.remodel,shipLevel3|...
				for(var i = 0; i < selectedShips.length; i++) {
					var ship = selectedShips[i];
					var shipId = ship.bid;
					if(RemodelDb.originOf(shipId) === previousId)
						// Dupes are separated with ,
						importString += ",";
					else // While first ones are separated by |shipId
						importString += "|" + RemodelDb.originOf(shipId) + ":";
					importString += ship.ship.level;
					if(RemodelDb.remodelInfo(shipId) && ship.ship.level >= RemodelDb.remodelInfo(shipId).level) {
						var group = RemodelDb.remodelGroup(shipId);
						var remodelNumber = group.indexOf(shipId) + 1;
						if(remodelNumber < group.length) // Not necessary for last cyclic remodels
							importString += "." + remodelNumber;
					}
					previousId = RemodelDb.originOf(shipId);
				}

				// Customized base64 encoding: http://kancolle-calc.net/data/share.js
				var CODE = [ '0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
					'1000', '1001', '1010', '1011', '1100', '1101' ];
				var BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-';

				var buff = '';
				var outputString = '';
				for (var j = 0; j < importString.length; j++) {
					var c = importString.charAt(j);
					var pos;
					if (c == ',') {
						pos = 10;
					} else if (c == '|') {
						pos = 11;
					} else if (c == '.') {
						pos = 12;
					} else if (c == ':') {
						pos = 13;
					} else {
						pos = parseInt(c);
					}
					buff += CODE[pos];
					if (buff.length >= 6) {
						var seg = buff.slice(0, 6);
						outputString += BASE64.charAt(parseInt(seg, 2));
						buff = buff.slice(6);
					}
				}
				if (buff.length > 0) {
					while (buff.length < 6) {
						buff += '1';
					}
					outputString += BASE64.charAt(parseInt(buff, 2));
				}

				window.open("http://kancolle-calc.net/kanmusu_list.html?data=" + outputString);
			});
			$(".ship_export .export_to_kancepts").on("click", function() {
				window.open("https://javran.github.io/kancepts/?sl=" +
					self.shipCache.filter(x => x.locked).map(function(x) {
						return (x.ship.level > 99 ? "r" : "") + x.bid;
					}).join(","));
			});
			$(".control_buttons .reset_default").on("click", function(){
				delete self.currentSorters;
				$.extend(true, self, self.defaultSettings);
				delete localStorage.srShiplist;
				KC3StrategyTabs.reloadTab(undefined, true);
			});
			// Binding click event ends

			// Add filter elements of ship types before `prepareFilters` executed
			$.each(KC3Meta.sortedStypes(), (idx, stype) => {
				// stype 12, 15 not used by shipgirl, marked as order 999
				// stype 1 is used from 2017-05-02
				if(stype.id && stype.order < 999){
					let cElm = $(".tab_ships .factory .ship_filter_type").clone()
						.appendTo(".tab_ships .filters .ship_types");
					cElm.data("id", stype.id);
					$(".filter_name", cElm).text(stype.name);
				}
			});

			// Update multi sorter elements
			var multiKeyCtrl = $( ".advanced_sorter .adv_sorter" );
			var updateSorterControl = function() {
				$(".filter_check", multiKeyCtrl).toggle( self.multiKey );
				self.sorterDescCtrl.toggle(self.multiKey);
			};
			multiKeyCtrl.on("click", function() {
				self.multiKey = ! self.multiKey;

				updateSorterControl();

				if (! self.multiKey) {
					var needUpdate = self.cutCurrentSorter();
					if (needUpdate)
						self.refreshTable();
				}
			});

			this.loadSettings();
			this.sorterDescCtrl = $(".advanced_sorter .sorter_desc");
			this.updateSorterDescription();
			updateSorterControl();
			this.prepareFilters();
			this.shipList = $(".tab_ships .ship_list");
			this.showFilters();

			// Ship show name quick filter
			$(".show_name_filter .name_criteria").on("keyup", () => {
				this.refreshShowNameFilter();
			}).on("focus", () => {
				$(".show_name_filter .name_criteria").select();
			}).val(this.showNameFilter);
		},

		refreshShowNameFilter: function() {
			var self = this;
			const newNameCriteria = $(".show_name_filter .name_criteria").val();
			const nameToSearch = newNameCriteria.toLowerCase();
			let hiddenShipsByName = 0;
			$(".ingame_page").remove();
			if (nameToSearch.length > 0) {
				$(".ship_list .ship_item").each(function() {
					// also search for JP name and kana yomi, not so useful for JP tho
					const shipName = $(".ship_name", this).text().toLowerCase(),
						shipNameJp = ($(".ship_name", this).data("jpName") || "").toLowerCase(),
						shipNameKana = ($(".ship_name", this).data("jpNameKana") || "").toLowerCase();
					const isToHide = ! (shipName.includes(nameToSearch)
						|| shipNameJp.includes(nameToSearch)
						|| shipNameKana.includes(nameToSearch));
					hiddenShipsByName += isToHide & 1;
					$(this).toggleClass("hidden_by_name", isToHide);
				});
			} else {
				$(".ship_list .ship_item").removeClass("hidden_by_name");
			}

			let visibleShips = 0;
			$(".ship_list .ship_item").each(function() {
				if(!$(this).hasClass("hidden_by_name")) {
					$(this).removeClass("odd").removeClass("even")
						.addClass(visibleShips % 2 ? "even" : "odd");
					if(visibleShips % 10 === 0)
						$("<div>").addClass("ingame_page")
							.html("Page " + Math.ceil((visibleShips + 1) / 10))
							.insertBefore(this).toggle(self.pageNo);
					visibleShips++;
				}
			});
			// update listed ship counter
			// have to take filtered list by data into account since hidden by name are still in list
			const filteredBeforeName = $(".ship_count .count_value .listed").data("filtered") || 0;
			$(".ship_count .count_value .listed").text(filteredBeforeName - hiddenShipsByName);
			if (this.showNameFilter !== newNameCriteria) {
				this.showNameFilter = newNameCriteria;
				this.saveSettings();
			}
			return hiddenShipsByName;
		},

		getLastCurrentSorter: function() {
			return this.currentSorters[this.currentSorters.length-1];
		},

		reverseLastCurrentSorter: function() {
			var sorter = this.getLastCurrentSorter();
			sorter.reverse = ! sorter.reverse;
			this.updateSorterDescription();
		},

		// try pushing a new sorter to existing list
		// if the sorter already exists, the its "reverse"
		// value will be flipped.
		pushToCurrentSorters: function(name) {
			var i;
			var found = false;
			for (i=0; !found && i<this.currentSorters.length; ++i) {
				var sorterInfo = this.currentSorters[i];
				if (name === sorterInfo.name) {
					found = true;
					sorterInfo.reverse = ! sorterInfo.reverse;
				}
			}

			if (!found) {
				this.currentSorters.push({
					name: name,
					reverse: false
				});
			}

			this.updateSorterDescription();
		},

		// remove all sorters except the first one
		// returning true means visible ship list needs to be updated.
		cutCurrentSorter: function() {
			if (this.currentSorters.length > 1) {
				this.currentSorters = [ this.currentSorters[0] ];
				this.updateSorterDescription();
				return true;
			}
			return false;
		},

		setCurrentSorter: function(name) {
			var sorter = this.sorters[name];
			console.assert(sorter, "sorter should have been registered");
			this.currentSorters = [ {name: sorter.name, reverse:false} ];
			this.updateSorterDescription();
		},

		updateSorterDescription: function() {
			var self = this;
			var desc = this.currentSorters
				.map(function(sorterInfo) {
					var sorter = self.sorters[sorterInfo.name];
					return sorterInfo.reverse
						? sorter.desc + "(R)"
						: sorter.desc;
				})
				.join(" > ");

			this.sorterDescCtrl.text( desc );
		},

		// create comparator based on current list sorters
		makeComparator: function() {
			function reversed(comparator) {
				return function(l, r) {
					return -comparator(l, r);
				};
			}
			function compose(prevComparator, nextComparator) {
				return function(l, r) {
					return prevComparator(l, r) || nextComparator(l, r);
				};
			}
			// Append sortno as default sorter to keep order stable
			const lastSorterReverse = this.getLastCurrentSorter().reverse;
			const sortnoSorter = {
				name: "sortno",
				reverse: lastSorterReverse
			};
			const mergedSorters = this.currentSorters.concat([sortnoSorter]);
			// To simulate in-game behavior: if 1st sorter is stype,
			// reverse sortno and add descending level if necessary
			if(this.currentSorters[0].name == "type"){
				sortnoSorter.reverse = !sortnoSorter.reverse;
				if(this.currentSorters.every(si => si.name !== "lv")){
					mergedSorters.push({
						name: "lv",
						reverse: false
					});
				}
			}
			// For duplicated ships, final sorter if roster ID not used
			if(this.currentSorters.every(si => si.name !== "id")){
				mergedSorters.push({
					name: "id",
					reverse: false
				});
			}
			return mergedSorters
				.map( sorterInfo => {
					var sorter = this.sorters[sorterInfo.name];
					return sorterInfo.reverse
						? reversed(sorter.comparator)
						: sorter.comparator;
				})
				.reduce( compose );
		},

		// prepares necessary info.
		// also stores those that doesn't need to be recomputed overtime.
		prepareShipData: function(ship) {
			var ThisShip = ship;
			var MasterShip = ThisShip.master();
			var cached =  {
				id: ThisShip.rosterId,
				bid : ThisShip.masterId,
				stype: MasterShip.api_stype,
				ctype: MasterShip.api_ctype,
				sortno: MasterShip.api_sortno,
				name: ThisShip.name(),
				jpName: MasterShip.api_name,
				jpNameKana: MasterShip.api_yomi,
				className: KC3Meta.ctypeName(MasterShip.api_ctype),
				fullName: KC3Meta.term("ShipListFullNamePattern")
					.format(KC3Meta.ctypeName(MasterShip.api_ctype), ThisShip.name()),
				level: ThisShip.level,
				levelClass: ThisShip.levelClass(),
				morale: ThisShip.morale,
				equip: ThisShip.items,
				locked: ThisShip.lock,

				hp: [ThisShip.hp[1], ThisShip.maxHp(true), MasterShip.api_taik[0] ],
				fp: [MasterShip.api_houg[1], MasterShip.api_houg[0] + ThisShip.mod[0], ThisShip.fp[0] ],
				tp: [MasterShip.api_raig[1], MasterShip.api_raig[0] + ThisShip.mod[1], ThisShip.tp[0] ],
				yasen: [
					MasterShip.api_houg[1] + MasterShip.api_raig[1],
					MasterShip.api_houg[0] + ThisShip.mod[0] + MasterShip.api_raig[0] + ThisShip.mod[1],
					ThisShip.fp[0] + ThisShip.tp[0]
				],
				aa: [MasterShip.api_tyku[1], MasterShip.api_tyku[0]+ThisShip.mod[2], ThisShip.aa[0] ],
				ar: [MasterShip.api_souk[1], MasterShip.api_souk[0]+ThisShip.mod[3], ThisShip.ar[0] ],
				as: [ThisShip.nakedAsw(), ThisShip.maxAswMod(), ThisShip.nakedAsw() - ThisShip.mod[6], ThisShip.as[0] ],
				ev: [this.getDerivedStatNaked("houk", ThisShip.ev[0], ThisShip), ThisShip.ev[0] ],
				ls: [this.getDerivedStatNaked("saku", ThisShip.ls[0], ThisShip), ThisShip.ls[0] ],
				lk: [ThisShip.lk[0], ThisShip.lk[1], MasterShip.api_luck[0]],
				sp: ThisShip.speed,
				range: ThisShip.range,
				slots: ThisShip.slots,
				exSlot: ThisShip.ex_item,
				slotNum: ThisShip.slotnum,
				fleet: ThisShip.onFleet(),
				ship: ThisShip,
				master: ThisShip.master(),
				// Check whether remodel is max
				remodel: RemodelDb.isFinalForm(ship.masterId),
				canEquipDaihatsu: ThisShip.canEquipDaihatsu()
			};
			var ThisShipData = cached;
			// Check whether modernization is max
			if( ThisShipData.fp[0] == ThisShipData.fp[1]
				&& ThisShipData.tp[0] == ThisShipData.tp[1]
				&& ThisShipData.aa[0] == ThisShipData.aa[1]
				&& ThisShipData.ar[0] == ThisShipData.ar[1]
			  )
				ThisShipData.statmax = 1;
			else
				ThisShipData.statmax = 0;
			return cached;
		},

		// default UI actions for options that are mutually exclusive
		// NOTE: this function is supposed to be a shared callback function
		// and should not be called directly.
		_mutualExclusiveOnToggle: function(selectedInd,optionRep,initializing) {
			// mutual exclusive options use just value indices
			// as the option value
			var oldVal = optionRep.curValue;
			if (oldVal === selectedInd)
				return;
			// first update value
			optionRep.curValue = selectedInd;
			// then update UI accordingly
			$.each(optionRep.options, function(thisInd, optionObj) {
				optionObj.view.toggleClass('on', thisInd === selectedInd);
			});
			// only trigger update when it's not the first time
			// first time we just need to give it a initial value (default value)
			// and then update UI.
			if (!initializing)
				this.refreshTable();
		},

		// findView given filter's name and this option
		// NOTE: this function is supposed to be a shared callback function
		// and should not be called directly.
		_commonFindView: function(filterName, option) {
			return $(".tab_ships .filters .massSelect"
					 +" ." + filterName
					 + "_" + option);
		},

		/*
		   defineShipFilter defines a filter that has UI controls.
		   see comments on each arguments for detail.
		 */
		defineShipFilter: function(
			// a string name for this filter
			filterName,
			// ship filters can hold a piece of value
			// which represents its state.
			// (e.g. true / false for keeping track of whether
			//  this filter is enabled or disable)
			defValue,
			// an array of arbitrary values, each of the option should
			// correspond to a toggle / control on UI
			options,
			// a callback function testShip(curVal,ship)
			// that does the actual filtering:
			// returning a falsy value means
			// the ship should be filtered out from the list.
			// curVal is the current state of the filter.
			testShip,
			// findView(filterName,option) should return
			// a jQuery object that represents the UI control specified by
			// "filterName" and "option", where "option" is one value from "options"
			// note that the length of the jquery object has to be exactly one,
			// otherwise you'll see assertion failures in the console.
			findView,
			// onToggle(newVal,optionRep,initializing) that triggers either when initializing
			// or when user has changed something on UI.
			// optionRep is the runtime representation of this filter:
			// * optionRep.curValue represents the current value
			//   held by this filter, when initializing, this value is set to "null".
			// * optionRep.options is the runtime representation of
			//   all options you have passed to this function.
			//   for all valid options indices ind
			//   * optionRep.options[ind].name is set to options[ind]
			//   * optionRep.options[ind].view is set to the jQuery object returned
			//     by your "findView".
			// * initializing: newly added to help indicate whether we are initializing
			// your onToggle is responsible for 2 things:
			// * when initalizing a filter, "optionRep.curValue" is set to "null",
			//   in this case "newVal" is "defValue" you passed to this function,
			//   you should do something like "optionRep.curValue = newVal"
			//   to complete initializing filter state. and update UI accordingly
			//   (but avoid refreshing ship list, since we are just initalizing)
			// * when user does something on UI, your onToggle function will be triggered.
			//   in this case "newVal" is set to an index of "options" to indicate
			//   which option triggers this function. in this case you are responsible
			//   for updating "optionRep.curValue" accordingly, updating UI to reflect the change
			//   and finally refresh ship list to execute all filters.
			onToggle) {
			var self = this;
			// as most filters are groups of mutually exclusive controls
			// it makes sense setting them as defaults
			if (! findView)
				findView = this._commonFindView;
			if (! onToggle)
				onToggle = this._mutualExclusiveOnToggle;

			var newOptions = [];
			$.each(options, function(ind, optionName) {
				var thisOption = {};
				var view = findView(filterName,optionName);
				thisOption.name = optionName;
				thisOption.view = view;
				thisOption.view.on('click', function(e) {
					var curRep = self.newFilterRep[filterName];
					var selectedInd = ind;
					curRep.onToggle.call(self,selectedInd,curRep,false,e);
				});
				console.assert(
					thisOption.view.length === 1,
					"expecting exactly one result of getView on "
						+ filterName  + "," + optionName );
				newOptions.push( thisOption );
			});

			var optionRep = {
				curValue: null,
				options: newOptions,
				onToggle: onToggle,
				testShip: function (ship) {
					return testShip(optionRep.curValue,ship);
				}
			};

			this.newFilterRep[filterName] = optionRep;
			optionRep.onToggle.call(self,defValue,optionRep,true);
		},

		prepareFilters: function() {
			var self = this;
			var savedFilterValues = this.settings.filters || {};
			self.defineShipFilter(
				"marriage",
				savedFilterValues.marriage || 0,
				[ "in","on","ex" ],
				function(curVal, ship) {
					return (curVal === 0)
						|| (curVal === 1 && ship.level >= 100)
						|| (curVal === 2 && ship.level <  100);
				});

			self.defineShipFilter(
				"remodel",
				savedFilterValues.remodel || 0,
				["all","max","nomax"],
				function(curVal, ship) {
					return (curVal === 0)
						|| (curVal === 1 && ship.remodel)
						|| (curVal === 2 && !ship.remodel);
				});

			self.defineShipFilter(
				"modernization",
				savedFilterValues.modernization || 0,
				["all","max","nomax"],
				function(curVal, ship) {
					return (curVal === 0)
						|| (curVal === 1 && ship.statmax)
						|| (curVal === 2 && !ship.statmax);
				});

			self.defineShipFilter(
				"heartlock",
				savedFilterValues.heartlock || 0,
				["all","yes","no"],
				function(curVal, ship) {
					return (curVal === 0)
						|| (curVal === 1 && ship.locked === 1)
						|| (curVal === 2 && ship.locked === 0);
				});

			self.defineShipFilter(
				"speed",
				savedFilterValues.speed || 0,
				["all","slow","fast","faster","fastest"],
				function(curVal,ship) {
					return (curVal === 0)
						|| (curVal === 1 && ship.sp > 0 && ship.sp < 10)
						|| (curVal === 2 && ship.sp >= 10 && ship.sp < 15)
						|| (curVal === 3 && ship.sp >= 15 && ship.sp < 20)
						|| (curVal === 4 && ship.sp >= 20);
				});

			self.defineShipFilter(
				"fleet",
				savedFilterValues.fleet || 0,
				["all", "yes","no"],
				function(curVal,ship) {
					return (curVal === 0)
						|| (curVal === 1 && ship.fleet)
						|| (curVal === 2 && !ship.fleet);
				});

			self.defineShipFilter(
				"sparkle",
				savedFilterValues.sparkle || 0,
				["all", "yes","no"],
				function(curVal, ship) {
					return (curVal === 0)
						|| (curVal === 1 && ship.morale >= 50)
						|| (curVal === 2 && ship.morale < 50);
				});

			self.defineShipFilter(
				"daihatsu",
				savedFilterValues.daihatsu || 0,
				["all", "yes","no"],
				function(curVal, ship) {
					return (curVal === 0)
						|| (curVal === 1 && ship.canEquipDaihatsu)
						|| (curVal === 2 && !ship.canEquipDaihatsu);
				});

			self.defineShipFilter(
				"exslot",
				savedFilterValues.exslot || 0,
				["all", "yes","no"],
				function(curVal, ship) {
					return (curVal === 0)
						|| (curVal === 1 && (ship.exSlot > 0 || ship.exSlot === -1))
						|| (curVal === 2 && ship.exSlot === 0);
				});

			self.defineShipFilter(
				"dupe",
				savedFilterValues.dupe || 0,
				["all", "yes","no"],
				function(curVal, ship) {
					if(curVal === 0) return true;
					var dupeShips = self.shipCache.filter(s =>
						(RemodelDb.originOf(ship.bid) === RemodelDb.originOf(s.bid)
							&& s.id !== ship.id)
					);
					return (curVal === 1 && dupeShips.length > 0)
							|| (curVal === 2 && dupeShips.length === 0);
				});

			self.defineShipFilter(
				"range",
				savedFilterValues.range || 0,
				["all","short","medium","long","verylong"],
				function(curVal, ship) {
					return (curVal === 0)
						|| (curVal === ship.range);
				});

			var stypes = Object.keys(KC3Meta.allStypes())
				.map(id => parseInt(id, 10))
				.filter(id => [12, 15].indexOf(id) < 0)
				.sort((a, b) => a - b);
			console.assert(stypes[0] === 0, "stype array should start with element 0");
			// remove initial "0", which is invalid
			stypes.shift();
			var stypeDefValue = [];
			$.each(stypes, function(ignore, stype) {
				stypeDefValue[stype] = true;
			});

			self.defineShipFilter(
				"stype",
				savedFilterValues.stype || stypeDefValue,
				// valid ship types and additionally 3 controls
				stypes.concat(["all","none","invert"]),
				// testShip
				function(curVal, ship) {
					return curVal[ship.stype];
				},
				// find view
				function (filterName, option) {
					if (typeof option === "number") {
						// this is a ship type toggle
						return $(".tab_ships .filters .ship_types .ship_filter_type")
							.filter( function() { return $(this).data("id") == option; } );
					} else {
						// one of: all / none / invert
						return $(".tab_ships .filters .massSelect ." + option);
					}
				},
				// onToggle
				function(selectedInd, optionRep, initializing, event) {
					if (initializing) {
						// the variable name is a bit misleading..
						// but at this point we should set the initial value
						optionRep.curValue = selectedInd;
					} else {
						var selected = optionRep.options[selectedInd];
						if (typeof selected.name === 'number') {
							if(event && event.altKey){
								// only select this ship type if Alt key held
								$.each(stypes, function(ignore, stype) {
									optionRep.curValue[stype] = false;
								});
								optionRep.curValue[selected.name] = true;
							} else {
								// this is a ship type toggle
								optionRep.curValue[selected.name] = !optionRep.curValue[selected.name];
							}
						} else {
							$.each(stypes, function(ignore, stype) {
								optionRep.curValue[stype] =
									(selected.name === "all")
									? true
									: (selected.name === "none")
									? false
									: ! optionRep.curValue[stype];
							});
						}
					}
					// update UI
					$.each(optionRep.options, function(ignored, x) {
						if (typeof x.name === "number") {
							$( ".filter_check", x.view ).toggle( optionRep.curValue[x.name] );
						}
					});
					if (!initializing)
						self.refreshTable();
				}
			);
		},

		// execute all registered filters on a ship
		executeFilters: function(ship) {
			for(let key in this.newFilterRep) {
				var filter = this.newFilterRep[key].testShip;
				if (!filter(ship)) return false;
			}
			return true;
		},

		saveSettings: function() {
			var shrinkedSettings = {
				sorters: this.currentSorters,
				filters: {},
				views: {}
			};
			for(let key in this.newFilterRep) {
				shrinkedSettings.filters[key] = this.newFilterRep[key].curValue;
			}
			shrinkedSettings.filters.showname = this.showNameFilter;
			shrinkedSettings.views.equip = this.equipMode;
			shrinkedSettings.views.page = this.pageNo;
			shrinkedSettings.views.scroll = this.scrollList;
			shrinkedSettings.views.lock = this.heartLockMode;
			shrinkedSettings.views.ctype = this.className;
			shrinkedSettings.views.tooltip = this.showTooltip;
			this.settings = shrinkedSettings;
			localStorage.srShiplist = JSON.stringify(this.settings);
		},

		loadSettings: function() {
			this.settings = JSON.parse( localStorage.srShiplist || "{}" );
			if(this.settings.sorters){
				this.currentSorters = this.settings.sorters;
				if(this.currentSorters.length > 1)
					this.multiKey = true;
			}
			if(this.settings.filters){
				this.showNameFilter = this.settings.filters.showname || "";
			}
			if(this.settings.views){
				this.equipMode = this.settings.views.equip || 0;
				this.pageNo = this.settings.views.page || false;
				this.scrollList = this.settings.views.scroll || false;
				this.heartLockMode = this.settings.views.lock || 0;
				this.className = this.settings.views.ctype || false;
				this.showTooltip = this.settings.views.tooltip || false;
			}
		},

		/* FILTERS
		Ship types, and other toggles
		---------------------------------*/
		showFilters :function(){
			var self = this;
			var sCtr;

			// Equip Stats: Yes
			self.viewElements.equip_yes = $(".tab_ships .filters .massSelect .equip_yes")
			.on("click", function(){
				self.equipMode = 1;
				self.refreshTable();
				self.viewElements.equip_yes.addClass('on');
				self.viewElements.equip_no.removeClass('on');
			});

			// Equip Stats: No
			self.viewElements.equip_no = $(".tab_ships .filters .massSelect .equip_no")
			.on("click", function(){
				self.equipMode = 0;
				self.refreshTable();
				self.viewElements.equip_yes.removeClass('on');
				self.viewElements.equip_no.addClass('on');
			});

			// Default status
			if( self.equipMode )
				self.viewElements.equip_yes.addClass('on');
			else
				self.viewElements.equip_no.addClass('on');

			// Column header sorting
			$(".tab_ships .ship_header .ship_field.hover").on("click", function(){
				var sorter = self.getLastCurrentSorter();
				var sorterName = $(this).data("type");
				if (sorterName === sorter.name) {
					self.reverseLastCurrentSorter();
				} else {
					if (self.multiKey) {
						// for multi index sorters
						self.pushToCurrentSorters( sorterName );
					} else {
						// for normal sorters
						self.setCurrentSorter( sorterName  );
					}
				}
				self.refreshTable();
			});

			this.refreshTable();
		},

		defineSorter: function(name,desc,comparator) {
			this.sorters[name] = {
				name: name,
				desc: desc,
				comparator: comparator
			};
		},

		defineSimpleSorter: function(name,desc,getter) {
			var self = this;
			this.defineSorter(
				name,desc,
				function(a,b) {
					var va = getter.call(self,a);
					var vb = getter.call(self,b);
					return typeof va === "string" ? va.localeCompare(vb) : va - vb;
				});
		},

		prepareSorters: function() {
			var define = this.defineSimpleSorter.bind(this);

			define("id", "Id",
				   function(x) { return x.id; });
			define("name", "Name",
				   function(x) { return this.className ? x.fullName : x.name; });
			define("type", "Type",
				   function(x) { return x.stype; });
			define("lv", "Level",
				   function(x) { return -x.level; });
			define("morale", "Morale",
				   function(x) { return -x.morale; });
			define("hp", "HP",
				   function(x) { return -x.hp[0]; });
			define("fp", "Firepower",
				   function(x) { return -x.fp[this.equipMode+1]; });
			define("tp", "Torpedo",
				   function(x) { return -x.tp[this.equipMode+1]; });
			define("yasen", "Yasen",
				   function(x) { return -(x.fp[this.equipMode+1] + x.tp[this.equipMode+1]); });
			define("aa", "Anti-Air",
				   function(x) { return -x.aa[this.equipMode+1]; });
			define("ar", "Armor",
				   function(x) { return -x.ar[this.equipMode+1]; });
			define("as", "ASW",
				   function(x) { return -x.as[this.equipMode ? 3 : 0]; });
			define("ev", "Evasion",
				   function(x) { return -x.ev[this.equipMode]; });
			define("ls", "LoS",
				   function(x) { return -x.ls[this.equipMode]; });
			define("lk", "Luck",
				   function(x) { return -x.lk[0]; });
			define("ctype", "Class",
				   function(x) { return x.ctype; });
			define("bid", "ShipId",
				   function(x) { return x.bid; });
			define("sortno", "SortOrder",
				   function(x) { return x.sortno; });
		},

		/* REFRESH TABLE
		Reload ship list based on filters
		---------------------------------*/
		refreshTable :function(){
			// use "isLoading" to check if we need UI update.
			if(this.isLoading){ return false; }
			this.isLoading = true;
			this.saveSettings();

			var self = this;
			this.startTime = Date.now();

			// Update indicators of sorters
			$(".tab_ships .ship_header .ship_field.hover").removeClass("sorted");
			$.each(this.currentSorters, function(i, s){
				$(".tab_ships .ship_header .ship_field.hover.ship_{0}".format(s.name)).addClass("sorted");
			});

			// Clear list
			this.shipList.empty().hide();
			$(".ship_count .count_value").hide();

			// Wait until execute
			setTimeout(function(){
				var shipCtr, cElm, cShip, shipLevel;

				// Filtering
				var FilteredShips = self.shipCache.filter(function(x) {
					return self.executeFilters(x);
				});

				// Sorting
				FilteredShips.sort( self.makeComparator() );

				// Fill up list
				Object.keys(FilteredShips).forEach(function(shipCtr){
					cShip = FilteredShips[shipCtr];
					shipLevel = cShip.level;

					// we can save some time by avoiding constructing jquery object
					// if we already have one
					if (cShip.view) {
						cElm = cShip.view;
						cElm.appendTo(self.shipList);

						if (cElm.onRecompute)
							cElm.onRecompute(cShip);
						return;
					}

					// elements constructing for the time-consuming 'first time rendering'
					cElm = $(".tab_ships .factory .ship_item").clone().appendTo(self.shipList);
					cShip.view = cElm;

					$(".ship_id", cElm).text( cShip.id );
					$(".ship_img .ship_icon", cElm)
						.attr("src", KC3Meta.shipIcon(cShip.bid))
						.attr("alt", cShip.bid);
					$(".ship_name", cElm).data("jpName", cShip.jpName)
						.data("jpNameKana", cShip.jpNameKana);
					if(shipLevel >= 100) {
						$(".ship_name", cElm).addClass("ship_kekkon-color");
					}
					if(cShip.fleet > 0) {
						$(".ship_name", cElm).addClass("ship_onfleet-color" + cShip.fleet);
					}
					$(".ship_type", cElm).text( KC3Meta.stype(cShip.stype) );
					$(".ship_lv .value", cElm).text( shipLevel )
						.addClass( cShip.levelClass );
					$(".ship_morale", cElm).text( cShip.morale );

					if(cShip.morale >= 50){ $(".ship_morale", cElm).addClass("sparkled"); }

					// Check whether remodel is max
					if( !cShip.remodel )
						cElm.addClass('remodel-max');
					else
						cElm.addClass('remodel-able');

					// Check whether modernization is max
					if( cShip.statmax )
						cElm.addClass('modernization-max');
					else
						cElm.addClass('modernization-able');

					cShip.equip.forEach(function(gid, idx){
						self.equipImg(cElm, idx + 1, cShip.slotNum, cShip.slots[idx], gid, cShip.id);
					});
					if(cShip.exSlot !== 0){
						self.equipImg(cElm, "ex", cShip.slotNum, -2, cShip.exSlot);
					}
					$(".ship_equip", cElm).toggleClass("slot5",
						cShip.slotNum + ((cShip.exSlot !== 0) & 1) > 5);

					// callback for things that has to be recomputed
					cElm.onRecompute = function(ship) {
						const thisShip = ship || cShip;
						// Reset shown ship name
						const showName = self.className ? thisShip.fullName : thisShip.name;
						$(".ship_name", this).text(showName).attr("title", showName);
						// Recomputes stats
						self.modernizableStat("hp", this, thisShip.hp, 0, 0, true);
						self.modernizableStat("fp", this, thisShip.fp, 2, 1);
						self.modernizableStat("tp", this, thisShip.tp, 2, 1);
						self.modernizableStat("yasen", this, thisShip.yasen);
						self.modernizableStat("aa", this, thisShip.aa, 2, 1);
						self.modernizableStat("ar", this, thisShip.ar, 2, 1);
						self.modernizableStat("as", this, thisShip.as, 3, 0, true);
						$(".ship_ev", this).text( thisShip.ev[self.equipMode] );
						$(".ship_ls", this).text( thisShip.ls[self.equipMode] );
						self.modernizableStat("lk", this, thisShip.lk, 0, 0, true);
						// Reset heart-lock icon
						$(".ship_lock img", this).attr("src",
							"/assets/img/client/heartlock{0}.png"
								.format(!thisShip.locked ? "-x" : "")
						).show();
						if((self.heartLockMode === 1 && thisShip.locked)
						|| (self.heartLockMode === 2 && !thisShip.locked)) {
							$(".ship_lock", this).show();
						} else {
							$(".ship_lock", this).hide();
						}
						// Update tooltip
						const targetElm = $(".ship_img .ship_icon", this);
						if(targetElm.tooltip("instance") !== undefined){
							targetElm.tooltip("destroy");
						}
						if(self.showTooltip){
							const tooltipBox = KC3ShipManager.get(thisShip.id)
								.htmlTooltip($(".tab_ships .factory .ship_tooltip").clone());
							targetElm.tooltip({
								position: { my: "left top", at: "left+25 bottom" },
								items: "div",
								content: tooltipBox.prop("outerHTML"),
								// might be disabled for performance
								open: KC3Ship.onShipTooltipOpen,
							});
						}
						// Rebind click handlers
						$(".ship_img .ship_icon", this).click(self.shipClickFunc);
						$(".ship_equip_icon img", this).click(self.gearClickFunc);
					};
					// also invoke recompute for the first time
					cElm.onRecompute(cShip);

				});

				self.shipList.show().createChildrenTooltips();
				$(".ship_count .count_value .listed").text(FilteredShips.length)
					.data("filtered", FilteredShips.length);
				$(".ship_count .count_value .total").text(self.shipCache.length);
				$(".ship_count .count_value").show();
				self.refreshShowNameFilter();
				self.toggleTableScrollbar(self.scrollList);
				self.isLoading = false;
				console.debug("Showing ship list took", (Date.now() - self.startTime)-100 , "milliseconds");
			}, 100);
		},

		shipClickFunc: function(e){
			KC3StrategyTabs.gotoTab("mstship", $(this).attr("alt"));
		},

		gearClickFunc: function(e){
			KC3StrategyTabs.gotoTab("mstgear", $(this).attr("alt"));
		},

		toggleTableScrollbar: function(isFixed){
			$(".ship_list").toggleClass("scroll_fix", isFixed);
			$(".page_padding").toggleClass("scroll_fix", isFixed);
			if(isFixed){
				$(".ship_list").height(window.innerHeight - $(".ship_list").offset().top - 5);
			}
		},

		/* Compute Derived Stats without Equipment
		--------------------------------------------*/
		getDerivedStatNaked :function(statName, equippedValue, shipObj){
			return equippedValue - shipObj.equipmentTotalStats(statName, true);
		},

		/* Show cell contents of a mod stat
		--------------------------------------------*/
		modernizableStat :function(statAbbr, rowElm, valuesTuple,
				equipStatIndex = 2, noEquipStatIndex = 1, isSup = false){
			const statElm = $(".ship_" + statAbbr, rowElm);
			$(".stat_value", statElm).text(
				valuesTuple[equipStatIndex > 0 ?
					(this.equipMode ? equipStatIndex : noEquipStatIndex) :
					noEquipStatIndex]
			);
			if(isSup){
				if(valuesTuple[0] >= valuesTuple[1]){
					statElm.addClass("max");
				}
				if(valuesTuple[0] > valuesTuple[2]){
					$(".sup", statElm).text(valuesTuple[0] - valuesTuple[2]);
				} else {
					$(".sup", statElm).hide();
				}
			} else {
				if(valuesTuple[0] <= valuesTuple[1]){
					$(".stat_left", statElm).hide();
					statElm.addClass("max");
				} else {
					$(".stat_left", statElm).show()
						.text("+" + (valuesTuple[0] - valuesTuple[1]));
				}
			}
		},

		/* Show single equipment icon
		--------------------------------------------*/
		equipImg :function(cElm, slotIndex, slotCount, slotSize, gearId, shipId){
			var element = $(".ship_equip_" + slotIndex, cElm);
			if(gearId > 0){
				var gear = KC3GearManager.get(gearId);
				if(gear.isDummy()){ element.hide(); return; }
				var ship = shipId > 0 ? KC3ShipManager.get(shipId) : undefined;
				$("img", element)
					.attr("src", "/assets/img/items/" + gear.master().api_type[3] + ".png")
					.attr("title", gear.htmlTooltip(slotSize, ship))
					.attr("alt", gear.master().api_id)
					.show();
				$("span", element).css("visibility", "hidden");
				element.show();
			} else if(slotIndex === "ex" || slotIndex <= Math.max(4, slotCount)){
				$("img", element).hide();
				const sizeSpan = $("span", element);
				if(slotSize > 0)
					sizeSpan.text(slotSize);
				else if(slotSize === -2)
					// for ex slot opened, but not equipped
					sizeSpan.addClass("empty");
				else
					sizeSpan.css("visibility", "hidden");
			} else {
				element.hide();
			}
		}
	};

})();


text:
using System;
using System.Linq;
using Microsoft.Azure;
using Microsoft.Azure.Management.RecoveryServices.Backup.Models;

namespace Microsoft.Azure.Management.RecoveryServices.Backup.Models
{
    /// <summary>
    /// List of protected items returned as a response by the list protected
    /// item API.
    /// </summary>
    public partial class ProtectedItemListResponse : AzureOperationResponse
    {
        private ProtectedItemResourceList _itemList;

        /// <summary>
        /// Optional. List of protected item resources.
        /// </summary>
        public ProtectedItemResourceList ItemList
        {
            get { return this._itemList; }
            set { this._itemList = value; }
        }

        /// <summary>
        /// Initializes a new instance of the ProtectedItemListResponse class.
        /// </summary>
        public ProtectedItemListResponse()
        {
        }
    }
}


text:
EXECUTABLE	:= bandwidthTest
# Cuda source files (compiled with cudacc)
CUFILES		:=  bandwidthTest.cu
# C/C++ source files (compiled with gcc / c++)
CCFILES		:=

# Do not link with CUTIL or SHRUTIL
OMIT_CUTIL_LIB := 1

################################################################################
# Rules and targets

include ../../common/common.mk


text:
namespace base {
class SingleThreadTaskRunner;
}

class TokenWebDataBackend;
class WebDatabaseService;
class WebDataServiceConsumer;

// The result of a get tokens operation.
struct TokenResult {
  TokenResult();
  TokenResult(const TokenResult& other);
  ~TokenResult();

  TokenServiceTable::Result db_result;
  std::map<std::string, std::string> tokens;
};

// TokenWebData is a data repository for storage of authentication tokens.

class TokenWebData : public WebDataServiceBase {
 public:
  TokenWebData(scoped_refptr<WebDatabaseService> wdbs,
               scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
               scoped_refptr<base::SingleThreadTaskRunner> db_task_runner);

  TokenWebData(scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
               scoped_refptr<base::SingleThreadTaskRunner> db_task_runner);

  TokenWebData(const TokenWebData&) = delete;
  TokenWebData& operator=(const TokenWebData&) = delete;

  // Set a token to use for a specified service.
  void SetTokenForService(const std::string& service, const std::string& token);

  // Remove all tokens stored in the web database.
  void RemoveAllTokens();

  // Removes a token related to |service| from the web database.
  void RemoveTokenForService(const std::string& service);

  // Null on failure. Success is WDResult<std::vector<std::string> >
  virtual Handle GetAllTokens(WebDataServiceConsumer* consumer);

 protected:
  // For unit tests, passes a null callback.
  TokenWebData();

  ~TokenWebData() override;

 private:
  scoped_refptr<TokenWebDataBackend> token_backend_;
};

#endif  // COMPONENTS_SIGNIN_PUBLIC_WEBDATA_TOKEN_WEB_DATA_H_


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/minutesEditText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:ems="5"
            android:inputType="number"
            android:maxLength="3" >

            <requestFocus />
        </EditText>

        <TextView
            android:id="@+id/minutesTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/minutes" />

        <EditText
            android:id="@+id/secondsEditText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".5"
            android:ems="5"
            android:inputType="number"
            android:maxLength="2"/>

        <TextView
            android:id="@+id/secondsTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/seconds" />

    </LinearLayout>

    <include layout="@layout/horizontal_divider_line_blue"/>

    <include layout="@layout/confirmation_bar"/>
</LinearLayout>


text:
layout: docs
title: Buttons
group: components
redirect_from: "/components/"
---

Use Bootstrap's custom button styles for actions in forms, dialogs, and more. Includes support for a handful of contextual variations, sizes, states, and more.

## Contents

* Will be replaced with the ToC, excluding the "Contents" header
{:toc}

## Examples

Bootstrap includes six predefined button styles, each serving its own semantic purpose.

{% example html %}

<button type="button" class="btn btn-primary">Primary</button>

<button type="button" class="btn btn-secondary">Secondary</button>

<button type="button" class="btn btn-success">Success</button>

<button type="button" class="btn btn-info">Info</button>

<button type="button" class="btn btn-warning">Warning</button>

<button type="button" class="btn btn-danger">Danger</button>

<button type="button" class="btn btn-link">Link</button>
{% endexample %}

{% callout warning %}
#### Conveying meaning to assistive technologies

Using color to add meaning to a button only provides a visual indication, which will not be conveyed to users of assistive technologies – such as screen readers. Ensure that information denoted by the color is either obvious from the content itself (the visible text of the button), or is included through alternative means, such as additional text hidden with the `.sr-only` class.
{% endcallout %}

## Button tags

The `.btn` classes are designed to be used with the `<button>` element. However, you can also use these classes on `<a>` or `<input>` elements (though some browsers may apply a slightly different rendering).

When using button classes on `<a>` elements that are used to trigger in-page functionality (like collapsing content), rather than linking to new pages or sections within the current page, these links should be given a `role="button"` to appropriately convey their purpose to assistive technologies such as screen readers.

{% example html %}
Link
<button class="btn btn-primary" type="submit">Button</button>
<input class="btn btn-primary" type="button" value="Input">
<input class="btn btn-primary" type="submit" value="Submit">
{% endexample %}

## Outline buttons

In need of a button, but not the hefty background colors they bring? Replace the default modifier classes with the `.btn-*-outline` ones to remove all background images and colors on any button.

{% example html %}
<button type="button" class="btn btn-primary-outline">Primary</button>
<button type="button" class="btn btn-secondary-outline">Secondary</button>
<button type="button" class="btn btn-success-outline">Success</button>
<button type="button" class="btn btn-info-outline">Info</button>
<button type="button" class="btn btn-warning-outline">Warning</button>
<button type="button" class="btn btn-danger-outline">Danger</button>
{% endexample %}

## Sizes

Fancy larger or smaller buttons? Add `.btn-lg` or `.btn-sm` for additional sizes.

{% example html %}
<button type="button" class="btn btn-primary btn-lg">Large button</button>
<button type="button" class="btn btn-secondary btn-lg">Large button</button>
{% endexample %}

{% example html %}
<button type="button" class="btn btn-primary btn-sm">Small button</button>
<button type="button" class="btn btn-secondary btn-sm">Small button</button>
{% endexample %}

Create block level buttons—those that span the full width of a parent—by adding `.btn-block`.

{% example html %}
<button type="button" class="btn btn-primary btn-lg btn-block">Block level button</button>
<button type="button" class="btn btn-secondary btn-lg btn-block">Block level button</button>
{% endexample %}

## Active state

Buttons will appear pressed (with a darker background, darker border, and inset shadow) when active. **There's no need to add a class to `<button>`s as they use a pseudo-class**. However, you can still force the same active appearance with `.active` (and include the aria-pressed="true" attribute) should you need to replicate the state programmatically.

{% example html %}
Primary link
Link
{% endexample %}

## Disabled state

Make buttons look inactive by adding the `disabled` boolean attribute to any `<button>` element.

{% callout info %}
**Heads up!** IE9 and below render disabled buttons with gray, shadowed text that we can't override.
{% endcallout %}

{% example html %}
<button type="button" class="btn btn-lg btn-primary" disabled>Primary button</button>
<button type="button" class="btn btn-secondary btn-lg" disabled>Button</button>
{% endexample %}

As `<a>` elements don't support the `disabled` attribute, you must add the `.disabled` class to fake it.

{% example html %}
Primary link
Link
{% endexample %}

{% callout warning %}
#### Link functionality caveat

This class uses `pointer-events: none` to try to disable the link functionality of `<a>`s, but that CSS property is not yet standardized and isn't fully supported in Opera 18 and below, or in Internet Explorer 11\. In addition, even in browsers that do support `pointer-events: none`, keyboard navigation remains unaffected, meaning that sighted keyboard users and users of assistive technologies will still be able to activate these links. So to be safe, use custom JavaScript to disable such links.
{% endcallout %}

## Button plugin

Do more with buttons. Control button states or create groups of buttons for more components like toolbars.

### Toggle states

Add `data-toggle="button"` to toggle a button's `active` state. If you're pre-toggling a button, you must manually add the `.active` class **and** `aria-pressed="true"` to the `<button>`.

{% example html %}
<button type="button" class="btn btn-primary" data-toggle="button" aria-pressed="false" autocomplete="off">
  Single toggle
</button>
{% endexample %}

### Checkbox and radio buttons

Bootstrap's `.button` styles can be applied to other elements, such as `<label>`s, to provide checkbox or radio style button toggling. Add `data-toggle="buttons"` to a `.btn-group` containing those modified buttons to enable toggling in their respective styles.

The checked state for these buttons is **only updated via `click` event** on the button. If you use another method to update the input—e.g., with `<input type="reset">` or by manually applying the input's `checked` property—you'll need to toggle `.active` on the `<label>` manually.

Note that pre-checked buttons require you to manually add the `.active` class to the input's `<label>`.

{% example html %}

    <input type="checkbox" checked autocomplete="off"> Checkbox 1 (pre-checked)

    <input type="checkbox" autocomplete="off"> Checkbox 2

    <input type="checkbox" autocomplete="off"> Checkbox 3

{% endexample %}

{% example html %}

    <input type="radio" name="options" id="option1" autocomplete="off" checked> Radio 1 (preselected)

    <input type="radio" name="options" id="option2" autocomplete="off"> Radio 2

    <input type="radio" name="options" id="option3" autocomplete="off"> Radio 3

{% endexample %}

### Methods

| Method | Description |
| --- | --- |
| `$().button('toggle')` |Toggles push state. Gives the button the appearance that it has been activated.  |


text:
from flask import render_template, jsonify, request
from . import main

'''
 向Web服务客户端发送 JSON 格式响应,除此之外都发送 HTML 格式响应
'''
@main.app_errorhandler(403)
def forbidden(e):
    if request.accept_mimetypes.accept_json and \
            not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'forbidden'})
        response.status_code = 403
        return response
    return render_template('403.html'), 403

@main.app_errorhandler(404)
def page_not_found(e):
    if request.accept_mimetypes.accept_json and \
            not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'not found'})
        response.status_code = 404
        return response
    return render_template('404.html'), 404

@main.app_errorhandler(500)
def internal_server_error(e):
    if request.accept_mimetypes.accept_json and \
            not request.accept_mimetypes.accept_html:
        response = jsonify({'error': 'internal server error'})
        response.status_code = 500
        return response
    return render_template('500.html'), 500


text:
package fronted

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"fmt"
	"math/rand"
	"net"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"

	"github.com/getlantern/eventual"
	"github.com/getlantern/golog"
	"github.com/getlantern/idletiming"
	"github.com/getlantern/tlsdialer"
)

const (
	NumberToVetInitially = 20
)

var (
	log       = golog.LoggerFor("fronted")
	_instance = eventual.NewValue()
)

type direct struct {
	tlsConfigsMutex sync.Mutex
	tlsConfigs      map[string]*tls.Config
	certPool        *x509.CertPool
	candidates      chan *Masquerade
	masquerades     chan *Masquerade
}

func Configure(pool *x509.CertPool, masquerades map[string][]*Masquerade) {
	log.Debug("Configuring fronted")
	if masquerades == nil || len(masquerades) == 0 {
		log.Errorf("No masquerades!!")
		return
	}

	// Make a copy of the masquerades to avoid data races.
	size := 0
	for _, v := range masquerades {
		size += len(v)
	}

	if size == 0 {
		log.Errorf("No masquerades!!")
		return
	}

	instance := &direct{
		tlsConfigs:  make(map[string]*tls.Config),
		certPool:    pool,
		candidates:  make(chan *Masquerade, size),
		masquerades: make(chan *Masquerade, size),
	}

	_instance.Set(instance)
	instance.loadCandidates(masquerades)
	instance.vetInitial()
}

func (d *direct) loadCandidates(initial map[string][]*Masquerade) {
	log.Debug("Loading candidates")
	for key, arr := range initial {
		size := len(arr)
		log.Tracef("Adding %d candidates for %v", size, key)
		for i := 0; i < size; i++ {
			// choose index uniformly in [i, n-1]
			r := i + rand.Intn(size-i)
			log.Trace("Adding candidate")
			d.candidates <- arr[r]
		}
	}
}

func (d *direct) vetInitial() {
	log.Debugf("Vetting %d initial candidates in parallel", NumberToVetInitially)
	for i := 0; i < NumberToVetInitially; i++ {
		go d.vetOne()
	}
}

func (d *direct) vetOne() {
	// We're just testing the ability to connect here, destination site doesn't
	// really matter
	for {
		log.Trace("Vetting one")
		conn, masqueradesRemain, err := d.dialWith(d.candidates, "tcp", "www.google.com")
		if err == nil {
			conn.Close()
			log.Trace("Finished vetting one")
			return
		}
		if !masqueradesRemain {
			log.Trace("Nothing left to vet")
			return
		}
	}
}

func NewDirectHttpClient(timeout time.Duration) *http.Client {
	instance, ok := _instance.Get(timeout)
	if !ok {
		panic(fmt.Errorf("No DirectHttpClient available within %v", timeout))
	}
	return instance.(*direct).NewDirectHttpClient()
}

// NewDirectHttpClient creates a new http.Client that does direct domain fronting.
func (d *direct) NewDirectHttpClient() *http.Client {
	trans := &directTransport{}
	trans.Dial = d.Dial
	trans.TLSHandshakeTimeout = 40 * time.Second
	trans.DisableKeepAlives = true
	return &http.Client{
		Transport: trans,
	}
}

// Do continually retries a given request until it succeeds because some fronting providers
// will return a 403 for some domains.
func (d *direct) Do(req *http.Request) (*http.Response, error) {
	for i := 0; i < 6; i++ {
		client := d.NewDirectHttpClient()
		if resp, err := client.Do(req); err != nil {
			log.Errorf("Could not complete request %v", err)
		} else if resp.StatusCode > 199 && resp.StatusCode < 400 {
			return resp, err
		} else {
			_ = resp.Body.Close()
		}
	}
	return nil, errors.New("Could not complete request even with retries")
}

// Dial dials the given address using a masquerade. If the available masquerade
// fails, it retries with others until it either succeeds or exhausts the
// available masquerades.
func (d *direct) Dial(network, addr string) (net.Conn, error) {
	conn, _, err := d.dialWith(d.masquerades, network, addr)
	return conn, err
}

func (d *direct) dialWith(in chan *Masquerade, network, addr string) (net.Conn, bool, error) {
	retryLater := make([]*Masquerade, 0)
	defer func() {
		for _, m := range retryLater {
			in <- m
		}
	}()

	for {
		var m *Masquerade
		select {
		case m = <-in:
			log.Trace("Got vetted masquerade")
		default:
			log.Trace("No vetted masquerade found, falling back to unvetted candidate")
			select {
			case m = <-d.candidates:
				log.Trace("Got unvetted masquerade")
			default:
				return nil, false, errors.New("Could not dial any masquerade?")
			}
		}

		log.Debugf("Dialing to %v", m)

		// We do the full TLS connection here because in practice the domains at a given IP
		// address can change frequently on CDNs, so the certificate may not match what
		// we expect.
		if conn, err := d.dialServerWith(m); err != nil {
			log.Debugf("Could not dial to %v, %v", m.IpAddress, err)
			// Don't re-add this candidate if it's any certificate error, as that
			// will just keep failing and will waste connections. We can't access the underlying
			// error at this point so just look for "certificate" and "handshake".
			if strings.Contains(err.Error(), "certificate") || strings.Contains(err.Error(), "handshake") {
				log.Debugf("Not re-adding candidate that failed on error '%v'", err.Error())
			} else {
				log.Debugf("Unexpected error dialing, keeping masquerade: %v", err)
				retryLater = append(retryLater, m)
			}
		} else {
			log.Debugf("Got successful connection to: %v", m)
			if err := d.headCheck(m); err != nil {
				log.Debugf("Could not perform successful head request: %v", err)
			} else {
				// Requeue the working connection to masquerades
				d.masquerades <- m
				idleTimeout := 70 * time.Second

				log.Debug("Wrapping connecting in idletiming connection")
				conn = idletiming.Conn(conn, idleTimeout, func() {
					log.Debugf("Connection to %s via %s idle for %v, closing", addr, conn.RemoteAddr(), idleTimeout)
					if err := conn.Close(); err != nil {
						log.Debugf("Unable to close connection: %v", err)
					}
				})
				log.Debug("Returning connection")
				return conn, true, nil
			}
		}
	}
}

func (d *direct) dialServerWith(masquerade *Masquerade) (net.Conn, error) {
	tlsConfig := d.tlsConfig(masquerade)
	dialTimeout := 10 * time.Second
	sendServerNameExtension := false

	cwt, err := tlsdialer.DialForTimings(
		&net.Dialer{
			Timeout: dialTimeout,
		},
		"tcp",
		masquerade.IpAddress+":443",
		sendServerNameExtension, // SNI or no
		tlsConfig)

	if err != nil && masquerade != nil {
		err = fmt.Errorf("Unable to dial masquerade %s: %s", masquerade.Domain, err)
	}
	return cwt.Conn, err
}

// tlsConfig builds a tls.Config for dialing the upstream host. Constructed
// tls.Configs are cached on a per-masquerade basis to enable client session
// caching and reduce the amount of PEM certificate parsing.
func (d *direct) tlsConfig(m *Masquerade) *tls.Config {
	d.tlsConfigsMutex.Lock()
	defer d.tlsConfigsMutex.Unlock()

	tlsConfig := d.tlsConfigs[m.Domain]
	if tlsConfig == nil {
		tlsConfig = &tls.Config{
			ClientSessionCache: tls.NewLRUClientSessionCache(1000),
			InsecureSkipVerify: false,
			ServerName:         m.Domain,
			RootCAs:            d.certPool,
		}
		d.tlsConfigs[m.Domain] = tlsConfig
	}

	return tlsConfig
}

// headCheck checks to make sure we can actually make a DDF head request through a
// given masquerade. We don't reuse the underlying connection here because that confuses
// the http.Client's internal transport.
func (d *direct) headCheck(m *Masquerade) error {
	trans := &http.Transport{
		Dial: func(network, address string) (net.Conn, error) {
			return d.dialServerWith(m)
		},
		TLSHandshakeTimeout: 40 * time.Second,
		DisableKeepAlives:   true,
	}

	client := &http.Client{
		Transport: trans,
	}
	url := "http://dlymairwlc89h.cloudfront.net/index.html"
	if resp, err := client.Head(url); err != nil {
		return err
	} else {
		defer resp.Body.Close()
		if 200 != resp.StatusCode {
			return fmt.Errorf("Unexpected response status: %v, %v", resp.StatusCode, resp.Status)
		}
	}
	log.Debugf("Successfully passed HEAD request through: %v", m)
	return nil
}

// directTransport is a wrapper struct enabling us to modify the protocol of outgoing
// requests to make them all HTTP instead of potentially HTTPS, which breaks our particular
// implemenation of direct domain fronting.
type directTransport struct {
	http.Transport
}

func (ddf *directTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
	// The connection is already encrypted by domain fronting.  We need to rewrite URLs starting
	// with "https://" to "http://", lest we get an error for doubling up on TLS.

	// The RoundTrip interface requires that we not modify the memory in the request, so we just
	// create a copy.
	norm := new(http.Request)
	*norm = *req // includes shallow copies of maps, but okay
	norm.URL = new(url.URL)
	*norm.URL = *req.URL
	norm.URL.Scheme = "http"
	return ddf.Transport.RoundTrip(norm)
}


text:
//********************************************************************************************************************************
// Filename:    IntegralSettings.cs
// Owner:       Richard Dunkley
// Description: Partial class containing the Integral Type Settings GUI.
//********************************************************************************************************************************
// Copyright © Richard Dunkley 2016
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
// License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable
// law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and
// limitations under the License.
//********************************************************************************************************************************
using System;
using System.Windows.Forms;
using XMLToDataClass.Data.Types;
using System.Globalization;

namespace XMLToDataClass.View
{
	public partial class IntegralSettings<T> : UserControl where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
	{
		private IIntegralType<T> mType;

		public event EventHandler SettingsChanged;

		public IntegralSettings(IIntegralType<T> type)
		{
			if (typeof(T) != typeof(byte) && typeof(T) != typeof(sbyte) && typeof(T) != typeof(ushort) && typeof(T) != typeof(short) &&
				typeof(T) != typeof(uint) && typeof(T) != typeof(int) && typeof(T) != typeof(ulong) && typeof(T) != typeof(long))
			{
				throw new ArgumentException("The generic type must be created with the following value types as T: byte, sbyte, ushort, short, uint, int, ulong, and long.");
			}

			if (type == null)
				throw new ArgumentNullException("type");
			mType = type;

			InitializeComponent();

			minimumTextBox.Text = type.MinimumValue.ToString("N0", NumberFormatInfo.CurrentInfo);
			maximumTextBox.Text = type.MaximumValue.ToString("N0", NumberFormatInfo.CurrentInfo);
			hex1CheckBox.Checked = type.AllowHexType1Values;
			hex2CheckBox.Checked = type.AllowHexType2Values;
			binaryCheckBox.Checked = type.AllowBinaryValues;
			integerCheckBox.Checked = type.AllowIntegerValues;
		}

		private void minimumTextBox_TextChanged(object sender, EventArgs e)
		{
			if(!mType.TryParseForMinMax(minimumTextBox.Text))
			{
				// Revert to previous value.
				minimumTextBox.Text = mType.MinimumValue.ToString("N0", NumberFormatInfo.CurrentInfo);
				return;
			}
			else
			{
				// Parse value and assign to minimum value.
				mType.MinimumValue = mType.ParseForMinMax(minimumTextBox.Text);
			}

			SettingsChanged?.Invoke(this, null);
		}

		private void maximumTextBox_TextChanged(object sender, EventArgs e)
		{
			if (!mType.TryParseForMinMax(maximumTextBox.Text))
			{
				// Revert to previous value.
				maximumTextBox.Text = mType.MaximumValue.ToString("N0", NumberFormatInfo.CurrentInfo);
				return;
			}
			else
			{
				// Parse value and assign to minimum value.
				mType.MaximumValue = mType.ParseForMinMax(maximumTextBox.Text);
			}

			SettingsChanged?.Invoke(this, null);
		}

		private void hex1CheckBox_CheckedChanged(object sender, EventArgs e)
		{
			mType.AllowHexType1Values = hex1CheckBox.Checked;
			SettingsChanged?.Invoke(this, null);
		}

		private void hex2CheckBox_CheckedChanged(object sender, EventArgs e)
		{
			mType.AllowHexType2Values = hex2CheckBox.Checked;
			SettingsChanged?.Invoke(this, null);
		}

		private void binaryCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			mType.AllowBinaryValues = binaryCheckBox.Checked;
			SettingsChanged?.Invoke(this, null);
		}

		private void integerCheckBox_CheckedChanged(object sender, EventArgs e)
		{
			mType.AllowIntegerValues = integerCheckBox.Checked;
			SettingsChanged?.Invoke(this, null);
		}
	}
}