text:
using stan::math::var;
using std::numeric_limits;
using std::vector;

class AgradDistributionsInvGamma : public AgradDistributionTest {
 public:
  void valid_values(vector<vector<double> >& parameters,
                    vector<double>& log_prob) {
    vector<double> param(3);

    param[0] = 1.0;  // y
    param[1] = 1.0;  // alpha
    param[2] = 1.0;  // beta
    parameters.push_back(param);
    log_prob.push_back(-1.0);  // expected log_prob

    param[0] = 0.5;  // y
    param[1] = 2.9;  // alpha
    param[2] = 3.1;  // beta
    parameters.push_back(param);
    log_prob.push_back(-0.8185294827413338580868);  // expected log_prob
  }

  void invalid_values(vector<size_t>& index, vector<double>& value) {
    // y

    // alpha
    index.push_back(1U);
    value.push_back(0.0);

    index.push_back(1U);
    value.push_back(-1.0);

    index.push_back(1U);
    value.push_back(numeric_limits<double>::infinity());

    index.push_back(1U);
    value.push_back(-numeric_limits<double>::infinity());

    // beta
    index.push_back(2U);
    value.push_back(0.0);

    index.push_back(2U);
    value.push_back(-1.0);

    index.push_back(2U);
    value.push_back(numeric_limits<double>::infinity());

    index.push_back(2U);
    value.push_back(-numeric_limits<double>::infinity());
  }

  template <typename T_y, typename T_shape, typename T_scale, typename T3,
            typename T4, typename T5>
  stan::return_type_t<T_y, T_shape, T_scale> log_prob(const T_y& y,
                                                      const T_shape& alpha,
                                                      const T_scale& beta,
                                                      const T3&, const T4&,
                                                      const T5&) {
    return stan::math::inv_gamma_log(y, alpha, beta);
  }

  template <bool propto, typename T_y, typename T_shape, typename T_scale,
            typename T3, typename T4, typename T5>
  stan::return_type_t<T_y, T_shape, T_scale> log_prob(const T_y& y,
                                                      const T_shape& alpha,
                                                      const T_scale& beta,
                                                      const T3&, const T4&,
                                                      const T5&) {
    return stan::math::inv_gamma_log<propto>(y, alpha, beta);
  }

  template <typename T_y, typename T_shape, typename T_scale, typename T3,
            typename T4, typename T5>
  stan::return_type_t<T_y, T_shape, T_scale> log_prob_function(
      const T_y& y, const T_shape& alpha, const T_scale& beta, const T3&,
      const T4&, const T5&) {
    if (y <= 0)
      return stan::math::LOG_ZERO;

    using boost::math::lgamma;
    using stan::math::multiply_log;

    return -lgamma(alpha) + multiply_log(alpha, beta)
           - multiply_log(alpha + 1.0, y) - beta / y;
  }
};

TEST(ProbDistributionsInvGammaCdf, Values) {
  EXPECT_FLOAT_EQ(0.557873, stan::math::inv_gamma_cdf(4.39, 1.349, 3.938));
}


text:
"""
"""
import argparse
import os

import h5py
import numpy as np

from astropy.io import fits

import scipy.interpolate
import scipy.stats.mstats as mstats
import scipy.signal

import matplotlib as mpl
mpl.use('Agg')
mpl.rcParams.update({'font.size': 14})
mpl.rcParams.update({'savefig.dpi': 100})
mpl.rcParams.update({'savefig.bbox': 'tight'})
import matplotlib.pyplot as plt

import bossdata

def plot_median_flux_ratio(wlen, red_ratio, blue_ratio, red_label=None, blue_label=None, show_quantiles=False):

    # Calculate median and 1-sigma quantiles
    quantiles = [scipy.stats.norm.cdf(sigma) for sigma in [-1, 0, 1]]
    red_quantiles = [mstats.mquantiles(red_ratio, q, axis=0)[0] for q in quantiles]
    blue_quantiles = [mstats.mquantiles(blue_ratio, q, axis=0)[0] for q in quantiles]

    # Plot median
    plt.plot(wlen, red_quantiles[1], color='red', label=red_label)
    plt.plot(wlen, blue_quantiles[1], color='blue', label=blue_label)

    if show_quantiles:
        plt.fill_between(wlen, red_quantiles[0], red_quantiles[-1], color='red', alpha=0.3, lw=0)
        plt.fill_between(wlen, blue_quantiles[0], blue_quantiles[-1], color='blue', alpha=0.3, lw=0)

    plt.xlim(wlen[0], wlen[-1])
    plt.ylabel('Median Flux Ratio')
    plt.xlabel(r'Observed Wavelength $\lambda$ $(\mathrm{\AA})$')
    plt.grid()

def main():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--tpcorr', type=str, default=None,
        help='throughput correction filename, required')
    parser.add_argument('--output', type=str, default=None,
        help='output filename')
    parser.add_argument('--validation', action='store_true',
        help='validation reduction')
    args = parser.parse_args()

    # Open the throughput correction file
    tpcorr = h5py.File(args.tpcorr, 'r')
    tpcorr_wave = np.squeeze(tpcorr['wave'].value)

    sdss_finder = bossdata.path.Finder(sas_path='/sas/dr12/sdss', redux_version='26')
    sdss_finder_103 = bossdata.path.Finder(sas_path='/sas/dr12/sdss', redux_version='103')
    sdss_finder_104 = bossdata.path.Finder(sas_path='/sas/dr12/sdss', redux_version='104')
    dr12_finder = bossdata.path.Finder(sas_path='/sas/dr12/boss', redux_version='v5_7_0')
    blue_finder = bossdata.path.Finder(sas_path='/sas/dr12/boss', redux_version='test')

    mirror = bossdata.remote.Manager()

    def get_sdss_spec(plate, mjd, fiber):
        try:
            sdss_spec_name = sdss_finder.get_spec_path(plate, mjd, fiber=fiber, lite=True)
            return bossdata.spec.SpecFile(mirror.get(sdss_spec_name))
        except RuntimeError:
            try:
                sdss_spec_name = sdss_finder_103.get_spec_path(plate, mjd, fiber=fiber, lite=True)
                return bossdata.spec.SpecFile(mirror.get(sdss_spec_name))
            except RuntimeError:
                try:
                    sdss_spec_name = sdss_finder_104.get_spec_path(plate, mjd, fiber=fiber, lite=True)
                    return bossdata.spec.SpecFile(mirror.get(sdss_spec_name))
                except RuntimeError:
                    print 'Could not find sdss spectrum ({}-{}-{}) in redux 26, 203, or 104.'.format(plate,mjd,fiber)
        return None

    if args.validation:
        # Open connection spAll db
        meta_db = bossdata.meta.Database(lite=False, verbose=True)
        # Failed quasars
        sample_selection = 'LAMBDA_EFF=4000 and OBJTYPE="QSO" and CLASS="STAR"'
        # Require targets were on "validation" plates
        validiation_plates = (6130,6131,6135,6136,6147,6155,6157,6290,6293,6296,6297,6298,6307,6506,6509,6590,6681,6734,6816,6986)
        validiation_plates_str = ','.join(['{}'.format(plate) for plate in validiation_plates])
        valid_selection = 'ZWARNING=0 and PLATE in ({})'.format(validiation_plates_str)
        what = 'PLATE,MJD,FIBER'
        sort = 'PLATE,MJD,FIBER'
        where = '{} and {}'.format(sample_selection, valid_selection)
        targets = meta_db.select_all(what, where, sort, max_rows=0)
    else:
        # Find repeat quasar observations using DR12Q (55752 cutoff is approx DR9 cutoff to compare with Paris et al composite)
        dr12q_db = bossdata.meta.Database(quasar_catalog=True, quasar_catalog_name='DR12Q')
        what = 'PLATE,MJD,FIBER,Z_VI,PLATE_DR7,MJD_DR7,FIBERID_DR7'
        where = 'SDSS_DR7!=0 and BAL_FLAG_VI=0 and ZWARNING&(1<<7)=0 and MJD <= 55752'
        sort = 'PLATE,MJD,FIBER'
        targets = dr12q_db.select_all(what, where, sort, max_rows=0)

    num_targets = len(targets)

    print num_targets

    # Use the "fiducial" wavelength grid
    fiducial_loglam = bossdata.spec.fiducial_loglam
    fiducial_wavelength = 10**fiducial_loglam
    num_pixels = len(fiducial_loglam)

    # Allocate masked arrays to store fluxes and ivars
    ref_composite_flux = np.ma.empty((num_targets, num_pixels))
    ref_composite_ivar = np.ma.empty_like(ref_composite_flux)
    ref_composite_flux[:] = np.ma.masked
    ref_composite_ivar[:] = np.ma.masked

    dr12_composite_flux = np.ma.empty_like(ref_composite_flux)
    dr12_composite_ivar = np.ma.empty_like(ref_composite_flux)
    dr12_composite_flux[:] = np.ma.masked
    dr12_composite_ivar[:] = np.ma.masked

    tpcorr_composite_flux = np.ma.empty_like(ref_composite_flux)
    tpcorr_composite_ivar = np.ma.empty_like(ref_composite_flux)
    tpcorr_composite_flux[:] = np.ma.masked
    tpcorr_composite_ivar[:] = np.ma.masked

    num_good_spectra = 0

    for i,target in enumerate(targets):
        plate, mjd, fiber = target['PLATE'],target['MJD'],target['FIBER']
        if i and i % 100 == 0:
            print i, plate, mjd, fiber, num_good_spectra

        # Get the DR12 spectrum
        dr12_spec_name = dr12_finder.get_spec_path(plate, mjd, fiber=fiber, lite=True)
        dr12_spec = bossdata.spec.SpecFile(mirror.get(dr12_spec_name, timeout=None, progress_min_size=0))

        # Make sure this is an offset target
        lambda_eff = dr12_spec.hdulist[2].read_column('LAMBDA_EFF')[0]
        if lambda_eff != 4000:
            # print '{}-{}-{}: LAMBDA_EFF!=4000'.format(plate, mjd, fiber)
            continue

        # Check that correction exists for this target
        tpcorr_key = '/'.join(map(str,[plate,mjd,fiber]))
        if tpcorr_key not in tpcorr:
            print '{}-{}-{}: No correction in tpcorr file.'.format(plate, mjd, fiber)
            continue

        # Get reference fiducial spectrum
        if args.validation:
            spplate_filename = blue_finder.get_plate_spec_path(plate, mjd)
            platefile = bossdata.plate.PlateFile(mirror.get(spplate_filename))
            fibers = np.array([fiber], dtype=int)
            data = platefile.get_valid_data(fibers, fiducial_grid=True, use_ivar=True)[0]
        else:
            sdss_plate, sdss_mjd, sdss_fiberid = target['PLATE_DR7'],target['MJD_DR7'],target['FIBERID_DR7']
            sdss_spec = get_sdss_spec(sdss_plate, sdss_mjd, sdss_fiberid)

            if sdss_spec is None:
                continue
            data = sdss_spec.get_valid_data(fiducial_grid=True, use_ivar=True)

        # All checks passed
        num_good_spectra += 1

        wlen,flux,ivar = data['wavelength'][:],data['flux'][:],data['ivar'][:]
        ref_composite_flux[i] = flux
        ref_composite_ivar[i] = ivar

        # Save flux and ivar
        data = dr12_spec.get_valid_data(fiducial_grid=True, use_ivar=True)
        wlen,flux,ivar = data['wavelength'][:],data['flux'][:],data['ivar'][:]
        dr12_composite_flux[i] = flux
        dr12_composite_ivar[i] = ivar

        # Read the target's throughput correction vector
        correction = tpcorr[tpcorr_key].value
        # Create an interpolated correction function
        correction_interp = scipy.interpolate.interp1d(tpcorr_wave, correction, kind='linear',
            bounds_error=False, fill_value=np.ma.masked)
        # Sample the interpolated correction using the observation's wavelength grid
        resampled_correction = correction_interp(wlen)
        # Apply the correction to the observed flux and ivar
        tpcorr_composite_flux[i] = flux * resampled_correction
        tpcorr_composite_ivar[i] = ivar / (resampled_correction**2)

    print num_targets, num_good_spectra

    fig = plt.figure(figsize=(16,4))
    dr12_ratio = dr12_composite_flux/ref_composite_flux
    tpcorr_ratio = tpcorr_composite_flux/ref_composite_flux
    plot_median_flux_ratio(fiducial_wavelength, dr12_ratio, tpcorr_ratio, show_quantiles=True)

    if args.validation:
        plt.ylim(0.7, 1.3)
        plt.savefig(args.output)
    else:
        plt.ylim(0, 2)
        plt.savefig(args.output)

    # if args.output:
    #     # save target list with sn column
    #     outfile = h5py.File(args.output, 'w')

    #     outfile.create_dataset('sdss_flux', data=ref_composite_flux)
    #     outfile.create_dataset('sdss_ivar', data=ref_composite_ivar)
    #     outfile.create_dataset('sdss_mask', data=ref_composite_flux.mask)
    #     outfile.create_dataset('dr12_flux', data=dr12_composite_flux)
    #     outfile.create_dataset('dr12_ivar', data=dr12_composite_ivar)
    #     outfile.create_dataset('dr12_mask', data=dr12_composite_flux.mask)
    #     outfile.create_dataset('tpcorr_flux', data=tpcorr_composite_flux)
    #     outfile.create_dataset('tpcorr_ivar', data=tpcorr_composite_ivar)
    #     outfile.create_dataset('tpcorr_mask', data=tpcorr_composite_flux.mask)
    #     outfile.create_dataset('wavelength', data=fiducial_wavelength)
    #     outfile.attrs['ntargets'] = num_targets

    #     outfile.close()

