text:
{-# LANGUAGE CPP #-}

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ConstraintKinds #-}

{-# LANGUAGE TypeOperators #-}

-- These warnings can be inaccurate, because of conditional compilation.
#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
{-# OPTIONS_GHC -Wno-unused-imports #-}
#else
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
#endif

-- | __WARNING:__ This module is an experiment to see how 'Alternative' may be encoded.
--   The authors are not aware of any generalized applicatives that make use of 'Alternative'.
--   Hence, we do not know if this encoding of it is sufficient.
--   Therefore, the encoding is not in its final form and may change in the future.
module Control.Super.Monad.Alternative
  ( AlternativeEmpty(..)
  , AlternativeAlt(..)
  ) where

import qualified Prelude as P
import qualified Control.Applicative as A

import GHC.Exts ( Constraint )

import qualified GHC.Conc as STM
--import qualified Control.Arrow as Arrow
--import qualified Control.Applicative as Applic
import qualified Data.Monoid as Mon
import qualified Text.ParserCombinators.ReadP as ReadP
import qualified Text.ParserCombinators.ReadPrec as ReadPrec
#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
import qualified GHC.Generics as Generics
import qualified Data.Semigroup as Semigroup
import qualified Data.Proxy as Proxy
import qualified Data.Functor.Product as Product ( Product(..) )
import qualified Data.Functor.Compose as Compose ( Compose(..) )
#endif

import Control.Super.Monad.Prelude
  ( ($), Applicative(..), Functor(..) )
-- Import of 'Functor' required for GHC 8+ instances.

-- | The encoding of the 'empty' operation.
--
--   'Return' is not a superclass, because the indices or constraints involved
--   in an 'AlternativeEmpty' instance may differ from those involved with the 'Return'
--   instance.
--
--   __WARNING:__ This module is an experiment to see how 'Alternative' may be encoded.
--   The authors are not aware of any generalized applicatives that make use of 'Alternative'.
--   Hence, we do not know if this encoding of it is sufficient.
--   Therefore, the encoding is not in its final form and may change in the future.
class (Functor f) => AlternativeEmpty f where
  type AlternativeEmptyCts f :: Constraint
  type AlternativeEmptyCts f = ()
  empty :: AlternativeEmptyCts f => f a

instance AlternativeEmpty [] where
  empty = A.empty
instance AlternativeEmpty P.Maybe where
  empty = A.empty
#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
instance AlternativeEmpty P.IO where
  empty = A.empty
#endif
instance AlternativeEmpty ReadP.ReadP where
  empty = A.empty
instance AlternativeEmpty ReadPrec.ReadPrec where
  empty = A.empty
instance AlternativeEmpty STM.STM where
  empty = A.empty
#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
instance AlternativeEmpty Semigroup.Option where
  empty = A.empty
instance AlternativeEmpty Proxy.Proxy where
  empty = A.empty
#endif
instance (AlternativeEmpty f) => AlternativeEmpty (Mon.Alt f) where
  type AlternativeEmptyCts (Mon.Alt f) = AlternativeEmptyCts f
  empty = Mon.Alt $ empty

#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
instance (AlternativeEmpty f, AlternativeEmpty f') => AlternativeEmpty (Product.Product f f') where
  type AlternativeEmptyCts (Product.Product f f') = (AlternativeEmptyCts f, AlternativeEmptyCts f')
  empty = Product.Pair empty empty

instance (AlternativeEmpty f, AlternativeEmpty f') => AlternativeEmpty (Compose.Compose f f') where
  type AlternativeEmptyCts (Compose.Compose f f') = (AlternativeEmptyCts f, AlternativeEmptyCts f')
  empty = Compose.Compose $ empty
#endif

-- TODO: ArrowMonad and WrappedMonad instances. These lead to cyclic dependencies.

#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
instance AlternativeEmpty Generics.U1 where
  empty = A.empty
instance AlternativeEmpty f => AlternativeEmpty (Generics.Rec1 f) where
  type AlternativeEmptyCts (Generics.Rec1 f) = AlternativeEmptyCts f
  empty = Generics.Rec1 empty
instance (AlternativeEmpty f, AlternativeEmpty g) => AlternativeEmpty (f Generics.:*: g) where
  type AlternativeEmptyCts (f Generics.:*: g) = (AlternativeEmptyCts f, AlternativeEmptyCts g)
  empty = empty Generics.:*: empty
instance (AlternativeEmpty f, AlternativeEmpty g) => AlternativeEmpty (f Generics.:.: g) where
  type AlternativeEmptyCts (f Generics.:.: g) = (AlternativeEmptyCts f, AlternativeEmptyCts g)
  empty = Generics.Comp1 $ empty
instance AlternativeEmpty f => AlternativeEmpty (Generics.M1 i c f) where
  type AlternativeEmptyCts (Generics.M1 i c f) = AlternativeEmptyCts f
  empty = Generics.M1 $ empty
#endif

-- | The encoding of the '<|>' operation.
--
--   'Applicative' is not a superclass, because the indices or constraints involved
--   in an 'Alternative' instance may differ from those involved with the 'Applicative'
--   instance.
--
--   __WARNING:__ This module is an experiment to see how 'Alternative' may be encoded.
--   The authors are not aware of any generalized applicatives that make use of 'Alternative'.
--   Hence, we do not know if this encoding of it is sufficient.
--   Therefore, the encoding is not in its final form and may change in the future.
class (Functor f, Functor g, Functor h) => AlternativeAlt f g h where
  type AlternativeAltCts f g h :: Constraint
  type AlternativeAltCts f g h = ()
  (<|>) :: AlternativeAltCts f g h => f a -> g a -> h a

instance AlternativeAlt [] [] [] where
  (<|>) = (A.<|>)
instance AlternativeAlt P.Maybe P.Maybe P.Maybe where
  (<|>) = (A.<|>)
#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
instance AlternativeAlt P.IO P.IO P.IO where
  (<|>) = (A.<|>)
#endif
instance AlternativeAlt ReadP.ReadP ReadP.ReadP ReadP.ReadP where
  (<|>) = (A.<|>)
instance AlternativeAlt ReadPrec.ReadPrec ReadPrec.ReadPrec ReadPrec.ReadPrec where
  (<|>) = (A.<|>)
instance AlternativeAlt STM.STM STM.STM STM.STM where
  (<|>) = (A.<|>)
#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
instance AlternativeAlt Semigroup.Option Semigroup.Option Semigroup.Option where
  (<|>) = (A.<|>)
instance AlternativeAlt Proxy.Proxy Proxy.Proxy Proxy.Proxy where
  (<|>) = (A.<|>)
#endif
instance (AlternativeAlt f g h) => AlternativeAlt (Mon.Alt f) (Mon.Alt g) (Mon.Alt h) where
  type AlternativeAltCts (Mon.Alt f) (Mon.Alt g) (Mon.Alt h) = AlternativeAltCts f g h
  (Mon.Alt ma) <|> (Mon.Alt na) = Mon.Alt $ ma <|> na

#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
instance (AlternativeAlt f g h, AlternativeAlt f' g' h') => AlternativeAlt (Product.Product f f') (Product.Product g g') (Product.Product h h') where
  type AlternativeAltCts (Product.Product f f') (Product.Product g g') (Product.Product h h') = (AlternativeAltCts f g h, AlternativeAltCts f' g' h')
  Product.Pair m1 m2 <|> Product.Pair n1 n2 = Product.Pair (m1 <|> n1) (m2 <|> n2)

-- TODO: This does the application of '<|>' on the inner type constructors, whereas the original
-- implementation for the standard classes applies '<|>' on the outer type constructors.
instance (Applicative f g h, AlternativeAlt f' g' h') => AlternativeAlt (Compose.Compose f f') (Compose.Compose g g') (Compose.Compose h h') where
  type AlternativeAltCts (Compose.Compose f f') (Compose.Compose g g') (Compose.Compose h h') = (ApplicativeCts f g h, AlternativeAltCts f' g' h')
  (Compose.Compose f) <|> (Compose.Compose g) = Compose.Compose $ fmap (<|>) f <*> g
#endif

-- TODO: ArrowMonad and WrappedMonad instances. These lead to cyclic dependencies.

#if MIN_VERSION_GLASGOW_HASKELL(8,0,0,0)
instance AlternativeAlt Generics.U1 Generics.U1 Generics.U1 where
  (<|>) = (A.<|>)
instance AlternativeAlt f g h => AlternativeAlt (Generics.Rec1 f) (Generics.Rec1 g) (Generics.Rec1 h) where
  type AlternativeAltCts (Generics.Rec1 f) (Generics.Rec1 g) (Generics.Rec1 h) = AlternativeAltCts f g h
  (Generics.Rec1 f) <|> (Generics.Rec1 g) = Generics.Rec1 $ f <|> g
instance (AlternativeAlt f g h, AlternativeAlt f' g' h') => AlternativeAlt (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') where
  type AlternativeAltCts (f Generics.:*: f') (g Generics.:*: g') (h Generics.:*: h') = (AlternativeAltCts f g h, AlternativeAltCts f' g' h')
  (f Generics.:*: g) <|> (f' Generics.:*: g') = (f <|> f') Generics.:*: (g <|> g')
-- TODO: This does the application of '<|>' on the inner type constructors, whereas the original
-- implementation for the standard classes applies '<|>' on the outer type constructors.
instance (Applicative f g h, AlternativeAlt f' g' h') => AlternativeAlt (f Generics.:.: f') (g Generics.:.: g') (h Generics.:.: h') where
  type AlternativeAltCts (f Generics.:.: f') (g Generics.:.: g') (h Generics.:.: h') = (ApplicativeCts f g h, AlternativeAltCts f' g' h')
  (Generics.Comp1 f) <|> (Generics.Comp1 g) = Generics.Comp1 $ fmap (<|>) f <*> g
instance AlternativeAlt f g h => AlternativeAlt (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h)  where
  type AlternativeAltCts (Generics.M1 i c f) (Generics.M1 i c g) (Generics.M1 i c h) = AlternativeAltCts f g h
  (Generics.M1 f) <|> (Generics.M1 g) = Generics.M1 $ f <|> g
#endif


text:
use queue::QueueType;

/// General capability, supporting graphics, compute and transfer operations.
pub enum General {}
/// Graphics capability, supporting graphics and transfer operations.
pub enum Graphics {}
/// Compute capability, supporting compute and transfer operations.
pub enum Compute {}
/// Transfer capability, supporting only transfer operations.
pub enum Transfer {}

///
pub trait Capability {
    /// Return true if this type level capability is supported by
    /// a run-time queue type.
    fn supported_by(QueueType) -> bool;
}
impl Capability for General {
    fn supported_by(qt: QueueType) -> bool {
        match qt {
            QueueType::General => true,
            _ => false,
        }
    }
}
impl Capability for Graphics {
    fn supported_by(qt: QueueType) -> bool {
        match qt {
            QueueType::General |
            QueueType::Graphics => true,
            _ => false,
        }
    }
}
impl Capability for Compute {
    fn supported_by(qt: QueueType) -> bool {
        match qt {
            QueueType::General |
            QueueType::Compute => true,
            _ => false,
        }
    }
}
impl Capability for Transfer {
    fn supported_by(qt: QueueType) -> bool {
        match qt {
            _ => true
        }
    }
}

///
pub trait Supports<T> { }
impl<T> Supports<T> for T { }
impl Supports<Graphics> for General { }
impl Supports<Compute> for General { }
impl Supports<Transfer> for General { }
impl Supports<Transfer> for Graphics { }
impl Supports<Transfer> for Compute { }

/// Encoding the minimal capability to support a combination of other capabilities.
pub trait Upper {
    /// Resulting minimal required capability.
    type Result;
}

impl<T> Upper for (T, T) { type Result = T; }
impl Upper for (General,  Graphics) { type Result = General; }
impl Upper for (General,  Compute)  { type Result = General; }
impl Upper for (General,  Transfer) { type Result = General; }
impl Upper for (Graphics, General)  { type Result = General; }
impl Upper for (Graphics, Compute)  { type Result = General; }
impl Upper for (Graphics, Transfer) { type Result = Graphics; }
impl Upper for (Compute,  General)  { type Result = General; }
impl Upper for (Compute,  Graphics) { type Result = General; }
impl Upper for (Compute,  Transfer) { type Result = Compute; }
impl Upper for (Transfer, General)  { type Result = General; }
impl Upper for (Transfer, Graphics) { type Result = Graphics; }
impl Upper for (Transfer, Compute)  { type Result = Compute; }

redpajama_set_name: RedPajamaGithub


text:
#include "config.h"
#include "EntityReference.h"

#include "Document.h"

namespace WebCore {

inline EntityReference::EntityReference(Document& document, const String&)
    : ContainerNode(document)
{
}

} // namespace


text:
using namespace Eigen;
using namespace std;

int main(int, char**)
{
  cout.precision(3);
  Matrix2d md = Matrix2d::Identity() * 0.45;
Matrix2f mf = Matrix2f::Identity();
cout << md + mf.cast<double>() << endl;

  return 0;
}


text:
/*
Template Name: Color Admin - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.7
Version: 2.1.0
Author: Sean Ngu
Website: http://www.seantheme.com/color-admin-v2.1/admin/html/
*/var handleSummernote=function(){$(".summernote").summernote({placeholder:"Hi, this is summernote. Please, write text here! Super simple WYSIWYG editor on Bootstrap",height:$(window).height()-$(".summernote").offset().top-80})},FormSummernote=function(){"use strict";return{init:function(){handleSummernote()}}}();


text:
<?php
/**
 * @author Stefano Torresi (http://stefanotorresi.it)
 * @license See the file LICENSE.txt for copying permission.
 * ************************************************
 */

namespace Thorr\Nonce\Entity;

interface NonceOwnerInterface
{
}


text:
namespace SGIS
{
	class ADevice;

	///Mapper maps raw inputs to ingame inputs through its enabled Contexts
	class Mapper
	{
    public:
        Mapper() : _mapped(*this), _nextEventValue(0) {}

	public:
		///create a new context in the mapper and returns a reference to it
		Context& createNewContext(std::string name, int priority);

		///returns a class which contains all the mapped input
		const Mapped& getMapped() const { return _mapped; }

		///returns nullptr if not found
		Context* getContext(const std::string& name);
		Context* getContext(Context::Id id);

        void enableContext(const std::string& name);
        void enableContext(Context::Id id);

        void disableContext(const std::string& name);
        void disableContext(Context::Id id);

        void registerNewDevice(ADevice& device);

        Event createNewEvent(std::string name);
        Event getEvent(const std::string& name) const;

        Axis createNewAxis(std::string name);
        Axis getAxis(const std::string& name) const;

		///update all the devices and launches callbacks
        void update();

	private:
		void updateDevices();
		void fireCallbacks() const;
        void mapRawInput(std::function<bool(const Context&)> tryToMapFunc) const;
		void mapButton(RawButton button, EEventType eventType);
        void mapAxis(RawAxis axis, float value);
		void foreachActiveContexts(const std::function<void(const Context&)>& todo) const;

	private:
		Mapped _mapped;

		Utils::IDForge<Context::Id> _nextContextId;

		///Contains Contexts associated to their priority
        using ContextMultimap = std::multimap<int, Context>;
        ContextMultimap _contexts;

		///Shortcuts for get fuctions
		std::unordered_map<Context::Id, std::reference_wrapper<Context>> _contextsById;
		std::unordered_map<std::string, std::reference_wrapper<Context>> _contextsByName;

        ///Events
        Event _nextEventValue;
        std::unordered_map<std::string, Event> _events;

        Axis  _nextAxisValue;
        std::unordered_map<std::string, Axis> _axis;

		std::list<std::reference_wrapper<ADevice>> _devices;
	};
}


text:
import React, { PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Pagination } from 'react-bootstrap';

import { Loader } from './widgets';

import * as ActionCreators from '../actions';

class PhotoListItem extends React.Component {
  static propTypes = {
    photo: PropTypes.object.isRequired
  }

  static contextTypes = {
    router: PropTypes.object.isRequired
  }

  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    event.preventDefault();
    this.context.router.transitionTo('/detail/' + this.props.photo.id);
  }

  render() {

    const photo = this.props.photo;
    const src = photo.photo ? `/uploads/thumbnails/${photo.photo}` : '/img/ajax-loader.gif';

    return (

{photo.title.substring(0, 20)}

      );
  }
}

class PhotoList extends React.Component {

  static propTypes = {
    photos: PropTypes.array.isRequired,
    total: PropTypes.number.isRequired,
    numPages: PropTypes.number.isRequired,
    currentPage: PropTypes.number.isRequired,
    handlePageSelect: PropTypes.func.isRequired
  }

  pagination() {
    const { handlePageSelect, numPages, currentPage, isLoaded } = this.props;
    if (!isLoaded) {
      return '';
    }
    if (numPages > 1) {
      return (
      <Pagination onSelect={handlePageSelect}
                  items={numPages}
                  ellipsis={true}
                  first={true}
                  last={true}
                  next={true}
                  prev={true}
                  maxButtons={12}
                  activePage={currentPage} />
      );
     }
     return '';
  }

  render() {
    const { photos, isLoaded } = this.props;
    if (!isLoaded) {
      return <Loader />;
    }
    const pagination = this.pagination();
    return (

      {pagination}

          {photos.map(photo => {

            return <PhotoListItem key={photo.id} photo={photo} />
          })}

      {pagination}

    );
  }

}

@connect(state => {
  return {
    photos: state.photos.toJS()
  }
})
export class Popular extends React.Component {

  static propTypes = {
    photos: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  }

  constructor(props) {
    super(props);
    const {dispatch} = this.props;
    this.actions = bindActionCreators(ActionCreators.photos, dispatch);
    this.handlePageSelect = this.handlePageSelect.bind(this);
  }

  handlePageSelect(event, selectedEvent) {
    event.preventDefault();
    const page = selectedEvent.eventKey;
    this.actions.getPhotos(page, "votes");
  }

  componentDidMount() {
    this.actions.getPhotos(1, "votes");
  }

  render() {
    return <PhotoList handlePageSelect={this.handlePageSelect} {...this.props.photos} />;
  }

}

@connect(state => {
  return {
    photos: state.photos.toJS()
  };
})
export class Latest extends React.Component {

  static propTypes = {
    photos: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  }

  constructor(props) {
    super(props);
    const {dispatch} = this.props;
    this.actions = bindActionCreators(ActionCreators.photos, dispatch);
    this.handlePageSelect = this.handlePageSelect.bind(this);
  }

  handlePageSelect(event, selectedEvent) {
    event.preventDefault();
    const page = selectedEvent.eventKey;
    this.actions.getPhotos(page, "created");
  }

  componentDidMount() {
    this.actions.getPhotos(1, "created");
  }

  render() {
    return <PhotoList handlePageSelect={this.handlePageSelect} {...this.props.photos} />;
  }

}

@connect(state => {
  return {
    photos: state.photos.toJS()
  }
})
export class Search extends React.Component {

  static propTypes = {
    photos: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  }

  static contextTypes = {
    router: PropTypes.object.isRequired
  }

  constructor(props) {
    super(props);
    const {dispatch} = this.props;
    this.actions = bindActionCreators(ActionCreators.photos, dispatch);
    this.handlePageSelect = this.handlePageSelect.bind(this);
  }

  handlePageSelect(event, selectedEvent) {
    event.preventDefault();
    this.searchPhotos(selectedEvent.eventKey);
  }

  componentDidMount() {
    this.searchPhotos();
  }

  shouldComponentUpdate(nextProps) {
    if (nextProps.photos.total !== this.props.photos.total && nextProps.photos.total === 1) {
      this.context.router.transitionTo("/detail/" + nextProps.photos.photos[0].id);
      return true;
    }
    const nextQuery  = this.getQuery(nextProps);
    if (nextQuery !== this.getQuery()) {
      this.searchPhotos(1, nextQuery);
    }
    return nextProps !== this.props;
  }

  searchPhotos(page=1, query) {
    query = query || this.getQuery();
    if (query) {
      this.actions.searchPhotos(page, query);
    }
  }

  getQuery(props) {
    props = props || this.props;
    if (props.location) {
      return props.location.query.q || '';
    }
    return '';
  }

  render() {
    const query = this.getQuery();
    if (!this.props.photos.isLoaded && query) {
      return (

Searching for {query}...

          <Loader />

      );
    }
    return (

{query ? `${this.props.photos.total} results for ${query}` : ''}

        <PhotoList handlePageSelect={this.handlePageSelect} {...this.props.photos} />

    );

  }

}

@connect(state => {
  return {
    photos: state.photos.toJS()
  }
})
export class User extends React.Component {

  static propTypes = {
    photos: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired
  }

  constructor(props) {
    super(props);
    const {dispatch} = this.props;
    this.actions = bindActionCreators(ActionCreators.photos, dispatch);
    this.handlePageSelect = this.handlePageSelect.bind(this);
  }

  handlePageSelect(event, selectedEvent) {
    event.preventDefault();
    this.getPhotos(selectedEvent.eventKey);
  }

  getPhotos(page=1) {
    const userID = this.props.params.userID;
    this.actions.getPhotosForOwner(userID, page);
  }

  componentDidMount() {
    this.getPhotos();
  }

  render() {
    const username = this.props.params.username;
    return (

{this.props.photos.total} Photos for {username}

        <PhotoList handlePageSelect={this.handlePageSelect} {...this.props.photos} />

    );

  }

}


text:
package com.app.presenter.event;

import com.app.ui.AppUI;
import com.google.gwt.thirdparty.guava.common.eventbus.EventBus;
import com.google.gwt.thirdparty.guava.common.eventbus.SubscriberExceptionContext;
import com.google.gwt.thirdparty.guava.common.eventbus.SubscriberExceptionHandler;

/**
 * @author David
 * A simple wrapper for Guava event bus. Defines static convenience methods for
 * relevant actions.
 */
public class AppEducacionalEventBus implements SubscriberExceptionHandler{

	private final EventBus eventBus = new EventBus(this);

    public static void post(final Object event) {
        AppUI.getAppEducacionalEventbus().eventBus.post(event);
    }

    public static void register(final Object object) {
    	AppUI.getAppEducacionalEventbus().eventBus.register(object);
    }

    public static void unregister(final Object object) {
    	AppUI.getAppEducacionalEventbus().eventBus.unregister(object);
    }

    @Override
    public final void handleException(final Throwable exception,
            final SubscriberExceptionContext context) {
        exception.printStackTrace();
    }

}


text:
{{extend 'layout.html'}}

Manage Languages

{{=grid}}


text:
title: Installing Vagrant
categories:
    - system
    - linux
    - debian
tags:

---
##Install virtual box

	sudo apt-get install virtualbox

##Install vagrant
- Download [Vagrant deb package](https://www.vagrantup.com/downloads.html):

	    cd /tmp/mozilla_ben0
	    dpkg -i vagrant_1.9.5_x86_64.deb

- Clone your vagrant repo and install it!


text:
package com.hemmerling;

public class World {

	private CellState myCellState = CellState.DEAD;
	private int countNeighbors = 0;

	public World nextGeneration() {
		return this;
	}

	public CellState cellState() {

		if (countNeighbors == 3) {
			return CellState.ALIVE;
		} else if (myCellState == CellState.ALIVE ) {
			return CellState.ALIVE;
		}
		return CellState.DEAD;

	}

	public void addNeighbor(MyCell cell) {
		countNeighbors++;
	}

	public void add(MyCell cell) {
		myCellState = CellState.ALIVE;
	}

}


text:
Tutte le informazioni su Desio, scritte dai desiani.

Questo progetto fa parte del contenitore [Open Desio](http://open.desio.org).

[Guarda tutti gli Argomenti](https://github.com/open-comune/conosci-desio/issues).

[Guarda tutti i Documenti](https://github.com/open-comune/conosci-desio/blob/master/data/lista-documenti.md)

Se vuoi partecipare:

1. [Registrati su GitHub](https://github.com/join)
2. Comunicami il tuo *nome utente*, spedendomi un'e-mail a [root@olisti.co](mailto:root@olisti.co) o contattandomi direttamente
3. [Crea un nuovo Argomento](https://github.com/open-comune/conosci-desio/issues/new) o documenta un Argomento presente

Se hai qualche dubbio guarda la pagina [FAQ](FAQ.md).

## Sperimentazione

Nella prima fase di sperimentazione si vuole coinvolgere il maggior numero di membri della Giunta e del Consiglio Comunale.

Ecco la [lista degli utenti](lista-utenti.md).

**Lo scopo è fornire loro uno spazio condiviso di narrazione e di confronto politico basati sui fatti e privo del rumore tipico di Facebook.**

**Nota bene**: questo è uno strumento gratuito, gestito su basi di volontariato da parte di tutti gli utenti partecipanti. L'esperienza è sicuramente migliorabile e nulla vieta che in futuro questo progetto venga migrato verso una piattaforma ancora più semplice e potente. Consideriamolo come un importante esperimento.


text: A rather offensive Telegram bot


text:
compileSelectors = function(arr, leaveHidden){
  var self = this
    , selectors = []
    , buf = []
    , hiddenSelectorRegexp = /^\s*\/?\$/;

  function interpolateParent(selector, buf) {
    var str = selector.val.replace(/^\//g, '').trim();
    if (buf.length) {
      for (var i = 0, len = buf.length; i < len; ++i) {
        if (~buf[i].indexOf('&') || '/' === buf[i].charAt(0)) {
          str = buf[i].replace(/&/g, str).replace(/^\//g, '').trim();
        } else {
          str += ' ' + buf[i].trim();
        }
      }
    }
    return str.trim();
  }

  function compile(arr, i) {
    if (i) {
      arr[i].forEach(function(selector){
        if (!leaveHidden && selector.val.match(hiddenSelectorRegexp)) return;
        if (selector.inherits) {
          buf.unshift(selector.val);
          compile(arr, i - 1);
          buf.shift();
        } else {
          selectors.push(interpolateParent(selector, buf));
        }
      });
    } else {
      arr[0].forEach(function(selector){
        if (!leaveHidden && selector.val.match(hiddenSelectorRegexp)) return;
        var str = interpolateParent(selector, buf);
        if (~str.indexOf('&')) str = str.replace(/&/g, '').trim();
        if (!str.length) return;
        selectors.push((self.indent || '') + str.trimRight());
      });
    }
  }

  compile(arr, arr.length - 1);

  // Return the list with unique selectors only
  return selectors.filter(function(value, index, self){
    return self.indexOf(value) === index;
  });
};

var plugin = function(){
    return function(style){
        style.define('root', function() {
          var stack = this.selectorStack;
          return stack.length ? utils.compileSelectors(stack.slice(0,1)).join(',') : '&';
        });

        style.define('up', function(i) {
          var stack = this.selectorStack,
              len   = stack.length, i;
          if (!stack.length) return '';
          i = parseInt(i, 10);
          if (!i) (i = 1);
          if (i < 0) (i = -i);
          i = (i >= len) ? len - 1 : i;
          stack = stack.slice(0,len-i);
          return utils.compileSelectors(stack).join(',');
        });

        style.define('end', function() {
          var len = this.selectorStack.length,
              selector = null;
          if (!len) return '';
          selector = utils.compileSelectors(this.selectorStack).join(',');
          selector = selector.toString().split(' ');
          return selector[selector.length-1];
        });
    };
};
module.exports = plugin;


text:
module Theblog
  module AdminHelper
    def formatted_value(item, attribute)
      unless attribute.is_a?(Hash)
        return raw(item.send(attribute))
      end

      association_name = attribute.keys.first
      association = item.try(association_name)
      return if association.nil?

      if association.respond_to?(:any?)
        raw(association.map { |el| print_association(el, attribute) }.join(', '))
      else
        print_association(association, attribute)
      end
    end

    def print_association(association, attribute)
      association_attribute = attribute.values.first
      title = association.send(association_attribute)

      if attribute[:link]
        link_to title, path_to_item(association)
      else
        raw(title)
      end
    end

    def link_to_item(item)
      link_to "View", path_to_item(item)
    end

    def link_to_update_status(item, action)
      link_to action.to_s.humanize, path_to_update_status(item, action), method: :put
    end

    def path_to_update_status(item, action)
      theblog.send("admin_#{model_class(item.class)}_#{action}_path", item)
    end

    def link_to_edit_item(item)
      link_to "Edit", path_to_edit_item(item)
    end

    def link_to_new_item(model, params = nil)
      link_to "New Item", path_to_new_item(model), params
    end

    def path_to_item(item)
      theblog.send("admin_#{model_class(item.class)}_path", item)
    end

    def path_to_edit_item(item)
      theblog.send("edit_admin_#{model_class(item.class)}_path", item)
    end

    def path_to_new_item(model)
      theblog.send("new_admin_#{model_class(model)}_path")
    end

    def model_class(model)
      model.to_s.underscore.match(/[\w_]+$/)
    end

    def bootstrap_input(form, field)
      parameters = {
        wrapper_html: { class: 'form-group' },
        input_html:   { class: 'form-control' }
      }
      field_name = if field.is_a? Hash
                     parameters[:as] = field.values.first
                     field.keys.first
                   else
                     field
                   end
      form.input field_name, parameters
    end
  end
end


text:
A prank mailing code in php to send fake e-mails with material ui.

Do not mis-use the code.

See a live demo of this repository here : http://ishanja.in/projects/mail/mail.php


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
?>
<form id="Login" name="Login" action="<?php echo site_url("user/login"); ?>" method="post">
		<h2> Log In </h2>

                <p>
			<label for="userEmail"  >Email </label>
			<input class="input" name ="userEmail" type ="text">
		</p>
		<p>
			<label for="userPass"  > Password </label>
			<input class="input" name ="userPass" type ="password">
		</p>

		<input type="submit" value="Log In" name="">
</form>


text:
define(["./ng-class", "./ng-error", "../core"], function($__0,$__2,$__4) {
  "use strict";
  if (!$__0 || !$__0.__esModule)
    $__0 = {default: $__0};
  if (!$__2 || !$__2.__esModule)
    $__2 = {default: $__2};
  if (!$__4 || !$__4.__esModule)
    $__4 = {default: $__4};
  var NgClass = $__0.NgClass;
  var NgError = $__2.NgError;
  var $__5 = $__4,
      isNode = $__5.isNode,
      isArray = $__5.isArray,
      isString = $__5.isString,
      forEach = $__5.forEach,
      instanceOf = $__5.instanceOf,
      isDocumentNode = $__5.isDocumentNode,
      isElementNode = $__5.isElementNode,
      isTextNode = $__5.isTextNode,
      isCommentNode = $__5.isCommentNode,
      isDocumentFragmentNode = $__5.isDocumentFragmentNode,
      isSafari = $__5.isSafari,
      isIE = $__5.isIE,
      clean = $__5.clean,
      parseXML = $__5.parseXML,
      toXML = $__5.toXML;
  var NgDOM = (function($__super) {
    function NgDOM(node) {
      $traceurRuntime.superConstructor(NgDOM).call(this, NgDOM);
      if (!isNode(node)) {
        throw new NgError('NgDOM error node is not valid');
      }
      this.node = node;
      if (this.node.localName && this.node.prefix) {
        this.type = this.node.localName;
        this.typePrefix = this.node.prefix;
      } else {
        this.type = this.node.nodeName;
        this.typePrefix = null;
      }
      this.namespaceURI = this.node.namespaceURI;
      this.className = 'NgDOM';
    }
    return ($traceurRuntime.createClass)(NgDOM, {
      is: function(type) {
        var prefix = arguments[1] !== (void 0) ? arguments[1] : false;
        var typePrefix = true;
        if (prefix) {
          typePrefix = this.typePrefix === prefix;
        }
        if (isArray(type)) {
          return type.indexOf(this.type) > -1 && !!typePrefix;
        }
        return this.type === type && !!typePrefix;
      },
      firstChild: function() {
        if (this.node) {
          return this.getInstance(this.node.firstChild);
        }
        return null;
      },
      firstElementChild: function() {
        if (this.node) {
          return this.getInstance(this.node.firstElementChild);
        }
        return null;
      },
      lastChild: function() {
        if (this.node) {
          return this.getInstance(this.node.lastChild);
        }
        return null;
      },
      lastElementChild: function() {
        if (this.node) {
          return this.getInstance(this.node.lastElementChild);
        }
        return null;
      },
      nextSibling: function() {
        if (this.node) {
          return this.getInstance(this.node.nextSibling);
        }
        return null;
      },
      nextElementSibling: function() {
        if (this.node) {
          return this.getInstance(this.node.nextElementSibling);
        }
        return null;
      },
      previousSibling: function() {
        if (this.node) {
          return this.getInstance(this.node.previousSibling);
        }
        return null;
      },
      previousElementSibling: function() {
        if (this.node) {
          return this.getInstance(this.node.previousElementSibling);
        }
        return null;
      },
      parentNode: function() {
        if (this.node) {
          return this.getInstance(this.node.parentNode);
        }
        return null;
      },
      createTextNode: function(str) {
        var doc = this.getDocument();
        if (doc && doc.isDocumentNode()) {
          return this.getInstance(doc.node.createTextNode(str));
        }
        throw new NgError('Element is not attached to document node');
      },
      createElement: function(name) {
        var doc = this.getDocument();
        if (doc && doc.isDocumentNode()) {
          return this.getInstance(doc.node.createElement(name));
        }
        throw new NgError('Element is not attached to document node');
      },
      createElementNs: function(namespace, name) {
        var doc = this.getDocument();
        if (doc && doc.isDocumentNode()) {
          return this.getInstance(doc.node.createElementNS(namespace, name));
        }
        throw new NgError('Element is not attached to document node');
      },
      importNode: function(nNode) {
        var doc = this.getDocument(),
            node = this.getInstance(nNode);
        if (doc.isDocumentNode() && instanceOf(node, NgDOM)) {
          doc.node.adoptNode(node.node);
          doc.node.importNode(node.node, true);
        } else {
          throw new NgError('There is no valid document at importNode');
        }
      },
      addChild: function(nNode, importNode) {
        var node = this.getInstance(nNode);
        if (!!importNode) {
          this.importNode(node);
        }
        if (!instanceOf(node, NgDOM)) {
          throw new NgError('Error in addChild node must be instance of NgDOM');
        }
        this.node.appendChild(node.node);
        return node;
      },
      replaceNode: function(nNode, importNode) {
        var parent = this.parentNode(),
            node = this.getInstance(nNode),
            current;
        if (parent && node) {
          if (!!importNode) {
            this.importNode(node);
          }
          current = this.node;
          try {
            this.destroy();
          } catch (e) {
            throw new NgError('replaceNode cannot destroy current child, parent "{0}", replace with "{1}", current "{2}",', [parent, node, current]);
          } finally {
            parent.node.replaceChild(node.node, current);
          }
          return parent;
        } else {
          throw new NgError('replaceNode parent or node is not provided parent "{0}", replace with "{1}", current "{2}",', [parent, node, this]);
        }
      },
      insertBefore: function(newNode, beforeNode, importNode) {
        var n = this.getInstance(newNode),
            b = this.getInstance(beforeNode);
        try {
          if (!!importNode) {
            this.importNode(newNode);
          }
          this.node.insertBefore(n.node, b.node);
        } catch (e) {
          throw new NgError('Unable to execute insert before error "{0}"', [e]);
        }
      },
      clone: function() {
        var clone;
        if (isSafari() && this.isDocumentNode()) {
          clone = parseXML(toXML(this.node));
        } else {
          clone = this.node.cloneNode(true);
        }
        return this.getInstance(clone);
      },
      remove: function() {
        var parent = this.parentNode(),
            node = this.node;
        try {
          this.destroy();
        } catch (e) {
          throw new NgError('Child not removed from node "{0}"', [e]);
        } finally {
          if (parent && parent.node) {
            parent.node.removeChild(node);
          }
          node = null;
          parent = null;
        }
      },
      destroy: function() {
        clean(this);
      },
      toXML: function() {
        return (new XMLSerializer()).serializeToString(this.node);
      },
      isCommentNode: function() {
        return isCommentNode(this.node);
      },
      isTextNode: function() {
        return isTextNode(this.node);
      },
      isElementNode: function() {
        return isElementNode(this.node);
      },
      isDocumentNode: function() {
        return isDocumentNode(this.node);
      },
      isDocumentFragmentNode: function() {
        return isDocumentFragmentNode(this.node);
      },
      getDocument: function() {
        if (this.isDocumentNode()) {
          return this;
        } else if (!this.$document) {
          this.$document = this.node.ownerDocument;
        }
        return this.getInstance(this.$document);
      },
      getInstance: function(node) {
        var doc;
        if (instanceOf(node, NgDOM)) {
          return node;
        } else if (isNode(node)) {
          doc = new NgDOM(node);
          doc.$document = this.getDocument();
        }
        return !!doc ? doc : null;
      },
      setValue: function(value) {
        if (this.isTextNode()) {
          this.node.nodeValue = value;
          return true;
        } else if (this.isElementNode()) {
          if (isSafari() || isIE()) {
            this.removeChildren();
            this.addChild(this.parse(value));
          } else {
            this.node.innerHTML = value;
          }
          return true;
        }
        return false;
      },
      getValue: function() {
        var str = '';
        if (this.isTextNode()) {
          return this.node.nodeValue;
        } else if (this.isElementNode()) {
          if (isSafari() || isIE()) {
            forEach(this.children(), function(cNode) {
              if (cNode.isTextNode()) {
                str += cNode.getValue();
              } else {
                str += cNode.toXML();
              }
            });
            return str;
          } else {
            return this.node.innerHTML;
          }
        }
        return str;
      },
      createFragment: function() {
        var doc = this.getDocument();
        if (doc) {
          return this.getInstance(doc.node.createDocumentFragment());
        }
        return null;
      },
      parse: function(html) {
        var docFragment = this.createFragment(),
            parseElement,
            importNode = false;
        if (docFragment) {
          if (isSafari() || isIE()) {
            parseElement = this.getInstance(parseXML('<div>' + html + '</div>').documentElement.cloneNode(true));
            importNode = true;
          } else {
            parseElement = docFragment.createElement('div');
            parseElement.node.innerHTML = html;
          }
          if (parseElement.hasChildren()) {
            forEach(parseElement.children(), function(cNode) {
              docFragment.addChild(cNode.clone(), importNode);
            });
          }
          parseElement.destroy();
          return docFragment;
        }
        return false;
      },
      children: function() {
        var nodes = [];
        forEach(this.node.childNodes, function(node) {
          nodes.push(this.getInstance(node));
        }, this);
        return nodes;
      },
      removeChildren: function() {
        forEach(this.children(), (function(cNode) {
          cNode.remove();
        }));
        return this;
      },
      hasChildren: function() {
        if (this.node) {
          return this.node.hasChildNodes();
        }
        return false;
      },
      hasChildElements: function() {
        if (this.node) {
          return this.node.childElementCount > 0;
        }
        return false;
      },
      getChildElementCount: function() {
        if (this.node) {
          return this.node.childElementCount;
        }
        return 0;
      },
      childElements: function() {
        var nodes = [];
        forEach(this.node.childNodes, function(node) {
          if (isElementNode(node)) {
            nodes.push(this.getInstance(node));
          }
        }, this);
        return nodes;
      },
      wrap: function(node) {
        node.addChild(this.clone());
        this.replaceNode(node);
        return node;
      },
      unwrap: function() {
        var parent = this.parentNode();
        forEach(this.children(), function(cNode) {
          parent.insertBefore(cNode.clone(), this);
        }, this);
        this.remove();
        return parent;
      },
      wrapChildren: function(node, prevent) {
        var nodesToSlice = [];
        if (isArray(prevent) || isString(prevent)) {
          forEach(this.children(), function(cNode) {
            if (isArray(prevent)) {
              if (prevent.indexOf(cNode.type) === -1) {
                nodesToSlice.push(cNode);
              }
            } else if (cNode.type !== prevent) {
              nodesToSlice.push(cNode);
            }
          });
        } else {
          nodesToSlice = this.children();
        }
        forEach(nodesToSlice, function(cNode) {
          node.addChild(cNode.clone());
          cNode.remove();
        });
        this.addChild(node);
        return this;
      },
      wrapDeepInTwoChildNs: function(node, ns, prefix) {
        var children = this.childElements();
        if (children.length > 2) {
          do {
            wrap.call(this, children, node, ns, prefix);
            children = this.childElements();
          } while (children.length > 2);
        }
        function wrap(childNodes, nodeName, nameSpace, nsPrefix) {
          var wrapNode;
          if (nodeName && !nameSpace) {
            wrapNode = this.createElement(nodeName);
          } else {
            if (nsPrefix) {
              nodeName = nsPrefix + nodeName;
            }
            wrapNode = this.createElementNs(nameSpace, nodeName);
          }
          forEach(childNodes.splice(0, 2), function(cNode) {
            wrapNode.addChild(cNode.clone());
            cNode.remove();
          });
          this.insertBefore(wrapNode, this.firstElementChild());
        }
        return this;
      },
      setAttributeNS: function(namespace, name, value) {
        this.node.setAttributeNS(namespace, name, value);
        return this;
      },
      setAttribute: function(name, value) {
        this.node.setAttribute(name, value);
        return this;
      },
      removeAttributeNS: function(namespace, name) {
        this.node.removeAttributeNS(namespace, name);
        return this;
      },
      removeAttribute: function(name) {
        this.node.removeAttribute(name);
        return this;
      },
      removeAttributeNode: function(attrNode) {
        this.node.removeAttributeNode(attrNode);
        return this;
      },
      hasAttributeNS: function(namespace, name) {
        return this.node.hasAttributeNS(namespace, name);
      },
      hasAttribute: function(name) {
        return this.node.hasAttribute(name);
      },
      isNamespace: function(attrNode) {
        if ((attrNode.prefix === 'xmlns' && this.node && attrNode.localName === this.node.prefix) || (attrNode.name === 'xmlns' && !attrNode.prefix) || (attrNode.prefix === 'xmlns')) {
          return true;
        }
        return false;
      },
      getNamespaces: function() {
        var namespaces = [];
        if (this.isElementNode()) {
          forEach(this.node.attributes, function(value) {
            if (this.isNamespace(value)) {
              namespaces.push({
                name: value.nodeName,
                prefix: value.prefix,
                localName: value.localName,
                type: value.nodeType,
                value: value.nodeValue,
                baseURI: value.baseURI,
                namespaceURI: value.namespaceURI
              });
            }
          }, this);
        }
        return namespaces;
      },
      getNamespace: function(namespace) {
        return this.getNamespaces().filter((function(item) {
          return item.value === namespace;
        })).shift();
      },
      textContent: function() {
        return this.node.textContent;
      },
      getAttributes: function() {
        return Array.prototype.slice.call(this.node.attributes);
      },
      getAttributeNode: function(name) {
        return this.node.getAttributeNode(name);
      },
      getAttributeNodeNS: function(namespace, name) {
        return this.node.getAttributeNodeNS(namespace, name);
      },
      getAttribute: function(name) {
        return this.node.getAttribute(name);
      },
      getAttributeNS: function(namespace, name) {
        return this.node.getAttributeNS(namespace, name);
      },
      querySelector: function(selector) {
        if (this.node && isString(selector)) {
          return this.getInstance(this.node.querySelector(selector));
        }
        return null;
      },
      querySelectorAll: function(selector) {
        if (isArray(selector)) {
          selector = selector.join(',');
        }
        if (this.node) {
          return [].map.call(this.node.querySelectorAll(selector), this.getInstance.bind(this));
        }
        return null;
      },
      querySelectorAllNS: function(namespace, selector) {
        if (isString(selector) && isString(namespace)) {
          return this.querySelectorAll('*|' + selector).filter((function(item) {
            return item.namespaceURI === namespace;
          }));
        }
        return null;
      }
    }, {}, $__super);
  }(NgClass));
  return {
    get NgDOM() {
      return NgDOM;
    },
    __esModule: true
  };
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycologia 80(6): 896 (1989)

#### Original name
Synnemellisia hyalospora N.K. Rao, Manohar. & Goos, 1989

### Remarks
null


text:
package org.docksidestage.hangar.freeflute.custom.gengap.exentity;

import org.docksidestage.hangar.freeflute.custom.gengap.bsentity.BsSeaPurchase;

/**
 * @author FreeGen
 */
public class SeaPurchase extends BsSeaPurchase {

    private static final long serialVersionUID = 1L;
}


text:
package org.apache.beam.sdk.io.kinesis;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.reset;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.AmazonServiceException.ErrorType;
import com.amazonaws.services.kinesis.AmazonKinesis;
import com.amazonaws.services.kinesis.model.DescribeStreamResult;
import com.amazonaws.services.kinesis.model.ExpiredIteratorException;
import com.amazonaws.services.kinesis.model.GetShardIteratorRequest;
import com.amazonaws.services.kinesis.model.GetShardIteratorResult;
import com.amazonaws.services.kinesis.model.LimitExceededException;
import com.amazonaws.services.kinesis.model.ProvisionedThroughputExceededException;
import com.amazonaws.services.kinesis.model.Shard;
import com.amazonaws.services.kinesis.model.ShardIteratorType;
import com.amazonaws.services.kinesis.model.StreamDescription;
import java.util.List;
import org.joda.time.Instant;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/***
 */
@RunWith(MockitoJUnitRunner.class)
public class SimplifiedKinesisClientTest {
    private static final String STREAM = "stream";
    private static final String SHARD_1 = "shard-01";
    private static final String SHARD_2 = "shard-02";
    private static final String SHARD_3 = "shard-03";
    private static final String SHARD_ITERATOR = "iterator";
    private static final String SEQUENCE_NUMBER = "abc123";

    @Mock
    private AmazonKinesis kinesis;
    @InjectMocks
    private SimplifiedKinesisClient underTest;

    @Test
    public void shouldReturnIteratorStartingWithSequenceNumber() throws Exception {
        given(kinesis.getShardIterator(new GetShardIteratorRequest()
                .withStreamName(STREAM)
                .withShardId(SHARD_1)
                .withShardIteratorType(ShardIteratorType.AT_SEQUENCE_NUMBER)
                .withStartingSequenceNumber(SEQUENCE_NUMBER)
        )).willReturn(new GetShardIteratorResult()
                .withShardIterator(SHARD_ITERATOR));

        String stream = underTest.getShardIterator(STREAM, SHARD_1,
                ShardIteratorType.AT_SEQUENCE_NUMBER, SEQUENCE_NUMBER, null);

        assertThat(stream).isEqualTo(SHARD_ITERATOR);
    }

    @Test
    public void shouldReturnIteratorStartingWithTimestamp() throws Exception {
        Instant timestamp = Instant.now();
        given(kinesis.getShardIterator(new GetShardIteratorRequest()
                .withStreamName(STREAM)
                .withShardId(SHARD_1)
                .withShardIteratorType(ShardIteratorType.AT_SEQUENCE_NUMBER)
                .withTimestamp(timestamp.toDate())
        )).willReturn(new GetShardIteratorResult()
                .withShardIterator(SHARD_ITERATOR));

        String stream = underTest.getShardIterator(STREAM, SHARD_1,
                ShardIteratorType.AT_SEQUENCE_NUMBER, null, timestamp);

        assertThat(stream).isEqualTo(SHARD_ITERATOR);
    }

    @Test
    public void shouldHandleExpiredIterationExceptionForGetShardIterator() {
        shouldHandleGetShardIteratorError(new ExpiredIteratorException(""),
                ExpiredIteratorException.class);
    }

    @Test
    public void shouldHandleLimitExceededExceptionForGetShardIterator() {
        shouldHandleGetShardIteratorError(new LimitExceededException(""),
                TransientKinesisException.class);
    }

    @Test
    public void shouldHandleProvisionedThroughputExceededExceptionForGetShardIterator() {
        shouldHandleGetShardIteratorError(new ProvisionedThroughputExceededException(""),
                TransientKinesisException.class);
    }

    @Test
    public void shouldHandleServiceErrorForGetShardIterator() {
        shouldHandleGetShardIteratorError(newAmazonServiceException(ErrorType.Service),
                TransientKinesisException.class);
    }

    @Test
    public void shouldHandleClientErrorForGetShardIterator() {
        shouldHandleGetShardIteratorError(newAmazonServiceException(ErrorType.Client),
                RuntimeException.class);
    }

    @Test
    public void shouldHandleUnexpectedExceptionForGetShardIterator() {
        shouldHandleGetShardIteratorError(new NullPointerException(),
                RuntimeException.class);
    }

    private void shouldHandleGetShardIteratorError(
            Exception thrownException,
            Class<? extends Exception> expectedExceptionClass) {
        GetShardIteratorRequest request = new GetShardIteratorRequest()
                .withStreamName(STREAM)
                .withShardId(SHARD_1)
                .withShardIteratorType(ShardIteratorType.LATEST);

        given(kinesis.getShardIterator(request)).willThrow(thrownException);

        try {
            underTest.getShardIterator(STREAM, SHARD_1, ShardIteratorType.LATEST, null, null);
            failBecauseExceptionWasNotThrown(expectedExceptionClass);
        } catch (Exception e) {
            assertThat(e).isExactlyInstanceOf(expectedExceptionClass);
        } finally {
            reset(kinesis);
        }
    }

    @Test
    public void shouldListAllShards() throws Exception {
        Shard shard1 = new Shard().withShardId(SHARD_1);
        Shard shard2 = new Shard().withShardId(SHARD_2);
        Shard shard3 = new Shard().withShardId(SHARD_3);
        given(kinesis.describeStream(STREAM, null)).willReturn(new DescribeStreamResult()
                .withStreamDescription(new StreamDescription()
                        .withShards(shard1, shard2)
                        .withHasMoreShards(true)));
        given(kinesis.describeStream(STREAM, SHARD_2)).willReturn(new DescribeStreamResult()
                .withStreamDescription(new StreamDescription()
                        .withShards(shard3)
                        .withHasMoreShards(false)));

        List<Shard> shards = underTest.listShards(STREAM);

        assertThat(shards).containsOnly(shard1, shard2, shard3);
    }

    @Test
    public void shouldHandleExpiredIterationExceptionForShardListing() {
        shouldHandleShardListingError(new ExpiredIteratorException(""),
                ExpiredIteratorException.class);
    }

    @Test
    public void shouldHandleLimitExceededExceptionForShardListing() {
        shouldHandleShardListingError(new LimitExceededException(""),
                TransientKinesisException.class);
    }

    @Test
    public void shouldHandleProvisionedThroughputExceededExceptionForShardListing() {
        shouldHandleShardListingError(new ProvisionedThroughputExceededException(""),
                TransientKinesisException.class);
    }

    @Test
    public void shouldHandleServiceErrorForShardListing() {
        shouldHandleShardListingError(newAmazonServiceException(ErrorType.Service),
                TransientKinesisException.class);
    }

    @Test
    public void shouldHandleClientErrorForShardListing() {
        shouldHandleShardListingError(newAmazonServiceException(ErrorType.Client),
                RuntimeException.class);
    }

    @Test
    public void shouldHandleUnexpectedExceptionForShardListing() {
        shouldHandleShardListingError(new NullPointerException(),
                RuntimeException.class);
    }

    private void shouldHandleShardListingError(
            Exception thrownException,
            Class<? extends Exception> expectedExceptionClass) {
        given(kinesis.describeStream(STREAM, null)).willThrow(thrownException);
        try {
            underTest.listShards(STREAM);
            failBecauseExceptionWasNotThrown(expectedExceptionClass);
        } catch (Exception e) {
            assertThat(e).isExactlyInstanceOf(expectedExceptionClass);
        } finally {
            reset(kinesis);
        }
    }

    private AmazonServiceException newAmazonServiceException(ErrorType errorType) {
        AmazonServiceException exception = new AmazonServiceException("");
        exception.setErrorType(errorType);
        return exception;
    }
}


text:
class RenameCategoryToRestaurantCategory < ActiveRecord::Migration[5.1]
  def change
    rename_table :categories, :restaurant_categories
  end
end


text:
package types

import (
	"fmt"
	"sort"
	"time"

	"github.com/gogo/protobuf/proto"
	"github.com/gravitational/trace"

	"github.com/gravitational/teleport/api"
)

// AppServer represents a single proxied web app.
type AppServer interface {
	// ResourceWithLabels provides common resource methods.
	ResourceWithLabels
	// GetNamespace returns server namespace.
	GetNamespace() string
	// GetTeleportVersion returns the teleport version the server is running on.
	GetTeleportVersion() string
	// GetHostname returns the server hostname.
	GetHostname() string
	// GetHostID returns ID of the host the server is running on.
	GetHostID() string
	// GetRotation gets the state of certificate authority rotation.
	GetRotation() Rotation
	// SetRotation sets the state of certificate authority rotation.
	SetRotation(Rotation)
	// String returns string representation of the server.
	String() string
	// Copy returns a copy of this app server object.
	Copy() AppServer
	// GetApp returns the app this app server proxies.
	GetApp() Application
	// SetApp sets the app this app server proxies.
	SetApp(Application) error
	// ProxiedService provides common methods for a proxied service.
	ProxiedService
}

// NewAppServerV3 creates a new app server instance.
func NewAppServerV3(meta Metadata, spec AppServerSpecV3) (*AppServerV3, error) {
	s := &AppServerV3{
		Metadata: meta,
		Spec:     spec,
	}
	if err := s.CheckAndSetDefaults(); err != nil {
		return nil, trace.Wrap(err)
	}
	return s, nil
}

// NewAppServerV3FromApp creates a new app server from the provided app.
func NewAppServerV3FromApp(app *AppV3, hostname, hostID string) (*AppServerV3, error) {
	return NewAppServerV3(Metadata{
		Name: app.GetName(),
	}, AppServerSpecV3{
		Hostname: hostname,
		HostID:   hostID,
		App:      app,
	})
}

// GetVersion returns the database server resource version.
func (s *AppServerV3) GetVersion() string {
	return s.Version
}

// GetTeleportVersion returns the Teleport version the server is running.
func (s *AppServerV3) GetTeleportVersion() string {
	return s.Spec.Version
}

// GetHostname returns the database server hostname.
func (s *AppServerV3) GetHostname() string {
	return s.Spec.Hostname
}

// GetHostID returns ID of the host the server is running on.
func (s *AppServerV3) GetHostID() string {
	return s.Spec.HostID
}

// GetKind returns the resource kind.
func (s *AppServerV3) GetKind() string {
	return s.Kind
}

// GetSubKind returns the resource subkind.
func (s *AppServerV3) GetSubKind() string {
	return s.SubKind
}

// SetSubKind sets the resource subkind.
func (s *AppServerV3) SetSubKind(sk string) {
	s.SubKind = sk
}

// GetResourceID returns the resource ID.
func (s *AppServerV3) GetResourceID() int64 {
	return s.Metadata.ID
}

// SetResourceID sets the resource ID.
func (s *AppServerV3) SetResourceID(id int64) {
	s.Metadata.ID = id
}

// GetMetadata returns the resource metadata.
func (s *AppServerV3) GetMetadata() Metadata {
	return s.Metadata
}

// GetNamespace returns the resource namespace.
func (s *AppServerV3) GetNamespace() string {
	return s.Metadata.Namespace
}

// SetExpiry sets the resource expiry time.
func (s *AppServerV3) SetExpiry(expiry time.Time) {
	s.Metadata.SetExpiry(expiry)
}

// Expiry returns the resource expiry time.
func (s *AppServerV3) Expiry() time.Time {
	return s.Metadata.Expiry()
}

// GetName returns the resource name.
func (s *AppServerV3) GetName() string {
	return s.Metadata.Name
}

// SetName sets the resource name.
func (s *AppServerV3) SetName(name string) {
	s.Metadata.Name = name
}

// GetRotation returns the server CA rotation state.
func (s *AppServerV3) GetRotation() Rotation {
	return s.Spec.Rotation
}

// SetRotation sets the server CA rotation state.
func (s *AppServerV3) SetRotation(r Rotation) {
	s.Spec.Rotation = r
}

// GetApp returns the app this app server proxies.
func (s *AppServerV3) GetApp() Application {
	return s.Spec.App
}

// SetApp sets the app this app server proxies.
func (s *AppServerV3) SetApp(app Application) error {
	appV3, ok := app.(*AppV3)
	if !ok {
		return trace.BadParameter("expected *AppV3, got %T", app)
	}
	s.Spec.App = appV3
	return nil
}

// String returns the server string representation.
func (s *AppServerV3) String() string {
	return fmt.Sprintf("AppServer(Name=%v, Version=%v, Hostname=%v, HostID=%v, App=%v)",
		s.GetName(), s.GetTeleportVersion(), s.GetHostname(), s.GetHostID(), s.GetApp())
}

// setStaticFields sets static resource header and metadata fields.
func (s *AppServerV3) setStaticFields() {
	s.Kind = KindAppServer
	s.Version = V3
}

// CheckAndSetDefaults checks and sets default values for any missing fields.
func (s *AppServerV3) CheckAndSetDefaults() error {
	s.setStaticFields()
	if err := s.Metadata.CheckAndSetDefaults(); err != nil {
		return trace.Wrap(err)
	}
	if s.Spec.HostID == "" {
		return trace.BadParameter("missing app server HostID")
	}
	if s.Spec.Version == "" {
		s.Spec.Version = api.Version
	}
	if s.Spec.App == nil {
		return trace.BadParameter("missing app server App")
	}
	if err := s.Spec.App.CheckAndSetDefaults(); err != nil {
		return trace.Wrap(err)
	}
	return nil
}

// Origin returns the origin value of the resource.
func (s *AppServerV3) Origin() string {
	return s.Metadata.Origin()
}

// SetOrigin sets the origin value of the resource.
func (s *AppServerV3) SetOrigin(origin string) {
	s.Metadata.SetOrigin(origin)
}

// GetProxyID returns a list of proxy ids this server is connected to.
func (s *AppServerV3) GetProxyIDs() []string {
	return s.Spec.ProxyIDs
}

// SetProxyID sets the proxy ids this server is connected to.
func (s *AppServerV3) SetProxyIDs(proxyIDs []string) {
	s.Spec.ProxyIDs = proxyIDs
}

// GetAllLabels returns all resource's labels. Considering:
// * Static labels from `Metadata.Labels` and `Spec.App`.
// * Dynamic labels from `Spec.App.Spec`.
func (s *AppServerV3) GetAllLabels() map[string]string {
	staticLabels := make(map[string]string)
	for name, value := range s.Metadata.Labels {
		staticLabels[name] = value
	}

	var dynamicLabels map[string]CommandLabelV2
	if s.Spec.App != nil {
		for name, value := range s.Spec.App.Metadata.Labels {
			staticLabels[name] = value
		}

		dynamicLabels = s.Spec.App.Spec.DynamicLabels
	}

	return CombineLabels(staticLabels, dynamicLabels)
}

// GetStaticLabels returns the app server static labels.
func (s *AppServerV3) GetStaticLabels() map[string]string {
	return s.Metadata.Labels
}

// SetStaticLabels sets the app server static labels.
func (s *AppServerV3) SetStaticLabels(sl map[string]string) {
	s.Metadata.Labels = sl
}

// Copy returns a copy of this app server object.
func (s *AppServerV3) Copy() AppServer {
	return proto.Clone(s).(*AppServerV3)
}

// MatchSearch goes through select field values and tries to
// match against the list of search values.
func (s *AppServerV3) MatchSearch(values []string) bool {
	return MatchSearch(nil, values, nil)
}

// AppServers represents a list of app servers.
type AppServers []AppServer

// Len returns the slice length.
func (s AppServers) Len() int { return len(s) }

// Less compares app servers by name and host ID.
func (s AppServers) Less(i, j int) bool {
	switch {
	case s[i].GetName() < s[j].GetName():
		return true
	case s[i].GetName() > s[j].GetName():
		return false
	default:
		return s[i].GetHostID() < s[j].GetHostID()
	}
}

// Swap swaps two app servers.
func (s AppServers) Swap(i, j int) { s[i], s[j] = s[j], s[i] }

// SortByCustom custom sorts by given sort criteria.
func (s AppServers) SortByCustom(sortBy SortBy) error {
	if sortBy.Field == "" {
		return nil
	}

	// We assume sorting by type AppServer, we are really
	// wanting to sort its contained resource Application.
	isDesc := sortBy.IsDesc
	switch sortBy.Field {
	case ResourceMetadataName:
		sort.SliceStable(s, func(i, j int) bool {
			return stringCompare(s[i].GetApp().GetName(), s[j].GetApp().GetName(), isDesc)
		})
	case ResourceSpecDescription:
		sort.SliceStable(s, func(i, j int) bool {
			return stringCompare(s[i].GetApp().GetDescription(), s[j].GetApp().GetDescription(), isDesc)
		})
	case ResourceSpecPublicAddr:
		sort.SliceStable(s, func(i, j int) bool {
			return stringCompare(s[i].GetApp().GetPublicAddr(), s[j].GetApp().GetPublicAddr(), isDesc)
		})
	default:
		return trace.NotImplemented("sorting by field %q for resource %q is not supported", sortBy.Field, KindAppServer)
	}

	return nil
}

// AsResources returns app servers as type resources with labels.
func (s AppServers) AsResources() []ResourceWithLabels {
	resources := make([]ResourceWithLabels, 0, len(s))
	for _, server := range s {
		resources = append(resources, ResourceWithLabels(server))
	}
	return resources
}

// GetFieldVals returns list of select field values.
func (s AppServers) GetFieldVals(field string) ([]string, error) {
	vals := make([]string, 0, len(s))
	switch field {
	case ResourceMetadataName:
		for _, server := range s {
			vals = append(vals, server.GetApp().GetName())
		}
	case ResourceSpecDescription:
		for _, server := range s {
			vals = append(vals, server.GetApp().GetDescription())
		}
	case ResourceSpecPublicAddr:
		for _, server := range s {
			vals = append(vals, server.GetApp().GetPublicAddr())
		}
	default:
		return nil, trace.NotImplemented("getting field %q for resource %q is not supported", field, KindAppServer)
	}

	return vals, nil
}


text:
import React from "react";
import { connect } from "react-redux";
import {
  DesignerPanel, DesignerPanelContent, DesignerPanelHeader,
} from "../../farm_designer/designer_panel";
import { Panel } from "../../farm_designer/panel_header";
import { mapStateToProps } from "../state_to_props";
import { Props } from "../interfaces";
import { t } from "../../i18next_wrapper";
import { EmptyStateWrapper, EmptyStateGraphic } from "../../ui";
import {
  SequenceEditorMiddleActive,
} from "../sequence_editor_middle_active";
import { Content } from "../../constants";
import { isTaggedSequence } from "../../resources/tagged_resources";
import {
  setActiveSequenceByName,
} from "../set_active_sequence_by_name";
import { push } from "../../history";
import { urlFriendly } from "../../util";

export class RawDesignerSequenceEditor extends React.Component<Props> {

  componentDidMount() {
    if (!this.props.sequence) { setActiveSequenceByName(); }
  }

  render() {
    const panelName = "designer-sequence-editor";
    const { sequence } = this.props;
    return <DesignerPanel panelName={panelName} panel={Panel.Sequences}>
      <DesignerPanelHeader
        panelName={panelName}
        panel={Panel.Sequences}
        title={this.props.sequence?.body.name || t("No Sequence selected")}
        backTo={"/app/designer/sequences"}>
        {sequence && window.innerWidth > 450 &&
          <a className={"right-button"}
            title={t("open full-page editor")}
            onClick={() =>
              push(`/app/sequences/${urlFriendly(sequence.body.name)}`)}>
            {t("full editor")}
          </a>}
      </DesignerPanelHeader>
      <DesignerPanelContent panelName={panelName}>
        <EmptyStateWrapper
          notEmpty={this.props.sequence && isTaggedSequence(this.props.sequence)}
          graphic={EmptyStateGraphic.sequences}
          title={t("No Sequence selected.")}
          text={Content.NO_SEQUENCE_SELECTED}>
          {this.props.sequence && <SequenceEditorMiddleActive
            dispatch={this.props.dispatch}
            sequence={this.props.sequence}
            resources={this.props.resources}
            syncStatus={this.props.syncStatus}
            hardwareFlags={this.props.hardwareFlags}
            farmwareData={this.props.farmwareData}
            shouldDisplay={this.props.shouldDisplay}
            getWebAppConfigValue={this.props.getWebAppConfigValue}
            visualized={this.props.visualized}
            hoveredStep={this.props.hoveredStep}
            menuOpen={this.props.menuOpen} />}
        </EmptyStateWrapper>
      </DesignerPanelContent>
    </DesignerPanel>;
  }
}

export const DesignerSequenceEditor =
  connect(mapStateToProps)(RawDesignerSequenceEditor);


text:
module EconGraphs {

    export interface ElasticityDefinition extends KG.ModelDefinition
    {
        inverse? : boolean;
        terms?: {};
        fn? : KGMath.Functions.Base;
    }

    export interface IElasticity extends KG.IModel
    {
        calculateElasticity: (inputs? : any) => Elasticity;
        _calculateElasticity: (inputs : any) => Elasticity;
        elasticity: number;
        absoluteElasticity: number;
        elasticityWord: string;
        elasticityNumber: (absoluteValue:boolean) => string
        elasticityComparator: string;
    }

    export class Elasticity extends KG.Model
    {
        private terms;
        public inverse;
        public elasticity;
        public absoluteElasticity;
        public elasticityWord;
        public elasticityComparator;

        constructor(definition:ElasticityDefinition, modelPath?:string) {
            definition.inverse = _.defaults(false, definition.inverse);
            definition.terms = _.defaults({
                perfectlyElastic: "perfectly elastic",
                perfectlyInelastic: "perfectly inelastic",
                elastic: "elastic",
                inelastic: "inelastic",
                unitElastic: "unit elastic"
            },definition.terms);
            super(definition, modelPath);
        }

        calculateElasticity(inputs? : any) {

            var e = this;

            e = e._calculateElasticity(inputs);

            e.absoluteElasticity = Math.abs(e.elasticity);
            if(isNaN(e.absoluteElasticity)) {
                e.absoluteElasticity == '\\emptyset';
            }
            e.elasticityComparator = e.elasticityNumber(true);

            if(e.absoluteElasticity == 0) {
                e.elasticityWord = e.terms.perfectlyInelastic;
            } else if(e.absoluteElasticity < 1) {
                e.elasticityWord =  e.terms.inelastic;
                e.elasticityComparator += "< 1";
            } else if(e.absoluteElasticity == 1) {
                e.elasticityWord =  e.terms.unitElastic;
            } else if(e.absoluteElasticity == Infinity) {
                e.elasticityWord =  e.terms.perfectlyElastic;
            } else if(e.absoluteElasticity > 1) {
                e.elasticityWord = e.terms.elastic;
                e.elasticityComparator += "> 1";
            } else {
                e.elasticityWord = 'undefined';
            }

            return e;
        }

        _calculateElasticity(inputs) {
            return this; // overridden by subclass
        }

        elasticityNumber(absoluteValue:boolean) {
            var e = this;
            absoluteValue = absoluteValue || false;

            if(isNaN(e.absoluteElasticity)) {
                return "\\emptyset";
            }

            var returnString = (!absoluteValue && e.elasticity < 0) ? '-' : '';

            returnString += (e.absoluteElasticity == Infinity) ? "\\infty" : (e.absoluteElasticity == 0) ? "0" : (e.absoluteElasticity == 1) ? "1" : e.absoluteElasticity.toFixed(2);

            return returnString;
        }

        _update(scope) {
            return this.calculateElasticity();
        }

    }

}


text:
all:
	time sh -c 'vagrant up --parallel && for F in client1 gw1 gw2 client2 cm; do vagrant ssh $$F -c date; done && vagrant destroy -f'


text:
var gulp = require('gulp');
var path = require('path');
//universal
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
//javascript
var jshint = require('gulp-jshint');
var uglify = require('gulp-uglify');
var autopolyfiller = require('gulp-autopolyfiller');
var modernizr = require('gulp-modernizr');
//sass/css
var sass = require('gulp-sass');
var minify = require('gulp-minify-css');
var autoprefixer = require('gulp-autoprefixer');

var jsInputDir = path.normalize(__dirname + '/public/javascripts');
var sassInputDir = path.normalize(__dirname + '/public/stylesheets');
var outputDir = path.normalize(__dirname + '/public/dist');

var jsGlob = path.normalize(jsInputDir + '**/*.js');
var sassGlob = path.normalize(sassInputDir + '**/*.scss');

gulp.task('js-app', function(done){
	gulp.src(jsGlob)
		.pipe(sourcemaps.init())
			.pipe(jshint())
			.pipe(jshint.reporter('default'))
			.pipe(concat('front-end-app.js'))
			.pipe(uglify())
		.pipe(sourcemaps.write('./'))
		.pipe(gulp.dest(outputDir));
	done();
});

gulp.task('polyfills', function(done){
	gulp.src(jsGlob)
		.pipe(autopolyfiller('polyfills.js'))
		.pipe(gulp.dest(outputDir));
	done();
});

gulp.task('modernizr', function() {
  gulp.src(jsGlob)
    .pipe(modernizr('modernizr.js'))
    .pipe(gulp.dest(outputDir));
});

gulp.task('js-all', ['js-app', 'polyfills', 'modernizr']);


text:
<!DOCTYPE html>

<link rel="help" href="https://drafts.csswg.org/css-backgrounds-3/#background-color">
<link rel="match" href="background-color-animation-single-keyframe-ref.html">


text:
/*
	By: facug91
	From: http://coj.uci.cu/24h/problem.xhtml?abb=2202
	Name:
	Number: 2202
*/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class HowManyLatticePoints {

	static long gcd (long a, long b) {
		if (b == 0) {
			return a;
		}
		return gcd(b, a%b);
	}

	public static void main (String[] args) throws IOException {

		BufferedReader stdin = new BufferedReader
				(new InputStreamReader(System.in));

		Long x, y, z;
		Long total;

		String input = stdin.readLine();
		while (input != null) {
			String[] inputTokens = input.split("[ ]+");
			x = Math.abs(Long.parseLong(inputTokens[0]) - Long.parseLong(inputTokens[3]));
			y = Math.abs(Long.parseLong(inputTokens[1]) - Long.parseLong(inputTokens[4]));
			z = Math.abs(Long.parseLong(inputTokens[2]) - Long.parseLong(inputTokens[5]));

			total = gcd(gcd(x, y), z)+1;

			System.out.println(total);

			input = stdin.readLine();
		}

		stdin.close();
	}
}


text:
using OpenQA.Selenium.Chrome;

namespace Atata.IntegrationTests.Context;

public class AtataContextEventsTests : UITestFixtureBase
{
    [Test]
    public void Init()
    {
        int executionsCount = 0;

        ConfigureBaseAtataContext()
            .EventSubscriptions.Add<AtataContextInitStartedEvent>((eventData, context) =>
            {
                eventData.Should().NotBeNull();
                context.Should().NotBeNull().And.Be(eventData.Context).And.Be(AtataContext.Current);

                context.Log.Should().NotBeNull();
                context.Driver.Should().BeNull();

                executionsCount++;
            })
            .Build();

        executionsCount.Should().Be(1);
    }

    [Test]
    public void Init_WithNullDriver()
    {
        int executionsCount = 0;

        Assert.Throws<InvalidOperationException>(() =>
            AtataContext.Configure()
                .UseDriver(() => null)
                .EventSubscriptions.Add<AtataContextInitStartedEvent>(() => executionsCount++)
                .Build());

        executionsCount.Should().Be(1);
    }

    [Test]
    public void InitCompleted()
    {
        int executionsCount = 0;

        ConfigureBaseAtataContext()
            .EventSubscriptions.Add<AtataContextInitCompletedEvent>((eventData, context) =>
            {
                eventData.Should().NotBeNull();
                context.Should().NotBeNull().And.Be(eventData.Context).And.Be(AtataContext.Current);

                context.Log.Should().NotBeNull();
                context.Driver.Should().BeOfType<ChromeDriver>();

                executionsCount++;
            })
            .Build();

        executionsCount.Should().Be(1);
    }

    [Test]
    public void DriverInit()
    {
        int executionsCount = 0;

        ConfigureBaseAtataContext()
            .EventSubscriptions.Add<DriverInitEvent>((eventData, context) =>
            {
                eventData.Should().NotBeNull();
                context.Should().NotBeNull().And.Be(AtataContext.Current);

                context.Log.Should().NotBeNull();
                eventData.Driver.Should().NotBeNull().And.Be(AtataContext.Current.Driver);

                executionsCount++;
            })
            .Build();

        executionsCount.Should().Be(1);
    }

    [Test]
    public void DriverInit_WhenRestartDriver()
    {
        int executionsCount = 0;
        IWebDriver initialDriver = null;

        ConfigureBaseAtataContext()
            .EventSubscriptions.Add<DriverInitEvent>(eventData =>
            {
                if (executionsCount == 0)
                    initialDriver = eventData.Driver;
                else
                    eventData.Driver.Should().NotBe(initialDriver);

                executionsCount++;
            })
            .Build();

        AtataContext.Current.RestartDriver();

        executionsCount.Should().Be(2);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Package org.apache.wicket.util.resource.locator (Wicket Parent 1.5.7 API)
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.apache.wicket.util.resource.locator

Packages that use org.apache.wicket.util.resource.locator

org.apache.wicket.resource

Locale aware resouce loaders.

org.apache.wicket.resource.loader

org.apache.wicket.settings

org.apache.wicket.settings.def

org.apache.wicket.util.resource.locator

Locators for finding/ loading resources.

org.apache.wicket.util.resource.locator.caching

Classes in org.apache.wicket.util.resource.locator used by org.apache.wicket.resource

IResourceStreamLocator

          Interface for code that locates resources.

Classes in org.apache.wicket.util.resource.locator used by org.apache.wicket.resource.loader

ResourceNameIterator

          Contains the logic to locate a resource based on a path, style (see
 Session), variation, locale and extension strings.

Classes in org.apache.wicket.util.resource.locator used by org.apache.wicket.settings

IResourceStreamLocator

          Interface for code that locates resources.

Classes in org.apache.wicket.util.resource.locator used by org.apache.wicket.settings.def

IResourceStreamLocator

          Interface for code that locates resources.

Classes in org.apache.wicket.util.resource.locator used by org.apache.wicket.util.resource.locator

ExtensionResourceNameIterator

          Iterate over a list of 'comma' separated strings.

IResourceStreamLocator

          Interface for code that locates resources.

LocaleResourceNameIterator

          Given a Locale it'll iterate over all possible combinations of the attrs making up the Locale.

ResourceNameIterator

          Contains the logic to locate a resource based on a path, style (see
 Session), variation, locale and extension strings.

ResourceStreamLocator

          Locate Wicket resource.

StyleAndVariationResourceNameIterator

          Iterate over all possible combinations of style and variation

Classes in org.apache.wicket.util.resource.locator used by org.apache.wicket.util.resource.locator.caching

IResourceStreamLocator

          Interface for code that locates resources.

ResourceNameIterator

          Contains the logic to locate a resource based on a path, style (see
 Session), variation, locale and extension strings.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2006-2012 Apache Software Foundation. All Rights Reserved.


text:
import urllib.request

url = 'http://zipcloud.ibsnet.co.jp/api/search?zipcode=7080824'
response = urllib.request.urlopen(url)
data = response.read().decode('utf-8')
# jsonfile = json.loads(html.read().decode('utf-8'))
# decoded_data = data.decode('shift_jis')
print (data)


text:
package org.yeshen.video.librtmp.unstable.net.sender.rtmp.io;

import org.yeshen.video.librtmp.unstable.net.sender.rtmp.packets.Chunk;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

/**
 * RTMPConnection's read thread
 *
 * @author francois, leo
 */
class ReadThread extends Thread {

    private RtmpDecoder rtmpDecoder;
    private InputStream in;
    private OnReadListener listener;
    private volatile boolean startFlag;

    ReadThread(InputStream in, SessionInfo sessionInfo) {
        this.in = in;
        this.rtmpDecoder = new RtmpDecoder(sessionInfo);
        startFlag = true;
    }

    void setOnReadListener(OnReadListener listener) {
        this.listener = listener;
    }

    @Override
    public void run() {
        while (startFlag) {
            try {
                Chunk chunk = rtmpDecoder.readPacket(in);
                if(chunk != null && listener != null) {
                    listener.onChunkRead(chunk);
                }
            } catch (EOFException e) {
                startFlag = false;
                if(listener != null) {
                    listener.onStreamEnd();
                }
            } catch (IOException e) {
                startFlag = false;
                if(listener != null) {
                    listener.onDisconnect();
                }
            }
        }
    }

    void shutdown() {
        listener = null;
        startFlag = false;
        this.interrupt();
    }

    void clearStoredChunks(int chunkStreamId) {
        rtmpDecoder.clearStoredChunks(chunkStreamId);
    }
}


text:
import marked from 'marked';
const renderer = new marked.Renderer();

export {
  renderer,
  marked
};


text:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;

using MahApps.Metro.Controls.Dialogs;
using MahApps.Metro.IconPacks;

using Microsoft.Extensions.DependencyInjection;

using Notifications.Wpf.Core;

using OSharp.CodeGeneration.Generates;
using OSharp.CodeGeneration.Services;
using OSharp.CodeGeneration.Services.Entities;
using OSharp.CodeGenerator.Data;
using OSharp.CodeGenerator.Views.Entities;
using OSharp.CodeGenerator.Views.Modules;
using OSharp.CodeGenerator.Views.Projects;
using OSharp.CodeGenerator.Views.Properties;
using OSharp.IO;
using OSharp.Wpf.Stylet;

using Stylet;

using Screen = Stylet.Screen;

namespace OSharp.CodeGenerator.Views
{
    [Singleton]
    public class MenuViewModel : Screen
    {
        private readonly IServiceProvider _provider;

        public MenuViewModel(IServiceProvider provider)
        {
            _provider = provider;
        }

        public ProjectViewModel Project { get; set; }

        public IObservableCollection<MenuItem> MenuItems { get; set; } = new BindableCollection<MenuItem>();

        public Screen SelectModel { get; set; }

        public void Init()
        {
            if (Project == null)
            {
                Helper.Notify("当前项目为空,请先通过菜单"项目-项目管理"加载项目", NotificationType.Error);
                return;
            }

            CodeProject[] projects = null;
            _provider.ExecuteScopedWork(provider =>
            {
                IDataContract contract = provider.GetRequiredService<IDataContract>();
                projects = contract.GetCodeProject(m => m.Name == Project.Name);
            });
            if (projects == null)
            {
                Helper.Notify($"名称为"{Project.Name}"的项目信息不存在", NotificationType.Error);
                return;
            }

            MenuItems.Clear();
            foreach (CodeProject project in projects)
            {
                MenuItems.Add(ToMenu(project));
            }
        }

        public void Select(RoutedPropertyChangedEventArgs<object> args)
        {
            if (args.NewValue is not MenuItem item)
            {
                return;
            }

            SelectModel = item.Screen;
            MainViewModel main = IoC.Get<MainViewModel>();
            main.ModuleList.IsShow = SelectModel is ProjectViewModel;
            main.EntityList.IsShow = SelectModel is ModuleViewModel;
            main.PropertyList.IsShow = SelectModel is EntityViewModel;
            switch (SelectModel)
            {
                case ProjectViewModel project:
                    ModuleListViewModel list1 = IoC.Get<ModuleListViewModel>();
                    list1.Project = project;
                    list1.Init();
                    break;
                case ModuleViewModel module:
                    EntityListViewModel list2 = IoC.Get<EntityListViewModel>();
                    list2.Module = module;
                    list2.Init();
                    break;
                case EntityViewModel entity:
                    PropertyListViewModel list3 = IoC.Get<PropertyListViewModel>();
                    list3.Entity = entity;
                    list3.Init();
                    break;
            }
        }

        public async void Generate()
        {
            if (Project == null)
            {
                Helper.Notify("当前项目为空,无法生成代码,请先通过菜单"项目-项目管理"加载项目", NotificationType.Error);
                return;
            }
            CodeProject project = null;
            CodeTemplate[] templates = Array.Empty<CodeTemplate>();
            _provider.ExecuteScopedWork(provider =>
            {
                IDataContract contract = provider.GetRequiredService<IDataContract>();
                project = contract.GetCodeProject(m => m.Name == Project.Name).FirstOrDefault();
                templates = contract.CodeProjectTemplates.Where(m => m.ProjectId == project.Id && !m.IsLocked && !m.Template.IsLocked).Select(m => m.Template).ToArray();
            });
            if (project == null)
            {
                Helper.Notify($"名称为"{Project.Name}"的项目信息不存在", NotificationType.Error);
                return;
            }

            if (templates.Length == 0)
            {
                Helper.Notify($"项目"{project.GetName()}"的模板数量为0,请先通过菜单"项目-项目模板管理"添加模板", NotificationType.Error);
                return;
            }

            CodeFile[] codeFiles = Array.Empty<CodeFile>();
            var progress = await Helper.Main.ShowProgressAsync("请稍候", "正在生成代码,请稍候");
            await Task.Run(async () =>
            {
                try
                {
                    ICodeGenerator generator = _provider.GetRequiredService<ICodeGenerator>();
                    codeFiles = await generator.GenerateCodes(templates, project);
                    await progress.CloseAsync();
                }
                catch (Exception ex)
                {
                    await progress.CloseAsync();
                    Helper.Notify($"代码生成失败:{ex.Message}", NotificationType.Error);
                }
            });
            SaveToFiles(codeFiles);
        }

        private void SaveToFiles(CodeFile[] codeFiles)
        {
            if (codeFiles.Length == 0)
            {
                Helper.Notify("生成的代码文件数量为0", NotificationType.Information);
                return;
            }
            string rootPath;
            if (string.IsNullOrEmpty(Project.RootPath) || !Path.IsPathFullyQualified(Project.RootPath))
            {
                FolderBrowserDialog dialog = new FolderBrowserDialog()
                {
                    UseDescriptionForTitle = true,
                    Description = $"项目"{Project.Name}({Project.NamespacePrefix})"生成了{codeFiles.Length}个代码文件,请选择保存文件夹:",
                    RootFolder = Environment.SpecialFolder.MyDocuments,
                    ShowNewFolderButton = true
                };

                DialogResult result = dialog.ShowDialog();
                if (result == DialogResult.OK)
                {
                    rootPath = dialog.SelectedPath;
                }
                else
                {
                    return;
                }
            }
            else
            {
                rootPath = Project.RootPath;
                DirectoryHelper.CreateIfNotExists(rootPath);
            }

            foreach (CodeFile codeFile in codeFiles)
            {
                if (codeFile.SaveToFile(rootPath))
                {
                    Helper.Output($"代码文件:{codeFile.FileName} 保存成功");
                }
            }
            Helper.Output($"项目"{Project.Name}"代码生成成功,输出{codeFiles.Length}个文件");
            Helper.Notify($"{codeFiles.Length}个代码文件已输出到:{rootPath}", NotificationType.Success, null, () => Helper.OpenFolder(rootPath));
        }

        private MenuItem ToMenu(CodeProject project)
        {
            MenuItem projectMenu = _provider.GetRequiredService<MenuItem>();
            projectMenu.Id = project.Id;
            projectMenu.Text = $"{project.Name}[{project.NamespacePrefix}]";
            projectMenu.Type = MenuItemType.Project;
            projectMenu.Icon = PackIconMaterialKind.AlphaPBoxOutline;
            ProjectViewModel projectModel = project.ToViewModel();
            projectMenu.Screen = projectModel;
            foreach (CodeModule module in project.Modules)
            {
                MenuItem moduleMenu = _provider.GetRequiredService<MenuItem>();
                moduleMenu.Id = module.Id;
                moduleMenu.Text = $"{module.Display}[{module.Name}]";
                moduleMenu.Type = MenuItemType.Module;
                moduleMenu.Icon = PackIconMaterialKind.AlphaMBoxOutline;
                ModuleViewModel moduleModel = module.ToViewModel(projectModel);
                moduleMenu.Screen = moduleModel;
                foreach (CodeEntity entity in module.Entities)
                {
                    MenuItem entityMenu = _provider.GetRequiredService<MenuItem>();
                    entityMenu.Id = entity.Id;
                    entityMenu.Text = $"{entity.Display}[{entity.Name}]";
                    entityMenu.Type = MenuItemType.Entity;
                    entityMenu.Icon = PackIconMaterialKind.AlphaEBoxOutline;
                    EntityViewModel entityModel = entity.ToViewModel(moduleModel);
                    entityMenu.Screen = entityModel;
                    moduleMenu.ItemMenus.Add(entityMenu);
                }
                projectMenu.ItemMenus.Add(moduleMenu);
            }

            return projectMenu;
        }
    }

    public class MenuItem : Screen
    {
        public Guid Id { get; set; }

        /// <summary>
        /// 获取或设置 显示
        /// </summary>
        public string Text { get; set; }

        /// <summary>
        /// 获取或设置 图标
        /// </summary>
        public PackIconMaterialKind Icon { get; set; }

        /// <summary>
        /// 获取或设置 节点类型
        /// </summary>
        public MenuItemType Type { get; set; }

        /// <summary>
        /// 获取或设置 当前关联视图模型
        /// </summary>
        public Screen Screen { get; set; }

        /// <summary>
        /// 获取或设置 子节点集合
        /// </summary>
        public IObservableCollection<MenuItem> ItemMenus { get; set; } = new BindableCollection<MenuItem>();
    }

    public enum MenuItemType
    {
        Project,

        Module,

        Entity,

        Property
    }
}


text:
package gq.baijie.voicebroadcastdevice.entity;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

import gq.baijie.voicebroadcastdevice.storage.database.Contract;

import static gq.baijie.voicebroadcastdevice.storage.database.Contract.PATH_CATEGORY;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.PATH_SOUND;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.PATH_SOUND_CATEGORY;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.SoundCategory.COLUMN_CATEGORY_ID;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.SoundCategory.COLUMN_ORDER_IN_CATEGORY;
import static gq.baijie.voicebroadcastdevice.storage.database.Contract.SoundCategory.COLUMN_SOUND_ID;

// unique indexes are created in DatabaseHelper
@DatabaseTable(tableName = PATH_SOUND_CATEGORY)
public class SoundCategory {

    @DatabaseField(columnName = COLUMN_SOUND_ID,
            foreign = true, columnDefinition = "INTEGER REFERENCES "
            + PATH_SOUND + "(" + Contract.Sound._ID + ") ON DELETE CASCADE ON UPDATE CASCADE")
    private Sound mSound;

    @DatabaseField(columnName = COLUMN_CATEGORY_ID,
            foreign = true, columnDefinition = "INTEGER REFERENCES "
            + PATH_CATEGORY + "(" + Contract.Category._ID + ") ON DELETE CASCADE ON UPDATE CASCADE")
    private Category mCategory;

    @DatabaseField(columnName = COLUMN_ORDER_IN_CATEGORY)
    private long mOrderInCategory;

    public Sound getSound() {
        return mSound;
    }

    public SoundCategory setSound(Sound sound) {
        mSound = sound;
        return this;
    }

    public Category getCategory() {
        return mCategory;
    }

    public SoundCategory setCategory(Category category) {
        mCategory = category;
        return this;
    }

    public long getOrderInCategory() {
        return mOrderInCategory;
    }

    public SoundCategory setOrderInCategory(long orderInCategory) {
        mOrderInCategory = orderInCategory;
        return this;
    }
}


text:
<!DOCTYPE html>

  <title>Wryter</title>

  <link rel="import" href="assets/components/core-toolbar/core-toolbar.html">
  <link rel="import" href="assets/components/core-menu/core-menu.html">
  <link rel="import" href="assets/components/core-item/core-item.html">
  <link rel="import" href="assets/components/core-header-panel/core-header-panel.html">
  <link rel="import" href="assets/components/core-drawer-panel/core-drawer-panel.html">
  <link rel="import" href="assets/components/core-icons/core-icons.html">
  <link rel="import" href="assets/components/paper-icon-button/paper-icon-button.html">

  <link rel="stylesheet" href="assets/css/medium-editor.min.css">
  <link rel="stylesheet" href="assets/css/themes/flat.css">
  <link rel="stylesheet" href="assets/css/styles.css">

<core-drawer-panel id="drawerPanel" responsiveWidth="9999px">
  <core-header-panel drawer>
    <core-toolbar id="navheader'">
      Wryter
    </core-toolbar>
    <core-menu>
      <core-item label="">{{main.title}}</core-item>
      <core-item label="Saved"></core-item>
    </core-menu>
   </core-header-panel>

  <core-header-panel main>
    <core-toolbar id="mainheader">
      <paper-icon-button
        id="navicon" icon="menu"></paper-icon-button>

    </core-toolbar>

        Supports Sync File System: {{main.supportSFS}}

  </core-header-panel>

</core-drawer-panel>


text:
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateArticleRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
          'title'=>'required|min:3|max:20',
          'body'=>'required',
          'published_at'=>'required|date',
        ];
    }
}


text:
<img src="https://cdn.rawgit.com/undefinedio/stash/develop/web/app/themes/stash/src/images/STASH-logo.svg" width="250">

=======
# STASH

Badges         | -
-------------  | -------------
Scrutinizer    | [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/undefinedio/stash/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/undefinedio/stash/?branch=master)
Composer       | [![Dependency Status](https://www.versioneye.com/user/projects/55dd7d7f8d9c4b00180009eb/badge.svg?style=flat)](https://www.versioneye.com/user/projects/55dd7d7f8d9c4b00180009eb)
NPM            | [![Dependency Status](https://www.versioneye.com/user/projects/55dd7d628d9c4b001b0009dc/badge.svg?style=flat)](https://www.versioneye.com/user/projects/55dd7d628d9c4b001b0009dc)
Bower          | [![Dependency Status](https://www.versioneye.com/user/projects/55dd7d5a8d9c4b001b0009d9/badge.svg?style=flat)](https://www.versioneye.com/user/projects/55dd7d5a8d9c4b001b0009d9)
Ruby           | [![Dependency Status](https://www.versioneye.com/user/projects/55dd7d5e8d9c4b00180009e4/badge.svg?style=flat)](https://www.versioneye.com/user/projects/55dd7d5e8d9c4b00180009e4)

## Requirements
* PHP >= 5.4
* Composer [Install](https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx)
* Ruby >= 1.9 [Install](https://www.ruby-lang.org/en/documentation/installation/)
* Bundler `gem install bundler`
* node & NPM [Install](https://nodejs.org/download/)
* Gulp global `npm install gulp -g`

## Manual Installation
1. Clone the git repo - `git clone https://github.com/undefinedio/stash.git`
2. Run `composer install`
3. Copy `.env.example` to `.env` and update environment variables
4. Set your site vhost document root to `/path/to/site/web/` (`/path/to/site/current/web/` if using deploys)
5. run `npm install`
5. run `gulp`

## Automated installation
1. Clone the git repo - `git clone https://github.com/undefinedio/stash.git`
2. Run `composer install`
2. Run `node ./bin/setup.js`

## To use ACF pro
1. Replace `$yourkeyhere` in composer.json with your own ACF key
2. run `composer require advanced-custom-fields/advanced-custom-fields-pro`