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

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

import org.flowable.engine.ProcessEngine;
import org.flowable.engine.impl.asyncexecutor.AsyncExecutor;
import org.flowable.engine.impl.asyncexecutor.DefaultAsyncJobExecutor;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.impl.cfg.StandaloneInMemProcessEngineConfiguration;
import org.flowable.engine.impl.test.JobTestHelper;
import org.flowable.engine.runtime.Job;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Tests specifically for the {@link AsyncExecutor}.
 *
 * @author Joram Barrez
 */
public class AsyncExecutorTwoEnginesTest {

    @Test
    public void testAsyncScriptExecutionOnTwoEngines() {

        ProcessEngine firstProcessEngine = null;
        ProcessEngine secondProcessEngine = null;

        try {

            // Deploy
            firstProcessEngine = createProcessEngine(false);
            Date now = setClockToCurrentTime(firstProcessEngine);
            deploy(firstProcessEngine, "AsyncExecutorTest.testAsyncScriptExecution.bpmn20.xml");

            // Start process instance. Nothing should happen
            firstProcessEngine.getRuntimeService().startProcessInstanceByKey("asyncScript");
            Assert.assertEquals(0, firstProcessEngine.getTaskService().createTaskQuery().taskName("Task after script").count());
            Assert.assertEquals(1, firstProcessEngine.getManagementService().createJobQuery().count());

            // Start second engine, with async executor enabled
            secondProcessEngine = createProcessEngine(true, now); // Same timestamp as first engine
            Assert.assertEquals(0, firstProcessEngine.getTaskService().createTaskQuery().taskName("Task after script").count());
            Assert.assertEquals(1, firstProcessEngine.getManagementService().createJobQuery().count());

            // Move the clock 1 second. Should be executed now by second engine
            addSecondsToCurrentTime(secondProcessEngine, 1);
            waitForAllJobsBeingExecuted(secondProcessEngine, 10000L);

            // Verify if all is as expected
            Assert.assertEquals(1, firstProcessEngine.getTaskService().createTaskQuery().taskName("Task after script").count());
            Assert.assertEquals(0, firstProcessEngine.getManagementService().createJobQuery().count());

            Assert.assertEquals(0, getAsyncExecutorJobCount(firstProcessEngine));
            Assert.assertEquals(1, getAsyncExecutorJobCount(secondProcessEngine));

        } finally {

            // Clean up
            cleanup(firstProcessEngine);
            cleanup(secondProcessEngine);

        }

    }

    // Helpers ////////////////////////////////////////////////////////

    private ProcessEngine createProcessEngine(boolean enableAsyncExecutor) {
        return createProcessEngine(enableAsyncExecutor, null);
    }

    private ProcessEngine createProcessEngine(boolean enableAsyncExecutor, Date time) {
        ProcessEngineConfigurationImpl processEngineConfiguration = new StandaloneInMemProcessEngineConfiguration();
        processEngineConfiguration.setJdbcUrl("jdbc:h2:mem:activiti-AsyncExecutorTest;DB_CLOSE_DELAY=1000");
        processEngineConfiguration.setDatabaseSchemaUpdate("true");

        if (enableAsyncExecutor) {
            processEngineConfiguration.setAsyncExecutorActivate(true);

            CountingAsyncExecutor countingAsyncExecutor = new CountingAsyncExecutor();
            countingAsyncExecutor.setDefaultAsyncJobAcquireWaitTimeInMillis(50); // To avoid waiting too long when a retry happens
            countingAsyncExecutor.setDefaultTimerJobAcquireWaitTimeInMillis(50);
            processEngineConfiguration.setAsyncExecutor(countingAsyncExecutor);
        }

        ProcessEngine processEngine = processEngineConfiguration.buildProcessEngine();

        if (time != null) {
            processEngine.getProcessEngineConfiguration().getClock().setCurrentTime(time);
        }

        return processEngine;
    }

    private Date setClockToCurrentTime(ProcessEngine processEngine) {
        Date date = new Date();
        processEngine.getProcessEngineConfiguration().getClock().setCurrentTime(date);
        return date;
    }

    private void addSecondsToCurrentTime(ProcessEngine processEngine, long nrOfSeconds) {
        Date currentTime = processEngine.getProcessEngineConfiguration().getClock().getCurrentTime();
        processEngine.getProcessEngineConfiguration().getClock().setCurrentTime(new Date(currentTime.getTime() + (nrOfSeconds * 1000L)));
    }

    private void cleanup(ProcessEngine processEngine) {
        for (org.flowable.engine.repository.Deployment deployment : processEngine.getRepositoryService().createDeploymentQuery().list()) {
            processEngine.getRepositoryService().deleteDeployment(deployment.getId(), true);
        }
        processEngine.close();
    }

    private String deploy(ProcessEngine processEngine, String resource) {
        return processEngine.getRepositoryService().createDeployment().addClasspathResource("org/flowable/engine/test/jobexecutor/" + resource).deploy().getId();
    }

    private void waitForAllJobsBeingExecuted(ProcessEngine processEngine) {
        waitForAllJobsBeingExecuted(processEngine, 10000L);
    }

    private void waitForAllJobsBeingExecuted(ProcessEngine processEngine, long maxWaitTime) {
        JobTestHelper.waitForJobExecutorToProcessAllJobsAndExecutableTimerJobs(processEngine.getProcessEngineConfiguration(), processEngine.getManagementService(), maxWaitTime, 1000L, false);
    }

    private int getAsyncExecutorJobCount(ProcessEngine processEngine) {
        AsyncExecutor asyncExecutor = processEngine.getProcessEngineConfiguration().getAsyncExecutor();
        if (asyncExecutor instanceof CountingAsyncExecutor) {
            return ((CountingAsyncExecutor) asyncExecutor).getCounter().get();
        }
        return 0;
    }

    static class CountingAsyncExecutor extends DefaultAsyncJobExecutor {

        private static final Logger logger = LoggerFactory.getLogger(CountingAsyncExecutor.class);

        private AtomicInteger counter = new AtomicInteger(0);

        @Override
        public boolean executeAsyncJob(Job job) {
            logger.info("About to execute job {}", job.getId());
            counter.incrementAndGet();
            boolean success = super.executeAsyncJob(job);
            logger.info("Handed off job {} to async executor (retries={})", job.getId(), job.getRetries());
            return success;
        }

        public AtomicInteger getCounter() {
            return counter;
        }

        public void setCounter(AtomicInteger counter) {
            this.counter = counter;
        }

    }

}


text: Testing travis'n'stuff

redpajama_set_name: RedPajamaGithub


text:
'use strict';

//Hists service used to communicate Hists REST endpoints
angular.module('hists').factory('Hists', ['$resource',
	function($resource) {
		return $resource('hists/:histId', { histId: '@_id'
		}, {
			update: {
				method: 'PUT'
			}
		});
	}
]);


text:
module.exports = function(config) {
  config.set({
    autoWatch: false,
    basePath: '..',
    frameworks: ['mocha', 'chai', 'sinon'],
    browsers: ['PhantomJS'],
    singleRun: true,
    preprocessors: {},
    files: [
      'components/javascript-utilities/utilities.js',
      'components/lodash/dist/lodash.js',
      'components/jquery/jquery.js',
      'components/angular/angular.js',
      'components/data-validation/data-validation.js',
      'components/angular-mocks/angular-mocks.js',
      'tests/libraries/mocker.js',
      'module.js',
      'config-provider.js',
      'schema-manager-factory.js',
      'model-factory.js',
      'repository-factory.js',
      'tests/*.js'
    ]
  });
};


text:
body{
	background-image: url("../images/eclipse-bg.png");
  background-repeat: no-repeat;
	font-family:monospace;
}

.accessGranted{
	position:absolute;
	top:200px;
	background:#333;
	padding:20px;
	border:1px solid #999;
	width:300px;
	left:50%;
	margin-left:-150px;
	text-align:center;
}

.accessDenied{
	position:absolute;
	top:200px;
	color:#F00;
	background:#511;
	padding:20px;
	border:1px solid #F00;
	width:300px;
	left:50%;
	margin-left:-150px;
	text-align:center;
}