if __name__ == '__main__':
    main()

redpajama_set_name: RedPajamaGithub


text:
namespace Machete.Layouts.Parsers
{
    using System.Collections.Generic;
    using System.Linq;

    public class LayoutParser<TLayout, TSchema> :
        IParser<TSchema, TLayout>
        where TSchema : Entity
        where TLayout : Layout
    {
        readonly ILayoutFactory<TLayout> _factory;
        readonly IParser<TSchema, LayoutMatch<TLayout>>[] _parsers;

        public LayoutParser(ILayoutFactory<TLayout> factory, IEnumerable<IParser<TSchema, LayoutMatch<TLayout>>> parsers)
        {
            _factory = factory;
            _parsers = parsers.ToArray();
        }

        public Result<Cursor<TSchema>, TLayout> Parse(Cursor<TSchema> input)
        {
            var matches = new List<LayoutMatch<TLayout>>(_parsers.Length);

            var next = input;
            for (var i = 0; i < _parsers.Length; i++)
            {
                var result = _parsers[i].Parse(next);

                if (result.HasResult == false)
                    return new Unmatched<Cursor<TSchema>, TLayout>(next);

                matches.Add(result.Result);

                next = result.Next;
            }

            var layout = _factory.Create();
            for (var i = 0; i < matches.Count; i++)
                matches[i].Apply(layout);

            return new Success<Cursor<TSchema>, TLayout>(layout, next);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/ptarmigan.iml" filepath="$PROJECT_DIR$/.idea/ptarmigan.iml" />
    </modules>
  </component>
</project>


text:
<!DOCTYPE html>

  <title>ROO Example</title>
  <meta charset="UTF-8">

  <link rel="stylesheet" type="text/css" href="http://blog.dfilimonov.com/github-ribbons-css/ribbons.css">
  <link rel="stylesheet" type="text/css" href="//ausftas.github.io/example-api-common/style.css">

API Rules Of Origin Example

      Please wait while it loads.


text:
void INI_Rename_Generic1();
void Rename_Generic1_op();


text:
[![Join the chat at https://gitter.im/manyminds/api2go-adapter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/manyminds/api2go-adapter?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[![Build Status](https://travis-ci.org/manyminds/api2go-adapter.svg?branch=master)](https://travis-ci.org/manyminds/api2go-adapter)
[![Coverage Status](https://coveralls.io/repos/manyminds/api2go-adapter/badge.svg?branch=master&service=github)](https://coveralls.io/github/manyminds/api2go-adapter?branch=master)
[![Go Report Card](http://goreportcard.com/badge/manyminds/api2go-adapter)](http://goreportcard.com/report/manyminds/api2go-adapter)

### Deprecated

All adapters got moved into the main repository and will only be updated there.

#### Upgrade
To Upgrade the gin-adapter from api2go-adapter simply install api2go with the build tag:

`go get -tags=gingonic github.com/manyminds/api2go` and replace `gingonic.New(r)` with `routing.Gin(r)`


text:
#ifndef WebKit_h
#define WebKit_h

#include "platform/WebCommon.h"

#define HAVE_WEBCOMPOSITOR

namespace WebKit {

class WebKitPlatformSupport;

// Must be called on the thread that will be the main WebKit thread before
// using any other WebKit APIs. The provided WebKitPlatformSupport; must be
// non-null and must remain valid until the current thread calls shutdown.
WEBKIT_EXPORT void initialize(WebKitPlatformSupport*);

// Must be called on the thread that will be the main WebKit thread before
// using any other WebKit APIs. The provided WebKitPlatformSupport; must be
// non-null and must remain valid until the current thread calls shutdown.
//
// This is a special variant of initialize that does not intitialize V8.
WEBKIT_EXPORT void initializeWithoutV8(WebKitPlatformSupport*);

// Once shutdown, the WebKitPlatformSupport passed to initialize will no longer
// be accessed. No other WebKit objects should be in use when this function is
// called. Any background threads created by WebKit are promised to be
// terminated by the time this function returns.
WEBKIT_EXPORT void shutdown();

// Returns the WebKitPlatformSupport instance passed to initialize.
WEBKIT_EXPORT WebKitPlatformSupport* webKitPlatformSupport();

// Alters the rendering of content to conform to a fixed set of rules.
WEBKIT_EXPORT void setLayoutTestMode(bool);
WEBKIT_EXPORT bool layoutTestMode();

// Enables the named log channel. See WebCore/platform/Logging.h for details.
WEBKIT_EXPORT void enableLogChannel(const char*);

// Purge the plugin list cache. If |reloadPages| is true, any pages
// containing plugins will be reloaded after refreshing the plugin list.
WEBKIT_EXPORT void resetPluginCache(bool reloadPages);

} // namespace WebKit

#endif


text:
namespace nu {

void breakDebugger();

}  // namespace nu


text:
package de.symeda.demo.java8.misc;

import org.junit.Test;

public class ArraySorterTest {

	@Test
	public void test() {

		new ArraySorter().initAndSort();

	}

}


text:
package epam.bdcc_app.util

import com.epam.common.TimeUtils

object ProfilingUtil {
    def profileTime[R](blockName: String)(block: => R): R = {
        val start = System.nanoTime()
        val result = block
        println(s"PROFILING: '$blockName' last: ${TimeUtils.toString((System.nanoTime() - start) / 1000000L)}")
        result
    }
}


text:
export default store => {
  store._IS_READY = false
  store.subscribe(mutation => {
    if (mutation.type === 'RESTORE_MUTATION') {
      store._vm.$root.$emit('vuex-persist:ready')
      store._IS_READY = true
    }
  })
}


text:
layout: page
title: Summit Edge Holdings Executive Retreat
date: 2016-05-24
author: Brandon Wolf
tags: weekly links, java
status: published
summary: Vivamus mollis nisi et nisi.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/05/2018
  endDate: 01/06/2018
  ctyhocn: QROSJHX
  groupCode: SEHER
published: true
---
Phasellus vel nulla ante. Cras iaculis, metus ac interdum hendrerit, massa purus vehicula dolor, eu aliquam orci tellus ut lacus. Duis eget faucibus est. Fusce consequat neque vitae arcu laoreet maximus. Quisque lobortis ac odio id iaculis. Curabitur dapibus, urna id fermentum dapibus, tortor leo consequat lectus, vel consequat ante enim sed turpis. Nulla finibus vulputate lorem, non cursus ipsum lacinia vel. Aenean consequat volutpat sapien suscipit gravida. Praesent sit amet rutrum purus. Curabitur mattis lectus vitae nisl vehicula, nec pellentesque purus faucibus. Maecenas pellentesque aliquam leo vel tincidunt.
Ut in accumsan nibh. Suspendisse tincidunt tristique porttitor. Nulla augue mi, dictum ut rutrum vitae, hendrerit vitae massa. Vivamus nec est nec dui lacinia tristique. Duis ultricies magna a dui semper ultrices. Aenean convallis, lacus et fringilla venenatis, ligula est dignissim justo, sed cursus dolor purus ac lorem. Morbi porta vulputate sem, sit amet tempus tellus facilisis et. Duis hendrerit dolor at vulputate facilisis.

* Ut tincidunt quam a lectus tincidunt, at convallis arcu pellentesque
* Maecenas laoreet dolor vel purus dictum, in pharetra urna malesuada
* Donec volutpat purus rhoncus ligula tristique molestie
* Aenean id nibh ac erat feugiat auctor
* Fusce blandit felis sed mollis condimentum
* Aenean a orci ultrices orci hendrerit blandit vel at est.

Aenean id mollis nunc. Quisque tristique dui a tempus sagittis. Praesent iaculis convallis nunc, at pharetra neque aliquet ac. Nunc sit amet justo condimentum diam mattis auctor. Maecenas vitae nisl eget diam varius placerat a in lacus. Nunc porttitor justo id dolor pharetra posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam varius felis eros, id scelerisque orci vulputate quis. Cras ullamcorper sapien a sapien porttitor laoreet. Duis eu eleifend orci.


text:
<?php

namespace Magento\Checkout\Controller\Cart;

class Delete extends \Magento\Checkout\Controller\Cart
{
    /**
     * Delete shopping cart item action
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        $id = (int)$this->getRequest()->getParam('id');
        if ($id) {
            try {
                $this->cart->removeItem($id)->save();
            } catch (\Exception $e) {
                $this->messageManager->addError(__('We can\'t remove the item.'));
                $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            }
        }
        $defaultUrl = $this->_objectManager->create('Magento\Framework\UrlInterface')->getUrl('*/*');
        return $this->resultRedirectFactory->create()->setUrl($this->_redirect->getRedirectUrl($defaultUrl));
    }
}


text:
iris.ui(function(self) {

	self.create = function() {
		self.tmpl(iris.path.ui.hangout.html);
	};

	self.render = function(contact) {
		var link = self.get('hangout');
		setUpHangout(link, contact);
	};

}, iris.path.ui.hangout.js);


text:
#include <string>
#include <utility>

#include "absl/memory/memory.h"
#include "tensorflow/compiler/xla/debug_options_flags.h"
#include "tensorflow/compiler/xla/service/call_inliner.h"
#include "tensorflow/compiler/xla/service/hlo_domain_isolator.h"
#include "tensorflow/compiler/xla/service/hlo_domain_metadata.h"
#include "tensorflow/compiler/xla/service/hlo_domain_remover.h"
#include "tensorflow/compiler/xla/service/hlo_parser.h"
#include "tensorflow/compiler/xla/service/hlo_sharding_metadata.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/hlo_test_base.h"
#include "tensorflow/core/lib/core/status_test_util.h"

namespace xla {
namespace {

class HloDomainTest : public HloTestBase {
 protected:
  bool FindUserViaDomainPath(HloInstruction* instruction,
                             HloInstruction* operand) const {
    for (HloInstruction* user : operand->users()) {
      if (user == instruction) {
        return true;
      }
      if (user->opcode() == HloOpcode::kDomain &&
          FindUserViaDomainPath(instruction, user)) {
        return true;
      }
    }
    return false;
  }

  // Checks whether there is a kDomain instruction in the edge between the
  // instruction and the operand.
  bool HasDomainEdge(HloModule* module, absl::string_view instruction_name,
                     absl::string_view operand_name) {
    HloInstruction* instruction = FindInstruction(module, instruction_name);
    HloInstruction* operand = FindInstruction(module, operand_name);
    CHECK_NE(instruction, nullptr);
    CHECK_NE(operand, nullptr);
    if (!instruction->IsUserOf(operand)) {
      // If instruction is not an immediate user, we must find a path from
      // operand to instruction anyway, otherwise there is a corruption.
      if (FindUserViaDomainPath(instruction, operand)) {
        return true;
      }
      LOG(FATAL) << "Bad HLO module generated across the '" << instruction_name
                 << "' and '" << operand_name << "' instructions:\n"
                 << module->ToString();
    }
    return false;
  }
};

// Dummy DomainMetadata implementation which create kDomain boundaries around
// HLO instructions with the same metadata().op_name() values.
class OpNameMetadata : public DomainMetadata {
 public:
  explicit OpNameMetadata(std::string opname) : opname_(std::move(opname)) {}

  std::unique_ptr<DomainMetadata> Clone() const override {
    return absl::make_unique<OpNameMetadata>(opname_);
  }

  absl::string_view Kind() const override { return KindName(); }

  bool Matches(const DomainMetadata& other) const override {
    const OpNameMetadata* other_ptr =
        dynamic_cast<const OpNameMetadata*>(&other);
    if (other_ptr == nullptr) {
      // If other is not a OpNameMetadata, then it is clearly a no match.
      return false;
    }
    return opname_ == other_ptr->opname_;
  }

  std::string ToString() const override { return opname_; }

  static absl::string_view KindName() { return "opname"; }

  size_t Hash() const override { return std::hash<std::string>()(opname_); }

 private:
  std::string opname_;
};

// Creator function for OpNameMetadata domains.
class OpNameDomainCreator {
 public:
  HloInstruction* operator()(HloInstruction* instruction, HloInstruction* root,
                             HloInstruction* operand) {
    if (instruction->metadata().op_name() == root->metadata().op_name()) {
      return nullptr;
    }
    std::unique_ptr<DomainMetadata> operand_side_metadata =
        absl::make_unique<OpNameMetadata>(root->metadata().op_name());
    std::unique_ptr<DomainMetadata> user_side_metadata =
        absl::make_unique<OpNameMetadata>(instruction->metadata().op_name());
    return operand->parent()->AddInstruction(HloInstruction::CreateDomain(
        operand->shape(), operand, std::move(operand_side_metadata),
        std::move(user_side_metadata)));
  }
};

Status OpNameDomainNormalizer(const DomainMetadata::Domain& domain,
                              const DomainMetadata* metadata) {
  // Nothing to do for the particular use this test make of the OpName domains.
  return Status::OK();
}

TEST_F(HloDomainTest, CheckDomainWithCallInlining) {
  const char* const hlo_string = R"(
HloModule Module

%add_block {
  l = f32[4] parameter(0)
  r = f32[4] parameter(1)
  ROOT m = f32[4] add(l, r), sharding={maximal device=1}
}

ENTRY entry {
  p0 = (f32[4], f32[4]) parameter(0)
  a = f32[4] get-tuple-element(p0), index=0
  b = f32[4] get-tuple-element(p0), index=1
  c = f32[4] call(f32[4] a, f32[4] b), to_apply=%add_block
  d = f32[4] subtract(a, b), sharding={maximal device=1}
  e = f32[4] multiply(c, d), sharding={maximal device=1}
  ROOT f = (f32[4], f32[4], f32[4]) tuple(c, d, e)
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_TRUE(isolator_changed);

  CallInliner call_inliner(/*single_call_site=*/false,
                           /*update_domain=*/true);
  TF_ASSERT_OK_AND_ASSIGN(bool inlined, call_inliner.Run(module.get()));
  EXPECT_TRUE(inlined);

  EXPECT_TRUE(HasDomainEdge(module.get(), "add", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "add", "b"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "d", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "d", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "add"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "d"));

  HloDomainRemover remover(ShardingMetadata::KindName(),
                           ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module.get()));
  EXPECT_TRUE(remover_changed);

  EXPECT_FALSE(HasDomainEdge(module.get(), "add", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "add", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "d", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "d", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "add"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "d"));
}

TEST_F(HloDomainTest, CheckDomainLinks) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  p0 = (f32[4], f32[4]) parameter(0)
  a = f32[4] get-tuple-element(p0), index=0
  b = f32[4] get-tuple-element(p0), index=1
  c = f32[4] add(f32[4] a, f32[4] b), sharding={maximal device=1}
  d = f32[4] subtract(a, b), sharding={maximal device=1}
  e = f32[4] multiply(c, d), sharding={maximal device=1}
  ROOT f = (f32[4], f32[4], f32[4]) tuple(c, d, e)
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_TRUE(isolator_changed);

  EXPECT_TRUE(HasDomainEdge(module.get(), "c", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "c", "b"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "d", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "d", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "c"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "d"));

  HloDomainRemover remover(ShardingMetadata::KindName(),
                           ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module.get()));
  EXPECT_TRUE(remover_changed);

  EXPECT_FALSE(HasDomainEdge(module.get(), "c", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "c", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "d", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "d", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "c"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "d"));
}

TEST_F(HloDomainTest, CheckNoDomainAddedIfNoSharding) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  p0 = (f32[4], f32[4]) parameter(0)
  a = f32[4] get-tuple-element(p0), index=0
  b = f32[4] get-tuple-element(p0), index=1
  c = f32[4] add(f32[4] a, f32[4] b)
  d = f32[4] subtract(a, b)
  e = f32[4] multiply(c, d)
  ROOT f = (f32[4], f32[4], f32[4]) tuple(c, d, e)
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_TRUE(!isolator_changed);
}

TEST_F(HloDomainTest, CheckDomainAroundIO) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  p0 = (f32[4]) parameter(0)
  a = f32[4] get-tuple-element(p0), index=0
  token0 = token[] after-all()
  b = (f32[4], u32[], token[]) send(a, token0), channel_id=1, sharding={maximal device=0}
  c = token[] send-done(b), channel_id=1, sharding={maximal device=0}
  d = (f32[4], u32[], token[]) recv(token0), channel_id=2, sharding={maximal device=0}
  e = (f32[4], token[]) recv-done(d), channel_id=2, sharding={maximal device=0}
  e_element = f32[4] get-tuple-element(e), index=0, sharding={maximal device=0}
  f = f32[4] add(a, e_element)
  g = f32[4] subtract(a, e_element)
  ROOT h = (f32[4], f32[4]) tuple(f, g)
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_TRUE(isolator_changed);

  EXPECT_TRUE(HasDomainEdge(module.get(), "b", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "f", "e_element"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "a", "p0"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "c", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "d"));

  HloDomainRemover remover(ShardingMetadata::KindName(),
                           ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module.get()));
  EXPECT_TRUE(remover_changed);

  EXPECT_FALSE(HasDomainEdge(module.get(), "b", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "f", "e_element"));
}

TEST_F(HloDomainTest, CheckNoDomainAddedOnPureIOComputation) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  token0 = token[] after-all(), sharding={maximal device=-1}
  a = (f32[4], u32[], token[]) recv(token0), channel_id=1, sharding={maximal device=-1}
  b = (f32[4], token[]) recv-done(a), channel_id=1, sharding={maximal device=-1}
  b_element = f32[4] get-tuple-element(b), index=0, sharding={maximal device=-1}
  c = f32[4] add(b_element, b_element), sharding={maximal device=-1}
  d = (f32[4], u32[], token[]) send(c, token0), channel_id=2, sharding={maximal device=-1}
  ROOT e = token[] send-done(d), channel_id=2, sharding={maximal device=-1}
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_FALSE(isolator_changed);
}

TEST_F(HloDomainTest, CheckNormalizationOnPureIOComputation) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  token0 = token[] after-all(), sharding={maximal device=0}
  a = (f32[4], u32[], token[]) recv(token0), channel_id=1, sharding={maximal device=0}
  b = (f32[4], token[]) recv-done(a), channel_id=1, sharding={maximal device=0}
  b_element = f32[4] get-tuple-element(b), index=0, sharding={maximal device=0}
  c = f32[4] add(b_element, b_element)
  d = (f32[4], u32[], token[]) send(c, token0), channel_id=2, sharding={maximal device=0}
  ROOT e = token[] send-done(d), channel_id=2, sharding={maximal device=0}
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainRemover remover(ShardingMetadata::KindName(),
                           ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module.get()));
  EXPECT_FALSE(remover_changed);

  HloInstruction* add = FindInstruction(module.get(), "c");
  ASSERT_NE(add, nullptr);
  auto device = add->sharding_unique_device();
  EXPECT_TRUE(device.has_value());
  EXPECT_EQ(*device, 0);
}

TEST_F(HloDomainTest, CheckMultiDomainLinks) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  p0 = (f32[4], f32[4]) parameter(0)
  a = f32[4] get-tuple-element(p0), index=0
  b = f32[4] get-tuple-element(p0), index=1
  c = f32[4] add(a, b), sharding={maximal device=1}
  d = f32[4] subtract(a, c), sharding={maximal device=1}, metadata={op_name="D"}
  e = f32[4] multiply(c, d), sharding={maximal device=1}, metadata={op_name="D"}
  f = f32[4] add(e, c), sharding={maximal device=1}
  ROOT g = (f32[4], f32[4], f32[4]) tuple(c, d, f)
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainIsolator sharding_isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool sharding_isolator_changed,
                          sharding_isolator.Run(module.get()));
  EXPECT_TRUE(sharding_isolator_changed);

