text:
# Copyright (c) 2015, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import time

from mcrouter.test.MCProcess import Memcached
from mcrouter.test.McrouterTestCase import McrouterTestCase

class TestMcrouterRoutingPrefixAscii(McrouterTestCase):
    config = './mcrouter/test/routing_prefix_test_ascii.json'
    extra_args = []

    def setUp(self):
        # The order here must corresponds to the order of hosts in the .json
        self.allhosts = []
        for i in range(0, 4):
            self.allhosts.append(self.add_server(Memcached()))

    def get_mcrouter(self):
        return self.add_mcrouter(
            self.config, '/a/a/', extra_args=self.extra_args)

    def test_routing_prefix(self):
        mcr = self.get_mcrouter()
        nclusters = len(self.allhosts)

        # first try setting a key to the local cluster
        mcr.set("testkeylocal", "testvalue")
        self.assertEqual(self.allhosts[0].get("testkeylocal"), "testvalue")
        for i in range(1, nclusters):
            self.assertIsNone(self.allhosts[i].get("testkeylocal"))

        mcr.set("/*/*/testkey-routing", "testvalue")
        # /*/*/ is all-fastest, and some requests might complete asynchronously.
        # As a workaround, just wait
        time.sleep(1)

        local = self.allhosts[0].get("testkey-routing", True)
        self.assertEqual(local["value"], "testvalue")
        # make sure the key got set as "/*/*/key"
        for i in range(1, nclusters):
            local = self.allhosts[i].get("/*/*/testkey-routing", True)
            self.assertEqual(local["value"], "testvalue")

class TestMcrouterRoutingPrefixUmbrella(TestMcrouterRoutingPrefixAscii):
    config = './mcrouter/test/routing_prefix_test_umbrella.json'

class TestMcrouterRoutingPrefixOldNaming(TestMcrouterRoutingPrefixAscii):
    config = './mcrouter/test/routing_prefix_test_old_naming.json'

class TestCustomRoutingPrefixes(McrouterTestCase):
    config = './mcrouter/test/routing_prefix_test_custom.json'
    extra_args = []

    def setUp(self):
        self.aa = self.add_server(Memcached())
        self.ab = self.add_server(Memcached())
        self.ba = self.add_server(Memcached())
        self.bb = self.add_server(Memcached())

    def get_mcrouter(self):
        return self.add_mcrouter(
            self.config, '/a/a/', extra_args=self.extra_args)

    def test_custom_routing_prefix(self):
        mcr = self.get_mcrouter()

        key = "/*/a/key"
        value = "value"

        mcr.set(key, value)
        time.sleep(1)
        self.assertEqual(self.aa.get('key'), value)
        self.assertEqual(self.ba.get('key'), value)

        key = "/b*/*/key"
        value = "value2"
        mcr.set(key, value)
        time.sleep(1)
        self.assertEqual(self.ba.get('key'), value)
        self.assertEqual(self.bb.get('key'), value)

        key = "/b/*b*/key"
        value = "value3"
        mcr.set(key, value)
        self.assertEqual(self.bb.get('key'), value)


text:
import md5, time
from xml.dom import minidom
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.web import client
from core.Uusipuu import UusipuuModule

class Module(UusipuuModule):

    def startup(self):
        if 'feeds' not in self.config or \
                type(self.config['feeds']) != type({}):
            self.config['feeds'] = {}

        self.items = {}
        for feed in self.config['feeds']:
            self.items[feed] = []
            self.query_feed(feed)

    def cmd_rssreset51515(self, user, replyto, params):
        name = params.strip()
        for feed in self.items:
            for item in self.items[feed][:]:
                if item['title'] == name:
                    self.items[feed].remove(item)
                    self.chanmsg('Ok, removing an item')
                    return
        self.chanmsg('No items found :(')

    def cmd_rss(self, user, replyto, params):
        pieces = params.strip().split(' ', 1)

        if not len(pieces) or not len(pieces[0]):
            self.chanmsg('Usage: !rss <add|remove|list|refresh> [...]')
            return

        if pieces[0].strip() in \
                ('add', 'remove', 'latest', 'refresh', 'list', 'addfilter',
                'removefilter'):
            mname = 'do_' + pieces[0].strip()
            params = ''
            if len(pieces) >= 2:
                params = pieces[1].strip()
            if hasattr(self, mname):
                getattr(self, mname)(user, params)

    def do_add(self, user, params):
        pieces = params.split()

        if len(pieces) < 2:
            self.chanmsg('Usage !rss add <name> <url>')
            return

        feed, url = pieces[0:2]

        interval = 180
        if len(pieces) == 3:
            interval = int(pieces[2])
        if interval < 120:
            interval = 120

        if feed in self.config['feeds']:
            self.chanmsg('Feed already exists: %s' % feed)
            return

        self.items[feed] = []
        self.config['feeds'][feed] = {
            'url':      url,
            'interval': interval,
            }
        self.save()
        self.chanmsg('Feed %s successfully added' % feed)
        self.query_feed(feed)

    def do_addfilter(self, user, params):
        pieces = params.split(' ', 1)
        if len(pieces) != 2:
            self.chanmsg('Usage !rss addfilter <feed> <string>')
            return
        feed, filter = pieces

        if feed not in self.config['feeds']:
            self.chanmsg('No such feed found')
            return

        self.config['feeds'][feed]['filter'] = filter
        self.save()
        self.chanmsg('Filter added for %s' % feed)

    def do_removefilter(self, user, feed):
        if feed not in self.config['feeds']:
            self.chanmsg('No such feed found')
            return

        if 'filter' in self.config['feeds'][feed]:
            del self.config['feeds'][feed]['filter']

        self.save()
        self.chanmsg('Filter removed from %s' % feed)

    def do_remove(self, user, feed):
        if not feed:
            self.chanmsg('Usage !rss remove <feed>')
            return

        if feed not in self.config['feeds']:
            self.chanmsg('Feed not found: %s' % feed)

        if 'feed_%s' % feed in self.scheduled:
            self.scheduled['feed_%s' % feed].cancel()
            del self.scheduled['feed_%s' % feed]

        del self.config['feeds'][feed]
        self.save()
        self.chanmsg('Feed %s successfully removed' % feed)

    def do_list(self, user, params):
        if not len(self.config['feeds']):
            self.chanmsg('No feeds found')
            return

        l = []
        for feed in self.config['feeds']:
            filter = ''
            if 'filter' in self.config['feeds'][feed]:
                filter = '{%s}' % self.config['feeds'][feed]['filter']
            l.append('%s(%s)[%s]%s' % \
                (feed,
                self.config['feeds'][feed]['interval'],
                self.config['feeds'][feed]['url'],
                filter))
        self.chanmsg(' '.join(l))

    def do_latest(self, user, feed):
        if not feed:
            self.chanmsg('Usage: !rss latest <name>')
            return

        if feed not in self.config['feeds']:
            self.chanmsg('No such feed found')
            return

        if feed not in self.items:
            self.chanmsg('No items found')
            return

        count = 0
        for item in self.items[feed]:
            self.chanmsg('%s %s' % (str(item['title']), str(item['link'])))
            count += 1
            if count == 3:
                break

    def do_refresh(self, user, feed):
        if not feed:
            self.chanmsg('Usage: !rss refresh <name>')
            return

        if feed not in self.config['feeds']:
            self.chanmsg('No such feed found')
            return

        if 'feed_%s' % feed in self.scheduled:
            self.scheduled['feed_%s' % feed].cancel()
            del self.scheduled['feed_%s' % feed]

        self.query_feed(feed)

    @inlineCallbacks
    def query_feed(self, feed):
        url = self.config['feeds'][feed]['url']
        interval = self.config['feeds'][feed]['interval']

        filter = None
        if 'filter' in self.config['feeds'][feed]:
            filter = self.config['feeds'][feed]['filter']

        try:
            data = yield client.getPage(url)
        except:
            self.log('I failed at checking %s' % feed)
            self.scheduled['feed_%s' % feed] = \
                reactor.callLater(interval, self.query_feed, feed)
            return

        try:
            dom = minidom.parseString(data)
        except:
            self.log('XML parse failed (%s)' % feed)
            self.scheduled['feed_%s' % feed] = \
                reactor.callLater(interval, self.query_feed, feed)
            return

        first = False
        if not len(self.items[feed]):
            first = True

        items = dom.getElementsByTagName('item')
        for item in items:
            titleorig = item.getElementsByTagName(
                'title')[0].childNodes[0].nodeValue.encode('UTF-8')
            try:
                title = titleorig.decode('UTF-8').encode('ISO-8859-1')
            except:
                title = titleorig

            link = item.getElementsByTagName(
                'link')[0].childNodes
            if len(link):
                link = link[0].nodeValue
            else:
                link = ''
            link = self.bot.factory.web.urlstorage.addURL(link)

            description = item.getElementsByTagName('description')
            if description:
                description = description[0].childNodes[0].nodeValue
            else:
                description = ''

            guid = item.getElementsByTagName('guid')
            if guid:
                guid = guid[0].childNodes[0].nodeValue
            else:
                guid = md5.md5(title).hexdigest()

            if filter and not (title.lower().count(filter.lower()) or \
                    description.count(filter.lower())):
                continue

            if guid not in [x['guid'] for x in self.items[feed]]:
                # Yes, we now keep every item we've ever seen (in this session)
                # to prevent excess flood when certain rss feeds (devblog)
                # fuck up
                self.items[feed].append({
                    'guid':             guid,
                    'title':            title,
                    'link':             link,
                    'found':            time.time(),
                    })
                if not first:
                    self.log('I would like to announce on %s: %s' % \
                        (feed, guid))
                    self.chanmsg('[%s] %s %s' % (feed, str(title), str(link)))

        self.scheduled['feed_%s' % feed] = \
            reactor.callLater(interval, self.query_feed, feed)