#header {
    background-color:black;
    color:white;
    text-align:center;
    padding:5px;
}
#nav {
    line-height:30px;
    background-color:#eeeeee;
    height:300px;
    width:100px;
    float:left;
    padding:5px;
}

#console {
    background-color: transparent !important;
    height: 522px;
    overflow: hidden;
    width:660px;
    margin-top:64px;
    padding-left:450px;
}


text:
require('defaultable')(module,
  {
  }, function(module, exports, DEFS, require) {

var lib = require('./lib')
  , util = require('util')
  , couch = require('./couch')
  , events = require('events')
  , assert = require('assert')
  , debug = require('debug')
  , querystring = require('querystring')
  ;

//
// Constants
//

//
// API
//

function Message (opts) {
  var self = this;
  events.EventEmitter.call(self);

  lib.copy(opts, self, 'uppercase');

  self.MessageId   = opts.MessageId   || opts._id  || null;
  self.Body        = opts.MessageBody || opts.Body || opts._str || null;
  self.MD5OfMessageBody = null;
  self.IdExtra     = opts.IdExtra     || null;
  self.queue       = opts.queue       || null;
  self.is_heartbeat= opts.is_heartbeat|| false;
  self.seq         = opts.seq         || null;

  self.log = debug('cqs:message:' + (self.MessageId || 'untitled'));
}
util.inherits(Message, events.EventEmitter);

Message.prototype.assert_received = function assert_received() {
  var self = this;
  assert.ok(self.queue        , 'Message not usable (no queue)');
  assert.ok(self.queue.db     , 'Message not usable (no queue db)');
  assert.ok(self.ReceiptHandle, 'Message not usable (no ReceiptHandle)');
}

Message.prototype.make_doc = function() {
  var self = this;

  var doc = lib.JDUP(self.mvcc || {});
  lib.copy(self, doc, 'uppercase');
  delete doc.MessageId; // _id is used instead
  delete doc.IdExtra;
  delete doc.VisibilityTimeout;
  delete doc.ReceiptHandle;

  return doc;
}

Message.prototype.send = function send_message(cb) {
  var self = this;
  assert.ok(cb);
  assert.ok(self.queue);
  assert.ok(self.queue.db);
  assert.ok(self.queue.db.couch);

  // Take advantage of the couch query to cache the userCtx a.k.a. pre-confirm before this query.
  var db = self.queue.db;
  db.couch.uuid(function(er, uuid) {
    if(er) return cb(er);

    var message_id = self.MessageId || uuid;
    if(typeof self.IdExtra === 'string')
      message_id += '/' + self.IdExtra;

    var doc_id = 'CQS/' + self.queue.name + '/' + message_id
      , sender_id = db.couch.userCtx.name
      , now = new Date
      ;

    // Unlike SQS, but like CouchDB, message bodies are structured (JSON), not just a string blob.
    var doc = { '_id'          : doc_id
              , 'SenderId'     : sender_id
              , 'SentTimestamp': now
              , 'visible_at'   : now
              , 'ApproximateReceiveCount': 0
              , 'ApproximateFirstReceiveTimestamp': null
              , 'Body'         : self.Body
              };

    //self.log = debug('PUT\n' + util.inspect(doc));
    db.request({method:'PUT',uri:lib.enc_id(doc._id), json:doc}, function(er, resp, result) {
      if(er) return cb(er);

      // The send was committed.
      self.MessageId = message_id;
      // TODO: MD5OfMessageBody

      cb(null, self);
    })
  })
}

Message.prototype.update = function update_message(callback) {
  var self = this;
  assert.ok(callback)
  assert.ok(callback);
  assert.ok(self.queue);
  assert.ok(self.queue.db);

  var doc_id = lib.enc_id('CQS/' + self.queue.name + '/' + self.MessageId);
  self.queue.db.request({'uri':doc_id, 'couch_errors':true}, function(er, resp, doc) {
    if(er)
      return callback(er);

    var key;
    if(resp.statusCode === 200)
      lib.copy(doc, self, 'uppercase');
    else {
      // This message was deleted;
      for (key in self)
        if(/^[A-Z]/.test(key))
          delete self[key];
      self.deleted = true;
    }

    // TODO: Detect if visible_at changed and update the alerts.
    return callback(null, self);
  })
}

Message.prototype.receive = function receive_message(callback) {
  var self = this;
  assert.ok(callback);
  assert.ok(self.queue);
  assert.ok(self.queue.db);
  assert.ok(self.queue.db.couch);

  assert.ok(self.mvcc);
  assert.ok(self.mvcc._id);
  assert.ok(new RegExp('/' + self.MessageId + '$').test(self.mvcc._id), lib.JS({_id:self.mvcc._id, ID:self.MessageId}));
  assert.ok('ApproximateReceiveCount'          in self, util.inspect(self));
  assert.ok('ApproximateFirstReceiveTimestamp' in self);

  self.queue.confirmed(function(er) {
    if(er) return callback(er);

    var doc = self.make_doc();
    doc.ReceiverId = self.queue.db.couch.userCtx.name;
    doc.ApproximateReceiveCount += 1;
    if(doc.ApproximateFirstReceiveTimestamp === null)
      doc.ApproximateFirstReceiveTimestamp = new Date;

    var timeout = self.VisibilityTimeout || self.queue.VisibilityTimeout;
    var visible_at = new Date;
    visible_at.setUTCMilliseconds(visible_at.getUTCMilliseconds() + (timeout * 1000));
    doc.visible_at = visible_at;

    var path = lib.enc_id(doc._id)
    self.queue.db.request({method:'PUT', uri:path, json:doc}, function(er, resp, result) {
      if(er) return callback(er);

      if(result.ok !== true)
        return callback(new Error('Bad doc update result: ' + lib.JS(result)));

      // Receive was a success.
      doc._rev = result.rev;
      self.reset(doc, visible_at);
      callback(null, self);
    })
  })
}

Message.prototype.reset = function(doc, new_visible_at) {
  var self = this;

  if(doc && new_visible_at) {
    delete self.mvcc;
    self.import_doc(doc);
    self.visible_at = new_visible_at;
    self.ReceiptHandle = {'_id':doc._id, '_rev':doc._rev};
  }

  self.receive_timers = self.receive_timers || [];
  self.receive_timers.forEach(function(timer) {
    clearTimeout(timer);
  })
  self.receive_timers = [];

  var reset_at = new Date
    , receipt_ms = new_visible_at - reset_at
    , warning_interval_ms, a, warner
    ;

  if(new_visible_at && self.is_heartbeat) {
    for(a = 1; a <= 12; a++) {
      warning_interval_ms = receipt_ms * (a / 12);
      warner = setTimeout(on_warn, warning_interval_ms);
      self.receive_timers.push(warner);
    }
  }

  function on_warn() {
    var interval_at = new Date
      , elapsed_ms = interval_at - reset_at
      , elapsed_pc = 100 * elapsed_ms / receipt_ms
      ;
    self.emit('heartbeat', elapsed_pc);
  }
}

Message.prototype.visibility =
Message.prototype.change_visibility = function (new_time, callback) {
  var self = this;

  assert.ok(callback);
  try        { self.assert_received() }
  catch (er) { return callback(er)    }

  var delta_ms, now = new Date;

  if(typeof new_time === 'number') {
    // Caller requests now + the given seconds.
    delta_ms = new_time * 1000;
    new_time = new Date;
    new_time.setUTCMilliseconds(new_time.getUTCMilliseconds() + delta_ms);
  } else {
    delta_ms = new_time - now;
    if(delta_ms < 0)
      return callback(new Error('Requested change ' + lib.JS(new_time) + ' is too late'));
    if(delta_ms < 2000)
      return callback(new Error('Requested change ' + lib.JS(new_time) + ' is less than 2s from now'));
  }

  self.mvcc = {'_id': self.ReceiptHandle._id, '_rev': self.ReceiptHandle._rev};
  var doc = self.make_doc();
  doc.visible_at = new_time;

  var path = lib.enc_id(doc._id)
  self.queue.db.request({method:'PUT', uri:path, json:doc}, function(er, resp, result) {
    if(er) return callback(er);

    if(result.ok !== true)
      return callback(new Error('Bad doc update result: ' + lib.JS(result)));

    // Update was a success.
    doc._rev = result.rev;
    self.reset(doc, new_time);
    callback(null, self);
  })
}

Message.prototype.del = function message_del(callback) {
  var self = this;

  assert.ok(callback);
  try        { self.assert_received() }
  catch (er) { return callback(er)    }

  var id = self.ReceiptHandle._id;
  var req = { method: 'DELETE'
            , uri   : lib.enc_id(id) + '?rev=' + self.ReceiptHandle._rev
            , headers: {'content-type': 'application/json'}
            }
  self.queue.db.request(req, function(er, resp, result) {
    // Note: delete always returns success.
    if(er)
      self.log = debug('Failed to delete ' + id + ': ' + er.message);

    if(!result || result.ok !== true)
      self.log = debug('Unknown response to delete' + lib.JS(result));

    Object.keys(self).forEach(function (key) {
      if(/^[A-Z]/.test(key))
        delete self[key];
    })

    self.reset();
    return callback(null, self);
  })
}

Message.prototype.import_doc = function(doc) {
  var self = this;

  lib.copy(doc, self, 'uppercase');
}

function change_visibility(opts, VisibilityTimeout, callback) {
  var message;
  if(lib.instanceof(opts, Message))
    message = opts;
  else if(opts.ReceiptHandle)
    return callback(new Error('ReceiptHandle is unsupported, use "Message" instead with message object'));
  else if(opts.Message || opts.message)
    message = opts.Message || opts.message;
  else
    return callback(new Error('Unknown options: ' + lib.JS(opts)));

  return message.change_visibility(VisibilityTimeout, callback);
}

function delete_message(msg, cb) {
  return msg.del(cb);
}

module.exports = { "Message" : Message
                 , "change_visibility"  : change_visibility
                 , "del"     : delete_message
                 };

//
// Utilities
//

}, require) // defaultable


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.srotya.sidewinder</groupId>
    <artifactId>sidewinder-parent</artifactId>
    <version>0.2.14-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>
  <artifactId>dist</artifactId>
  <packaging>pom</packaging>
  <name>sidewinder-dist</name>
  <modules>
    <module>standalone</module>
  </modules>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