  HloDomainIsolator opname_isolator([]() { return OpNameDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool opname_isolator_changed,
                          opname_isolator.Run(module.get()));
  EXPECT_TRUE(opname_isolator_changed);

  EXPECT_TRUE(HasDomainEdge(module.get(), "c", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "c", "b"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "d", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "d", "c"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "d"));

  HloDomainRemover sharding_remover(ShardingMetadata::KindName(),
                                    ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool sharding_remover_changed,
                          sharding_remover.Run(module.get()));
  EXPECT_TRUE(sharding_remover_changed);

  HloDomainRemover opname_remover(OpNameMetadata::KindName(),
                                  OpNameDomainNormalizer);
  TF_ASSERT_OK_AND_ASSIGN(bool opname_remover_changed,
                          opname_remover.Run(module.get()));
  EXPECT_TRUE(opname_remover_changed);

  EXPECT_FALSE(HasDomainEdge(module.get(), "c", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "c", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "d", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "d", "c"));
}

TEST_F(HloDomainTest, CheckNormalizationOnInfeedTuple) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  token0 = token[] after-all()
  infeed = ((f32[4], f32[4]), token[]) infeed(token0),
    sharding={{maximal device=1}, {maximal device=0}, {maximal device=0}}
  infeed.data = (f32[4], f32[4]) get-tuple-element(infeed), index=0,
    sharding={{maximal device=1}, {maximal device=0}}
  gte0 = f32[4] get-tuple-element(infeed.data), index=0
  gte1 = f32[4] get-tuple-element(infeed.data), index=1
  copy0 = f32[4] copy(gte0)
  copy1 = f32[4] copy(gte1)
  ROOT add = f32[4] add(copy0, copy1)
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_TRUE(isolator_changed);

