text:
/*
 * HTML5 Boilerplate
 *
 * What follows is the result of much research on cross-browser styling.
 * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal,
 * Kroc Camen, and the H5BP dev community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

/*
 * Remove the gap between images and the bottom of their containers: h5bp.com/i/440
 */

img {
    vertical-align: middle;
}

/*
 * Remove default fieldset styles.
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas.
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */

body {
    /*height: 1500px;*/
}

#header {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:45px;
    line-height:45px;
    background-color:#000;
    padding:0;
    color:#eee;
    font-size:20px;
    text-align:center;
}

#header a {
    color:#f3f3f3;
    text-decoration:none;
    font-weight:bold;
    text-shadow:0 -1px 0 rgba(0,0,0,0.5);
}

#wrapper {
    position:absolute;
    z-index:1;
    top:45px;
    bottom:45px;
    left:0;
    width:100%;
    background:#aaa;
    overflow:auto;
}

#scroller {
    position:relative;
    -webkit-tap-highlight-color:rgba(0,0,0,0);
    width:100%;
    padding:0;
    bottom: 0;
}
#scroller ul {
    position:relative;
    list-style:none;
    padding:0;
    margin:0;
    width:100%;
    text-align:left;
}

#scroller li {
    padding:0 10px;
    height:40px;
    line-height:40px;
    border-bottom:1px solid #ccc;
    border-top:1px solid #fff;
    background-color:#fafafa;
    font-size:14px;
}

#scroller li > a {
    display:block;
}

