text:
package sodium;

import java.util.Optional;

/**
 * Represents a value of type A that changes over time.
 */
public class Cell {
	final Stream str;
	A value;
	A valueUpdate;
	private Listener cleanup;
    Lazy lazyInitValue;  // Used by LazyCell

	/**
	 * A cell with a constant value.
	 */
    public Cell(A value)
    {
    	this.str = new Stream();
    	this.value = value;
    }

    Cell(final Stream str, A initValue)
    {
    	this.str = str;
    	this.value = initValue;
    	Transaction.run(new Handler<Transaction>() {
    		public void run(Transaction trans1) {
	    		Cell.this.cleanup = str.listen(Node.NULL, trans1, new TransactionHandler() {
	    			public void run(Transaction trans2, A a) {
			    		if (Cell.this.valueUpdate == null) {
			    			trans2.last(new Runnable() {
			    				public void run() {
				    				Cell.this.value = Cell.this.valueUpdate;
				    				Cell.this.lazyInitValue = null;
				    				Cell.this.valueUpdate = null;
				    			}
			    			});
			    		}
			    		Cell.this.valueUpdate = a;
			    	}
	    		}, false);
    		}
    	});
    }

    /**
     * @return The value including any updates that have happened in this transaction.
     */
    final A newValue()
    {
    	return valueUpdate == null ? sampleNoTrans() :  valueUpdate;
    }

    /**
     * Sample the cell's current value.
     *

     * It may be used inside the functions passed to primitives that apply them to {@link Stream}s,
     * including {@link Stream#map(Lambda1)} in which case it is equivalent to snapshotting the cell,
     * {@link Stream#snapshot(Cell, Lambda2)}, {@link Stream#filter(Lambda1)} and
     * {@link Stream#merge(Stream, Lambda2)}.
     * It should generally be avoided in favour of {@link listen(Handler)} so you don't
     * miss any updates, but in many circumstances it makes sense.
     */
    public final A sample()
    {
        return Transaction.apply(new Lambda1<Transaction, A>() {
        	public A apply(Transaction trans) {
        		return sampleNoTrans();
        	}
        });
    }

    private static class LazySample {
        LazySample(Cell cell) {
            this.cell = cell;
        }
        Cell cell;
        boolean hasValue;
        A value;
    }

    /**
     * A variant of {@link sample()} that works with {@link CellLoop}s when they haven't been looped yet.
     * It should be used in any code that's general enough that it could be passed a {@link CellLoop}.
     * @see Stream#holdLazy(Lazy) Stream.holdLazy()
     */
    public final Lazy sampleLazy() {
        final Cell me = this;
        return Transaction.apply(new Lambda1<Transaction, Lazy>() {
        	public Lazy apply(Transaction trans) {
        	    return me.sampleLazy(trans);
            }
        });
    }

    final Lazy sampleLazy(Transaction trans) {
        final Cell me = this;
        final LazySample s = new LazySample(me);
        trans.last(new Runnable() {
            public void run() {
                s.value = me.valueUpdate != null ? me.valueUpdate : me.sampleNoTrans();
                s.hasValue = true;
                s.cell = null;
            }
        });
        return new Lazy(new Lambda0() {
            public A apply() {
                if (s.hasValue)
                    return s.value;
                else
                    return s.cell.sample();
            }
        });
    }

    A sampleNoTrans()
    {
        return value;
    }

    final Stream updates(Transaction trans)
    {
        return str.lastFiringOnly(trans);
    }

    final Stream value(Transaction trans1)
    {
    	final StreamWithSend<Unit> sSpark = new StreamWithSend<Unit>();
        trans1.prioritized(sSpark.node, new Handler<Transaction>() {
            public void run(Transaction trans2) {
                sSpark.send(trans2, Unit.UNIT);
            }
        });
    	Stream sInitial = sSpark.snapshot(this);
        return updates(trans1).orElse(sInitial);
    }

    /**
     * Transform the cell's value according to the supplied function, so the returned Cell
     * always reflects the value of the function applied to the input Cell's value.
     * @param f Function to apply to convert the values. It must be referentially transparent.
     */
	public final  Cell map(final Lambda1 f)
	{
		return Transaction.apply(new Lambda1<Transaction, Cell>() {
			public Cell apply(Transaction trans) {
                return updates(trans).map(f).holdLazy(trans, sampleLazy(trans).map(f));
            }
        });
	}

	/**
	 * Lift a binary function into cells, so the returned Cell always reflects the specified
	 * function applied to the input cells' values.
	 * @param f Function to apply. It must be referentially transparent.
	 */
	public static final  Cell<C> lift(final Lambda2 f, Cell a, Cell b)
	{
		Lambda1<A, Lambda1> ffa = new Lambda1<A, Lambda1>() {
			public Lambda1 apply(final A aa) {
				return new Lambda1() {
					public C apply(B bb) {
						return f.apply(aa,bb);
					}
				};
			}
		};
		Cell<Lambda1> bf = a.map(ffa);
		return apply(bf, b);
	}

	/**
	 * Lift a ternary function into cells, so the returned Cell always reflects the specified
	 * function applied to the input cells' values.
	 * @param f Function to apply. It must be referentially transparent.
	 */
	public static final  Cell<D> lift(final Lambda3 f, Cell a, Cell b, Cell<C> c)
	{
		Lambda1<A, Lambda1<B, Lambda1<C,D>>> ffa = new Lambda1<A, Lambda1<B, Lambda1<C,D>>>() {
			public Lambda1<B, Lambda1<C,D>> apply(final A aa) {
				return new Lambda1<B, Lambda1<C,D>>() {
					public Lambda1<C,D> apply(final B bb) {
						return new Lambda1<C,D>() {
							public D apply(C cc) {
								return f.apply(aa,bb,cc);
							}
						};
					}
				};
			}
		};
		Cell<Lambda1<B, Lambda1<C, D>>> bf = a.map(ffa);
		return a.apply(apply(bf, b), c);
	}

	/**
	 * Lift a quaternary function into cells, so the returned Cell always reflects the specified
	 * function applied to the input cells' values.
	 * @param f Function to apply. It must be referentially transparent.
	 */
	public static final  Cell<E> lift(final Lambda4 f, Cell a, Cell b, Cell<C> c, Cell<D> d)
	{
		Lambda1<A, Lambda1<B, Lambda1<C, Lambda1<D,E>>>> ffa = new Lambda1<A, Lambda1<B, Lambda1<C, Lambda1<D,E>>>>() {
			public Lambda1<B, Lambda1<C, Lambda1<D,E>>> apply(final A aa) {
				return new Lambda1<B, Lambda1<C, Lambda1<D,E>>>() {
					public Lambda1<C, Lambda1<D, E>> apply(final B bb) {
						return new Lambda1<C, Lambda1<D,E>>() {
							public Lambda1<D,E> apply(final C cc) {
                                return new Lambda1<D, E>() {
                                    public E apply(D dd) {
                                        return f.apply(aa,bb,cc,dd);
                                    }
                                };
							}
						};
					}
				};
			}
		};
		Cell<Lambda1<B, Lambda1<C, Lambda1<D, E>>>> bf = a.map(ffa);
		return apply(apply(apply(bf, b), c), d);
	}

	/**
	 * Lift a 5-argument function into cells, so the returned Cell always reflects the specified
	 * function applied to the input cells' values.
	 * @param fn Function to apply. It must be referentially transparent.
	 */
	public static final  Cell<F> lift(final Lambda5 fn, Cell a, Cell b, Cell<C> c, Cell<D> d, Cell<E> e)
	{
		Lambda1<A, Lambda1<B, Lambda1<C, Lambda1<D, Lambda1<E, F>>>>> ffa = new Lambda1<A, Lambda1<B, Lambda1<C, Lambda1<D,Lambda1<E, F>>>>>() {
			public Lambda1<B, Lambda1<C, Lambda1<D, Lambda1<E, F>>>> apply(final A aa) {
				return new Lambda1<B, Lambda1<C, Lambda1<D, Lambda1<E, F>>>>() {
					public Lambda1<C, Lambda1<D, Lambda1<E, F>>> apply(final B bb) {
						return new Lambda1<C, Lambda1<D, Lambda1<E, F>>>() {
							public Lambda1<D, Lambda1<E, F>> apply(final C cc) {
                                return new Lambda1<D, Lambda1<E, F>>() {
                                    public Lambda1<E, F> apply(final D dd) {
                                        return new Lambda1<E, F>() {
                                            public F apply(E ee) {
                                                return fn.apply(aa,bb,cc,dd,ee);
                                            }
                                        };
                                    }
                                };
							}
						};
					}
				};
			}
		};
		Cell<Lambda1<B, Lambda1<C, Lambda1<D, Lambda1<E, F>>>>> bf = a.map(ffa);
		return apply(apply(apply(apply(bf, b), c), d), e);
	}