  EXPECT_TRUE(HasDomainEdge(module.get(), "infeed.data", "infeed"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "copy0", "gte0"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "copy1", "gte1"));

  // Inject unassigned tuple/gte within the infeed domain, to simulate the
  // HLO passes adding unexpected instructions.
  //
  //            infeed
  //              |
  //          infeed.data (tuple element 0 of infeed)
  //           /      \
  //         GTE0    GTE1
  //         /          \
  //       COPY0       COPY1
  //          \         /
  //           \       /
  //             TUPLE
  //               |
  HloInstruction* infeed_data = FindInstruction(module.get(), "infeed.data");
  ASSERT_NE(infeed_data, nullptr);

  auto infeed_data_users = infeed_data->users();
  HloInstruction* new_gte0 = infeed_data->parent()->AddInstruction(
      HloInstruction::CreateGetTupleElement(
          ShapeUtil::GetTupleElementShape(infeed_data->shape(), 0), infeed_data,
          0));
  HloInstruction* new_copy0 =
      infeed_data->parent()->AddInstruction(HloInstruction::CreateUnary(
          new_gte0->shape(), HloOpcode::kCopy, new_gte0));
  HloInstruction* new_gte1 = infeed_data->parent()->AddInstruction(
      HloInstruction::CreateGetTupleElement(
          ShapeUtil::GetTupleElementShape(infeed_data->shape(), 1), infeed_data,
          1));
  HloInstruction* new_copy1 =
      infeed_data->parent()->AddInstruction(HloInstruction::CreateUnary(
          new_gte1->shape(), HloOpcode::kCopy, new_gte1));
  HloInstruction* new_tuple = infeed_data->parent()->AddInstruction(
      HloInstruction::CreateTuple({new_copy0, new_copy1}));
  for (HloInstruction* user : infeed_data_users) {
    TF_EXPECT_OK(infeed_data->ReplaceUseWith(user, new_tuple));
  }

  HloDomainRemover remover(ShardingMetadata::KindName(),
                           ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module.get()));
  EXPECT_TRUE(remover_changed);

  struct Assignment {
    HloInstruction* instruction;
    int64_t device;
  } assignments[] = {
      {new_gte0, 1},
      {new_copy0, 1},
      {new_gte1, 0},
      {new_copy1, 0},
  };
  for (auto& assignment : assignments) {
    auto device = assignment.instruction->sharding_unique_device();
    ASSERT_TRUE(device.has_value());
    EXPECT_EQ(*device, assignment.device);
  }
  EXPECT_TRUE(new_tuple->has_sharding());
  EXPECT_EQ(
      new_tuple->sharding(),
      HloSharding::Tuple(new_tuple->shape(), {HloSharding::AssignDevice(1),
                                              HloSharding::AssignDevice(0)}));
}

TEST_F(HloDomainTest, EmptyRootDomain) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  %param = f32[1] parameter(0), sharding={maximal device=0}
  %tuple = (f32[1]) tuple(%param),
    sharding={maximal device=1}
  ROOT %gte = f32[1] get-tuple-element(%tuple), index=0,
    sharding={maximal device=1}
})";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_TRUE(isolator_changed);

  EXPECT_TRUE(HasDomainEdge(module.get(), "tuple", "param"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "gte", "tuple"));

  // Remove %tuple and %gte (tuple simplification)
  HloInstruction* gte = FindInstruction(module.get(), "gte");
  HloInstruction* tuple = FindInstruction(module.get(), "tuple");
  module->entry_computation()->set_root_instruction(tuple->mutable_operand(0));
  TF_EXPECT_OK(module->entry_computation()->RemoveInstruction(gte));
  TF_EXPECT_OK(module->entry_computation()->RemoveInstruction(tuple));

  HloDomainRemover remover(ShardingMetadata::KindName(),
                           ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module.get()));
  EXPECT_TRUE(remover_changed);

  const HloInstruction* root = module->entry_computation()->root_instruction();
  EXPECT_TRUE(root->has_sharding());
  EXPECT_EQ(root->sharding(), HloSharding::AssignDevice(1));
}

// Tests that text dumps of domain instructions can be parsed back, in the
// specific case of null shardings.
TEST_F(HloDomainTest, DumpParseNullSharding) {
  auto builder = HloComputation::Builder(TestName());
  Shape shape = ShapeUtil::MakeShape(F32, {});
  auto sharding_md_0 = absl::make_unique<ShardingMetadata>(nullptr);
  auto sharding_md_1 = absl::make_unique<ShardingMetadata>(nullptr);
  HloInstruction* param =
      builder.AddInstruction(HloInstruction::CreateParameter(0, shape, "p"));
  HloInstruction* domain = builder.AddInstruction(HloInstruction::CreateDomain(
      shape, param, std::move(sharding_md_0), std::move(sharding_md_1)));
  builder.AddInstruction(
      HloInstruction::CreateBinary(shape, HloOpcode::kAdd, domain, domain));

  auto module = CreateNewVerifiedModule();
  module->AddEntryComputation(builder.Build());

  auto hlo_string = module->ToString();
  ASSERT_TRUE(ParseAndReturnVerifiedModule(hlo_string).status().ok());
}

// Tuple inputs are domain instructions.
TEST_F(HloDomainTest, DomainTuple) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  p0 = f32[4] parameter(0), sharding={maximal device=0}
  cst = u32[] constant(0), sharding={maximal device=1}
  tpl = (u32[], f32[4]) tuple(cst, p0),
    sharding={{maximal device=1}, {maximal device=0}}
  ROOT gte = f32[4] get-tuple-element(tpl), index=1, sharding={maximal device=0}
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_TRUE(isolator_changed);

  // Clear sharding of tpl instruction, in order to test domain sharding
  // application.
  auto tpl = FindInstruction(module.get(), "tpl");
  tpl->clear_sharding();

  HloDomainRemover remover(ShardingMetadata::KindName(),
                           ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module.get()));
  EXPECT_TRUE(remover_changed);

  EXPECT_EQ(HloSharding::Tuple(tpl->shape(), {HloSharding::AssignDevice(1),
                                              HloSharding::AssignDevice(0)}),
            tpl->sharding());
}

TEST_F(HloDomainTest, MultiDomainMultiUser) {
  const char* const hlo_string = R"(
  HloModule Module

ENTRY %entry (p0: (f32[4], f32[4])) -> (f32[4], f32[4], f32[4]) {
  %p0 = (f32[4], f32[4]) parameter(0)
  %a = f32[4]{0} get-tuple-element(%p0), index=0
  %domain = f32[4] domain(%a),
    domain={kind="sharding", entry={maximal device=1}, exit={maximal device=0}}
  %b = f32[4] get-tuple-element(%p0), index=1
  %domain.1 = f32[4] domain(%b),
    domain={kind="sharding", entry={maximal device=1}, exit={maximal device=0}}
  %c = f32[4] add(%domain, %domain.1), sharding={maximal device=1}
  %domain.2 = f32[4] domain(%c),
    domain={kind="sharding", entry={maximal device=0}, exit={maximal device=1}}
  %d = f32[4] subtract(%domain, %c),
    sharding={maximal device=1}, metadata={op_name="D"}
  %domain.3 = f32[4] domain(%d),
    domain={kind="sharding", entry={maximal device=0}, exit={maximal device=1}}
  %e = f32[4] multiply(%c, %d),
    sharding={maximal device=1}, metadata={op_name="D"}
  %f = f32[4] add(f32[4]{0} %e, f32[4]{0} %c), sharding={maximal device=1}
  %domain.4 = f32[4]{0} domain(%f),
    domain={kind="sharding", entry={maximal device=0}, exit={maximal device=1}}
  ROOT %g = (f32[4], f32[4], f32[4]) tuple(%domain.2, %domain.3, %domain.4)
})";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));
  LOG(INFO) << "Original module:\n" << module->ToString();

  HloDomainIsolator opname_isolator([]() { return OpNameDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool opname_isolator_changed,
                          opname_isolator.Run(module.get()));
  EXPECT_TRUE(opname_isolator_changed);

  EXPECT_TRUE(HasDomainEdge(module.get(), "c", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "c", "b"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "d", "a"));
  EXPECT_TRUE(HasDomainEdge(module.get(), "d", "c"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "e", "d"));

  HloDomainRemover sharding_remover(ShardingMetadata::KindName(),
                                    ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool sharding_remover_changed,
                          sharding_remover.Run(module.get()));
  EXPECT_TRUE(sharding_remover_changed);

  HloDomainRemover opname_remover(OpNameMetadata::KindName(),
                                  OpNameDomainNormalizer);
  TF_ASSERT_OK_AND_ASSIGN(bool opname_remover_changed,
                          opname_remover.Run(module.get()));
  EXPECT_TRUE(opname_remover_changed);

  EXPECT_FALSE(HasDomainEdge(module.get(), "c", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "c", "b"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "d", "a"));
  EXPECT_FALSE(HasDomainEdge(module.get(), "d", "c"));
}

// Emulate instructions inserted at top and bottom within nested tuple domain.
TEST_F(HloDomainTest, DomainTupleTopBottomInsert) {
  const char* const hlo_string = R"(
HloModule Module

ENTRY entry {
  p0 = f32[4] parameter(0), sharding={maximal device=1}
  p1 = (f32[5], f32[6]) parameter(1),
    sharding={{maximal device=1}, {maximal device=0}}
  tuple.0 = (f32[4], (f32[5], f32[6])) tuple(p0, p1),
    sharding={{maximal device=1}, {maximal device=1}, {maximal device=0}}
  ROOT res = (f32[5], f32[6]) get-tuple-element(tuple.0), index=1,
    sharding={{maximal device=1}, {maximal device=0}}
}
)";

  TF_ASSERT_OK_AND_ASSIGN(auto module,
                          ParseAndReturnVerifiedModule(hlo_string));

  HloDomainIsolator isolator([]() { return ShardingDomainCreator{}; });
  TF_ASSERT_OK_AND_ASSIGN(bool isolator_changed, isolator.Run(module.get()));
  EXPECT_TRUE(isolator_changed);

  // Clear sharding of tuple.0 instruction, in order to test domain sharding
  // application.
  auto tuple0 = FindInstruction(module.get(), "tuple.0");
  tuple0->clear_sharding();

  // Insert the following instructions above and below tuple.0, to emulate other
  // passes effects:
  //                 COPY.0
  //             \    /
  //            TUPLE.0
  //              /    \
  //           COPY.1   \
  //            /        \
  //         GTE.0      GTE.1
  //           |          |
  //           |        COPY.2
  //            \       /
  //             \     /
  //             TUPLE.1
  //                |
  auto tuple0_users = tuple0->users();
  auto computation = tuple0->parent();
  HloInstruction* copy0 = computation->AddInstruction(
      HloInstruction::CreateUnary(tuple0->operand(1)->shape(), HloOpcode::kCopy,
                                  tuple0->mutable_operand(1)));
  TF_EXPECT_OK(tuple0->ReplaceOperandWith(1, copy0));

  HloInstruction* copy1 = computation->AddInstruction(
      HloInstruction::CreateUnary(tuple0->shape(), HloOpcode::kCopy, tuple0));
  HloInstruction* gte0 =
      computation->AddInstruction(HloInstruction::CreateGetTupleElement(
          ShapeUtil::GetTupleElementShape(copy1->shape(), 0), copy1, 0));
  HloInstruction* gte1 =
      computation->AddInstruction(HloInstruction::CreateGetTupleElement(
          ShapeUtil::GetTupleElementShape(tuple0->shape(), 1), tuple0, 1));
  HloInstruction* copy2 = computation->AddInstruction(
      HloInstruction::CreateUnary(gte1->shape(), HloOpcode::kCopy, gte1));
  HloInstruction* tuple1 =
      computation->AddInstruction(HloInstruction::CreateTuple({gte0, copy2}));

  for (HloInstruction* user : tuple0_users) {
    TF_EXPECT_OK(tuple0->ReplaceUseWith(user, tuple1));
  }

  HloDomainRemover remover(ShardingMetadata::KindName(),
                           ShardingMetadata::NormalizeShardingDomain);
  TF_ASSERT_OK_AND_ASSIGN(bool remover_changed, remover.Run(module.get()));
  EXPECT_TRUE(remover_changed);

  EXPECT_TRUE(tuple0->has_sharding());
  EXPECT_EQ(HloSharding::Tuple(tuple0->shape(), {HloSharding::AssignDevice(1),
                                                 HloSharding::AssignDevice(1),
                                                 HloSharding::AssignDevice(0)}),
            tuple0->sharding());

  EXPECT_TRUE(copy0->has_sharding());
  EXPECT_EQ(HloSharding::Tuple(copy0->shape(), {HloSharding::AssignDevice(1),
                                                HloSharding::AssignDevice(0)}),
            copy0->sharding());

  // copy1 has partial information only from gte.0, so in the end it gets no
  // sharding at all. During propagation it does propagate the information from
  // gte.0 though, enabling Tuple.0 to be fully sharded.
  EXPECT_FALSE(copy1->has_sharding());

  EXPECT_TRUE(gte0->has_sharding());
  EXPECT_EQ(HloSharding::AssignDevice(1), gte0->sharding());

  EXPECT_TRUE(gte1->has_sharding());
  EXPECT_EQ(HloSharding::Tuple(gte1->shape(), {HloSharding::AssignDevice(1),
                                               HloSharding::AssignDevice(0)}),
            gte1->sharding());

  EXPECT_TRUE(copy2->has_sharding());
  EXPECT_EQ(HloSharding::Tuple(copy2->shape(), {HloSharding::AssignDevice(1),
                                                HloSharding::AssignDevice(0)}),
            copy2->sharding());

  EXPECT_TRUE(tuple1->has_sharding());
  EXPECT_EQ(tuple0->sharding(), tuple1->sharding());
}

}  // namespace
}  // namespace xla