/* Set the fixed height of the footer here */
#footer {
    /*position: fixed;
    height: 45px;
    z-index: 2;
    bottom: 0;
    width: 100%;
    background-color: #000;*/
    position:fixed;
    bottom:0; left:0;
    width:100%;
    height:48px;
    background-image:-webkit-gradient(linear, 0 0, 0 100%, color-stop(0, #999), color-stop(0.02, #666), color-stop(1, #222));
    background-image:-moz-linear-gradient(top, #999, #666 2%, #222);
    background-image:-o-linear-gradient(top, #999, #666 2%, #222);
    padding:0;
    border-top:1px solid #444;
    z-index: 2;
}

.btn-super-large {
    padding: 16px 18px;
    font-size: 26px;
}
.btn-black {
    background: #000;
}

/* ==========================================================================
   Helper classes
   ========================================================================== */

/* Prevent callout */

.nocallout {
    -webkit-touch-callout: none;
}

.pressed {
    background-color: rgba(0, 0, 0, 0.7);
}

/* A hack for HTML5 contenteditable attribute on mobile */

textarea[contenteditable] {
    -webkit-appearance: none;
}

/* A workaround for S60 3.x and 5.0 devices which do not animated gif images if
   they have been set as display: none */

.gifhidden {
    position: absolute;
    left: -100%;
}

/*
 * Image replacement
 */

.ir {
    background-color: transparent;
    background-repeat: no-repeat;
    border: 0;
    direction: ltr;
    display: block;
    overflow: hidden;
    text-align: left;
    text-indent: -999em;
}

.ir br {
    display: none;
}

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

/* ==========================================================================
   EXAMPLE Media Queries for Responsive Design.
   Theses examples override the primary ('mobile first') styles.
   Modify as content requires.
   ========================================================================== */

@media only screen and (min-width: 800px) {
    /* Style adjustments for viewports that meet the condition */
}

@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
       only screen and (min-resolution: 144dpi) {
    /* Style adjustments for viewports that meet the condition */
}


text:
package io.spacedog.client.elastic;

import java.io.IOException;

import io.spacedog.utils.Check;

public class ESMatchPhraseQueryBuilder extends ESQueryBuilder
		implements ESBoostableQueryBuilder<ESMatchPhraseQueryBuilder> {

	private String fieldName;
	private Object value;
	private String analyzer;
	private Float boost;
	private Integer slop;

	public ESMatchPhraseQueryBuilder(String fieldName, Object value) {
		Check.notNullOrEmpty(fieldName, "fieldName");
		Check.notNull(value, "value");
		this.fieldName = fieldName;
		this.value = value;
	}

	/**
	 * Set the boost to apply to the query.
	 */
	@Override
	public ESMatchPhraseQueryBuilder boost(float boost) {
		this.boost = boost;
		return this;
	}

	/** Sets a slop factor for phrase queries */
	public ESMatchPhraseQueryBuilder slop(int slop) {
		if (slop < 0)
			throw new IllegalArgumentException("No negative slop allowed.");

		this.slop = slop;
		return this;
	}

	@Override
	protected void doXContent(ESJsonContentBuilder builder) throws IOException {
		builder.startObject("match_phrase");
		builder.startObject(fieldName);

		builder.field("query", value);

		if (analyzer != null)
			builder.field("analyzer", analyzer);
		if (boost != null)
			builder.field("boost", boost);
		if (slop != null)
			builder.field("slop", slop);

		builder.endObject();
		builder.endObject();
	}

}

redpajama_set_name: RedPajamaGithub


text:
package io.cattle.platform.api.credential;

import io.cattle.platform.core.constants.CredentialConstants;
import io.cattle.platform.core.model.Credential;
import io.github.ibuildthecloud.gdapi.context.ApiContext;
import io.github.ibuildthecloud.gdapi.model.Resource;
import io.github.ibuildthecloud.gdapi.request.ApiRequest;
import io.github.ibuildthecloud.gdapi.response.ResourceOutputFilter;

public class ApiKeyOutputFilter implements ResourceOutputFilter {

    @Override
    public Resource filter(ApiRequest request, Object original, Resource converted) {
        if (original instanceof Credential) {
            Credential cred = (Credential)original;
            if (CredentialConstants.KIND_API_KEY.equals(cred.getKind()) ||
                    CredentialConstants.KIND_AGENT_API_KEY.equals(cred.getKind())) {
                converted.getLinks().put(CredentialConstants.LINK_CERTIFICATE,
                        ApiContext.getUrlBuilder().resourceLink(converted, CredentialConstants.LINK_CERTIFICATE));
            }
        }

        return converted;
    }

}


text:
Demo2
-----

This demo shows how to use basic libraries.


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (c) 2015 PocketHub
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<resources xmlns:android="http://schemas.android.com/apk/res/android">

    <style name="Theme.PocketHub" parent="@style/Theme.AppCompat.Light.NoActionBar">

        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>

        <item name="actionBarPopupTheme">@style/ThemeOverlay.AppCompat.Dark</item>

        <item name="actionBarStyle">@style/Widget.Styled.ActionBar</item>
        <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
        <item name="windowActionBar">false</item>

    </style>

    <style name="Theme.PocketHub.NavigationDrawer" parent="Theme.PocketHub" />

    <style name="Widget.Styled.ActionBar" parent="Widget.AppCompat.ActionBar.Solid">
        <item name="indeterminateProgressStyle">@style/IndeterminateProgress</item>
        <item name="android:indeterminateProgressStyle">@style/IndeterminateProgress</item>
    </style>

    <style name="IndeterminateProgress" parent="@android:style/Widget.ProgressBar">
        <item name="android:indeterminateDrawable">@drawable/actionbar_spinner</item>
        <item name="android:minWidth">16dp</item>
    </style>

    <style name="ToolbarTheme" parent="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="colorControlNormal">@android:color/white</item>
        <item name="colorControlHighlight">@color/ripple_material_dark</item>
        <item name="colorAccent">#FFFFFF</item>
    </style>

    <style name="Theme.GitHub.CheckBoxLight" parent="@style/Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
    </style>

</resources>


text:
package main

import (
	// Standard library packages
	"net/http"

	// Third party packages
	"github.com/julienschmidt/httprouter"
	"github.com/swhite24/go-rest-tutorial/controllers"
	"gopkg.in/mgo.v2"
)

func main() {
	// Instantiate a new router
	r := httprouter.New()

	// Get a UserController instance
	uc := controllers.NewUserController(getSession())

	// Get a user resource
	r.GET("/user/:id", uc.GetUser)

	// Create a new user
	r.POST("/user", uc.CreateUser)

	// Remove an existing user
	r.DELETE("/user/:id", uc.RemoveUser)

	// Fire up the server
	http.ListenAndServe("localhost:3000", r)
}

// getSession creates a new mongo session and panics if connection error occurs
func getSession() *mgo.Session {
	// Connect to our local mongo
	s, err := mgo.Dial("mongodb://localhost")

	// Check if connection error, is mongo running?
	if err != nil {
		panic(err)
	}

	// Deliver session
	return s
}


text:
import 'application.css.sass'

const FastClick = require('fastclick');

if ('addEventListener' in document) {
	document.addEventListener('DOMContentLoaded', function() {
		FastClick.attach(document.body);
	}, false);
}

// Scroller
window.addEventListener('scroll', (function(event) {
  var d, e, g, sessionLink, progressBar, targets, w, y;
  w = window;
  d = document;
  e = d.documentElement;
  g = d.getElementsByTagName('body')[0];
  y = w.innerHeight || e.clientHeight || g.clientHeight;
  targets = document.querySelectorAll('.js-scrollable-session');
  sessionLink = document.querySelectorAll('.js-session-link');
  targets.forEach(function(el, index) {
    var progress;
    progress = (el.getBoundingClientRect().top - y) / el.getBoundingClientRect().height;
    progress = progress * -1;
    progress = Math.max(0, progress);
    progressBar = sessionLink[index].querySelector('.nav__bar');
    if (progress > 0.5 && progress < 1.5) {
      sessionLink[index].classList.add('active');
      progressBar.style.width = progress * 1.5 + "em";
    } else {
      sessionLink[index].classList.remove('active');
      progressBar.style.width = "0em";
    }
  });
}), false);

var swiper = new Swiper('.js-main-swiper', {
  loop: true,
  slidesPerView: 1,
  parallax: true,
  longSwipesRatio: 0.05,
  speed: 500,
  nextButton: '.js-slider-next',
  prevButton: '.js-slider-prev',
  onSlideChangeStart: function() {
    if (!swiper) return;
    var sliderStatus = document.querySelector('.js-slider-status')
    sliderStatus.innerText = '0'+(swiper.realIndex+1)
  }
});

// .js-slider-status

var clients = new Swiper('.js-clients', {
  pagination: '.swiper-pagination',
  paginationClickable: true,
  loop: true,
  slidesPerView: 1,
  nextButton: '.js-cliente-next',
  prevButton: '.js-cliente-prev'
});


text:
template <typename T, ssize_t inline_elements = -1>
class FixedArray {
 public:
  // For playing nicely with stl:
  typedef T value_type;
  typedef T* iterator;
  typedef T const* const_iterator;
  typedef T& reference;
  typedef T const& const_reference;
  typedef T* pointer;
  typedef std::ptrdiff_t difference_type;
  typedef size_t size_type;

  // REQUIRES: n >= 0
  // Creates an array object that can store "n" elements.
  //
  // FixedArray<T> will not zero-initialiaze POD (simple) types like int,
  // double, bool, etc.
  // Non-POD types will be default-initialized just like regular vectors or
  // arrays.
  explicit FixedArray(size_type n);

  // Releases any resources.
  ~FixedArray();

  // Returns the length of the array.
  inline size_type size() const { return size_; }

  // Returns the memory size of the array in bytes.
  inline size_t memsize() const { return size_ * sizeof(T); }

  // Returns a pointer to the underlying element array.
  inline const T* get() const { return reinterpret_cast<T *>(array_); }
  inline T* get() { return reinterpret_cast<T *>(array_); }

  // REQUIRES: 0 <= i < size()
  // Returns a reference to the "i"th element.
  inline T& operator[](size_type i) {
    DCHECK_GE(i, 0);
    DCHECK_LT(i, size_);
    return array_[i].element;
  }

  // REQUIRES: 0 <= i < size()
  // Returns a reference to the "i"th element.
  inline const T& operator[](size_type i) const {
    DCHECK_GE(i, 0);
    DCHECK_LT(i, size_);
    return array_[i].element;
  }

  inline iterator begin() { return get(); }
  inline iterator end() { return get() + size_; }

  inline const_iterator begin() const { return get(); }
  inline const_iterator end() const { return get() + size_; }

 private:
  // Container to hold elements of type T.  This is necessary to handle
  // the case where T is a a (C-style) array.  The size of InnerContainer
  // and T must be the same, otherwise callers' assumptions about use
  // of this code will be broken.
  struct InnerContainer {
    T element;
  };
  COMPILE_ASSERT(sizeof(InnerContainer) == sizeof(T),
                 fixedarray_inner_container_size_mismatch);

  // How many elements should we store inline?
  //   a. If not specified, use a default of 256 bytes (256 bytes
  //      seems small enough to not cause stack overflow or unnecessary
  //      stack pollution, while still allowing stack allocation for
  //      reasonably long character arrays.
  //   b. Never use 0 length arrays (not ISO C++)
  static const size_type S1 = ((inline_elements < 0)
                               ? (256/sizeof(T)) : inline_elements);
  static const size_type S2 = (S1 <= 0) ? 1 : S1;
  static const size_type kInlineElements = S2;

  size_type const       size_;
  InnerContainer* const array_;

  // Allocate some space, not an array of elements of type T, so that we can
  // skip calling the T constructors and destructors for space we never use.
  base::ManualConstructor<InnerContainer>
      inline_space_[kInlineElements];

  DISALLOW_EVIL_CONSTRUCTORS(FixedArray);
};

// Implementation details follow

template <class T, ssize_t S>
inline FixedArray<T, S>::FixedArray(typename FixedArray<T, S>::size_type n)
    : size_(n),
      array_((n <= kInlineElements
              ? reinterpret_cast<InnerContainer*>(inline_space_)
              : new InnerContainer[n])) {
  DCHECK_GE(n, 0);

  // Construct only the elements actually used.
  if (array_ == reinterpret_cast<InnerContainer*>(inline_space_)) {
    for (int i = 0; i != size_; ++i) {
      inline_space_[i].Init();
    }
  }
}

template <class T, ssize_t S>
inline FixedArray<T, S>::~FixedArray() {
  if (array_ != reinterpret_cast<InnerContainer*>(inline_space_)) {
    delete[] array_;
  } else {
    for (int i = 0; i != size_; ++i) {
      inline_space_[i].Destroy();
    }
  }
}

#endif  // UTIL_GTL_FIXEDARRAY_H__


text:
<?php
/**
 * Abstract class for Update Element processors. To be extended for each derivative element type.
 *
 * @abstract
 * @package modx
 * @subpackage processors.element
 */
abstract class modElementUpdateProcessor extends modObjectUpdateProcessor {
    public $previousCategory;
    /** @var modElement $object */
    public $object;

    public function beforeSave() {
        $locked = $this->getProperty('locked');
        if (!is_null($locked)) {
            $this->object->set('locked',(boolean)$locked);
        }

        /* make sure a name was specified */
        $nameField = $this->classKey == 'modTemplate' ? 'templatename' : 'name';
        $name = $this->getProperty($nameField,'');
        if (empty($name)) {
            $this->addFieldError($nameField,$this->modx->lexicon($this->objectType.'_err_ns_name'));
        } else if ($this->alreadyExists($name)) {
            /* if changing name, but new one already exists */
            $this->modx->error->addField($nameField,$this->modx->lexicon($this->objectType.'_err_exists_name',array('name' => $name)));
        }

        /* if element is locked */
        if ($this->object->get('locked') && $this->modx->hasPermission('edit_locked') == false) {
            $this->addFieldError($nameField,$this->modx->lexicon($this->objectType.'_err_locked'));
        }

        /* category */
        $category = $this->object->get('category');
        $this->previousCategory = $category;
        if (!empty($category)) {
            $category = $this->modx->getObject('modCategory',array('id' => $category));
            if (empty($category)) {
                $this->addFieldError('category',$this->modx->lexicon('category_err_nf'));
            }
        }

        /* can't change content if static source is not writable */
        if ($this->object->staticContentChanged()) {
            if (!$this->object->isStaticSourceMutable()) {
                $this->addFieldError('static_file', $this->modx->lexicon('element_static_source_immutable'));
            } else if (!$this->object->isStaticSourceValidPath()) {
                $this->addFieldError('static_file',$this->modx->lexicon('element_static_source_protected_invalid'));
            }
        }

        return !$this->hasErrors();
    }

    public function alreadyExists($name) {
        $nameField = $this->classKey == 'modTemplate' ? 'templatename' : 'name';
        return $this->modx->getCount($this->classKey,array(
            'id:!=' => $this->object->get('id'),
            $nameField => $name,
        )) > 0;
    }

    public function afterSave() {
        if ($this->getProperty('clearCache',true)) {
            $this->modx->cacheManager->refresh();
        }
    }

    public function cleanup() {
        return $this->success('',array_merge($this->object->get(array('id', 'name', 'description', 'locked', 'category', 'content')), array('previous_category' => $this->previousCategory)));
    }
}


text:
title: "Refactoring Models and Controllers"
date: '2016-03-19'
categories: [Ruby on Rails]
tags: [Ruby, Rails, Refactoring]
---

Let's reactor the Rails Models and Controllers.

This is part two of how to start refactoring your Rails app. [The first post was about refactoring logic out of the view]({{ site:url }}/refactoring-rails-views), since it doesn't really belong there. The next logical place to look at refactoring is the controller and the model. I'm doing both because we can actually refactor the controller in such a way that our model remains largely untouched.

We all know that actions inside the controller can sometimes get bloated to 20 lines or more. You have tons of conditional logic as well as creating, updating,  and rendering. It can get overwhelming fairly quickly. So you treat the controller like the class it is and create other methods to deal with the logic. This is a good next step - you're whittling down the number of lines your action has and with good method names you can make it quite clear what each step is doing. But pretty soon, your controller is large, containing 10-15 different methods, none of them having to do with the actual actions of the controller.

So the next step developers take is refactoring to the models. After all, you seem to always hear 'Fat models, skinny controllers'. But should you be doing that? Should logic that really has nothing to do with the model really be in the model? Just because it's convenient, doesn't mean it should be done.

So if not the model and not the controller, where should the logic go? Enter action/service classes. Action classes are my favorite and are perfect for taking care of that pesky logic that doesn't have a home. Let's work through an example.

This is a basic, quick example which is not normally the case. If you need to resort to action classes you likely have a complex app. But for our purposes and the sake of time, we'll make it simple.

Suppose we have a list of companies and you as a user want to put the company in your profile. A basic model set up would be:

{% highlight ruby linenos%}
class Company
  has_many :portfolio
  has_many :users, through: :portfolios
end

class User
  has_many :portfolios
  has_many :companies, through: :portfolios
end

class Portfolio
  belongs_to :company
  belongs_to :user
end
{% endhighlight %}

In our database, we have a list of companies. So the controller for creating a portfolio would look like:

{% highlight ruby linenos%}
class PortfoliosController < ApplicationController
  def create
    Portfolio.create(user_id: current_user.id, company_id: params:company_id)
    flash[:notice] = "Portfolio saved"
    redirect_to portfolio_new_path
  end
end
{% endhighlight %}

This is very straightforward, and if this is all that is needed, then we're good. We don't render any errors here because we assume there will be a `company_id` (which we look at below). But what if we also want to allow the users to create a company if it doesn't exist in the database? Our controller would need to check if there is a company. If there is not, we need to create the company, then create the portfolio. We also need to do checks on the company to make sure it's valid. For instance, we can't create it if the user didn't provide a name. This becomes a little messier.

{% highlight ruby linenos%}
class PortfoliosController < ApplicationController
  def create
    company = Company.find_or_create_by(company_params)
    if company.valid?
      Portfolio.create(user_id: current_user.id, company_id: params:company_id)
      redirect_to portfolio_new_path
    else
      flash[:errors] = company.errors.full_messages
      render :new
    end
  end
end
{% endhighlight %}

As I said, this is a basic example and you'd probably be fine with this code in the controller. But often times, you need to introduce more logic if the requirements keep getting added. Like, what if a company shouldn't be saved if the portfolio is invalid? Well then you have to wrap the whole thing in a transaction and then have a rescue to show what the errors are. And what about the name? We need to have certain requirements for names, like they should be capitalized. And what if the user enters Amazon as the company but we already have Amazon.com, Inc? I don't believe `find_or_create_by` will be able to pick up that they are the same company. We would need a general search, like `Company.where("lower(name) LIKE ?", "%#{params[:name]}%")`.

One step we can take is refactoring this into it's own method.

{% highlight ruby linenos%}
company = create_company

def find_or_create_company
  company = Company.where("lower(name) LIKE ?", "%#{params[:name]}%")
  if company.nil?
    company_params[:name].capitalize!
    company = Company.new(company_params)
  end
  company
end
{% endhighlight %}

Then in our `create` action, we just need to set `company = find_or_create_company`

Again, this would probably be just fine. That extra method isn't taking up much space. Until we get more requirements. For brevity's sake however, I won't go over any other requirements or any other methods that could be created in the controller. Instead, I'll show you how to refactor this in such that any new requirements you get, will most likely be easily taken care of without adding more logic inside the controller.

Let's add an action class. You can do so in your project by creating an `actions` directory inside the `app` directory. Place your file here and name it the same name as the action class (like the models and controllers are named). Here's what the rest of the code could look like.

{% highlight ruby linenos%}
class CreateCompanyPortfolio
  attr_accessor :company_params, :portfolio_params, :current_user

  def initialize(company_params, portfolio_params, current_user)
    company_params[:name].capitalize!
    @company_params = company_params
    @portfolio_params = portfolio_params
    @current_user = current_user
  end

  def create_portfolio
      ActiveRecord::Base.transaction do
        company = find_or_create_company
        company.save!
        portfolio = Portfolio.create!(user_id: current_user.id, company_id: company.id
      end
    company
  end

  def find_or_create_company
    company = Company.where("lower(name) LIKE ?", "%#{company_params[:name}%")
    company = Company.new(company_params) if company.nil
  end
end
{% endhighlight %}

Then controller would simply be:

{% highlight ruby linenos%}
class PortfoliosController < ApplicationController
  def create
    company = CreateCompanyPortfolio(company_params, portfolio_params, current_user).create_portfolio
    if company.valid?
      redirect_to portfolio_new_path
    else
      flash[:errors] = company.errors.full_messages
      render :new
    end
  end
end
{% endhighlight %}

You may wonder, this cleaned up the controller a little, but it seemed to add a lot more code. True. As I said, this was a basic example. But imagine if you have further requirements that require other checks or inserting more data, like if we needed to create a notification of some kind. Now, instead of adding any more code to the controller, that code can be added to the action class. Build out that action class as you need and keep the controller *and* the model skinny. Responsibilities of classes remain singular and leave only logic that is supposed to exist in those controllers and models!


text:
================================================
Exercise 1.21 - entab, replaces spaces with tabs
================================================

Question
--------

Write a program entab that replaces strings of blanks by the minimum number of
tabs and blanks to achieve the same spacing. Use the same tab stops as for
detab. When either a tab or a single blank would suffice to reach a tab stop,
which should be given preference?

Solution
--------

.. literalinclude:: ../../languages/cprogs/Ex_1.21_entab.c
   :language: c
   :tab-width: 4

.. runcode:: ../../languages/cprogs/Ex_1.21_entab.c
   :language: c
   :codesite: ideone

:use-local-compiler:`gcc`

Explanation
===========

1. We declare TABINC as 8 in `#define TABINC 8` as the number of spaces which
make a TAB.

2. We declare two variables **nb** for number of spaces and **nt** for number of
tabs.

3. We get the current character by calling getchar() and storing it in variable
c and keep track of the position.

4. As soon as a space character is found, we increment the number of spaces or
number of tabs. We increment the spaces by pos, if the space is not divisible by
TABINC. If the space occurance is divisible by TABINC, we increment the number
of tabs. This step collects the minimum number of tabs and blanks.

5. In the else part, when non space is found, we first print the all remaining
tabs, then remaining spaces, then print the character. And We reset the position
accordingly. If it is a newline, we reset the pos, if it is a tab character, we
reset it to previous tab character - 1. This step replaces the spaces with
minimum tabs and spaces.

.. git_changelog::

.. seealso::

  * :c-suggest-improve:`Ex_1.21_entab.c`
  * :c-better-explain:`Ex_1.21_entab.rst`


text:
package com.dell.doradus.service.db.fs;

import java.io.File;

public class FsDataStore {
    private File m_dataDir;

    public FsDataStore(File storeDir) {
        m_dataDir = new File(storeDir, "data");
        if(!m_dataDir.exists()) m_dataDir.mkdir();
    }

    public void save(String row, String column, byte[] data) {
        File rowDir = new File(m_dataDir, FileUtils.encode(row));
        if(!rowDir.exists()) rowDir.mkdir();
        File file = new File(rowDir, FileUtils.encode(column));
        FileUtils.write(file, data);
    }

    public byte[] load(String row, String column) {
        File rowDir = new File(m_dataDir, FileUtils.encode(row));
        if(!rowDir.exists()) return null;
        File file = new File(rowDir, FileUtils.encode(column));
        if(!file.exists()) return null;
        return FileUtils.read(file);
    }

    public void delete(String  row, String column) {
        File rowDir = new File(m_dataDir, FileUtils.encode(row));
        if(!rowDir.exists()) return;
        File file = new File(rowDir, FileUtils.encode(column));
        if(file.exists()) file.delete();
    }

    public void deleteRow(String row) {
        File rowDir = new File(m_dataDir, FileUtils.encode(row));
        if(!rowDir.exists()) return;
        FileUtils.deleteDirectory(rowDir);
    }
}


text:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const path = require('path');
const fs = require('bluebird').promisifyAll(require('fs-extra'));
const _ = require('lodash');
const hbs = require('handlebars');
const chokidar = require('chokidar');
const glob = require('glob');

var articleTemplate = hbs.compile(fs.readFileSync(path.join(__dirname, '../templates', 'article-shell.html'), 'utf-8'));
const imageList = [];
const projectRoot = path.join(__dirname, '../');

// var watcher = chokidar.watch('blog_content/**/*.png', {
//   ignored: /(^|[\/\\])\../,
//   persistent: true
// });

// watcher.on('add', (path) => {

// });
// watcher.on('remove', (path) => {

// });

glob(path.join(__dirname, '../blog_content') + '/**/*{png,jpg,jpeg,gif}', {}, function (er, files) {
    files.forEach((f) => imageList.push({ title: path.basename(f), value: '/' + f.replace(projectRoot, '') }));
});

app.use(express.static(path.join(__dirname, '..')));
app.use(bodyParser.json());

app.post('/editor/createblog', function (req, res) {
    var data = req.body;
    var tmplLoc = path.join(__dirname, '..', 'blog_content');
    var blogDescription = fs.readJsonSync(path.join(__dirname, '../blog_content/blog_description.json'));

    const ret = _.find(blogDescription, function (blog) {
        return blog.url === data.url;
    });
    if (ret) {
        res.status(400).send({
            status: 'failure',
            message: " URL:" + data.url + " Already present"
        });
        return;
    }

    if (data.url == null || data.url.length == 0) {
        res.status(400).send({
            status: 'failure',
            message: " URL:" + data.url + " is Empty"
        });
        return;
    }

    //End of Guard checks

    if (data.url.split('.').pop() !== 'html') {
        data.url = data.url + '.html';
    }
    tmplLoc = path.join(tmplLoc, data.url);
    var projectRoot = path.join(__dirname, '..');
    data.htmlSrcUrl = tmplLoc.replace(projectRoot, '');

    blogDescription.posts.push(data);
    fs.ensureFileAsync(tmplLoc).then(function () {
        return fs.writeFileAsync(tmplLoc, articleTemplate(data));
    }).then(function () {
        return fs.writeJsonAsync(path.join(__dirname, '../blog_content/blog_description.json'), blogDescription);
    }).then(function () {
        res.send({ status: 'ok', htmlSrcUrl: data.htmlSrcUrl });
        return;
    }).catch(function (er) {
        console.log(er);
        res.status(500).send({ status: 'failure' });
        return;
    });

});

app.post('/editor/savetemplate', function (req, res) {
    var data = req.body;
    fs.writeFileAsync(path.join(projectRoot, data.htmlSrcUrl), data.html)
        .then(() => res.send({ status: 'ok' }))
        .catch((er) => { console.log(er); res.status(500).send({ status: 'failure' }); });

});

app.post('/editor/compile', function (req, res) {
    res.send({ status: 'ok' });
});

app.get('/editor/image-list', function (req, res) {
    res.send(imageList);
});

app.listen(3000, function () {
    console.log('App Ready on http://localhost:3000/editor/index.html');
});


text:
#include <memory>
#include <numeric>
#include <random>
#include <vector>

#include "tensorflow/compiler/xla/array2d.h"
#include "tensorflow/compiler/xla/array4d.h"
#include "tensorflow/compiler/xla/client/computation.h"
#include "tensorflow/compiler/xla/client/computation_builder.h"
#include "tensorflow/compiler/xla/client/global_data.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/layout_util.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/reference_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test.h"
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include "tensorflow/compiler/xla/tests/literal_test_util.h"
#include "tensorflow/compiler/xla/tests/test_macros.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/gtl/array_slice.h"
#include "tensorflow/core/platform/types.h"

namespace xla {
namespace {

class ReshapeTest : public ClientLibraryTestBase {
 public:
  ErrorSpec zero_error_spec_{0.0};
};

// Collapses 2-dimensional pseudo-scalar (single-element array) to 1 dimension.
XLA_TEST_F(ReshapeTest, CollapseTrivial1x1) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2<float>({{1.0}});
  builder.Collapse(/*operand=*/a, /*dimensions=*/{0, 1});

  ComputeAndCompareR1<float>(&builder, {1.0f}, {}, zero_error_spec_);
}

XLA_TEST_F(ReshapeTest, CollapseTrivialR1EmptyDims) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR1<float>({1.0});
  builder.Collapse(/*operand=*/a, /*dimensions=*/{});

  ComputeAndCompareR1<float>(&builder, {1.0f}, {}, zero_error_spec_);
}

XLA_TEST_F(ReshapeTest, CollapseTrivialR1OnlyDim) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR1<float>({1.0});
  builder.Collapse(/*operand=*/a, /*dimensions=*/{0});

  ComputeAndCompareR1<float>(&builder, {1.0f}, {}, zero_error_spec_);
}

// Collapses 2-dimensional pseudo-scalar (single-element array) to scalar.
XLA_TEST_F(ReshapeTest, SingleElementArrayToScalar) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2<float>({{1.0}});
  auto reshape =
      builder.Reshape(/*operand=*/a, /*dimensions=*/{0, 1}, /*new_sizes=*/{});
  auto new_shape = builder.GetShape(reshape).ConsumeValueOrDie();

  ComputeAndCompareR0<float>(&builder, 1.0f, {}, zero_error_spec_);
}

XLA_TEST_F(ReshapeTest, ScalarToSingleElementArray) {
  ComputationBuilder builder(client_, TestName());

  std::unique_ptr<Literal> param0_literal = Literal::CreateR0<float>(1.0f);
  std::unique_ptr<GlobalData> param0_data =
      client_->TransferToServer(*param0_literal).ConsumeValueOrDie();

  auto a = builder.Parameter(0, ShapeUtil::MakeShape(F32, {}), "param0");
  a = builder.Neg(a);
  auto reshape =
      builder.Reshape(/*operand=*/a, /*dimensions=*/{}, /*new_sizes=*/{1});

  ComputeAndCompareR1<float>(&builder, {-1.0f}, {param0_data.get()},
                             zero_error_spec_);
}

XLA_TEST_F(ReshapeTest, Trivial0x3) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2FromArray2D<float>(Array2D<float>(0, 3));
  auto result = builder.Collapse(/*operand=*/a, /*dimensions=*/{0, 1});

  ComputeAndCompareR1<float>(&builder, {}, {}, zero_error_spec_);
}

// TODO(b/29185393): Make this work with the GPU backend. The GPU backend
// does not handle zero-sized shapes correctly. Failed last on 2017-05-15
// with an incorrect result rank.
XLA_TEST_F(ReshapeTest, DISABLED_ON_GPU(Trivial0x3WithParameter)) {
  ComputationBuilder builder(client_, TestName());

  std::unique_ptr<Literal> param0_literal =
      Literal::CreateR2FromArray2D<float>(Array2D<float>(0, 3));
  std::unique_ptr<GlobalData> param0_data =
      client_->TransferToServer(*param0_literal).ConsumeValueOrDie();

  auto a = builder.Parameter(0, ShapeUtil::MakeShape(F32, {0, 3}), "param0");
  auto result = builder.Collapse(/*operand=*/a, /*dimensions=*/{0, 1});

  ComputeAndCompareR1<float>(&builder, {}, {param0_data.get()},
                             zero_error_spec_);
}

XLA_TEST_F(ReshapeTest, Trivial3x0) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2FromArray2D<float>(Array2D<float>(3, 0));
  auto result = builder.Collapse(/*operand=*/a, /*dimensions=*/{0, 1});

  ComputeAndCompareR1<float>(&builder, {}, {}, zero_error_spec_);
}

