text:
@interface KMMCertificationTests : XCTestCase

@end

@implementation KMMCertificationTests

- (void)testCertificationIsCorrectlyCreated {
    NSString *code = @"PG";
    NSString *meaning = @"Parental guidance advised. There is no age restriction but some material may not be suitable for all children.";
    NSUInteger order = 2;

    KMMCertification *certification = [[KMMCertification alloc] initWithCode:code meanging:meaning order:order];

    XCTAssertNotNil(certification);
    XCTAssertTrue([certification.code isEqualToString:code], @"Code should be equal");
    XCTAssertTrue([certification.meaning isEqualToString:meaning], @"Meaning should be equal");
    XCTAssertTrue(certification.order == order, @"Order should be equal");
}

-(void)testCertificationCannotBeCreatedWithoutCode {
    NSString *meaning = @"Meaning";
    NSUInteger order = 2;
    XCTAssertThrows([[KMMCertification alloc] initWithCode:nil meanging:meaning order:order]);
}

-(void)testCertificationCannotBeCreatedWithoutMeaning {
    NSString *code = @"code";
    NSUInteger order = 2;
    XCTAssertThrows([[KMMCertification alloc] initWithCode:code meanging:nil order:order]);
}

- (void)testCertificationCreationPerformance {
    NSString *code = @"PG";
    NSString *meaning = @"Parental guidance advised. There is no age restriction but some material may not be suitable for all children.";
    NSUInteger order = 2;

    [self measureBlock:^{
            KMMCertification *certification = [[KMMCertification alloc] initWithCode:code meanging:meaning order:order];
            XCTAssertNotNil(certification);
    }];
}

-(void)testCertificationCopy {
    NSString *code = @"PG";
    NSString *meaning = @"Parental guidance advised. There is no age restriction but some material may not be suitable for all children.";
    NSUInteger order = 2;

    KMMCertification *certification = [[KMMCertification alloc] initWithCode:code meanging:meaning order:order];
    KMMCertification *otherCertification = [certification copy];

    XCTAssertEqual(certification, otherCertification);
}

@end


text:
import { crouton_thrift } from '../platform_abstraction_layer'; // eslint-disable-line camelcase
import _each from '../_each'; // eslint-disable-line camelcase
import * as coerce from './coerce';

let proto = require('./generated_proto/collector_pb');

export default class ReportImp {
    constructor(runtime, oldestMicros, youngestMicros, spanRecords, internalLogs, counters, timestampOffsetMicros) {
        this._runtime = runtime;
        this._oldestMicros = oldestMicros;
        this._youngestMicros = youngestMicros;
        this._spanRecords = spanRecords;
        this._internalLogs = internalLogs;
        this._counters = counters;
        this._timestampOffsetMicros = timestampOffsetMicros;
    }

    getSpanRecords() {
        return this._spanRecords;
    }

    getInternalLogs() {
        return this._internalLogs;
    }

    getCounters() {
        return this._counters;
    }

    toThrift() {
        _each(this._spanRecords, (span) => {
            span.runtime_guid = this._runtimeGUID;
        });

        let thriftCounters = [];
        _each(this._counters, (value, key) => {
            if (value === 0) {
                return;
            }
            thriftCounters.push(new crouton_thrift.MetricsSample({
                name         : coerce.toString(key),
                double_value : coerce.toNumber(value),
            }));
        });

        let thriftSpanRecords = [];
        _each(this._spanRecords, (spanRecord) => {
            thriftSpanRecords.push(spanRecord._toThrift());
        });

        return new crouton_thrift.ReportRequest({
            runtime          : this._runtime.toThrift(),
            oldest_micros    : this._oldestMicros,
            youngest_micros  : this._youngestMicros,
            span_records     : thriftSpanRecords,
            internal_logs    : this._internalLogs,
            internal_metrics : new crouton_thrift.Metrics({
                counts : thriftCounters,
            }),
            timestamp_offset_micros : this._timestampOffsetMicros,
        });
    }