# vim: set et sw=4:

redpajama_set_name: RedPajamaGithub


text:
enum MyEnumType {
    foo, bar
}
var _arr = [{ key: 'foo' }, { key: 'bar' }]
var enumValue = MyEnumType.foo;
var x = _arr.map(o => MyEnumType[o.key] === enumValue); // these are not same type

//// [enumIndexer.js]
var MyEnumType;
(function (MyEnumType) {
    MyEnumType[MyEnumType["foo"] = 0] = "foo";
    MyEnumType[MyEnumType["bar"] = 1] = "bar";
})(MyEnumType || (MyEnumType = {}));
var _arr = [{ key: 'foo' }, { key: 'bar' }];
var enumValue = MyEnumType.foo;
var x = _arr.map(function (o) { return MyEnumType[o.key] === enumValue; }); // these are not same type


text:
using UnityEngine;
using System.Collections;

public class Init_Scene13 : MonoBehaviour
{

	// Use this for initialization
	void Start ()
	{

	}

	// Update is called once per frame
	void Update ()
	{

	}

	void OnGUI ()
	{
		GUILayout.TextArea ("屏幕鼠标侦测世界空间内物体");
	}
}


text:
package org.locationtech.geowave.service;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Produces(MediaType.APPLICATION_JSON)
@Path("/v0")
public interface BaseService {
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("/operation_status")
  public Response operation_status(@QueryParam("id") String id);
}


text:
namespace bookmarks {

// static
bool BookmarkNodeData::ClipboardContainsBookmarks() {
  NOTREACHED();
  return false;
}

void BookmarkNodeData::WriteToClipboard() {
  NOTREACHED();
}

bool BookmarkNodeData::ReadFromClipboard(ui::ClipboardBuffer buffer) {
  NOTREACHED();
  return false;
}

}  // namespace bookmarks


text:
using SharpKit.JavaScript;
namespace Ext
{
    #region ComponentLoader
    /// <inheritdocs />
    ///
    ///
This class is used to load content via Ajax into a <see cref="Ext.Component">Ext.Component</see>. In general
    /// this class will not be instanced directly, rather a loader configuration will be passed to the
    /// constructor of the <see cref="Ext.Component">Ext.Component</see>.

    ///
HTML Renderer

    ///
By default, the content loaded will be processed as raw html. The response text
    /// from the request is taken and added to the component. This can be used in
    /// conjunction with the <see cref="Ext.ComponentLoaderConfig.scripts">scripts</see> option to execute any inline scripts in
    /// the resulting content. Using this renderer has the same effect as passing the
    /// <see cref="Ext.ComponentConfig.html">Ext.Component.html</see> configuration option.

    ///
Data Renderer

    ///
This renderer allows content to be added by using JSON data and a <see cref="Ext.XTemplate">Ext.XTemplate</see>.
    /// The content received from the response is passed to the <see cref="Ext.Component.update">Ext.Component.update</see> method.
    /// This content is run through the attached <see cref="Ext.ComponentConfig.tpl">Ext.Component.tpl</see> and the data is added to
    /// the Component. Using this renderer has the same effect as using the <see cref="Ext.ComponentConfig.data">Ext.Component.data</see>
    /// configuration in conjunction with a <see cref="Ext.ComponentConfig.tpl">Ext.Component.tpl</see>.

    ///
Component Renderer

    ///
This renderer can only be used with a <see cref="Ext.container.Container">Ext.container.Container</see> and subclasses. It allows for
    /// Components to be loaded remotely into a Container. The response is expected to be a single/series of
    /// <see cref="Ext.Component">Ext.Component</see> configuration objects. When the response is received, the data is decoded
    /// and then passed to <see cref="Ext.container.Container.add">Ext.container.Container.add</see>. Using this renderer has the same effect as specifying
    /// the <see cref="Ext.container.ContainerConfig.items">Ext.container.Container.items</see> configuration on a Container.

    ///
Custom Renderer

    ///
A custom function can be passed to handle any other special case, see the <see cref="Ext.ComponentLoaderConfig.renderer">renderer</see> option.

    ///
Example Usage

