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

/**
 * @fileoverview JavaScript shim for the liblouis Native Client wrapper.
 */

goog.provide('cvox.LibLouis');

/**
 * Encapsulates a liblouis Native Client instance in the page.
 * @constructor
 * @param {string} nmfPath Path to .nmf file for the module.
 * @param {string=} opt_tablesDir Path to tables directory.
 */
cvox.LibLouis = function(nmfPath, opt_tablesDir) {
  /**
   * Path to .nmf file for the module.
   * @private {string}
   */
  this.nmfPath_ = nmfPath;

  /**
   * Path to translation tables.
   * @private {?string}
   */
  this.tablesDir_ = goog.isDef(opt_tablesDir) ? opt_tablesDir : null;

  /**
   * Native Client <embed> element.
   * {@code null} when no <embed> is attached to the DOM.
   * @private {NaClEmbedElement}
   */
  this.embedElement_ = null;

  /**
   * The state of the instance.
   * @private {cvox.LibLouis.InstanceState}
   */
  this.instanceState_ =
      cvox.LibLouis.InstanceState.NOT_LOADED;

  /**
   * Pending requests to construct translators.
   * @private {!Array.<{tableName: string,
   *   callback: function(cvox.LibLouis.Translator)}>}
   */
  this.pendingTranslators_ = [];

  /**
   * Pending RPC callbacks. Maps from message IDs to callbacks.
   * @private {!Object.<string, function(!Object)>}
   */
  this.pendingRpcCallbacks_ = {};

  /**
   * Next message ID to be used. Incremented with each sent message.
   * @private {number}
   */
  this.nextMessageId_ = 1;
};

/**
 * Describes the loading state of the instance.
 * @enum {number}
 */
cvox.LibLouis.InstanceState = {
  NOT_LOADED: 0,
  LOADING: 1,
  LOADED: 2,
  ERROR: -1
};

/**
 * Attaches the Native Client wrapper to the DOM as a child of the provided
 * element, assumed to already be in the document.
 * @param {!Element} elem Desired parent element of the instance.
 */
cvox.LibLouis.prototype.attachToElement = function(elem) {
  if (this.isAttached()) {
    throw Error('instance already attached');
  }

  var embed = document.createElement('embed');
  embed.src = this.nmfPath_;
  embed.type = 'application/x-nacl';
  embed.width = 0;
  embed.height = 0;
  if (!goog.isNull(this.tablesDir_)) {
    embed.setAttribute('tablesdir', this.tablesDir_);
  }
  embed.addEventListener('load', goog.bind(this.onInstanceLoad_, this),
      false /* useCapture */);
  embed.addEventListener('error', goog.bind(this.onInstanceError_, this),
      false /* useCapture */);
  embed.addEventListener('message', goog.bind(this.onInstanceMessage_, this),
      false /* useCapture */);
  elem.appendChild(embed);

  this.embedElement_ = /** @type {!NaClEmbedElement} */ (embed);
  this.instanceState_ = cvox.LibLouis.InstanceState.LOADING;
};

/**
 * Detaches the Native Client instance from the DOM.
 */
cvox.LibLouis.prototype.detach = function() {
  if (!this.isAttached()) {
    throw Error('cannot detach unattached instance');
  }

  this.embedElement_.parentNode.removeChild(this.embedElement_);
  this.embedElement_ = null;
  this.instanceState_ =
      cvox.LibLouis.InstanceState.NOT_LOADED;
};

/**
 * Determines whether the Native Client instance is attached.
 * @return {boolean} {@code true} if the <embed> element is attached to the DOM.
 */
cvox.LibLouis.prototype.isAttached = function() {
  return this.embedElement_ !== null;
};

/**
 * Returns a translator for the desired table, asynchronously.
 * @param {string} tableNames Comma separated list of braille table names for
 *     liblouis.
 * @param {function(cvox.LibLouis.Translator)} callback
 *     Callback which will receive the translator, or {@code null} on failure.
 */
cvox.LibLouis.prototype.getTranslator =
    function(tableNames, callback) {
  switch (this.instanceState_) {
    case cvox.LibLouis.InstanceState.NOT_LOADED:
    case cvox.LibLouis.InstanceState.LOADING:
      this.pendingTranslators_.push(
          { tableNames: tableNames, callback: callback });
      return;
    case cvox.LibLouis.InstanceState.ERROR:
      callback(null /* translator */);
      return;
    case cvox.LibLouis.InstanceState.LOADED:
      this.rpc_('CheckTable', { 'table_names': tableNames },
          goog.bind(function(reply) {
        if (reply['success']) {
          var translator = new cvox.LibLouis.Translator(
              this, tableNames);
          callback(translator);
        } else {
          callback(null /* translator */);
        }
      }, this));
      return;
  }
};

/**
 * Dispatches a message to the remote end and returns the reply asynchronously.
 * A message ID will be automatically assigned (as a side-effect).
 * @param {string} command Command name to be sent.
 * @param {!Object} message JSONable message to be sent.
 * @param {function(!Object)} callback Callback to receive the reply.
 * @private
 */
cvox.LibLouis.prototype.rpc_ =
    function(command, message, callback) {
  if (this.instanceState_ !==
      cvox.LibLouis.InstanceState.LOADED) {
    throw Error('cannot send RPC: liblouis instance not loaded');
  }
  var messageId = '' + this.nextMessageId_++;
  message['message_id'] = messageId;
  message['command'] = command;
  var json = JSON.stringify(message);
  if (goog.DEBUG) {
    window.console.debug('RPC -> ' + json);
  }
  this.embedElement_.postMessage(json);
  this.pendingRpcCallbacks_[messageId] = callback;
};

/**
 * Invoked when the Native Client instance successfully loads.
 * @param {Event} e Event dispatched after loading.
 * @private
 */
cvox.LibLouis.prototype.onInstanceLoad_ = function(e) {
  window.console.info('loaded liblouis Native Client instance');
  this.instanceState_ = cvox.LibLouis.InstanceState.LOADED;
  this.pendingTranslators_.forEach(goog.bind(function(record) {
    this.getTranslator(record.tableNames, record.callback);
  }, this));
  this.pendingTranslators_.length = 0;
};

/**
 * Invoked when the Native Client instance fails to load.
 * @param {Event} e Event dispatched after loading failure.
 * @private
 */
cvox.LibLouis.prototype.onInstanceError_ = function(e) {
  window.console.error('failed to load liblouis Native Client instance');
  this.instanceState_ = cvox.LibLouis.InstanceState.ERROR;
  this.pendingTranslators_.forEach(goog.bind(function(record) {
    this.getTranslator(record.tableNames, record.callback);
  }, this));
  this.pendingTranslators_.length = 0;
};

/**
 * Invoked when the Native Client instance posts a message.
 * @param {Event} e Event dispatched after the message was posted.
 * @private
 */
cvox.LibLouis.prototype.onInstanceMessage_ = function(e) {
  if (goog.DEBUG) {
    window.console.debug('RPC <- ' + e.data);
  }
  var message = /** @type {!Object} */ (JSON.parse(e.data));
  var messageId = message['in_reply_to'];
  if (!goog.isDef(messageId)) {
    window.console.warn('liblouis Native Client module sent message with no ID',
        message);
    return;
  }
  if (goog.isDef(message['error'])) {
    window.console.error('liblouis Native Client error', message['error']);
  }
  var callback = this.pendingRpcCallbacks_[messageId];
  if (goog.isDef(callback)) {
    delete this.pendingRpcCallbacks_[messageId];
    callback(message);
  }
};

/**
 * Braille translator which uses a Native Client instance of liblouis.
 * @constructor
 * @param {!cvox.LibLouis} instance The instance wrapper.
 * @param {string} tableNames Comma separated list of Table names to be passed
 *     to liblouis.
 */
cvox.LibLouis.Translator = function(instance, tableNames) {
  /**
   * The instance wrapper.
   * @private {!cvox.LibLouis}
   */
  this.instance_ = instance;

  /**
   * The table name.
   * @private {string}
   */
  this.tableNames_ = tableNames;
};

/**
 * Translates text into braille cells.
 * @param {string} text Text to be translated.
 * @param {function(ArrayBuffer, Array.<number>, Array.<number>)} callback
 *     Callback for result.  Takes 3 parameters: the resulting cells,
 *     mapping from text to braille positions and mapping from braille to
 *     text positions.  If translation fails for any reason, all parameters are
 *     {@code null}.
 */
cvox.LibLouis.Translator.prototype.translate = function(text, callback) {
  var message = { 'table_names': this.tableNames_, 'text': text };
  this.instance_.rpc_('Translate', message, function(reply) {
    var cells = null;
    var textToBraille = null;
    var brailleToText = null;
    if (reply['success'] && goog.isString(reply['cells'])) {
      cells = cvox.LibLouis.Translator.decodeHexString_(reply['cells']);
      if (goog.isDef(reply['text_to_braille'])) {
        textToBraille = reply['text_to_braille'];
      }
      if (goog.isDef(reply['braille_to_text'])) {
        brailleToText = reply['braille_to_text'];
      }
    } else if (text.length > 0) {
      // TODO(plundblad): The nacl wrapper currently returns an error
      // when translating an empty string.  Address that and always log here.
      console.error('Braille translation error for ' + JSON.stringify(message));
    }
    callback(cells, textToBraille, brailleToText);
  });
};

/**
 * Translates braille cells into text.
 * @param {!ArrayBuffer} cells Cells to be translated.
 * @param {function(?string)} callback Callback for result.
 */
cvox.LibLouis.Translator.prototype.backTranslate =
    function(cells, callback) {
  if (cells.byteLength == 0) {
    // liblouis doesn't handle empty input, so handle that trivially
    // here.
    callback('');
    return;
  }
  var message = {
    'table_names': this.tableNames_,
    'cells': cvox.LibLouis.Translator.encodeHexString_(cells)
  };
  this.instance_.rpc_('BackTranslate', message, function(reply) {
    if (reply['success'] && goog.isString(reply['text'])) {
      callback(reply['text']);
    } else {
      callback(null /* text */);
    }
  });
};

/**
 * Decodes a hexadecimal string to an {@code ArrayBuffer}.
 * @param {string} hex Hexadecimal string.
 * @return {!ArrayBuffer} Decoded binary data.
 * @private
 */
cvox.LibLouis.Translator.decodeHexString_ = function(hex) {
  if (!/^([0-9a-f]{2})*$/i.test(hex)) {
    throw Error('invalid hexadecimal string');
  }
  var array = new Uint8Array(hex.length / 2);
  var idx = 0;
  for (var i = 0; i < hex.length; i += 2) {
    array[idx++] = parseInt(hex.substring(i, i + 2), 16);
  }
  return array.buffer;
};

/**
 * Encodes an {@code ArrayBuffer} in hexadecimal.
 * @param {!ArrayBuffer} arrayBuffer Binary data.
 * @return {string} Hexadecimal string.
 * @private
 */
cvox.LibLouis.Translator.encodeHexString_ = function(arrayBuffer) {
  var array = new Uint8Array(arrayBuffer);
  var hex = '';
  for (var i = 0; i < array.length; i++) {
    var b = array[i];
    hex += (b < 0x10 ? '0' : '') + b.toString(16);
  }
  return hex;
};


text:
'use strict';

var Gaze = require('../lib/gaze.js').Gaze;
var path = require('path');
var fs = require('fs');
var helper = require('./helper');

var fixtures = path.resolve(__dirname, 'fixtures');
var sortobj = helper.sortobj;