text:
from .mapa_compras_necessidade_detalhe import *
from .mapa_compras_necessidades import *
from .mapa_compras_semana_ref import *
from .mapa_compras_semana import *
from .mapa_compras import *
from .mapa import *
from .ref import *
from .rolo import *
from .views import *


text:
#ifndef LEXER_H
#define LEXER_H

#include "depends.h"
#include "pp_parser.h"

//enumerate the possible token types.  Some tokens here, such as LBRACKET, are
//never used.
typedef enum MY_TOKEN_TYPE {
	TOKEN_IDENTIFIER, TOKEN_HEXCONSTANT, TOKEN_INTCONSTANT, TOKEN_FLOATCONSTANT,
	TOKEN_STRING_LITERAL, TOKEN_SIZEOF, TOKEN_PTR_OP, TOKEN_INC_OP,
	TOKEN_DEC_OP, TOKEN_LEFT_OP, TOKEN_RIGHT_OP, TOKEN_CONDITIONAL,
	TOKEN_LE_OP, TOKEN_GE_OP, TOKEN_EQ_OP, TOKEN_NE_OP, TOKEN_AND_OP,
	TOKEN_OR_OP, TOKEN_MUL_ASSIGN, TOKEN_DIV_ASSIGN, TOKEN_MOD_ASSIGN,
	TOKEN_ADD_ASSIGN, TOKEN_SUB_ASSIGN, TOKEN_LEFT_ASSIGN, TOKEN_RIGHT_ASSIGN,
	TOKEN_AND_ASSIGN, TOKEN_XOR_ASSIGN, TOKEN_OR_ASSIGN, TOKEN_TYPE_NAME,
	TOKEN_TYPEDEF, TOKEN_EXTERN, TOKEN_STATIC, TOKEN_AUTO, TOKEN_REGISTER,
	TOKEN_CHAR, TOKEN_SHORT, TOKEN_INT, TOKEN_LONG, TOKEN_SIGNED,
	TOKEN_UNSIGNED, TOKEN_FLOAT, TOKEN_DOUBLE, TOKEN_CONST, TOKEN_VOLATILE,
	TOKEN_VOID, TOKEN_STRUCT, TOKEN_UNION, TOKEN_ENUM, TOKEN_ELLIPSIS,
	TOKEN_CASE, TOKEN_DEFAULT, TOKEN_IF, TOKEN_ELSE, TOKEN_SWITCH,
	TOKEN_WHILE, TOKEN_DO, TOKEN_FOR, TOKEN_GOTO, TOKEN_CONTINUE,
	TOKEN_BREAK, TOKEN_RETURN, TOKEN_SEMICOLON, TOKEN_LCURLY, TOKEN_RCURLY,
	TOKEN_COMMA, TOKEN_COLON, TOKEN_ASSIGN, TOKEN_LPAREN, TOKEN_RPAREN,
	TOKEN_LBRACKET, TOKEN_RBRACKET, TOKEN_FIELD, TOKEN_BITWISE_AND,
	TOKEN_BOOLEAN_NOT, TOKEN_BITWISE_NOT, TOKEN_ADD, TOKEN_SUB, TOKEN_MUL,
	TOKEN_DIV, TOKEN_MOD, TOKEN_LT, TOKEN_GT, TOKEN_XOR, TOKEN_BITWISE_OR,
	TOKEN_ERROR, TOKEN_COMMENT, TOKEN_EOF, EPSILON, END_OF_TOKENS
} MY_TOKEN_TYPE;

/******************************************************************************
*  CToken -- This class encapsulates the tokens that CLexer creates.  It serves
*  to encapsulate the information for OOD purposes.
******************************************************************************/
typedef struct Token {
	MY_TOKEN_TYPE theType;
	CHAR theSource[MAX_TOKEN_LENGTH + 1];
	TEXTPOS theTextPosition;
	ULONG charOffset;
} Token;

/******************************************************************************
*  CLexer -- This class is created with a string of unicode characters and a
*  starting position, which it uses to create a series of CTokens based on the
*  script.  Its purpose is to break down the characters into "words" for the
*  parser.
******************************************************************************/
typedef struct Lexer {
	LPCSTR thePath;
	LPCSTR ptheSource;
	pp_parser preprocessor;
	CHAR *pcurChar;
	TEXTPOS theTokenPosition;
} Lexer;

//Constructor
void Token_Init(Token * ptoken, MY_TOKEN_TYPE theType, LPCSTR theSource, TEXTPOS theTextPosition, ULONG charOffset);
void Lexer_Init(Lexer * plexer, pp_context * pcontext, LPCSTR thePath, LPSTR theSource, TEXTPOS theStartingPosition);
void Lexer_Clear(Lexer * plexer);
HRESULT Lexer_GetNextToken(Lexer * plexer, Token * theNextToken);
HRESULT Lexer_GetTokenIdentifier(Lexer * plexer, Token * theNextToken);
HRESULT Lexer_GetTokenNumber(Lexer * plexer, Token * theNextToken);
HRESULT Lexer_GetTokenStringLiteral(Lexer * plexer, Token * theNextToken);
HRESULT Lexer_GetTokenSymbol(Lexer * plexer, Token * theNextToken);
HRESULT Lexer_SkipComment(Lexer * lexer, COMMENT_TYPE theType);

#endif


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="refresh" content="30">
    <link rel="stylesheet" href="credo_status.css">
    <title>CREDO status</title>

    CREDO status

Device health

        $devicehealth_tablecontents

X-ray source

            $xraysource_status

Detector

            $detector_status

Accounting

            $accounting_data

File sequence numbers

            $filesequence_data

Motor positions

            $motorpositions_tablecontents

Uptime: $uptime

     http://credo.ttk.mta.hu

$timestamp


text:
// Copyright (c) 2012 Ecma International.  All rights reserved.
// Ecma International makes this code available under the terms and conditions set
// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
// "Use Terms").   Any redistribution of this code must retain the above
// copyright and this notice and otherwise comply with the Use Terms.

/*---
es5id: 10.6-12-1
description: Accessing callee property of Arguments object is allowed
includes: [runTestCase.js]
---*/

function testcase() {
  try
  {
    arguments.callee;
    return true;
  }
  catch (e) {
  }
 }
runTestCase(testcase);


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Grittier Login</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
    <link href="/assets/login.css" rel="stylesheet">
    <link rel="apple-touch-icon" sizes="57x57" href="/assets/ico/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/assets/ico/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/assets/ico/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/assets/ico/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/assets/ico/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/assets/ico/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/assets/ico/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/assets/ico/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/assets/ico/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192"  href="/assets/ico/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/assets/ico/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="/assets/ico/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/assets/ico/favicon-16x16.png">
    <link rel="manifest" href="/assets/ico/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/assets/ico/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

                    Grittier

                    <form class="form-signin" action="/auth?client_name=FormClient" method="POST">

Please Log In

                            Username:

                                <input type="text" name="username" id="username" class="form-control" autofocus>

                            Password:

                                <input type="password" name="password" id="password" class="form-control">

                        <button class="btn btn btn-primary" type="submit">Log In</button>
                        Register
                    </form>


text:
<?php
class Controller_Admin_Images extends Controller_Admin{

	public function action_index()
	{
		$data['images'] = Model_Image::find('all');
		$this->template->title = "Images";
		$this->template->content = View::forge('admin\images/index', $data);

	}

	public function action_view($id = null)
	{
		$data['image'] = Model_Image::find($id);

		$this->template->title = "Image";
		$this->template->content = View::forge('admin\images/view', $data);

	}

	public function action_create()
	{
		$view = View::forge('admin\images/create');
		if (Input::method() == 'POST')
		{
			$val = Model_Image::validate('create');

			if ($val->run())
			{
				$image = Model_Image::forge(array(
					'plant_id' => Input::post('plant_id'),
					'url' => Input::post('url'),
				));

				$config = array(
				    'path' => DOCROOT.'herbals_photos/'. $image->plant_id,
				    'randomize' => false,
				    'ext_whitelist' => array('img', 'jpg', 'jpeg', 'gif', 'png')
				    // 'max_size'=> 1024 * 1024,
				);

				// while(Upload::get_files()){

				// process the uploaded files in $_FILES
				Upload::process($config);

				// if there are any valid files
					if (Upload::is_valid())
					{
					    // save them according to the config
					    Upload::save();
						$value = Upload::get_files();
						// Upload::save($config['path'], array_keys($value));

					    $upload_count = 0;//for upload content
					    $i = 0;//index for POST method index used for multiple file upload

					    foreach ($value as $files) {
					    	$image->url = $value[$upload_count]['saved_as'];//incremental upload using the POST method index
					    	$date = new DateTime();
					    	DB::Query("INSERT INTO `images`(`plant_id`,`url`,`created_at`, `updated_at`) VALUES ('".$image->plant_id."','".$value[$upload_count]['name']."', '".$date->getTimestamp()."', '".$date->getTimestamp()."')")->execute();
					    	// $image->save();

							$upload_count++;

			    			// Read the contents of a directory
			    			try
							{
							    $dir = File::create_dir(DOCROOT.'herbals_photos', $image->plant_id, 0755, null);
							}
							catch(\FileAccessException $e)
							{
							    // Operation failed
							}
							try
							{
							    $dir = File::create_dir(DOCROOT.'herbals_photos/'.$image->plant_id,'/thumbs', 0755, null);
							}
							catch(\FileAccessException $e)
							{
							    // Operation failed
							}

							Image::load('herbals_photos/'.$image->plant_id.'/'.$image->url)
								->crop_resize(128, 128)
							    ->save('herbals_photos/'.$image->plant_id.'/thumbs/'.$image->url);
						}

						if($image)
						{
							Session::set_flash('success', e('Added '.$upload_count.' image(s)'));

							Response::redirect('admin/images');
						}
						else
						{
							Session::set_flash('error', e('Opps!, Something went wrong!'));
						}

						/*if ($image and $image->save())
						{
							Session::set_flash('success', e('Added image #'.$image->id.'.'));

							Response::redirect('admin/images');
						}

						else
						{
							Session::set_flash('error', e('Could not save image.'));
						}*/

					}//end if (Upload::is_valid())

			  	// }//end while

			}//if ($val->run())

			else
			{
				Session::set_flash('error', $val->error());
			}
		}

		$view->set_global('plant', Arr::assoc_to_keyval(Model_Plant::find('all'), 'id', 'name'));

		$this->template->title = "Images";
		$this->template->content = $view;

	}