	/**
	 * Lift a 6-argument function into cells, so the returned Cell always reflects the specified
	 * function applied to the input cells' values.
	 * @param f Function to apply. It must be referentially transparent.
	 */
	public static final  Cell<G> lift(final Lambda6 fn, Cell a, Cell b, Cell<C> c, Cell<D> d, Cell<E> e, Cell<F> f)
	{
		Lambda1<A, Lambda1<B, Lambda1<C, Lambda1<D, Lambda1<E, Lambda1<F, G>>>>>> ffa = new Lambda1<A, Lambda1<B, Lambda1<C, Lambda1<D,Lambda1<E, Lambda1<F, G>>>>>>() {
			public Lambda1<B, Lambda1<C, Lambda1<D, Lambda1<E, Lambda1<F, G>>>>> apply(final A aa) {
				return new Lambda1<B, Lambda1<C, Lambda1<D, Lambda1<E, Lambda1<F, G>>>>>() {
					public Lambda1<C, Lambda1<D, Lambda1<E, Lambda1<F, G>>>> apply(final B bb) {
						return new Lambda1<C, Lambda1<D, Lambda1<E, Lambda1<F, G>>>>() {
							public Lambda1<D, Lambda1<E, Lambda1<F, G>>> apply(final C cc) {
                                return new Lambda1<D, Lambda1<E, Lambda1<F, G>>>() {
                                    public Lambda1<E, Lambda1<F, G>> apply(final D dd) {
                                        return new Lambda1<E, Lambda1<F, G>>() {
                                            public Lambda1<F, G> apply(final E ee) {
                                                return new Lambda1<F, G>() {
                                                    public G apply(final F ff) {
                                                        return fn.apply(aa,bb,cc,dd,ee,ff);
                                                    }
                                                };
                                            }
                                        };
                                    }
                                };
							}
						};
					}
				};
			}
		};
		Cell<Lambda1<B, Lambda1<C, Lambda1<D, Lambda1<E, Lambda1<F, G>>>>>> bf = a.map(ffa);
		return apply(apply(apply(apply(apply(bf, b), c), d), e), f);
	}

	/**
	 * Apply a value inside a cell to a function inside a cell. This is the
	 * primitive for all function lifting.
	 */
	public static  Cell apply(final Cell<Lambda1> bf, final Cell ba)
	{
    	return Transaction.apply(new Lambda1<Transaction, Cell>() {
    		public Cell apply(Transaction trans0) {
                final StreamWithSend out = new StreamWithSend();

                class ApplyHandler implements Handler<Transaction> {
                    ApplyHandler(Transaction trans0) {
                    }
                    Lambda1 f = null;
                    A a = null;
                    @Override
                    public void run(Transaction trans1) {
                        trans1.prioritized(out.node, new Handler<Transaction>() {
                            public void run(Transaction trans2) {
                                out.send(trans2, f.apply(a));
                            }
                        });
                    }
                }

                Node out_target = out.node;
                final Node in_target = new Node(0);
                Node.Target[] node_target_ = new Node.Target[1];
                in_target.linkTo(null, out_target, node_target_);
                final Node.Target node_target = node_target_[0];
                final ApplyHandler h = new ApplyHandler(trans0);
                Listener l1 = bf.value(trans0).listen_(in_target, new TransactionHandler<Lambda1>() {
                    public void run(Transaction trans1, Lambda1 f) {
                        h.f = f;
                        if (h.a != null)
                            h.run(trans1);
                    }
                });
                Listener l2 = ba.value(trans0).listen_(in_target, new TransactionHandler() {
                    public void run(Transaction trans1, A a) {
                        h.a = a;
                        if (h.f != null)
                            h.run(trans1);
                    }
                });
                return out.unsafeAddCleanup(l1).unsafeAddCleanup(l2).unsafeAddCleanup(
                    new Listener() {
                        public void unlisten() {
                            in_target.unlinkTo(node_target);
                        }
                    }).holdLazy(new Lazy(new Lambda0() {
                        public B apply() {
                            return bf.sampleNoTrans().apply(ba.sampleNoTrans());
                        }
                    }));
            }
        });
	}

	/**
	 * Unwrap a cell inside another cell to give a time-varying cell implementation.
	 */
	public static  Cell switchC(final Cell<Cell> bba)
	{
	    return Transaction.apply(new Lambda1<Transaction, Cell>() {
	        public Cell apply(Transaction trans0) {
                Lazy za = bba.sampleLazy().map(new Lambda1<Cell, A>() {
                    public A apply(Cell ba) {
                        return ba.sample();
                    }
                });
                final StreamWithSend out = new StreamWithSend();
                TransactionHandler<Cell> h = new TransactionHandler<Cell>() {
                    private Listener currentListener;
                    @Override
                    public void run(Transaction trans2, Cell ba) {
                        // Note: If any switch takes place during a transaction, then the
                        // value().listen will always cause a sample to be fetched from the
                        // one we just switched to. The caller will be fetching our output
                        // using value().listen, and value() throws away all firings except
                        // for the last one. Therefore, anything from the old input cell
                        // that might have happened during this transaction will be suppressed.
                        if (currentListener != null)
                            currentListener.unlisten();
                        currentListener = ba.value(trans2).listen(out.node, trans2, new TransactionHandler() {
                            public void run(Transaction trans3, A a) {
                                out.send(trans3, a);
                            }
                        }, false);
                    }

                    @Override
                    protected void finalize() throws Throwable {
                        if (currentListener != null)
                            currentListener.unlisten();
                    }
                };
                Listener l1 = bba.value(trans0).listen_(out.node, h);
                return out.unsafeAddCleanup(l1).holdLazy(za);
            }
        });
	}

	/**
	 * Unwrap a stream inside a cell to give a time-varying stream implementation.
	 */
	public static  Stream switchS(final Cell<Stream> bea)
	{
        return Transaction.apply(new Lambda1<Transaction, Stream>() {
        	public Stream apply(final Transaction trans) {
                return switchS(trans, bea);
        	}
        });
    }

	private static  Stream switchS(final Transaction trans1, final Cell<Stream> bea)
	{
        final StreamWithSend out = new StreamWithSend();
        final TransactionHandler h2 = new TransactionHandler() {
        	public void run(Transaction trans2, A a) {
	            out.send(trans2, a);
	        }
        };
        TransactionHandler<Stream> h1 = new TransactionHandler<Stream>() {
            private Listener currentListener = bea.sampleNoTrans().listen(out.node, trans1, h2, false);

            @Override
            public void run(final Transaction trans2, final Stream ea) {
                trans2.last(new Runnable() {
                	public void run() {
	                    if (currentListener != null)
	                        currentListener.unlisten();
	                    currentListener = ea.listen(out.node, trans2, h2, true);
	                }
                });
            }

            @Override
            protected void finalize() throws Throwable {
                if (currentListener != null)
                    currentListener.unlisten();
            }
        };
        Listener l1 = bea.updates(trans1).listen(out.node, trans1, h1, false);
        return out.unsafeAddCleanup(l1);
	}

	@Override
	protected void finalize() throws Throwable {
	    if (cleanup != null)
            cleanup.unlisten();
	}

	/**
	 * Listen for updates to the value of this cell. This is the observer pattern. The
	 * returned {@link Listener} has a {@link Listener#unlisten()} method to cause the
	 * listener to be removed. This is an OPERATIONAL mechanism is for interfacing between
	 * the world of I/O and for FRP.
	 * @param action The handler to execute when there's a new value.
	 *   You should make no assumptions about what thread you are called on, and the
	 *   handler should not block. You are not allowed to use {@link CellSink#send(Object)}
	 *   or {@link StreamSink#send(Object)} in the handler.
	 *   An exception will be thrown, because you are not meant to use this to create
	 *   your own primitives.
     */
	public final Listener listen(final Handler action) {
        return Transaction.apply(new Lambda1<Transaction, Listener>() {
        	public Listener apply(final Transaction trans) {
                return value(trans).listen(action);
			}
		});
	}
}


text:
package in.twizmwaz.cardinal.module.modules.regions.parsers;

import in.twizmwaz.cardinal.module.modules.regions.RegionParser;
import in.twizmwaz.cardinal.util.Numbers;
import org.bukkit.util.Vector;
import org.jdom2.Element;

public class SphereParser extends RegionParser {

    private final Vector origin;
    private double radius;

    public SphereParser(Element element) {
        super(element.getAttributeValue("name") != null ? element.getAttributeValue("name") : element.getAttributeValue("id"));
        String origin = element.getAttributeValue("origin");
        String[] origina = origin.contains(",") ? origin.split(",") : origin.trim().replaceAll(" ", ",").split(",");
        this.origin = new Vector(Numbers.parseDouble(origina[0].trim()), Numbers.parseDouble(origina[1].trim()), Numbers.parseDouble(origina[2].trim()));
        this.radius = Numbers.parseDouble(element.getAttributeValue("radius").trim());
    }

    public Vector getOrigin() {
        return origin;
    }

    public double getRadius() {
        return radius;
    }

}

redpajama_set_name: RedPajamaGithub


text:
gst::Mouse::Mouse()
    : buttons(static_cast<int>(Button::COUNT), ButtonState::UP),
      position(0, 0),
      position_delta(0, 0),
      scroll_delta(0)
{
}

void gst::Mouse::tick()
{
    for (auto i = 0u; i < buttons.size(); i++) {
        ButtonState state = buttons[i];
        if (state == ButtonState::CLICKED || state == ButtonState::DBLCLICKED) {
            buttons[i] = ButtonState::DOWN;
        } else if (state == ButtonState::RELEASED) {
            buttons[i] = ButtonState::UP;
        }
    }
    position_delta.x = 0;
    position_delta.y = 0;
    scroll_delta = 0;
}

void gst::Mouse::set_button_state(Button button, ButtonState state)
{
    buttons[static_cast<int>(button)] = state;
}

void gst::Mouse::set_position(glm::ivec2 position)
{
    this->position = position;
}

void gst::Mouse::add_position_delta(glm::ivec2 delta)
{
    position_delta += delta;
}

void gst::Mouse::add_scroll_delta(int delta)
{
    scroll_delta += delta;
}