exports.add = {
  setUp: function (done) {
    process.chdir(fixtures);
    done();
  },
  addToWatched: function (test) {
    test.expect(1);
    var files = [
      'Project (LO)/',
      'Project (LO)/one.js',
      'nested/',
      'nested/one.js',
      'nested/three.js',
      'nested/sub/',
      'nested/sub/two.js',
      'one.js',
    ];
    var expected = {
      'Project (LO)/': ['one.js'],
      '.': ['Project (LO)/', 'nested/', 'one.js', 'sub/'],
      'nested/': ['sub/', 'sub2/', 'one.js', 'three.js'],
      'nested/sub/': ['two.js'],
    };
    var gaze = new Gaze('addnothingtowatch');
    gaze._addToWatched(files);
    var result = gaze.relative(null, true);
    test.deepEqual(sortobj(result), sortobj(expected));
    gaze.on('end', test.done);
    gaze.close();
  },
  addLater: function (test) {
    test.expect(3);
    new Gaze('sub/one.js', function (err, watcher) {
      test.deepEqual(watcher.relative('sub'), ['one.js']);
      watcher.add('sub/*.js', function () {
        test.deepEqual(watcher.relative('sub'), ['one.js', 'two.js']);
        watcher.on('changed', function (filepath) {
          test.equal('two.js', path.basename(filepath));
          watcher.on('end', test.done);
          watcher.close();
        });
        fs.writeFileSync(path.resolve(__dirname, 'fixtures', 'sub', 'two.js'), 'var two = true;');
      });
    });
  },
  addNoCallback: function (test) {
    test.expect(1);
    new Gaze('sub/one.js', function (err, watcher) {
      this.add('sub/two.js');
      this.on('changed', function (filepath) {
        test.equal('two.js', path.basename(filepath));
        watcher.on('end', test.done);
        watcher.close();
      });
      setTimeout(function () {
        fs.writeFileSync(path.resolve(__dirname, 'fixtures', 'sub', 'two.js'), 'var two = true;');
      }, 500);
    });
  },
};

redpajama_set_name: RedPajamaGithub


text:
Device drivers infrastructure
=============================

The Basic Device Driver-Model Structures
----------------------------------------

.. kernel-doc:: include/linux/device.h
   :internal:

Device Drivers Base
-------------------

.. kernel-doc:: drivers/base/init.c
   :internal:

.. kernel-doc:: drivers/base/driver.c
   :export:

.. kernel-doc:: drivers/base/core.c
   :export:

.. kernel-doc:: drivers/base/syscore.c
   :export:

.. kernel-doc:: drivers/base/class.c
   :export:

.. kernel-doc:: drivers/base/node.c
   :internal:

.. kernel-doc:: drivers/base/firmware_class.c
   :export:

.. kernel-doc:: drivers/base/transport_class.c
   :export:

.. kernel-doc:: drivers/base/dd.c
   :export:

.. kernel-doc:: include/linux/platform_device.h
   :internal:

.. kernel-doc:: drivers/base/platform.c
   :export:

.. kernel-doc:: drivers/base/bus.c
   :export:

Device Drivers DMA Management
-----------------------------

.. kernel-doc:: drivers/base/dma-coherent.c
   :export:

.. kernel-doc:: drivers/base/dma-mapping.c
   :export:

Device drivers PnP support
--------------------------

.. kernel-doc:: drivers/pnp/core.c
   :internal:

.. kernel-doc:: drivers/pnp/card.c
   :export:

.. kernel-doc:: drivers/pnp/driver.c
   :internal:

.. kernel-doc:: drivers/pnp/manager.c
   :export:

.. kernel-doc:: drivers/pnp/support.c
   :export:

Userspace IO devices
--------------------

.. kernel-doc:: drivers/uio/uio.c
   :export:

.. kernel-doc:: include/linux/uio_driver.h
   :internal:


text:
class ItemEffects:

    """
    Item effects model
    """

    def __init__(self, **kwargs):
        self.db = kwargs["db"]

    def _get_item_effects_map(self, effects):
        item_effects_map = {}

        for item_effect in effects:
            item_id = item_effect["item_id"]

            if item_id not in item_effects_map:
                item_effects_map[item_id] = []

            item_effects_map[item_id].append(item_effect["effect_id"])

        return item_effects_map

    def get_item_effects(self):
        """
        Fetches effects for one or many items
        """
        cursor = self.db.cursor()

        cursor.execute("""SELECT
                          ie.item_id,
                          ie.effect_id
                          FROM spiffyrpg_item_effects ie
                          JOIN spiffyrpg_items i ON ie.item_id = i.id""")

        tmp_items = cursor.fetchall()
        cursor.close()
        items = []

        if tmp_items:
            for i in tmp_items:
                item = dict(i)
                items.append(item)

        return items


text:
@protocol ComGoogleCommonCollectFilteredMultimap;
@protocol JavaUtilCollection;
@protocol JavaUtilIterator;

@interface ComGoogleCommonCollectFilteredMultimapValues : JavaUtilAbstractCollection

#pragma mark Public

- (void)clear;

- (jboolean)containsWithId:(id)o;

- (id<JavaUtilIterator>)iterator;

- (jboolean)removeWithId:(id)o;

- (jboolean)removeAllWithJavaUtilCollection:(id<JavaUtilCollection>)c;

- (jboolean)retainAllWithJavaUtilCollection:(id<JavaUtilCollection>)c;

- (jint)size;

#pragma mark Package-Private

- (instancetype)initWithComGoogleCommonCollectFilteredMultimap:(id<ComGoogleCommonCollectFilteredMultimap>)multimap;

@end

J2OBJC_EMPTY_STATIC_INIT(ComGoogleCommonCollectFilteredMultimapValues)

FOUNDATION_EXPORT void ComGoogleCommonCollectFilteredMultimapValues_initWithComGoogleCommonCollectFilteredMultimap_(ComGoogleCommonCollectFilteredMultimapValues *self, id<ComGoogleCommonCollectFilteredMultimap> multimap);

FOUNDATION_EXPORT ComGoogleCommonCollectFilteredMultimapValues *new_ComGoogleCommonCollectFilteredMultimapValues_initWithComGoogleCommonCollectFilteredMultimap_(id<ComGoogleCommonCollectFilteredMultimap> multimap) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT ComGoogleCommonCollectFilteredMultimapValues *create_ComGoogleCommonCollectFilteredMultimapValues_initWithComGoogleCommonCollectFilteredMultimap_(id<ComGoogleCommonCollectFilteredMultimap> multimap);

J2OBJC_TYPE_LITERAL_HEADER(ComGoogleCommonCollectFilteredMultimapValues)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_ComGoogleCommonCollectFilteredMultimapValues")


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2017 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Simon Grätzer
////////////////////////////////////////////////////////////////////////////////

#ifndef ARANGOD_STORAGE_ENGINE_WAL_ACCESS_H
#define ARANGOD_STORAGE_ENGINE_WAL_ACCESS_H 1

#include "Basics/Result.h"
#include "Utils/CollectionGuard.h"
#include "Utils/DatabaseGuard.h"
#include "VocBase/voc-types.h"

#include <velocypack/Builder.h>

namespace arangodb {

struct WalAccessResult : public Result {
  WalAccessResult()
      : Result(TRI_ERROR_NO_ERROR),
        _fromTickIncluded(false),
        _lastIncludedTick(0),
        _latestTick(0) {}
  WalAccessResult(int code, bool ft, TRI_voc_tick_t included,
                  TRI_voc_tick_t latest)
      : Result(code),
        _fromTickIncluded(ft),
        _lastIncludedTick(included),
        _latestTick(latest) {}

  WalAccessResult(WalAccessResult const& other)
      : Result(other),
        _fromTickIncluded(other._fromTickIncluded),
        _lastIncludedTick(other._lastIncludedTick),
        _latestTick(other._latestTick) {}

  bool fromTickIncluded() const { return _fromTickIncluded; }
  TRI_voc_tick_t lastIncludedTick() const { return _lastIncludedTick; }
  TRI_voc_tick_t latestTick() const { return _latestTick; }

  Result& reset(int errorNumber, bool ft, TRI_voc_tick_t included,
                TRI_voc_tick_t latest) {
    _errorNumber = errorNumber;
    _fromTickIncluded = ft;
    _lastIncludedTick = included;
    _latestTick = latest;
    return *this;
  }

 private:
  bool _fromTickIncluded;
  TRI_voc_tick_t _lastIncludedTick;
  TRI_voc_tick_t _latestTick;
};

/// @brief StorageEngine agnostic wal access interface.
/// TODO: add methods for _admin/wal/ and get rid of engine specific handlers
class WalAccess {
  WalAccess(WalAccess const&) = delete;
  WalAccess& operator=(WalAccess const&) = delete;

 protected:
  WalAccess() {}
  virtual ~WalAccess(){};

 public:
  struct Filter {
    Filter() {}

    /// In case collection is == 0,
    bool includeSystem = false;

    /// only output markers from this database
    TRI_voc_tick_t vocbase = 0;
    /// Only output data from this collection
    /// FIXME: make a set of collections
    TRI_voc_cid_t collection = 0;

    /// only include these transactions, up to
    /// (not including) firstRegularTick
    std::unordered_set<TRI_voc_tid_t> transactionIds;
    /// @brief starting from this tick ignore transactionIds
    TRI_voc_tick_t firstRegularTick = 0;
  };

  typedef std::function<void(TRI_vocbase_t*, velocypack::Slice const&)>
      MarkerCallback;
  typedef std::function<void(TRI_voc_tid_t, TRI_voc_tid_t)> TransactionCallback;

  /// {"tickMin":"123", "tickMax":"456",
  ///  "server":{"version":"3.2", "serverId":"abc"}}
  virtual Result tickRange(
      std::pair<TRI_voc_tick_t, TRI_voc_tick_t>& minMax) const = 0;

  /// {"lastTick":"123",
  ///  "server":{"version":"3.2",
  ///  "serverId":"abc"},
  ///  "clients": {
  ///    "serverId": "ass", "lastTick":"123", ...
  ///  }}
  ///
  virtual TRI_voc_tick_t lastTick() const = 0;

  /// should return the list of transactions started, but not committed in that
  /// range (range can be adjusted)
  virtual WalAccessResult openTransactions(
      uint64_t tickStart, uint64_t tickEnd, Filter const& filter,
      TransactionCallback const&) const = 0;

  virtual WalAccessResult tail(uint64_t tickStart, uint64_t tickEnd,
                               size_t chunkSize, TRI_voc_tid_t barrierId,
                               Filter const& filter,
                               MarkerCallback const&) const = 0;
};

/// @brief helper class used to resolve vocbases
///        and collections from wal markers in an efficient way
struct WalAccessContext {
  WalAccessContext(WalAccess::Filter const& filter,
                   WalAccess::MarkerCallback const& c)
      : _filter(filter), _callback(c), _responseSize(0) {}

  ~WalAccessContext() {}

  /// @brief Check if collection is in filter
  bool shouldHandleCollection(TRI_voc_tick_t dbid, TRI_voc_cid_t cid);

  /// @brief try to get collection, may return null
  TRI_vocbase_t* loadVocbase(TRI_voc_tick_t dbid);

  LogicalCollection* loadCollection(TRI_voc_tick_t dbid, TRI_voc_cid_t cid);

  /// @brief get global unique id
  /*std::string const& cidToUUID(TRI_voc_tick_t dbid, TRI_voc_cid_t cid);

  /// @brief cid to collection name
  std::string cidToName(TRI_voc_tick_t dbid, TRI_voc_cid_t cid);*/

 public:
  /// @brief arbitrary collection filter (inclusive)
  WalAccess::Filter _filter;
  /// @brief callback for marker output
  WalAccess::MarkerCallback _callback;

  /// @brief current response size
  size_t _responseSize;

  /// @brief result builder
  velocypack::Builder _builder;