    toProto(auth) {
        let spansList = [];
        _each(this._spanRecords, (spanRecord) => {
            spansList.push(spanRecord._toProto());
        });

        let countsList = [];
        _each(this._counters, (count) => {
            let metricSample = new proto.MetricsSample();
            metricSample.setName(count.name);
            metricSample.setIntValue(count.int64_value);
            metricSample.setDoubleValue(count.double_value);
            countsList.push(metricSample);
        });

        let internalMetrics = new proto.InternalMetrics();
        internalMetrics.setCountsList(countsList);

        let reportProto = new proto.ReportRequest();
        reportProto.setAuth(auth.toProto());
        reportProto.setReporter(this._runtime.toProto());
        reportProto.setSpansList(spansList);
        reportProto.setTimestampOffsetMicros(this._timestampOffsetMicros.toString(10));
        reportProto.setInternalMetrics(internalMetrics);
        return reportProto;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/weather-icons/1.3.2/css/weather-icons.css">
  <title>ngOpenWeatherMap</title>

ngOpenWeatherMap Demo App

  City name: <input type="text" placeholder="New York,US" ng-model="city"/>
  <button ng-click="searchCity(city)">Search</button>
  <button ng-click="geoLocate()" ng-show="geoLocate">GeoLocation</button>

{{ message }}

      {{ current.name }},{{ current.sys.country }}
      [ID:{{ current.id }}]
      (N{{ current.coord.lat }}/W{{ current.coord.lon }})

    OpenWeatherMap API response status: {{ current.cod }}

Weather

Temperature: {{ current.main.temp }}°C (Max: {{ current.main.temp_max }}°C / Min: {{ current.main.temp_min }}°C)

Pressure: {{ current.main.pressure }}hPa

Humidity: {{ current.main.humidity }}%

Visibility: {{ current.visibility }}

Wind speed: {{ current.wind.speed }}m/s

Wind direction: {{ current.wind.deg }}°

Cloudiness: {{ current.clouds.all }} %

Rain last 1h: {{ current.rain['1h'] }} %

Snow last 1h: {{ current.snow['1h'] }} %

Sunrise: {{ current.sys.sunrise*1000 |date:'medium' }} UTC

Sunset: {{ current.sys.sunset*1000 |date:'medium' }} UTC

Current Conditions

        <owm-icon id="{{ condition.id }}"></owm-icon>
        {{ condition.main }} ({{ condition.description }})


text:
package ee.bitweb.banklink.sdk.protocol;

import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Created by tobre on 21/03/2017.
 */
public class VendorTest {

    private Vendor vendor;

    @Before
    public void setUp() throws Exception {
        vendor = new Vendor("senderid", "sender name", "12356");
    }

    @Test
    public void testGetters() throws Exception {
        assertEquals("senderid", vendor.getSenderId());
        assertEquals("sender name", vendor.getName());
        assertEquals("12356", vendor.getAccountNumber());
    }
}


text:
import React from 'react';
import InputWithButton from '../basic/inputWithButton';

export default function(props) {
	return (
		<InputWithButton
			buttonName= "Send"
			onClick={ props.sendMessage }
			/>
	);
};


text:
namespace biz.dfch.CS.Abiquo.Client.v1.Model
{
    public class ExternalIp : IpBaseDto
    {
        public bool Available { get; set; }

        public bool Quarantine { get; set; }
    }
}


text:
<?php
namespace Acme\RestaurantsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Acme\RestaurantsBundle\Entity\Places;
class Pagecontroller extends Controller
{

 public function indexAction(Request $request)
 {
      ini_set('max_execution_time', 300);
      $places_raiting= $request->query->get('raiting');
      $em = $this->getDoctrine();
      $pagetoken1="";
      $type='gym';
      //$this->getPlaces($pagetoken1,$em,$type);
      if (isset($places_raiting)){
      $query=$em->getManager()->createQuery(
                'SELECT p from AcmeRestaurantsBundle:Places p
                 WHERE p.placesRating = :places_raiting '
                 )->setParameter(':places_raiting',$places_raiting);
                 $places=$query->getResult();
      }
      else
      {
       $places = $em->getRepository('AcmeRestaurantsBundle:Places')
                    ->findAll();
      }
      $images=$this->selectimages();
      return $this->render('AcmeRestaurantsBundle:Default:index.html.twig', array(
                                     'images'      => $images,
                                     'places'      => $places,
                                        ));
 }

 private function SelectPlaceWithId($places_id,$em)
 {
     $query=$em->getManager()
               ->createQuery(
                 'SELECT p from AcmeRestaurantsBundle:Places p
                  WHERE p.placesId = :id ')
               ->setParameter(':id',$places_id);
     $id=$query->getResult();
     return $id;
 }

 private function InserNewPlace($places_id,$places_name,$places_address,$places_rating,
              $places_lat,$places_lng,$places_open_now,$places_reference,$places_types,$places_icon,$place_photo)
 {
    $place=new Places();
    $place->setPlacesId($places_id);
    $place->setPlacesName($places_name);
    $place->setPlacesAddress($places_address);
    $place->setPlacesRating($places_rating);
    $place->setPlacesLat($places_lat);
    $place->setPlacesLng($places_lng);
    $place->setPlacesOpenNow($places_open_now);
    $place->setPlacesReference($places_reference);
    $place->setPlacesTypes($places_types);
    $place->setPlacesIcon($places_icon);
    $place->setPlacePhoto($place_photo);
    $em = $this->getDoctrine()->getManager();
    $em->persist($place);
    $em->flush();
 }

 function getPlaces($pagetoken,$em,$type)
 {
    sleep(2);
    $pagetoken=rawurlencode($pagetoken);
    $urltest="https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=46.778125,23.597732&types=".$type."&sensor=true&radius=5000&key=AIzaSyDebLnPBz09xodVnFIzNq2WRTVxuOsCJgc&pagetoken=$pagetoken";
    $url=str_replace("\"","",$urltest);
    $tuCurl = curl_init();
    curl_setopt($tuCurl, CURLOPT_URL, $url);
    curl_setopt($tuCurl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
    $tuData = curl_exec($tuCurl);
    curl_close($tuCurl);
    $tuData_a=json_decode($tuData);
    $i=0;
    if (isset($tuData_a->status) && $tuData_a->status == "OK")
    {
      while ($i<20)
      {

        $places_name='';
        $places_address='';
        $places_id='';
        $places_rating=0;
        $places_lat=0;
        $places_lng=0;
        $places_icon=0;
        $places_open_now=0;
        $places_reference=0;
        $places_types='';
        if (isset($tuData_a->results[$i]->name)){
        $places_name = $tuData_a->results[$i]->name;
        }
        if (isset($tuData_a->results[$i]->formatted_address)){
        $places_address = $tuData_a->results[$i]->formatted_address;
        }
        if (isset($tuData_a->results[$i]->id)){
        $places_id=$tuData_a->results[$i]->id;
        }
        if (isset($tuData_a->results[$i]->rating)){
        $places_rating=$tuData_a->results[$i]->rating;
        }
        if (isset($tuData_a->results[$i]->geometry->location->lat)){
        $places_lat=$tuData_a->results[$i]->geometry->location->lat;
        }
        if (isset($tuData_a->results[$i]->geometry->location->lng)){
        $places_lng=$tuData_a->results[$i]->geometry->location->lng;
        }
        if (isset($tuData_a->results[$i]->icon)){
        $places_icon=$tuData_a->results[$i]->icon;
        }
        if (isset($tuData_a->results[$i]->opening_hours->open_now)){
        $places_open_now=$tuData_a->results[$i]->opening_hours->open_now;
        }
        if (isset($tuData_a->results[$i]->reference)){
        $places_reference=$tuData_a->results[$i]->reference;

        }
         if (isset($tuData_a->results[$i]->types[0])){
         $places_types=$tuData_a->results[$i]->types[0];
         }
         $places_types.=" ";
         if (isset($tuData_a->results[$i]->types[2]))
         {
         $places_types.=$tuData_a->results[$i]->types[1];
         }
         $places_types.=" ";
         if (isset($tuData_a->results[$i]->types[2]))
         {
         $places_types.=$tuData_a->results[$i]->types[2];
         }
         $photo_reference="";
         if (isset($tuData_a->results[$i]->photos[0])){
         $photo_reference = $tuData_a->results[$i]->photos[0]->photo_reference;

         }
         $place_photo=$this->RedirectUrl($photo_reference);
         $id=$this->SelectPlaceWithId($places_id,$em);

         if (empty($id))
         {

         $this->InserNewPlace($places_id,$places_name,$places_address,$places_rating,
              $places_lat,$places_lng,$places_open_now,$places_reference,$places_types,$places_icon,$place_photo);
         }
        $i++;
        sleep(2);
      }
    }
    else echo $tuData_a->status;
      if (isset($tuData_a->next_page_token)){
        $pagetoken=$tuData_a->next_page_token;
        $this->getPlaces($pagetoken,$em,$type);
      }
      return $pagetoken;
 }

private function selectimages()
{
  $em=$this->getDoctrine()->getManager();
  $images = $em->createQueryBuilder()
               ->select('i')
               ->from('AcmeRestaurantsBundle:Images',  'i')
               ->getQuery()
               ->getResult();
   return $images;
 }
 public function RedirectUrl($photo_reference)
 {
    $urlpicture="https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=$photo_reference&sensor=true&key=AIzaSyDa5Q4aq-rfNjpv-VrUoEVqGZuJW54vz4M";
    $tuCurl = curl_init($urlpicture);
    curl_setopt($tuCurl, CURLOPT_URL, $urlpicture);
    curl_setopt($tuCurl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($tuCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_exec($tuCurl);
    $last_url1 = curl_getinfo($tuCurl);
    $last_url = $last_url1['redirect_url'];
    return $last_url;
 }

}


text:
sudo add-apt-repository "deb http://archive.ubuntu.com/ubuntu $(lsb_release -sc) universe"

echo 'deb http://download.webmin.com/download/repository sarge contrib' | sudo tee /etc/apt/sources.list.d/webmain.list

wget http://www.webmin.com/jcameron-key.asc && sudo apt-key add jcameron-key.asc

sudo apt update

sudo apt install webmin -y


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>phpCAS: Configuration</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Modules

Classes

Files

Examples

Modules |
Functions |
Variables

Configuration

[Implementation]

Modules

 	Internal behaviour of phpCAS

 	HTML output

 	Internationalization

Functions

 	CAS_Client::getServerVersion ()

 	CAS_Client::getServerHostname ()

 	CAS_Client::getServerPort ()

 	CAS_Client::getServerURI ()

 	CAS_Client::getServerBaseURL ()

 	CAS_Client::getServerLoginURL ($gateway=false, $renew=false)

 	CAS_Client::setServerLoginURL ($url)

 	CAS_Client::setServerServiceValidateURL ($url)

 	CAS_Client::setServerProxyValidateURL ($url)

 	CAS_Client::setServerSamlValidateURL ($url)

 	CAS_Client::getServerServiceValidateURL ()

 	CAS_Client::getServerSamlValidateURL ()

 	CAS_Client::getServerProxyValidateURL ()

 	CAS_Client::getServerProxyURL ()

 	CAS_Client::getServerLogoutURL ()

 	CAS_Client::setServerLogoutURL ($url)

 	CAS_Client::setExtraCurlOption ($key, $value)

 	CAS_Client::__construct ($server_version, $proxy, $server_hostname, $server_port, $server_uri, $start_session=true)

 	CAS_Client::setStartSession ($session)

 	CAS_Client::getStartSession ($session)

Variables

 	CAS_Client::$_server

 	CAS_Client::$_curl_options = array()

 	CAS_Client::$_start_session

Function Documentation

          CAS_Client::__construct
          (
          $
           server_version,

          $
           proxy,

          $
           server_hostname,

          $
           server_port,

          $
           server_uri,

          $
           start_session = true

          )
          		 [inherited]

CAS_Client constructor.

Parameters:

	$server_version 	the version of the CAS server

	$proxy 	TRUE if the CAS client is a CAS proxy, FALSE otherwise

	$server_hostname 	the hostname of the CAS server

	$server_port 	the port the CAS server is running on

	$server_uri 	the URI the CAS server is responding on

	$start_session 	Have phpCAS start PHP sessions (default true)

Returns:

a newly created CAS_Client object

Definition at line 689 of file Client.php.

References phpCAS::error(), CAS_Client::getServerVersion(), CAS_Client::isCallbackMode(), CAS_Client::isHttps(), CAS_Client::isLogoutRequest(), CAS_Client::isProxy(), CAS_Client::setCallbackMode(), phpCAS::trace(), phpCAS::traceBegin(), and phpCAS::traceEnd().

          CAS_Client::getServerBaseURL
          (

           )
           [private, inherited]

This method is used to retrieve the base URL of the CAS server.

Returns:

a URL.

Definition at line 328 of file Client.php.

Referenced by CAS_Client::getServerLoginURL(), CAS_Client::getServerLogoutURL(), CAS_Client::getServerProxyURL(), CAS_Client::getServerProxyValidateURL(), CAS_Client::getServerSamlValidateURL(), CAS_Client::getServerServiceValidateURL(), and CAS_Client::HTMLFilterOutput().

          CAS_Client::getServerHostname
          (

           )
           [private, inherited]

This method is used to retrieve the hostname of the CAS server.

Returns:

the hostname of the CAS server.

Definition at line 307 of file Client.php.

Referenced by CAS_Client::handleLogoutRequests().

          CAS_Client::getServerLoginURL
          (
          $
           gateway = false,

          $
           renew = false

          )
          		 [inherited]

This method is used to retrieve the login URL of the CAS server.

Parameters:

	$gateway 	true to check authentication, false to force it

	$renew 	true to force the authentication with the CAS server NOTE : It is recommended that CAS implementations ignore the "gateway" parameter if "renew" is set

Returns:

a URL.

Definition at line 350 of file Client.php.

References CAS_Client::buildQueryUrl(), CAS_Client::getServerBaseURL(), CAS_Client::getURL(), phpCAS::traceBegin(), and phpCAS::traceEnd().

Referenced by CAS_Client::redirectToCas().

          CAS_Client::getServerLogoutURL
          (

           )
           [inherited]

This method is used to retrieve the logout URL of the CAS server.

Returns:

a URL.

Definition at line 505 of file Client.php.

References CAS_Client::getServerBaseURL().

Referenced by CAS_Client::logout().

          CAS_Client::getServerPort
          (

           )
           [private, inherited]

This method is used to retrieve the port of the CAS server.

Returns:

the port of the CAS server.

Definition at line 314 of file Client.php.

          CAS_Client::getServerProxyURL
          (

           )
           [inherited]

This method is used to retrieve the proxy URL of the CAS server.

Returns:

a URL.

Definition at line 485 of file Client.php.

References CAS_Client::getServerBaseURL(), and CAS_Client::getServerVersion().

          CAS_Client::getServerProxyValidateURL
          (

           )
           [inherited]

This method is used to retrieve the proxy validating URL of the CAS server.

Returns:

a URL.

Definition at line 461 of file Client.php.

References CAS_Client::buildQueryUrl(), CAS_Client::getServerBaseURL(), CAS_Client::getServerVersion(), CAS_Client::getURL(), phpCAS::traceBegin(), and phpCAS::traceEnd().

          CAS_Client::getServerSamlValidateURL
          (

           )
           [inherited]

This method is used to retrieve the SAML validating URL of the CAS server.

Returns:

a URL.

Definition at line 440 of file Client.php.

References CAS_Client::buildQueryUrl(), CAS_Client::getServerBaseURL(), CAS_Client::getServerVersion(), CAS_Client::getURL(), phpCAS::traceBegin(), and phpCAS::traceEnd().

          CAS_Client::getServerServiceValidateURL
          (

           )
           [inherited]

This method is used to retrieve the service validating URL of the CAS server.

Returns:

a URL.

Definition at line 418 of file Client.php.

References CAS_Client::buildQueryUrl(), CAS_Client::getServerBaseURL(), CAS_Client::getServerVersion(), CAS_Client::getURL(), phpCAS::traceBegin(), and phpCAS::traceEnd().

Referenced by CAS_Client::validateST().

          CAS_Client::getServerURI
          (

           )
           [private, inherited]

This method is used to retrieve the URI of the CAS server.

Returns:

a URI.

Definition at line 321 of file Client.php.

          CAS_Client::getServerVersion
          (

           )
           [private, inherited]

This method is used to retrieve the version of the CAS server.

Returns:

the version of the CAS server.

Definition at line 298 of file Client.php.

Referenced by CAS_Client::__construct(), CAS_Client::getServerProxyURL(), CAS_Client::getServerProxyValidateURL(), CAS_Client::getServerSamlValidateURL(), CAS_Client::getServerServiceValidateURL(), and CAS_Client::HTMLFilterOutput().

          CAS_Client::getStartSession
          (
          $
           session
           )
           [inherited]

Definition at line 844 of file Client.php.

          CAS_Client::setExtraCurlOption
          (
          $
           key,

          $
           value

          )
          		 [inherited]

This method is used to set additional user curl options.

Definition at line 532 of file Client.php.

          CAS_Client::setServerLoginURL
          (
          $
           url
           )
           [inherited]

This method sets the login URL of the CAS server.

Parameters:

	$url 	the login URL

Since:

0.4.21 by Wyman Chan

Definition at line 375 of file Client.php.

          CAS_Client::setServerLogoutURL
          (
          $
           url
           )
           [inherited]

This method sets the logout URL of the CAS server.

Parameters:

	$url 	the logout URL

Since:

0.4.21 by Wyman Chan

Definition at line 519 of file Client.php.

          CAS_Client::setServerProxyValidateURL
          (
          $
           url
           )
           [inherited]

This method sets the proxyValidate URL of the CAS server.

Parameters:

	$url 	the proxyValidate URL

Since:

1.1.0 by Joachim Fritschi

Definition at line 397 of file Client.php.

          CAS_Client::setServerSamlValidateURL
          (
          $
           url
           )
           [inherited]

This method sets the samlValidate URL of the CAS server.

Parameters:

	$url 	the samlValidate URL

Since:

1.1.0 by Joachim Fritschi

Definition at line 408 of file Client.php.

          CAS_Client::setServerServiceValidateURL
          (
          $
           url
           )
           [inherited]

This method sets the serviceValidate URL of the CAS server.

Parameters:

	$url 	the serviceValidate URL

Since:

1.1.0 by Joachim Fritschi

Definition at line 386 of file Client.php.

          CAS_Client::setStartSession
          (
          $
           session
           )
           [private, inherited]

Definition at line 839 of file Client.php.

Variable Documentation

          CAS_Client::$_curl_options = array() [private, inherited]

An array to store extra curl options.

Definition at line 527 of file Client.php.

          CAS_Client::$_server [private, inherited]

a record to store information about the CAS server.

$_server["version"]: the version of the CAS server

$_server["hostname"]: the hostname of the CAS server

$_server["port"]: the port the CAS server is running on

$_server["uri"]: the base URI the CAS server is responding on

$_server["base_url"]: the base URL of the CAS server

$_server["login_url"]: the login URL of the CAS server

$_server["service_validate_url"]: the service validating URL of the CAS server

$_server["proxy_url"]: the proxy URL of the CAS server

$_server["proxy_validate_url"]: the proxy validating URL of the CAS server

$_server["logout_url"]: the logout URL of the CAS server

$_server["version"], $_server["hostname"], $_server["port"] and $_server["uri"] are written by CAS_Client::CAS_Client(), read by CAS_Client::getServerVersion(), CAS_Client::getServerHostname(), CAS_Client::getServerPort() and CAS_Client::getServerURI().

The other fields are written and read by CAS_Client::getServerBaseURL(), CAS_Client::getServerLoginURL(), CAS_Client::getServerServiceValidateURL(), CAS_Client::getServerProxyValidateURL() and CAS_Client::getServerLogoutURL().

Definition at line 288 of file Client.php.

          CAS_Client::$_start_session [private, inherited]

A variable to whether phpcas will use its own session handling. Default = true

Definition at line 837 of file Client.php.

<address class="footer">Generated on Sun Jun 5 2011 19:05:26 for phpCAS by

 1.7.1 </address>


text:
junk
=====

Package junk is as advertised nothing useful.

See docs at http://hkjn.me/junk.


text:
require 'linguist/tokenizer'

require 'test/unit'

class TestTokenizer < Test::Unit::TestCase
  include Linguist

  def samples_path
    File.expand_path("../../samples", __FILE__)
  end

  def tokenize(data)
    data = File.read(File.join(samples_path, data.to_s)) if data.is_a?(Symbol)
    Tokenizer.tokenize(data)
  end

  def test_skip_string_literals
    assert_equal %w(print), tokenize('print ""')
    assert_equal %w(print), tokenize('print "Josh"')
    assert_equal %w(print), tokenize("print 'Josh'")
    assert_equal %w(print), tokenize('print "Hello \"Josh\""')
    assert_equal %w(print), tokenize("print 'Hello \\'Josh\\''")
    assert_equal %w(print), tokenize("print \"Hello\", \"Josh\"")
    assert_equal %w(print), tokenize("print 'Hello', 'Josh'")
    assert_equal %w(print), tokenize("print \"Hello\", \"\", \"Josh\"")
    assert_equal %w(print), tokenize("print 'Hello', '', 'Josh'")
  end

  def test_skip_number_literals
    assert_equal %w(+), tokenize('1 + 1')
    assert_equal %w(add \( \)), tokenize('add(123, 456)')
    assert_equal %w(|), tokenize('0x01 | 0x10')
    assert_equal %w(*), tokenize('500.42 * 1.0')
  end

  def test_skip_comments
    assert_equal %w(foo), tokenize("foo\n# Comment")
    assert_equal %w(foo bar), tokenize("foo\n# Comment\nbar")
    assert_equal %w(foo), tokenize("foo\n// Comment")
    assert_equal %w(foo), tokenize("foo /* Comment */")
    assert_equal %w(foo), tokenize("foo /* \nComment\n */")
    assert_equal %w(foo), tokenize("foo ")
    assert_equal %w(foo), tokenize("foo {- Comment -}")
    assert_equal %w(foo), tokenize("foo (* Comment *)")
    assert_equal %w(%), tokenize("2 % 10\n% Comment")
  end

  def test_sgml_tags
    assert_equal %w( ), tokenize("")
    assert_equal %w(
 id
), tokenize("

")
    assert_equal %w(
 id=
), tokenize("

")
    assert_equal %w(
 id class
), tokenize("

")
    assert_equal %w(
 id=
), tokenize("

")
    assert_equal %w(
 id=
), tokenize("

")
    assert_equal %w(<?xml> version=), tokenize("<?xml version=\"1.0\"?>")
  end

  def test_operators
    assert_equal %w(+), tokenize("1 + 1")
    assert_equal %w(-), tokenize("1 - 1")
    assert_equal %w(*), tokenize("1 * 1")
    assert_equal %w(/), tokenize("1 / 1")
    assert_equal %w(%), tokenize("2 % 5")
    assert_equal %w(&), tokenize("1 & 1")
    assert_equal %w(&&), tokenize("1 && 1")
    assert_equal %w(|), tokenize("1 | 1")
    assert_equal %w(||), tokenize("1 || 1")
    assert_equal %w(<), tokenize("1 < 0x01")
    assert_equal %w(<<), tokenize("1 << 0x01")
  end

  def test_c_tokens
    assert_equal %w(#ifndef HELLO_H #define HELLO_H void hello \( \) ; #endif), tokenize(:"C/hello.h")
    assert_equal %w(#include <stdio.h> int main \( \) { printf \( \) ; return ; }), tokenize(:"C/hello.c")
  end

  def test_cpp_tokens
    assert_equal %w(class Bar { protected char *name ; public void hello \( \) ; }), tokenize(:"C++/bar.h")
    assert_equal %w(#include <iostream> using namespace std ; int main \( \) { cout << << endl ; }), tokenize(:"C++/hello.cpp")
  end

  def test_objective_c_tokens
    assert_equal %w(#import <Foundation/Foundation.h> @interface Foo NSObject { } @end), tokenize(:"Objective-C/Foo.h")
    assert_equal %w(#import @implementation Foo @end), tokenize(:"Objective-C/Foo.m")
    assert_equal %w(#import <Cocoa/Cocoa.h> int main \( int argc char *argv [ ] \) { NSLog \( @ \) ; return ; }), tokenize(:"Objective-C/hello.m")
  end

  def test_shebang
    assert_equal "SHEBANG#!sh", tokenize(:"Shell/sh.script!")[0]
    assert_equal "SHEBANG#!bash", tokenize(:"Shell/bash.script!")[0]
    assert_equal "SHEBANG#!zsh", tokenize(:"Shell/zsh.script!")[0]
    assert_equal "SHEBANG#!perl", tokenize(:"Perl/perl.script!")[0]
    assert_equal "SHEBANG#!python", tokenize(:"Python/python.script!")[0]
    assert_equal "SHEBANG#!ruby", tokenize(:"Ruby/ruby.script!")[0]
    assert_equal "SHEBANG#!ruby", tokenize(:"Ruby/ruby2.script!")[0]
    assert_equal "SHEBANG#!node", tokenize(:"JavaScript/js.script!")[0]
    assert_equal "SHEBANG#!php", tokenize(:"PHP/php.script!")[0]
    assert_equal "SHEBANG#!escript", tokenize(:"Erlang/factorial.script!")[0]
    assert_equal "echo", tokenize(:"Shell/invalid-shebang.sh")[0]
  end

  def test_javascript_tokens
    assert_equal %w( \( function \( \) { console.log \( \) ; } \) .call \( this \) ;), tokenize(:"JavaScript/hello.js")
  end

  def test_json_tokens
    assert_equal %w( { [ ] { } } ), tokenize(:"JSON/product.json")
  end

  def test_ruby_tokens
    assert_equal %w(module Foo end), tokenize(:"Ruby/foo.rb")
    assert_equal %w(task default do puts end), tokenize(:"Ruby/filenames/Rakefile")
  end
end


text: package augmentedairuntime


text:
module Scruffy::Helpers

  # ==Scruffy::Helpers::LayerContainer
  #
  # Author:: Brasten Sager
  # Date:: August 16th, 2006
  #
  # Adds some common functionality to any object which needs to act as a
  # container for graph layers.  The best example of this is the Scruffy::Graph
  # object itself, but this module is also used by Scruffy::Layer::Stacked.
  module LayerContainer

    # Adds a Layer to the Graph/Container.  Accepts either a list of
    # arguments used to build a new layer, or a Scruffy::Layers::Base-derived
    # object.  When passing a list of arguments, all arguments are optional,
    # but the arguments specified must be provided in a particular order:
    # type (Symbol), title (String), points (Array), options (Hash).
    #
    # Both #add and #<< can be used.
    #
    #   graph.add(:line, [100, 200, 150])     # Create and add an untitled line graph
    #
    #   graph << (:line, "John's Sales", [150, 100])    # Create and add a titled line graph
    #
    #   graph << Scruffy::Layers::Bar.new({...})   # Adds Bar layer to graph
    #
    def <<(*args, &block)
      if args[0].kind_of?(Scruffy::Layers::Base)
        layers << args[0]
      else
        type = args.first.is_a?(Symbol) ? args.shift : @default_type
        title = args.shift if args.first.is_a?(String)

        # Layer handles PointContainer mixin, don't do it here
        points = [Array, Hash].include?(args.first.class) ? args.shift : []
        options = args.first.is_a?(Hash) ? args.shift : {}

        title ||= ''

        raise ArgumentError,
                'You must specify a graph type (:area, :bar, :line, etc) if you do not have a default type specified.' if type.nil?

        class_name = "Scruffy::Layers::#{to_camelcase(type.to_s)}"
        layer_class = Kernel::module_eval(class_name)
        options = {:points => points, :title => title}.merge options
        layer = layer_class.new(options, &block)
        layers << layer
      end
      layer
    end

    alias :add :<<

    # Layer Writer
    def layers=(val)
      @layers = val
    end

    # Layer Reader
    def layers
      @layers ||= []
    end

    # Returns the highest value in any of this container's layers.
    #
    # If padding is set to :padded, a 15% padding is added to the highest value.
    def top_value(padding=nil) # :nodoc:
      topval = layers.inject(0) { |max, layer| (max = ((max < layer.top_value) ? layer.top_value : max)) unless layer.top_value.nil?; max }
      below_zero = (topval <= 0)
      topval = padding == :padded ? (topval + ((topval - bottom_value) * 0.15)) : topval
      (below_zero && topval > 0) ? 0 : topval
    end

    # Returns the lowest value in any of this container's layers.
    #
    # If padding is set to :padded, a 15% padding is added below the lowest value.
    # If the lowest value is greater than zero, then the padding will not cross the zero line, preventing
    # negative values from being introduced into the graph purely due to padding.
    def bottom_value(padding=nil) # :nodoc:
      botval = layers.inject(0) do |min, layer|
        (min = ((min > layer.bottom_value) ? layer.bottom_value : min)) unless layer.bottom_value.nil?
        min
      end
      above_zero = (botval >= 0)
      botval = (botval - ((top_value - botval) * 0.15)) if padding == :padded

      # Don't introduce negative values solely due to padding.
      # A user-provided value must be negative before padding will extend into negative values.
      (above_zero && botval < 0) ? 0 : botval
    end

    def bottom_key(padding=nil)
      return 0 unless layers.any?
      min = layers[0].bottom_key
      layers.each do |layer|
        min = layer.bottom_key if min.nil? && !layer.bottom_key.nil?
        (min = ((min > layer.bottom_key) ? layer.bottom_key : min)) unless layer.bottom_key.nil?
      end
      min
    end

    def top_key(padding=nil)
      return 1 unless layers.any?
      max = layers[0].top_key
      layers.each do |layer|
        max = layer.top_key if max.nil? && !layer.top_key.nil?
        (max = ((max < layer.top_key) ? layer.top_key : max)) unless layer.top_key.nil?
      end
      max
    end

    protected
      def to_camelcase(type)  # :nodoc:
        type.split('_').map { |e| e.capitalize }.join('')
      end

  end
end


text:
<?php

defined( 'BASEPATH' ) OR exit( 'No direct script access allowed' );

class MRegistrasi extends MY_Model {

    function __construct() {
        parent::__construct();
    }

    public function save($data){
         $this->db->insert('members',$data);
         return $this->db->affected_rows();
    }
}


text:
import inspect
import gc

class Debug(object):

    " Subclass for collection of debugging informations "

    def __new__(cls, *a, **b):
        # Get the frame where the instantiation came from
        frame = inspect.stack()[1]
        # Continue with __new__ in super objects
        o = super(Debug, cls).__new__(cls, a, b)
        # Save important frame infos in object
        o.debug_call = list(frame[1:4]) + [frame[4][0]]
        return o

    def DebugInfo(self):
        # Split our informations
        file, line, module, source = self.debug_call
        # Format informative output
        return 'Object instantiated in file "%s", line %s, in %s: %s' % (
            file,
            line,
            module,
            source.strip() )

def DumpDebugObjects(title):
    print "***", title, "***"
    gc.collect()
    for o in gc.get_objects():
        if isinstance(o, Debug):
            print o.DebugInfo()

if __name__=="__main__":

    class Test(Debug):

        def __init__(self, arg):
            print "Test", arg

    class Test2(Test):

        pass

    t1 = Test(1)
    t2 = Test(2)
    t3 = Test(3)

    DumpDebugObjects("We expect 3 objects")

    del t2

    DumpDebugObjects("Now one less")


text:
  待确认运费

  待付款

  待发货

  已发货

  交易成功


text:
package com.jetdrone.vertx.yoke.middleware;

import com.jetdrone.vertx.yoke.Middleware;
import org.jetbrains.annotations.NotNull;
import io.vertx.core.Handler;

public final class CrossDomain extends Middleware {

    private static final String DATA =
            "<?xml version=\"1.0\"?>" +
            "<!DOCTYPE cross-domain-policy SYSTEM \"http://www.adobe.com/xml/dtds/cross-domain-policy.dtd\">" +
            "<cross-domain-policy>" +
            "<site-control permitted-cross-domain-policies=\"none\"/>" +
            "</cross-domain-policy>";

    @Override
    public void handle(@NotNull YokeRequest request, @NotNull Handler<Object> next) {
        if ("/crossdomain.xml".equals(request.path())) {
            request.response().putHeader("Content-Type", "text/x-cross-domain-policy");
            request.response().end(DATA);
        } else {
            next.handle(null);
        }
    }
}


text:
package org.thingsboard.server.common.data;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.thingsboard.server.common.data.id.DeviceProfileId;
import org.thingsboard.server.common.data.id.OtaPackageId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.ota.ChecksumAlgorithm;
import org.thingsboard.server.common.data.ota.OtaPackageType;
import org.thingsboard.server.common.data.validation.Length;
import org.thingsboard.server.common.data.validation.NoXss;
import org.thingsboard.server.common.data.ota.ChecksumAlgorithm;
import org.thingsboard.server.common.data.ota.OtaPackageType;

@ApiModel
@Slf4j
@Data
@EqualsAndHashCode(callSuper = true)
public class OtaPackageInfo extends SearchTextBasedWithAdditionalInfo<OtaPackageId> implements HasName, HasTenantId {

    private static final long serialVersionUID = 3168391583570815419L;

    @ApiModelProperty(position = 3, value = "JSON object with Tenant Id. Tenant Id of the ota package can't be changed.", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private TenantId tenantId;
    @ApiModelProperty(position = 4, value = "JSON object with Device Profile Id. Device Profile Id of the ota package can't be changed.", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private DeviceProfileId deviceProfileId;
    @ApiModelProperty(position = 5, value = "OTA Package type.", example = "FIRMWARE", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private OtaPackageType type;
    @Length(fieldName = "title")
    @NoXss
    @ApiModelProperty(position = 6, value = "OTA Package title.", example = "fw", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private String title;
    @Length(fieldName = "version")
    @NoXss
    @ApiModelProperty(position = 7, value = "OTA Package version.", example = "1.0", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private String version;
    @Length(fieldName = "tag")
    @NoXss
    @ApiModelProperty(position = 8, value = "OTA Package tag.", example = "fw_1.0", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private String tag;
    @Length(fieldName = "url")
    @NoXss
    @ApiModelProperty(position = 9, value = "OTA Package url.", example = "http://thingsboard.org/fw/1", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private String url;
    @ApiModelProperty(position = 10, value = "Indicates OTA Package 'has data'. Field is returned from DB ('true' if data exists or url is set).  If OTA Package 'has data' is 'false' we can not assign the OTA Package to the Device or Device Profile.", example = "true", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private boolean hasData;
    @Length(fieldName = "file name")
    @NoXss
    @ApiModelProperty(position = 11, value = "OTA Package file name.", example = "fw_1.0", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private String fileName;
    @NoXss
    @Length(fieldName = "contentType")
    @ApiModelProperty(position = 12, value = "OTA Package content type.", example = "APPLICATION_OCTET_STREAM", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private String contentType;
    @ApiModelProperty(position = 13, value = "OTA Package checksum algorithm.", example = "CRC32", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private ChecksumAlgorithm checksumAlgorithm;
    @Length(fieldName = "checksum", max = 1020)
    @ApiModelProperty(position = 14, value = "OTA Package checksum.", example = "0xd87f7e0c", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private String checksum;
    @ApiModelProperty(position = 15, value = "OTA Package data size.", example = "8", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    private Long dataSize;

    public OtaPackageInfo() {
        super();
    }

    public OtaPackageInfo(OtaPackageId id) {
        super(id);
    }

    public OtaPackageInfo(OtaPackageInfo otaPackageInfo) {
        super(otaPackageInfo);
        this.tenantId = otaPackageInfo.getTenantId();
        this.deviceProfileId = otaPackageInfo.getDeviceProfileId();
        this.type = otaPackageInfo.getType();
        this.title = otaPackageInfo.getTitle();
        this.version = otaPackageInfo.getVersion();
        this.tag = otaPackageInfo.getTag();
        this.url = otaPackageInfo.getUrl();
        this.hasData = otaPackageInfo.isHasData();
        this.fileName = otaPackageInfo.getFileName();
        this.contentType = otaPackageInfo.getContentType();
        this.checksumAlgorithm = otaPackageInfo.getChecksumAlgorithm();
        this.checksum = otaPackageInfo.getChecksum();
        this.dataSize = otaPackageInfo.getDataSize();
    }

    @ApiModelProperty(position = 1, value = "JSON object with the ota package Id. " +
            "Specify existing ota package Id to update the ota package. " +
            "Referencing non-existing ota package id will cause error. " +
            "Omit this field to create new ota package.")
    @Override
    public OtaPackageId getId() {
        return super.getId();
    }

    @ApiModelProperty(position = 2, value = "Timestamp of the ota package creation, in milliseconds", example = "1609459200000", accessMode = ApiModelProperty.AccessMode.READ_ONLY)
    @Override
    public long getCreatedTime() {
        return super.getCreatedTime();
    }

    @Override
    public String getSearchText() {
        return title;
    }

    @Override
    @JsonIgnore
    public String getName() {
        return title;
    }

    @JsonIgnore
    public boolean hasUrl() {
        return StringUtils.isNotEmpty(url);
    }

    @ApiModelProperty(position = 17, value = "OTA Package description.", example = "Description for the OTA Package fw_1.0")
    @Override
    public JsonNode getAdditionalInfo() {
        return super.getAdditionalInfo();
    }
}


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

namespace LightRail
{
    /// <summary>
    /// Enables looking up interfaced mapped to generated concrete types
    /// and vice versa.
    /// </summary>
    public interface IMessageMapper
    {
        T CreateInstance<T>();
        T CreateInstance<T>(Action<T> action);
        object CreateInstance(Type messageType);

        /// <summary>
        /// Initializes the mapper with the given types to be scanned.
        /// </summary>
        /// <param name="types"></param>
        void Initialize(IEnumerable<Type> types);

        /// <summary>
        /// If the given type is an interface, returns the generated concrete type.
        /// If the given type is concerete, returns the interface it was generated from.
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        Type GetMappedTypeFor(Type t);

        /// <summary>
        /// Looks up the type mapped for the given name.
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        Type GetMappedTypeFor(string typeName);

        List<Type> GetMessageTypeHierarchy(Type type);

        IEnumerable<string> GetEnclosedMessageTypes(Type type);
    }
}


text:
const electron = require('electron');
const { app, BrowserWindow, Menu } = electron;
let mainWnd = null;

function createMainWnd() {
  mainWnd = new BrowserWindow({
    width:800,
    height:600,
    minWidth:800,
    maxWidth: 800,
    minHeight: 600,
    maxHeight: 600,
    useContentSize: true,
    show: false,
    frame: false,
    titleBarStyle: 'hidden',
    webPreferences: {
      nodeIntegration: true
    }
  });

  mainWnd.loadURL('http://127.0.0.1:16000/index.html');

  mainWnd.on('ready-to-show', ()=>{
    Menu.setApplicationMenu(null);
    mainWnd.show();
    // mainWnd.webContents.openDevTools({ detach:true });
  });

  mainWnd.on('closed', () => {
    mainWnd = null;
    process.exit();
  });
}

app.on('ready', ()=>{
  createMainWnd();
});

app.on('window-all-closed', () => {
  app.quit();
});


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

#include "net/quic/quic_chromium_client_stream.h"

#include <string>

#include "base/bind.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/quic/quic_chromium_client_session.h"
#include "net/test/gtest_util.h"
#include "net/test/test_with_task_environment.h"
#include "net/third_party/quiche/src/quic/core/http/quic_spdy_client_session_base.h"
#include "net/third_party/quiche/src/quic/core/http/quic_spdy_client_stream.h"
#include "net/third_party/quiche/src/quic/core/http/spdy_utils.h"
#include "net/third_party/quiche/src/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_ptr_util.h"
#include "net/third_party/quiche/src/quic/test_tools/crypto_test_utils.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_config_peer.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_spdy_session_peer.h"
#include "net/third_party/quiche/src/quic/test_tools/quic_test_utils.h"
#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
#include "testing/gmock/include/gmock/gmock.h"

using testing::_;
using testing::Return;

namespace net {
namespace test {
namespace {

class MockQuicClientSessionBase : public quic::QuicSpdyClientSessionBase {
 public:
  explicit MockQuicClientSessionBase(quic::QuicConnection* connection,
                                     quic::QuicClientPushPromiseIndex* index);
  ~MockQuicClientSessionBase() override;

  const quic::QuicCryptoStream* GetCryptoStream() const override {
    return crypto_stream_.get();
  }

  quic::QuicCryptoStream* GetMutableCryptoStream() override {
    return crypto_stream_.get();
  }

  // From quic::QuicSession.
  MOCK_METHOD2(OnConnectionClosed,
               void(const quic::QuicConnectionCloseFrame& frame,
                    quic::ConnectionCloseSource source));
  MOCK_METHOD1(CreateIncomingStream,
               quic::QuicSpdyStream*(quic::QuicStreamId id));
  MOCK_METHOD1(CreateIncomingStream,
               quic::QuicSpdyStream*(quic::PendingStream* pending));
  MOCK_METHOD0(CreateOutgoingBidirectionalStream, QuicChromiumClientStream*());
  MOCK_METHOD0(CreateOutgoingUnidirectionalStream, QuicChromiumClientStream*());
  MOCK_METHOD6(WritevData,
               quic::QuicConsumedData(
                   quic::QuicStreamId id,
                   size_t write_length,
                   quic::QuicStreamOffset offset,
                   quic::StreamSendingState state,
                   quic::TransmissionType type,
                   quiche::QuicheOptional<quic::EncryptionLevel> level));
  MOCK_METHOD3(SendRstStream,
               void(quic::QuicStreamId stream_id,
                    quic::QuicRstStreamErrorCode error,
                    quic::QuicStreamOffset bytes_written));

  MOCK_METHOD2(OnStreamHeaders,
               void(quic::QuicStreamId stream_id,
                    quiche::QuicheStringPiece headers_data));
  MOCK_METHOD2(OnStreamHeadersPriority,
               void(quic::QuicStreamId stream_id,
                    const spdy::SpdyStreamPrecedence& precedence));
  MOCK_METHOD3(OnStreamHeadersComplete,
               void(quic::QuicStreamId stream_id, bool fin, size_t frame_len));
  MOCK_METHOD2(OnPromiseHeaders,
               void(quic::QuicStreamId stream_id,
                    quiche::QuicheStringPiece headers_data));
  MOCK_METHOD3(OnPromiseHeadersComplete,
               void(quic::QuicStreamId stream_id,
                    quic::QuicStreamId promised_stream_id,
                    size_t frame_len));
  MOCK_CONST_METHOD0(OneRttKeysAvailable, bool());
  // Methods taking non-copyable types like spdy::SpdyHeaderBlock by value
  // cannot be mocked directly.
  size_t WriteHeadersOnHeadersStream(
      quic::QuicStreamId id,
      spdy::SpdyHeaderBlock headers,
      bool fin,
      const spdy::SpdyStreamPrecedence& precedence,
      quic::QuicReferenceCountedPointer<quic::QuicAckListenerInterface>
          ack_listener) override {
    return WriteHeadersOnHeadersStreamMock(id, headers, fin, precedence,
                                           std::move(ack_listener));
  }
  MOCK_METHOD5(WriteHeadersOnHeadersStreamMock,
               size_t(quic::QuicStreamId id,
                      const spdy::SpdyHeaderBlock& headers,
                      bool fin,
                      const spdy::SpdyStreamPrecedence& precedence,
                      const quic::QuicReferenceCountedPointer<
                          quic::QuicAckListenerInterface>& ack_listener));
  MOCK_METHOD1(OnHeadersHeadOfLineBlocking, void(quic::QuicTime::Delta delta));

  using quic::QuicSession::ActivateStream;

  // Returns a quic::QuicConsumedData that indicates all of |write_length| (and
  // |fin| if set) has been consumed.
  static quic::QuicConsumedData ConsumeAllData(
      quic::QuicStreamId id,
      size_t write_length,
      quic::QuicStreamOffset offset,
      bool fin,
      quic::QuicAckListenerInterface* ack_listener);

  void OnProofValid(
      const quic::QuicCryptoClientConfig::CachedState& cached) override {}
  void OnProofVerifyDetailsAvailable(
      const quic::ProofVerifyDetails& verify_details) override {}
  bool IsAuthorized(const std::string& hostname) override { return true; }

 protected:
  MOCK_METHOD1(ShouldCreateIncomingStream, bool(quic::QuicStreamId id));
  MOCK_METHOD0(ShouldCreateOutgoingBidirectionalStream, bool());
  MOCK_METHOD0(ShouldCreateOutgoingUnidirectionalStream, bool());

 private:
  std::unique_ptr<quic::QuicCryptoStream> crypto_stream_;

  DISALLOW_COPY_AND_ASSIGN(MockQuicClientSessionBase);
};

MockQuicClientSessionBase::MockQuicClientSessionBase(
    quic::QuicConnection* connection,
    quic::QuicClientPushPromiseIndex* push_promise_index)
    : quic::QuicSpdyClientSessionBase(connection,
                                      push_promise_index,
                                      quic::test::DefaultQuicConfig(),
                                      connection->supported_versions()) {
  crypto_stream_.reset(new quic::test::MockQuicCryptoStream(this));
  Initialize();
  ON_CALL(*this, WritevData(_, _, _, _, _, _))
      .WillByDefault(testing::Return(quic::QuicConsumedData(0, false)));
}

MockQuicClientSessionBase::~MockQuicClientSessionBase() {}

class QuicChromiumClientStreamTest
    : public ::testing::TestWithParam<quic::ParsedQuicVersion>,
      public WithTaskEnvironment {
 public:
  QuicChromiumClientStreamTest()
      : version_(GetParam()),
        crypto_config_(
            quic::test::crypto_test_utils::ProofVerifierForTesting()),
        session_(new quic::test::MockQuicConnection(
                     &helper_,
                     &alarm_factory_,
                     quic::Perspective::IS_CLIENT,
                     quic::test::SupportedVersions(version_)),
                 &push_promise_index_) {
    quic::test::QuicConfigPeer::SetReceivedInitialSessionFlowControlWindow(
        session_.config(), quic::kMinimumFlowControlSendWindow);
    quic::test::QuicConfigPeer::
        SetReceivedInitialMaxStreamDataBytesOutgoingBidirectional(
            session_.config(), quic::kMinimumFlowControlSendWindow);
    quic::test::QuicConfigPeer::SetReceivedMaxUnidirectionalStreams(
        session_.config(), 10);
    session_.OnConfigNegotiated();
    stream_ = new QuicChromiumClientStream(
        quic::test::GetNthClientInitiatedBidirectionalStreamId(
            version_.transport_version, 0),
        &session_, quic::BIDIRECTIONAL, NetLogWithSource(),
        TRAFFIC_ANNOTATION_FOR_TESTS);
    session_.ActivateStream(base::WrapUnique(stream_));
    handle_ = stream_->CreateHandle();
    helper_.AdvanceTime(quic::QuicTime::Delta::FromSeconds(1));
  }

  void InitializeHeaders() {
    headers_[":host"] = "www.google.com";
    headers_[":path"] = "/index.hml";
    headers_[":scheme"] = "https";
    headers_["cookie"] =
        "__utma=208381060.1228362404.1372200928.1372200928.1372200928.1; "
        "__utmc=160408618; "
        "GX=DQAAAOEAAACWJYdewdE9rIrW6qw3PtVi2-d729qaa-74KqOsM1NVQblK4VhX"
        "hoALMsy6HOdDad2Sz0flUByv7etmo3mLMidGrBoljqO9hSVA40SLqpG_iuKKSHX"
        "RW3Np4bq0F0SDGDNsW0DSmTS9ufMRrlpARJDS7qAI6M3bghqJp4eABKZiRqebHT"
        "pMU-RXvTI5D5oCF1vYxYofH_l1Kviuiy3oQ1kS1enqWgbhJ2t61_SNdv-1XJIS0"
        "O3YeHLmVCs62O6zp89QwakfAWK9d3IDQvVSJzCQsvxvNIvaZFa567MawWlXg0Rh"
        "1zFMi5vzcns38-8_Sns; "
        "GA=v*2%2Fmem*57968640*47239936%2Fmem*57968640*47114716%2Fno-nm-"
        "yj*15%2Fno-cc-yj*5%2Fpc-ch*133685%2Fpc-s-cr*133947%2Fpc-s-t*1339"
        "47%2Fno-nm-yj*4%2Fno-cc-yj*1%2Fceft-as*1%2Fceft-nqas*0%2Fad-ra-c"
        "v_p%2Fad-nr-cv_p-f*1%2Fad-v-cv_p*859%2Fad-ns-cv_p-f*1%2Ffn-v-ad%"
        "2Fpc-t*250%2Fpc-cm*461%2Fpc-s-cr*722%2Fpc-s-t*722%2Fau_p*4"
        "SICAID=AJKiYcHdKgxum7KMXG0ei2t1-W4OD1uW-ecNsCqC0wDuAXiDGIcT_HA2o1"
        "3Rs1UKCuBAF9g8rWNOFbxt8PSNSHFuIhOo2t6bJAVpCsMU5Laa6lewuTMYI8MzdQP"
        "ARHKyW-koxuhMZHUnGBJAM1gJODe0cATO_KGoX4pbbFxxJ5IicRxOrWK_5rU3cdy6"
        "edlR9FsEdH6iujMcHkbE5l18ehJDwTWmBKBzVD87naobhMMrF6VvnDGxQVGp9Ir_b"
        "Rgj3RWUoPumQVCxtSOBdX0GlJOEcDTNCzQIm9BSfetog_eP_TfYubKudt5eMsXmN6"
        "QnyXHeGeK2UINUzJ-D30AFcpqYgH9_1BvYSpi7fc7_ydBU8TaD8ZRxvtnzXqj0RfG"
        "tuHghmv3aD-uzSYJ75XDdzKdizZ86IG6Fbn1XFhYZM-fbHhm3mVEXnyRW4ZuNOLFk"
        "Fas6LMcVC6Q8QLlHYbXBpdNFuGbuZGUnav5C-2I_-46lL0NGg3GewxGKGHvHEfoyn"
        "EFFlEYHsBQ98rXImL8ySDycdLEFvBPdtctPmWCfTxwmoSMLHU2SCVDhbqMWU5b0yr"
        "JBCScs_ejbKaqBDoB7ZGxTvqlrB__2ZmnHHjCr8RgMRtKNtIeuZAo ";
  }

  void ReadData(quiche::QuicheStringPiece expected_data) {
    scoped_refptr<IOBuffer> buffer =
        base::MakeRefCounted<IOBuffer>(expected_data.length() + 1);
    EXPECT_EQ(static_cast<int>(expected_data.length()),
              stream_->Read(buffer.get(), expected_data.length() + 1));
    EXPECT_EQ(expected_data, quiche::QuicheStringPiece(buffer->data(),
                                                       expected_data.length()));
  }

  quic::QuicHeaderList ProcessHeaders(const spdy::SpdyHeaderBlock& headers) {
    quic::QuicHeaderList h = quic::test::AsHeaderList(headers);
    stream_->OnStreamHeaderList(false, h.uncompressed_header_bytes(), h);
    return h;
  }

  quic::QuicHeaderList ProcessTrailers(const spdy::SpdyHeaderBlock& headers) {
    quic::QuicHeaderList h = quic::test::AsHeaderList(headers);
    stream_->OnStreamHeaderList(true, h.uncompressed_header_bytes(), h);
    return h;
  }

  quic::QuicHeaderList ProcessHeadersFull(
      const spdy::SpdyHeaderBlock& headers) {
    quic::QuicHeaderList h = ProcessHeaders(headers);
    TestCompletionCallback callback;
    EXPECT_EQ(static_cast<int>(h.uncompressed_header_bytes()),
              handle_->ReadInitialHeaders(&headers_, callback.callback()));
    EXPECT_EQ(headers, headers_);
    EXPECT_TRUE(stream_->header_list().empty());
    return h;
  }

  quic::QuicStreamId GetNthClientInitiatedBidirectionalStreamId(int n) {
    return quic::test::GetNthClientInitiatedBidirectionalStreamId(
        session_.connection()->transport_version(), n);
  }

  quic::QuicStreamId GetNthServerInitiatedUnidirectionalStreamId(int n) {
    return quic::test::GetNthServerInitiatedUnidirectionalStreamId(
        session_.connection()->transport_version(), n);
  }

  void ResetStreamCallback(QuicChromiumClientStream* stream, int /*rv*/) {
    stream->Reset(quic::QUIC_STREAM_CANCELLED);
  }

  std::string ConstructDataHeader(size_t body_len) {
    if (!version_.HasIetfQuicFrames()) {
      return "";
    }
    std::unique_ptr<char[]> buffer;
    auto header_length =
        quic::HttpEncoder::SerializeDataFrameHeader(body_len, &buffer);
    return std::string(buffer.get(), header_length);
  }

  const quic::ParsedQuicVersion version_;
  quic::QuicCryptoClientConfig crypto_config_;
  std::unique_ptr<QuicChromiumClientStream::Handle> handle_;
  std::unique_ptr<QuicChromiumClientStream::Handle> handle2_;
  quic::test::MockQuicConnectionHelper helper_;
  quic::test::MockAlarmFactory alarm_factory_;
  MockQuicClientSessionBase session_;
  QuicChromiumClientStream* stream_;
  spdy::SpdyHeaderBlock headers_;
  spdy::SpdyHeaderBlock trailers_;
  quic::QuicClientPushPromiseIndex push_promise_index_;
};

INSTANTIATE_TEST_SUITE_P(Version,
                         QuicChromiumClientStreamTest,
                         ::testing::ValuesIn(quic::AllSupportedVersions()),
                         ::testing::PrintToStringParamName());

TEST_P(QuicChromiumClientStreamTest, Handle) {
  testing::InSequence seq;
  EXPECT_TRUE(handle_->IsOpen());
  EXPECT_EQ(quic::test::GetNthClientInitiatedBidirectionalStreamId(
                version_.transport_version, 0),
            handle_->id());
  EXPECT_EQ(quic::QUIC_NO_ERROR, handle_->connection_error());
  EXPECT_EQ(quic::QUIC_STREAM_NO_ERROR, handle_->stream_error());
  EXPECT_TRUE(handle_->IsFirstStream());
  EXPECT_FALSE(handle_->IsDoneReading());
  EXPECT_FALSE(handle_->fin_sent());
  EXPECT_FALSE(handle_->fin_received());
  EXPECT_EQ(0u, handle_->stream_bytes_read());
  EXPECT_EQ(0u, handle_->stream_bytes_written());
  EXPECT_EQ(0u, handle_->NumBytesConsumed());

  InitializeHeaders();
  quic::QuicStreamOffset offset = 0;
  ProcessHeadersFull(headers_);
  quic::QuicStreamFrame frame2(
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      true, offset, quiche::QuicheStringPiece());
  stream_->OnStreamFrame(frame2);
  EXPECT_TRUE(handle_->fin_received());
  handle_->OnFinRead();

  const char kData1[] = "hello world";
  const size_t kDataLen = base::size(kData1);

  // All data written.
  std::string header = ConstructDataHeader(kDataLen);
  if (version_.HasIetfQuicFrames()) {
    EXPECT_CALL(session_,
                WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
        .WillOnce(Return(quic::QuicConsumedData(header.length(), false)));
  }
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      .WillOnce(Return(quic::QuicConsumedData(kDataLen, true)));
  TestCompletionCallback callback;
  EXPECT_EQ(
      OK, handle_->WriteStreamData(quiche::QuicheStringPiece(kData1, kDataLen),
                                   true, callback.callback()));

  EXPECT_FALSE(handle_->IsOpen());
  EXPECT_EQ(quic::test::GetNthClientInitiatedBidirectionalStreamId(
                version_.transport_version, 0),
            handle_->id());
  EXPECT_EQ(quic::QUIC_NO_ERROR, handle_->connection_error());
  EXPECT_EQ(quic::QUIC_STREAM_NO_ERROR, handle_->stream_error());
  EXPECT_TRUE(handle_->IsFirstStream());
  EXPECT_TRUE(handle_->IsDoneReading());
  EXPECT_TRUE(handle_->fin_sent());
  EXPECT_TRUE(handle_->fin_received());
  EXPECT_EQ(0u, handle_->stream_bytes_read());
  EXPECT_EQ(header.length() + kDataLen, handle_->stream_bytes_written());
  EXPECT_EQ(0u, handle_->NumBytesConsumed());

  EXPECT_EQ(
      ERR_CONNECTION_CLOSED,
      handle_->WriteStreamData(quiche::QuicheStringPiece(kData1, kDataLen),
                               true, callback.callback()));

  std::vector<scoped_refptr<IOBuffer>> buffers = {
      base::MakeRefCounted<IOBuffer>(10)};
  std::vector<int> lengths = {10};
  EXPECT_EQ(
      ERR_CONNECTION_CLOSED,
      handle_->WritevStreamData(buffers, lengths, true, callback.callback()));

  spdy::SpdyHeaderBlock headers;
  EXPECT_EQ(0, handle_->WriteHeaders(std::move(headers), true, nullptr));
}

TEST_P(QuicChromiumClientStreamTest, HandleAfterConnectionClose) {
  EXPECT_CALL(
      session_,
      SendRstStream(quic::test::GetNthClientInitiatedBidirectionalStreamId(
                        version_.transport_version, 0),
                    quic::QUIC_RST_ACKNOWLEDGEMENT, 0));
  stream_->OnConnectionClosed(quic::QUIC_INVALID_FRAME_DATA,
                              quic::ConnectionCloseSource::FROM_PEER);

  EXPECT_FALSE(handle_->IsOpen());
  EXPECT_EQ(quic::QUIC_INVALID_FRAME_DATA, handle_->connection_error());
}

TEST_P(QuicChromiumClientStreamTest, HandleAfterStreamReset) {
  // Verify that the Handle still behaves correctly after the stream is reset.
  quic::QuicRstStreamFrame rst(
      quic::kInvalidControlFrameId,
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      quic::QUIC_STREAM_CANCELLED, 0);
  if (!version_.HasIetfQuicFrames()) {
    EXPECT_CALL(
        session_,
        SendRstStream(quic::test::GetNthClientInitiatedBidirectionalStreamId(
                          version_.transport_version, 0),
                      quic::QUIC_RST_ACKNOWLEDGEMENT, 0));
  } else {
    // Intercept & check that the call to the QuicConnection's OnStreamReast
    // has correct stream ID and error code -- for V99/IETF Quic, it should
    // have the STREAM_CANCELLED error code, not RST_ACK... Capture
    // OnStreamReset (rather than SendRstStream) because the V99 path bypasses
    // SendRstStream, calling SendRstStreamInner directly. Mocking
    // SendRstStreamInner is problematic since the test relies on it to perform
    // the closing operations and getting the stream in the correct state.
    EXPECT_CALL(
        *(static_cast<quic::test::MockQuicConnection*>(session_.connection())),
        OnStreamReset(stream_->id(), quic::QUIC_STREAM_CANCELLED));
  }

  stream_->OnStreamReset(rst);
  if (version_.HasIetfQuicFrames()) {
    // Make a STOP_SENDING frame and pass it to QUIC. For V99/IETF QUIC,
    // we need both a REST_STREAM and a STOP_SENDING to effect a closed
    // stream.
    quic::QuicStopSendingFrame stop_sending_frame(
        quic::kInvalidControlFrameId,
        quic::test::GetNthClientInitiatedBidirectionalStreamId(
            version_.transport_version, 0),
        quic::QUIC_STREAM_CANCELLED);
    session_.OnStopSendingFrame(stop_sending_frame);
  }
  EXPECT_FALSE(handle_->IsOpen());
  EXPECT_EQ(quic::QUIC_STREAM_CANCELLED, handle_->stream_error());
}

TEST_P(QuicChromiumClientStreamTest, OnFinRead) {
  InitializeHeaders();
  quic::QuicStreamOffset offset = 0;
  ProcessHeadersFull(headers_);
  quic::QuicStreamFrame frame2(
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      true, offset, quiche::QuicheStringPiece());
  stream_->OnStreamFrame(frame2);
}

TEST_P(QuicChromiumClientStreamTest, OnDataAvailable) {
  InitializeHeaders();
  ProcessHeadersFull(headers_);

  const char data[] = "hello world!";
  int data_len = strlen(data);
  size_t offset = 0;
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(data_len);
    stream_->OnStreamFrame(quic::QuicStreamFrame(
        quic::test::GetNthClientInitiatedBidirectionalStreamId(
            version_.transport_version, 0),
        /*fin=*/false,
        /*offset=*/offset, header));
    offset += header.length();
  }
  stream_->OnStreamFrame(quic::QuicStreamFrame(
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      /*fin=*/false,
      /*offset=*/offset, data));

  // Read the body and verify that it arrives correctly.
  TestCompletionCallback callback;
  scoped_refptr<IOBuffer> buffer = base::MakeRefCounted<IOBuffer>(2 * data_len);
  EXPECT_EQ(data_len,
            handle_->ReadBody(buffer.get(), 2 * data_len, callback.callback()));
  EXPECT_EQ(quiche::QuicheStringPiece(data),
            quiche::QuicheStringPiece(buffer->data(), data_len));
}

TEST_P(QuicChromiumClientStreamTest, OnDataAvailableAfterReadBody) {
  InitializeHeaders();
  ProcessHeadersFull(headers_);

  const char data[] = "hello world!";
  int data_len = strlen(data);

  // Start to read the body.
  TestCompletionCallback callback;
  scoped_refptr<IOBuffer> buffer = base::MakeRefCounted<IOBuffer>(2 * data_len);
  EXPECT_EQ(ERR_IO_PENDING,
            handle_->ReadBody(buffer.get(), 2 * data_len, callback.callback()));

  size_t offset = 0;
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(data_len);
    stream_->OnStreamFrame(quic::QuicStreamFrame(
        quic::test::GetNthClientInitiatedBidirectionalStreamId(
            version_.transport_version, 0),
        /*fin=*/false,
        /*offset=*/offset, header));
    offset += header.length();
  }

  stream_->OnStreamFrame(quic::QuicStreamFrame(
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      /*fin=*/false,
      /*offset=*/offset, data));

  EXPECT_EQ(data_len, callback.WaitForResult());
  EXPECT_EQ(quiche::QuicheStringPiece(data),
            quiche::QuicheStringPiece(buffer->data(), data_len));
  base::RunLoop().RunUntilIdle();
}

TEST_P(QuicChromiumClientStreamTest, ProcessHeadersWithError) {
  spdy::SpdyHeaderBlock bad_headers;
  bad_headers["NAME"] = "...";
  EXPECT_CALL(
      session_,
      SendRstStream(quic::test::GetNthClientInitiatedBidirectionalStreamId(
                        version_.transport_version, 0),
                    quic::QUIC_BAD_APPLICATION_PAYLOAD, 0));

  auto headers = quic::test::AsHeaderList(bad_headers);
  stream_->OnStreamHeaderList(false, headers.uncompressed_header_bytes(),
                              headers);

  base::RunLoop().RunUntilIdle();
}

TEST_P(QuicChromiumClientStreamTest, OnDataAvailableWithError) {
  InitializeHeaders();
  auto headers = quic::test::AsHeaderList(headers_);
  ProcessHeadersFull(headers_);
  EXPECT_CALL(
      session_,
      SendRstStream(quic::test::GetNthClientInitiatedBidirectionalStreamId(
                        version_.transport_version, 0),
                    quic::QUIC_STREAM_CANCELLED, 0));

  const char data[] = "hello world!";
  int data_len = strlen(data);

  // Start to read the body.
  TestCompletionCallback callback;
  scoped_refptr<IOBuffer> buffer = base::MakeRefCounted<IOBuffer>(2 * data_len);
  EXPECT_EQ(
      ERR_IO_PENDING,
      handle_->ReadBody(
          buffer.get(), 2 * data_len,
          base::BindOnce(&QuicChromiumClientStreamTest::ResetStreamCallback,
                         base::Unretained(this), stream_)));

  // Receive the data and close the stream during the callback.
  size_t offset = 0;
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(data_len);
    stream_->OnStreamFrame(quic::QuicStreamFrame(
        quic::test::GetNthClientInitiatedBidirectionalStreamId(
            version_.transport_version, 0),
        /*fin=*/false,
        /*offset=*/offset, header));
    offset += header.length();
  }
  stream_->OnStreamFrame(quic::QuicStreamFrame(
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      /*fin=*/false,
      /*offset=*/0, data));

  base::RunLoop().RunUntilIdle();
}

TEST_P(QuicChromiumClientStreamTest, OnError) {
  //  EXPECT_CALL(delegate_, OnError(ERR_INTERNET_DISCONNECTED)).Times(1);

  stream_->OnError(ERR_INTERNET_DISCONNECTED);
  stream_->OnError(ERR_INTERNET_DISCONNECTED);
}

TEST_P(QuicChromiumClientStreamTest, OnTrailers) {
  InitializeHeaders();
  ProcessHeadersFull(headers_);

  const char data[] = "hello world!";
  int data_len = strlen(data);
  size_t offset = 0;
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(data_len);
    stream_->OnStreamFrame(quic::QuicStreamFrame(
        quic::test::GetNthClientInitiatedBidirectionalStreamId(
            version_.transport_version, 0),
        /*fin=*/false,
        /*offset=*/offset, header));
    offset += header.length();
  }
  stream_->OnStreamFrame(quic::QuicStreamFrame(
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      /*fin=*/false,
      /*offset=*/offset, data));

  // Read the body and verify that it arrives correctly.
  TestCompletionCallback callback;
  scoped_refptr<IOBuffer> buffer = base::MakeRefCounted<IOBuffer>(2 * data_len);
  EXPECT_EQ(data_len,
            handle_->ReadBody(buffer.get(), 2 * data_len, callback.callback()));
  EXPECT_EQ(quiche::QuicheStringPiece(data),
            quiche::QuicheStringPiece(buffer->data(), data_len));

  spdy::SpdyHeaderBlock trailers;
  trailers["bar"] = "foo";
  if (!version_.HasIetfQuicFrames()) {
    trailers[quic::kFinalOffsetHeaderKey] = base::NumberToString(strlen(data));
  }

  auto t = ProcessTrailers(trailers);

  TestCompletionCallback trailers_callback;
  EXPECT_EQ(
      static_cast<int>(t.uncompressed_header_bytes()),
      handle_->ReadTrailingHeaders(&trailers_, trailers_callback.callback()));

  // Read the body and verify that it arrives correctly.
  EXPECT_EQ(0,
            handle_->ReadBody(buffer.get(), 2 * data_len, callback.callback()));

  // Make sure quic::kFinalOffsetHeaderKey is gone from the delivered actual
  // trailers.
  trailers.erase(quic::kFinalOffsetHeaderKey);
  EXPECT_EQ(trailers, trailers_);
  base::RunLoop().RunUntilIdle();
}

// Tests that trailers are marked as consumed only before delegate is to be
// immediately notified about trailers.
TEST_P(QuicChromiumClientStreamTest, MarkTrailersConsumedWhenNotifyDelegate) {
  InitializeHeaders();
  ProcessHeadersFull(headers_);

  const char data[] = "hello world!";
  int data_len = strlen(data);
  size_t offset = 0;
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(data_len);
    stream_->OnStreamFrame(quic::QuicStreamFrame(
        quic::test::GetNthClientInitiatedBidirectionalStreamId(
            version_.transport_version, 0),
        /*fin=*/false,
        /*offset=*/offset, header));
    offset += header.length();
  }
  stream_->OnStreamFrame(quic::QuicStreamFrame(
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      /*fin=*/false,
      /*offset=*/offset, data));

  // Read the body and verify that it arrives correctly.
  TestCompletionCallback callback;
  scoped_refptr<IOBuffer> buffer = base::MakeRefCounted<IOBuffer>(2 * data_len);
  EXPECT_EQ(data_len,
            handle_->ReadBody(buffer.get(), 2 * data_len, callback.callback()));
  EXPECT_EQ(quiche::QuicheStringPiece(data),
            quiche::QuicheStringPiece(buffer->data(), data_len));

  // Read again, and it will be pending.
  EXPECT_THAT(
      handle_->ReadBody(buffer.get(), 2 * data_len, callback.callback()),
      IsError(ERR_IO_PENDING));

  spdy::SpdyHeaderBlock trailers;
  trailers["bar"] = "foo";
  if (!version_.HasIetfQuicFrames()) {
    trailers[quic::kFinalOffsetHeaderKey] = base::NumberToString(strlen(data));
  }
  quic::QuicHeaderList t = ProcessTrailers(trailers);
  EXPECT_FALSE(stream_->IsDoneReading());

  EXPECT_EQ(static_cast<int>(t.uncompressed_header_bytes()),
            handle_->ReadTrailingHeaders(&trailers_, callback.callback()));

  // Read the body and verify that it arrives correctly.
  EXPECT_EQ(0, callback.WaitForResult());

  // Make sure the stream is properly closed since trailers and data are all
  // consumed.
  EXPECT_TRUE(stream_->IsDoneReading());
  // Make sure quic::kFinalOffsetHeaderKey is gone from the delivered actual
  // trailers.
  trailers.erase(quic::kFinalOffsetHeaderKey);
  EXPECT_EQ(trailers, trailers_);

  base::RunLoop().RunUntilIdle();
}

// Test that if Read() is called after response body is read and after trailers
// are received but not yet delivered, Read() will return ERR_IO_PENDING instead
// of 0 (EOF).
TEST_P(QuicChromiumClientStreamTest, ReadAfterTrailersReceivedButNotDelivered) {
  InitializeHeaders();
  ProcessHeadersFull(headers_);

  const char data[] = "hello world!";
  int data_len = strlen(data);
  size_t offset = 0;
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(data_len);
    stream_->OnStreamFrame(quic::QuicStreamFrame(
        quic::test::GetNthClientInitiatedBidirectionalStreamId(
            version_.transport_version, 0),
        /*fin=*/false,
        /*offset=*/offset, header));
    offset += header.length();
  }
  stream_->OnStreamFrame(quic::QuicStreamFrame(
      quic::test::GetNthClientInitiatedBidirectionalStreamId(
          version_.transport_version, 0),
      /*fin=*/false,
      /*offset=*/offset, data));

  // Read the body and verify that it arrives correctly.
  TestCompletionCallback callback;
  scoped_refptr<IOBuffer> buffer = base::MakeRefCounted<IOBuffer>(2 * data_len);
  EXPECT_EQ(data_len,
            handle_->ReadBody(buffer.get(), 2 * data_len, callback.callback()));
  EXPECT_EQ(quiche::QuicheStringPiece(data),
            quiche::QuicheStringPiece(buffer->data(), data_len));

  // Deliver trailers. Delegate notification is posted asynchronously.
  spdy::SpdyHeaderBlock trailers;
  trailers["bar"] = "foo";
  if (!version_.HasIetfQuicFrames()) {
    trailers[quic::kFinalOffsetHeaderKey] = base::NumberToString(strlen(data));
  }

  quic::QuicHeaderList t = ProcessTrailers(trailers);

  EXPECT_FALSE(stream_->IsDoneReading());
  // Read again, it return ERR_IO_PENDING.
  EXPECT_THAT(
      handle_->ReadBody(buffer.get(), 2 * data_len, callback.callback()),
      IsError(ERR_IO_PENDING));

  // Trailers are not delivered
  EXPECT_FALSE(stream_->IsDoneReading());

  TestCompletionCallback callback2;
  EXPECT_EQ(static_cast<int>(t.uncompressed_header_bytes()),
            handle_->ReadTrailingHeaders(&trailers_, callback2.callback()));

  // Read the body and verify that it arrives correctly.
  // OnDataAvailable() should follow right after and Read() will return 0.
  EXPECT_EQ(0, callback.WaitForResult());

  // Make sure the stream is properly closed since trailers and data are all
  // consumed.
  EXPECT_TRUE(stream_->IsDoneReading());

  // Make sure quic::kFinalOffsetHeaderKey is gone from the delivered actual
  // trailers.
  trailers.erase(quic::kFinalOffsetHeaderKey);
  EXPECT_EQ(trailers, trailers_);

  base::RunLoop().RunUntilIdle();
}

TEST_P(QuicChromiumClientStreamTest, WriteStreamData) {
  testing::InSequence seq;
  const char kData1[] = "hello world";
  const size_t kDataLen = base::size(kData1);

  // All data written.
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(kDataLen);
    EXPECT_CALL(session_,
                WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
        .WillOnce(Return(quic::QuicConsumedData(header.length(), false)));
  }
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      .WillOnce(Return(quic::QuicConsumedData(kDataLen, true)));
  TestCompletionCallback callback;
  EXPECT_EQ(
      OK, handle_->WriteStreamData(quiche::QuicheStringPiece(kData1, kDataLen),
                                   true, callback.callback()));
}

TEST_P(QuicChromiumClientStreamTest, WriteStreamDataAsync) {
  testing::InSequence seq;
  const char kData1[] = "hello world";
  const size_t kDataLen = base::size(kData1);

  // No data written.
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      .WillOnce(Return(quic::QuicConsumedData(0, false)));
  TestCompletionCallback callback;
  EXPECT_EQ(ERR_IO_PENDING, handle_->WriteStreamData(
                                quiche::QuicheStringPiece(kData1, kDataLen),
                                true, callback.callback()));
  ASSERT_FALSE(callback.have_result());

  // All data written.
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(kDataLen);
    EXPECT_CALL(session_,
                WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
        .WillOnce(Return(quic::QuicConsumedData(header.length(), false)));
  }
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      .WillOnce(Return(quic::QuicConsumedData(kDataLen, true)));
  stream_->OnCanWrite();
  // Do 2 writes in version 99.
  if (version_.HasIetfQuicFrames()) {
    stream_->OnCanWrite();
  }
  ASSERT_TRUE(callback.have_result());
  EXPECT_THAT(callback.WaitForResult(), IsOk());
}

TEST_P(QuicChromiumClientStreamTest, WritevStreamData) {
  testing::InSequence seq;
  scoped_refptr<StringIOBuffer> buf1 =
      base::MakeRefCounted<StringIOBuffer>("hello world!");
  scoped_refptr<StringIOBuffer> buf2 =
      base::MakeRefCounted<StringIOBuffer>("Just a small payload");

  // All data written.
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(buf1->size());
    EXPECT_CALL(session_,
                WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
        .WillOnce(Return(quic::QuicConsumedData(header.length(), false)));
  }
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      .WillOnce(Return(quic::QuicConsumedData(buf1->size(), false)));
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(buf2->size());
    EXPECT_CALL(session_,
                WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
        .WillOnce(Return(quic::QuicConsumedData(header.length(), false)));
  }
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      .WillOnce(Return(quic::QuicConsumedData(buf2->size(), true)));
  TestCompletionCallback callback;
  EXPECT_EQ(
      OK, handle_->WritevStreamData({buf1, buf2}, {buf1->size(), buf2->size()},
                                    true, callback.callback()));
}

TEST_P(QuicChromiumClientStreamTest, WritevStreamDataAsync) {
  testing::InSequence seq;
  scoped_refptr<StringIOBuffer> buf1 =
      base::MakeRefCounted<StringIOBuffer>("hello world!");
  scoped_refptr<StringIOBuffer> buf2 =
      base::MakeRefCounted<StringIOBuffer>("Just a small payload");

  // Only a part of the data is written.
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(buf1->size());
    EXPECT_CALL(session_,
                WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
        .WillOnce(Return(quic::QuicConsumedData(header.length(), false)));
  }
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      // First piece of data is written.
      .WillOnce(Return(quic::QuicConsumedData(buf1->size(), false)));
  // Second piece of data is queued.
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      .WillOnce(Return(quic::QuicConsumedData(0, false)));
  TestCompletionCallback callback;
  EXPECT_EQ(ERR_IO_PENDING,
            handle_->WritevStreamData({buf1.get(), buf2.get()},
                                      {buf1->size(), buf2->size()}, true,
                                      callback.callback()));
  ASSERT_FALSE(callback.have_result());

  // The second piece of data is written.
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(buf2->size());
    EXPECT_CALL(session_,
                WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
        .WillOnce(Return(quic::QuicConsumedData(header.length(), false)));
  }
  EXPECT_CALL(session_,
              WritevData(stream_->id(), _, _, _, quic::NOT_RETRANSMISSION, _))
      .WillOnce(Return(quic::QuicConsumedData(buf2->size(), true)));
  stream_->OnCanWrite();
  if (version_.HasIetfQuicFrames()) {
    stream_->OnCanWrite();
  }
  ASSERT_TRUE(callback.have_result());
  EXPECT_THAT(callback.WaitForResult(), IsOk());
}

TEST_P(QuicChromiumClientStreamTest, HeadersBeforeHandle) {
  // We don't use stream_ because we want an incoming server push
  // stream.
  quic::QuicStreamId stream_id = GetNthServerInitiatedUnidirectionalStreamId(0);
  QuicChromiumClientStream* stream2 = new QuicChromiumClientStream(
      stream_id, &session_, quic::READ_UNIDIRECTIONAL, NetLogWithSource(),
      TRAFFIC_ANNOTATION_FOR_TESTS);
  session_.ActivateStream(base::WrapUnique(stream2));

  InitializeHeaders();

  // Receive the headers before the delegate is set.
  quic::QuicHeaderList header_list = quic::test::AsHeaderList(headers_);
  stream2->OnStreamHeaderList(true, header_list.uncompressed_header_bytes(),
                              header_list);

  // Now set the delegate and verify that the headers are delivered.
  handle2_ = stream2->CreateHandle();
  TestCompletionCallback callback;
  EXPECT_EQ(static_cast<int>(header_list.uncompressed_header_bytes()),
            handle2_->ReadInitialHeaders(&headers_, callback.callback()));
  EXPECT_EQ(headers_, headers_);
}

TEST_P(QuicChromiumClientStreamTest, HeadersAndDataBeforeHandle) {
  // We don't use stream_ because we want an incoming server push
  // stream.
  quic::QuicStreamId stream_id = GetNthServerInitiatedUnidirectionalStreamId(0);
  QuicChromiumClientStream* stream2 = new QuicChromiumClientStream(
      stream_id, &session_, quic::READ_UNIDIRECTIONAL, NetLogWithSource(),
      TRAFFIC_ANNOTATION_FOR_TESTS);
  session_.ActivateStream(base::WrapUnique(stream2));

  InitializeHeaders();

  // Receive the headers and data before the delegate is set.
  quic::QuicHeaderList header_list = quic::test::AsHeaderList(headers_);
  stream2->OnStreamHeaderList(false, header_list.uncompressed_header_bytes(),
                              header_list);
  const char data[] = "hello world!";

  size_t offset = 0;
  if (version_.HasIetfQuicFrames()) {
    std::string header = ConstructDataHeader(strlen(data));
    stream2->OnStreamFrame(quic::QuicStreamFrame(stream_id,
                                                 /*fin=*/false,
                                                 /*offset=*/offset, header));
    offset += header.length();
  }
  stream2->OnStreamFrame(quic::QuicStreamFrame(stream_id, /*fin=*/false,
                                               /*offset=*/offset, data));

  // Now set the delegate and verify that the headers are delivered, but
  // not the data, which needs to be read explicitly.
  handle2_ = stream2->CreateHandle();
  TestCompletionCallback callback;
  EXPECT_EQ(static_cast<int>(header_list.uncompressed_header_bytes()),
            handle2_->ReadInitialHeaders(&headers_, callback.callback()));
  EXPECT_EQ(headers_, headers_);
  base::RunLoop().RunUntilIdle();

  // Now explicitly read the data.
  int data_len = base::size(data) - 1;
  scoped_refptr<IOBuffer> buffer = base::MakeRefCounted<IOBuffer>(data_len + 1);
  ASSERT_EQ(data_len, stream2->Read(buffer.get(), data_len + 1));
  EXPECT_EQ(quiche::QuicheStringPiece(data),
            quiche::QuicheStringPiece(buffer->data(), data_len));
}

// Regression test for https://crbug.com/1043531.
TEST_P(QuicChromiumClientStreamTest, ResetOnEmptyResponseHeaders) {
  if (!VersionUsesHttp3(version_.transport_version)) {
    // QuicSpdyStream resets itself on empty headers,
    // because it is used to signal that headers were too large.
    EXPECT_CALL(session_,
                SendRstStream(stream_->id(), quic::QUIC_HEADERS_TOO_LARGE, 0));
  }

  const spdy::SpdyHeaderBlock empty_response_headers;
  ProcessHeaders(empty_response_headers);

  if (VersionUsesHttp3(version_.transport_version)) {
    // Empty headers are allowed by QuicSpdyStream,
    // but an error is generated by QuicChromiumClientStream.
    int rv = handle_->ReadInitialHeaders(&headers_, CompletionOnceCallback());
    EXPECT_THAT(rv, IsError(ERR_INVALID_RESPONSE));
  }
}

}  // namespace
}  // namespace test
}  // namespace net


text:
package com.coolweather.app.model;

import com.coolweather.app.util.MyApplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

/**
 * 2016Äê9ÔÂ11ÈÕ13:24:37
 *
 * ÅäÖà ÉèÖÃÀïÃæµÄ¶«Î÷
 *
 * @author XFHY
 *
 * ÅäÖÃÐÅÏ¢ÊDZ£´æµ½SharedPreferencesÎļþÖеÄ
 *
 */
public class Configure {

	/**
	 * ¸üÐÂƵÂÊ
	 */
	private static int UpdateFrequency;

	/**
	 * ÊÇ·ñ¸üÐÂ
	 */
	private static boolean WhetherToUpdate;

	/**
	 * ÉèÖøüÐÂƵÂÊ
	 * @param updateFrequency
	 */
	public static void setUpdateFrequency(int updateFrequency) {
		//µÃµ½SharedPreferencesÎļþ
		SharedPreferences config = MyApplication.getContext()
				.getSharedPreferences("config", Context.MODE_PRIVATE);
		//µÃµ½Editor¶ÔÏó
		Editor editor = config.edit();
		//·â×°Êý¾Ýµ½Editor¶ÔÏóÖÐ
		editor.putInt("update_rate", updateFrequency);
		//Ìá½»Êý¾Ý
		editor.commit();
	}

	/**
	 * ·µ»Ø¸üÐÂƵÂÊ
	 * @return
	 */
	public static int getUpdateFrequency() {
		// µÃµ½SharedPreferencesÎļþ   ÎļþÃû³Æ,´ò¿ª·½Ê½(ÕâÀïÊÇprivate˽ÓÐ)
		SharedPreferences config = MyApplication.getContext()
				.getSharedPreferences("config", Context.MODE_PRIVATE);
		//´ÓSharedPreferencesÎļþÖлñÈ¡¸üÐÂƵÂÊ
		UpdateFrequency = config.getInt("update_rate", 8);
		return UpdateFrequency;
	}

	/**
	 * ÉèÖÃÊÇ·ñ¸üÐÂ
	 *
	 * @param whetherToUpdate
	 */
	public static void setWhetherToUpdate(boolean whetherToUpdate) {
		// µÃµ½SharedPreferencesÎļþ
		SharedPreferences config = MyApplication.getContext()
				.getSharedPreferences("config", Context.MODE_PRIVATE);
		Editor editor = config.edit();
		editor.putBoolean("whether_to_update", whetherToUpdate);
		editor.commit();
	}

	/**
	 * ·µ»ØÊÇ·ñ¸üÐÂ
	 * @return
	 */
	public static boolean getWhetherToUpdate() {
		SharedPreferences config = MyApplication.getContext()
				.getSharedPreferences("config", Context.MODE_PRIVATE);
		WhetherToUpdate = config.getBoolean("whether_to_update", true);
		return WhetherToUpdate;
	}

}


text:
all:
	cd sources/ && swift build
	sources/.build/debug/HelloWorld

build:
	cd sources/ && swift build

run:
	sources/.build/debug/HelloWorld

clean:
	rm -rf sources/.build/


text:
package org.apache.hadoop.mapred.gridmix;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.mapred.MiniMRClientCluster;
import org.apache.hadoop.mapred.MiniMRClientClusterFactory;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.mapreduce.server.jobtracker.JTConfig;
import org.apache.hadoop.conf.Configuration;

import java.io.IOException;

/**
 * This is a test class.
 */
public class GridmixTestUtils {
  private static final Log LOG = LogFactory.getLog(GridmixTestUtils.class);
  static final Path DEST = new Path("/gridmix");
  static FileSystem dfs = null;
  static MiniDFSCluster dfsCluster = null;
  static MiniMRClientCluster mrvl = null;
  protected static final String GRIDMIX_USE_QUEUE_IN_TRACE =
      "gridmix.job-submission.use-queue-in-trace";
  protected static final String GRIDMIX_DEFAULT_QUEUE =
      "gridmix.job-submission.default-queue";

  public static void initCluster(Class<?> caller) throws IOException {
    Configuration conf = new Configuration();
//    conf.set("mapred.queue.names", "default,q1,q2");
  conf.set("mapred.queue.names", "default");
    conf.set("yarn.scheduler.capacity.root.queues", "default");
    conf.set("yarn.scheduler.capacity.root.default.capacity", "100.0");

    conf.setBoolean(GRIDMIX_USE_QUEUE_IN_TRACE, false);
    conf.set(GRIDMIX_DEFAULT_QUEUE, "default");

    dfsCluster = new MiniDFSCluster.Builder(conf).numDataNodes(1).format(true)
        .build();// MiniDFSCluster(conf, 3, true, null);
    dfs = dfsCluster.getFileSystem();
    conf.set(JTConfig.JT_RETIREJOBS, "false");
    mrvl = MiniMRClientClusterFactory.create(caller, 2, conf,false);

    conf = mrvl.getConfig();
    String[] files = conf.getStrings(MRJobConfig.CACHE_FILES);
    if (files != null) {
      String[] timestamps = new String[files.length];
      for (int i = 0; i < files.length; i++) {
        timestamps[i] = Long.toString(System.currentTimeMillis());
      }
      conf.setStrings(MRJobConfig.CACHE_FILE_TIMESTAMPS, timestamps);
    }

  }

  public static void shutdownCluster() throws IOException {
    if (mrvl != null) {
      mrvl.stop();
    }
    if (dfsCluster != null) {
      dfsCluster.shutdown();
    }
  }

  /**
   * Methods to generate the home directory for dummy users.
   *
   * @param conf
   */
  public static void createHomeAndStagingDirectory(String user,
      Configuration conf) {
    try {
      FileSystem fs = dfsCluster.getFileSystem();
      String path = "/user/" + user;
      Path homeDirectory = new Path(path);
      if (!fs.exists(homeDirectory)) {
        LOG.info("Creating Home directory : " + homeDirectory);
        fs.mkdirs(homeDirectory);
        changePermission(user, homeDirectory, fs);

      }
      changePermission(user, homeDirectory, fs);
      Path stagingArea = new Path(
          conf.get("mapreduce.jobtracker.staging.root.dir",
              "/tmp/hadoop/mapred/staging"));
      LOG.info("Creating Staging root directory : " + stagingArea);
      fs.mkdirs(stagingArea);
      fs.setPermission(stagingArea, new FsPermission((short) 0777));
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }

  static void changePermission(String user, Path homeDirectory, FileSystem fs)
      throws IOException {
    fs.setOwner(homeDirectory, user, "");
  }
}


text:
import argparse
import json
import logging
import multiprocessing
import os
import re

import argparse_extensions
import requests
import six

from . import __version__

_ALBUM_HASH_RE = re.compile(r'^(?:.*/)?([A-Za-z0-9]{5})(?:[/?#].*)?$')
_IMAGES_RE = re.compile(r'"images":(\[.*)')
_TITLE_RE = re.compile(r'"title":"(.*?)","title_clean":')
_TITLE_SANITIZE_RE = re.compile(r'(?:[^ -~]|[/:])+')

def save_image(url, path):
  if os.path.exists(path):
    logging.error('file exists: %s', path)
    return

  try:
    response = requests.get(url)
    response.raise_for_status()
    with open(path, 'wb') as out_file:
      out_file.write(response.content)
    logging.info('saved file: %s', path)
  except (Exception, KeyboardInterrupt):
    logging.exception('could not save file: %s', path)

def save_albums(albums, numbers=False, titles=False):
  raw_decode = json.JSONDecoder().raw_decode
  unescape = six.moves.html_parser.HTMLParser().unescape
  pool = multiprocessing.Pool()

  for album in albums:
    try:
      album_hash = _ALBUM_HASH_RE.search(album).group(1)
      response = requests.get('https://imgur.com/a/%s/all' % album_hash)
      response.raise_for_status()
      images, _ = raw_decode(_IMAGES_RE.search(response.text).group(1))
    except Exception:
      logging.exception('could not read album: %s', album)
      continue

    album_dir = album_hash
    if titles:
      title_match = _TITLE_RE.search(response.text)
      if title_match:
        title = _TITLE_SANITIZE_RE.sub(' ', unescape(title_match.group(1)))
        album_dir = '%s-[%s]' % (album_hash, title)
      else:
        logging.warning('failed to extract album title')

    if not os.path.exists(album_dir):
      logging.info('making directory: %s', album_dir)
      os.makedirs(album_dir)

    for i, image in enumerate(images, start=1):
      orig_name = '%s%s' % (image['hash'], image['ext'])
      url = 'https://i.imgur.com/%s' % orig_name
      filename = ('%d-%s' % (i, orig_name)) if numbers else orig_name
      path = '%s/%s' % (album_dir, filename)
      pool.apply_async(save_image, args=(url, path))

  pool.close()
  pool.join()

def main():
  parser = argparse.ArgumentParser(
      usage='%(prog)s [<options>] [--] <album>...',
      description='Imgur album downloader')

  parser.add_argument(
      'albums',
      nargs='+',
      type=str,
      help='an album hash or URL',
      metavar='<album>')

  parser.add_argument(
      '-n',
      '--numbers',
      action=argparse_extensions.NegatableStoreTrueAction,
      help='prepend numbers to filenames; default: %(default)s')
  parser.add_argument(
      '-t',
      '--titles',
      action=argparse_extensions.NegatableStoreTrueAction,
      help='append album titles to directory names; default: %(default)s')
  parser.add_argument(
      '-v',
      '--version',
      action='version',
      version='%(prog)s ' + __version__)

  args = parser.parse_args()

  logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO)
  logging.getLogger('requests').setLevel(logging.WARNING)

  save_albums(args.albums, numbers=args.numbers, titles=args.titles)

if __name__ == '__main__':
  main()


text:
namespace PRPE.Test.Models {
    public enum StateType {
        Unknown,
        On,
        Off
    }
}


text:
package com.timitoc.groupic.dialogBoxes;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;

/**
 * Created by timi on 17.07.2016.
 */
public class ProposeOfflineUseDialogBox extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Do you want to use the app offline? ");

        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                goOffline();
            }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                ProposeOfflineUseDialogBox.this.getDialog().cancel();
            }
        });
        return builder.create();
    }

    public void goOffline() {

    }
}


text:
import time

def timestamp_ms():
    return int(time.time() * 1000)


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

Page rendered in <?php echo $elapsed_time;?> seconds.


text:
#include "dcgf.h"
#include "BSurface.h"

//////////////////////////////////////////////////////////////////////
CBSurface::CBSurface(CBGame* inGame):CBBase(inGame)
{
	m_ReferenceCount = 0;

	m_Width = m_Height = 0;

	m_Filename = NULL;

	m_PixelOpReady = false;

	m_CKDefault = true;
	m_CKRed = m_CKGreen = m_CKBlue = 0;
	m_LifeTime = 0;
	m_KeepLoaded = false;

	m_LastUsedTime = 0;
	m_Valid = false;
}

//////////////////////////////////////////////////////////////////////
CBSurface::~CBSurface()
{
	if(m_PixelOpReady) EndPixelOp();
	if(m_Filename) delete [] m_Filename;
}

//////////////////////////////////////////////////////////////////////
HRESULT CBSurface::Create(char * Filename, bool default_ck, BYTE ck_red, BYTE ck_green, BYTE ck_blue, int LifeTime, bool KeepLoaded)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////
HRESULT CBSurface::Restore()
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////
bool CBSurface::IsTransparentAt(int X, int Y)
{
	return false;
}

//////////////////////////////////////////////////////////////////////
HRESULT CBSurface::Display(int X, int Y, RECT rect, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////
HRESULT CBSurface::DisplayTrans(int X, int Y, RECT rect, DWORD Alpha, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////
HRESULT CBSurface::DisplayTransOffset(int X, int Y, RECT rect, DWORD Alpha, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY, int offsetX, int offsetY)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////
HRESULT CBSurface::DisplayTransZoom(int X, int Y, RECT rect, float ZoomX, float ZoomY, DWORD Alpha, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////
HRESULT CBSurface::DisplayZoom(int X, int Y, RECT rect, float ZoomX, float ZoomY, DWORD Alpha, bool Transparent, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////
HRESULT CBSurface::DisplayHalfTrans(int X, int Y, RECT rect)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurface::DisplayTransform(int X, int Y, int HotX, int HotY, RECT Rect, float ZoomX, float ZoomY, DWORD Alpha, float Rotate, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return DisplayTransZoom(X, Y, Rect, ZoomX, ZoomY, Alpha, BlendMode, MirrorX, MirrorY);
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurface::Create(int Width, int Height){
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurface::StartPixelOp()
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurface::EndPixelOp()
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurface::GetPixel(int X, int Y, BYTE *R, BYTE *G, BYTE *B, BYTE *A)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurface::PutPixel(int X, int Y, BYTE R, BYTE G, BYTE B, int A)
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////////
bool CBSurface::ComparePixel(int X, int Y, BYTE R, BYTE G, BYTE B, int A)
{
	return false;
}

//////////////////////////////////////////////////////////////////////
bool CBSurface::IsTransparentAtLite(int X, int Y)
{
	return false;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurface::Invalidate()
{
	return E_FAIL;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurface::PrepareToDraw()
{
	m_LastUsedTime = Game->m_LiveTimer;

	if(!m_Valid){
		//Game->LOG(0, "Reviving: %s", m_Filename);
		return Create(m_Filename, m_CKDefault, m_CKRed, m_CKGreen, m_CKBlue, m_LifeTime, m_KeepLoaded);
	}
	else return S_OK;
}

//////////////////////////////////////////////////////////////////////////
void CBSurface::SetFilename(char* Filename)
{
	SAFE_DELETE_ARRAY(m_Filename);
	if(!Filename) return;

	m_Filename = new char[strlen(Filename)+1];
	if(m_Filename) strcpy(m_Filename, Filename);
}

//////////////////////////////////////////////////////////////////////////
void CBSurface::SetSize(int Width, int Height)
{
	m_Width = Width;
	m_Height = Height;
}