</project>


text:
<Title>Boost Graph Library: Dijkstra Visitor</Title>

Dijkstra Visitor Concept

This concept defines the visitor interface for <tt>dijkstra_shortest_paths()</tt>
and related algorithms. The user can create a class that matches this
interface, and then pass objects of the class into
<tt>dijkstra_shortest_paths()</tt> to augment the actions taken during
the search.

Refinement of

Copy Constructible
(copying a visitor should be a lightweight operation).

Notation

<tt>V</tt>
A type that is a model of Dijkstra Visitor.

<tt>vis</tt>
An object of type <tt>V</tt>.

<tt>G</tt>
A type that is a model of Graph.

<tt>g</tt>
An object of type <tt>G</tt>.

<tt>e</tt>
An object of type <tt>boost::graph_traits<G>::edge_descriptor</tt>.

<tt>s,u,v</tt>
An object of type <tt>boost::graph_traits<G>::vertex_descriptor</tt>.

<tt>DistanceMap</tt>
A type that is a model of Read/Write Property Map.

<tt>d</tt>
An object of type <tt>DistanceMap</tt>.

<tt>WeightMap</tt>
A type that is a model of Readable Property Map.

<tt>w</tt>
An object of type <tt>WeightMap</tt>.

Associated Types

none

Valid Expressions

Name	Expression	Return Type	Description

Initialize Vertex
<tt>vis.initialize_vertex(u, g)</tt>
<tt>void</tt>

This is invoked one each vertex of the graph when it is initialized.

Examine Vertex
<tt>vis.examine_vertex(u, g)</tt>
<tt>void</tt>

This is invoked on a vertex as it is popped from the queue. This
happens immediately before <tt>examine_edge()</tt> is invoked
on each of the out-edges of vertex <tt>u</tt>.

Examine Edge
<tt>vis.examine_edge(e, g)</tt>
<tt>void</tt>

This is invoked on every out-edge of each vertex after it is discovered.

Discover Vertex
<tt>vis.discover_vertex(u, g)</tt>
<tt>void</tt>

This is invoked when a vertex is encountered for the first time.

Edge Relaxed
<tt>vis.edge_relaxed(e, g)</tt>
<tt>void</tt>

Upon examination, if the following condition holds then the edge
is relaxed (its distance is reduced), and this method is invoked.

<tt>
tie(u,v) = incident(e, g);

D d_u = get(d, u), d_v = get(d, v);

W w_e = get(w, e);

assert(compare(combine(d_u, w_e), d_v));

</tt>

Edge Not Relaxed
<tt>vis.edge_not_relaxed(e, g)</tt>
<tt>void</tt>

Upon examination, if the edge is not relaxed (see above) then
this method is invoked.

Finish Vertex
<tt>vis.finish_vertex(u, g)</tt>
<tt>void</tt>

This invoked on a vertex after all of its out edges have been added to the
search tree and all of the adjacent vertices have been discovered
(but before their out-edges have been examined).

Models

<tt>dijkstra_visitor</tt>

Python

To implement a model of the <tt>DijkstraVisitor</tt> concept in Python,
create a new class that derives from the <tt>DijkstraVisitor</tt> type of
the graph, which will be
named <tt>GraphType.DijkstraVisitor</tt>. The events and syntax are
the same as with visitors in C++. Here is an example for the
Python <tt>bgl.Graph</tt> graph type:

class count_tree_edges_dijkstra_visitor(bgl.Graph.DijkstraVisitor):
  def __init__(self, name_map):
    bgl.Graph.DijkstraVisitor.__init__(self)
    self.name_map = name_map

  def edge_relaxed(self, e, g):
    (u, v) = (g.source(e), g.target(e))
    print "Relaxed edge ",
    print self.name_map[u],
    print " -> ",
    print self.name_map[v]

Copyright © 2000-2001
Jeremy Siek,
Indiana University (jsiek@osl.iu.edu)

Lie-Quan Lee, Indiana University (llee@cs.indiana.edu)

Andrew Lumsdaine,
Indiana University (lums@osl.iu.edu)


text:
@ECHO OFF
SET version=0.9.3.0
"C:\Program Files (x86)\NuGet\nuget.exe" push Styx.Client.%version%.nupkg
pause


text:
Just another strings library. No serious purposes, but a way to practice and improve my C++ skills.

# Contents

This library aims to implement the most common implementations for the string data structure: A basic data structre in all CS courses, but which implementation is subject of lot of techniques and optimizations to improve its performance on different scenarios.
This techniques are not usually covered by any CS course, despite the fact this are needed to provide enough performance for real world usage.

## Copy On Write string