  /// @brief cache the vocbases
  std::map<TRI_voc_tick_t, DatabaseGuard> _vocbases;

  // @brief collection replication UUID cache
  std::map<TRI_voc_cid_t, CollectionGuard> _collectionCache;
};

}  // namespace arangodb

#endif


text:
package br.com.kurtis.financial;

import br.com.kurtis.financial.domain.Transaction;
import br.com.kurtis.financial.infra.ContextConfiguration;
import br.com.kurtis.financial.nubank.NubankService;
import br.com.kurtis.financial.spreadsheet.SpreadsheetGenerator;
import lombok.NonNull;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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

public class AccountStatementApp {

    public static void main(@NonNull String args[]) throws IOException {
        final ApplicationContext context = new AnnotationConfigApplicationContext(ContextConfiguration.class);
        final NubankService nubankService = context.getBean(NubankService.class);
        final SpreadsheetGenerator spreadsheetGenerator = context.getBean(SpreadsheetGenerator.class);

        final String filePath = args[0];
        final List<Transaction> transactions = nubankService.transactionsFrom(filePath);
        spreadsheetGenerator.generate(transactions, filePath.replace(".json", ".xlsx"));
    }
}


text:
#include "xml2_parse.h"

#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xinclude.h>

#define MY_ENCODING "UTF-8"

xmlChar*
xml2_parse(
		const char* content,
		int lengthInBytes,
		int* parsedLengthInBytes_p)
{
	/*
	 * this initialize the library and check potential ABI mismatches
	 * between the version it was compiled for and the actual shared
	 * library used.
	 */
	LIBXML_TEST_VERSION

	/*
	 * The document being in memory, it have no base per RFC 2396,
	 * and the "noname.xml" argument will serve as its base.
	 *
	 * TODO original name here somehow?
	 */
	xmlDocPtr doc;
	doc = xmlReadMemory(content, lengthInBytes, "noname.xml", MY_ENCODING, 0);
	if (doc == NULL) {
		fprintf(stderr, "Failed to parse document\n");
		// TODO gracefully report error back to Java code
		return NULL;
	}

	// Process any xincludes in the document
	if (xmlXIncludeProcessFlags(doc, XML_PARSE_XINCLUDE) < 0) {
		fprintf(stderr, "XInclude processing failed\n");
		return NULL;
	}

	xmlChar* parsedContents_p;
	xmlDocDumpFormatMemory(doc, &parsedContents_p, parsedLengthInBytes_p, 1);

	/*
	 * Free associated memory.
	 */
	xmlFreeDoc(doc);

	return parsedContents_p;
}


text:
package com.github.aureliano.edocs.app;

import javax.swing.SwingUtilities;

import com.github.aureliano.edocs.app.gui.AppFrame;

public class EdocsApp {

	private static EdocsApp instance;
	private AppFrame frame;

	public static void main(String[] args) {
		final EdocsApp application = instance();

		SwingUtilities.invokeLater(new Runnable() {

			@Override
			public void run() {
				application.getFrame().showFrame();
			}
		});
	}

	public static EdocsApp instance() {
		if (instance == null) {
			instance = new EdocsApp();
		}

		return instance;
	}

	public EdocsApp() {
		this.frame = new AppFrame();
	}

	public AppFrame getFrame() {
		return this.frame;
	}
}


text:
using namespace llvm;
using namespace lld;

// Returns the demangled C++ symbol name for name.
std::string lld::demangleItanium(StringRef name) {
  // itaniumDemangle can be used to demangle strings other than symbol
  // names which do not necessarily start with "_Z". Name can be
  // either a C or C++ symbol. Don't call demangle if the name
  // does not look like a C++ symbol name to avoid getting unexpected
  // result for a C symbol that happens to match a mangled type name.
  if (!name.startswith("_Z"))
    return std::string(name);

  return demangle(std::string(name));
}

SingleStringMatcher::SingleStringMatcher(StringRef Pattern) {
  if (Pattern.size() > 2 && Pattern.startswith("\"") &&
      Pattern.endswith("\"")) {
    ExactMatch = true;
    ExactPattern = Pattern.substr(1, Pattern.size() - 2);
  } else {
    Expected<GlobPattern> Glob = GlobPattern::create(Pattern);
    if (!Glob) {
      error(toString(Glob.takeError()));
      return;
    }
    ExactMatch = false;
    GlobPatternMatcher = *Glob;
  }
}

bool SingleStringMatcher::match(StringRef s) const {
  return ExactMatch ? (ExactPattern == s) : GlobPatternMatcher.match(s);
}

bool StringMatcher::match(StringRef s) const {
  for (const SingleStringMatcher &pat : patterns)
    if (pat.match(s))
      return true;
  return false;
}

// Converts a hex string (e.g. "deadbeef") to a vector.
std::vector<uint8_t> lld::parseHex(StringRef s) {
  std::vector<uint8_t> hex;
  while (!s.empty()) {
    StringRef b = s.substr(0, 2);
    s = s.substr(2);
    uint8_t h;
    if (!to_integer(b, h, 16)) {
      error("not a hexadecimal value: " + b);
      return {};
    }
    hex.push_back(h);
  }
  return hex;
}

// Returns true if S is valid as a C language identifier.
bool lld::isValidCIdentifier(StringRef s) {
  return !s.empty() && (isAlpha(s[0]) || s[0] == '_') &&
         std::all_of(s.begin() + 1, s.end(),
                     [](char c) { return c == '_' || isAlnum(c); });
}

// Write the contents of the a buffer to a file
void lld::saveBuffer(StringRef buffer, const Twine &path) {
  std::error_code ec;
  raw_fd_ostream os(path.str(), ec, sys::fs::OpenFlags::OF_None);
  if (ec)
    error("cannot create " + path + ": " + ec.message());
  os << buffer;
}


text:
//
// Copyright (c) 2015-2017, Deutsches Forschungszentrum für Künstliche Intelligenz GmbH.
// Copyright (c) 2015-2017, University of Bremen
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
//   list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
//   this list of conditions and the following disclaimer in the documentation
//   and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#ifndef __MAPS_SURFACEPATCHES_HPP_
#define __MAPS_SURFACEPATCHES_HPP_

#include <numeric/PlaneFitting.hpp>

#include <base/Eigen.hpp>
#include <base-logging/Logging.hpp>

#include <Eigen/Core>

#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/version.hpp>

#include <boost_serialization/BaseNumeric.hpp>

#include "MLSConfig.hpp"
#include "Index.hpp"
#include <cmath>
#include <limits>
#include <vector>

namespace maps { namespace grid
{
//! global typedef for all SurfacePatches. Only float seems to be useful.
typedef float SPScalar;
typedef Eigen::Matrix<SPScalar, 3, 1> Vector3;
typedef Eigen::Matrix<SPScalar, 3, 3> Matrix33;

class SurfacePatchBase
{
protected:
    float min, max;

public:
    // TODO set default value properly
    SurfacePatchBase()
        : min(0),
          max(0)
    {}

    explicit SurfacePatchBase(const float &z)
    : min(z), max(z)
    {}

    explicit SurfacePatchBase(const float &mean, const float &height)
    : min(mean - height), max(mean)
    {}

    bool merge(const SurfacePatchBase& other, const float& gapSize=0.0f)
    {
        if(!isCovered(other, gapSize)) return false;
        min = std::min(min, other.min);
        max = std::max(max, other.max);
        return true;
    }

    float getMin() const { return min; }
    float getMax() const { return max; }
    float getTop() const { return max; }
    float getBottom() const { return min; }
    void getRange(float& mini, float& maxi) const {mini = min; maxi = max; }

    bool isCovered(const float& z, const float& gapSize = 0.0f) const
    {
        return min - gapSize < z && z < max + gapSize;
    }

    bool isCovered(const SurfacePatchBase& other, const float& gapSize) const
    {
        return min - gapSize < other.max && other.min - gapSize < max;
    }

    bool operator<(const SurfacePatchBase& other) const
    {
        return min < other.min;
    }

    bool operator==(const SurfacePatchBase& other) const
    {
        return min == other.min && max == other.max;
    }

    void getClosestContactPoint(const Vector3& pos_in_cell, Vector3& contact_point) const
    {
        if(pos_in_cell.z() > max)
            contact_point << pos_in_cell.block(0,0,2,1), max;
        else if(pos_in_cell.z() < min)
            contact_point << pos_in_cell.block(0,0,2,1), min;
        else
            contact_point << pos_in_cell;
    }

    float getSurfacePos(const Vector3& pos_in_cell) const
    {
        return max;
    }

protected:
    /** Grants access to boost serialization */
    friend class boost::serialization::access;

    /** Serializes the members of this class*/
    template <typename Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_NVP(min);
        ar & BOOST_SERIALIZATION_NVP(max);

    }
};

/**
 * Templated surface patch class.
 * TODO add color option
 */
template<MLSConfig::update_model model>
class SurfacePatch;

template<>
class SurfacePatch<MLSConfig::BASE> : public SurfacePatchBase
{
    typedef SurfacePatchBase Base;
public:
    explicit SurfacePatch(const float &z = 0, const float height = 0) : SurfacePatchBase(z, height) {}
    // implicit conversion from any other SurfacePatch:
    SurfacePatch(const SurfacePatchBase& other) : SurfacePatchBase(other) { }

    Eigen::Vector3f getCenter() const
    {
        Eigen::Vector3f center(0.0f, 0.0f, 0.5f*(max+min));
        return center;
    }

    Eigen::Vector3f getNormal() const
    {
        return Eigen::Vector3f::UnitZ();
    }

    bool merge(const SurfacePatch& other, const MLSConfig& config)
    {
        return Base::merge(other, config.gapSize);
    }
};

/**
 * SurfacePatch type for SLOPE update model.
 */
template<>
class SurfacePatch<MLSConfig::SLOPE> : public SurfacePatchBase
{
    typedef SurfacePatchBase Base;
    numeric::PlaneFitting<float> plane;
    float n;

public:

    SurfacePatch() : n(0)
    {}

    SurfacePatch(const Eigen::Vector3f& point, const float& cov)
        : Base(point.z())
        , plane(point, 1.0f/cov)
        , n(1)
    {}

    /**
     * Compares two patches by their center of mass
     */
    bool operator<(const SurfacePatch& other) const
    {
        return plane.z * other.plane.n < other.plane.z * plane.n;
    }

    bool operator==(const SurfacePatch& other) const
    {
        return Base::operator ==(other) &&
                plane.n == other.plane.n && plane.x == other.plane.x &&
                plane.y == other.plane.y && plane.z == other.plane.z &&
                plane.xx == other.plane.xx && plane.xy == other.plane.xy &&
                plane.xz == other.plane.xz && plane.yy == other.plane.yy &&
                plane.yz == other.plane.yz && plane.zz == other.plane.zz &&
                n == other.n;
    }

    /**
     * returns the top most
     */
    float getTop() const
    {
        // TODO
        return Base::getMax();
    }

    float getBottom() const
    {
        // TODO
        return Base::getMin();
    }

    Eigen::Vector3f getCenter() const
    {
        Eigen::Vector3f center(plane.x, plane.y, plane.z);
        return center * (1.0f/plane.n);
    }

    Eigen::Vector3f getNormal() const
    {
        if(n<=1.0f) return Eigen::Vector3f::UnitZ();
        return plane.getNormal();
    }

    bool merge(const SurfacePatch& other, const MLSConfig& config)
    {
        if(Base::merge(other, config.gapSize))
        {
            plane.update(other.plane);
            n+= other.n;
            return true;
        }

        return false;
    }

    float getClosestContactPoint(const Vector3& pos_in_cell, Vector3& contact_point) const
    {
        Eigen::Hyperplane<float, 3> plane(getNormal(), getCenter());
        const float distance = plane.signedDistance(pos_in_cell);
        contact_point = plane.projection(pos_in_cell);
        return distance;
    }