// Collapses a 2-dimensional row vector to 1 dimension.
XLA_TEST_F(ReshapeTest, Trivial1x3) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2<float>({{1.0f, 2.0f, 3.0f}});
  auto result = builder.Collapse(/*operand=*/a, /*dimensions=*/{0, 1});

  ComputeAndCompareR1<float>(&builder, {1.0f, 2.0f, 3.0f}, {},
                             zero_error_spec_);
}

// Collapses a 2-dimensional column vector to 1 dimension.
XLA_TEST_F(ReshapeTest, Trivial3x1) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2<float>({{1.0f}, {2.0f}, {3.0f}});
  auto result = builder.Collapse(/*operand=*/a, /*dimensions=*/{0, 1});

  ComputeAndCompareR1<float>(&builder, {1.0f, 2.0f, 3.0f}, {},
                             zero_error_spec_);
}

// Splits an empty vector into an empty matrix.
XLA_TEST_F(ReshapeTest, R1ToR2_0_To_2x0) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR1<float>({});
  auto result =
      builder.Reshape(/*operand=*/a, /*dimensions=*/{0}, /*new_sizes=*/{2, 0});
  ComputeAndCompareR2<float>(&builder, Array2D<float>(2, 0), {},
                             zero_error_spec_);
}

// Splits a vector into a matrix.
XLA_TEST_F(ReshapeTest, R1ToR2_6_To_2x3) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR1<float>({1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f});
  auto result =
      builder.Reshape(/*operand=*/a, /*dimensions=*/{0}, /*new_sizes=*/{2, 3});
  Array2D<float> expected_2x3({{1.0f, 2.0f, 3.0f}, {4.0f, 5.0f, 6.0f}});
  ComputeAndCompareR2<float>(&builder, expected_2x3, {}, zero_error_spec_);
}

// Transposes a 2x0 array to a 0x2 array.
XLA_TEST_F(ReshapeTest, Reshape0x2To2x0) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2FromArray2D<float>(Array2D<float>(0, 2));
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{0, 1},
                                /*new_sizes=*/{2, 0});

  ComputeAndCompareR2<float>(&builder, Array2D<float>(2, 0), {},
                             zero_error_spec_);
}

// Transposes a 2-dimensional row vector to a column vector.
XLA_TEST_F(ReshapeTest, ReshapeRowToCol) {
  ComputationBuilder builder(client_, TestName());
  auto simple = MakeLinspaceArray2D(1.0f, 3.0f, 1, 3);
  auto a = builder.ConstantR2FromArray2D<float>(*simple);
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{0, 1},
                                /*new_sizes=*/{3, 1});

  auto expected = ReferenceUtil::TransposeArray2D(*simple);
  ComputeAndCompareR2<float>(&builder, *expected, {}, zero_error_spec_);
}