	public function action_edit($id = null)
	{
		$view = View::forge('admin\images/edit');
		$image = Model_Image::find($id);
		$val = Model_Image::validate('edit');

		if ($val->run())
		{
			$image->plant_id = Input::post('plant_id');
			$image->url = Input::post('url');

			if ($image->save())
			{
				Session::set_flash('success', e('Updated image #' . $id));

				Response::redirect('admin/images');
			}

			else
			{
				Session::set_flash('error', e('Could not update image #' . $id));
			}
		}

		else
		{
			if (Input::method() == 'POST')
			{
				$image->plant_id = $val->validated('plant_id');
				$image->url = $val->validated('url');

				Session::set_flash('error', $val->error());
			}

			$this->template->set_global('image', $image, false);
		}

		$view->set_global('plant', Arr::assoc_to_keyval(Model_Plant::find('all'), 'id', 'name'));
		$this->template->title = "Images";
		$this->template->content = $view;

	}

	public function action_delete($id = null)
	{
		if ($image = Model_Image::find($id))
		{
			$image->delete();

			$query = DB::query("SELECT `id` FROM `images` ORDER BY `id` DESC LIMIT 1")->execute()->as_array();
			$query2 = DB::query("ALTER TABLE `images` AUTO_INCREMENT = ".$query[0]["id"])->execute();

			Session::set_flash('success', e('Deleted image #'.$id));
		}

		else
		{
			Session::set_flash('error', e('Could not delete image #'.$id));
		}

		Response::redirect('admin/images');

	}

}


text:
struct Animation
{
    //! Les points de la trajectoire/courbe d'animation que va suivre la fusée
    Vec3f* P;
    //! Nombre de point
    int nbp;
};

//! renvoie le temps passé depuis le demarrage
float temps();

//! initialise la courbe d'animation avec une liste de points de C du fichier "nom_fichier"
void animInit(Animation& a, const char* nom_fichier);

//! dessine la coure d'animation
void animDraw(const Animation& a);

	// VOICI un exemple de comment animer un objet : ceci est à mettre dans la fonction sceneDraw(...)
	//
//    glPushMatrix();
//    Vec3f pos ;
//    float t = temps();
//    int temps_entier = int(t);
//    int temps_entier_ok = temps_entier % sc.anim.nbp ;
//    pos = sc.anim.P[temps_entier_ok] ;
//    glTranslatef( pos.x, pos.y, pos.z ) ;
//    draw_plane();
//    glPopMatrix();

#endif


text:
.class public final Lcom/google/android/gms/common/internal/BinderWrapper;
.super Ljava/lang/Object;

# interfaces
.implements Landroid/os/Parcelable;

# static fields
.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Lcom/google/android/gms/common/internal/BinderWrapper;",
            ">;"
        }
    .end annotation
.end field

# instance fields
.field private zzaeJ:Landroid/os/IBinder;

# direct methods
.method static constructor <clinit>()V
    .registers 1

    new-instance v0, Lcom/google/android/gms/common/internal/BinderWrapper$1;

    invoke-direct {v0}, Lcom/google/android/gms/common/internal/BinderWrapper$1;-><init>()V

    sput-object v0, Lcom/google/android/gms/common/internal/BinderWrapper;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method public constructor <init>()V
    .registers 2

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/google/android/gms/common/internal/BinderWrapper;->zzaeJ:Landroid/os/IBinder;

    return-void
.end method

.method public constructor <init>(Landroid/os/IBinder;)V
    .registers 3
    .param p1, "binder"    # Landroid/os/IBinder;

    .prologue
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/google/android/gms/common/internal/BinderWrapper;->zzaeJ:Landroid/os/IBinder;

    iput-object p1, p0, Lcom/google/android/gms/common/internal/BinderWrapper;->zzaeJ:Landroid/os/IBinder;

    return-void
.end method

.method private constructor <init>(Landroid/os/Parcel;)V
    .registers 3
    .param p1, "in"    # Landroid/os/Parcel;

    .prologue
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/google/android/gms/common/internal/BinderWrapper;->zzaeJ:Landroid/os/IBinder;

    invoke-virtual {p1}, Landroid/os/Parcel;->readStrongBinder()Landroid/os/IBinder;

    move-result-object v0

    iput-object v0, p0, Lcom/google/android/gms/common/internal/BinderWrapper;->zzaeJ:Landroid/os/IBinder;

    return-void
.end method

.method synthetic constructor <init>(Landroid/os/Parcel;Lcom/google/android/gms/common/internal/BinderWrapper$1;)V
    .registers 3
    .param p1, "x0"    # Landroid/os/Parcel;
    .param p2, "x1"    # Lcom/google/android/gms/common/internal/BinderWrapper$1;

    .prologue
    invoke-direct {p0, p1}, Lcom/google/android/gms/common/internal/BinderWrapper;-><init>(Landroid/os/Parcel;)V

    return-void
.end method

# virtual methods
.method public describeContents()I
    .registers 2

    const/4 v0, 0x0

    return v0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .registers 4
    .param p1, "dest"    # Landroid/os/Parcel;
    .param p2, "flags"    # I

    .prologue
    iget-object v0, p0, Lcom/google/android/gms/common/internal/BinderWrapper;->zzaeJ:Landroid/os/IBinder;

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    return-void
.end method


text:
module.exports = function (sequelize, DataTypes) {
  const Team = sequelize.define('Team',
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true
      },
      name: {
        type: DataTypes.TEXT,
        allowNull: false
      },
      area: {
        type: DataTypes.TEXT,
        allowNull: false
      },
      establishedAt: {
        type: DataTypes.INTEGER
      }
    }, {
      paranoid: true,
      timestamps: false,
      classMethods: {
        associate: function (models) {
          Team.hasMany(models.Player,
            {
              as: 'players',
              constraints: false,
              foreignKey: 'teamId',
              allowNull: false
            })
        }
      }
    })
  return Team
}


text:
package org.eclipse.equinox.internal.p2.engine;

import org.eclipse.equinox.internal.provisional.p2.core.eventbus.IProvisioningEventBus;
import org.eclipse.equinox.p2.core.IAgentLocation;
import org.eclipse.equinox.p2.core.IProvisioningAgent;
import org.eclipse.equinox.p2.core.spi.IAgentServiceFactory;
import org.eclipse.equinox.p2.engine.IProfileRegistry;

/**
 * Instantiates default instances of {@link IProfileRegistry}.
 */
public class ProfileRegistryComponent implements IAgentServiceFactory {

	public Object createService(IProvisioningAgent agent) {
		IAgentLocation location = (IAgentLocation) agent.getService(IAgentLocation.SERVICE_NAME);
		SimpleProfileRegistry registry = new SimpleProfileRegistry(agent, SimpleProfileRegistry.getDefaultRegistryDirectory(location));
		registry.setEventBus((IProvisioningEventBus) agent.getService(IProvisioningEventBus.SERVICE_NAME));
		return registry;
	}
}


text:
<!DOCTYPE html>
    <head>
        <meta charset="utf-8"/>
        <title>Freestyle</title>

        <script src="index.js"></script>
        <script>
            fly.loadTemplate(templates);
            app = $(document).flyficate('w-ajax')[0];
        </script>
    </head>
    <body class="w-ajax__body"></body>
</html>


text:
namespace JoinRpg.Dal.Impl.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class AccomodationSubscribe : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.UserSubscriptions", "AccommodationChange", c => c.Boolean(nullable: false, defaultValue: true));
        }

        public override void Down()
        {
            DropColumn("dbo.UserSubscriptions", "AccommodationChange");
        }
    }
}


text:
package com.jme3.terrain.heightmap;

import com.jme3.asset.AssetManager;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.asset.TextureKey;
import com.jme3.math.Vector3f;
import com.jme3.texture.Texture;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Loads Terrain grid tiles with image heightmaps.
 * By default it expects a 16-bit grayscale image as the heightmap, but
 * you can also call setImageType(BufferedImage.TYPE_) to set it to be a different
 * image type. If you do this, you must also set a custom ImageHeightmap that will
 * understand and be able to parse the image. By default if you pass in an image of type
 * BufferedImage.TYPE_3BYTE_BGR, it will use the ImageBasedHeightMap for you.
 *
 * @author Anthyon, Brent Owens
 */
@Deprecated
/**
 * @Deprecated in favor of ImageTileLoader
 */
public class ImageBasedHeightMapGrid implements HeightMapGrid {

    private static final Logger logger = Logger.getLogger(ImageBasedHeightMapGrid.class.getName());
    private final AssetManager assetManager;
    private final Namer namer;
    private int size;

    public ImageBasedHeightMapGrid(final String textureBase, final String textureExt, AssetManager assetManager) {
        this(assetManager, new Namer() {

            public String getName(int x, int y) {
                return textureBase + "_" + x + "_" + y + "." + textureExt;
            }
        });
    }

    public ImageBasedHeightMapGrid(AssetManager assetManager, Namer namer) {
        this.assetManager = assetManager;
        this.namer = namer;
    }

    public HeightMap getHeightMapAt(Vector3f location) {
        // HEIGHTMAP image (for the terrain heightmap)
        int x = (int) location.x;
        int z = (int) location.z;

        AbstractHeightMap heightmap = null;
        //BufferedImage im = null;

        try {
            String name = namer.getName(x, z);
            logger.log(Level.FINE, "Loading heightmap from file: {0}", name);
            final Texture texture = assetManager.loadTexture(new TextureKey(name));

            // CREATE HEIGHTMAP
            heightmap = new ImageBasedHeightMap(texture.getImage());

            heightmap.setHeightScale(1);
            heightmap.load();

        } catch (AssetNotFoundException e) {
            logger.log(Level.SEVERE, "Asset Not found! ", e);
        }
        return heightmap;
    }

    public void setSize(int size) {
        this.size = size - 1;
    }
}


text:
<?php

namespace Buzz\Test\History;

use Buzz\Listener\History\Entry;
use Buzz\Message;

class EntryTest extends \PHPUnit_Framework_TestCase
{
    public function testDuration()
    {
        $entry = new Entry(new Message\Request(), new Message\Response(), 123);
        $this->assertEquals(123, $entry->getDuration());
    }
}


text:
package tk.fusselrulezz.ets2editor.application;

import java.io.File;

import tk.fusselrulezz.ets2editor.application.lang.LocalizationManager;
import tk.fusselrulezz.ets2editor.application.plugins.PluginManager;
import tk.fusselrulezz.ets2editor.ingame.CountryManager;
import tk.fusselrulezz.ets2editor.profile.ProfileManager;
import tk.fusselrulezz.ets2editor.streams.StreamConfig;
import tk.fusselrulezz.ets2editor.util.FileUtils;
import tk.fusselrulezz.ets2editor.util.Logger;
import tk.fusselrulezz.ets2editor.util.Logger.Level;

public final class DataController {