    ///
var cmp = <see cref="Ext.ExtContext.create">Ext.create</see>('<see cref="Ext.Component">Ext.Component</see>', {
    /// renderTo: <see cref="Ext.ExtContext.getBody">Ext.getBody</see>(),
    /// tpl: '{firstName} - {lastName}',
    /// loader: {
    /// url: 'myPage.php',
    /// renderer: 'data',
    /// params: {
    /// userId: 1
    /// }
    /// }
    /// });
    /// // call the loader manually (or use autoLoad:true instead)
    /// cmp.getLoader().load();
    ///

    ///
    [JsType(JsMode.Prototype, Export=false, OmitOptionalParameters=true)]
    public partial class ComponentLoader : ElementLoader
    {
        public ComponentLoader(ComponentLoaderConfig config){}
        public ComponentLoader(){}
        public ComponentLoader(params object[] args){}
    }
    #endregion
    #region ComponentLoaderConfig
    /// <inheritdocs />
    [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
    public partial class ComponentLoaderConfig : ElementLoaderConfig
    {
        public ComponentLoaderConfig(params object[] args){}
    }
    #endregion
    #region ComponentLoaderEvents
    /// <inheritdocs />
    [JsType(JsMode.Json, Export=false, OmitOptionalParameters=true)]
    public partial class ComponentLoaderEvents : ElementLoaderEvents
    {
        public ComponentLoaderEvents(params object[] args){}
    }
    #endregion
}


text:
Activités

        <?php if(validation_errors()): ?>

<?php echo validation_errors(); ?>

        <?php endif; ?>

Modifier une activité

                <?php echo form_open('activites/addActivite'); ?>

                    Nom
                    <input type="text" class="form-control" name="nom" placeholder="Nom">

                    Description
                    <input type="text" class="form-control" name="description" placeholder="Description">

                    Type
                    <select name="typeActivite" class="form-control">
                        <option value="1">Banquet</option>
                    </select>

                    Date de Début
                    <input type="datetime-local" class="form-control" name="dateDebut">

                    Date de Fin
                    <input type="datetime-local" class="form-control" name="dateFin">

                    <button id="btn_addActivite" type="submit" class="btn btn-primary">Modifier une activité </button>

                <?php echo form_close(); ?>


text:
package om.edu.mec.smartHouseClient;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
import java.io.File;
import java.io.IOException;

public class FireStatusPanel extends Panel{
	// This extends a panel to create a highly cuztomized panel
	//This class is basically the colourful fancy bit of the frame in the middle

	private boolean isActive = false; // if this is true, then there is a fire

	//components for heading
	private Panel heading;
	private Label fireStatusLabel;

	//components for the images
	private Panel imagePanel;
	private BufferedImage img;

	//Status light will be drawn on this panel
	private Panel statusLight;

	//componenets for the status message
	private Panel messagePanel;
	private Label warningMessage;

	public FireStatusPanel(){

		//Layout of the Panel
		setLayout(new GridLayout(4,1));

		//////heading//////////

		fireStatusLabel = new Label("Fire Status");
		fireStatusLabel.setFont(new Font(Font.SANS_SERIF,Font.BOLD,21));
		fireStatusLabel.setAlignment(Label.CENTER);
		fireStatusLabel.setForeground(Color.RED);

		/////image///////////////////

		//get Image from res folder
		try{
			img = ImageIO.read(getClass().getResource("/res/Moltres.png"));
		}
		catch(IOException e){
			System.out.println(e);
		}

		//These three lines will produce a grayscale image.
		//gimg will hold the gray image, and imp will hold the coloured image
		ImageFilter filter = new GrayFilter(true, 50);
		ImageProducer producer = new FilteredImageSource(img.getSource(), filter);
		Image gimg = Toolkit.getDefaultToolkit().createImage(producer);

		//this overrides the paint method in the new panel such that it draws the image based on the size of the panel
		imagePanel = new Panel(){
			public void paint(Graphics g){

				if(isActive){
					//draws coloured image if active else, draw grayscale image
					g.drawImage(img,0,0,getWidth(),getHeight(),null);
				}
				else{
					g.drawImage(gimg,0,0,getWidth(),getHeight(),null);
				}
			}
		};

		/////Status Light/////////////
		statusLight = new Panel(){
			public void paint(Graphics g){
				//draws that circular status "light"
				int r = getHeight()-50; //radius
				int x = getWidth()/2-r/2; //x coordinate
				int y = getHeight()/2-r/2; //y coordinate
				if(isActive){
					//colour is set according to whether the panel is active or not
					g.setColor(Color.RED);
				}
				else{
					g.setColor(Color.GREEN);
				}

				g.fillOval(x,y,r,r);
			}

		};

		////Warning Message//////////////
		//the warning messages are the default values

		warningMessage = new Label("No Fire");
		warningMessage.setFont(new Font(Font.SANS_SERIF,Font.BOLD,18));
		warningMessage.setAlignment(Label.CENTER);
		warningMessage.setForeground(Color.GREEN);

		////Add everything
		add(fireStatusLabel);
		add(imagePanel);
		add(statusLight);
		add(warningMessage);
	}

	void on(){
		//turns the panel on or "Active" this is called if a fire is found
		isActive = true; //changes the state of the class
		statusLight.repaint(); //repaints the "Status light" to reflect the change
		imagePanel.repaint(); //repaints the image to reflect the change
		warningMessage.setForeground(Color.RED); //change colour of status message
		warningMessage.setText("Fire!!!");	//Change the status message string
	}

	void off(){
		//This is the opposite of the above method
		isActive = false;
		statusLight.repaint();
		imagePanel.repaint();
		warningMessage.setForeground(Color.GREEN);
		warningMessage.setText("No Fire");
	}
}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI.Windows.Plugins.Flow;
using System.Collections.Generic;
using System;
using System.Linq;

namespace UnityEngine.UI.Windows.Plugins.Services {

	public interface IServiceBase {

		string GetServiceName();

	};

	public interface IService : IServiceBase {

		bool isActive { set; get; }

		bool IsSupported();

		string GetAuthKey(ServiceItem item);
		AuthKeyPermissions GetAuthPermissions();

		System.Collections.Generic.IEnumerator<byte> Auth(string key, ServiceItem serviceItem);

		#if UNITY_EDITOR
		void OnEditorAuth(string key, System.Action<bool> onResult);
		void OnEditorDisconnect(System.Action<bool> onResult);
		void DrawInspectorGUI(ScriptableObject settings, ServiceItem item, System.Action onReset, GUISkin skin);
		#endif

	};

	public abstract class ServiceBase : MonoBehaviour, IService {

		public bool isActive { set; get; }

		public ServiceManagerBase serviceManager;

		public virtual void Awake() {

			if (this.serviceManager == null) return;
			this.serviceManager.Register(this);

		}

		public virtual string GetAuthKey(ServiceItem item) {

			#if UNITY_EDITOR
			if (Application.isPlaying == false) {

				return FlowSystem.GetData().GetAuthKeyEditor();

			} else {

				return FlowSystem.GetData().GetAuthKeyBuild();

			}
			#else
			return FlowSystem.GetData().GetAuthKeyBuild();
			#endif

		}

		public virtual AuthKeyPermissions GetAuthPermissions() {

			return AuthKeyPermissions.None;

		}

		public abstract bool IsSupported();

		public virtual System.Collections.Generic.IEnumerator<byte> Auth(string key, ServiceItem serviceItem) {

			yield return 0;

		}

		public virtual void OnApplicationPause(bool paused) {
		}

		public abstract string GetServiceName();

		#if UNITY_EDITOR
		public virtual void OnEditorAuth(string key, System.Action<bool> onResult) {

			if (onResult != null) onResult.Invoke(false);

		}

		public virtual void OnEditorDisconnect(System.Action<bool> onResult) {

			if (onResult != null) onResult.Invoke(false);

		}

		public void DrawInspectorGUI(ScriptableObject settings, ServiceItem item, System.Action onReset, GUISkin skin) {

			if (FlowSystem.GetData() == null) {

				GUILayout.Label("No Data");
				return;

			}

			++UnityEditor.EditorGUI.indentLevel;
			try {

				if (this.GetAuthPermissions() != AuthKeyPermissions.None && FlowSystem.GetData().IsValidAuthKey() == false) {

					UnityEditor.EditorGUILayout.HelpBox("Authorization Key is not valid.", UnityEditor.MessageType.Error);
					FlowSystem.DrawEditorGetKeyButton(skin);

				} else if (FlowSystem.GetData().IsValidAuthKey(this.GetAuthPermissions()) == false) {

					UnityEditor.EditorGUILayout.HelpBox("You have no permission to use this service.", UnityEditor.MessageType.Warning);
					FlowSystem.DrawEditorGetKeyButton(skin);

				} else {

					this.DoInspectorGUI(settings, item, onReset, skin);

				}

			} catch (UnityException e) {

				Debug.LogException(e);

			}
			--UnityEditor.EditorGUI.indentLevel;

		}

		protected abstract void DoInspectorGUI(ScriptableObject settings, ServiceItem item, System.Action onReset, GUISkin skin);

		public virtual void OnValidate() {

			if (Application.isPlaying == true) return;
			#if UNITY_EDITOR
			if (UnityEditor.EditorApplication.isUpdating == true) return;
			#endif

			if (this.serviceManager == null) this.serviceManager = this.GetComponent<ServiceManagerBase>();

		}
		#endif

	}

}


text:
module Cryptoexchange::Exchanges
  module UpbitIndonesia
    class Market < Cryptoexchange::Models::Market
      NAME = 'upbit_indonesia'
      API_URL = 'https://crix-api-id.upbit.com/v1/crix'

      def self.trade_page_url(args={})
        "https://id.upbit.com/exchange?code=CRIX.UPBIT.#{args[:target].upcase}-#{args[:base].upcase}"
      end
    end
  end
end


text:
package org.springframework.boot.actuate.autoconfigure.health;

import java.util.Collections;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.actuate.endpoint.SecurityContext;
import org.springframework.boot.actuate.health.HealthEndpointGroup;
import org.springframework.boot.actuate.health.HealthEndpointGroups;
import org.springframework.boot.actuate.health.HttpCodeStatusMapper;
import org.springframework.boot.actuate.health.SimpleHttpCodeStatusMapper;
import org.springframework.boot.actuate.health.SimpleStatusAggregator;
import org.springframework.boot.actuate.health.Status;
import org.springframework.boot.actuate.health.StatusAggregator;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link AutoConfiguredHealthEndpointGroups}.
 *
 * @author Phillip Webb
 */
class AutoConfiguredHealthEndpointGroupsTests {

	private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
			.withConfiguration(AutoConfigurations.of(AutoConfiguredHealthEndpointGroupsTestConfiguration.class));

	@Test
	void getPrimaryGroupMatchesAllMembers() {
		this.contextRunner.run((context) -> {
			HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
			HealthEndpointGroup primary = groups.getPrimary();
			assertThat(primary.isMember("a")).isTrue();
			assertThat(primary.isMember("b")).isTrue();
			assertThat(primary.isMember("C")).isTrue();
		});
	}

	@Test
	void getNamesReturnsGroupNames() {
		this.contextRunner.withPropertyValues("management.endpoint.health.group.a.include=*",
				"management.endpoint.health.group.b.include=*").run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					assertThat(groups.getNames()).containsExactlyInAnyOrder("a", "b");
				});
	}

	@Test
	void getGroupWhenGroupExistsReturnsGroup() {
		this.contextRunner.withPropertyValues("management.endpoint.health.group.a.include=*").run((context) -> {
			HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
			HealthEndpointGroup group = groups.get("a");
			assertThat(group).isNotNull();
		});
	}

	@Test
	void getGroupWhenGroupDoesNotExistReturnsNull() {
		this.contextRunner.withPropertyValues("management.endpoint.health.group.a.include=*").run((context) -> {
			HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
			HealthEndpointGroup group = groups.get("b");
			assertThat(group).isNull();
		});
	}