gst::ButtonState gst::Mouse::get_button_state(Button button) const
{
    return buttons[static_cast<int>(button)];
}

glm::ivec2 gst::Mouse::get_position() const
{
    return position;
}

glm::ivec2 gst::Mouse::get_position_delta() const
{
    return position_delta;
}

int gst::Mouse::get_scroll_delta() const
{
    return scroll_delta;
}


text:
/*
 * This file is part of the swblocks-baselib library.
 *
 * 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.
 */

#ifndef __BL_TASKS_TASKSINCLUDES_H_
#define __BL_TASKS_TASKSINCLUDES_H_

/*
 * Common includes used by the reactive interfaces and generic implementation(s)
 */

#include <baselib/core/ObjModel.h>
#include <baselib/core/ObjModelDefs.h>
#include <baselib/core/OS.h>
#include <baselib/core/Uuid.h>
#include <baselib/core/Utils.h>
#include <baselib/core/ThreadPool.h>
#include <baselib/core/NetUtils.h>
#include <baselib/core/BaseIncludes.h>

#include <exception>
#include <type_traits>
#include <string>
#include <functional>

#endif /* __BL_TASKS_TASKSINCLUDES_H_ */


text:
namespace media {

class WebMStreamParser : public StreamParser {
 public:
  WebMStreamParser();
  virtual ~WebMStreamParser();

  // StreamParser implementation.
  virtual void Init(const InitCB& init_cb, StreamParserHost* host) OVERRIDE;
  virtual void Flush() OVERRIDE;
  virtual int Parse(const uint8* buf, int size) OVERRIDE;

 private:
  enum State {
    WAITING_FOR_INIT,
    PARSING_HEADERS,
    PARSING_CLUSTERS
  };

  void ChangeState(State new_state);

  // Parses WebM Header, Info, Tracks elements. It also skips other level 1
  // elements that are not used right now. Once the Info & Tracks elements have
  // been parsed, this method will transition the parser from PARSING_HEADERS to
  // PARSING_CLUSTERS.
  //
  // Returns < 0 if the parse fails.
  // Returns 0 if more data is needed.
  // Returning > 0 indicates success & the number of bytes parsed.
  int ParseInfoAndTracks(const uint8* data, int size);

  // Incrementally parses WebM cluster elements. This method also skips
  // CUES elements if they are encountered since we currently don't use the
  // data in these elements.
  //
  // Returns < 0 if the parse fails.
  // Returns 0 if more data is needed.
  // Returning > 0 indicates success & the number of bytes parsed.
  int ParseCluster(const uint8* data, int size);

  State state_;
  InitCB init_cb_;
  StreamParserHost* host_;

  scoped_ptr<WebMClusterParser> cluster_parser_;

  DISALLOW_COPY_AND_ASSIGN(WebMStreamParser);
};

}  // namespace media

#endif  // MEDIA_WEBM_WEBM_STREAM_PARSER_H_


text:
using Umbraco.Core.Compose;
using Umbraco.Core.Composing;

namespace Umbraco.Core.Logging.Viewer
{
    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    // ReSharper disable once UnusedMember.Global
    public class LogViewerComposer : ICoreComposer
    {
        public void Compose(Composition composition)
        {
            composition.SetLogViewer(_ => new JsonLogViewer(composition.Logger));
        }
    }
}


text:
OpenSpending = "OpenSpending" in window ? OpenSpending : {};