    float getSurfacePos(const Vector3& pos_in_cell) const
    {
        Eigen::Hyperplane<float, 3> plane(getNormal(), getCenter());
        float z_pos = (-plane.coeffs()(0) * pos_in_cell(0) - plane.coeffs()(1) * pos_in_cell(1) - plane.coeffs()(3)) / plane.coeffs()(2);
        if(z_pos > max)
            z_pos = max;
        return z_pos;
    }

    int getNumberOfMeasurements() const
    {
        return n;
    }

protected:
    /** Grants access to boost serialization */
    friend class boost::serialization::access;

    /** @deprecated type definition */
    enum TYPE
    {
        VERTICAL = 0,
        HORIZONTAL = 1,
        NEGATIVE = 2
    };

    /** Serializes the members of this class*/
    template <typename Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(SurfacePatchBase);
        ar & BOOST_SERIALIZATION_NVP(plane);
        ar & BOOST_SERIALIZATION_NVP(n);
        if(version == 0)
        {
            TYPE type;
            ar & BOOST_SERIALIZATION_NVP(type);
        }
    }
}; // SurfacePatch<MLSConfig::SLOPE>

template<>
class SurfacePatch<MLSConfig::KALMAN>: public SurfacePatchBase
{
    typedef SurfacePatchBase Base;
    float mean, var, height;

    template <class T> static inline void kalman_update( T& mean, T& var, T m_mean, T m_var )
    {
        float gain = var / (var + m_var);
        if( gain != gain )
            gain = 0.5f; // this happens when both vars are 0.
        mean = mean + gain * (m_mean - mean);
        var = (1.0f-gain)*var;
    }

public:
    SurfacePatch() : mean(0), var(0), height(0)
    {}

    SurfacePatch(const Eigen::Vector3f& point, const float& variance)
        : Base(point.z())
        , mean(point.z()), var(variance), height(0)
    {}

    SurfacePatch(const float& mean, const float& variance, const float& height = 0)
        : Base(mean, height)
        , mean(mean), var(variance), height(height)
    {}

    bool merge(const SurfacePatch& other, const MLSConfig& config)
    {
        float delta_dev = std::sqrt(var + other.var);

        if(!Base::merge(other, config.gapSize + delta_dev))
            return false;

        if(isHorizontal() && other.isHorizontal() &&
            (mean - config.thickness - delta_dev) < other.mean &&
            (mean + config.thickness + delta_dev) > other.mean )
        {
            kalman_update(mean, var, other.mean, other.var);
        }
        else
        {
            height = std::max(mean, other.mean) - std::min(mean - height, other.mean - other.height);
            if(mean < other.mean)
            {
                mean = other.mean;
                var = other.var;
            }
        }

        // update min and max after current mean and height are computed
        min = mean - height;
        max = mean;

        return true;
    }

    Eigen::Vector3f getCenter() const
    {
        Eigen::Vector3f center(0.0f, 0.0f, mean);
        return center;
    }

    bool operator<(const SurfacePatch& other) const
    {
        return mean < other.mean;
    }

    bool operator==(const SurfacePatch& other) const
    {
        return Base::operator ==(other) && mean == other.mean && var == other.var && height == other.height;
    }

    Eigen::Vector3f getNormal() const
    {
        return Eigen::Vector3f::UnitZ();
    }

    float getMean() const
    {
        return mean;
    }

    float getHeight() const
    {
        return height;
    }

    float getVariance() const
    {
        return var;
    }

    float getStandardDeviation() const
    {
        return std::sqrt(var);
    }

    bool isVertical() const
    {
        return height != 0.0;
    }

    bool isHorizontal() const
    {
        return height == 0.0;
    }

    float getClosestContactPoint(const Vector3& pos_in_cell, Vector3& contact_point) const
    {
        const float std_dev = getStandardDeviation();
        const float z = pos_in_cell.z();
        if(z > max + std_dev)
        {
            contact_point << pos_in_cell.head<2>(), max + std_dev;
            return z - (max+std_dev);
        }
        else if(z < min - std_dev)
        {
            contact_point << pos_in_cell.head<2>(), min - std_dev;
            return z - (min-std_dev);
        }
        else
        {
            contact_point = pos_in_cell;
            return 0.f;
        }
    }

    float getSurfacePos(const Vector3& pos_in_cell) const
    {
        float std_dev = getStandardDeviation();
        return max + std_dev;
    }

protected:
    /** Grants access to boost serialization */
    friend class boost::serialization::access;

    /** Serializes the members of this class*/
    template <typename Archive>
    void serialize(Archive &ar, const unsigned int version)
    {
        ar & BOOST_SERIALIZATION_BASE_OBJECT_NVP(SurfacePatchBase);
        ar & BOOST_SERIALIZATION_NVP(mean);
        ar & BOOST_SERIALIZATION_NVP(var);
        ar & BOOST_SERIALIZATION_NVP(height);
    }

}; // SurfacePatch<MLSConfig::KALMAN>

/**
 * SurfacePatch type for data exchange
 */
template<>
class SurfacePatch<MLSConfig::PRECALCULATED> : public SurfacePatchBase
{
    typedef SurfacePatchBase Base;
    Eigen::Hyperplane<float, 3> plane;
public:

    SurfacePatch() : SurfacePatchBase()
    {
        // empty
    }

    SurfacePatch(const Eigen::Vector3f& center, const Eigen::Vector3f& normal, const float &min, const float &max) :
                SurfacePatchBase(), plane(normal, center)
    {
        this->min = min;
        this->max = max;
    }

    template<MLSConfig::update_model model>
    SurfacePatch(const SurfacePatch<model>& other) : SurfacePatchBase(other), plane(other.getNormal(), other.getCenter())
    {
        // empty
    }
    template<MLSConfig::update_model model>
    SurfacePatch& operator=(const SurfacePatch<model>& other)
    {
        new(this) SurfacePatch(other);
        return *this;
    }

    Eigen::Vector3f getCenter() const { return plane.normal() * -plane.offset(); }
    Eigen::Vector3f getNormal() const { return plane.normal(); }
    const Eigen::Vector4f& getCoeffs() const { return plane.coeffs(); }
    Eigen::Vector4f& getCoeffs() { return plane.coeffs(); }
    const Eigen::Hyperplane<float, 3>& getPlane() const { return plane; }
    Eigen::Hyperplane<float, 3>& getPlane() { return plane; }

    bool operator<(const SurfacePatch& other) const
    {
        return plane.offset() < other.plane.offset();
    }

    bool operator==(const SurfacePatch& other) const
    {
        return Base::operator==(other) && plane.coeffs() == other.plane.coeffs();
    }

    float getClosestContactPoint(const Vector3& pos_in_cell, Vector3& contact_point) const
    {
        const float distance = plane.signedDistance(pos_in_cell);
        contact_point = plane.projection(pos_in_cell);
        return distance;
    }

    float getSurfacePos(const Vector3& pos_in_cell) const
    {
        float z_pos = (-plane.coeffs()(0) * pos_in_cell(0) - plane.coeffs()(1) * pos_in_cell(1) - plane.coeffs()(3)) / plane.coeffs()(2);
        if(z_pos > max)
            z_pos = max;
        return z_pos;
    }

protected:
    /** Grants access to boost serialization */
    friend class boost::serialization::access;

    /** Serializes the members of this class*/
    template<class Archive>
    void save(Archive & ar, const unsigned int version) const
    {
        ar << BOOST_SERIALIZATION_BASE_OBJECT_NVP(SurfacePatchBase);
        ar << boost::serialization::make_nvp("plane_coeffs", plane.coeffs());
    }

    template<class Archive>
    void load(Archive & ar, const unsigned int version)
    {
        ar >> BOOST_SERIALIZATION_BASE_OBJECT_NVP(SurfacePatchBase);
        if(version == 0)
        {
            Eigen::Vector3f center, normal;
            ar >> boost::serialization::make_nvp("center", center);
            ar >> boost::serialization::make_nvp("normal", normal);
            plane = Eigen::Hyperplane<float, 3>(normal, center);
        }
        else
        {
            ar >> boost::serialization::make_nvp("plane_coeffs", plane.coeffs());
        }

    }

    BOOST_SERIALIZATION_SPLIT_MEMBER()
}; // SurfacePatch<MLSConfig::PRECALCULATED>

/**
 * Given the width of the cells, this outputs the bounding polygon points when intersecting
 * the fitting plane with the cell boundaries.
 * Optionally, it returns the normal vector, as well.
 */
template<MLSConfig::update_model S>
void getPolygon(std::vector<Eigen::Vector3f>& points, const SurfacePatch<S> &sp, const Eigen::Vector2f& posi, const Eigen::Vector2f& cell_size, Eigen::Vector3f * normal_out = 0)
{
    Eigen::Vector3f normal = sp.getNormal();
    if(normal_out) *normal_out = normal;
    float mn, mx;
    sp.getRange(mn,mx);
    Eigen::Vector3f extents, position;
    extents << 0.5f*cell_size, 0.5f*(mx-mn);
    position << posi, 0.5f*(mn+mx);

    Eigen::Vector3f mean = sp.getCenter();
    mean.z() -= position.z();

#ifndef NDEBUG
    // Sanity check (disabled in release mode)
    for(int i=0; i<3; ++i)
    {
        if( std::abs(mean[i]) > extents[i])
        {
            LOG_DEBUG_S << "Mean of SurfacePatch is outside of its extents! {";
            for(int j=0; j<3; ++j) LOG_DEBUG_S << mean[j] << (j==2? "}   {" : ", ");
            for(int j=0; j<3; ++j) LOG_DEBUG_S << extents[j] << (j==2? "}\n" : ", ");
            break;
        }
    }
#endif

    points.clear(); points.reserve(6);

    // first calculate the intersections of the plane with the borders of the box
    // Here, `extents` and `mean` are relative to the origin of the box
    float dist = mean.dot(normal); // scalar product gives the signed distance from the origin

    // find the max coefficient of the normal:
    int i=0, j=1, k=2;
    if(std::abs(normal[i]) < std::abs(normal[j])) std::swap(i,j);
    if(std::abs(normal[i]) < std::abs(normal[k])) std::swap(i,k);

    float dotj = extents[j]*normal[j];
    float dotk = extents[k]*normal[k];

    Eigen::Vector3f prev_p;
    enum { NONE, LOW, BOX, HIGH } prev_pos = NONE, pos;
    // calculate intersections in direction k:
    for(int n=0; n<5; ++n)
    {
        Eigen::Vector3f p(0,0,0);
        float dotp = 0.0f;
        if((n+1)&2)
            dotp += dotj, p[j] = extents[j];
        else
            dotp -= dotj, p[j] = -extents[j];
        if(n&2)
            dotp += dotk, p[k] = extents[k];
        else
            dotp -= dotk, p[k] = -extents[k];

        p[i] = (dist - dotp) / normal[i];

        if( p[i] < -extents[i])
            pos = LOW;
        else if( p[i] > extents[i])
            pos = HIGH;
        else
            pos = BOX;

        if( (prev_pos == LOW || prev_pos == HIGH) && pos != prev_pos )
        {
            // clipping in
            float h = prev_pos == LOW ? -extents[i] : extents[i];
            float s = (h - prev_p[i]) / (p[i] - prev_p[i]);
            Eigen::Vector3f cp = prev_p + (p - prev_p) * s;
            points.push_back(position + cp);
        }
        if( pos == BOX )
        {
            // plane intersected with outer square
            // for mostly horizontal patches this is the standard case
            if(n!=4) // do not push again, if we started here
                points.push_back(position + p);
        }
        else if( pos != prev_pos && prev_pos != NONE )
        {
            // clipping out
            float h = pos == LOW ? -extents[i] : extents[i];
            float s = (h - prev_p[i]) / (p[i] - prev_p[i]);
            Eigen::Vector3f cp = prev_p + (p - prev_p) * s;
            points.push_back(position + cp);
        }

        prev_pos = pos;
        prev_p = p;
    }
}