The usual [copy-on-write idiom](https://en.wikipedia.org/wiki/Copy-on-write) applied to strings. This technique consists in delaying buffer copy (hence allocation) until the "cloned" string requests a write.

I have a simple example of cow strings as a gist [here](https://gist.github.com/Manu343726/02287de75bb24f2cef00), which I wrote for teaching purposes. It was not written with performance in mind (Uses `std::shared_ptr` under the hood for buffer sharing), but to understand the technique.

GNU stdlibc++'s `std::string` was usually built using this technique, but C++11 introduced changes on iterator invalidation requirements preventing using COW.

## Short String Optimization

Consists in adding a static buffer to the string type itself, so when strings are short enough to fit in this buffer, it's used as storage directly, avoiding dynamic memory allocation and improving cache friendliness.

```
template<typename Char>
struct sso_string
{
	TODO ¬¬

private:
	Char* dynamic_buffer_;
	Char static_buffer_[20];
};
```

## Short String Optimization using tagged pointers

Based on [this article](). Due to x86_64 architecture, even if modern processors have 64bit addressing, only 48bits are used for addressing an up to 256TB memory space. This is enough RAM these days, and adding pins and lines to communicate between CPU and RAM takes money.

The idea is to use the remaining 16 higher bits to store data. In my case, `strings::basic_tagged_string` type has a tagged pointer as member with the following layout:

```
On short string mode:

64             63                48                      0
+--------------+-----------------+-----------------------+
|       1      |         5       |        "hello"        |
+--------------+-----------------+-----------------------+
 <------------> <---------------> <--------------------->
  short string    string length           string
      flag

On wide string mode:

64             63                48                      0
+--------------+-----------------+-----------------------+    @0x0ab3211c225f1
|       0      |        11       |    0x0ab3211c225f1    | ------------------> "hello world"
+--------------+-----------------+-----------------------+
 <------------> <---------------> <--------------------->
  short string    string length         pointer to
      flag                                string
```

The string operates in two different modes:

 - **Short**: When the string is short enough, string characters are stored directly in the first 48 bits of the pointer. The pointer becomes no longer a pointer but a container for string data. The next 15 bits store string length (Both in short and wide modes), and MSB acts as a flag to indicate current operating mode (1=short, 0=wide).

 - **Wide**: The string does not fit in the pointer, so usual dynamic memory allocation is done. The buffer address is stored in the pointer.

The implementation starts with a wrapper around a tagged pointer, `strings::detail::tagged_pointer<T>` that provides `::data()`, `address()`, `::pointer()`, etc accessors for easy manipulation of tagged pointer data:

``` cpp
int main()
{
    int i
    strings::detail::tagged_pointer<int> ptr = &i;

    ptr.data() = 0xabcd;
    *ptr = 5;

    std::cout << ptr.data(); // Gives 0xabcd
    std::cout << ptr.address(); // Gives i address (0xWHATEVER)
    std::cout << ptr.pointer(); // Gives pointer to i
    std::cout << i; // Gives 5
}
```

Finally, `strings::detail::tagged_pointer<T>` type is built upon `strings::detail::bitchunk<T>`, an integer wrapper for simple bit access like `std::bitset`, but with manipulation of chunks of bits in mind, instead of individual bits:

``` cpp
int main()
{
    strings::detail::bitchunk<int> i = 0xFFFFF00F;

    i(4,8) = 0xA;
    std::cout << i(0,4);   // Gives 0xF
    std::cout << i(4,8);   // Gives 0xA
    std::cout << i(8,12);  // Gives 0x0
    std::cout << i(12,16); // Gives 0xF
    ...
}
```

`strings::detail::bitchunk<T>` owns the underlying integer by default, but it's designed to act as view of another `bitchunk`s if required. That means you can get "*chunks of chunks of chunks of...". For example:

``` cpp
auto i = strings::detail::make_bitchunk(0x00000F0); // Same as bitchunk<int>{0x0000000F0}

int j = i(16,32)(4,8) = 0xF; // Sets bits [20,24) to 0xF
```

This works great when manipulating data from tagged pointers:

``` cpp
void set_data(tagged_pointer<int>& ptr, unsigned int count, unsigned int tag)
{
    ptr.data()(0,8) = count;
    ptr.data()(8,16) = tag;
}
```

# License

This project is licensed under the terms of the MIT license. See `LICENSE.md` file for more details.


text:
title: "Wordplay: Baby Bounce and Tot Rock Livestream"
description: "Songs and nursery rhymes."
day: Mondays, Wednesdays and Fridays
times: 1030-1100
location: kesgrave-library
location-display-name: Kesgrave Library
location-display-url: /branches/kesgrave-library/
category: children
link: https://www.facebook.com/Kesgravelibrary/
format: live
---


text:
var assert = require('assert')
  , validator = require('../validator')
  , min = require('../validator.min');

describe('Minified version', function () {

    it('should export the same things as the server-side version', function () {
        for (var key in validator) {
            assert.equal(typeof validator[key], typeof min[key], 'Minified version did not export ' + key);
        }
    });

    it('should be up to date', function () {
        assert.equal(min.version, validator.version, 'Minified version mismatch. Run `make min`');
    });

    it('should validate strings', function () {
        assert.equal(min.isEmail('foo@bar.com'), true);
        assert.equal(min.isEmail('foo'), false);
    });

    it('should sanitize strings', function () {
        assert.equal(min.toBoolean('1'), true);
    });

});


text:
require_relative 'spec_helper'

describe 'gradle::default' do
  subject(:chef_run) { ChefSpec::Runner.new.converge described_recipe }

  it { should put_ark('gradle').with(path: '/usr/local', owner: 'root', group: 'root', mode: 0755) }

end


text:
<?php

namespace ZfTable\Decorator\Cell;

use ZfTable\Decorator\Exception;

class Status extends AbstractCellDecorator
{

    /**
     *
     * @var array
     */
    protected $options;

    /**
     * Constructor
     *
     * @param array $options
     */
    public function __construct(array $options = array())
    {
        $this->options = $options;
    }

    /**
     * Rendering decorator
     *
     * @param string $context
     * @return string
     */
    public function render($context)
    {
        if ($context) {
            return "Sim";
        } else {
            return "Não";
        }
    }
}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.Management.Network.Models
{
    public partial class FirewallPolicyRuleGroup : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Name != null)
            {
                writer.WritePropertyName("name");
                writer.WriteStringValue(Name);
            }
            if (Etag != null)
            {
                writer.WritePropertyName("etag");
                writer.WriteStringValue(Etag);
            }
            if (Type != null)
            {
                writer.WritePropertyName("type");
                writer.WriteStringValue(Type);
            }
            if (Id != null)
            {
                writer.WritePropertyName("id");
                writer.WriteStringValue(Id);
            }
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Priority != null)
            {
                writer.WritePropertyName("priority");
                writer.WriteNumberValue(Priority.Value);
            }
            if (Rules != null)
            {
                writer.WritePropertyName("rules");
                writer.WriteStartArray();
                foreach (var item in Rules)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            if (ProvisioningState != null)
            {
                writer.WritePropertyName("provisioningState");
                writer.WriteStringValue(ProvisioningState.Value.ToString());
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static FirewallPolicyRuleGroup DeserializeFirewallPolicyRuleGroup(JsonElement element)
        {
            string name = default;
            string etag = default;
            string type = default;
            string id = default;
            int? priority = default;
            IList<FirewallPolicyRule> rules = default;
            ProvisioningState? provisioningState = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("name"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("etag"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    etag = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    type = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    id = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("priority"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            priority = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("rules"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            List<FirewallPolicyRule> array = new List<FirewallPolicyRule>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                if (item.ValueKind == JsonValueKind.Null)
                                {
                                    array.Add(null);
                                }
                                else
                                {
                                    array.Add(FirewallPolicyRule.DeserializeFirewallPolicyRule(item));
                                }
                            }
                            rules = array;
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                continue;
                            }
                            provisioningState = new ProvisioningState(property0.Value.GetString());
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new FirewallPolicyRuleGroup(id, name, etag, type, priority, rules, provisioningState);
        }
    }
}


text:
'use strict';

const globalModulesDir = require('global-modules');
const yarnGlobalModulesDir = require('yarn-global-modules')();
const addonPath = require.resolve('ember-cli/blueprints/addon/index', {
  paths: [ yarnGlobalModulesDir, globalModulesDir ]
});

const path = require('path');
const Addon = require(addonPath);
const stringUtil = require('ember-cli-string-utils');
const walkSync = require('walk-sync');
const existsSync = require('exists-sync');
const uniq = require('ember-cli-lodash-subset').uniq;
const sortPackageJson = require('sort-package-json');
const fs = require('fs-extra');

const stringifyAndNormalizePath = require.resolve('ember-cli/lib/utilities/stringify-and-normalize', {
  paths: [ yarnGlobalModulesDir, globalModulesDir ]
});
const stringifyAndNormalize = require(stringifyAndNormalizePath);

module.exports = Object.assign({}, Addon, {
  description: 'Creates a stand-alone Engine for Ember.js.',

  locals(options) {
    let superLocals = Addon.locals(...arguments);

    let engineName = options.entity.name;
    let engineModulePrefix = stringUtil.dasherize(engineName);

    return Object.assign(superLocals, {
      engineModulePrefix,
      isLazy: !!options.lazy,
      includeRoutesInApplication: !options.excludeRoutesFromApplication,
      welcome: false
    });
  },

  availableOptions: [
    {
      name: 'type',
      type: [ 'routable', 'routeless' ],
      default: 'routable',
      aliases: [
        { 'routable': 'routable' },
        { 'routeless': 'routeless' }
      ]
    },
    {
      name: 'lazy',
      type: Boolean,
      default: false,
      description: 'Whether this Engine should load lazily or not'
    },
    {
      name: 'exclude-routes-from-application',
      type: Boolean,
      description: 'Whether this Engine should exclude its routes from the applications vendor file or not'
    }
  ],

  install(options) {
    this.options = options;
    return this._super.install.apply(this, arguments);
  },

  uninstall(options) {
    this.options = options;
    return this._super.uninstall.apply(this, arguments);
  },

  filesPath() {
    let type = this._getEngineType();
    return path.join(this.path, "files", type + '-files');
  },

  files() {
    if (this._files) { return this._files; }

    this._appBlueprint = this.lookupBlueprint('app');
    let appFiles = this._appBlueprint.files();

    this._addonBlueprint = this.lookupBlueprint('addon');
    let addonFiles = this._addonBlueprint.files();

    let filesPath = this.filesPath(this.options);
    let engineFiles = [];
    if (existsSync(filesPath)) {
      engineFiles = walkSync(filesPath);
    }

    let files = uniq(appFiles.concat(addonFiles).concat(engineFiles));

    let addonGitKeep = files.indexOf('addon/.gitkeep');
    files.splice(addonGitKeep, 1);

    // Remove app/.gitkeep, engines don't need app directories
    let appGitKeep = files.indexOf('app/.gitkeep');
    files.splice(appGitKeep, 1);

    return this._files = files;
  },

  srcPath(file) {
    let type = this._getEngineType();
    let engineFilePath = path.join(this.path, "files", type + '-files', file);
    let addonFilePath = path.resolve(this._addonBlueprint.path, 'files', file);
    if (existsSync(engineFilePath)) {
      return engineFilePath;
    } else if (existsSync(addonFilePath)) {
      return addonFilePath;
    } else {
      return path.resolve(this._appBlueprint.path, 'files', file);
    }
  },

  updatePackageJson(contents) {
    contents = Addon.updatePackageJson.apply(this, arguments);
    contents = JSON.parse(contents)

    // Add `ember-engines` to devDependencies by default
    contents.devDependencies['ember-engines'] = '^0.8.12';

    return stringifyAndNormalize(sortPackageJson(contents));
  },

  _getEngineType() {
    if (this._engineType) { return this._engineType; }
    return this._engineType = this.options && this.options.type || 'routable';
  },

  afterInstall() {
    let type = this._getEngineType();
    let packagePath = path.join(this.path, 'files', type + '-files', 'package.json');
    let bowerPath = path.join(this.path, 'files', type + '-files', 'bower.json');

    [packagePath, bowerPath].forEach(filePath => {
      fs.removeSync(filePath);
    });
  }

});


text:
module BeachApiCore
  class NotificationMailer < ApplicationMailer

    layout 'notification_mailer'

    def daily_notifications
      @notifications_by_project = params[:notifications_by_project]

      mail from: 'notifications@beach.io',
           to: params[:email],
           subject: 'Daily notifications'
    end
  end
end


text:
package androidx.media2.test.client.tests;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.RatingCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat.QueueItem;
import android.support.v4.media.session.PlaybackStateCompat;

import androidx.media.AudioAttributesCompat;
import androidx.media.VolumeProviderCompat;
import androidx.media2.common.FileMediaItem;
import androidx.media2.common.MediaItem;
import androidx.media2.common.MediaMetadata;
import androidx.media2.common.SessionPlayer;
import androidx.media2.session.HeartRating;
import androidx.media2.session.MediaSession;
import androidx.media2.session.MediaUtils;
import androidx.media2.session.RemoteSessionPlayer;
import androidx.media2.session.ThumbRating;
import androidx.media2.test.client.MediaTestUtils;
import androidx.media2.test.client.RemoteMediaSession;
import androidx.media2.test.common.PollingCheck;
import androidx.media2.test.common.TestUtils;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.FlakyTest;
import androidx.test.filters.LargeTest;
import androidx.test.filters.SdkSuppress;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Tests for {@link MediaControllerCompat.Callback} with {@link MediaSession}.
 */
@SdkSuppress(maxSdkVersion = 32) // b/244312419
@RunWith(AndroidJUnit4.class)
@LargeTest
public class MediaControllerCompatCallbackWithMediaSessionTest extends MediaSessionTestBase {
    private static final String TAG = "MCCCallbackTestWithMS2";

    private static final long TIMEOUT_MS = 1000L;
    private static final float EPSILON = 1e-6f;

    private RemoteMediaSession mSession;
    private MediaControllerCompat mControllerCompat;

    @Before
    @Override
    public void setUp() throws Exception {
        super.setUp();
        mSession = new RemoteMediaSession(TAG, mContext, null);
        mControllerCompat = new MediaControllerCompat(mContext, mSession.getCompatToken());
    }

    @After
    @Override
    public void cleanUp() throws Exception {
        super.cleanUp();
        mSession.close();
    }

    @Test
    public void gettersAfterConnected() throws Exception {
        int testState = SessionPlayer.PLAYER_STATE_PLAYING;
        int testBufferingPosition = 1500;
        float testSpeed = 1.5f;
        List<MediaItem> testPlaylist = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            testPlaylist.add(new MediaItem.Builder()
                    .setMetadata(new MediaMetadata.Builder()
                            .putString(MediaMetadata.METADATA_KEY_MEDIA_ID, "id=" + i)
                            .putRating(MediaMetadata.METADATA_KEY_USER_RATING, new HeartRating())
                            .build())
                    .build());
        }
        int testItemIndex = 0;
        String testPlaylistTitle = "testPlaylistTitle";
        MediaMetadata testPlaylistMetadata = new MediaMetadata.Builder()
                .putText(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, testPlaylistTitle).build();
        int testShuffleMode = SessionPlayer.SHUFFLE_MODE_ALL;
        int testRepeatMode = SessionPlayer.SHUFFLE_MODE_GROUP;

        Bundle playerConfig = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setPlayerState(testState)
                .setBufferedPosition(testBufferingPosition)
                .setPlaybackSpeed(testSpeed)
                .setPlaylist(testPlaylist)
                .setPlaylistMetadata(testPlaylistMetadata)
                .setCurrentMediaItem(testPlaylist.get(testItemIndex))
                .setShuffleMode(testShuffleMode)
                .setRepeatMode(testRepeatMode)
                .build();
        mSession.updatePlayer(playerConfig);

        MediaControllerCompat controller =
                new MediaControllerCompat(mContext, mSession.getCompatToken());
        CountDownLatch latch = new CountDownLatch(1);
        controller.registerCallback(
                new MediaControllerCompat.Callback() {
                    @Override
                    public void onSessionReady() {
                        latch.countDown();
                    }
                }, sHandler);

        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));

        assertEquals(testState, MediaUtils.convertToPlayerState(controller.getPlaybackState()));
        assertEquals(testBufferingPosition, controller.getPlaybackState().getBufferedPosition());
        assertEquals(testSpeed, controller.getPlaybackState().getPlaybackSpeed(), EPSILON);

        assertEquals(testPlaylist.get(testItemIndex).getMediaId(),
                controller.getMetadata().getString(MediaMetadata.METADATA_KEY_MEDIA_ID));

        List<QueueItem> queue = controller.getQueue();
        assertNotNull(queue);
        assertEquals(testPlaylist.size(), queue.size());
        for (int i = 0; i < testPlaylist.size(); i++) {
            assertEquals(testPlaylist.get(i).getMediaId(),
                    queue.get(i).getDescription().getMediaId());
        }
        assertEquals(testPlaylistTitle, controller.getQueueTitle().toString());
        assertEquals(RatingCompat.RATING_HEART, controller.getRatingType());
        assertEquals(testShuffleMode, controller.getShuffleMode());
        assertEquals(testRepeatMode, controller.getRepeatMode());
    }

    @Test
    public void repeatModeChange() throws Exception {
        int testRepeatMode = SessionPlayer.REPEAT_MODE_GROUP;

        CountDownLatch latch = new CountDownLatch(1);
        AtomicInteger repeatModeRef = new AtomicInteger();
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onRepeatModeChanged(int repeatMode) {
                repeatModeRef.set(repeatMode);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().setRepeatMode(testRepeatMode);
        mSession.getMockPlayer().notifyRepeatModeChanged();
        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testRepeatMode, repeatModeRef.get());
        assertEquals(testRepeatMode, mControllerCompat.getRepeatMode());
    }

    @Test
    public void shuffleModeChange() throws Exception {
        int testShuffleMode = SessionPlayer.SHUFFLE_MODE_GROUP;

        CountDownLatch latch = new CountDownLatch(1);
        AtomicInteger shuffleModeRef = new AtomicInteger();
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onShuffleModeChanged(int shuffleMode) {
                shuffleModeRef.set(shuffleMode);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().setShuffleMode(testShuffleMode);
        mSession.getMockPlayer().notifyShuffleModeChanged();
        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testShuffleMode, shuffleModeRef.get());
        assertEquals(testShuffleMode, mControllerCompat.getShuffleMode());
    }

    @Test
    public void close() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onSessionDestroyed() {
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.close();
        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
    }

    @Test
    public void updatePlayer() throws Exception {
        int testState = SessionPlayer.PLAYER_STATE_PLAYING;
        int testBufferingPosition = 1500;
        float testSpeed = 1.5f;
        List<MediaItem> testPlaylist = MediaTestUtils.createFileMediaItems(3);
        int testItemIndex = 0;
        String testPlaylistTitle = "testPlaylistTitle";
        MediaMetadata testPlaylistMetadata = new MediaMetadata.Builder()
                .putText(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, testPlaylistTitle).build();
        int testShuffleMode = SessionPlayer.SHUFFLE_MODE_ALL;
        int testRepeatMode = SessionPlayer.SHUFFLE_MODE_GROUP;

        AtomicReference<PlaybackStateCompat> playbackStateRef = new AtomicReference<>();
        AtomicReference<MediaMetadataCompat> metadataRef = new AtomicReference<>();
        AtomicReference<CharSequence> queueTitleRef = new AtomicReference<>();
        AtomicInteger shuffleModeRef = new AtomicInteger();
        AtomicInteger repeatModeRef = new AtomicInteger();
        CountDownLatch latchForPlaybackState = new CountDownLatch(1);
        CountDownLatch latchForMetadata = new CountDownLatch(1);
        CountDownLatch latchForQueue = new CountDownLatch(2);
        CountDownLatch latchForShuffleMode = new CountDownLatch(1);
        CountDownLatch latchForRepeatMode = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onPlaybackStateChanged(PlaybackStateCompat state) {
                playbackStateRef.set(state);
                latchForPlaybackState.countDown();
            }

            @Override
            public void onMetadataChanged(MediaMetadataCompat metadata) {
                metadataRef.set(metadata);
                latchForMetadata.countDown();
            }

            @Override
            public void onQueueChanged(List<QueueItem> queue) {
                latchForQueue.countDown();
            }

            @Override
            public void onQueueTitleChanged(CharSequence title) {
                queueTitleRef.set(title);
                latchForQueue.countDown();
            }

            @Override
            public void onShuffleModeChanged(int shuffleMode) {
                shuffleModeRef.set(shuffleMode);
                latchForShuffleMode.countDown();
            }

            @Override
            public void onRepeatModeChanged(int repeatMode) {
                repeatModeRef.set(repeatMode);
                latchForRepeatMode.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        Bundle playerConfig = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setPlayerState(testState)
                .setBufferedPosition(testBufferingPosition)
                .setPlaybackSpeed(testSpeed)
                .setPlaylist(testPlaylist)
                .setPlaylistMetadata(testPlaylistMetadata)
                .setCurrentMediaItem(testPlaylist.get(testItemIndex))
                .setShuffleMode(testShuffleMode)
                .setRepeatMode(testRepeatMode)
                .build();
        mSession.updatePlayer(playerConfig);

        assertTrue(latchForPlaybackState.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testState, MediaUtils.convertToPlayerState(playbackStateRef.get()));
        assertEquals(testBufferingPosition, playbackStateRef.get().getBufferedPosition());
        assertEquals(testSpeed, playbackStateRef.get().getPlaybackSpeed(), EPSILON);

        assertTrue(latchForMetadata.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testPlaylist.get(testItemIndex).getMediaId(),
                metadataRef.get().getString(MediaMetadata.METADATA_KEY_MEDIA_ID));

        assertTrue(latchForQueue.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        List<QueueItem> queue = mControllerCompat.getQueue();
        assertNotNull(queue);
        assertEquals(testPlaylist.size(), queue.size());
        for (int i = 0; i < testPlaylist.size(); i++) {
            assertEquals(testPlaylist.get(i).getMediaId(),
                    queue.get(i).getDescription().getMediaId());
        }
        assertEquals(testPlaylistTitle, queueTitleRef.get().toString());

        assertTrue(latchForShuffleMode.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testShuffleMode, shuffleModeRef.get());
        assertTrue(latchForRepeatMode.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testRepeatMode, repeatModeRef.get());
    }

    @Test
    public void updatePlayer_playbackTypeChangedToRemote() throws Exception {
        int controlType = VolumeProviderCompat.VOLUME_CONTROL_ABSOLUTE;
        int maxVolume = 25;
        int currentVolume = 10;

        CountDownLatch playbackInfoNotified = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onAudioInfoChanged(MediaControllerCompat.PlaybackInfo info) {
                if (info.getPlaybackType()
                        == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_REMOTE
                        && info.getVolumeControl() == controlType
                        && info.getMaxVolume() == maxVolume
                        && info.getCurrentVolume() == currentVolume) {
                    playbackInfoNotified.countDown();
                }
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        Bundle playerConfig = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setVolumeControlType(controlType)
                .setMaxVolume(maxVolume)
                .setCurrentVolume(currentVolume)
                .build();
        mSession.updatePlayer(playerConfig);

        assertTrue(playbackInfoNotified.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        MediaControllerCompat.PlaybackInfo info = mControllerCompat.getPlaybackInfo();
        assertEquals(MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_REMOTE,
                info.getPlaybackType());
        assertEquals(controlType, info.getVolumeControl());
        assertEquals(maxVolume, info.getMaxVolume());
        assertEquals(currentVolume, info.getCurrentVolume());
    }

    @Test
    public void updatePlayer_playbackTypeChangedToLocal() throws Exception {
        Bundle playerConfig = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setVolumeControlType(VolumeProviderCompat.VOLUME_CONTROL_ABSOLUTE)
                .setMaxVolume(10)
                .setCurrentVolume(1)
                .build();
        mSession.updatePlayer(playerConfig);

        int legacyStream = AudioManager.STREAM_RING;
        AudioAttributesCompat attrs = new AudioAttributesCompat.Builder()
                .setLegacyStreamType(legacyStream).build();

        CountDownLatch playbackInfoNotified = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onAudioInfoChanged(MediaControllerCompat.PlaybackInfo info) {
                if (info.getPlaybackType() == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_LOCAL
                        && info.getAudioAttributes().getLegacyStreamType() == legacyStream) {
                    playbackInfoNotified.countDown();
                }
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        Bundle playerConfigToUpdate = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setAudioAttributes(attrs)
                .build();
        mSession.updatePlayer(playerConfigToUpdate);

        // In API 21 and 22, onAudioInfoChanged is not called when playback is changed to local.
        if (Build.VERSION.SDK_INT == 21 || Build.VERSION.SDK_INT == 22) {
            PollingCheck.waitFor(TIMEOUT_MS, () -> {
                MediaControllerCompat.PlaybackInfo info = mControllerCompat.getPlaybackInfo();
                return info.getPlaybackType()
                        == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_LOCAL
                        && info.getAudioAttributes().getLegacyStreamType() == legacyStream;
            });
        } else {
            assertTrue(playbackInfoNotified.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
            MediaControllerCompat.PlaybackInfo info = mControllerCompat.getPlaybackInfo();
            assertEquals(MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_LOCAL,
                    info.getPlaybackType());
            assertEquals(legacyStream, info.getAudioAttributes().getLegacyStreamType());
        }
    }

    @Test
    public void updatePlayer_playbackTypeNotChanged_local() throws Exception {
        int legacyStream = AudioManager.STREAM_RING;
        AudioAttributesCompat attrs = new AudioAttributesCompat.Builder()
                .setLegacyStreamType(legacyStream).build();

        CountDownLatch playbackInfoNotified = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onAudioInfoChanged(MediaControllerCompat.PlaybackInfo info) {
                if (info.getPlaybackType() == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_LOCAL
                        && info.getAudioAttributes().getLegacyStreamType() == legacyStream) {
                    playbackInfoNotified.countDown();
                }
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        Bundle playerConfig = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setAudioAttributes(attrs)
                .build();
        mSession.updatePlayer(playerConfig);

        // In API 21+, onAudioInfoChanged() is not called when playbackType is not changed.
        if (Build.VERSION.SDK_INT >= 21) {
            PollingCheck.waitFor(TIMEOUT_MS, () -> {
                MediaControllerCompat.PlaybackInfo info = mControllerCompat.getPlaybackInfo();
                return info.getPlaybackType()
                        == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_LOCAL
                        && info.getAudioAttributes().getLegacyStreamType() == legacyStream;
            });
        } else {
            assertTrue(playbackInfoNotified.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
            MediaControllerCompat.PlaybackInfo info = mControllerCompat.getPlaybackInfo();
            assertEquals(MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_LOCAL,
                    info.getPlaybackType());
            assertEquals(legacyStream, info.getAudioAttributes().getLegacyStreamType());
        }
    }

    @Test
    public void updatePlayer_playbackTypeNotChanged_remote() throws Exception {
        Bundle playerConfig = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setVolumeControlType(VolumeProviderCompat.VOLUME_CONTROL_ABSOLUTE)
                .setMaxVolume(10)
                .setCurrentVolume(1)
                .build();
        mSession.updatePlayer(playerConfig);

        int controlType = VolumeProviderCompat.VOLUME_CONTROL_ABSOLUTE;
        int maxVolume = 25;
        int currentVolume = 1;

        CountDownLatch playbackInfoNotified = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onAudioInfoChanged(MediaControllerCompat.PlaybackInfo info) {
                if (info.getPlaybackType()
                        == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_REMOTE
                        && info.getVolumeControl() == controlType
                        && info.getMaxVolume() == maxVolume
                        && info.getCurrentVolume() == currentVolume) {
                    playbackInfoNotified.countDown();
                }
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        Bundle playerConfigToUpdate = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setVolumeControlType(controlType)
                .setMaxVolume(maxVolume)
                .setCurrentVolume(currentVolume)
                .build();
        mSession.updatePlayer(playerConfigToUpdate);

        // In API 21+, onAudioInfoChanged() is not called when playbackType is not changed.
        if (Build.VERSION.SDK_INT >= 21) {
            PollingCheck.waitFor(TIMEOUT_MS, () -> {
                MediaControllerCompat.PlaybackInfo info = mControllerCompat.getPlaybackInfo();
                return info.getPlaybackType()
                        == MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_REMOTE
                        && info.getVolumeControl() == controlType
                        && info.getMaxVolume() == maxVolume
                        && info.getCurrentVolume() == currentVolume;
            });
        } else {
            assertTrue(playbackInfoNotified.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
            MediaControllerCompat.PlaybackInfo info = mControllerCompat.getPlaybackInfo();
            assertEquals(MediaControllerCompat.PlaybackInfo.PLAYBACK_TYPE_REMOTE,
                    info.getPlaybackType());
            assertEquals(controlType, info.getVolumeControl());
            assertEquals(maxVolume, info.getMaxVolume());
            assertEquals(currentVolume, info.getCurrentVolume());
        }
    }

    @Test
    public void playerStateChange() throws Exception {
        int targetState = SessionPlayer.PLAYER_STATE_PLAYING;

        AtomicReference<PlaybackStateCompat> playbackStateRef = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(2);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onSessionReady() {
                latch.countDown();
            }

            @Override
            public void onPlaybackStateChanged(PlaybackStateCompat state) {
                playbackStateRef.set(state);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().notifyPlayerStateChanged(targetState);
        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(targetState, MediaUtils.convertToPlayerState(playbackStateRef.get()));
        assertEquals(targetState,
                MediaUtils.convertToPlayerState(mControllerCompat.getPlaybackState()));
    }

    @Test
    public void playbackSpeedChange() throws Exception {
        float speed = 1.5f;

        AtomicReference<PlaybackStateCompat> playbackStateRef = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onPlaybackStateChanged(PlaybackStateCompat state) {
                playbackStateRef.set(state);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().setPlaybackSpeed(speed);
        mSession.getMockPlayer().notifyPlaybackSpeedChanged(speed);
        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(speed, playbackStateRef.get().getPlaybackSpeed(), EPSILON);
        assertEquals(speed, mControllerCompat.getPlaybackState().getPlaybackSpeed(), EPSILON);
    }

    @Test
    public void bufferingStateChange() throws Exception {
        List<MediaItem> testPlaylist = MediaTestUtils.createFileMediaItems(3);
        int testItemIndex = 0;
        int testBufferingState = SessionPlayer.BUFFERING_STATE_BUFFERING_AND_PLAYABLE;
        long testBufferingPosition = 500;
        mSession.getMockPlayer().setPlaylistWithFakeItem(testPlaylist);

        AtomicReference<PlaybackStateCompat> playbackStateRef = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onPlaybackStateChanged(PlaybackStateCompat state) {
                playbackStateRef.set(state);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().setBufferedPosition(testBufferingPosition);
        mSession.getMockPlayer().notifyBufferingStateChanged(testItemIndex, testBufferingState);
        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testBufferingPosition, playbackStateRef.get().getBufferedPosition());
        assertEquals(testBufferingPosition,
                mControllerCompat.getPlaybackState().getBufferedPosition());
    }

    @Test
    public void seekComplete() throws Exception {
        long testSeekPosition = 1300;

        AtomicReference<PlaybackStateCompat> playbackStateRef = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onPlaybackStateChanged(PlaybackStateCompat state) {
                playbackStateRef.set(state);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().setCurrentPosition(testSeekPosition);
        mSession.getMockPlayer().setPlayerState(SessionPlayer.PLAYER_STATE_PAUSED);
        mSession.getMockPlayer().notifySeekCompleted(testSeekPosition);
        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testSeekPosition, playbackStateRef.get().getPosition());
        assertEquals(testSeekPosition, mControllerCompat.getPlaybackState().getPosition());
    }

    @FlakyTest(bugId = 187338985)
    @Test
    public void currentMediaItemChange() throws Exception {
        int testItemIndex = 3;
        long testPosition = 1234;
        String displayTitle = "displayTitle";
        MediaMetadata metadata = new MediaMetadata.Builder()
                .putText(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, displayTitle)
                .putRating(MediaMetadata.METADATA_KEY_USER_RATING, new ThumbRating())
                .build();
        MediaItem currentMediaItem = new FileMediaItem.Builder(ParcelFileDescriptor.adoptFd(-1))
                .setMetadata(metadata)
                .build();

        List<MediaItem> playlist = MediaTestUtils.createFileMediaItems(5);
        playlist.set(testItemIndex, currentMediaItem);
        mSession.getMockPlayer().setPlaylistWithFakeItem(playlist);

        AtomicReference<MediaMetadataCompat> metadataRef = new AtomicReference<>();
        AtomicReference<PlaybackStateCompat> playbackStateRef = new AtomicReference<>();
        CountDownLatch latchForMetadata = new CountDownLatch(1);
        CountDownLatch latchForPlaybackState = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onMetadataChanged(MediaMetadataCompat metadata) {
                metadataRef.set(metadata);
                latchForMetadata.countDown();
            }

            @Override
            public void onPlaybackStateChanged(PlaybackStateCompat state) {
                playbackStateRef.set(state);
                latchForPlaybackState.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().setCurrentMediaItem(testItemIndex);
        mSession.getMockPlayer().setCurrentPosition(testPosition);
        mSession.getMockPlayer().notifyCurrentMediaItemChanged(testItemIndex);

        assertTrue(latchForMetadata.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(displayTitle,
                metadataRef.get().getString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE));
        assertEquals(displayTitle,
                mControllerCompat.getMetadata().getString(
                        MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE));
        assertTrue(latchForPlaybackState.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(testPosition, playbackStateRef.get().getPosition());
        assertEquals(testPosition, mControllerCompat.getPlaybackState().getPosition());
        assertEquals(MediaUtils.convertToQueueItemId(testItemIndex),
                playbackStateRef.get().getActiveQueueItemId());
        assertEquals(MediaUtils.convertToQueueItemId(testItemIndex),
                mControllerCompat.getPlaybackState().getActiveQueueItemId());
        assertEquals(RatingCompat.RATING_THUMB_UP_DOWN, mControllerCompat.getRatingType());
    }

    @Test
    public void playlistAndPlaylistMetadataChange() throws Exception {
        List<MediaItem> playlist = MediaTestUtils.createFileMediaItems(5);
        String playlistTitle = "playlistTitle";
        MediaMetadata playlistMetadata = new MediaMetadata.Builder()
                .putText(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, playlistTitle).build();

        AtomicReference<CharSequence> queueTitleRef = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(2);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onQueueChanged(List<QueueItem> queue) {
                latch.countDown();
            }

            @Override
            public void onQueueTitleChanged(CharSequence title) {
                queueTitleRef.set(title);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().setPlaylist(playlist);
        mSession.getMockPlayer().setPlaylistMetadata(playlistMetadata);
        mSession.getMockPlayer().notifyPlaylistChanged();

        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));

        List<QueueItem> queue = mControllerCompat.getQueue();
        assertNotNull(queue);
        assertEquals(playlist.size(), queue.size());
        for (int i = 0; i < playlist.size(); i++) {
            assertEquals(playlist.get(i).getMediaId(), queue.get(i).getDescription().getMediaId());
        }
        assertEquals(playlistTitle, queueTitleRef.get().toString());
    }

    @Test
    public void playlistAndPlaylistMetadataChange_longList() throws Exception {
        String playlistTitle = "playlistTitle";
        MediaMetadata playlistMetadata = new MediaMetadata.Builder()
                .putText(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, playlistTitle).build();

        AtomicReference<CharSequence> queueTitleRef = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(2);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onQueueChanged(List<QueueItem> queue) {
                latch.countDown();
            }

            @Override
            public void onQueueTitleChanged(CharSequence title) {
                queueTitleRef.set(title);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        int listSize = 5000;
        mSession.getMockPlayer().createAndSetFakePlaylist(listSize);
        mSession.getMockPlayer().setPlaylistMetadata(playlistMetadata);
        mSession.getMockPlayer().notifyPlaylistChanged();

        assertTrue(latch.await(3, TimeUnit.SECONDS));

        List<QueueItem> queue = mControllerCompat.getQueue();
        assertNotNull(queue);

        if (Build.VERSION.SDK_INT >= 21) {
            assertEquals(listSize, queue.size());
        } else {
            // Below API 21, only the initial part of the playlist is sent to the
            // MediaControllerCompat when the list is too long.
            assertTrue(queue.size() < listSize);
        }
        for (int i = 0; i < queue.size(); i++) {
            assertEquals(TestUtils.getMediaIdInFakeList(i),
                    queue.get(i).getDescription().getMediaId());
        }
        assertEquals(playlistTitle, queueTitleRef.get().toString());
    }

    @Test
    public void playlistMetadataChange() throws Exception {
        String playlistTitle = "playlistTitle";
        MediaMetadata playlistMetadata = new MediaMetadata.Builder()
                .putText(MediaMetadata.METADATA_KEY_DISPLAY_TITLE, playlistTitle).build();

        AtomicReference<CharSequence> queueTitleRef = new AtomicReference<>();
        CountDownLatch latch = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onQueueTitleChanged(CharSequence title) {
                queueTitleRef.set(title);
                latch.countDown();
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().setPlaylistMetadata(playlistMetadata);
        mSession.getMockPlayer().notifyPlaylistMetadataChanged();

        assertTrue(latch.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(playlistTitle, queueTitleRef.get().toString());
    }

    @Test
    public void onAudioInfoChanged_isCalled_byVolumeChange() throws Exception {
        Bundle playerConfig = new RemoteMediaSession.MockPlayerConfigBuilder()
                .setVolumeControlType(RemoteSessionPlayer.VOLUME_CONTROL_ABSOLUTE)
                .setMaxVolume(10)
                .setCurrentVolume(1)
                .build();
        mSession.updatePlayer(playerConfig);

        int targetVolume = 3;
        CountDownLatch targetVolumeNotified = new CountDownLatch(1);
        MediaControllerCompat.Callback callback = new MediaControllerCompat.Callback() {
            @Override
            public void onAudioInfoChanged(MediaControllerCompat.PlaybackInfo info) {
                if (info.getCurrentVolume() == targetVolume) {
                    targetVolumeNotified.countDown();
                }
            }
        };
        mControllerCompat.registerCallback(callback, sHandler);

        mSession.getMockPlayer().notifyVolumeChanged(targetVolume);

        assertTrue(targetVolumeNotified.await(TIMEOUT_MS, TimeUnit.MILLISECONDS));
        assertEquals(targetVolume, mControllerCompat.getPlaybackInfo().getCurrentVolume());
    }
}


text:
#ifndef TENSORFLOW_COMPILER_TF2XLA_TPU_UTIL_H_
#define TENSORFLOW_COMPILER_TF2XLA_TPU_UTIL_H_

#include <string>

#include "tensorflow/compiler/xla/client/sharding_builder.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/lib/core/status.h"

namespace tensorflow {

// Parses the op sharding from the 'replicated core' device_name <device_name>.
// Returns an error:
// - if the device name is invalid.
// - the core is parsed and is out of the range [0, num_cores_per_replica).
//
// Otherwise, returns either:
// - explicit_sharding if explicit_sharding.has_value()
// - a non-value if there is no assigned core or
// - a sharding set as per xla::sharding_builder::AssignDevice.
xla::StatusOr<tensorflow::gtl::optional<xla::OpSharding>>
ParseShardingFromDevice(const string& device_name, int num_cores_per_replica,
                        tensorflow::gtl::optional<xla::OpSharding>
                            explicit_sharding = tensorflow::gtl::nullopt);

xla::StatusOr<tensorflow::gtl::optional<xla::OpSharding>>
ParseShardingFromDevice(const Node& node, int num_cores_per_replica);

xla::StatusOr<tensorflow::gtl::optional<xla::OpSharding>>
ParseShardingFromDevice(const NodeDef& node_def, int num_cores_per_replica);

void SetShardingDeviceAssignmentFromNode(const Node& src, Node* dst);

}  // namespace tensorflow

#endif  // TENSORFLOW_COMPILER_TF2XLA_TPU_UTIL_H_


text:
<component name="libraryTable">
  <library name="Maven: com.vaadin:vaadin-client-compiled:8.0.0">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/com/vaadin/vaadin-client-compiled/8.0.0/vaadin-client-compiled-8.0.0.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/com/vaadin/vaadin-client-compiled/8.0.0/vaadin-client-compiled-8.0.0-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/com/vaadin/vaadin-client-compiled/8.0.0/vaadin-client-compiled-8.0.0-sources.jar!/" />
    </SOURCES>
  </library>
</component>