$(function() {
  var context = {
    dataset: "kosice",
    siteUrl: "http://openspending.org",
    pagesize: 50,
    callback: function(name) {
      console.log("HUHU");
    }
  };

  OpenSpending.WidgetLink = Backbone.Router.extend({
    routes: {
        "": "home",
        "*args": "drilldown"
    },

    home: function() {
      this.setFilters(this.initialFilters);
    },

    drilldown: function(args) {
      var router = this;
      var currentFilters = this.getFilters();
      router.treetable.drilldown(currentFilters, function (name, filters, drilldown) {
        var filters = _.extend({}, filters);
        filters[drilldown] = name;
        this.setFilters(filters);
      });
    },

    getFragment: function(filters) {
      return _.map(_.keys(filters), function(k) {
        return k + ':' + filters[k];
      }).join('/');
    },

    setFilters: function(filters) {
      var newFilters = $.extend({}, this.getFilters(), filters);
      this.navigate(this.getFragment(newFilters), {trigger: true});
    },

    getFilters: function() {
      var filters = {};
      _.each(Backbone.history.fragment.split('/'), function(kv) {
        var kv_ = kv.split(':', 2);
        filters[kv_[0]] = kv_[1];
      });
      return filters;
    },

    setupYearsLinks: function(yearsContainer) {
      var router = this;

      function fetchDistinct(dimension, attribute, query) {
        var dfd = $.ajax({
            url: context.siteUrl + '/' + context.dataset + '/' + dimension + '.distinct',
            data: {attribute: attribute, q: query, limit: 20},
            dataType: 'jsonp',
            cache: true,
            jsonpCallback: 'distinct_' + btoa(dimension + '__' + attribute + '__' + query).replace(/\=/g, '')
            });
        return dfd.promise();
      }

      function renderYears(years) {
        _.each(years.sort(), function (year) {
          yearsContainer.append(""+year+"");
        });
      }

      function setupYearsEvents() {
        yearsContainer.find('a').click(function () {
          var element = $(this);
          element.siblings().removeClass('disable')
          element.addClass('disable');
          router.setFilters(element.data());
          return false;
        });
      }

      return fetchDistinct("time", "year").then(function (distinct) {
        var years = _.map(distinct.results, function (result) {
          return result.year;
        });

        renderYears(years);
        setupYearsEvents();
      }).promise();
    },

    initialize: function(elem, context, filters, drilldowns) {
      this.treetable = OpenSpending.Treetable(elem, context, drilldowns);
      this.initialFilters = filters;

      var yearsContainer = $('
').insertBefore(elem);
      this.setupYearsLinks(yearsContainer).then(function () {
        yearsContainer.find(':last').click();
      });
    },
  });

  OpenSpending.app = new OpenSpending.WidgetLink($('#treetable_widget'), context, {'year': '2012'}, ['group']);
});


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class NYSUSine : MonoBehaviour {

	// Struct for our SinWave values
	private class SinWave
	{
		public float amplitude;
		public float period;
	}

	// Storage for our SinWaves
	private static Dictionary<string, SinWave> _sinWaveValues = new Dictionary<string, SinWave> ();

#region Adding/Removing Sin requestors

	public static string AddSinWaveRequestor (float amplitude, float period)
	{
		string guid = System.Guid.NewGuid ().ToString ();
		SinWave sinWave = new SinWave () {
			amplitude = amplitude,
			period = period,
		};

		_sinWaveValues.Add (guid, sinWave);
		return guid;
	}

	public static void RemoveSinWaveRequestor (string guid)
	{
		if (!_sinWaveValues.ContainsKey (guid)) {
			Debug.LogWarning (string.Format ("No key found for {0}", guid));
			return;
		}

		_sinWaveValues.Remove (guid);
	}

#endregion

#region Sin Waves

	// This is the base sinewave gauranteed to be uniform for all components
	public static float GetGlobalSinWave ()
	{
		return Mathf.Sin(Time.timeSinceLevelLoad);
	}

	public static float GetSinWave (string guid)
	{
		if (!_sinWaveValues.ContainsKey (guid)) {
			Debug.LogWarning (string.Format ("No key found for {0}", guid));
			return 0f;
		}

		float theta = Time.timeSinceLevelLoad / _sinWaveValues [guid].period;
		return _sinWaveValues [guid].amplitude * Mathf.Sin(theta);
	}

#endregion

}


text:
Overview
=============

Code app allows embedding any HTML markup.

# Installation instructions

0. Clone this repository.
1. Download and install NodeJS and npm from [http://nodejs.org](http://nodejs.org) (either from package or athe source).
2. sudo npm install grunt-cli -g
3. Run the following command in the project directory: npm install
4. Now you can use 'grunt' command to build the project

# License

Copyright 2014 Echo

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or 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.

# Demo

You can see the demo page of Echo Code app [here](http://echoappsteam.github.io/EchoHTMLEmbed/).


text:
package org.elasticsearch.action.termvectors;

import com.carrotsearch.hppc.ObjectLongHashMap;
import com.carrotsearch.hppc.cursors.ObjectLongCursor;
import org.apache.lucene.index.Fields;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.BoostAttribute;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;

import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;

import static org.apache.lucene.util.ArrayUtil.grow;

/**
 * This class represents the result of a {@link TermVectorsRequest}. It works
 * exactly like the {@link Fields} class except for one thing: It can return
 * offsets and payloads even if positions are not present. You must call
 * nextPosition() anyway to move the counter although this method only returns
 * <tt>-1,</tt>, if no positions were returned by the {@link TermVectorsRequest}.
 *

 * The data is stored in two byte arrays ({@code headerRef} and
 * {@code termVectors}, both {@link BytesRef}) that have the following format:
 *

 * {@code headerRef}: Stores offsets per field in the {@code termVectors} array
 * and some header information as {@link BytesRef}. Format is
 *

 *
String : "TV"

 *
vint: version (=-1)

 *
boolean: hasTermStatistics (are the term statistics stored?)

 *
boolean: hasFieldStatitsics (are the field statistics stored?)

 *
vint: number of fields

 *

 *

 *
String: field name 1

 *
vint: offset in {@code termVectors} for field 1

 *
...

 *
String: field name last field

 *
vint: offset in {@code termVectors} for last field

 *

 *

 *

 *

 * termVectors: Stores the actual term vectors as a {@link BytesRef}.
 *

 * Term vectors for each fields are stored in blocks, one for each field. The
 * offsets in {@code headerRef} are used to find where the block for a field
 * starts. Each block begins with a
 *

 *
vint: number of terms

 *
boolean: positions (has it positions stored?)

 *
boolean: offsets (has it offsets stored?)

 *
boolean: payloads (has it payloads stored?)

 *

 * If the field statistics were requested ({@code hasFieldStatistics} is true,
 * see {@code headerRef}), the following numbers are stored:
 *

 *
vlong: sum of total term freqencies of the field (sumTotalTermFreq)

 *
vlong: sum of document frequencies for each term (sumDocFreq)

 *
vint: number of documents in the shard that has an entry for this field
 * (docCount)

 *

 *

 * After that, for each term it stores
 *

 *
vint: term lengths

 *
BytesRef: term name

 *

 *

 * If term statistics are requested ({@code hasTermStatistics} is true, see
 * {@code headerRef}):
 *

 *
vint: document frequency, how often does this term appear in documents?

 *
vlong: total term frequency. Sum of terms in this field.

 *

 * After that
 *

 *
vint: frequency (always returned)

 *

 *

 *
vint: position_1 (if positions == true)

 *
vint: startOffset_1 (if offset == true)

 *
vint: endOffset_1 (if offset == true)

 *
BytesRef: payload_1 (if payloads == true)

 *
...

 *
vint: endOffset_freqency (if offset == true)

 *
BytesRef: payload_freqency (if payloads == true)

 *

 *

 */

public final class TermVectorsFields extends Fields {

    private final ObjectLongHashMap<String> fieldMap;
    private final BytesReference termVectors;
    final boolean hasTermStatistic;
    final boolean hasFieldStatistic;
    public final boolean hasScores;

    /**
     * @param headerRef   Stores offsets per field in the {@code termVectors} and some
     *                    header information as {@link BytesRef}.
     * @param termVectors Stores the actual term vectors as a {@link BytesRef}.
     */
    public TermVectorsFields(BytesReference headerRef, BytesReference termVectors) throws IOException {
        StreamInput header = headerRef.streamInput();
        fieldMap = new ObjectLongHashMap<>();
        // here we read the header to fill the field offset map
        String headerString = header.readString();
        assert headerString.equals("TV");
        int version = header.readInt();
        assert version == -1;
        hasTermStatistic = header.readBoolean();
        hasFieldStatistic = header.readBoolean();
        hasScores = header.readBoolean();
        final int numFields = header.readVInt();
        for (int i = 0; i < numFields; i++) {
            fieldMap.put((header.readString()), header.readVLong());
        }
        header.close();
        // reference to the term vector data
        this.termVectors = termVectors;
    }

    @Override
    public Iterator<String> iterator() {
        final Iterator<ObjectLongCursor<String>> iterator = fieldMap.iterator();
        return new Iterator<String>() {
            @Override
            public boolean hasNext() {
                return iterator.hasNext();
            }

            @Override
            public String next() {
                return iterator.next().key;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    @Override
    public Terms terms(String field) throws IOException {
        // first, find where in the termVectors bytes the actual term vector for
        // this field is stored
        final int keySlot = fieldMap.indexOf(field);
        if (keySlot < 0) {
            return null; // we don't have it.
        }
        long readOffset = fieldMap.indexGet(keySlot);
        return new TermVector(termVectors, readOffset);
    }

    @Override
    public int size() {
        return fieldMap.size();
    }

    private final class TermVector extends Terms {

        private final StreamInput perFieldTermVectorInput;
        private final long readOffset;

        private long numTerms;
        private boolean hasPositions;
        private boolean hasOffsets;
        private boolean hasPayloads;
        private long sumTotalTermFreq;
        private long sumDocFreq;
        private int docCount;

        public TermVector(BytesReference termVectors, long readOffset) throws IOException {
            this.perFieldTermVectorInput = termVectors.streamInput();
            this.readOffset = readOffset;
            reset();
        }

        private void reset() throws IOException {
            this.perFieldTermVectorInput.reset();
            this.perFieldTermVectorInput.skip(readOffset);

            // read how many terms....
            this.numTerms = perFieldTermVectorInput.readVLong();
            // ...if positions etc. were stored....
            this.hasPositions = perFieldTermVectorInput.readBoolean();
            this.hasOffsets = perFieldTermVectorInput.readBoolean();
            this.hasPayloads = perFieldTermVectorInput.readBoolean();
            // read the field statistics
            this.sumTotalTermFreq = hasFieldStatistic ? readPotentiallyNegativeVLong(perFieldTermVectorInput) : -1;
            this.sumDocFreq = hasFieldStatistic ? readPotentiallyNegativeVLong(perFieldTermVectorInput) : -1;
            this.docCount = hasFieldStatistic ? readPotentiallyNegativeVInt(perFieldTermVectorInput) : -1;
        }

        @Override
        public TermsEnum iterator() throws IOException {
            // reset before asking for an iterator
            reset();
            // convert bytes ref for the terms to actual data
            return new TermsEnum() {
                int currentTerm = 0;
                int freq = 0;
                int docFreq = -1;
                long totalTermFrequency = -1;
                int[] positions = new int[1];
                int[] startOffsets = new int[1];
                int[] endOffsets = new int[1];
                BytesRefBuilder[] payloads = new BytesRefBuilder[1];
                final BytesRefBuilder spare = new BytesRefBuilder();
                BoostAttribute boostAtt = this.attributes().addAttribute(BoostAttribute.class);

                @Override
                public BytesRef next() throws IOException {
                    if (currentTerm++ < numTerms) {
                        // term string. first the size...
                        int termVectorSize = perFieldTermVectorInput.readVInt();
                        spare.grow(termVectorSize);
                        // ...then the value.
                        perFieldTermVectorInput.readBytes(spare.bytes(), 0, termVectorSize);
                        spare.setLength(termVectorSize);
                        if (hasTermStatistic) {
                            docFreq = readPotentiallyNegativeVInt(perFieldTermVectorInput);
                            totalTermFrequency = readPotentiallyNegativeVLong(perFieldTermVectorInput);
                        }

                        freq = readPotentiallyNegativeVInt(perFieldTermVectorInput);
                        // grow the arrays to read the values. this is just
                        // for performance reasons. Re-use memory instead of
                        // realloc.
                        growBuffers();
                        // finally, read the values into the arrays
                        // currentPosition etc. so that we can just iterate
                        // later
                        writeInfos(perFieldTermVectorInput);

                        // read the score if available
                        if (hasScores) {
                            boostAtt.setBoost(perFieldTermVectorInput.readFloat());
                        }
                        return spare.get();

                    } else {
                        return null;
                    }
                }

                private void writeInfos(final StreamInput input) throws IOException {
                    for (int i = 0; i < freq; i++) {
                        if (hasPositions) {
                            positions[i] = input.readVInt();
                        }
                        if (hasOffsets) {
                            startOffsets[i] = input.readVInt();
                            endOffsets[i] = input.readVInt();
                        }
                        if (hasPayloads) {
                            int payloadLength = input.readVInt();
                            if (payloads[i] == null) {
                                payloads[i] = new BytesRefBuilder();
                            }
                            payloads[i].grow(payloadLength);
                            input.readBytes(payloads[i].bytes(), 0, payloadLength);
                            payloads[i].setLength(payloadLength);
                        }
                    }
                }

                private void growBuffers() {
                    if (hasPositions) {
                        positions = grow(positions, freq);
                    }
                    if (hasOffsets) {
                        startOffsets = grow(startOffsets, freq);
                        endOffsets = grow(endOffsets, freq);
                    }
                    if (hasPayloads) {
                        if (payloads.length < freq) {
                            payloads = Arrays.copyOf(payloads, ArrayUtil.oversize(freq, RamUsageEstimator.NUM_BYTES_OBJECT_REF));
                        }
                    }
                }

                @Override
                public SeekStatus seekCeil(BytesRef text) throws IOException {
                    throw new UnsupportedOperationException();
                }

                @Override
                public void seekExact(long ord) throws IOException {
                    throw new UnsupportedOperationException("Seek is not supported");
                }

                @Override
                public BytesRef term() throws IOException {
                    return spare.get();
                }

                @Override
                public long ord() throws IOException {
                    throw new UnsupportedOperationException("ordinals are not supported");
                }

                @Override
                public int docFreq() throws IOException {
                    return docFreq;
                }

                @Override
                public long totalTermFreq() throws IOException {
                    return totalTermFrequency;
                }

                @Override
                public PostingsEnum postings(PostingsEnum reuse, int flags) throws IOException {
                    final TermVectorPostingsEnum retVal = (reuse instanceof TermVectorPostingsEnum ? (TermVectorPostingsEnum) reuse
                            : new TermVectorPostingsEnum());
                    return retVal.reset(hasPositions ? positions : null, hasOffsets ? startOffsets : null, hasOffsets ? endOffsets
                            : null, hasPayloads ? payloads : null, freq);
                }

            };
        }

        @Override
        public long size() throws IOException {
            return numTerms;
        }

        @Override
        public long getSumTotalTermFreq() throws IOException {
            return sumTotalTermFreq;
        }

        @Override
        public long getSumDocFreq() throws IOException {
            return sumDocFreq;
        }

        @Override
        public int getDocCount() throws IOException {
            return docCount;
        }

        @Override
        public boolean hasFreqs() {
            return true;
        }

        @Override
        public boolean hasOffsets() {
            return hasOffsets;
        }

        @Override
        public boolean hasPositions() {
            return hasPositions;
        }

        @Override
        public boolean hasPayloads() {
            return hasPayloads;
        }
    }

    private final class TermVectorPostingsEnum extends PostingsEnum {
        private boolean hasPositions;
        private boolean hasOffsets;
        private boolean hasPayloads;
        int curPos = -1;
        int doc = -1;
        private int freq;
        private int[] startOffsets;
        private int[] positions;
        private BytesRefBuilder[] payloads;
        private int[] endOffsets;

        private PostingsEnum reset(int[] positions, int[] startOffsets, int[] endOffsets, BytesRefBuilder[] payloads, int freq) {
            curPos = -1;
            doc = -1;
            this.hasPositions = positions != null;
            this.hasOffsets = startOffsets != null;
            this.hasPayloads = payloads != null;
            this.freq = freq;
            this.startOffsets = startOffsets;
            this.endOffsets = endOffsets;
            this.payloads = payloads;
            this.positions = positions;
            return this;
        }

        @Override
        public int nextDoc() throws IOException {
            return doc = (doc == -1 ? 0 : NO_MORE_DOCS);
        }

        @Override
        public int docID() {
            return doc;
        }

        @Override
        public int advance(int target) throws IOException {
            while (nextDoc() < target && doc != NO_MORE_DOCS) {
            }
            return doc;
        }

        @Override
        public int freq() throws IOException {
            return freq;
        }

        // call nextPosition once before calling this one
        // because else counter is not advanced
        @Override
        public int startOffset() throws IOException {
            assert curPos < freq && curPos >= 0;
            return hasOffsets ? startOffsets[curPos] : -1;

        }

        @Override
        // can return -1 if posistions were not requested or
        // stored but offsets were stored and requested
        public int nextPosition() throws IOException {
            assert curPos + 1 < freq;
            ++curPos;
            // this is kind of cheating but if you don't need positions
            // we safe lots fo space on the wire
            return hasPositions ? positions[curPos] : -1;
        }

        @Override
        public BytesRef getPayload() throws IOException {
            assert curPos < freq && curPos >= 0;
            if (hasPayloads) {
                final BytesRefBuilder payload = payloads[curPos];
                if (payload != null) {
                    return payload.get();
                }
            }
            return null;
        }

        @Override
        public int endOffset() throws IOException {
            assert curPos < freq && curPos >= 0;
            return hasOffsets ? endOffsets[curPos] : -1;
        }

        @Override
        public long cost() {
            return 1;
        }
    }

    // read a vInt. this is used if the integer might be negative. In this case,
    // the writer writes a 0 for -1 or value +1 and accordingly we have to
    // subtract 1 again
    // adds one to mock not existing term freq
    int readPotentiallyNegativeVInt(StreamInput stream) throws IOException {
        return stream.readVInt() - 1;
    }

    // read a vLong. this is used if the integer might be negative. In this
    // case, the writer writes a 0 for -1 or value +1 and accordingly we have to
    // subtract 1 again
    // adds one to mock not existing term freq
    long readPotentiallyNegativeVLong(StreamInput stream) throws IOException {
        return stream.readVLong() - 1;
    }
}


text:
<?php

namespace Ef\AdminBundle\Controller\Solicitud;

use Admingenerated\EfAdminBundle\BaseSolicitudController\ListController as BaseListController;

/**
 * ListController
 */
class ListController extends BaseListController
{
}


text:
import chai from 'chai';
import sinonChai from 'sinon-chai';

const expect = chai.expect;

chai.use(sinonChai);

import formatNumber from '../../src/lib/formatNumber';

describe('lib: formatNumber', () => {
  it('is a function', () => {
    expect(formatNumber).to.be.a('function');
  });

  it('returns numbers greater than 100, formatted with commas', () => {
    expect(formatNumber(9001)).to.equal('9,001');
  });

  it('works with numbers with an arbitray number of commas required', () => {
    expect(formatNumber(1234567891234)).to.equal('1,234,567,891,234');
  });

  it('doesn"t add unneeded commas', () => {
    expect(formatNumber(123)).to.equal('123');
  });
});


text:
#import "CoreDAVTaskDelegate-Protocol.h"

@protocol CoreDAVDeleteTaskDelegate <CoreDAVTaskDelegate>

@optional
- (void)deleteTask:(id)arg1 completedWithError:(id)arg2;
@end


text:
`echo <text>` — print text to the stdout at a new line
`echo -e <text>` — enable interpretation of backslashes (e.g. "echo -e 'foo\nbar'")

`!!` — last command (e.g. "sudo !!")
`'` or `"` — start a multiline input (single quote)

`.. $<variable>` — inline variable (e.g. environment variables)
`.. "$<variable>"` — same, but less error-prone
`<variable>=<value>` — set a variable
`export <variable>` — set as environment variable

## Bash Shortcuts

Ctrl + C — cancel current terminal process
Ctrl + L — clear the terminal
Shift + Page Up/Down — pages of terminal (after a clearing)

Ctrl + A — start of a line
Ctrl + E — end of a line

Esc + b — one word backwards
Esc + f — one word forward

Esc + c — capitalize word
Esc + u — upper-case word
Esc + l — lower-case word

Ctrl + U — delete to the left
Ctrl + K — delete to the right
Ctrl + W — delete a word on the left
Ctrl + Y — revert deleting

Ctrl + R — search the history
Tab — autocomplete

## Streams

`` `<command>` `` — execute a command and paste it inline (e.g. "echo \`pwd\`/test")
`>` — redirect a stream to a file or another stream (1\> for stdin, 2\> for stderr)
`>>` — redirect a stream to the end of a file (e.g. "sort \<\< END" helps to pipe stdin to sort)
`|` — pipe the result of a command to the next command

`xargs <command> <arguments>` — execute a command with given arguments
`xargs -0 ..` — set 0 as delimiter (e.g. "find . -name "\*.sh" -print0 | xargs -0 rm -rf")
`xargs -n <number> ..` — split arguments by n and execute a command
`xargs sh -c '<command>; <command>;' ..` — xargs with multiple commands
`<command> | xargs <command>` — copy stdout of the first command to the arguments of the next command

## File System

`ls -a` — list ALL files
`ls -lh` — detailed human-readable list (with rights)
`ls *.jpg` — jpeg only files
`ls -1` — list representation (e.g. ls -1 | sort)

`mkdir myfolder/another/ ..` — create a folder

`pwd` — print a working directory

`du -h` — disk usage of folders

`touch <file>` — create/update a file

`mv <file/folder> <folder>` — move everything to anywhere
`mv <file> <file>` — rename a file

`cp <file> <file>` — copy and rename a file
`cp -R <folder> <folder>` — copy and rename a folder (recursive)
`cp *.txt <folder>` — copy all txt's to a folder

`rm <file>` — delete a file
`rm -rf <folder>` — force deleting a folder

`ln <file> <file>` — physical link (very low-level concept)
`ln -s <file> <file>` — just a symbolic link

## File Processing

`cat <file>` — content of a single file
`head -n <number> <file>` — just head of a single file
`tail -n <number> <file>` — just tail of a single file

`less <file>` — cat on steroids (commands: \<number\>G, g, q, arrows, page up/down)
`.. | less` — less supports flow redirection

`sort <file>` — sort lines of file alphabetically
`sort -o <file> <file>` — put the results to a file
`sort -r <file>` — sort in reverse
`sort -R <file>` — sort randomly
`sort -n <file>` — sort numbers

`wc <file>` — word count
`wc -l <file>` — lines count
`wc -n <file>` — char count
`wc -c <file>` — bytes size

`diff -rc <file/folder> <file/folder>` — diffrences with context (recursive)

`patch -i <file>.diff <file>` — apply diff to a file (need full path to .diff file)
`patch <file> < <file>.diff` — same as above, but don't need full path
`patch -d <folder> < <file>.diff` — apply diff to a whole folder
`patch -p<number> ..` — cusomize diff to it's location (typically you need -p1)

## Search in files

`find <optional folder> -name "<pattern>"` — list files which filenames suits the pattern
`find .. -type d` — only files (or "-type d" for directories)
`find .. -atime +-<time>` — find from last access
`find .. -size +-<size><M/K/G>` — find files bigger/smaller than
`find .. -print0` — set null char as a delimiter

`grep <text> <file>` — list of lines with given text in a single file
`grep -r <text> <folder>` — list of lines with given text in all folder (with filenames)
`grep -E <regex> <file>` — same, but with regex (e.g. "grep -r -E ^Alex .")
`grep -i ..` — ignore case

## Time & Sheduling

`date "+%H:%M:%S of %Y"` — format the date and print it

`at <time>` — shedule tasks (Ctrl + D to close input)
`at now +<number> <minutes/hours/days/weeks> ..` — shedule from now
`atq` — list of tasks with id's
`atrm <id>` — delete a task

`crontab -e` — modify the crontab
`crontab -l` — list the crontab
`crontab -r` — delete the crontab

`sleep <seconds>` — puts thread to sleep for a number of seconds

## Process Management

`&` — execute in the background (e.g. "cp large_file.txt folder/ &")
`jobs` — what is running in the background
`fg <id>` — put a background process to the foreground

`w` — who is logged on and what they are doing

`ps` — static process list
`ps -ef` — all static process list
`ps -uf` — only from current user
`ps -ejF` — show process hierarchy

`top` — show dynamic process list (q to quit, k to kill a process)

`kill <PID>` — kill a process

`sudo halt` — shut down the computer
`sudo reboot` — reboot the computer

## Rights

`chown <username>:<optional group> <filename>` — change the owner of a file
`chown -R ..` — change the owner of a folder (recursive)

`chmod <number> <file>` — change mode manually
`chmod <u/g/o>+-<r/w/x> <file>` — add/remove rights
`chmod -R ..` — change mode of a folder (recursive)

## Users

`sudo adduser <username>` — create a new user
`sudo paawd <username>` — change user's password
`sudo deluser <username>` — delete a user

`addgroup <group>` — create a new user group
`delgroup <group>` — delete a user group

`usermod -g <group> <username>` — add user to a group

## Compress data

`gzip <file>` — zip a file and delete it (just a compression algorithm, ONLY for files)
`gunzip <file>.gz` — unzip a file and delete an archive
`gunzip -c <file>.gz > <file>` — unzip a file without deleting archive

`tar cvf <file>.tar <file/folder>` — create an archive
`tar xvf <file>.tar` — extract an archive to a folder
`tar tf <file>.tar` — view a content of an archive
`tar xzvf <file>.tgz` = `gunzip -c <file>.tar.gz | tar xv` — extract a tgz archive
`tar xIvf <file>.tar.bz2` — extract a tar.bz2 archive

## Network

`hostname` — display hostname of the machine
`hostname -i` — display IP of the machine
`ping <ip/domain>` — ping a remote server
`ping -f <ip/domain>` — flood a remote server
`traceroute <host>` — complete route to a particular destination

`ifconfig` — get network configuration
`ifconfig -a` — same, but with disabled interfaces
`ifconfig <interface> down` — disable an interface
`ifconfig <interface> up` — enable an interface
`ifconfig <interface> <IP>` — change the IP of an interface
`ifconfig <interface> netstat <mask>` — change the subnet mask of an interface
`ifconfig <interface> broadcast <IP>` — change the broadcast adress of an interface

`netstat` — display connections, routing tables, etc.
`netstat -at` — display all TCP ports
`netstat -au` — display all UDP ports
`netstat -l` — list only listening ports
`netstat -s` — show statistics for all ports
`netstat -p` — display PID and program names
`netstat -g` — display all multicast network subscribed by this host

`nslookup <host>` — DNS lookup
`nslookup <IP>` — reverse DNS lookup

> Network is a big topic. Maybe I should move it to a separate cheatsheet.
> I'll cover nmap, natcat, telnet, wget and curl later, when I finish a course about networks and make sure I completely understand everything. *To be continued...*


text:
An AttributionControl control presents the map's attribution information.

### Props

### `compact`

- **Type:** `Boolean`
- **Default:** `true`
- **Non-Synced**
- **Description:** If true force a compact attribution
- **See:** `options.compact` in [AttributionControl](https://docs.mapbox.com/mapbox-gl-js/api/#attributioncontrol)

### `customAttribution`

- **Type:** `string, Array<string>?`
- **Default:** `true`
- **Non-Synced**
- **Description:** String or strings to show in addition to any other attributions.
- **See:** `options.customAttribution` in [AttributionControl](https://docs.mapbox.com/mapbox-gl-js/api/#attributioncontrol)

## FullscreenControl

Creates a button on the map to toggle fulscreen mode.

### Props

### `container`

- **Type:** `HTMLElement`
- **Non-Synced**
- **Description:** DOM element which should be made full screen. By default, the map container element will be made full screen.
- **See:** `options.container` in [FullscreenControl](https://docs.mapbox.com/mapbox-gl-js/api/#fullscreencontrol)

## GeolocateControl

Provides a button that uses the browser's geolocation API to locate the user on the map.

### Props

### `positionOptions`

- **Type:** `Object`
- **Default:** `{ enableHighAccuracy: false, timeout: 6000}`
- **Non-Synced**
- **Description:** A Geolocation API PositionOptions object.
- **See:** `options.positionOptions` in [GeolocateControl](https://docs.mapbox.com/mapbox-gl-js/api/#geolocatecontrol)

### `fitBoundsOptions`

- **Type:** `Object`
- **Default:** `{ maxZoom:15 }`
- **Non-Synced**
- **Description:** A fitBounds options object to use when the map is panned and zoomed to the user's location.
- **See:** `options.fitBoundsOptions` in [GeolocateControl](https://docs.mapbox.com/mapbox-gl-js/api/#geolocatecontrol)

### `trackUserLocation`

- **Type:** `Boolean`
- **Default:** `false`
- **Non-Synced**
- **Description:** If true the Geolocate Control becomes a toggle button and when active the map will receive updates to the user's location as it changes.to the user's location.
- **See:** `options.trackUserLocation` in [GeolocateControl](https://docs.mapbox.com/mapbox-gl-js/api/#geolocatecontrol)

### `showUserLocation`

- **Type:** `Boolean`
- **Default:** `true`
- **Non-Synced**
- **Description:** By default a dot will be shown on the map at the user's location. Set to false to disable.
- **See:** `options.showUserLocation` in [GeolocateControl](https://docs.mapbox.com/mapbox-gl-js/api/#geolocatecontrol)

### Methods

### `.trigger()`

- **Description:** Trigger a geolocation
- **Returns:** `boolean`
- **See:** [trigger](https://docs.mapbox.com/mapbox-gl-js/api/#geolocatecontrol#trigger) GeolocateControl method

## NavigationControl

### Props

### `showCompass`

- **Type:** `Boolean`
- **Default:** `true`
- **Non-Synced**
- **Description:** If true the compass button is included.
- **See:** `options.showCompass` in [NavigationControl](https://docs.mapbox.com/mapbox-gl-js/api/#navigationcontrol)

### `showZoom`

- **Type:** `Boolean`
- **Default:** `true`
- **Non-Synced**
- **Description:** If true the zoom-in and zoom-out buttons are included.
- **See:** `options.showZoom` in [NavigationControl](https://docs.mapbox.com/mapbox-gl-js/api/#navigationcontrol)

## ScaleControl

### Props

### `maxWidth`

- **Type:** `Number`
- **Default:** `100`
- **Non-Synced**
- **Description:** The maximum length of the scale control in pixels.
- **See:** `options.maxWidth` in [ScaleControl](https://docs.mapbox.com/mapbox-gl-js/api/#scalecontrol)

### `unit`

- **Type:** `String, "imperial" | "metric" | "nautical"`
- **Default:** `metric`
- **Non-Synced**
- **Description:** Unit of the distance
- **See:** `options.unit` in [ScaleControl](https://docs.mapbox.com/mapbox-gl-js/api/#scalecontrol)


text: Graph {{$index + 1}}


text:
"""
Set up the bot for execution.
"""
from rhobot.application import Application
from move_bot.components.commands import load_commands
from move_bot.components import load_components

application = Application()

# Register all of the components that are defined in this application.
application.pre_init(load_commands)
application.pre_init(load_components)

@application.post_init
def register_plugins(bot):
    # Components
    bot.register_plugin('update_service')

    # Commands
    bot.register_plugin('configure_client_details')
    bot.register_plugin('configure_access_token')
    bot.register_plugin('fetch_from_month')


text:
Cells
------

Cancer cells are represented by the Cell class, each cell has a CellType

CellType Class
^^^^^^^^^^^^^^

.. autoclass:: code.cells.CellType
        :members:

Cell Class
^^^^^^^^^^

.. autoclass:: code.cells.Cell
        :members:

GhostCell Class
^^^^^^^^^^^^^^^

.. autoclass:: code.cells.GhostCell
        :members: update


text:
@interface ColoredPointAnnotation : MKPointAnnotation
@property (nonatomic, strong) UIColor *pinTintColor;
@end


text:
<component name="libraryTable">
  <library name="gradle-wrapper32">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/Lesson12-Visual-Polish/T12.03-Solution-TabletLayout/gradle/wrapper/gradle-wrapper.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
package com.mygdx.sharkbait.entities;

import java.io.Serializable;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.mygdx.sharkbait.utils.Assets;
import com.mygdx.sharkbait.utils.Position;

/** Player sprite. */
public class Player extends TileSprite implements Serializable {
    private static final long serialVersionUID = 1;

    public static final int Z_INDEX = 5;

    public static final int IDLE = 0;
    public static final int DODGING = 1;
    public static final int MOVING = 2;

    private static final int UP = 0;
    private static final int DOWN = 1;
    private static final int LEFT = 2;
    private static final int RIGHT = 3;

    /** The length in seconds of the invincibility period after death. */
    private static final float INVINCIBILITY_DURATION = 7;

    private Position prev;
    private int state;
    private int direction;
    private int flickerCounter;
    private float speed;
    private float invincibilityTimer;
    private boolean mirror;
    private boolean invincible;
    private boolean transparent;

    /** Creates a player with the specified starting position. */
    public Player(Position position) {
        super(position);
        prev = position;
        speed = 1;
        zIndex = Z_INDEX;
    }

    /**
     * Moves the player to the specified position. The caller is responsible for
     * ensuring that the new position is adjacent to the old one.
     */
    public void move(Position next) {
        adjustDirection(next);
        prev = position;
        position = next;
        stateTime = 0;
        state = MOVING;
    }

    /** Makes the player dodge an attack. Does not change the player's position. */
    public void dodge() {
        stateTime = 0;
        state = DODGING;
    }

    /**
     * Called when the player gets attacked. Temporarily makes the player
     * invincible.
     */
    public void hit() {
        if (!invincible) {
            invincible = true;
            invincibilityTimer = INVINCIBILITY_DURATION;
        }
    }

    /**
     * Sets the multiplier for the player's movement speed across rocks.
     * Does not affect dodging.
     */
    public void setSpeed(float speed) {
        this.speed = speed;
    }

    /** Returns the player's movement speed multiplier. */
    public float getSpeed() {
        return speed;
    }

    /** Returns true if invincibility is in effect. */
    public boolean isInvincible() {
        return invincible;
    }

    /**
     * Returns the player's state.
     *
     * @return one of the following states: IDLE, DODGING, MOVING
     */
    public int getState() {
        return state;
    }

    /** Resets stats and removes abnormal statuses. */
    public void restore() {
        speed = 1;
        invincible = false;
        transparent = false;
    }

    @Override
    public void draw(Batch batch, float tileWidth) {
        switch (state) {
        case IDLE:
            keyFrame = Assets.player;
            break;
        case DODGING:
            keyFrame = Assets.playerDodge.getKeyFrame(stateTime);
            break;
        case MOVING:
            keyFrame = Assets.playerMove.getKeyFrame(stateTime * speed);
            break;
        }

        if (mirror) {
            keyFrame = new TextureRegion(keyFrame);
            keyFrame.flip(true, false);
        }

        if (transparent) {
            Color c = batch.getColor();
            batch.setColor(c.r, c.g, c.b, 0.2f);
            super.draw(batch, tileWidth);
            batch.setColor(c);
        } else {
            super.draw(batch, tileWidth);
        }
    }

    @Override
    public void update(float delta) {
        super.update(delta);

        if (invincible) {
            invincibilityTimer -= delta;
            transparent = (++flickerCounter & 2) == 0;
            if (invincibilityTimer <= 0) {
                invincible = false;
                transparent = false;
            }
        }

        switch (state) {
        case DODGING:
            if (Assets.playerDodge.isAnimationFinished(stateTime)) {
                state = IDLE;
            }
            break;
        case MOVING:
            if (Assets.playerMove.isAnimationFinished(stateTime * speed)) {
                state = IDLE;
                draw.set(position.x, position.y);
                break;
            }
            float distance = stateTime * speed / Assets.playerMove.animationDuration;
            switch (direction) {
            case UP:
                draw.y = prev.y - distance;
                break;
            case DOWN:
                draw.y = prev.y + distance;
                break;
            case LEFT:
                draw.x = prev.x - distance;
                break;
            case RIGHT:
                draw.x = prev.x + distance;
                break;
            }
            break;
        }
    }

    /** Sets the player's direction and orientation based on his next move. */
    private void adjustDirection(Position next) {
        if (next.y < position.y) {
            direction = UP;
        } else if (next.y > position.y) {
            direction = DOWN;
        } else if (next.x < position.x) {
            direction = LEFT;
            if (!mirror) {
                mirror = true;
            }
        } else if (next.x > position.x) {
            direction = RIGHT;
            if (mirror) {
                mirror = false;
            }
        }
    }
}


text:
package io.github.jeddict.db.accessor;

import org.eclipse.persistence.internal.jpa.metadata.columns.AttributeOverrideMetadata;
import io.github.jeddict.jpa.spec.AttributeOverride;

/**
 *
 * @author Gaurav Gupta
 */
public class AttributeOverrideSpecMetadata extends AttributeOverrideMetadata {

    private AttributeOverrideSpecMetadata() {
    }

    public static AttributeOverrideSpecMetadata getInstance(AttributeOverride attributeOverride) {
        AttributeOverrideSpecMetadata accessor = new AttributeOverrideSpecMetadata();
        accessor.setName(attributeOverride.getName());
        if (attributeOverride.getColumn() != null) {
            accessor.setColumn(attributeOverride.getColumn().getAccessor());
        }
        return accessor;
    }

}


text:
<?php

/**
 * Test theme model
 */
namespace Magento\Core\Model;

use Magento\Framework\View\Design\ThemeInterface;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\View\Design\Theme\Image\PathInterface;

class ThemeTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Core\Model\Theme|PHPUnit_Framework_MockObject_MockObject
     */
    protected $_model;

    /**
     * @var \PHPUnit_Framework_MockObject_MockObject
     */
    protected $_imageFactory;

    protected function setUp()
    {
        $customizationConfig = $this->getMock('Magento\Theme\Model\Config\Customization', [], [], '', false);
        $customizationFactory = $this->getMock(
            'Magento\Framework\View\Design\Theme\CustomizationFactory',
            ['create'],
            [],
            '',
            false
        );
        $resourceCollection = $this->getMock(
            'Magento\Core\Model\Resource\Theme\Collection',
            [],
            [],
            '',
            false
        );
        $this->_imageFactory = $this->getMock(
            'Magento\Framework\View\Design\Theme\ImageFactory',
            ['create'],
            [],
            '',
            false
        );

        $objectManagerHelper = new \Magento\TestFramework\Helper\ObjectManager($this);
        $arguments = $objectManagerHelper->getConstructArguments(
            'Magento\Core\Model\Theme',
            [
                'customizationFactory' => $customizationFactory,
                'customizationConfig' => $customizationConfig,
                'imageFactory' => $this->_imageFactory,
                'resourceCollection' => $resourceCollection,
            ]
        );

        $this->_model = $objectManagerHelper->getObject('Magento\Core\Model\Theme', $arguments);
    }

    protected function tearDown()
    {
        $this->_model = null;
    }

    /**
     * @covers \Magento\Core\Model\Theme::getThemeImage
     */
    public function testThemeImageGetter()
    {
        $this->_imageFactory->expects($this->once())->method('create')->with(['theme' => $this->_model]);
        $this->_model->getThemeImage();
    }

    /**
     * @dataProvider isVirtualDataProvider
     * @param int $type
     * @param string $isVirtual
     * @covers \Magento\Core\Model\Theme::isVirtual
     */
    public function testIsVirtual($type, $isVirtual)
    {
        /** @var $themeModel \Magento\Core\Model\Theme */
        $themeModel = $this->getMock('Magento\Core\Model\Theme', ['__wakeup'], [], '', false);
        $themeModel->setType($type);
        $this->assertEquals($isVirtual, $themeModel->isVirtual());
    }

    /**
     * @return array
     */
    public function isVirtualDataProvider()
    {
        return [
            ['type' => ThemeInterface::TYPE_VIRTUAL, 'isVirtual' => true],
            ['type' => ThemeInterface::TYPE_STAGING, 'isVirtual' => false],
            ['type' => ThemeInterface::TYPE_PHYSICAL, 'isVirtual' => false]
        ];
    }

    /**
     * @dataProvider isPhysicalDataProvider
     * @param int $type
     * @param string $isPhysical
     * @covers \Magento\Core\Model\Theme::isPhysical
     */
    public function testIsPhysical($type, $isPhysical)
    {
        /** @var $themeModel \Magento\Core\Model\Theme */
        $themeModel = $this->getMock('Magento\Core\Model\Theme', ['__wakeup'], [], '', false);
        $themeModel->setType($type);
        $this->assertEquals($isPhysical, $themeModel->isPhysical());
    }

    /**
     * @return array
     */
    public function isPhysicalDataProvider()
    {
        return [
            ['type' => ThemeInterface::TYPE_VIRTUAL, 'isPhysical' => false],
            ['type' => ThemeInterface::TYPE_STAGING, 'isPhysical' => false],
            ['type' => ThemeInterface::TYPE_PHYSICAL, 'isPhysical' => true]
        ];
    }

    /**
     * @dataProvider isVisibleDataProvider
     * @param int $type
     * @param string $isVisible
     * @covers \Magento\Core\Model\Theme::isVisible
     */
    public function testIsVisible($type, $isVisible)
    {
        /** @var $themeModel \Magento\Core\Model\Theme */
        $themeModel = $this->getMock('Magento\Core\Model\Theme', ['__wakeup'], [], '', false);
        $themeModel->setType($type);
        $this->assertEquals($isVisible, $themeModel->isVisible());
    }

    /**
     * @return array
     */
    public function isVisibleDataProvider()
    {
        return [
            ['type' => ThemeInterface::TYPE_VIRTUAL, 'isVisible' => true],
            ['type' => ThemeInterface::TYPE_STAGING, 'isVisible' => false],
            ['type' => ThemeInterface::TYPE_PHYSICAL, 'isVisible' => true]
        ];
    }

    /**
     * Test id deletable
     *
     * @dataProvider isDeletableDataProvider
     * @param string $themeType
     * @param bool $isDeletable
     * @covers \Magento\Core\Model\Theme::isDeletable
     */
    public function testIsDeletable($themeType, $isDeletable)
    {
        /** @var $themeModel \Magento\Core\Model\Theme */
        $themeModel = $this->getMock('Magento\Core\Model\Theme', ['getType', '__wakeup'], [], '', false);
        $themeModel->expects($this->once())->method('getType')->will($this->returnValue($themeType));
        $this->assertEquals($isDeletable, $themeModel->isDeletable());
    }

    /**
     * @return array
     */
    public function isDeletableDataProvider()
    {
        return [
            [ThemeInterface::TYPE_VIRTUAL, true],
            [ThemeInterface::TYPE_STAGING, true],
            [ThemeInterface::TYPE_PHYSICAL, false]
        ];
    }

    /**
     * @param mixed $originalCode
     * @param string $expectedCode
     * @dataProvider getCodeDataProvider
     */
    public function testGetCode($originalCode, $expectedCode)
    {
        $this->_model->setCode($originalCode);
        $this->assertSame($expectedCode, $this->_model->getCode());
    }

    /**
     * @return array
     */
    public function getCodeDataProvider()
    {
        return [
            'string code' => ['theme/code', 'theme/code'],
            'null code' => [null, ''],
            'number code' => [10, '10']
        ];
    }
}


text:
Basic Example

  <md-radio-button name="group1">Option 1</md-radio-button>
  <md-radio-button name="group1">Option 2</md-radio-button>
  <md-radio-button name="group1" disabled="true">Option 3 (disabled)</md-radio-button>

Dynamic Example

    isDisabled: {{isDisabled}}
    <button md-raised-button (click)="isDisabled=!isDisabled" class="demo-button">
      Disable buttons
    </button>

    <md-checkbox [(ngModel)]="isAlignEnd">Align end</md-checkbox>

  <md-radio-group name="my_options" [disabled]="isDisabled" [align]="isAlignEnd ? 'end' : 'start'">
    <md-radio-button value="option_1">Option 1</md-radio-button>
    <md-radio-button value="option_2">Option 2</md-radio-button>
    <md-radio-button value="option_3">Option 3</md-radio-button>
  </md-radio-group>

Favorite Season Example

Dynamic Example with two-way data-binding

  <md-radio-group name="more_options" [(ngModel)]="favoriteSeason">
    <md-radio-button *ngFor="let season of seasonOptions" name="more_options" [value]="season">
      {{season}}
    </md-radio-button>
  </md-radio-group>

Your favorite season is: {{favoriteSeason}}


text:
import PosterImage from '../../src/js/poster-image.js';
import * as browser from '../../src/js/utils/browser.js';
import TestHelpers from './test-helpers.js';
import document from 'global/document';

q.module('PosterImage', {
  'setup': function(){
    // Store the original background support so we can test different vals
    this.origVal = browser.BACKGROUND_SIZE_SUPPORTED;
    this.poster1 = '#poster1';
    this.poster2 = '#poster2';

    // Create a mock player object that responds as a player would
    this.mockPlayer = {
      poster_: this.poster1,
      poster: function(){
        return this.poster_;
      },
      handler_: null,
      on: function(type, handler){
        this.handler_ = handler;
      },
      trigger: function(type){
        this.handler_.call();
      }
    };
  },
  'teardown': function(){
    browser.BACKGROUND_SIZE_SUPPORTED = this.origVal;
  }
});

test('should create and update a poster image', function(){
  browser.BACKGROUND_SIZE_SUPPORTED = true;

  let posterImage = new PosterImage(this.mockPlayer);
  let backgroundImage = posterImage.el().style.backgroundImage;
  notEqual(backgroundImage.indexOf(this.poster1), -1, 'Background image used');

  // Update with a new poster source and check the new value
  this.mockPlayer.poster_ = this.poster2;
  this.mockPlayer.trigger('posterchange');
  backgroundImage = posterImage.el().style.backgroundImage;
  notEqual(backgroundImage.indexOf(this.poster2), -1, 'Background image updated');
});

test('should create and update a fallback image in older browsers', function(){
  browser.BACKGROUND_SIZE_SUPPORTED = false;

  let posterImage = new PosterImage(this.mockPlayer);
  notEqual(posterImage.fallbackImg_.src.indexOf(this.poster1), -1, 'Fallback image created');

  // Update with a new poster source and check the new value
  this.mockPlayer.poster_ = this.poster2;
  this.mockPlayer.trigger('posterchange');
  notEqual(posterImage.fallbackImg_.src.indexOf(this.poster2), -1, 'Fallback image updated');
});

test('should remove itself from the document flow when there is no poster', function(){
  let posterImage = new PosterImage(this.mockPlayer);
  equal(posterImage.el().style.display, '', 'Poster image shows by default');

  // Update with an empty string
  this.mockPlayer.poster_ = '';
  this.mockPlayer.trigger('posterchange');
  equal(posterImage.hasClass('vjs-hidden'), true, 'Poster image hides with an empty source');

  // Updated with a valid source
  this.mockPlayer.poster_ = this.poster2;
  this.mockPlayer.trigger('posterchange');
  equal(posterImage.hasClass('vjs-hidden'), false, 'Poster image shows again when there is a source');
});

test('should hide the poster in the appropriate player states', function(){
  var posterImage = new PosterImage(this.mockPlayer);
  var playerDiv = document.createElement('div');
  var fixture = document.getElementById('qunit-fixture');
  var el = posterImage.el();

  // Remove the source so when we add to the DOM it doesn't throw an error
  // We want to poster to still think it has a real source so it doesn't hide itself
  posterImage.setSrc('');

  // Add the elements to the DOM so styles are computed
  playerDiv.appendChild(el);
  fixture.appendChild(playerDiv);

  playerDiv.className = 'video-js vjs-has-started';
  equal(TestHelpers.getComputedStyle(el, 'display'), 'none', 'The poster hides when the video has started (CSS may not be loaded)');

  playerDiv.className = 'video-js vjs-has-started vjs-audio';
  equal(TestHelpers.getComputedStyle(el, 'display'), 'block', 'The poster continues to show when playing audio');
});


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/**
 * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-5-b-119.js
 * @description Object.defineProperties - 'value' property of 'descObj' is inherited accessor property (8.10.5 step 5.a)
 */

function testcase() {
        var obj = {};

        var proto = {};

        Object.defineProperty(proto, "value", {
            get: function () {
                return "inheritedAccessorProperty";
            }
        });

        var Con = function () { };
        Con.prototype = proto;

        var descObj = new Con();

        Object.defineProperties(obj, {
            property: descObj
        });

        return obj.property === "inheritedAccessorProperty";

    }
runTestCase(testcase);


text:
package org.gwtnode.core.node.http;

import org.gwtnode.core.meta.GwtNodeObject;
import org.gwtnode.core.node.event.EventEmitter;
import org.gwtnode.core.node.event.ParameterlessEventHandler;

import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString;

/**
 * @author Chad Retz
 */
@GwtNodeObject
public class Agent extends EventEmitter {

    protected Agent() {
    }

    public final void onUpgrade(ServerUpgradeEventHandler handler) {
        on("upgrade", handler);
    }

    public final void onContinue(ParameterlessEventHandler handler) {
        on("continue", handler);
    }

    public final native int maxSockets() /*-{
        return this.maxSockets;
    }-*/;

    public final native void maxSockets(int maxSockets) /*-{
        this.maxSockets = maxSockets;
    }-*/;

    public final native JsArrayString sockets() /*-{
        return this.sockets;
    }-*/;

    public final native JsArray<ClientRequest> requests() /*-{
        return this.requests;
    }-*/;
}


text:
<?php
namespace ItemRest\Model;

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class Item implements InputFilterAwareInterface {
	public $id;
	public $name;
	public $amount;

	protected $inputFilter;

	public function exchangeArray($data) {
		$this->id     = (!empty($data['id']))     ? $data['id']     : null;
		$this->name   = (!empty($data['name']))   ? $data['name']   : null;
		$this->amount = (!empty($data['amount'])) ? $data['amount'] : null;
	}

	public function setInputFilter(InputFilterInterface $inputFilter) {
		throw new \Exception("Not used");
	}

	public function getInputFilter() {
		if (!$this->inputFilter) {
			$inputFilter = new InputFilter();

			$inputFilter->add([
				'name'     => 'id',
				'required' => false,
				'filters'  => [
					['name' => 'Int'],
				],
			]);

			$inputFilter->add([
				'name'     => 'name',
				'required' => true,
				'filters'  => [
					['name' => 'StripTags'],
					['name' => 'StringTrim'],
				],
				'validators' => [[
					'name'    => 'StringLength',
					'options' => [
						'encoding' => 'UTF-8',
						'min'      => 1,
						'max'      => 255,
					]
				]],
			]);

			$inputFilter->add([
				'name'     => 'amount',
				'required' => true,
                                'filters'  => [
                                        ['name' => 'Int'],
                                ],
			]);

			$this->inputFilter = $inputFilter;
		}

		return $this->inputFilter;
	}
}


text:
<?php namespace Larbac\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Request;
use Larbac\Models\Role;
use Larbac\Models\User;

/**
 * Description of UserController
 *
 * @author Alexander Pechkarev <alexpechkarev@gmail.com>
 */
class UserController extends Controller{

    /**
     * Class constructor
     */
    public function __construct() {

      // Setting role based access
      $permissions = ['role'=>[config('larbac.role')]  ];

      if( is_object(Request::route()) ) {

          Request::route()->setParameter('larbac', $permissions);
          $this->middleware('larbac');
      }

    }
    /***/

    /**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
            $users = User::select('id', 'name')
                            ->with(array('roles'=>function($query){
                                    $query->select('name');
                                }))
                            ->get();

            return view('larbac::users.view-user', compact("users"));
	}
        /***/

	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{

            $user = User::with('roles')->findOrFail($id);
            $data = array(
                "id"            =>  $user->id,
                "name"          =>  $user->name,
                "availRoles"    =>  Role::select('id', 'name')->orderBy('name')->lists('name', 'id'),
                "assignedRoles" =>  (count($user->roles) > 0) ? $user->roles->lists('id') :0
            );
            return view('larbac::users.edit-user', $data);
	}
        /***/

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{

            // find user
            $user = User::with('roles')->findOrFail($id);
            // get roles
            $roles = is_array(Request::get('roles')) ? Request::get('roles') : [];
            // asign roles
            $user->roles()->sync($roles);

            return redirect(route(config('larbac.routes.routeUser').'.index'));

	}
        /***/

}