	public static final File CONFIG_FILE = new File("config.cfg");

	private static File documents;

	private static ApplicationConfig config;

	private static GameConfig gameConfig;
	private static StreamConfig streamConfig;

	private static boolean initialized = false;

	private DataController() {}

	public static void initialize() {
		if(initialized) {
			Logger.printMessage(Level.WARNING, "DataController already initialized!");
			return;
		}

		documents = FileUtils.getDocumentDirectory("Euro Truck Simulator 2\\");

		config = new ApplicationConfig(CONFIG_FILE);

		gameConfig = new GameConfig(getDocuments("config.cfg"));
		streamConfig = new StreamConfig(getDocuments("live_streams.sii"));

		if(config.isPluginsEnabled()) {
			PluginManager.loadPlugins(ETSEditor.DIRECTORY_PLUGINS);
			PluginManager.enablePlugins();

			Logger.printMessage(Level.INFO, "Loaded and enabled " + PluginManager.getPlugins().size() + " plugins");
		}

		LocalizationManager.loadDefaultLocales();
		LocalizationManager.setCurrent(config.getLocale());

		initialized = true;
	}

	public static void load() {
		CountryManager.loadCountries();
		ProfileManager.loadProfiles(getDocuments("profiles\\"));
	}

	public static boolean isInitialized() {
		return initialized;
	}

	public static ApplicationConfig getConfig() {
		return config;
	}

	public static GameConfig getGameConfig() {
		return gameConfig;
	}

	public static StreamConfig getStreamConfig() {
		return streamConfig;
	}

	public static File getDocuments() {
		return documents;
	}

	public static File getDocuments(String file) {
		return new File(documents.getAbsolutePath() + "\\" + file);
	}

	public static boolean isFirstExecution() {
		return config.wasCreated();
	}
}


text:
package com.otb.firebasechat.constants;

/**
 * Created by Mohit Rajput on 5/7/17.
 * General constants used in app
 */

public interface AppConstants {
    String FILESTACK_API_KEY = "AqWmnwWXyTTSYJINHzGrPz";
    String EMPTY = "";
    String SPACE = " ";
    String COLON = ":";
    String AUTHORIZATION = "authorization";
    String BEARER = "Bearer ";
}


text:
<?php

/**
 * Admin pricealarm list manager.
 * Performs collection and managing (such as filtering or deleting) function.
 * Admin Menu: Customer News -> pricealarm.
 */
class PriceAlarm_List extends oxAdminList
{

    /**
     * Current class template name.
     *
     * @var string
     */
    protected $_sThisTemplate = 'pricealarm_list.tpl';

    /**
     * Name of chosen object class (default null).
     *
     * @var string
     */
    protected $_sListClass = 'oxpricealarm';

    /**
     * Default SQL sorting parameter (default null).
     *
     * @var string
     */
    protected $_sDefSortField = "oxuserid";

    /**
     * Modifying SQL query to load additional article and customer data
     *
     * @param object $oListObject list main object
     *
     * @return string
     */
    protected function _buildSelectString($oListObject = null)
    {
        $sViewName = getViewName("oxarticles", (int) $this->getConfig()->getConfigParam("sDefaultLang"));
        $sSql = "select oxpricealarm.*, {$sViewName}.oxtitle AS articletitle, ";
        $sSql .= "oxuser.oxlname as userlname, oxuser.oxfname as userfname ";
        $sSql .= "from oxpricealarm left join {$sViewName} on {$sViewName}.oxid = oxpricealarm.oxartid ";
        $sSql .= "left join oxuser on oxuser.oxid = oxpricealarm.oxuserid WHERE 1 ";

        return $sSql;
    }

    /**
     * Builds and returns array of SQL WHERE conditions
     *
     * @return array
     */
    public function buildWhere()
    {
        $this->_aWhere = parent::buildWhere();
        $sViewName = getViewName("oxpricealarm");
        $sArtViewName = getViewName("oxarticles");

        // updating price fields values for correct search in DB
        if (isset($this->_aWhere[$sViewName . '.oxprice'])) {
            $sPriceParam = (double) str_replace(array('%', ','), array('', '.'), $this->_aWhere[$sViewName . '.oxprice']);
            $this->_aWhere[$sViewName . '.oxprice'] = '%' . $sPriceParam . '%';
        }

        if (isset($this->_aWhere[$sArtViewName . '.oxprice'])) {
            $sPriceParam = (double) str_replace(array('%', ','), array('', '.'), $this->_aWhere[$sArtViewName . '.oxprice']);
            $this->_aWhere[$sArtViewName . '.oxprice'] = '%' . $sPriceParam . '%';
        }

        return $this->_aWhere;
    }
}


text:
import * as pg from 'pg';

// instantiate a new client
// the client will read connection information from
// the same environment varaibles used by postgres cli tools
const client = new pg.Client();

// connect to our database
client.connect(function (err) {
  if (err) {
    throw err;
  }

  // execute a query on our database
  client.query('SELECT $1::text as name', ['brianc'], function (queryErr, result) {
    if (err) {
      throw err;
    }

    // just print the result to the console
    console.log(result.rows[0]); // outputs: { name: 'brianc' }

    // disconnect the client
    client.end();
  });
});