/**
 * Given the width of the cells, this outputs the bounding polygon points when intersecting
 * the fitting plane with the cell boundaries.
 * This function calculates the cells position using the Index vector (in local grid coordinates).
 * Optionally, it returns the normal vector, as well.
 */
template<MLSConfig::update_model S>
void getPolygon(std::vector<Eigen::Vector3f>& points, const SurfacePatch<S> &sp, const Index& idx, const Eigen::Vector2f& cell_size, Eigen::Vector3f * normal_out = 0)
{
    Eigen::Vector2f posi((idx.x()+0.5f)*cell_size.x(), (idx.y()+0.5f)*cell_size.y());
    getPolygon(points, sp, posi, cell_size, normal_out);
}

}  // namespace grid
}  // namespace maps

BOOST_CLASS_VERSION(maps::grid::SurfacePatch<maps::grid::MLSConfig::SLOPE>, 1);
BOOST_CLASS_VERSION(maps::grid::SurfacePatch<maps::grid::MLSConfig::PRECALCULATED>, 1);

#endif /* __MAPS_SURFACEPATCHES_HPP_ */


text:
package org.apache.qpid.jms.test.testpeer.describedtypes;

import org.apache.qpid.jms.test.testpeer.ListDescribedType;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.UnsignedLong;

/**
 * Generated by generate-described-types.xsl, which resides in this package.
 */
public class SaslInitFrame extends ListDescribedType
{
    public static final Symbol DESCRIPTOR_SYMBOL = Symbol.valueOf("amqp:sasl-init:list");
    public static final UnsignedLong DESCRIPTOR_CODE = UnsignedLong.valueOf(0x0000000000000041L);

    private static final int FIELD_MECHANISM = 0;
    private static final int FIELD_INITIAL_RESPONSE = 1;
    private static final int FIELD_HOSTNAME = 2;

    public SaslInitFrame(Object... fields)
    {
        super(3);
        int i = 0;
        for(Object field : fields)
        {
            getFields()[i++] = field;
        }
    }

    @Override
    public Symbol getDescriptor()
    {
        return DESCRIPTOR_SYMBOL;
    }

    public SaslInitFrame setMechanism(Object o)
    {
        getFields()[FIELD_MECHANISM] = o;
        return this;
    }

    public SaslInitFrame setInitialResponse(Object o)
    {
        getFields()[FIELD_INITIAL_RESPONSE] = o;
        return this;
    }

    public SaslInitFrame setHostname(Object o)
    {
        getFields()[FIELD_HOSTNAME] = o;
        return this;
    }

}


text:
package com.github.fhuss.kafka.streams.cep;

import com.github.fhuss.kafka.streams.cep.core.Sequence;
import com.github.fhuss.kafka.streams.cep.core.pattern.Pattern;
import com.github.fhuss.kafka.streams.cep.core.pattern.PatternBuilder;
import org.apache.kafka.streams.kstream.KStream;

/**
 * Default interface to build a CEP Streams.
 *
 * @param <K>   the record key type.
 * @param <V>   the record value type.
 */
public interface CEPStream<K, V> {

    /**
     *
     * @param queryName     the query name.
     * @param builder       the {@link PatternBuilder} to build the pattern to query.
     * @return              the {@link KStream} that contains only those records that satisfy
     *                      the given pattern with unmodified keys and new values.
     */
    default KStream<K, Sequence<K, V>> query(final String queryName, final PatternBuilder<K, V> builder) {
        return query(queryName, builder, null);
    }

    /**
     *
     * @param queryName     the query name.
     * @param builder       the {@link PatternBuilder} to build the pattern to query.
     * @param queried       the {@link Queried} instance.
     * @return              the {@link KStream} that contains only those records that satisfy
     *                      the given pattern with unmodified keys and new values.
     */
    default KStream<K, Sequence<K, V>> query(final String queryName,
                                             final PatternBuilder<K, V> builder,
                                             final Queried<K, V> queried) {
        return query(queryName, builder.build(), queried);
    }

    /**
     *
     * @param queryName     the query name.
     * @param pattern       the pattern to query.
     * @return              the {@link KStream} that contains only those records that satisfy
     *                      the given pattern with unmodified keys and new values.
     */
    default KStream<K, Sequence<K, V>> query(final String queryName, final Pattern<K, V> pattern) {
        return query(queryName, pattern, null);
    }

    /**
     *
     * @param queryName     the query name.
     * @param pattern       the pattern to query.
     * @param queried       the queried object.
     * @return              the {@link KStream} that contains only those records that satisfy
     *                      the given pattern with unmodified keys and new values.
     */
    KStream<K, Sequence<K, V>> query(final String queryName,
                                     final Pattern<K, V> pattern,
                                     final Queried<K, V> queried);
}


text:
var win = Ti.UI.createWindow({
	backgroundColor : 'white'
});

var quickpdfreader = require('com.kuchbee.quickpdf');
Ti.API.info("module is => " + quickpdfreader);

var button = Ti.UI.createButton({
	top:10,
	left:10,
	right:10,
	title:'Open Pdf File'
});

win.add(button);
button.addEventListener('click',function(e){
	quickpdfreader.openPDF({
		file: 'app',
		password: '',
		isMailEnabled:false, // Is mail option enabled or not
		loadFileFrom: 'resources',
		close: function(e){
			alert('closed');
		}
	});
});

win.open();


text:
<!--
  Generated template for the AddBankPage page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-navbar *navbar faceshop>
  <ion-title>Bank</ion-title>
  <ion-buttons end>
    <button ion-button icon-only (click)="close()">
        <ion-icon name="close"></ion-icon>
      </button>
  </ion-buttons>
</ion-navbar>

<ion-content class="add-bank">
  <ion-list>

    <ion-item>
      <ion-label floating>Name*</ion-label>
      <ion-input type="text" [(ngModel)]="bank.bank_owner"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label floating>Bank No.*</ion-label>
      <ion-input type="text" [(ngModel)]="bank.bank_no"></ion-input>
    </ion-item>

    <ion-item>
      <ion-label floating>Bank Name*</ion-label>
      <ion-input type="text" [(ngModel)]="bank.bank_name"></ion-input>
    </ion-item>

  </ion-list>
  <div text-center *ngIf="bank.bank_owner != '' && bank.bank_no != '' && bank.bank_name != ''">
    <button ion-button round (click)="add(bank)" >Add Bank</button>
  </div>
</ion-content>


text:
require_relative '../../lib/cdo/pegasus'
require 'minitest/autorun'

class StringTest < Minitest::Test
  def test_end_with()
    assert 'hello world'.end_with?('hello world')
    assert 'hello world'.end_with?('')
    assert 'hello world'.end_with?('world')
    assert 'hello world'.end_with?(' world')
    assert 'hello world'.end_with?('o world')
    assert !('hello world'.end_with?('hello'))
    assert !('hello world'.end_with?('hello '))
    assert !('hello world'.end_with?('hello w'))
  end

  def test_include_one_of
    assert 'hello world'.include_one_of?('hello')
    assert 'hello world'.include_one_of?('lo wor')
    assert 'hello world'.include_one_of?('world')
    assert !('hello world'.include_one_of?('goodbye'))
  end

  def test_multiply_concat
    assert_equal ['ac', 'ad', 'bc', 'bd'], String.multiply_concat(['a','b'], ['c','d'])
  end

  def test_to_bool
    %w(true t yes y 1).each{|true_value| assert true_value.to_bool}
    ['', 'false','f','no','n','0'].each{|false_value| assert !false_value.to_bool}
  end

  def test_utf8_to_iso_8859
    iso_8859_string = "ISO-8859 test \xE0" # Includes an à in ISO-8859-1
    assert_raises ArgumentError do
      # .gsub on an ISO-8859-1 encoded string throws an error
      iso_8859_string.gsub(/test regex/, 'replacement')
    end

    forced_string = iso_8859_string.force_8859_to_utf8
    assert_equal('ISO-8859 test à', forced_string)
    assert_equal('ISO-8859 replacement à', forced_string.gsub(/test/, 'replacement'))
    assert_equal('normal string', 'normal string'.force_8859_to_utf8)
    assert_equal('UTF-8sπ´å™£¢∞¡™£', 'UTF-8sπ´å™£¢∞¡™£'.force_8859_to_utf8)
  end
end


text:
module.exports = KeyRingAgentPlugin;

var mod_util = require('util');
var mod_assert = require('assert-plus');
var mod_sshpk = require('sshpk');
var mod_agent = require('sshpk-agent');
var mod_vasync = require('vasync');
var mod_errors = require('./errors');
var KeyRingPlugin = require('./krplugin');

var mod_keypair = require('./keypair');
var KeyPair = mod_keypair.KeyPair;
var LockedKeyPair = mod_keypair.LockedKeyPair;

function KeyRingAgentPlugin(kr, opts) {
	KeyRingPlugin.call(this, kr, opts);
	mod_assert.optionalObject(opts.sshAgentOpts);

	this.kra_error = undefined;
	this.kra_agent = new mod_agent.Client(opts.sshAgentOpts);
}
mod_util.inherits(KeyRingAgentPlugin, KeyRingPlugin);

KeyRingAgentPlugin.prototype.listKeys = function (cb) {
	var self = this;
	if (!this.kra_agent) {
		cb(null, []);
		return;
	}
	this.kra_agent.listKeys(function (err, keys) {
		if (err) {
			cb(err);
			return;
		}
		var kps = keys.map(function (k) {
			return (new AgentKeyPair(self.krp_kr, self.kra_agent, {
			    plugin: 'agent', public: k }));
		});
		cb(null, kps);
	});
};

KeyRingAgentPlugin.shortName = 'agent';

KeyRingAgentPlugin.prototype.findKey = function (fp, cb) {
	mod_assert.ok(mod_sshpk.Fingerprint.isFingerprint(fp));
	var self = this;
	if (!this.kra_agent) {
		cb(new mod_errors.KeyNotFoundError(fp, ['SSH agent']));
		return;
	}
	this.kra_agent.listKeys(function (err, keys) {
		if (err) {
			cb(err);
			return;
		}
		for (var i = 0; i < keys.length; ++i) {
			if (fp.matches(keys[i])) {
				var kp = new AgentKeyPair(self.krp_kr,
				    self.kra_agent, { plugin: 'agent',
				    public: keys[i] });
				cb(null, [kp]);
				return;
			}
		}
		cb(new mod_errors.KeyNotFoundError(fp, ['SSH agent']));
	});
};

function AgentKeyPair(kr, agent, opts) {
	KeyPair.call(this, kr, opts);
	this.akp_agent = agent;
}
mod_util.inherits(AgentKeyPair, KeyPair);

AgentKeyPair.prototype.getPrivateKey = function () {
	throw (new Error('Agent private keys cannot be directly retrieved'));
};

AgentKeyPair.prototype.canSign = function () {
	return (true);
};