// Transposes a 2-dimensional array.
XLA_TEST_F(ReshapeTest, TransposeAsReshape) {
  ComputationBuilder builder(client_, TestName());
  auto a4x3 = MakeLinspaceArray2D(1.0f, 12.0f, 4, 3);
  auto a = builder.ConstantR2FromArray2D<float>(*a4x3);
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{1, 0},
                                /*new_sizes=*/{3, 4});

  auto expected3x4 = ReferenceUtil::TransposeArray2D(*a4x3);
  ComputeAndCompareR2<float>(&builder, *expected3x4, {}, zero_error_spec_);
}

// Transposes a 0x4 array with ComputationBuilder::Trans.
XLA_TEST_F(ReshapeTest, Transpose0x4) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2FromArray2D<float>(Array2D<float>(0, 4));
  auto result = builder.Transpose(a, {1, 0});

  ComputeAndCompareR2<float>(&builder, Array2D<float>(4, 0), {},
                             zero_error_spec_);
}

// Transposes a 2-dimensional array with ComputationBuilder::Trans.
XLA_TEST_F(ReshapeTest, Transpose4x3) {
  ComputationBuilder builder(client_, TestName());
  auto a4x3 = MakeLinspaceArray2D(1.0f, 12.0f, 4, 3);
  auto a = builder.ConstantR2FromArray2D<float>(*a4x3);
  auto result = builder.Transpose(a, {1, 0});

  auto expected3x4 = ReferenceUtil::TransposeArray2D(*a4x3);
  ComputeAndCompareR2<float>(&builder, *expected3x4, {}, zero_error_spec_);
}

// Reshapes an empty 2-dimensional array with dimensions that are not just a
// rearrangement of the originals (split), but no reordering (no shuffle).
XLA_TEST_F(ReshapeTest, ReshapeSplitNoShuffleZeroElements) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2FromArray2D<float>(Array2D<float>(6, 0));
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{0, 1},
                                /*new_sizes=*/{2, 3, 0, 0});

  ComputeAndCompareR4<float>(&builder, Array4D<float>(2, 3, 0, 0), {},
                             zero_error_spec_);
}

XLA_TEST_F(ReshapeTest, ReshapeR4ToR2ZeroElements) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR4FromArray4D<float>(Array4D<float>(2, 3, 4, 0));
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{0, 1, 2, 3},
                                /*new_sizes=*/{24, 0});

  ComputeAndCompareR2<float>(&builder, Array2D<float>(24, 0), {},
                             zero_error_spec_);
}

// Reshapes a 2-dimensional array with dimensions that are not just a
// rearrangement of the originals (split), but no reordering (no shuffle).
XLA_TEST_F(ReshapeTest, ReshapeSplitNoShuffle) {
  ComputationBuilder builder(client_, TestName());
  auto a4x3 = MakeLinspaceArray2D(1.0f, 12.0f, 4, 3);
  auto a = builder.ConstantR2FromArray2D<float>(*a4x3);
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{0, 1},
                                /*new_sizes=*/{2, 6});

  auto expected2x6 = MakeLinspaceArray2D(1.0f, 12.0f, 2, 6);
  ComputeAndCompareR2<float>(&builder, *expected2x6, {}, zero_error_spec_);
}

// Reshapes a 2-dimensional array with dimensions that are not just a
// rearrangement of the originals (split), and reorder the input (shuffle).
XLA_TEST_F(ReshapeTest, ReshapeSplitAndShuffleZeroElements) {
  ComputationBuilder builder(client_, TestName());
  auto a = builder.ConstantR2FromArray2D<float>(Array2D<float>(0, 6));
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{1, 0},
                                /*new_sizes=*/{3, 0});

  ComputeAndCompareR2<float>(&builder, Array2D<float>(3, 0), {},
                             zero_error_spec_);
}

// Reshapes a 2-dimensional array with dimensions that are not just a
// rearrangement of the originals (split), and reorder the input (shuffle).
XLA_TEST_F(ReshapeTest, ReshapeSplitAndShuffle) {
  ComputationBuilder builder(client_, TestName());
  auto a4x3 = MakeLinspaceArray2D(1.0f, 12.0f, 4, 3);
  auto a = builder.ConstantR2FromArray2D<float>(*a4x3);
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{1, 0},
                                /*new_sizes=*/{2, 6});

  Array2D<float> expected2x6({{1.0f, 4.0f, 7.0f, 10.0f, 2.0f, 5.0f},
                              {8.0f, 11.0f, 3.0f, 6.0f, 9.0f, 12.0f}});
  ComputeAndCompareR2<float>(&builder, expected2x6, {}, zero_error_spec_);
}

// The following tests use the same input 3D array; they test the examples we
// show for the Reshape operation in the operation_semantics document.
// TODO(b/34503277): find a way to show this code in the documentation without
// duplication on the TF documentation server.
Array3D<int> v_array_for_doc_R3_tests({{{10, 11, 12}, {15, 16, 17}},
                                       {{20, 21, 22}, {25, 26, 27}},
                                       {{30, 31, 32}, {35, 36, 37}},
                                       {{40, 41, 42}, {45, 46, 47}}});

XLA_TEST_F(ReshapeTest, DocR3_R1_Collapse_012) {
  ComputationBuilder builder(client_, TestName());
  auto v = builder.ConstantR3FromArray3D<int>(v_array_for_doc_R3_tests);
  auto result = builder.Reshape(/*operand=*/v, /*dimensions=*/{0, 1, 2},
                                /*new_sizes=*/{24});
  ComputeAndCompareR1<int>(&builder,
                           {10, 11, 12, 15, 16, 17, 20, 21, 22, 25, 26, 27,
                            30, 31, 32, 35, 36, 37, 40, 41, 42, 45, 46, 47},
                           {});
}

XLA_TEST_F(ReshapeTest, DocR3_R2_Collapse_012_Refine_83) {
  ComputationBuilder builder(client_, TestName());
  auto v = builder.ConstantR3FromArray3D<int>(v_array_for_doc_R3_tests);
  auto result = builder.Reshape(/*operand=*/v, /*dimensions=*/{0, 1, 2},
                                /*new_sizes=*/{8, 3});
  Array2D<int> expected({{10, 11, 12},
                         {15, 16, 17},
                         {20, 21, 22},
                         {25, 26, 27},
                         {30, 31, 32},
                         {35, 36, 37},
                         {40, 41, 42},
                         {45, 46, 47}});
  ComputeAndCompareR2<int>(&builder, expected, {});
}

XLA_TEST_F(ReshapeTest, DocR3_R1_Collapse_120) {
  ComputationBuilder builder(client_, TestName());
  auto v = builder.ConstantR3FromArray3D<int>(v_array_for_doc_R3_tests);
  auto result = builder.Reshape(/*operand=*/v, /*dimensions=*/{1, 2, 0},
                                /*new_sizes=*/{24});
  ComputeAndCompareR1<int>(&builder,
                           {10, 20, 30, 40, 11, 21, 31, 41, 12, 22, 32, 42,
                            15, 25, 35, 45, 16, 26, 36, 46, 17, 27, 37, 47},
                           {});
}

XLA_TEST_F(ReshapeTest, DocR3_R2_Collapse_120_Refine_83) {
  ComputationBuilder builder(client_, TestName());
  auto v = builder.ConstantR3FromArray3D<int>(v_array_for_doc_R3_tests);
  auto result = builder.Reshape(/*operand=*/v, /*dimensions=*/{1, 2, 0},
                                /*new_sizes=*/{8, 3});
  Array2D<int> expected({{10, 20, 30},
                         {40, 11, 21},
                         {31, 41, 12},
                         {22, 32, 42},
                         {15, 25, 35},
                         {45, 16, 26},
                         {36, 46, 17},
                         {27, 37, 47}});
  ComputeAndCompareR2<int>(&builder, expected, {});
}

XLA_TEST_F(ReshapeTest, DocR3_R3_Collapse_120_Refine_262) {
  ComputationBuilder builder(client_, TestName());
  auto v = builder.ConstantR3FromArray3D<int>(v_array_for_doc_R3_tests);
  auto result = builder.Reshape(/*operand=*/v, /*dimensions=*/{1, 2, 0},
                                /*new_sizes=*/{2, 6, 2});
  Array3D<int> expected(
      {{{10, 20}, {30, 40}, {11, 21}, {31, 41}, {12, 22}, {32, 42}},
       {{15, 25}, {35, 45}, {16, 26}, {36, 46}, {17, 27}, {37, 47}}});
  ComputeAndCompareR3<int>(&builder, expected, {});
}

// Collapses the low dimensions of a 4D tensor to get a 2D matrix, without
// reordering dimensions (for NeuralNet::FullyConnected).
//
// First we create a tesseract raster-face like:
//
// 1 2 3
// 4 5 6
//
// First we collapse Y and X within the raster space yielding:
//
// 1 2 3 4 5 6
//
// Then we collapse Z be collapsed so we just end up with planes:
//
// 1 2 3 4 5 6 1 2 3 4 5 6
XLA_TEST_F(ReshapeTest, FullyConnectedCollapse) {
  ComputationBuilder builder(client_, TestName());
  Array4D<float> t2x2x2x3(2, 2, 2, 3);
  auto filler2x3 = MakeLinspaceArray2D(1.0f, 6.0f, 2, 3);
  t2x2x2x3.FillWithYX(*filler2x3);
  auto a = builder.ConstantR4FromArray4D<float>(t2x2x2x3);
  auto result = builder.Collapse(/*operand=*/a, /*dimensions=*/{1, 2, 3});

  Array2D<float> expected2x12(
      {{1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f},
       {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f,
        6.0f}});
  ComputeAndCompareR2<float>(&builder, expected2x12, {}, zero_error_spec_);
}

// As above, but uses reshape directly.
XLA_TEST_F(ReshapeTest, FullyConnectedCollapseDesugared) {
  ComputationBuilder builder(client_, TestName());
  Array4D<float> t(2, 1, 2, 2);
  t(0, 0, 0, 0) = 0;
  t(0, 0, 0, 1) = 1;
  t(0, 0, 1, 0) = 2;
  t(0, 0, 1, 1) = 3;
  t(1, 0, 0, 0) = 4;
  t(1, 0, 0, 1) = 5;
  t(1, 0, 1, 0) = 6;
  t(1, 0, 1, 1) = 7;
  auto a = builder.ConstantR4FromArray4D<float>(t);
  auto result = builder.Reshape(/*operand=*/a, /*dimensions=*/{0, 1, 2, 3},
                                /*new_sizes=*/{2, 4});

  Array2D<float> expected({{0, 1, 2, 3}, {4, 5, 6, 7}});
  ComputeAndCompareR2<float>(&builder, expected, {}, zero_error_spec_);
}

// Reshape various ranks to a scalar.
XLA_TEST_F(ReshapeTest, ToScalar) {
  for (int rank = 0; rank < 8; ++rank) {
    ComputationBuilder b(client_, TestName());
    auto input = Literal::CreateR1<float>({83.0f});
    std::vector<int64> ones(rank, 1);  // this is {1, ..., 1}.
    std::vector<int64> dimensions(rank);
    std::iota(dimensions.begin(), dimensions.end(), 0);
    *input->mutable_shape() = ShapeUtil::MakeShape(F32, ones);
    b.Reshape(b.ConstantLiteral(*input), dimensions, {});

    ComputeAndCompareR0<float>(&b, 83.0f, {}, zero_error_spec_);
  }
}

XLA_TEST_F(ReshapeTest, BadDimensions) {
  ComputationBuilder b(client_, TestName());
  b.Reshape(b.ConstantR1<int32>({1}), {}, {});
  EXPECT_THAT(ExecuteToString(&b, {}),
              ::testing::HasSubstr("dimensions not a permutation"));
}

XLA_TEST_F(ReshapeTest, BadNewSizes) {
  ComputationBuilder b(client_, TestName());
  b.Reshape(b.ConstantR1<int32>({1, 2}), {1}, {});
  EXPECT_THAT(ExecuteToString(&b, {}),
              ::testing::HasSubstr("mismatched element counts"));
}