text:
namespace llvm {

bool ConvertUTF8toWide(unsigned WideCharWidth, llvm::StringRef Source,
                       char *&ResultPtr, const UTF8 *&ErrorPtr) {
  assert(WideCharWidth == 1 || WideCharWidth == 2 || WideCharWidth == 4);
  ConversionResult result = conversionOK;
  // Copy the character span over.
  if (WideCharWidth == 1) {
    const UTF8 *Pos = reinterpret_cast<const UTF8*>(Source.begin());
    if (!isLegalUTF8String(&Pos, reinterpret_cast<const UTF8*>(Source.end()))) {
      result = sourceIllegal;
      ErrorPtr = Pos;
    } else {
      memcpy(ResultPtr, Source.data(), Source.size());
      ResultPtr += Source.size();
    }
  } else if (WideCharWidth == 2) {
    const UTF8 *sourceStart = (const UTF8*)Source.data();
    // FIXME: Make the type of the result buffer correct instead of
    // using reinterpret_cast.
    UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
    ConversionFlags flags = strictConversion;
    result = ConvertUTF8toUTF16(
        &sourceStart, sourceStart + Source.size(),
        &targetStart, targetStart + Source.size(), flags);
    if (result == conversionOK)
      ResultPtr = reinterpret_cast<char*>(targetStart);
    else
      ErrorPtr = sourceStart;
  } else if (WideCharWidth == 4) {
    const UTF8 *sourceStart = (const UTF8*)Source.data();
    // FIXME: Make the type of the result buffer correct instead of
    // using reinterpret_cast.
    UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
    ConversionFlags flags = strictConversion;
    result = ConvertUTF8toUTF32(
        &sourceStart, sourceStart + Source.size(),
        &targetStart, targetStart + Source.size(), flags);
    if (result == conversionOK)
      ResultPtr = reinterpret_cast<char*>(targetStart);
    else
      ErrorPtr = sourceStart;
  }
  assert((result != targetExhausted)
         && "ConvertUTF8toUTFXX exhausted target buffer");
  return result == conversionOK;
}

bool ConvertCodePointToUTF8(unsigned Source, char *&ResultPtr) {
  const UTF32 *SourceStart = &Source;
  const UTF32 *SourceEnd = SourceStart + 1;
  UTF8 *TargetStart = reinterpret_cast<UTF8 *>(ResultPtr);
  UTF8 *TargetEnd = TargetStart + 4;
  ConversionResult CR = ConvertUTF32toUTF8(&SourceStart, SourceEnd,
                                           &TargetStart, TargetEnd,
                                           strictConversion);
  if (CR != conversionOK)
    return false;

  ResultPtr = reinterpret_cast<char*>(TargetStart);
  return true;
}

bool hasUTF16ByteOrderMark(ArrayRef<char> S) {
  return (S.size() >= 2 &&
          ((S[0] == '\xff' && S[1] == '\xfe') ||
           (S[0] == '\xfe' && S[1] == '\xff')));
}

bool convertUTF16ToUTF8String(ArrayRef<char> SrcBytes, std::string &Out) {
  assert(Out.empty());

  // Error out on an uneven byte count.
  if (SrcBytes.size() % 2)
    return false;

  // Avoid OOB by returning early on empty input.
  if (SrcBytes.empty())
    return true;

  const UTF16 *Src = reinterpret_cast<const UTF16 *>(SrcBytes.begin());
  const UTF16 *SrcEnd = reinterpret_cast<const UTF16 *>(SrcBytes.end());

  // Byteswap if necessary.
  std::vector<UTF16> ByteSwapped;
  if (Src[0] == UNI_UTF16_BYTE_ORDER_MARK_SWAPPED) {
    ByteSwapped.insert(ByteSwapped.end(), Src, SrcEnd);
    for (unsigned I = 0, E = ByteSwapped.size(); I != E; ++I)
      ByteSwapped[I] = llvm::sys::SwapByteOrder_16(ByteSwapped[I]);
    Src = &ByteSwapped[0];
    SrcEnd = &ByteSwapped[ByteSwapped.size() - 1] + 1;
  }

  // Skip the BOM for conversion.
  if (Src[0] == UNI_UTF16_BYTE_ORDER_MARK_NATIVE)
    Src++;

  // Just allocate enough space up front.  We'll shrink it later.  Allocate
  // enough that we can fit a null terminator without reallocating.
  Out.resize(SrcBytes.size() * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1);
  UTF8 *Dst = reinterpret_cast<UTF8 *>(&Out[0]);
  UTF8 *DstEnd = Dst + Out.size();

  ConversionResult CR =
      ConvertUTF16toUTF8(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
  assert(CR != targetExhausted);

  if (CR != conversionOK) {
    Out.clear();
    return false;
  }

  Out.resize(reinterpret_cast<char *>(Dst) - &Out[0]);
  Out.push_back(0);
  Out.pop_back();
  return true;
}

bool convertUTF16ToUTF8String(ArrayRef<UTF16> Src, std::string &Out)
{
  return convertUTF16ToUTF8String(
      llvm::ArrayRef<char>(reinterpret_cast<const char *>(Src.data()),
      Src.size() * sizeof(UTF16)), Out);
}

bool convertUTF8ToUTF16String(StringRef SrcUTF8,
                              SmallVectorImpl<UTF16> &DstUTF16) {
  assert(DstUTF16.empty());

  // Avoid OOB by returning early on empty input.
  if (SrcUTF8.empty()) {
    DstUTF16.push_back(0);
    DstUTF16.pop_back();
    return true;
  }

  const UTF8 *Src = reinterpret_cast<const UTF8 *>(SrcUTF8.begin());
  const UTF8 *SrcEnd = reinterpret_cast<const UTF8 *>(SrcUTF8.end());

  // Allocate the same number of UTF-16 code units as UTF-8 code units. Encoding
  // as UTF-16 should always require the same amount or less code units than the
  // UTF-8 encoding.  Allocate one extra byte for the null terminator though,
  // so that someone calling DstUTF16.data() gets a null terminated string.
  // We resize down later so we don't have to worry that this over allocates.
  DstUTF16.resize(SrcUTF8.size()+1);
  UTF16 *Dst = &DstUTF16[0];
  UTF16 *DstEnd = Dst + DstUTF16.size();

  ConversionResult CR =
      ConvertUTF8toUTF16(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
  assert(CR != targetExhausted);

  if (CR != conversionOK) {
    DstUTF16.clear();
    return false;
  }

  DstUTF16.resize(Dst - &DstUTF16[0]);
  DstUTF16.push_back(0);
  DstUTF16.pop_back();
  return true;
}

static_assert(sizeof(wchar_t) == 1 || sizeof(wchar_t) == 2 ||
                  sizeof(wchar_t) == 4,
              "Expected wchar_t to be 1, 2, or 4 bytes");

template <typename TResult>
static inline bool ConvertUTF8toWideInternal(llvm::StringRef Source,
                                             TResult &Result) {
  // Even in the case of UTF-16, the number of bytes in a UTF-8 string is
  // at least as large as the number of elements in the resulting wide
  // string, because surrogate pairs take at least 4 bytes in UTF-8.
  Result.resize(Source.size() + 1);
  char *ResultPtr = reinterpret_cast<char *>(&Result[0]);
  const UTF8 *ErrorPtr;
  if (!ConvertUTF8toWide(sizeof(wchar_t), Source, ResultPtr, ErrorPtr)) {
    Result.clear();
    return false;
  }
  Result.resize(reinterpret_cast<wchar_t *>(ResultPtr) - &Result[0]);
  return true;
}

bool ConvertUTF8toWide(llvm::StringRef Source, std::wstring &Result) {
  return ConvertUTF8toWideInternal(Source, Result);
}

bool ConvertUTF8toWide(const char *Source, std::wstring &Result) {
  if (!Source) {
    Result.clear();
    return true;
  }
  return ConvertUTF8toWide(llvm::StringRef(Source), Result);
}

bool convertWideToUTF8(const std::wstring &Source, std::string &Result) {
  if (sizeof(wchar_t) == 1) {
    const UTF8 *Start = reinterpret_cast<const UTF8 *>(Source.data());
    const UTF8 *End =
        reinterpret_cast<const UTF8 *>(Source.data() + Source.size());
    if (!isLegalUTF8String(&Start, End))
      return false;
    Result.resize(Source.size());
    memcpy(&Result[0], Source.data(), Source.size());
    return true;
  } else if (sizeof(wchar_t) == 2) {
    return convertUTF16ToUTF8String(
        llvm::ArrayRef<UTF16>(reinterpret_cast<const UTF16 *>(Source.data()),
                              Source.size()),
        Result);
  } else if (sizeof(wchar_t) == 4) {
    const UTF32 *Start = reinterpret_cast<const UTF32 *>(Source.data());
    const UTF32 *End =
        reinterpret_cast<const UTF32 *>(Source.data() + Source.size());
    Result.resize(UNI_MAX_UTF8_BYTES_PER_CODE_POINT * Source.size());
    UTF8 *ResultPtr = reinterpret_cast<UTF8 *>(&Result[0]);
    UTF8 *ResultEnd = reinterpret_cast<UTF8 *>(&Result[0] + Result.size());
    if (ConvertUTF32toUTF8(&Start, End, &ResultPtr, ResultEnd,
                           strictConversion) == conversionOK) {
      Result.resize(reinterpret_cast<char *>(ResultPtr) - &Result[0]);
      return true;
    } else {
      Result.clear();
      return false;
    }
  } else {
    llvm_unreachable(
        "Control should never reach this point; see static_assert further up");
  }
}

} // end namespace llvm


text:
sails-redis

Lightweight Redis Adapter for Node.js / Sails Apps

A lightweight Sails/Waterline adapter for Redis. May be used in a [Sails](http://sailsjs.com) app, or any Node.js module using [Waterline](http://waterlinejs.org) as its ORM.

> #### Heads up
> **This adapter _does not support the Semantic or Queryable interfaces_.  Instead, it simply provides robust, managed access to the underlying Redis client.**  That means you can't use it to call methods like `.find()`.  Instead, use it as a simple way to easily configure, obtain a connection, and communicate with Redis (e.g. for caching) within the lifecycle of your Node.js / Sails application.
>
> **Looking for the old repo?**  See the [for-sails-0.12 branch](https://github.com/balderdashy/sails-redis/tree/for-sails-0.12) of this repo or [ryanc1256/sails-redis](https://github.com/ryanc1256/sails-redis) for examples of conventional adapters that let you use Redis to directly store and query records from your models.
>
> **This is an adapter for Sails versions 1.0 and up.**  If you are using an earlier version of Sails (or Waterline <v0.13), check out the [for-sails-0.12 branch](https://github.com/balderdashy/sails-redis/tree/for-sails-0.12).  Since this new release of sails-redis is more lightweight, and does not support the same semantic interface as its predecessor, be aware that there are breaking changes in your app when you upgrade.  But I think you'll find that this new release is a great way to easily communicate with Redis, with minimal interference and a stable API.
> _If you are interested in upgrading the new, Sails-v1-compatible release of this Redis adapter to support semantic usage (find, create, update, destroy), then please [contact Mike or another core maintainer](http://sailsjs.com/contact)._

## Usage

#### Install

Install is through NPM.

```bash
npm install sails-redis
```

#### Getting started

After installing and configuring this adapter (see below), you'll be able to use it to send commands to Redis from your Sails/Node.js app.

Here's an example demonstrating how to look up a cached value from Redis using async/await:

```javascript
var util = require('util');

// Made up a fake parameter:
var key = 'foo';

// Inspired by https://github.com/node-machine/driver-interface/blob/06776813ff3a29cfa80c0011f3affa07bbc28698/layers/cache/get-cached-value.js
// Redis client docs: https://github.com/NodeRedis/node_redis/tree/v.2.8.0#sending-commands
// See also https://github.com/sailshq/machinepack-redis/blob/f0892e581286eac24757532513387162396356f7/machines/get-cached-value.js#L79-L94
// > If Redis returns `null`, then the value at this key is expired or does
// > not exist.  If a value _was_ found, attempt to JSON.parse() it.
// > (See `set-cached` for more info on why we're deserializing JSON here.)
var value = await sails.getDatastore('cache').leaseConnection(async (db)=>{
  var found = await (util.promisify(db.get).bind(db))(key);
  if (found === null) {
    return undefined;
  } else {
    return JSON.parse(found);
  }
});//¬
```

And here's another async/await example, this time showing how to _set_ a value in Redis, along with a TTL (i.e. expiry):

```javascript
var util = require('util');

// Made up some fake parameters:
var key = 'foo';
var value = {
  coolPhrase: `hello world, it's ${new Date()}`,
  iCan: ['put','w/e','I','want',4,'here']
};
var expiresIn = 1000*60*60*24;

// Convert `expiresIn` (which is expressed in milliseconds) to seconds,
// because unlike JavaScript, Redis likes to work with whole entire seconds.
var ttlInSeconds = Math.ceil(expiresIn / 1000);

// Inspired by https://github.com/node-machine/driver-interface/blob/06776813ff3a29cfa80c0011f3affa07bbc28698/layers/cache/cache-value.js
// Redis client docs: https://github.com/NodeRedis/node_redis/tree/v.2.8.0#sending-commands
// See also https://github.com/sailshq/machinepack-redis/blob/f0892e581286eac24757532513387162396356f7/machines/cache-value.js#L86-L107
// > Note: Redis expects string values, so we serialize `value` to JSON…
// > even if it is already a string.  (This is important for seamless reversibility.)
// > Also note that TTL is seconds, not ms…  I know it's weird -- sorry!
await sails.getDatastore('cache').leaseConnection(async (db)=>{
  await (util.promisify(db.setex).bind(db))(key, ttlInSeconds, JSON.stringify(value));
});//¬
```

Note that the leased connection (`db`) is just a [Redis client instance](https://www.npmjs.com/package/redis).  No need to connect it/bind event listeners-- it's already hot and ready to go.  Any fatal, unexpected errors that would normally be emitted as the "error" event are handled by the underlying driver, and can be optionally handled with custom logic by providing a function for `onUnexpectedFailure`.

> Need to use a different Redis client, like ioredis?  Please have a look at the [underlying driver](https://www.npmjs.com/package/machinepack-redis) for the latest info/discussion.

#### Using the Redis client instance

The documentation for the version of `redis` used in this adapter can be found here:
https://github.com/NodeRedis/node_redis/tree/v.2.8.0#sending-commands

## Configuration

This adapter supports [standard datastore configuration](http://sailsjs.com/documentation/reference/configuration/sails-config-datastores), as well as some additional low-level options.

For example, in a Sails app, add the config below to your [`config/datastores.js`](http://sailsjs.com/anatomy/config/datastores-js) file:

```javascript
cache: {
  adapter: 'sails-redis',
  url: 'redis://localhost:6379',

  // Other available low-level options can also be configured here.
  // (see below for more information)
},
```

> Note that you probably shouldn't set Redis as the default datastore for your application (your models wouldn't work!)

#### Low-Level Configuration (for redis client)

Configuration for the underlying Redis client itself is located as an object under the `options`.  The following options are available:

* `parser`: which Redis protocol reply parser to use.  Defaults to `hiredis` if that module is installed.
This may also be set to `javascript`.
* `return_buffers`: defaults to `false`.  If set to `true`, then all replies will be sent to callbacks as node Buffer
objects instead of JavaScript Strings.
* `detect_buffers`: default to `false`. If set to `true`, then replies will be sent to callbacks as node Buffer objects
if any of the input arguments to the original command were Buffer objects.
This option lets you switch between Buffers and Strings on a per-command basis, whereas `return_buffers` applies to
every command on a client.
* `socket_nodelay`: defaults to `true`. Whether to call setNoDelay() on the TCP stream, which disables the
Nagle algorithm on the underlying socket.  Setting this option to `false` can result in additional throughput at the
cost of more latency.  Most applications will want this set to `true`.
* `no_ready_check`: defaults to `false`. When a connection is established to the Redis server, the server might still
be loading the database from disk.  While loading, the server not respond to any commands.  To work around this,
`node_redis` has a "ready check" which sends the `INFO` command to the server.  The response from the `INFO` command
indicates whether the server is ready for more commands.  When ready, `node_redis` emits a `ready` event.
Setting `no_ready_check` to `true` will inhibit this check.
* `enable_offline_queue`: defaults to `true`. By default, if there is no active
connection to the redis server, commands are added to a queue and are executed
once the connection has been established. Setting `enable_offline_queue` to
`false` will disable this feature and the callback will be execute immediately
with an error, or an error will be thrown if no callback is specified.
* `retry_max_delay`: defaults to `null`. By default every time the client tries to connect and fails time before
reconnection (delay) almost doubles. This delay normally grows infinitely, but setting `retry_max_delay` limits delay
to maximum value, provided in milliseconds.
* `connect_timeout` defaults to `false`. By default client will try reconnecting until connected. Setting `connect_timeout`
limits total time for client to reconnect. Value is provided in milliseconds and is counted once the disconnect occured.
* `max_attempts` defaults to `null`. By default client will try reconnecting until connected. Setting `max_attempts`
limits total amount of reconnects.
* `auth_pass` defaults to `null`. By default client will try connecting without auth. If set, client will run redis auth command on connect.

## Help

For more examples, or if you get stuck or have questions, click [here](http://sailsjs.com/support).

## Bugs   [![NPM version](https://badge.fury.io/js/sails-redis.svg)](http://npmjs.com/package/sails-redis)

To report a bug, [click here](http://sailsjs.com/bugs).

## Contributing   [![Build Status](https://travis-ci.org/balderdashy/sails-redis.svg?branch=master)](https://travis-ci.org/balderdashy/sails-redis)

Please observe the guidelines and conventions laid out in the [Sails project contribution guide](http://sailsjs.com/contribute) when opening issues or submitting pull requests.

[![NPM](https://nodei.co/npm/sails-redis.png?downloads=true)](http://npmjs.com/package/sails-redis)

## Acknowledgements

I owe a big thank you to [@ryanc1256](https://github.com/ryanc1256) for all of his work with the original version of this adapter.

## License

This adapter, like the [Sails framework](http://sailsjs.com), is free and open-source under the [MIT License](http://sailsjs.com/license).