AgentKeyPair.prototype.createSign = function (opts) {
	mod_assert.object(opts, 'options');
	mod_assert.optionalString(opts.algorithm, 'options.algorithm');
	mod_assert.optionalString(opts.keyId, 'options.keyId');
	mod_assert.string(opts.user, 'options.user');
	mod_assert.optionalString(opts.subuser, 'options.subuser');
	mod_assert.optionalBool(opts.mantaSubUser, 'options.mantaSubUser');

	var pub = this.getPublicKey();
	var keyId = this.getKeyId();
	var alg = opts.algorithm;
	var algParts = alg ? alg.toLowerCase().split('-') : [];

	if (algParts[0] && algParts[0] !== pub.type) {
		throw (new Error('Requested algorithm ' + alg + ' is ' +
		    'not supported with a key of type ' + pub.type));
	}

	var self = this;
	var cache = this.skp_kr.getSignatureCache();

	function sign(data, cb) {
		if (Buffer.isBuffer(data)) {
			mod_assert.buffer(data, 'data');
		} else {
			mod_assert.string(data, 'data');
		}
		mod_assert.func(cb, 'callback');

		var ck = { key: pub, data: data };
		if (Buffer.isBuffer(data))
			ck.data = data.toString('base64');
		if (cache.get(ck, cb))
			return;
		cache.registerPending(ck);

		self.akp_agent.sign(pub, data, function (err, sig) {
			if (err) {
				cb(err);
				return;
			}

			var res = {
			    algorithm: pub.type + '-' + sig.hashAlgorithm,
			    keyId: keyId,
			    signature: sig.toString(),
			    user: opts.user,
			    subuser: opts.subuser
			};
			sign.algorithm = res.algorithm;

			cache.put(ck, null, res);
			cb(null, res);
		});
	}

	sign.keyId = keyId;
	sign.user = opts.user;
	sign.subuser = opts.subuser;
	sign.getKey = function (cb) {
		cb(null, self.skp_public);
	};
	return (sign);
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using Umbraco.Web;
using System.Globalization;

namespace mUtility.Umbraco.Validation
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = true)]
    public class UmbracoDateFieldsCompareAttribute : ValidationAttribute
    {

        /// <summary>
        /// Gets or sets the error message dictionary key.
        /// </summary>
        /// <value>
        /// The error message dictionary key.
        /// </value>
        //public string ErrorMessageDictionaryKey { get; set; }

        /// <summary>
        /// The umbraco
        /// </summary>
        private UmbracoHelper umbraco = new UmbracoHelper(UmbracoContext.Current);

        /// <summary>
        /// The date format
        /// </summary>
        private string dateFormat = string.Empty;
        /// <summary>
        /// The date field to compare with
        /// </summary>
        private string dateFieldToCompareWith = string.Empty;
        /// <summary>
        /// The comparison type
        /// </summary>
        private DateComparisonType comparisonType;

        /// <summary>
        /// Initializes a new instance of the <see cref="UmbracoDateFieldsCompareAttribute"/> class.
        /// </summary>
        /// <param name="dateFieldToCompareWith">The date field to compare with.</param>
        /// <param name="dateComparisonType">Type of the date comparison.</param>
        public UmbracoDateFieldsCompareAttribute(string dateFieldToCompareWith, DateComparisonType dateComparisonType, string errorMessageDictionaryKey)
        {
            this.dateFieldToCompareWith = dateFieldToCompareWith;
            this.comparisonType = dateComparisonType;

            if (!string.IsNullOrWhiteSpace(errorMessageDictionaryKey))
                base.ErrorMessage = umbraco.GetDictionaryValue(errorMessageDictionaryKey);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="UmbracoDateFieldsCompareAttribute"/> class.
        /// </summary>
        /// <param name="dateFormat">The date format.</param>
        /// <param name="dateFieldToCompareWith">The date field to compare with.</param>
        /// <param name="dateComparisonType">Type of the date comparison.</param>
        public UmbracoDateFieldsCompareAttribute(string dateFormat, string dateFieldToCompareWith, DateComparisonType dateComparisonType, string errorMessageDictionaryKey)
        {
            this.dateFormat = dateFormat;
            this.dateFieldToCompareWith = dateFieldToCompareWith;
            this.comparisonType = dateComparisonType;

            if (!string.IsNullOrWhiteSpace(errorMessageDictionaryKey))
                base.ErrorMessage = umbraco.GetDictionaryValue(errorMessageDictionaryKey);
        }

        /// <summary>
        /// Validates the specified value with respect to the current validation attribute.
        /// </summary>
        /// <param name="value">The value to validate.</param>
        /// <param name="validationContext">The context information about the validation operation.</param>
        /// <returns>
        /// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class.
        /// </returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                DateTime result;

                if (!string.IsNullOrWhiteSpace(dateFormat))
                {
                    if (DateTime.TryParseExact(value.ToString(), dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
                    {
                        return CompareDates(result, validationContext);
                    }
                }
                else
                {
                    if (DateTime.TryParse(value.ToString(), out result))
                    {
                        return CompareDates(result, validationContext);
                    }
                }
            }

            return ValidationResult.Success;
        }

        /// <summary>
        /// Compares the dates.
        /// </summary>
        /// <param name="date">The date.</param>
        /// <param name="validationContext">The validation context.</param>
        /// <returns></returns>
        private ValidationResult CompareDates(DateTime date, ValidationContext validationContext)
        {
            if (!string.IsNullOrWhiteSpace(dateFieldToCompareWith))
            {
                DateTime result;

                var dateToCompare = validationContext.ObjectType.GetProperty(dateFieldToCompareWith).GetValue(validationContext.ObjectInstance, null);

                if (dateToCompare != null)
                {
                    if (!string.IsNullOrWhiteSpace(dateFormat))
                    {
                        if (DateTime.TryParseExact(dateToCompare.ToString(), dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
                        {
                            return SwitchComparisonTypes(date, result, validationContext);
                        }
                    }
                    else
                    {
                        if (DateTime.TryParse(dateToCompare.ToString(), out result))
                        {
                            return SwitchComparisonTypes(date, result, validationContext);
                        }
                    }
                }
            }

            return ValidationResult.Success;
        }

        /// <summary>
        /// Switches the comparison types.
        /// </summary>
        /// <param name="fieldDate">The field date.</param>
        /// <param name="fieldToCompareDate">The field to compare date.</param>
        /// <returns></returns>
        private ValidationResult SwitchComparisonTypes(DateTime fieldDate, DateTime fieldToCompareDate, ValidationContext validationContext)
        {
            switch (comparisonType)
            {
                case DateComparisonType.GreaterThan:

                    if (fieldDate > fieldToCompareDate)
                        return ValidationResult.Success;

                    return new ValidationResult(base.ErrorMessageString, new List<string>() { validationContext.MemberName });

                case DateComparisonType.GreaterThanOrEqual:

                    if (fieldDate >= fieldToCompareDate)
                        return ValidationResult.Success;

                    return new ValidationResult(base.ErrorMessageString, new List<string>() { validationContext.MemberName });

                case DateComparisonType.LowerThanOrEqual:

                    if (fieldDate <= fieldToCompareDate)
                        return ValidationResult.Success;

                    return new ValidationResult(base.ErrorMessageString, new List<string>() { validationContext.MemberName });

                case DateComparisonType.LowerThan:

                    if (fieldDate < fieldToCompareDate)
                        return ValidationResult.Success;

                    return new ValidationResult(base.ErrorMessageString, new List<string>() { validationContext.MemberName });

                case DateComparisonType.Equal:

                    if (fieldDate == fieldToCompareDate)
                        return ValidationResult.Success;

                    return new ValidationResult(base.ErrorMessageString, new List<string>() { validationContext.MemberName });

                default:
                    return ValidationResult.Success;
            }
        }
    }
}


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

	<ListView
	    android:id="@+id/accountsListView"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content" >
	</ListView>

</LinearLayout>


text:
An image that lets us build android apps with docker using gitlab-ci

## Build command

```bash
docker build -t ekreative/android .
```

## Build an app

```bash
docker run -ti --rm --volume=$(pwd):/srv -w /srv ekreative/android ./gradlew assembleRelease
```

## Credit

Borrowed a few ideas from [jacekmarchwicki/android](https://hub.docker.com/r/jacekmarchwicki/android/)
And license accepter from [thyrlian/AndroidSDK](https://github.com/thyrlian/AndroidSDK/blob/master/android-sdk/license_accepter.sh)

## Finding new packages

I use this command to list the available packages

```bash
sdkmanager --list
```


text:
(function (app) {

	/*
	 * Serving the list of repos
	**/
	app.controller('ReposCtrl', [
		'$scope',
		'ghUser',
		'GitHubApiService',
		function ($scope, ghUser, GitHubApiService) {

			$scope.repos = null;
			$scope.loading = true;
			GitHubApiService
				.getRepos(ghUser)
				.success(function (resp) {
					$scope.repos = resp.data;
					$scope.loading = false;
				});

		}
	]);

})(angular.module('ghSwag'));


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2021 Google LLC

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.
-->
<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.google.cloud.bigtable</groupId>
    <artifactId>bigtable-hbase-mirroring-client-2.x-parent</artifactId>
    <version>0.1.4-SNAPSHOT</version> <!-- {x-version-update:bigtable-hbase-mirroring:current} -->
  </parent>

  <artifactId>bigtable-hbase-mirroring-client-2.x-shaded</artifactId>
  <packaging>jar</packaging>
  <version>0.1.4-SNAPSHOT</version> <!-- {x-version-update:bigtable-hbase-mirroring:current} -->

  <name>${project.groupId}:${project.artifactId}</name>
  <description>
    Bigtable/HBase Mirroring Client conforming to HBase API 2.x. Uses hbase-shaded-client and shades all dependencies.
  </description>

  <dependencies>
    <!-- Internal dependencies that will be shaded along with their transitive dependencies. -->
    <dependency>
      <groupId>com.google.cloud.bigtable</groupId>
      <artifactId>bigtable-hbase-mirroring-client-2.x</artifactId>
      <version>0.1.4-SNAPSHOT</version> <!-- {x-version-update:bigtable-hbase-mirroring:current} -->
      <scope>compile</scope>
    </dependency>

    <!-- Manually promote dependencies: This is necessary to avoid flattening hbase-shaded-client's dependency tree -->
    <dependency>
      <groupId>org.apache.hbase</groupId>
      <artifactId>hbase-shaded-client</artifactId>
      <version>${hbase2.version}</version>
    </dependency>

    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>${commons-logging.version}</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <shadedArtifactAttached>false</shadedArtifactAttached>
              <createDependencyReducedPom>true</createDependencyReducedPom>
              <filters>
                <filter>
                  <artifact>*:*</artifact>
                  <excludes>
                    <exclude>META-INF/*.SF</exclude>
                    <exclude>META-INF/*.DSA</exclude>
                    <exclude>META-INF/*.RSA</exclude>
                    <exclude>META-INF/**/pom.properties</exclude>
                    <exclude>META-INF/**/pom.xml</exclude>
                    <exclude>META-INF/MANIFEST.MF</exclude>
                    <exclude>META-INF/LICENSE</exclude>
                    <exclude>META-INF/LICENSE.txt</exclude>
                    <exclude>META-INF/NOTICE</exclude>
                    <exclude>META-INF/DEPENDENCIES</exclude>
                    <exclude>META-INF/NOTICE.txt</exclude>
                    <exclude>META-INF/versions/9/module-info.class</exclude>
                  </excludes>
                </filter>
              </filters>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
              </transformers>
              <artifactSet>
                <excludes>
                  <!-- exclude user visible deps -->
                  <exclude>commons-logging:commons-logging</exclude>
                  <!-- exclude hbase-shaded-client & all of its dependencies -->
                  <exclude>org.apache.hbase:hbase-shaded-client</exclude>
                  <exclude>org.slf4j:slf4j-api</exclude>
                  <exclude>log4j:log4j</exclude>
                  <exclude>org.apache.htrace:htrace-core4</exclude>
                  <exclude>org.apache.yetus:audience-annotations</exclude>
                  <exclude>
                    com.github.stephenc.findbugs:findbugs-annotations
                  </exclude>
                  <exclude>log4j:log4j</exclude>
                </excludes>
              </artifactSet>
              <relocations>
                <relocation>
                  <pattern>com.google</pattern>
                  <shadedPattern>${shading-prefix}.com.google</shadedPattern>
                  <excludes>
                    <!-- don't shade our public hbase implementation. This includes com.google.cloud.bigtable.mirroring.hbase.*
                     and references to com.google.cloud.bigtable.mirroring.hbase1_x in the version specific jars.
                    -->
                    <exclude>com.google.cloud.bigtable.mirroring.core.**</exclude>
                    <exclude>com.google.cloud.bigtable.mirroring.hbase*.**</exclude>

                    <!-- in case maven is called with overlapping goals (ie. mvn install verify),
                    avoid double relocation -->
                    <exclude>${shading-prefix}.**</exclude>
                  </excludes>
                </relocation>

                <relocation>
                  <pattern>com.fasterxml</pattern>
                  <shadedPattern>${shading-prefix}.com.fasterxml</shadedPattern>
                </relocation>
                <relocation>
                  <pattern>io.opencensus</pattern>
                  <shadedPattern>${shading-prefix}.io.opencensus</shadedPattern>
                </relocation>
                <!-- grpc is used only by opencensus dependency -->
                <relocation>
                  <pattern>io.grpc</pattern>
                  <shadedPattern>${shading-prefix}.io.grpc</shadedPattern>
                </relocation>
                <relocation>
                  <pattern>org.checkerframework</pattern>
                  <shadedPattern>${shading-prefix}.org.checkerframework</shadedPattern>
                </relocation>
                <relocation>
                  <pattern>javax.annotation</pattern>
                  <shadedPattern>${shading-prefix}.javax.annotation</shadedPattern>
                </relocation>
                <relocation>
                  <pattern>com.fasterxml</pattern>
                  <shadedPattern>${shading-prefix}.com.fasterxml</shadedPattern>
                </relocation>
                <relocation>
                  <pattern>io.opencensus</pattern>
                  <shadedPattern>${shading-prefix}.io.opencensus</shadedPattern>
                </relocation>
                <!-- grpc is used only by opencensus dependency -->
                <relocation>
                  <pattern>io.grpc</pattern>
                  <shadedPattern>${shading-prefix}.io.grpc</shadedPattern>
                </relocation>
                <!-- protobuf-java-format-shaded exposes already shaded classes -->
                <relocation>
                  <pattern>net.javacrumbs.futureconverter</pattern>
                  <shadedPattern>${shading-prefix}.net.javacrumbs.futureconverter</shadedPattern>
                </relocation>
              </relocations>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-enforcer-plugin</artifactId>
        <executions>
          <execution>
            <id>enforce</id>
            <configuration>
              <rules>
                <requireUpperBoundDeps>
                  <excludes>
                    <!--
                    ${guava.version} == 30.1-android
                    api-common:1.10.4 requires 30.1.1-android
                     -->
                    <exclude>com.google.guava:guava</exclude>
                    <!--
                    guava:30.1-android requires error_prone_annotations:2.3.4
                    truth:1.1.2 requires error_prone_annotations:2.5.1
                     -->
                    <exclude>com.google.errorprone:error_prone_annotations</exclude>
                  </excludes>
                </requireUpperBoundDeps>
              </rules>
            </configuration>
            <goals>
              <goal>enforce</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>com.google.cloud.bigtable.test</groupId>
        <artifactId>bigtable-build-helper</artifactId>
        <version>2.6.4-SNAPSHOT</version> <!-- {x-version-update:bigtable-client-parent:current} -->

        <executions>
          <execution>
            <id>verify-shaded-jar-entries</id>
            <phase>verify</phase>
            <goals>
              <goal>verify-shaded-jar-entries</goal>
            </goals>
            <configuration>
              <allowedJarClassEntries>
                <classEntry>${shading-prefix-path}</classEntry>
                <classEntry>com/google/cloud/bigtable/mirroring</classEntry>
              </allowedJarClassEntries>
            </configuration>
          </execution>
          <execution>
            <id>verify-shaded-exclusions</id>
            <phase>verify</phase>
            <goals>
              <goal>verify-shaded-exclusions</goal>
            </goals>
          </execution>
          <execution>
            <id>verify-mirror-deps</id>
            <phase>verify</phase>
            <goals>
              <goal>verify-mirror-deps</goal>
            </goals>
            <configuration>
              <targetDependencies>
                <targetDependency>org.apache.hbase:hbase-shaded-client</targetDependency>
              </targetDependencies>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <!-- skip for shaded jar-->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <configuration>
          <ignoredDependencies>
            <dependency>*</dependency>
          </ignoredDependencies>
        </configuration>
      </plugin>
      <!-- skip for shaded jar-->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>clirr-maven-plugin</artifactId>
        <configuration>
          <skip>true</skip>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
import _ from 'underscore';

import FileModel from '@girder/core/models/FileModel';
import View from '@girder/core/views/View';
import events from '@girder/core/events';
import { renderMarkdown, formatSize } from '@girder/core/misc';

import MarkdownWidgetTemplate from '@girder/core/templates/widgets/markdownWidget.pug';

import '@girder/core/stylesheets/widgets/markdownWidget.styl';

import '@girder/core/utilities/jquery/girderEnable';

import 'bootstrap/js/tab';

/**
 * A simple widget for editing markdown text with a preview tab.
 */
var MarkdownWidget = View.extend({
    events: {
        'show.bs.tab .g-preview-link': function () {
            renderMarkdown(this.val().trim() || 'Nothing to show',
                this.$('.g-markdown-preview'));
        },

        'shown.bs.tab .g-write-link': function () {
            this.$('.g-markdown-text').trigger('focus');
        },

        'click .g-browse': function () {
            this.$('.g-file-input').trigger('click');
        },

        'change .g-file-input': function (e) {
            var files = e.target.files;

            if (files.length) {
                this.files = files;
                this.filesAdded();
            }
        },

        'dragenter .g-markdown-drop-zone': function (e) {
            e.stopPropagation();
            e.preventDefault();
            e.originalEvent.dataTransfer.dropEffect = 'copy';
            this.$('.g-markdown-text,.g-upload-footer').addClass('dragover');
        },

        'dragleave .g-markdown-drop-zone': function (e) {
            e.stopPropagation();
            e.preventDefault();
            this.$('.g-markdown-text,.g-upload-footer').removeClass('dragover');
        },

        'dragover .g-markdown-drop-zone': function (e) {
            e.originalEvent.dataTransfer.dropEffect = 'copy';
            this.$('.g-markdown-text,.g-upload-footer').addClass('dragover');
        },

        'drop .g-markdown-drop-zone': function (e) {
            e.stopPropagation();
            e.preventDefault();
            this.$('.g-markdown-text,.g-upload-footer').removeClass('dragover');
            this.files = e.originalEvent.dataTransfer.files;
            this.filesAdded();
        }
    },

    /**
     * @param [settings.text=''] Initial markdown text.
     * @param [settings.placeholder=''] Text area placeholder.
     * @param [settings.prefix='markdown'] Prefix for element IDs in case
     *     multiple of these widgets are rendered simultaneously.
     * @param [settings.enableUploads=false] Whether to allow uploading files
     *     inline into the markdown.
     * @param [settings.maxUploadSize=10 MB] Max upload size in bytes.
     * @param [settings.parent] If enableUploads is true, set this to the object
     *     into which files should be uploaded.
     * @param [settings.allowedExtensions=null] If you want to restrict to
     *     certain file extensions, set this to a list of (lowercase) extensions,
     *     not including periods. E.g.: ["png", "jpg", "jpeg"]
     */
    initialize: function (settings) {
        this.text = settings.text || '';
        this.placeholder = settings.placeholder || '';
        this.prefix = settings.prefix || 'markdown';
        this.enableUploads = settings.enableUploads || false;
        this.parent = settings.parent || null;
        this.maxUploadSize = settings.maxUploadSize || 1024 * 1024 * 10;
        this.allowedExtensions = settings.allowedExtensions || null;
        this.files = [];
    },

    filesAdded: function () {
        try {
            this.validateFiles();
        } catch (err) {
            events.trigger('g:alert', {
                type: 'danger',
                text: err.message,
                icon: 'cancel',
                timeout: 5000
            });
            return;
        }

        var file = this.files[0];
        var fileModel = new FileModel();

        fileModel.on('g:upload.complete', function () {
            var val = this.$('.g-markdown-text').val();
            val += '![' + file.name + '](' + fileModel.downloadUrl() + ')\n';

            this.$('.g-upload-overlay').addClass('hide');
            this.$('.g-markdown-text').girderEnable(true).val(val);

            this.trigger('g:fileUploaded', {
                file: file,
                model: fileModel
            });
        }, this).on('g:upload.progress', function (info) {
            var currentProgress = info.startByte + info.loaded;
            this.$('.g-markdown-upload-progress>.progress-bar').css('width',
                Math.ceil(100 * currentProgress / info.total) + '%');
            this.$('.g-markdown-upload-progress-message').text(
                'Uploading ' + info.file.name + ' - ' +
                   formatSize(currentProgress) + ' / ' +
                   formatSize(info.total)
            );
        }, this).on('g:upload.error', function (info) {
            events.trigger('g:alert', {
                type: 'danger',
                text: info.message,
                icon: 'cancel',
                timeout: 5000
            });
            this.$('.g-upload-overlay').addClass('hide');
            this.$('.g-markdown-text').girderEnable(true);
        }, this).on('g:upload.errorStarting', function (info) {
            events.trigger('g:alert', {
                type: 'danger',
                text: info.message,
                icon: 'cancel',
                timeout: 5000
            });
            this.$('.g-upload-overlay').addClass('hide');
            this.$('.g-markdown-text').girderEnable(true);
        }, this).upload(this.parent, file);

        this.$('.g-upload-overlay').removeClass('hide');
        this.$('.g-markdown-text').girderEnable(false);
    },

    /**
     * Validate a selection of files. If invalid, throws an object containing
     * a "message" field.
     */
    validateFiles: function (files) {
        files = files || this.files;

        if (this.files.length !== 1) {
            throw new Error('Please add only one file at a time.');
        }

        var file = files[0],
            ext = file.name.split('.').pop().toLowerCase();

        if (this.maxUploadSize && file.size > this.maxUploadSize) {
            throw new Error(
                'That file is too large. You may only attach files ' +
                'up to ' + formatSize(this.maxUploadSize) + '.'
            );
        }

        if (this.allowedExtensions && !_.contains(this.allowedExtensions, ext)) {
            throw new Error(
                'Only files with the following extensions are allowed: ' +
                this.allowedExtensions.join(', ') + '.'
            );
        }
    },

    render: function () {
        this.$el.html(MarkdownWidgetTemplate({
            text: this.text,
            placeholder: this.placeholder,
            prefix: this.prefix,
            enableUploads: this.enableUploads
        }));

        return this;
    },

    /**
     * Get or set the current markdown text. Call with no arguments to return
     * the current value, or call with one argument to set the value to that.
     */
    val: function () {
        if (arguments.length) {
            return this.$('.g-markdown-text').val(arguments[0]);
        } else {
            return this.$('.g-markdown-text').val();
        }
    },

    /**
     * Normally, calling render() on this widget will reset it to its initial text
     * value. Call this to set the text value that should be shown on re-render
     * to the current value of the text area.
     */
    saveText: function () {
        this.text = this.val();
    }
});

export default MarkdownWidget;


text:
package org.wso2.carbon.uuf.sample.petsstore.bundle.internal.impl;

import org.wso2.carbon.uuf.sample.petsstore.bundle.service.PetsManager;

public class PetsManagerImpl implements PetsManager {

    @Override
    public String getHelloMessage(String name) {
        return "Hello " + name + "!";
    }
}


text:
require 'spec_helper'

RSpec.describe CredHubble::Resources::Health do
  describe '.from_json' do
    subject { CredHubble::Resources::Health }

    context 'when the JSON includes the required attributes' do
      let(:json_response) { '{"status": "UP"}' }

      it 'instantiates a new Health object with the correct values' do
        health = subject.from_json(json_response)
        expect(health.status).to eq('UP')
      end
    end

    it_behaves_like 'a JSON deserializing resource'
  end

  describe 'immutability' do
    subject { CredHubble::Resources::Health.new(status: 'UP') }

    it_behaves_like 'an immutable resource', :status
  end
end


text:
"""
usage: teuthology --help
       teuthology --version
       teuthology [options] [--] <config>...

Run ceph integration tests

positional arguments:
  <config> one or more config files to read

optional arguments:
  -h, --help                     show this help message and exit
  -v, --verbose                  be more verbose
  --version                      the current installed version of teuthology
  -a DIR, --archive DIR          path to archive results in
  --description DESCRIPTION      job description
  --owner OWNER                  job owner
  --lock                         lock machines for the duration of the run
  --machine-type MACHINE_TYPE    Type of machine to lock/run tests on.
  --os-type OS_TYPE              Distro/OS of machine to run test on.
  --os-version OS_VERSION        Distro/OS version of machine to run test on.
  --block                        block until locking machines succeeds (use with --lock)
  --name NAME                    name for this teuthology run
  --suite-path SUITE_PATH        Location of ceph-qa-suite on disk. If not specified,
                                 it will be fetched
"""
import docopt

import teuthology.run

def main():
    args = docopt.docopt(__doc__, version=teuthology.__version__)
    teuthology.run.main(args)


text:
package org.apache.drill.exec.rpc;

import java.util.Map;
import java.util.concurrent.Executor;

import org.apache.drill.shaded.guava.com.google.common.base.Preconditions;
import org.apache.drill.shaded.guava.com.google.common.collect.ImmutableMap;
import org.apache.drill.shaded.guava.com.google.common.collect.Maps;
import com.google.protobuf.Internal.EnumLite;
import com.google.protobuf.MessageLite;

public class RpcConfig {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RpcConfig.class);

  private final String name;
  private final int timeout;
  private final Map<EnumLite, RpcMessageType<?, ?, ?>> sendMap;
  private final Map<Integer, RpcMessageType<?, ?, ?>> receiveMap;
  private final Executor executor;

  private RpcConfig(String name, Map<EnumLite, RpcMessageType<?, ?, ?>> sendMap,
      Map<Integer, RpcMessageType<?, ?, ?>> receiveMap, int timeout, Executor executor) {
    Preconditions.checkNotNull(executor, "Executor must be defined.");
    this.name = name;
    this.timeout = timeout;
    this.sendMap = ImmutableMap.copyOf(sendMap);
    this.receiveMap = ImmutableMap.copyOf(receiveMap);
    this.executor = executor;
  }

  public String getName() {
    return name;
  }

  public int getTimeout() {
    return timeout;
  }

  public boolean hasTimeout() {
    return timeout > 0;
  }

  public Executor getExecutor() {
    return executor;
  }

  public boolean checkReceive(int rpcType, Class<?> receiveClass) {
    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug(String.format("Checking reception for rpcType %d and receive class %s.", rpcType, receiveClass));
    }
    RpcMessageType<?,?,?> type = receiveMap.get(rpcType);
    if (type == null) {
      throw new IllegalStateException(String.format("%s: There is no defined RpcMessage type for a Rpc receive type number of %s.", name, rpcType));
    }

    if (receiveClass != type.getRet()) {
      throw new IllegalStateException(String.format("%s: The definition for receive doesn't match implementation code.  The definition is %s however the current receive for this type was of type %s.", name, type, receiveClass.getCanonicalName()));
    }
    return true;
  }

  public boolean checkSend(EnumLite send, Class<?> sendClass, Class<?> receiveClass) {
    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug(String.format("Checking send classes for send RpcType %s.  Send Class is %s and Receive class is %s.", send, sendClass, receiveClass));
    }
    RpcMessageType<?,?,?> type = sendMap.get(send);
    if (type == null) {
      throw new IllegalStateException(String.format("%s: There is no defined RpcMessage type for a Rpc send type of %s.", name, send));
    }

    if (type.getSend() != sendClass) {
      throw new IllegalStateException(String.format("%s: The definition for send doesn't match implementation code.  The definition is %s however the current send is trying to send an object of type %s.", name, type, sendClass.getCanonicalName()));
    }
    if (type.getRet() != receiveClass) {
      throw new IllegalStateException(String.format("%s: The definition for send doesn't match implementation code.  The definition is %s however the current send is trying to setup an expected reception of an object of type %s.", name, type, receiveClass.getCanonicalName()));
    }

    return true;
  }

  public boolean checkResponseSend(EnumLite responseType, Class<?> responseClass) {
    if (RpcConstants.EXTRA_DEBUGGING) {
      logger.debug(String.format("Checking responce send of type %s with response class of %s.",  responseType, responseClass));
    }
    RpcMessageType<?,?,?> type = receiveMap.get(responseType.getNumber());
    if (type == null) {
      throw new IllegalStateException(String.format("%s: There is no defined RpcMessage type for a Rpc response of type %s.", name, responseType));
    }
    if (type.getRet() != responseClass) {
      throw new IllegalStateException(String.format("%s: The definition for the response doesn't match implementation code.  The definition is %s however the current response is trying to response with an object of type %s.", name, type, responseClass.getCanonicalName()));
    }

    return true;
  }

  public static class RpcMessageType<SEND extends MessageLite, RECEIVE extends MessageLite, T extends EnumLite>{
    private T sendEnum;
    private Class<SEND> send;
    private T receiveEnum;
    private Class<RECEIVE> ret;
    public RpcMessageType(T sendEnum, Class<SEND> send, T receiveEnum, Class<RECEIVE> ret) {
      super();
      this.sendEnum = sendEnum;
      this.send = send;
      this.receiveEnum = receiveEnum;
      this.ret = ret;
    }
    public Class<SEND> getSend() {
      return send;
    }
    public void setSend(Class<SEND> send) {
      this.send = send;
    }
    public T getSendEnum() {
      return sendEnum;
    }
    public void setSendEnum(T sendEnum) {
      this.sendEnum = sendEnum;
    }
    public Class<RECEIVE> getRet() {
      return ret;
    }
    public void setRet(Class<RECEIVE> ret) {
      this.ret = ret;
    }
    public T getReceiveEnum() {
      return receiveEnum;
    }
    public void setReceiveEnum(T receiveEnum) {
      this.receiveEnum = receiveEnum;
    }
    @Override
    public String toString() {
      return "RpcMessageType [sendEnum=" + sendEnum + ", send=" + send + ", receiveEnum=" + receiveEnum + ", ret="
          + ret + "]";
    }

  }

  public static RpcConfigBuilder newBuilder() {
    return new RpcConfigBuilder();
  }

  public static class RpcConfigBuilder {
    private String name;
    private int timeout = -1;
    private Executor executor;
    private Map<EnumLite, RpcMessageType<?, ?, ?>> sendMap = Maps.newHashMap();
    private Map<Integer, RpcMessageType<?, ?, ?>> receiveMap = Maps.newHashMap();

    private RpcConfigBuilder() {
    }

    public RpcConfigBuilder name(String name) {
      this.name = name;
      return this;
    }

    public RpcConfigBuilder timeout(int timeoutInSeconds) {
      this.timeout = timeoutInSeconds;
      return this;
    }

    public <SEND extends MessageLite, RECEIVE extends MessageLite, T extends EnumLite>  RpcConfigBuilder add(T sendEnum, Class<SEND> send, T receiveEnum, Class<RECEIVE> rec) {
      RpcMessageType<SEND, RECEIVE, T> type = new RpcMessageType<SEND, RECEIVE, T>(sendEnum, send, receiveEnum, rec);
      this.sendMap.put(sendEnum, type);
      this.receiveMap.put(receiveEnum.getNumber(), type);
      return this;
    }

    public RpcConfigBuilder executor(Executor executor) {
      this.executor = executor;
      return this;
    }

    public RpcConfig build() {
      Preconditions.checkArgument(timeout > -1, "Timeout must be a positive number or zero for disabled.");
      Preconditions.checkArgument(name != null, "RpcConfig name must be set.");
      return new RpcConfig(name, sendMap, receiveMap, timeout, executor);
    }

  }

}


text:
"""Utilities.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

def ascii_histogram(data, nbins=10, height=20, character='#'):
  """Text-based vertical histogram.

  Returns a multi-line string with a vertical histogram of data.

  Args:
    data: array of data,
    nbins: Number of bins in the histogram.
    height: Height of the histogram in characters.
    character: Character to use.

  Returns:
    Multi-line string.
  """
  h = np.histogram(data, bins=nbins)
  his = """"""
  xl = ['%.2f'%n for n in h[1]]
  lxl = [len(l) for l in xl]
  bars = h[0]/np.max(h[0])*height
  his += ' '*int(np.max(bars)+2+np.max(lxl)) + (
      '%.1f %%\n'%(100.*np.max(h[0])/len(data)))
  for i, c in enumerate(bars):
    line = xl[i] + ' '*int(np.max(lxl)-lxl[i]) + ': ' + character*int(c) + '\n'
    his += line
  return his

def interp_ecdf(data, value):
  """Returns the probabilty of a random variable of being above a threshold.

  Args:
    data: Samples of the random variable.
    value: Interpolation value.
  """
  y_interp = stats.percentileofscore(data, value)/100.

  return y_interp

def prob_above_thr(data, threshold):
  """Returns the probabilty of a random variable of being above a threshold.

  Args:
    data: Samples of the random variable.
    threshold: Threshold for probabiltiy calculation.
  """
  return 1. - interp_ecdf(data, threshold)

def prob_below_thr(data, threshold):
  """Returns the probabilty of a random variable of being below a threshold.

  Args:
    data: Samples of the random variable.
    threshold: Threshold for probabiltiy calculation.
  """
  return interp_ecdf(data, threshold)

def ecdf(data):
  """Empirical CDF.

  Args:
    data: Data

  Returns:
    Tuple (xs, ys):
      - xs: Sorted data values
      - ys: ECDF value
  """
  xs = np.sort(data)
  ys = np.arange(1, len(xs)+1)/float(len(xs))
  return xs, ys

def qqplot(vardata1, vardata2):
  """Plot QQ-plot for two variables.

  Args:
    vardata1: Variable to use for X axis.
    vardata2: Variable to use for Y axis.

  Returns:
    Matplotlib figure
  """
  var1_xs, var1_ecdf_mean_bounds = vardata1.ecdf_data()
  var2_xs, var2_ecdf_mean_bounds = vardata2.ecdf_data()

  quants = np.linspace(0, 1, 1000)

  x_vals = np.interp(quants, var1_ecdf_mean_bounds[0], var1_xs)
  y_vals = np.interp(quants, var2_ecdf_mean_bounds[0], var2_xs)
  min_xvals = min(x_vals[0], y_vals[0])
  max_xvals = max(x_vals[-1], y_vals[-1])
  plt.plot(x_vals, y_vals, 'o')
  plt.plot([min_xvals, max_xvals], [min_xvals, max_xvals], 'k--')
  plt.grid()
  plt.xlabel(vardata1.variable_info['name'])
  plt.ylabel(vardata2.variable_info['name'])

  return plt.gcf()


text: gcloud run deploy --source .