	@Test
	void createWhenNoDefinedBeansAdaptsProperties() {
		this.contextRunner.withPropertyValues("management.endpoint.health.show-components=always",
				"management.endpoint.health.show-details=never", "management.endpoint.health.status.order=up,down",
				"management.endpoint.health.status.http-mapping.down=200").run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					assertThat(primary.showComponents(SecurityContext.NONE)).isTrue();
					assertThat(primary.showDetails(SecurityContext.NONE)).isFalse();
					assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN))
							.isEqualTo(Status.UP);
					assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200);
				});
	}

	@Test
	void createWhenHasStatusAggregatorBeanReturnsInstanceWithAgregatorUsedForAllGroups() {
		this.contextRunner.withUserConfiguration(CustomStatusAggregatorConfiguration.class)
				.withPropertyValues("management.endpoint.health.status.order=up,down",
						"management.endpoint.health.group.a.include=*")
				.run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UNKNOWN);
					assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UNKNOWN);
				});
	}

	@Test
	void createWhenHasStatusAggregatorBeanAndGroupSpecificPropertyReturnsInstanceThatUsesBeanOnlyForUnconfiguredGroups() {
		this.contextRunner.withUserConfiguration(CustomStatusAggregatorConfiguration.class)
				.withPropertyValues("management.endpoint.health.group.a.include=*",
						"management.endpoint.health.group.a.status.order=up,down",
						"management.endpoint.health.group.b.include=*")
				.run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					HealthEndpointGroup groupB = groups.get("b");
					assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UNKNOWN);
					assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UP);
					assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UNKNOWN);
				});
	}

	@Test
	void createWhenHasStatusAggregatorPropertyReturnsInstanceWithPropertyUsedForAllGroups() {
		this.contextRunner.withPropertyValues("management.endpoint.health.status.order=up,down",
				"management.endpoint.health.group.a.include=*").run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN))
							.isEqualTo(Status.UP);
					assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN))
							.isEqualTo(Status.UP);
				});
	}

	@Test
	void createWhenHasStatusAggregatorPropertyAndGroupSpecificPropertyReturnsInstanceWithPropertyUsedForExpectedGroups() {
		this.contextRunner.withPropertyValues("management.endpoint.health.status.order=up,down",
				"management.endpoint.health.group.a.include=*",
				"management.endpoint.health.group.a.status.order=unknown,up,down",
				"management.endpoint.health.group.b.include=*").run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					HealthEndpointGroup groupB = groups.get("b");
					assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UP);
					assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UNKNOWN);
					assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UP);
				});
	}

	@Test
	void createWhenHasStatusAggregatorPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() {
		this.contextRunner.withUserConfiguration(CustomStatusAggregatorGroupAConfiguration.class)
				.withPropertyValues("management.endpoint.health.status.order=up,down",
						"management.endpoint.health.group.a.include=*",
						"management.endpoint.health.group.a.status.order=up,down",
						"management.endpoint.health.group.b.include=*")
				.run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					HealthEndpointGroup groupB = groups.get("b");
					assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UP);
					assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UNKNOWN);
					assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UP);
				});
	}

	@Test
	void createWhenHasGroupSpecificStatusAggregatorPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() {
		this.contextRunner.withUserConfiguration(CustomStatusAggregatorGroupAConfiguration.class)
				.withPropertyValues("management.endpoint.health.group.a.include=*",
						"management.endpoint.health.group.a.status.order=up,down",
						"management.endpoint.health.group.b.include=*",
						"management.endpoint.health.group.b.status.order=up,down")
				.run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					HealthEndpointGroup groupB = groups.get("b");
					assertThat(primary.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.DOWN);
					assertThat(groupA.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UNKNOWN);
					assertThat(groupB.getStatusAggregator().getAggregateStatus(Status.UP, Status.DOWN, Status.UNKNOWN))
							.isEqualTo(Status.UP);
				});
	}

	@Test
	void createWhenHasHttpCodeStatusMapperBeanReturnsInstanceWithMapperUsedForAllGroups() {
		this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperConfiguration.class)
				.withPropertyValues("management.endpoint.health.status.http-mapping.down=201",
						"management.endpoint.health.group.a.include=*")
				.run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200);
					assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200);
				});
	}

	@Test
	void createWhenHasHttpCodeStatusMapperBeanAndGroupSpecificPropertyReturnsInstanceThatUsesBeanOnlyForUnconfiguredGroups() {
		this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperConfiguration.class)
				.withPropertyValues("management.endpoint.health.group.a.include=*",
						"management.endpoint.health.group.a.status.http-mapping.down=201",
						"management.endpoint.health.group.b.include=*")
				.run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					HealthEndpointGroup groupB = groups.get("b");
					assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200);
					assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201);
					assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200);
				});
	}

	@Test
	void createWhenHasHttpCodeStatusMapperPropertyReturnsInstanceWithPropertyUsedForAllGroups() {
		this.contextRunner.withPropertyValues("management.endpoint.health.status.http-mapping.down=201",
				"management.endpoint.health.group.a.include=*").run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201);
					assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201);
				});
	}

	@Test
	void createWhenHasHttpCodeStatusMapperPropertyAndGroupSpecificPropertyReturnsInstanceWithPropertyUsedForExpectedGroups() {
		this.contextRunner.withPropertyValues("management.endpoint.health.status.http-mapping.down=201",
				"management.endpoint.health.group.a.include=*",
				"management.endpoint.health.group.a.status.http-mapping.down=202",
				"management.endpoint.health.group.b.include=*").run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					HealthEndpointGroup groupB = groups.get("b");
					assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201);
					assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(202);
					assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201);
				});
	}

	@Test
	void createWhenHasHttpCodeStatusMapperPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() {
		this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperGroupAConfiguration.class)
				.withPropertyValues("management.endpoint.health.status.http-mapping.down=201",
						"management.endpoint.health.group.a.include=*",
						"management.endpoint.health.group.a.status.http-mapping.down=201",
						"management.endpoint.health.group.b.include=*")
				.run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					HealthEndpointGroup groupB = groups.get("b");
					assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201);
					assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200);
					assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201);
				});
	}

	@Test
	void createWhenHasGroupSpecificHttpCodeStatusMapperPropertyAndGroupQualifiedBeanReturnsInstanceWithBeanUsedForExpectedGroups() {
		this.contextRunner.withUserConfiguration(CustomHttpCodeStatusMapperGroupAConfiguration.class)
				.withPropertyValues("management.endpoint.health.group.a.include=*",
						"management.endpoint.health.group.a.status.http-mapping.down=201",
						"management.endpoint.health.group.b.include=*",
						"management.endpoint.health.group.b.status.http-mapping.down=201")
				.run((context) -> {
					HealthEndpointGroups groups = context.getBean(HealthEndpointGroups.class);
					HealthEndpointGroup primary = groups.getPrimary();
					HealthEndpointGroup groupA = groups.get("a");
					HealthEndpointGroup groupB = groups.get("b");
					assertThat(primary.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(503);
					assertThat(groupA.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(200);
					assertThat(groupB.getHttpCodeStatusMapper().getStatusCode(Status.DOWN)).isEqualTo(201);
				});
	}

	@Configuration(proxyBeanMethods = false)
	@EnableConfigurationProperties(HealthEndpointProperties.class)
	static class AutoConfiguredHealthEndpointGroupsTestConfiguration {

		@Bean
		AutoConfiguredHealthEndpointGroups healthEndpointGroups(ConfigurableApplicationContext applicationContext,
				HealthEndpointProperties properties) {
			return new AutoConfiguredHealthEndpointGroups(applicationContext, properties);
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class CustomStatusAggregatorConfiguration {

		@Bean
		@Primary
		StatusAggregator statusAggregator() {
			return new SimpleStatusAggregator(Status.UNKNOWN, Status.UP, Status.DOWN);
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class CustomStatusAggregatorGroupAConfiguration {

		@Bean
		@Qualifier("a")
		StatusAggregator statusAggregator() {
			return new SimpleStatusAggregator(Status.UNKNOWN, Status.UP, Status.DOWN);
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class CustomHttpCodeStatusMapperConfiguration {

		@Bean
		@Primary
		HttpCodeStatusMapper httpCodeStatusMapper() {
			return new SimpleHttpCodeStatusMapper(Collections.singletonMap(Status.DOWN.getCode(), 200));
		}

	}

	@Configuration(proxyBeanMethods = false)
	static class CustomHttpCodeStatusMapperGroupAConfiguration {

		@Bean
		@Qualifier("a")
		HttpCodeStatusMapper httpCodeStatusMapper() {
			return new SimpleHttpCodeStatusMapper(Collections.singletonMap(Status.DOWN.getCode(), 200));
		}

	}

}


text:
prueva para la web delicia
[visit ami pagina](http://www.delizia.com.bo)


text:
package vtk.edit.editor;

import vtk.repository.Property;
import vtk.util.text.TextUtils;

public class TagsEditPreprocessor implements PropertyEditPreprocessor {

    public String preprocess(String valueString, Property prop) {
        return TextUtils.removeDuplicatesIgnoreCase(valueString, ",");
    }

}


text:
import numpy as np
import pandas as pd
from scipy import interpolate

from tardis.plasma.properties.base import (BasePlasmaProperty,
                                           ProcessingPlasmaProperty)
from tardis.plasma.properties import PhiSahaNebular, PhiSahaLTE

__all__ = ['PreviousElectronDensities', 'PreviousBetaSobolevs',
           'HeliumNLTE']

class PreviousIterationProperty(BasePlasmaProperty):
    def _set_output_value(self, output, value):
        setattr(self, output, value)

    def set_value(self, value):
        assert len(self.outputs) == 1
        self._set_output_value(self.outputs[0], value)

class PreviousElectronDensities(PreviousIterationProperty):
    outputs = ('previous_electron_densities',)

class PreviousBetaSobolevs(PreviousIterationProperty):
    outputs = ('previous_beta_sobolevs',)

class HeliumNLTE(ProcessingPlasmaProperty):
    outputs = ('helium_population',)

    def calculate(self, level_boltzmann_factor, electron_densities,
        ionization_data, beta_rad, g, g_electron, w, t_rad, t_electrons,
        delta, zeta_data, number_density, partition_function):
        helium_population = level_boltzmann_factor.ix[2].copy()
        # He I excited states
        he_one_population = self.calculate_helium_one(g_electron, beta_rad,
            partition_function, ionization_data, level_boltzmann_factor,
            electron_densities, g, w, t_rad, t_electrons)
        helium_population.ix[0].update(he_one_population)
        #He I metastable states
        helium_population.ix[0].ix[1] *= (1 / w)
        helium_population.ix[0].ix[2] *= (1 / w)
        #He I ground state
        helium_population.ix[0].ix[0] = 0.0
        #He II excited states
        he_two_population = level_boltzmann_factor.ix[2,1].mul(
            (g.ix[2,1].ix[0]**(-1)) * (t_electrons / t_rad)**0.5)
        helium_population.ix[1].update(he_two_population)
        #He II ground state
        helium_population.ix[1].ix[0] = 1.0
        #He III states
        helium_population.ix[2].ix[0] = self.calculate_helium_three(t_rad, w,
            zeta_data, t_electrons, delta, g_electron, beta_rad,
            partition_function, ionization_data, electron_densities)
        unnormalised = helium_population.sum()
        normalised = helium_population.mul(number_density.ix[2] / unnormalised)
        helium_population.update(normalised)
        return helium_population

    def calculate_helium_one(self, g_electron, beta_rad, partition_function,
            ionization_data, level_boltzmann_factor, electron_densities, g,
            w, t_rad, t_electron):
        (partition_function_index, ionization_data_index, partition_function,
            ionization_data) = self.filter_with_helium_index(2, 1,
            partition_function, ionization_data)
        phis = (1 / PhiSahaLTE.calculate(g_electron, beta_rad,
            partition_function, ionization_data)) * electron_densities * \
            (1.0/g.ix[2,1,0]) * (1/w) * (t_rad/t_electron)**(0.5)
        return level_boltzmann_factor.ix[2].ix[0].mul(
            pd.DataFrame(phis.ix[2].ix[1].values)[0].transpose())

    def calculate_helium_three(self, t_rad, w, zeta_data, t_electrons, delta,
        g_electron, beta_rad, partition_function, ionization_data,
        electron_densities):
        (partition_function_index, ionization_data_index, partition_function,
            ionization_data) = self.filter_with_helium_index(2, 2,
            partition_function, ionization_data)
        zeta_data = pd.DataFrame(zeta_data.ix[2].ix[2].values,
            columns=ionization_data_index, index=zeta_data.columns).transpose()
        delta = pd.DataFrame(delta.ix[2].ix[2].values,
            columns=ionization_data_index, index=delta.columns).transpose()
        phis = PhiSahaNebular.calculate(t_rad, w,
            zeta_data, t_electrons, delta, g_electron,
            beta_rad, partition_function, ionization_data)
        return (phis * (partition_function.ix[2].ix[1] /
            partition_function.ix[2].ix[2]) * (1 /
            electron_densities)).ix[2].ix[2]

    @staticmethod
    def filter_with_helium_index(atomic_number, ion_number, partition_function,
        ionization_data):
        partition_function_index = pd.MultiIndex.from_tuples([(atomic_number,
            ion_number-1), (atomic_number, ion_number)],
            names=['atomic_number', 'ion_number'])
        ionization_data_index = pd.MultiIndex.from_tuples([(atomic_number,
            ion_number)],
            names=['atomic_number', 'ion_number'])
        partition_function = pd.DataFrame(
            partition_function.ix[atomic_number].ix[
            ion_number-1:ion_number].values,
            index=partition_function_index, columns=partition_function.columns)
        ionization_data = pd.DataFrame(
            ionization_data.ix[atomic_number].ix[ion_number][
            'ionization_energy'], index=ionization_data_index,
            columns=['ionization_energy'])
        return partition_function_index, ionization_data_index,\
               partition_function, ionization_data


text:
// Code generated by Wire protocol buffer compiler, do not edit.
// Source file: google/protobuf/descriptor.proto at 610:1
package com.google.protobuf;

import com.squareup.wire.FieldEncoding;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoAdapter;
import com.squareup.wire.ProtoReader;
import com.squareup.wire.ProtoWriter;
import com.squareup.wire.WireField;
import com.squareup.wire.WireInternal;
import java.io.IOException;
import java.lang.Boolean;
import java.lang.Double;
import java.lang.Long;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import java.util.List;
import okio.ByteString;

/**
 * A message representing a option the parser does not recognize. This only
 * appears in options protos created by the compiler::Parser class.
 * DescriptorPool resolves these when building Descriptor objects. Therefore,
 * options protos in descriptor objects (e.g. returned by Descriptor::options(),
 * or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
 * in them.
 */
public final class UninterpretedOption extends Message<UninterpretedOption, UninterpretedOption.Builder> {
  public static final ProtoAdapter<UninterpretedOption> ADAPTER = new ProtoAdapter_UninterpretedOption();

  private static final long serialVersionUID = 0L;

  public static final String DEFAULT_IDENTIFIER_VALUE = "";

  public static final Long DEFAULT_POSITIVE_INT_VALUE = 0L;

  public static final Long DEFAULT_NEGATIVE_INT_VALUE = 0L;

  public static final Double DEFAULT_DOUBLE_VALUE = 0.0d;

  public static final ByteString DEFAULT_STRING_VALUE = ByteString.EMPTY;

  public static final String DEFAULT_AGGREGATE_VALUE = "";

  @WireField(
      tag = 2,
      adapter = "com.google.protobuf.UninterpretedOption$NamePart#ADAPTER",
      label = WireField.Label.REPEATED
  )
  public final List<NamePart> name;

  /**
   * The value of the uninterpreted option, in whatever type the tokenizer
   * identified it as during parsing. Exactly one of these should be set.
   */
  @WireField(
      tag = 3,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String identifier_value;

  @WireField(
      tag = 4,
      adapter = "com.squareup.wire.ProtoAdapter#UINT64"
  )
  public final Long positive_int_value;

  @WireField(
      tag = 5,
      adapter = "com.squareup.wire.ProtoAdapter#INT64"
  )
  public final Long negative_int_value;

  @WireField(
      tag = 6,
      adapter = "com.squareup.wire.ProtoAdapter#DOUBLE"
  )
  public final Double double_value;

  @WireField(
      tag = 7,
      adapter = "com.squareup.wire.ProtoAdapter#BYTES"
  )
  public final ByteString string_value;

  @WireField(
      tag = 8,
      adapter = "com.squareup.wire.ProtoAdapter#STRING"
  )
  public final String aggregate_value;

  public UninterpretedOption(List<NamePart> name, String identifier_value, Long positive_int_value, Long negative_int_value, Double double_value, ByteString string_value, String aggregate_value) {
    this(name, identifier_value, positive_int_value, negative_int_value, double_value, string_value, aggregate_value, ByteString.EMPTY);
  }

  public UninterpretedOption(List<NamePart> name, String identifier_value, Long positive_int_value, Long negative_int_value, Double double_value, ByteString string_value, String aggregate_value, ByteString unknownFields) {
    super(unknownFields);
    this.name = WireInternal.immutableCopyOf("name", name);
    this.identifier_value = identifier_value;
    this.positive_int_value = positive_int_value;
    this.negative_int_value = negative_int_value;
    this.double_value = double_value;
    this.string_value = string_value;
    this.aggregate_value = aggregate_value;
  }

  @Override
  public Builder newBuilder() {
    Builder builder = new Builder();
    builder.name = WireInternal.copyOf("name", name);
    builder.identifier_value = identifier_value;
    builder.positive_int_value = positive_int_value;
    builder.negative_int_value = negative_int_value;
    builder.double_value = double_value;
    builder.string_value = string_value;
    builder.aggregate_value = aggregate_value;
    builder.addUnknownFields(unknownFields());
    return builder;
  }

  @Override
  public boolean equals(Object other) {
    if (other == this) return true;
    if (!(other instanceof UninterpretedOption)) return false;
    UninterpretedOption o = (UninterpretedOption) other;
    return WireInternal.equals(unknownFields(), o.unknownFields())
        && WireInternal.equals(name, o.name)
        && WireInternal.equals(identifier_value, o.identifier_value)
        && WireInternal.equals(positive_int_value, o.positive_int_value)
        && WireInternal.equals(negative_int_value, o.negative_int_value)
        && WireInternal.equals(double_value, o.double_value)
        && WireInternal.equals(string_value, o.string_value)
        && WireInternal.equals(aggregate_value, o.aggregate_value);
  }

  @Override
  public int hashCode() {
    int result = super.hashCode;
    if (result == 0) {
      result = unknownFields().hashCode();
      result = result * 37 + (name != null ? name.hashCode() : 1);
      result = result * 37 + (identifier_value != null ? identifier_value.hashCode() : 0);
      result = result * 37 + (positive_int_value != null ? positive_int_value.hashCode() : 0);
      result = result * 37 + (negative_int_value != null ? negative_int_value.hashCode() : 0);
      result = result * 37 + (double_value != null ? double_value.hashCode() : 0);
      result = result * 37 + (string_value != null ? string_value.hashCode() : 0);
      result = result * 37 + (aggregate_value != null ? aggregate_value.hashCode() : 0);
      super.hashCode = result;
    }
    return result;
  }

  @Override
  public String toString() {
    StringBuilder builder = new StringBuilder();
    if (name != null) builder.append(", name=").append(name);
    if (identifier_value != null) builder.append(", identifier_value=").append(identifier_value);
    if (positive_int_value != null) builder.append(", positive_int_value=").append(positive_int_value);
    if (negative_int_value != null) builder.append(", negative_int_value=").append(negative_int_value);
    if (double_value != null) builder.append(", double_value=").append(double_value);
    if (string_value != null) builder.append(", string_value=").append(string_value);
    if (aggregate_value != null) builder.append(", aggregate_value=").append(aggregate_value);
    return builder.replace(0, 2, "UninterpretedOption{").append('}').toString();
  }

  public static final class Builder extends Message.Builder<UninterpretedOption, Builder> {
    public List<NamePart> name;

    public String identifier_value;

    public Long positive_int_value;

    public Long negative_int_value;

    public Double double_value;

    public ByteString string_value;

    public String aggregate_value;

    public Builder() {
      name = WireInternal.newMutableList();
    }

    public Builder name(List<NamePart> name) {
      WireInternal.checkElementsNotNull(name);
      this.name = name;
      return this;
    }

    /**
     * The value of the uninterpreted option, in whatever type the tokenizer
     * identified it as during parsing. Exactly one of these should be set.
     */
    public Builder identifier_value(String identifier_value) {
      this.identifier_value = identifier_value;
      return this;
    }

    public Builder positive_int_value(Long positive_int_value) {
      this.positive_int_value = positive_int_value;
      return this;
    }

    public Builder negative_int_value(Long negative_int_value) {
      this.negative_int_value = negative_int_value;
      return this;
    }

    public Builder double_value(Double double_value) {
      this.double_value = double_value;
      return this;
    }

    public Builder string_value(ByteString string_value) {
      this.string_value = string_value;
      return this;
    }

    public Builder aggregate_value(String aggregate_value) {
      this.aggregate_value = aggregate_value;
      return this;
    }

    @Override
    public UninterpretedOption build() {
      return new UninterpretedOption(name, identifier_value, positive_int_value, negative_int_value, double_value, string_value, aggregate_value, buildUnknownFields());
    }
  }

  /**
   * The name of the uninterpreted option.  Each string represents a segment in
   * a dot-separated name.  is_extension is true iff a segment represents an
   * extension (denoted with parentheses in options specs in .proto files).
   * E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
   * "foo.(bar.baz).qux".
   */
  public static final class NamePart extends Message<NamePart, NamePart.Builder> {
    public static final ProtoAdapter<NamePart> ADAPTER = new ProtoAdapter_NamePart();

    private static final long serialVersionUID = 0L;

    public static final String DEFAULT_NAME_PART = "";

    public static final Boolean DEFAULT_IS_EXTENSION = false;

    @WireField(
        tag = 1,
        adapter = "com.squareup.wire.ProtoAdapter#STRING",
        label = WireField.Label.REQUIRED
    )
    public final String name_part;

    @WireField(
        tag = 2,
        adapter = "com.squareup.wire.ProtoAdapter#BOOL",
        label = WireField.Label.REQUIRED
    )
    public final Boolean is_extension;

    public NamePart(String name_part, Boolean is_extension) {
      this(name_part, is_extension, ByteString.EMPTY);
    }

    public NamePart(String name_part, Boolean is_extension, ByteString unknownFields) {
      super(unknownFields);
      this.name_part = name_part;
      this.is_extension = is_extension;
    }

    @Override
    public Builder newBuilder() {
      Builder builder = new Builder();
      builder.name_part = name_part;
      builder.is_extension = is_extension;
      builder.addUnknownFields(unknownFields());
      return builder;
    }

    @Override
    public boolean equals(Object other) {
      if (other == this) return true;
      if (!(other instanceof NamePart)) return false;
      NamePart o = (NamePart) other;
      return WireInternal.equals(unknownFields(), o.unknownFields())
          && WireInternal.equals(name_part, o.name_part)
          && WireInternal.equals(is_extension, o.is_extension);
    }

    @Override
    public int hashCode() {
      int result = super.hashCode;
      if (result == 0) {
        result = unknownFields().hashCode();
        result = result * 37 + (name_part != null ? name_part.hashCode() : 0);
        result = result * 37 + (is_extension != null ? is_extension.hashCode() : 0);
        super.hashCode = result;
      }
      return result;
    }

    @Override
    public String toString() {
      StringBuilder builder = new StringBuilder();
      if (name_part != null) builder.append(", name_part=").append(name_part);
      if (is_extension != null) builder.append(", is_extension=").append(is_extension);
      return builder.replace(0, 2, "NamePart{").append('}').toString();
    }

    public static final class Builder extends Message.Builder<NamePart, Builder> {
      public String name_part;

      public Boolean is_extension;

      public Builder() {
      }

      public Builder name_part(String name_part) {
        this.name_part = name_part;
        return this;
      }

      public Builder is_extension(Boolean is_extension) {
        this.is_extension = is_extension;
        return this;
      }

      @Override
      public NamePart build() {
        if (name_part == null
            || is_extension == null) {
          throw WireInternal.missingRequiredFields(name_part, "name_part",
              is_extension, "is_extension");
        }
        return new NamePart(name_part, is_extension, buildUnknownFields());
      }
    }

    private static final class ProtoAdapter_NamePart extends ProtoAdapter<NamePart> {
      ProtoAdapter_NamePart() {
        super(FieldEncoding.LENGTH_DELIMITED, NamePart.class);
      }

      @Override
      public int encodedSize(NamePart value) {
        return ProtoAdapter.STRING.encodedSizeWithTag(1, value.name_part)
            + ProtoAdapter.BOOL.encodedSizeWithTag(2, value.is_extension)
            + value.unknownFields().size();
      }

      @Override
      public void encode(ProtoWriter writer, NamePart value) throws IOException {
        ProtoAdapter.STRING.encodeWithTag(writer, 1, value.name_part);
        ProtoAdapter.BOOL.encodeWithTag(writer, 2, value.is_extension);
        writer.writeBytes(value.unknownFields());
      }

      @Override
      public NamePart decode(ProtoReader reader) throws IOException {
        Builder builder = new Builder();
        long token = reader.beginMessage();
        for (int tag; (tag = reader.nextTag()) != -1;) {
          switch (tag) {
            case 1: builder.name_part(ProtoAdapter.STRING.decode(reader)); break;
            case 2: builder.is_extension(ProtoAdapter.BOOL.decode(reader)); break;
            default: {
              FieldEncoding fieldEncoding = reader.peekFieldEncoding();
              Object value = fieldEncoding.rawProtoAdapter().decode(reader);
              builder.addUnknownField(tag, fieldEncoding, value);
            }
          }
        }
        reader.endMessage(token);
        return builder.build();
      }

      @Override
      public NamePart redact(NamePart value) {
        Builder builder = value.newBuilder();
        builder.clearUnknownFields();
        return builder.build();
      }
    }
  }

  private static final class ProtoAdapter_UninterpretedOption extends ProtoAdapter<UninterpretedOption> {
    ProtoAdapter_UninterpretedOption() {
      super(FieldEncoding.LENGTH_DELIMITED, UninterpretedOption.class);
    }

    @Override
    public int encodedSize(UninterpretedOption value) {
      return NamePart.ADAPTER.asRepeated().encodedSizeWithTag(2, value.name)
          + (value.identifier_value != null ? ProtoAdapter.STRING.encodedSizeWithTag(3, value.identifier_value) : 0)
          + (value.positive_int_value != null ? ProtoAdapter.UINT64.encodedSizeWithTag(4, value.positive_int_value) : 0)
          + (value.negative_int_value != null ? ProtoAdapter.INT64.encodedSizeWithTag(5, value.negative_int_value) : 0)
          + (value.double_value != null ? ProtoAdapter.DOUBLE.encodedSizeWithTag(6, value.double_value) : 0)
          + (value.string_value != null ? ProtoAdapter.BYTES.encodedSizeWithTag(7, value.string_value) : 0)
          + (value.aggregate_value != null ? ProtoAdapter.STRING.encodedSizeWithTag(8, value.aggregate_value) : 0)
          + value.unknownFields().size();
    }

    @Override
    public void encode(ProtoWriter writer, UninterpretedOption value) throws IOException {
      if (value.name != null) NamePart.ADAPTER.asRepeated().encodeWithTag(writer, 2, value.name);
      if (value.identifier_value != null) ProtoAdapter.STRING.encodeWithTag(writer, 3, value.identifier_value);
      if (value.positive_int_value != null) ProtoAdapter.UINT64.encodeWithTag(writer, 4, value.positive_int_value);
      if (value.negative_int_value != null) ProtoAdapter.INT64.encodeWithTag(writer, 5, value.negative_int_value);
      if (value.double_value != null) ProtoAdapter.DOUBLE.encodeWithTag(writer, 6, value.double_value);
      if (value.string_value != null) ProtoAdapter.BYTES.encodeWithTag(writer, 7, value.string_value);
      if (value.aggregate_value != null) ProtoAdapter.STRING.encodeWithTag(writer, 8, value.aggregate_value);
      writer.writeBytes(value.unknownFields());
    }

    @Override
    public UninterpretedOption decode(ProtoReader reader) throws IOException {
      Builder builder = new Builder();
      long token = reader.beginMessage();
      for (int tag; (tag = reader.nextTag()) != -1;) {
        switch (tag) {
          case 2: builder.name.add(NamePart.ADAPTER.decode(reader)); break;
          case 3: builder.identifier_value(ProtoAdapter.STRING.decode(reader)); break;
          case 4: builder.positive_int_value(ProtoAdapter.UINT64.decode(reader)); break;
          case 5: builder.negative_int_value(ProtoAdapter.INT64.decode(reader)); break;
          case 6: builder.double_value(ProtoAdapter.DOUBLE.decode(reader)); break;
          case 7: builder.string_value(ProtoAdapter.BYTES.decode(reader)); break;
          case 8: builder.aggregate_value(ProtoAdapter.STRING.decode(reader)); break;
          default: {
            FieldEncoding fieldEncoding = reader.peekFieldEncoding();
            Object value = fieldEncoding.rawProtoAdapter().decode(reader);
            builder.addUnknownField(tag, fieldEncoding, value);
          }
        }
      }
      reader.endMessage(token);
      return builder.build();
    }

    @Override
    public UninterpretedOption redact(UninterpretedOption value) {
      Builder builder = value.newBuilder();
      WireInternal.redactElements(builder.name, NamePart.ADAPTER);
      builder.clearUnknownFields();
      return builder.build();
    }
  }
}


text:
/**
 * This file is mostly for the TypeScript declaration and not the behavior
 * If this file does not type check, mocha will refuse to start test
 */

import { expect } from 'chai';
/// <reference types="node" />

import * as libtidy from '../';

describe('index.d.ts', () => {
  const testDoc1 = Buffer.from('<!DOCTYPE html>\n\n' +
    '
foo
');

  let doc: libtidy.TidyDoc;

  beforeEach(() => {
    doc = libtidy.TidyDoc();
  });

  it("has sync tidy API", () => {
    // not actually calling the API
    if (1) return;

    doc.parseBufferSync(testDoc1);
    var res = doc.cleanAndRepairSync();
    const diag: string = doc.runDiagnosticsSync();
    const buf: Buffer = doc.saveBufferSync();
  });

  it("has async tidy API", () => {
    if (1) return;

    doc.parseBuffer(testDoc1, dummyCB);
    doc.cleanAndRepair(dummyCB);
    doc.runDiagnostics(dummyCB);
    doc.saveBuffer(dummyCB);
    doc.tidyBuffer(testDoc1, dummyCB);
  });

  it("has option set / get API", () => {
    doc.optSet("alt-text", "foo");
    expect(doc.optGet("alt_text")).to.eq('foo');
    expect(doc.optGet("AltText")).to.eq('foo');

    doc.optSet("wrap", 82);
    expect(doc.optGet("Wrap")).to.eq(82);

    doc.options = {
      wrap: 83,
      input_encoding: "win1252"
    };

    expect(doc.optGet("Wrap")).to.eq(83);
    expect(doc.optGet("input-encoding")).to.eq("win1252");

    expect(doc.getOption('char-encoding'))
      .to.be.instanceof(libtidy.TidyOption);

    // libtidy.TidyOption is not callable with () or new
    // libtidy.TidyOption();
    // new libtidy.TidyOption);
  });
});

function dummyCB(err: Error, result: { errlog: string, output: Buffer }) { }

// vim: shiftwidth=2


text:
layout: article
title: FileStream in chrome
category: chrome
---

FileStream is a basic interface for reading and writing files synchronously or asynchronously with support for seeking to an offset. Generally speaking, we normally use asynchronous mode on a `TYPE_IO` Thread, because it's more effective. Note that even when used asynchronously, only one operation is supported at a time.

## FileStream class declare

{% highlight c++ %}
class NET_EXPORT FileStream {
 public:
  // Creates a |FileStream| with a new |BoundNetLog| (based on |net_log|)
  // attached.  |net_log| may be NULL if no logging is needed.
  // Uses |task_runner| for asynchronous operations.
  FileStream(net::NetLog* net_log,
             const scoped_refptr<base::TaskRunner>& task_runner);

  // |flags| is a bitfield of base::PlatformFileFlags when the file handle was
  // opened.
  FileStream(base::PlatformFile file,
             int flags,
             net::NetLog* net_log,
             const scoped_refptr<base::TaskRunner>& task_runner);

  // The underlying file is closed automatically.
  virtual ~FileStream();

  // Call this method to open the FileStream asynchronously.  The remaining
  // methods cannot be used unless the file is opened successfully. Returns
  // ERR_IO_PENDING if the operation is started. If the operation cannot be
  // started then an error code is returned.
  //
  // Once the operation is done, |callback| will be run on the thread where
  // Open() was called, with the result code. open_flags is a bitfield of
  // base::PlatformFileFlags.
  virtual int Open(const base::FilePath& path, int open_flags,
                   const CompletionCallback& callback);

  // Returns ERR_IO_PENDING and closes the file asynchronously, calling
  // |callback| when done.
  virtual int Close(const CompletionCallback& callback);

  // Closes the file immediately and returns OK. If the file is open
  // asynchronously, Close(const CompletionCallback&) should be used instead.
  virtual int CloseSync();

  // Returns true if Open succeeded and Close has not been called.
  virtual bool IsOpen() const;

  // Adjust the position from where data is read asynchronously.
  // Upon success, ERR_IO_PENDING is returned and |callback| will be run
  // on the thread where Seek() was called with the the stream position
  // relative to the start of the file.  Otherwise, an error code is returned.
  // It is invalid to request any asynchronous operations while there is an
  // in-flight asynchronous operation.
  virtual int Seek(Whence whence, int64 offset,
                   const Int64CompletionCallback& callback);

  // Adjust the position from where data is read synchronously.
  // Upon success, the stream position relative to the start of the file is
  // returned.  Otherwise, an error code is returned.  It is not valid to
  // call SeekSync while a Read call has a pending completion.
  virtual int64 SeekSync(Whence whence, int64 offset);

  // Returns the number of bytes available to read from the current stream
  // position until the end of the file.  Otherwise, an error code is returned.
  virtual int64 Available();

  // Call this method to read data from the current stream position
  // asynchronously. Up to buf_len bytes will be copied into buf.  (In
  // other words, partial reads are allowed.)  Returns the number of bytes
  // copied, 0 if at end-of-file, or an error code if the operation could
  // not be performed.
  //
  // The file must be opened with PLATFORM_FILE_ASYNC, and a non-null
  // callback must be passed to this method. If the read could not
  // complete synchronously, then ERR_IO_PENDING is returned, and the
  // callback will be run on the thread where Read() was called, when the
  // read has completed.
  //
  // It is valid to destroy or close the file stream while there is an
  // asynchronous read in progress.  That will cancel the read and allow
  // the buffer to be freed.
  //
  // This method must not be called if the stream was opened WRITE_ONLY.
  virtual int Read(IOBuffer* buf, int buf_len,
                   const CompletionCallback& callback);

  // Call this method to write data at the current stream position
  // asynchronously.  Up to buf_len bytes will be written from buf. (In
  // other words, partial writes are allowed.)  Returns the number of
  // bytes written, or an error code if the operation could not be
  // performed.
  //
  // The file must be opened with PLATFORM_FILE_ASYNC, and a non-null
  // callback must be passed to this method. If the write could not
  // complete synchronously, then ERR_IO_PENDING is returned, and the
  // callback will be run on the thread where Write() was called when
  // the write has completed.
  virtual int Write(IOBuffer* buf, int buf_len,
                    const CompletionCallback& callback);

  // Call this method to open the FileStream synchronously.
  // If the file stream is not closed manually, the underlying file will be
  // automatically closed when FileStream is destructed.
  virtual int OpenSync(const base::FilePath& path, int open_flags);

  // Call this method to read data from the current stream position
  // synchronously. Up to buf_len bytes will be copied into buf.
  // Returns the number of bytes copied, 0 if at end-of-file,
  // or an error code if the operation could not be performed.
  virtual int ReadSync(char* buf, int buf_len);

  // Performs the same as ReadSync, but ensures that exactly buf_len bytes
  // are copied into buf.  A partial read may occur, but only as a result of
  // end-of-file or fatal error.  Returns the number of bytes copied into buf,
  // 0 if at end-of-file and no bytes have been read into buf yet,
  // or an error code if the operation could not be performed.
  virtual int ReadUntilComplete(char *buf, int buf_len);

  // Call this method to write data at the current stream position
  // synchronously.  Up to buf_len bytes will be written from buf. (In
  // other words, partial writes are allowed.)  Returns the number of
  // bytes written, or an error code if the operation could not be
  // performed.
  //
  // The file must not be opened with PLATFORM_FILE_ASYNC.
  // This method must not be called if the stream was opened READ_ONLY.
  //
  // Zero byte writes are not allowed.
  virtual int WriteSync(const char* buf, int buf_len);

  // Truncates the file to be |bytes| length. This is only valid for writable
  // files. After truncation the file stream is positioned at |bytes|. The new
  // position is returned, or a value < 0 on error.
  // WARNING: one may not truncate a file beyond its current length on any
  //   platform with this call.
  virtual int64 Truncate(int64 bytes);

  // Forces out a filesystem sync on this file to make sure that the file was
  // written out to disk and is not currently sitting in the buffer. This does
  // not have to be called, it just forces one to happen at the time of
  // calling.
  //
  // The file must be opened with PLATFORM_FILE_ASYNC, and a non-null
  // callback must be passed to this method. If the write could not
  // complete synchronously, then ERR_IO_PENDING is returned, and the
  // callback will be run on the thread where Flush() was called when
  // the write has completed.
  //
  // It is valid to destroy or close the file stream while there is an
  // asynchronous flush in progress.  That will cancel the flush and allow
  // the buffer to be freed.
  //
  // It is invalid to request any asynchronous operations while there is an
  // in-flight asynchronous operation.
  //
  // This method should not be called if the stream was opened READ_ONLY.
  virtual int Flush(const CompletionCallback& callback);

  // Forces out a filesystem sync on this file to make sure that the file was
  // written out to disk and is not currently sitting in the buffer. This does
  // not have to be called, it just forces one to happen at the time of
  // calling.
  //
  // Returns an error code if the operation could not be performed.
  //
  // This method should not be called if the stream was opened READ_ONLY.
  virtual int FlushSync();

  // Turns on UMA error statistics gathering.
  void EnableErrorStatistics();

  // Sets the source reference for net-internals logging.
  // Creates source dependency events between |owner_bound_net_log| and
  // |bound_net_log_|.  Each gets an event showing the dependency on the other.
  // If only one of those is valid, it gets an event showing that a change
  // of ownership happened, but without details.
  void SetBoundNetLogSource(const net::BoundNetLog& owner_bound_net_log);

  // Returns the underlying platform file for testing.
  base::PlatformFile GetPlatformFileForTesting();

 private:
  class Context;

  bool is_async() const { return !!(open_flags_ & base::PLATFORM_FILE_ASYNC); }

  int open_flags_;
  net::BoundNetLog bound_net_log_;

  // Context performing I/O operations. It was extracted into separate class
  // to perform asynchronous operations because FileStream can be destroyed
  // before completion of async operation. Also if async FileStream is destroyed
  // without explicit closing file should be closed asynchronously without
  // delaying FileStream's destructor. To perform all that separate object is
  // necessary.
  scoped_ptr<Context> context_;

  DISALLOW_COPY_AND_ASSIGN(FileStream);
};
{% endhighlight %}

## Sample

The example below shows how to use FileStream's APIs asynchronously, helper function `ReadFileAsync` should be used on thread with type TYPE_IO.

{% highlight c++ %}
#include "base/bind.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/task_runner.h"
#include "base/files/file_path.h"

#include "net/base/file_stream.h"
#include "net/base/net_errors.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"

#include <assert.h>
#include <string>

namespace internal {

// File basic info
struct FileBasicInfo
{
  FileBasicInfo() : file_size(0), file_exists(false) {}

  int file_size;
  bool file_exists;
};

// file reader
class FileReader
{
public:
  FileReader( const scoped_refptr<base::TaskRunner>& file_task_runner )
    : file_task_runner_(file_task_runner)
    , stream_(new net::FileStream(NULL, file_task_runner))
    , file_size_(0)
  {
  }

  bool Read( std::wstring const& filePath,
      base::Callback<void(int,std::string)> completeCallback )
  {
    if ( !base::MessageLoop::current() ||
      base::MessageLoop::current()->type() != base::MessageLoop::TYPE_IO )
    {
      assert(false && "MUST called on base::Thread IO message_loop");
      return false;
    }

    file_path_ = base::FilePath(filePath);
    complete_callback_ = completeCallback;

    FileBasicInfo* meta_info = new FileBasicInfo();

    file_task_runner_->PostTaskAndReply( FROM_HERE,
      base::Bind(&FileReader::FetchMetaInfo, file_path_,
        base::Unretained(meta_info)),
      base::Bind(&FileReader::DidFetchMetaInfo,
        base::Unretained(this), base::Owned(meta_info)) );

    return true;
  }

private:
  static void FetchMetaInfo(const base::FilePath& file_path,
      FileBasicInfo* meta_info)
  {
    base::PlatformFileInfo platform_info;
    meta_info->file_exists = file_util::GetFileInfo(file_path, &platform_info);
    if (meta_info->file_exists)
    {
      meta_info->file_size = (int)platform_info.size;
    }
  }

  void DidFetchMetaInfo(const FileBasicInfo* meta_info)
  {
    if (!meta_info->file_exists)
    {
      // file not exist
      DidReadFileFailed(net::ERR_FILE_NOT_FOUND);
      return;
    }

    if ( meta_info->file_size == 0 )
    {
      // empty file
      DidReadFileFailed(net::ERR_FAILED);
      return;
    }
    file_size_ = meta_info->file_size;

    if ( !stream_ )
    {
      stream_.reset( new net::FileStream(NULL, file_task_runner_) );
    }

    int flags = base::PLATFORM_FILE_OPEN |
      base::PLATFORM_FILE_READ |
      base::PLATFORM_FILE_ASYNC;
    int rv = stream_->Open(base::FilePath(file_path_), flags,
      base::Bind(&FileReader::DidOpen, base::Unretained(this)));

    if (rv != net::ERR_IO_PENDING)
      DidOpen(rv);
  }

  void DidOpen(int result)
  {
    if (result != net::OK) {
      // open failed
      DidReadFileFailed(net::ERR_ACCESS_DENIED);
      return;
    }

    read_buffer_ = new net::IOBuffer(file_size_);

    if (file_size_ > 0 )
    {// seek to position 0
      int rv = stream_->Seek(net::FROM_BEGIN, 0,
        base::Bind(&FileReader::DidSeek, base::Unretained(this)));

      if (rv != net::ERR_IO_PENDING) {
        // seek failed
        DidSeek(-1);
      }
    }
  }

  void DidSeek(int64 result)
  {
    if (result != 0)
    {
      // seek failed
      DidReadFileFailed(net::ERR_FAILED);
      return;
    }

    int rv = stream_->Read(read_buffer_.get(), file_size_,
      base::Bind(&FileReader::DidReadFileData, base::Unretained(this)));

    if ( rv >= 0 ) {
      // Data is immediately available.
      DidReadFileData(rv);
      return;
    }
  }

  void DidReadFileData(int result)
  {
    std::string data = std::string(read_buffer_->data(), file_size_);
    complete_callback_.Run( net::OK, data );
  }

  void DidReadFileFailed(int result)
  {
    complete_callback_.Run(result, "");
  }

private:
  const scoped_refptr<base::TaskRunner> file_task_runner_;
  scoped_ptr<net::FileStream> stream_;
  scoped_refptr<net::IOBuffer> read_buffer_;
  base::FilePath file_path_;
  int file_size_;
  base::Callback<void(int,std::string)> complete_callback_;
};

// ReadFileAsyncHelper
class ReadFileAsyncHelper
  : public base::RefCountedThreadSafe<ReadFileAsyncHelper>
{
public:
  ReadFileAsyncHelper(const scoped_refptr<base::TaskRunner>& file_task_runner,
      std::wstring const& filePath,
      base::Callback<void(int,std::string)> completeCallback)
    : file_reader_( new FileReader(file_task_runner) )
    , complete_callback_(completeCallback)
    , file_path_(filePath)
  {
  }

  bool Start()
  {// Reference of this is token by callback to FileReader,
   // which is only released in callback
    return file_reader_->Read(file_path_,
      base::Bind(&ReadFileAsyncHelper::OnReadComplete, this));
  }

private:
  void OnReadComplete( int status, std::string data )
  {
    complete_callback_.Run(status, data);
    delete file_reader_;
    file_reader_ = NULL;
  }

private:
  FileReader * file_reader_;
  std::wstring file_path_;
  base::Callback<void(int,std::string)> complete_callback_;
};

}//namespace internal

// Read file async
// When the file is read, callback will be called on the call thread
inline bool ReadFileAsync(
  const scoped_refptr<base::TaskRunner>& file_task_runner,
  std::wstring const& filePath,
  base::Callback<void(int,std::string)> completeCallback )
{
  scoped_refptr<internal::ReadFileAsyncHelper> readHelper
    = new internal::ReadFileAsyncHelper( file_task_runner,
        filePath, completeCallback );
  return readHelper->Start();
}

{% endhighlight %}


text:
module.exports = function (config) {
    config.set({
        basePath: '.',
        frameworks: ['jasmine'],
        files: [
            'http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js',
            'http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-mocks.js',
            'dist/debug/*.js',
            'test/*.spec.js'
        ],
        exclude: [],
        preprocessors: {
            'dist/debug/*.js': ['coverage']
        },
        reporters: ['spec', 'coverage'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: false,
        browsers: ['Firefox'],
        singleRun: true
    });
};