XLA_TEST_F(ReshapeTest, R4Dim0MinorLayoutToR2Dim0MajorLayout) {
  const Shape parameter_shape = ShapeUtil::MakeShape(F32, {2, 2, 2, 2});
  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, parameter_shape, "a");
  builder.Reshape(a, /*dimensions=*/{0, 1, 2, 3}, /*new_sizes=*/{2, 8});

  // clang-format off
  auto literal = Literal::CreateR4FromArray4DWithLayout(Array4D<float>{
    {
      {
        {0, 1},
        {2, 3},
      },
      {
        {100, 101},
        {102, 103},
      },
    },
    {
      {
        {222, 333},
        {444, 555},
      },
      {
        {666, 777},
        {888, 999},
      },
    },
  },
       LayoutUtil::MakeLayout({0, 1, 2, 3}));
  // clang-format on
  std::unique_ptr<GlobalData> input =
      client_->TransferToServer(*literal).ConsumeValueOrDie();
  Array2D<float> expected_array({
      {0, 1, 2, 3, 100, 101, 102, 103},
      {222, 333, 444, 555, 666, 777, 888, 999},
  });

  Computation computation = builder.Build().ConsumeValueOrDie();
  ExecutionOptions execution_options = execution_options_;
  *execution_options.mutable_shape_with_output_layout() =
      ShapeUtil::MakeShapeWithLayout(F32, {2, 8}, {1, 0});
  std::unique_ptr<Literal> actual =
      client_
          ->ExecuteAndTransfer(computation, {input.get()}, &execution_options)
          .ConsumeValueOrDie();
  std::unique_ptr<Literal> expected =
      Literal::CreateR2FromArray2D<float>(expected_array);
  LiteralTestUtil::ExpectEqual(*expected, *actual);
}

XLA_TEST_F(ReshapeTest, R2ToR4_3x8_To_3x2x1x4) {
  std::unique_ptr<Literal> input = Literal::CreateR2<float>({
      {0, 1, 2, 3, 4, 5, 6, 7},
      {100, 101, 102, 103, 104, 105, 106, 107},
      {200, 201, 202, 203, 204, 205, 206, 207},
  });
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{0, 1}, /*new_sizes=*/{3, 2, 1, 4});

  // clang-format off
  Array4D<float> expected = {
    {{{0, 1, 2, 3}},
     {{4, 5, 6, 7}}},
    {{{100, 101, 102, 103}},
     {{104, 105, 106, 107}}},
    {{{200, 201, 202, 203}},
     {{204, 205, 206, 207}}}
  };
  // clang-format on
  ComputeAndCompareR4<float>(&builder, expected, {input_data.get()},
                             zero_error_spec_);
}

// Tests R2->R4 reshape with the reshape dimensions {1, 0}.
XLA_TEST_F(ReshapeTest, R2ToR4_3x8_To_3x2x1x4_Dimensions_10) {
  std::unique_ptr<Literal> input = Literal::CreateR2<float>({
      {0, 1, 2, 3, 4, 5, 6, 7},
      {100, 101, 102, 103, 104, 105, 106, 107},
      {200, 201, 202, 203, 204, 205, 206, 207},
  });
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{1, 0}, /*new_sizes=*/{3, 2, 1, 4});

  // clang-format off
  Array4D<float> expected = {
    {{{0, 100, 200, 1}},
     {{101, 201, 2, 102}}},
    {{{202, 3, 103, 203}},
     {{4, 104, 204, 5}}},
    {{{105, 205, 6, 106}},
     {{206, 7, 107, 207}}}
  };
  // clang-format on
  ComputeAndCompareR4<float>(&builder, expected, {input_data.get()},
                             zero_error_spec_);
}

XLA_TEST_F(ReshapeTest, R4ToR2_2x1x1x1_To_2x1) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  Array4D<float> input(2, 1, 1, 1);
  input.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input, LayoutUtil::MakeLayout({3, 2, 1, 0}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input_literal->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{0, 1, 2, 3}, /*new_sizes=*/{2, 1});

  std::unique_ptr<Literal> expected =
      LiteralTestUtil::Reshape({2, 1}, {1, 0}, *input_literal);
  ComputeAndCompareLiteral(&builder, *expected, {input_data.get()},
                           zero_error_spec_);
}

XLA_TEST_F(ReshapeTest, R4ToR2_2x1x4x1_To_4x2) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  Array4D<float> input(2, 1, 4, 1);
  input.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input, LayoutUtil::MakeLayout({3, 2, 1, 0}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input_literal->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{0, 1, 2, 3}, /*new_sizes=*/{4, 2});

  std::unique_ptr<Literal> expected =
      LiteralTestUtil::Reshape({4, 2}, {1, 0}, *input_literal);
  ComputeAndCompareLiteral(&builder, *expected, {input_data.get()},
                           zero_error_spec_);
}

// Tests R4->R2 reshape with the reshape dimensions {0, 2, 1, 3}.
XLA_TEST_F(ReshapeTest, R4ToR2_5x10x2x3_To_5x60_Dimensions_0213) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  Array4D<float> input(5, 10, 2, 3);
  input.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input, LayoutUtil::MakeLayout({3, 2, 1, 0}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input_literal->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{0, 2, 1, 3}, /*new_sizes=*/{5, 60});

  Array2D<float> expected_array(5, 60);
  input.Each([&](tensorflow::gtl::ArraySlice<int64> indices, float* cell) {
    expected_array(indices[0], indices[2] * 30 + indices[1] * 3 + indices[3]) =
        *cell;
  });
  auto expected = Literal::CreateR2FromArray2D(expected_array);
  ComputeAndCompareLiteral(&builder, *expected, {input_data.get()});
}

XLA_TEST_F(ReshapeTest, NoopReshape) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  Array4D<float> input_array(2, 3, 5, 7);
  input_array.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input_array, LayoutUtil::MakeLayout({1, 2, 3, 0}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto input = builder.Parameter(0, input_literal->shape(), "input");
  builder.Reshape(input, /*dimensions=*/{3, 0, 1, 2},
                  /*new_sizes=*/{7, 2, 3, 5});
  Computation computation = builder.Build().ConsumeValueOrDie();

  ExecutionOptions execution_options = execution_options_;
  *execution_options.mutable_shape_with_output_layout() =
      ShapeUtil::MakeShapeWithLayout(F32, {7, 2, 3, 5}, {2, 3, 0, 1});
  std::unique_ptr<Literal> output_literal =
      client_
          ->ExecuteAndTransfer(computation, {input_data.get()},
                               &execution_options)
          .ConsumeValueOrDie();

  // Since the reshape is a no-op, verify that it does not change the underlying
  // data.
  EXPECT_EQ(tensorflow::gtl::ArraySlice<float>(input_literal->f32s()),
            tensorflow::gtl::ArraySlice<float>(output_literal->f32s()));
}

XLA_TEST_F(ReshapeTest, R4ToR4Reshape_Trivial) {
  auto literal_1x2x3x4 = Literal::CreateR4(
      {{{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}},
        {{13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}}}});

  ComputationBuilder builder(client_, TestName());
  auto input = builder.ConstantLiteral(*literal_1x2x3x4);
  builder.Reshape(input, /*dimensions=*/{0, 1, 2, 3},
                  /*new_sizes=*/{1, 2, 3, 4});

  ComputeAndCompareLiteral(&builder, *literal_1x2x3x4, {});
}

XLA_TEST_F(ReshapeTest, R4ToR4Reshape) {
  auto literal_1x2x3x4 = Literal::CreateR4(
      {{{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}},
        {{13, 14, 15, 16}, {17, 18, 19, 20}, {21, 22, 23, 24}}}});

  ComputationBuilder builder(client_, TestName());
  auto input = builder.ConstantLiteral(*literal_1x2x3x4);
  builder.Reshape(input, /*dimensions=*/{1, 3, 2, 0},
                  /*new_sizes=*/{2, 4, 3, 1});

  // clang-format off
  auto expected_2x4x3x1 = Literal::CreateR4(
      {{{{1}, {5}, {9}},
        {{2}, {6}, {10}},
        {{3}, {7}, {11}},
        {{4}, {8}, {12}}},
       {{{13}, {17}, {21}},
        {{14}, {18}, {22}},
        {{15}, {19}, {23}},
        {{16}, {20}, {24}}}});
  // clang-format on

  ComputeAndCompareLiteral(&builder, *expected_2x4x3x1, {});
}

XLA_TEST_F(ReshapeTest, R4TwoMinorTransposeSimple) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  std::vector<int64> bounds = {2, 2, 2, 2};
  std::vector<int64> new_bounds = {bounds[0], bounds[1], bounds[3], bounds[2]};
  Array4D<float> input(bounds[0], bounds[1], bounds[2], bounds[3]);
  input.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input, LayoutUtil::MakeLayout({3, 2, 1, 0}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input_literal->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{0, 1, 3, 2}, /*new_sizes=*/new_bounds);

  std::unique_ptr<Literal> expected =
      LiteralTestUtil::Reshape(new_bounds, {2, 3, 1, 0}, *input_literal)
          ->Relayout(LayoutUtil::MakeLayout({3, 2, 1, 0}));

  // Specify the requested output shape explicitly to ensure that this reshape
  // actually corresponds to a two minor transpose.
  ComputeAndCompareLiteral(&builder, *expected, {input_data.get()},
                           zero_error_spec_, &expected->shape());
}

XLA_TEST_F(ReshapeTest, R4TwoMinorTransposeMajorFirstEffectiveR2) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  std::vector<int64> bounds = {1, 1, 250, 300};
  std::vector<int64> new_bounds = {bounds[0], bounds[1], bounds[3], bounds[2]};
  Array4D<float> input(bounds[0], bounds[1], bounds[2], bounds[3]);
  input.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input, LayoutUtil::MakeLayout({3, 2, 1, 0}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input_literal->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{0, 1, 3, 2}, /*new_sizes=*/new_bounds);

  std::unique_ptr<Literal> expected =
      LiteralTestUtil::Reshape(new_bounds, {2, 3, 1, 0}, *input_literal)
          ->Relayout(LayoutUtil::MakeLayout({3, 2, 1, 0}));

  // Specify the requested output shape explicitly to ensure that this reshape
  // actually corresponds to a two minor transpose.
  ComputeAndCompareLiteral(&builder, *expected, {input_data.get()},
                           zero_error_spec_, &expected->shape());
}

XLA_TEST_F(ReshapeTest, R4TwoMinorTransposeMajorFirstMinorEffectiveR1) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  std::vector<int64> bounds = {5, 5, 1, 10};
  std::vector<int64> new_bounds = {bounds[0], bounds[1], bounds[3], bounds[2]};
  Array4D<float> input(bounds[0], bounds[1], bounds[2], bounds[3]);
  input.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input, LayoutUtil::MakeLayout({3, 2, 1, 0}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input_literal->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{0, 1, 3, 2}, /*new_sizes=*/new_bounds);

  std::unique_ptr<Literal> expected =
      LiteralTestUtil::Reshape(new_bounds, {2, 3, 1, 0}, *input_literal)
          ->Relayout(LayoutUtil::MakeLayout({3, 2, 1, 0}));

  // Specify the requested output shape explicitly to ensure that this reshape
  // actually corresponds to a two minor transpose.
  ComputeAndCompareLiteral(&builder, *expected, {input_data.get()},
                           zero_error_spec_, &expected->shape());
}

XLA_TEST_F(ReshapeTest, R4TwoMinorTransposeMajorFirstMinorEffectiveR1InR2) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  // This happens in NN-Builder MNIST.
  std::vector<int64> bounds = {5, 5, 10, 1};
  std::vector<int64> new_bounds = {bounds[0], bounds[1], bounds[3], bounds[2]};
  Array4D<float> input(bounds[0], bounds[1], bounds[2], bounds[3]);
  input.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input, LayoutUtil::MakeLayout({3, 2, 1, 0}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input_literal->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{0, 1, 3, 2}, /*new_sizes=*/new_bounds);

  std::unique_ptr<Literal> expected =
      LiteralTestUtil::Reshape(new_bounds, {2, 3, 1, 0}, *input_literal)
          ->Relayout(LayoutUtil::MakeLayout({3, 2, 1, 0}));

  // Specify the requested output shape explicitly to ensure that this reshape
  // actually corresponds to a two minor transpose.
  ComputeAndCompareLiteral(&builder, *expected, {input_data.get()},
                           zero_error_spec_, &expected->shape());
}

XLA_TEST_F(ReshapeTest, R4TwoMinorTransposeTrivialR2) {
  std::mt19937 rng;
  std::uniform_real_distribution<float> distribution;
  std::vector<int64> bounds = {3, 3, 1, 3};
  std::vector<int64> new_bounds = {bounds[1], bounds[0], bounds[2], bounds[3]};
  Array4D<float> input(bounds[0], bounds[1], bounds[2], bounds[3]);
  input.Each(
      [&rng, &distribution](tensorflow::gtl::ArraySlice<int64> /* indices */,
                            float* cell) { *cell = distribution(rng); });
  std::unique_ptr<Literal> input_literal =
      Literal::CreateR4FromArray4DWithLayout(
          input, LayoutUtil::MakeLayout({0, 1, 2, 3}));
  std::unique_ptr<GlobalData> input_data =
      client_->TransferToServer(*input_literal).ConsumeValueOrDie();

  ComputationBuilder builder(client_, TestName());
  auto a = builder.Parameter(0, input_literal->shape(), "a");
  builder.Reshape(a, /*dimensions=*/{1, 0, 2, 3}, /*new_sizes=*/new_bounds);

  std::unique_ptr<Literal> expected =
      LiteralTestUtil::Reshape(new_bounds, {1, 0, 2, 3}, *input_literal)
          ->Relayout(input_literal->shape().layout());

  // Specify the requested output shape explicitly to ensure that this reshape
  // actually corresponds to a two minor transpose.
  ComputeAndCompareLiteral(&builder, *expected, {input_data.get()},
                           zero_error_spec_, &expected->shape());
}

}  // namespace
}  // namespace xla


text:
<?php

//@require 'Swift/Mime/Headers/AbstractHeader.php';
//@require 'Swift/RfcComplianceException.php';

/**
 * A Path Header in Swift Mailer, such a Return-Path.
 * @package Swift
 * @subpackage Mime
 * @author Chris Corbyn
 */
class Swift_Mime_Headers_PathHeader extends Swift_Mime_Headers_AbstractHeader
{

  /**
   * The address in this Header (if specified).
   * @var string
   * @access private
   */
  private $_address;

  /**
   * Creates a new PathHeader with the given $name.
   * @param string $name
   */
  public function __construct($name)
  {
    $this->setFieldName($name);
    $this->initializeGrammar();
  }

  /**
   * Get the type of Header that this instance represents.
   * @return int
   * @see TYPE_TEXT, TYPE_PARAMETERIZED, TYPE_MAILBOX
   * @see TYPE_DATE, TYPE_ID, TYPE_PATH
   */
  public function getFieldType()
  {
    return self::TYPE_PATH;
  }

  /**
   * Set the model for the field body.
   * This method takes a string for an address.
   * @param string $model
   * @throws Swift_RfcComplianceException
   */
  public function setFieldBodyModel($model)
  {
    $this->setAddress($model);
  }

  /**
   * Get the model for the field body.
   * This method returns a string email address.
   * @return mixed
   */
  public function getFieldBodyModel()
  {
    return $this->getAddress();
  }

  /**
   * Set the Address which should appear in this Header.
   * @param string $address
   * @throws Swift_RfcComplianceException
   */
  public function setAddress($address)
  {
    if (is_null($address))
    {
      $this->_address = null;
    }
    elseif ('' == $address
      || preg_match('/^' . $this->getGrammar('addr-spec') . '$/D', $address))
    {
      $this->_address = $address;
    }
    else
    {
      throw new Swift_RfcComplianceException(
        'Address set in PathHeader does not comply with addr-spec of RFC 2822.'
        );
    }
    $this->setCachedValue(null);
  }

  /**
   * Get the address which is used in this Header (if any).
   * Null is returned if no address is set.
   * @return string
   */
  public function getAddress()
  {
    return $this->_address;
  }

  /**
   * Get the string value of the body in this Header.
   * This is not necessarily RFC 2822 compliant since folding white space will
   * not be added at this stage (see {@link toString()} for that).
   * @return string
   * @see toString()
   */
  public function getFieldBody()
  {
    if (!$this->getCachedValue())
    {
      if (isset($this->_address))
      {
        $this->setCachedValue('<' . $this->_address . '>');
      }
    }
    return $this->getCachedValue();
  }

}


text:
namespace RakNet
{
	//-------------------------------  State manager -------------------------------------------

	CPtr<CClusterConfig> CHaStateManager::LoadConfig()
	{
		return CClusterConfig::Deserialize( *m_ConfigBuffer );
	}

	void CHaStateManager::SaveConfig(const CClusterConfig& config)
	{
		m_ConfigBuffer = config.Serialize();
	}

	void CHaStateManager::SaveState(const CServerState& state)
	{
		m_StateBuffer = state.Serialize();
	}

	CPtr<CServerState> CHaStateManager::ReadState()
	{
		return CServerState::Deserialize( *m_StateBuffer );
	}

	CPtr<CLogStore> CHaStateManager::LoadLogStore()
	{
		return cs_new<CFileSystemLogStore>( m_StrLogStore, -1 );
	}

	int32 CHaStateManager::ServerId()
	{
		return (int32) RakNetGUID::ToUint32(rakPeerInterface->GetMyGUID());
	}

	void CHaStateManager::SystemExit(const int exit_code)
	{
		rakPeerInterface->Shutdown( 100, 0, PacketPriority::HIGH_PRIORITY );
	}

	//-------------------------------  State machine -------------------------------------------

	void CHaStateMachine::Commit(const ulong log_idx, CBuffer& data)
	{

	}

	void CHaStateMachine::PreCommit(const ulong log_idx, CBuffer& data)
	{

	}

	void CHaStateMachine::Rollback(const ulong log_idx, CBuffer& data)
	{

	}

	void CHaStateMachine::SaveSnapshotData(CSnapshot& s, const ulong offset, CBuffer& data)
	{

	}

	bool CHaStateMachine::ApplySnapshot(CSnapshot& s)
	{
		false;
	}

	int CHaStateMachine::ReadSnapshotData(CSnapshot& s, const ulong offset, CBuffer& data)
	{
		return 0;
	}

	CPtr<CSnapshot> CHaStateMachine::LastSnapshot()
	{
		return CPtr<CSnapshot>();
	}

	void CHaStateMachine::CreateSnapshot(CSnapshot& s, CAsyncResult<bool>::handler_type& when_done)
	{

	}

	//-------------------------------  Logger class -------------------------------------------
	CHaClusterFileLogger::CHaClusterFileLogger(CHaClusterLoggerManager& ClusterLoggerManager, const std::string& log_file, ELogLevel::Type eLevel)
		: m_LoggerManager(ClusterLoggerManager), m_LogLevel(eLevel), m_LogFile(log_file), m_LogBuffer(), m_Mutex() {}

	CHaClusterFileLogger::~CHaClusterFileLogger()
	{
		Flush();
		m_LogFile.flush();
		m_LogFile.close();
		m_LoggerManager.RemoveLogger(this);
	}

	void CHaClusterFileLogger::Debug(const std::string& log_line)
	{
		if (m_LogLevel <= 0)
			write_log("debug", log_line);
	}

	void CHaClusterFileLogger::Info(const std::string& log_line)
	{
		if (m_LogLevel <= 1)
			write_log("info ", log_line);
	}

	void CHaClusterFileLogger::Warning(const std::string& log_line)
	{
		if (m_LogLevel <= 2)
			write_log("warn ", log_line);
	}

	void CHaClusterFileLogger::Error(const std::string& log_line)
	{
		if (m_LogLevel <= 3)
			write_log("error", log_line);
	}

	void CHaClusterFileLogger::Flush()
	{
		DataStructures::Queue<std::string> mBackup;
		{
			std::lock_guard<std::mutex> guard(m_Mutex);
			if (m_LogBuffer.Size() > 0)
				m_LogBuffer.Swap(mBackup);
		}

		for (int iIndex = 0; iIndex < mBackup.Size(); iIndex++)
		{
			m_LogFile << mBackup[iIndex] << std::endl;
		}
		mBackup.Clear(_FILE_AND_LINE_);
	}

	void CHaClusterFileLogger::write_log(const std::string& level, const std::string& log_line)
	{
		std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
		int ms = (int)(std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count() % 1000);
		__time64_t now_c = std::chrono::system_clock::to_time_t(now);
		std::tm* tm = std::gmtime(&now_c);
		std::hash<std::thread::id> hasher;
		std::string line(sstrfmt("%d/%d/%d %d:%d:%d.%d\t[%d]\t%s\t").fmt(tm->tm_mon + 1, tm->tm_mday, tm->tm_year + 1900, tm->tm_hour, tm->tm_min, tm->tm_sec, ms, hasher(std::this_thread::get_id()), level.c_str()));
		line += log_line;
		{
			std::lock_guard<std::mutex> guard(m_Mutex);
			m_LogBuffer.Push(line, _FILE_AND_LINE_ );
		}
	}

	//-------------------------------  Logger manager -------------------------------------------

	CHaClusterLoggerManager::CHaClusterLoggerManager() : m_bHasRemovedLogger(false) {}

	CHaClusterLoggerManager::~CHaClusterLoggerManager()
	{
		Clear();
	}

	CHaClusterFileLogger* CHaClusterLoggerManager::LoggerAdd( const std::string& log_file, ELogLevel::Type eLevel )
	{
		CHaClusterFileLogger* pLogger = OP_NEW_3<CHaClusterFileLogger>( _FILE_AND_LINE_, *this, log_file, eLevel );
		m_aLoggers.Push( pLogger, _FILE_AND_LINE_ );
		return pLogger;
	}

	void CHaClusterLoggerManager::RemoveLogger(CHaClusterFileLogger* pLogger)
	{
		unsigned int uiIndex = m_aLoggers.GetIndexOf( pLogger );
		if ( uiIndex != MAX_UNSIGNED_LONG )
		{
			m_aLoggers.RemoveAtIndexFast( uiIndex );
			m_aRemovedLoggers.Push(pLogger, _FILE_AND_LINE_ );
			m_bHasRemovedLogger = true;
		}
	}

	void CHaClusterLoggerManager::Progress()
	{
		if ( !m_bHasRemovedLogger )
			return;
		for( int iIndex = 0; iIndex < m_aRemovedLoggers.Size(); iIndex++ )
			OP_DELETE<CHaClusterFileLogger>( m_aRemovedLoggers[iIndex], _FILE_AND_LINE_ );
		m_aRemovedLoggers.Clear( true,_FILE_AND_LINE_ );
	}

	void CHaClusterLoggerManager::Clear()
	{
		for( int iIndex = 0; iIndex < m_aLoggers.Size(); iIndex++ )
			OP_DELETE<CHaClusterFileLogger>( m_aLoggers[iIndex], _FILE_AND_LINE_ );
		m_aLoggers.Clear( true,_FILE_AND_LINE_ );
	}

	//-------------------------------  Sheduler -------------------------------------------
	void CHADelayedTaskScheduler::Schedule(CPtr<CDelayedTask>& pTask, int32 iMs)
	{
		m_aTasks.Push( OP_NEW_3<CHaDelayedTask>( _FILE_AND_LINE_,  pTask, iMs, std::bind(&CHADelayedTaskScheduler::FreeTask, this, std::placeholders::_1)), _FILE_AND_LINE_ );
	}

	void CHADelayedTaskScheduler::FreeTask(void* ptr)
	{
		CHaDelayedTask* pTask = static_cast<CHaDelayedTask*>(ptr);
		if (!pTask)
		{
			assert(false);
			return;
		}
		//pTask->m_eStatus = CHADelayedTaskScheduler::

	}

	void CHADelayedTaskScheduler::OnCancel(CPtr<CDelayedTask>& pTask)
	{
		CHaDelayedTask* pHaTask = static_cast<CHaDelayedTask*>(pTask->GetContext());
		if (pHaTask)
			pHaTask->Cancel();
	}

	void CHADelayedTaskScheduler::Clear()
	{
		for (int iIndex = 0; iIndex < m_aTasks.Size(); iIndex)
		{
			CHaDelayedTask* pTasks = m_aTasks.Get(iIndex);
			if (pTasks->m_Task)
			{
				pTasks->m_Task->Cancel();
				OP_DELETE<CHaDelayedTask>(pTasks, _FILE_AND_LINE_);
			}
		}
		m_aTasks.Clear(false, _FILE_AND_LINE_);
	}

	void CHADelayedTaskScheduler::Progress()
	{
		TimeMS msCurrentTime = GetTimeMS();
		for (int iIndex = 0; iIndex < m_aTasks.Size(); iIndex)
		{
			CHaDelayedTask* pTasks = m_aTasks.Get(iIndex);
			if (pTasks->m_eStatus == CHaDelayedTask::EStatus::eAssigned && pTasks->m_MsStart <= msCurrentTime)
			{
				pTasks->m_Task->Execute();
				pTasks->m_eStatus = CHaDelayedTask::EStatus::eExecuted;
			}
			else if (pTasks->m_eStatus == CHaDelayedTask::EStatus::eFinished || pTasks->m_eStatus == CHaDelayedTask::EStatus::eExecuted )
			{
				m_aGc.Push(pTasks, _FILE_AND_LINE_);
				m_aTasks.RemoveAtIndex(iIndex);
				iIndex--;
			}
		}

		GC();
		m_LastCheck = msCurrentTime;
	}

	void CHADelayedTaskScheduler::GC()
	{
		for (int iIndex = 0; iIndex < m_aGc.Size(); iIndex)
		{
			OP_DELETE<CHaDelayedTask>( m_aGc.Get(iIndex), _FILE_AND_LINE_);
		}
		m_aGc.Clear(true, _FILE_AND_LINE_);
	}

	CHADelayedTaskScheduler::CHADelayedTaskScheduler() : m_LastCheck(GetTimeMS())
	{

	}

	CHADelayedTaskScheduler::~CHADelayedTaskScheduler()
	{
		Clear();
	}

	// Serializer helpers

	void SerializeState( const CServerState& State, BitStream* pBitStream )
	{
		pBitStream->Write( State.GetTerm() );
		pBitStream->Write( State.GetCommitIndex() );
		pBitStream->Write( State.GetVotedFor() );
	}

	void DeSerializeState( CPtr<CServerState>& State, BitStream* pBitStream )
	{
		int iTemp;
		unsigned long ulTemp;
		pBitStream->Read( ulTemp );
		State->SetTerm( ulTemp );

		pBitStream->Read( ulTemp );
		State->SetCommitIndex( ulTemp );

		pBitStream->Read( iTemp );
		State->SetVotedFor( iTemp );
	}

}


text:
Villkor
==============================================

[Anax Flat finns på GitHub](https://github.com/canax/anax-flat) under [MIT licens](https://github.com/canax/anax-flat/blob/master/LICENSE).


text:
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.Comment
       (js_newComment, newComment, Comment, castToComment, gTypeComment)
       where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums

foreign import javascript unsafe "new window[\"Comment\"]($1)"
        js_newComment :: JSString -> IO (JSRef Comment)

-- | <https://developer.mozilla.org/en-US/docs/Web/API/Comment Mozilla Comment documentation>
newComment :: (MonadIO m, ToJSString data') => data' -> m Comment
newComment data'
  = liftIO (js_newComment (toJSString data') >>= fromJSRefUnchecked)


text:
/**
 * Autogenerated by Thrift Compiler (0.9.1)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#include "computeResourceModel_constants.h"

namespace apache { namespace airavata { namespace model { namespace appcatalog { namespace computeresource {

const computeResourceModelConstants g_computeResourceModel_constants;

computeResourceModelConstants::computeResourceModelConstants() {
  DEFAULT_ID = "DO_NOT_SET_AT_CLIENTS";

}

}}}}} // namespace


text:
define(function(require){

	var signin = document.getElementById('signin');

	signin.onclick = function(){
		require.async('./login', function(login){
			login.show();
		});
	};

});


text:
require 'rails_helper'

describe User do
  it { should have_many(:repos).through(:memberships) }
  it { should have_many(:subscribed_repos).through(:subscriptions) }
  it { should validate_presence_of :github_username }
  it { should have_many(:memberships).dependent(:destroy) }

  describe '.subscribed_repos' do
    it 'returns subscribed repos' do
      user = create(:user)
      _unsubscribed_repo = create(:repo, users: [user])
      _inactive_subscription = create(:subscription, :inactive, user: user)
      active_subscription = create(:subscription, user: user)

      repos = user.subscribed_repos

      expect(repos).to eq [active_subscription.repo]
    end
  end

  describe '#create' do
    it 'generates a remember_token' do
      user = build(:user)
      allow(SecureRandom).to receive(:hex) { 'remembertoken' }

      user.save

      expect(SecureRandom).to have_received(:hex).with(20)
      expect(user.remember_token).to eq 'remembertoken'
    end
  end

  describe '#token' do
    it 'generates saves encrypted token in database' do
      user = build(:user)
      user.token = 'original-token'

      user.save

      expect(user['token']).to_not eq(user.token)
      expect(user['token']).to_not eq('original-token')
    end

    it 'returns original value of token on call' do
      user = build(:user)
      user.token = 'original-token'

      user.save

      expect(user.reload.token).to eq('original-token')
    end
  end

  describe '#to_s' do
    it 'returns GitHub username' do
      user = build(:user)

      user_string = user.to_s

      expect(user_string).to eq user.github_username
    end
  end

  describe '#active_repos' do
    it 'returns active repos' do
      user = create(:user)
      active_repo = create(:repo, :active, users: [user])
      create(:repo, :inactive, users: [user])

      expect(user.active_repos).to eq([active_repo])
    end
  end

  describe '#has_repos_with_missing_information?' do
    context 'with repo without organization info' do
      it 'returns true' do
        skip 'TODO: Implement for gitlab'
        user = create(:user)
        repo = create(:repo, in_organization: nil)
        user.repos << repo

        expect(user).to have_repos_with_missing_information
      end
    end

    context 'with repo without privacy info' do
      it 'return true' do
        skip 'TODO: Implement for gitlab'
        user = create(:user)
        repo = create(:repo, private: nil)
        user.repos << repo

        expect(user).to have_repos_with_missing_information
      end
    end

    context 'with repo without organization and privacy info' do
      it 'returns true' do
        skip 'TODO: Implement for gitlab'
        user = create(:user)
        repo = create(:repo, in_organization: nil, private: nil)
        user.repos << repo

        expect(user).to have_repos_with_missing_information
      end
    end

    context 'with repo with organization and privacy info' do
      it 'returns false' do
        user = create(:user)
        repo = create(:repo, in_organization: true, private: true)
        user.repos << repo

        expect(user).not_to have_repos_with_missing_information
      end
    end
  end

  describe '#has_access_to_private_repos?' do
    context 'when token scopes include repo' do
      it 'returns true' do
        user = User.new(token_scopes: 'repo,user:email')

        expect(user).to have_access_to_private_repos
      end
    end

    context "when token scopes don't include repo" do
      it 'returns false' do
        user = User.new(token_scopes: 'public_repo,user:email')

        expect(user).not_to have_access_to_private_repos
      end
    end
  end
end


text:
.error-register{
	  text-align: center;
	  padding: 10px;
	  background: linear-gradient(to bottom, rgba(240, 221, 175, 0.196), rgba(240, 221, 175, 0.400)) transparent;
}
.errors{
	text-align: left;
}

.registerview input.btn.btn-default{
	float: none;
}


text:
package com.opengamma.examples.simulated.masterdb;

import org.testng.annotations.Test;

import com.opengamma.integration.masterdb.AbstractIntegrationDbPositionMasterTest;
import com.opengamma.util.test.TestGroup;

/**
 * Test DbPositionMaster.
 */
@Test(groups = TestGroup.INTEGRATION)
public class IntegrationDbPositionMasterTest extends AbstractIntegrationDbPositionMasterTest {

  @Test
  public void test_querySampleEntry() {
    // TODO:
  }

}


text:
/*
 * $Id TestDisplayContentTable.java 2012/12/03 14:52:00 rwincewicz $
 */

/*

 Copyright (c) 2012 Board of Trustees of Leland Stanford Jr. University,
 all rights reserved.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
 IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 Except as contained in this notice, the name of Stanford University shall not
 be used in advertising or otherwise to promote the sale, use or other dealings
 in this Software without prior written authorization from Stanford University.

 */
package org.lockss.servlet;

import java.util.*;
import org.lockss.plugin.*;
import org.lockss.protocol.MockIdentityManager;
import org.lockss.test.*;

/**
 *
 * @author rwincewicz
 */
public class TestDisplayContentTable extends LockssTestCase {

  MockArchivalUnit au1;
  MockArchivalUnit au2;
  MockArchivalUnit au3;
  MockArchivalUnit au4;
  MockArchivalUnit au5;

  private Collection createAuList() {
    MockLockssDaemon daemon = getMockLockssDaemon();
    MockIdentityManager idm = new MockIdentityManager();
    daemon.setIdentityManager(idm);
    ArrayList<ArchivalUnit> auList = new ArrayList<ArchivalUnit>();
    au1 = MockArchivalUnit.newInited(daemon);
    MockPlugin plugin1 = new MockPlugin(daemon);
    plugin1.setPluginName("B plugin");
    au1.setPlugin(plugin1);
    auList.add(au1);
    au2 = MockArchivalUnit.newInited(daemon);
    MockPlugin plugin2 = new MockPlugin(daemon);
    plugin2.setPluginName("D plugin");
    au2.setPlugin(plugin2);
    auList.add(au2);
    au3 = MockArchivalUnit.newInited(daemon);
    MockPlugin plugin3 = new MockPlugin(daemon);
    plugin3.setPluginName("A plugin");
    au3.setPlugin(plugin3);
    auList.add(au3);
    au4 = MockArchivalUnit.newInited(daemon);
    MockPlugin plugin4 = new MockPlugin(daemon);
    plugin4.setPluginName("C plugin");
    au4.setPlugin(plugin4);
    auList.add(au4);
    au5 = MockArchivalUnit.newInited(daemon);
    MockPlugin plugin5 = new MockPlugin(daemon);
    au5.setPlugin(plugin5);
    auList.add(au5);
    return auList;
  }

  public void testOrderAusByPlugin() {
    Collection<ArchivalUnit> aus = createAuList();
    assertNotNull(aus);
    TreeMap<Plugin, TreeSet<ArchivalUnit>> auList = DisplayContentTable.orderAusByPlugin(aus);
    assertNotNull(auList);
    Set auSet = auList.keySet();
    Object[] auArray = auSet.toArray();
    Plugin plugin1 = (Plugin) auArray[0];
    assertEquals("A plugin", plugin1.getPluginName());
    Plugin plugin2 = (Plugin) auArray[1];
    assertEquals("B plugin", plugin2.getPluginName());
    Plugin plugin3 = (Plugin) auArray[2];
    assertEquals("C plugin", plugin3.getPluginName());
    Plugin plugin4 = (Plugin) auArray[3];
    assertEquals("D plugin", plugin4.getPluginName());
    Plugin plugin5 = (Plugin) auArray[4];
    assertEquals("Mock Plugin", plugin5.getPluginName());
  }

  public void testOrderAusByPublisher() {
    Collection<ArchivalUnit> aus = createAuList();
    assertNotNull(aus);
  }

  public void testCleanName() {
    String name = "(T e& s &t)";
    String cleanedName = DisplayContentTable.cleanName(name);
    assertEquals("T_e_s_t", cleanedName);
  }
}


text:
.PlaylistPanel-empty {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: calc(100% - 54px);
  padding: 0 20%;
}

.PlaylistPanel-emptyIcon {
  width: 240px;
  height: 240px;
  max-height: 50%;
  color: rgba(255, 255, 255, 0.2);
}

.PlaylistPanel-emptyHeader {
  font-weight: bold;
}


text:
package quasar.yggdrasil.vfs

import quasar.precog.util.IOUtils

import fs2.Stream
import fs2.interop.scalaz._

import org.specs2.mutable._

import pathy.Path

import scalaz.{~>, Coproduct, NaturalTransformation}
import scalaz.concurrent.Task

import scodec.bits.ByteVector

import java.nio.file.Files
import java.io.{File, FileInputStream, FileOutputStream}

object RealPOSIXSpecs extends Specification {
  import POSIXOp._

  "real posix interpreter" should {
    "mkdir on root if non-existent" in {
      val target = new File(newBase(), "non-existent")
      RealPOSIX(target).unsafePerformSync

      target.exists() mustEqual true
      target.isDirectory() mustEqual true
    }

    "produce distinct UUIDs" in setupDir { base =>
      val test = for {
        interp <- RealPOSIX(base)
        first <- interp(GenUUID)
        second <- interp(GenUUID)
      } yield (first, second)

      val (first, second) = test.unsafePerformSync

      first must not(be(second))
    }

    "open a file and return its contents" in setupDir { base =>
      val file = new File(base, "test")

      val fos = new FileOutputStream(file)
      fos.write(Array[Byte](1, 2, 3, 4, 5))
      fos.close()

      val test = for {
        interp <- RealPOSIX(base)
        results <- interp(OpenR(Path.rootDir </> Path.file("test")))
        contents <- translate(results, interp).fold(ByteVector.empty)(_ ++ _).runLast
      } yield contents

      test.unsafePerformSync must beSome(ByteVector(1, 2, 3, 4, 5))
    }

    "write to a file" in setupDir { base =>
      val file = new File(base, "test")

      val test = for {
        interp <- RealPOSIX(base)
        sink <- interp(OpenW(Path.rootDir </> Path.file("test")))
        driver = Stream(ByteVector(1, 2, 3, 4, 5)).to(sink)
        _ <- translate(driver, interp).run
      } yield ()

      test.unsafePerformSync

      val fis = new FileInputStream(file)
      val buffer = new Array[Byte](10)
      fis.read(buffer) mustEqual 5
      fis.close()

      buffer mustEqual Array(1, 2, 3, 4, 5, 0, 0, 0, 0, 0)
    }

    "list the contents of a directory" in setupDir { base =>
      val targets = List("test1", "test2", "test3")
      targets.foreach(target => Files.createFile(new File(base, target).toPath()))

      val test = for {
        interp <- RealPOSIX(base)
        files <- interp(Ls(Path.rootDir))
      } yield files

      test.unsafePerformSync must containTheSameElementsAs(targets.map(Path.file))
    }

    "make a subdirectory" in setupDir { base =>
      val target = "foo"

      val test = for {
        interp <- RealPOSIX(base)
        _ <- interp(MkDir(Path.rootDir </> Path.dir(target)))
      } yield ()

      test.unsafePerformSync

      val ftarget = new File(base, target)

      ftarget.exists() mustEqual true
      ftarget.isDirectory() mustEqual true
    }

    "link two directories" in setupDir { base =>
      val from = "foo"
      val to = "bar"

      val test = for {
        interp <- RealPOSIX(base)
        _ <- interp(MkDir(Path.rootDir </> Path.dir(from)))
        _ <- interp(LinkDir(Path.rootDir </> Path.dir(from), Path.rootDir </> Path.dir(to)))
      } yield ()

      test.unsafePerformSync

      val ffrom = new File(base, from)
      val fto = new File(base, to)

      fto.exists() mustEqual true
      fto.isDirectory() mustEqual true

      Files.createFile(new File(ffrom, "test").toPath())

      new File(fto, "test").exists() mustEqual true
    }

    "link two files" in setupDir { base =>
      val from = "foo"
      val to = "bar"

      val test = for {
        interp <- RealPOSIX(base)

        sink1 <- interp(OpenW(Path.rootDir </> Path.file(from)))
        driver1 = Stream(ByteVector(1, 2, 3)).to(sink1)
        _ <- translate(driver1, interp).run

        _ <- interp(LinkFile(Path.rootDir </> Path.file(from), Path.rootDir </> Path.file(to)))

        sink2 <- interp(OpenW(Path.rootDir </> Path.file(from)))
        driver2 = Stream(ByteVector(4, 5, 6)).to(sink2)
        _ <- translate(driver2, interp).run
      } yield ()

      test.unsafePerformSync

      val fis = new FileInputStream(new File(base, to))
      val buffer = new Array[Byte](3)
      fis.read(buffer) mustEqual 3
      fis.close()

      buffer mustEqual Array(4, 5, 6)
    }

    "move a file" in setupDir { base =>
      val from = "foo"
      val to = "bar"

      Files.createFile(new File(base, from).toPath())

      val test = for {
        interp <- RealPOSIX(base)
        _ <- interp(Move(Path.rootDir </> Path.file(from), Path.rootDir </> Path.file(to)))
      } yield ()

      test.unsafePerformSync

      new File(base, from).exists() mustEqual false
      new File(base, to).exists() mustEqual true
    }

    "check if a file exists" in setupDir { base =>
      val foo = "foo"
      val bar = "bar"

      Files.createFile(new File(base, foo).toPath())

      val test = for {
        interp <- RealPOSIX(base)
        fooEx <- interp(Exists(Path.rootDir </> Path.file(foo)))
        barEx <- interp(Exists(Path.rootDir </> Path.file(bar)))
      } yield (fooEx, barEx)

      val (fooEx, barEx) = test.unsafePerformSync

      fooEx mustEqual true
      barEx mustEqual false
    }

    "check if a directory exists" in setupDir { base =>
      val foo = "foo"
      val bar = "bar"

      new File(base, foo).mkdir()

      val test = for {
        interp <- RealPOSIX(base)
        fooEx <- interp(Exists(Path.rootDir </> Path.dir(foo)))
        barEx <- interp(Exists(Path.rootDir </> Path.dir(bar)))
      } yield (fooEx, barEx)

      val (fooEx, barEx) = test.unsafePerformSync

      fooEx mustEqual true
      barEx mustEqual false
    }

    "delete a file" in setupDir { base =>
      val target = "foo"

      Files.createFile(new File(base, target).toPath())

      val test = for {
        interp <- RealPOSIX(base)
        _ <- interp(Delete(Path.rootDir </> Path.file(target)))
      } yield ()

      test.unsafePerformSync

      new File(base, target).exists() mustEqual false
    }

    "delete an empty directory" in setupDir { base =>
      val target = "foo"
      val ftarget = new File(base, target)

      ftarget.mkdir()

      val test = for {
        interp <- RealPOSIX(base)
        _ <- interp(Delete(Path.rootDir </> Path.dir(target)))
      } yield ()

      test.unsafePerformSync

      ftarget.exists() mustEqual false
    }

    "delete a non-empty directory" in setupDir { base =>
      val target = "foo"
      val ftarget = new File(base, target)

      ftarget.mkdir()

      Files.createFile(new File(ftarget, "bar").toPath())

      val test = for {
        interp <- RealPOSIX(base)
        _ <- interp(Delete(Path.rootDir </> Path.dir(target)))
      } yield ()

      test.unsafePerformSync

      ftarget.exists() mustEqual false
    }

    "delete a non-empty dir symlink" in setupDir { base =>
      val target = "foo"
      val ftarget = new File(base, target)

      ftarget.mkdir()

      Files.createFile(new File(ftarget, "test").toPath())

      val test = for {
        interp <- RealPOSIX(base)
        _ <- interp(LinkDir(Path.rootDir </> Path.dir("foo"), Path.rootDir </> Path.dir("bar")))
        _ <- interp(Delete(Path.rootDir </> Path.dir("bar")))
      } yield ()

      test.unsafePerformSync

      ftarget.exists() mustEqual true
      new File(ftarget, "test").exists() mustEqual true

      new File(base, "bar").exists() mustEqual false
    }
  }

  def translate[A](str: Stream[POSIXWithTask, A], interp: POSIXOp ~> Task): Stream[Task, A] = {
    import fs2.util.UF1

    val nt = λ[UF1[POSIXWithTask, Task]] { pwt =>
      val fullInt =
        λ[Coproduct[POSIXOp, Task, ?] ~> Task](_.fold(interp, NaturalTransformation.refl[Task]))

      pwt.foldMap(fullInt)
    }

    str.translate(nt)
  }

  def setupDir[A](body: File => A): A = {
    val base = newBase()
    val back = body(base)
    IOUtils.recursiveDelete(base).unsafePerformIO()
    back
  }

  def newBase() = Files.createTempDirectory("RealPOSIXSpecs").toFile
}


text:
#ifndef BT_COMPOUND_COLLISION_ALGORITHM_H
#define BT_COMPOUND_COLLISION_ALGORITHM_H

#include "btActivatingCollisionAlgorithm.h"
#include "XMBullet/BulletCollision/BroadphaseCollision/btDispatcher.h"
#include "XMBullet/BulletCollision/BroadphaseCollision/btBroadphaseInterface.h"

#include "XMBullet/BulletCollision/NarrowPhaseCollision/btPersistentManifold.h"
class btDispatcher;
#include "XMBullet/BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "btCollisionCreateFunc.h"
#include "XMBullet/LinearMath/btAlignedObjectArray.h"
class btDispatcher;
class btCollisionObject;

/// btCompoundCollisionAlgorithm  supports collision between CompoundCollisionShapes and other collision shapes
class btCompoundCollisionAlgorithm  : public btActivatingCollisionAlgorithm
{
	btAlignedObjectArray<btCollisionAlgorithm*> m_childCollisionAlgorithms;
	bool m_isSwapped;

	class btPersistentManifold*	m_sharedManifold;
	bool					m_ownsManifold;

	int	m_compoundShapeRevision;//to keep track of changes, so that childAlgorithm array can be updated

	void	removeChildAlgorithms();

	void	preallocateChildAlgorithms(btCollisionObject* body0,btCollisionObject* body1);

public:

	btCompoundCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci,btCollisionObject* body0,btCollisionObject* body1,bool isSwapped);

	virtual ~btCompoundCollisionAlgorithm();

	virtual void processCollision (btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	btScalar	calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut);

	virtual	void	getAllContactManifolds(btManifoldArray&	manifoldArray)
	{
		int i;
		for (i=0;i<m_childCollisionAlgorithms.size();i++)
		{
			if (m_childCollisionAlgorithms[i])
				m_childCollisionAlgorithms[i]->getAllContactManifolds(manifoldArray);
		}
	}

	struct CreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm));
			return new(mem) btCompoundCollisionAlgorithm(ci,body0,body1,false);
		}
	};

	struct SwappedCreateFunc :public 	btCollisionAlgorithmCreateFunc
	{
		virtual	btCollisionAlgorithm* CreateCollisionAlgorithm(btCollisionAlgorithmConstructionInfo& ci, btCollisionObject* body0,btCollisionObject* body1)
		{
			void* mem = ci.m_dispatcher1->allocateCollisionAlgorithm(sizeof(btCompoundCollisionAlgorithm));
			return new(mem) btCompoundCollisionAlgorithm(ci,body0,body1,true);
		}
	};

};

#endif //BT_COMPOUND_COLLISION_ALGORITHM_H


text:
kerubApp.controller('BusType', function($scope, $log) {
	$scope.init = function(link) {
		$log.debug('init', link);
        $scope.link = link;
	};
    $scope.choose = function(value) {
    	$scope.link.bus = value;
    };
    $scope.setBus = function (bus) {
    	$scope.link.bus = bus;
    };
    $scope.setType = function (device) {
    	$scope.link.device = device;
    };
    $scope.isBus = function(bus) {
    	return $scope.link.bus === bus
    }
});