text:
(function() {

  'use strict';

  angular.module('monthlyBudget')
    .controller('homeCtrl', homeCtrl);

  homeCtrl.$inject = ['budgetService', 'Popeye'];

  function homeCtrl(budgetService, Popeye) {
    var vm = this;

    vm.addExpense = addExpense;
    vm.budgets = [];
    vm.expenses = [];
    vm.calcTotExpense = calcTotExpense;
    vm.calcPercUsed = calcPercUsed;
    vm.createBudget = createBudget;
    vm.deleteBudget = deleteBudget;
    vm.getBudget = getBudget;
    vm.listExpenses = listExpenses;
    vm.listMyBudgets = listMyBudgets;
    vm.openNewBudgetModal = openNewBudgetModal;
    vm.openNewExpenseModal = openNewExpenseModal;
    vm.selectedBudget = {};

    ///////////////////////////////////////////

    init();

    ///////////////////////////////////////////

    function init() {
      listMyBudgets();
    }

    function createBudget(name, amount, timeStart, timeEnd) {
      budgetService.create(name, amount, timeStart, timeEnd)
        .then(function(res) {
          console.log(res);
        })
        .catch(function(err) {
          console.log(err);
        });
    }

    function getBudget(id) {
      budgetService.get(id)
        .then(function(res) {
          console.log(res);
        })
        .catch(function(err) {
          console.log(err);
        });
    }

    function addExpense(expName, expAmount, expDate, expBudget, expCat, expNote) {
      budgetService.addExpense(expName, expAmount, expDate, expBudget, expCat, expNote)
        .then(function(res) {
          console.log(res);
        })
        .catch(function(err) {
          console.log(err);
        });
    }

    function deleteBudget(budgId) {
      budgetService.update(budgId, new Date())
        .then(function(res) {
          console.log(res);
        })
        .catch(function(err) {
          console.log(err);
        });
    }

    function listMyBudgets() {
      budgetService.getAll()
        .then(function(res) {
          vm.budgets = res.data;
        })
        .catch(function(err) {
          console.log(err);
        });
    }

    function listExpenses(budget) {
      vm.expenses = budget.expenses;
      vm.selectedBudget = budget;
    }

    function calcTotExpense(budget) {
      budget.expenses = budget.expenses || [];
      var totExpense = budget.expenses
        .map(function(exp) {
          return exp.amount;
        })
        .reduce(function(a, b) {
          return a + b;
        },0);

      return totExpense;
    }

    function calcPercUsed(budget) {
      var percUsed = calcTotExpense(budget) / budget.amount * 100;
      return percUsed;
    }

    function openNewBudgetModal() {
      var modal = Popeye.openModal({
        templateUrl: '/dist/html/newBudgetModal/newBudgetModal.html',
        controller: 'newBudgetModalCtrl as budgetModal'
      });
      modal.closed.then(function(res) {
        if (res.name){
          vm.budgets.unshift(res);
        }
      });
    }

    function openNewExpenseModal(){
      if (!vm.selectedBudget._id){
        return;
      }
      var modal = Popeye.openModal({
        templateUrl: '/dist/html/newExpenseModal/newExpenseModal.html',
        controller: 'newExpenseModalCtrl as expenseModal',
        locals: {
          selectedBudget: vm.selectedBudget
        }
      });
      modal.closed.then(function(res) {
        if (res.name){
          vm.selectedBudget.expenses.unshift(res);
        }
      });
    }
  }

})();


text:
'''
This file is part of LIO(tm).

Copyright (c) 2012-2014 by Datera, Inc.
More information on www.datera.io.

Original author: Jerome Martin <jxm@netiant.com>

Datera and LIO are trademarks of Datera, Inc., which may be registered in some
jurisdictions.

Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
'''
import pyparsing as pp
import sys, tty, cmd, termios, readline, traceback

import rtslib.config, rtslib.config_tree
from targetcli.cli_logger import logger as log
from rtslib.config import ConfigError

# TODO Implement | filters: top N, last N, page, grep
# TODO Redo help summary, using 2 columns: cmd, short description

class CliError(Exception):
    pass

class Cli(cmd.Cmd):
    '''
    Our base Cli class, common to both CliLive and CliConfig
    '''
    intro = ''
    log_levels = {'debug': 10, 'info': 20, 'warning': 30,
                  'error': 40, 'critical': 50}

    def __init__(self, interactive, history_path):
        '''
        Initializes a new Cli object.

        interactive is a boolean to run either interactively or in batch mode
        history_path is the path to the command-line history file
        '''
        cmd.Cmd.__init__(self)
        self.debug_level = 'off'
        self.last_traceback = None
        self.interactive = interactive
        self.do_save_history = self.interactive
        if self.interactive:
            self.load_history()
        readline.set_completer_delims(' \t\n`~!@#$%^&*()=+[{]}\\|;\'",<>/?')

    def do_EOF(self, options):
        sys.stdout.write("exit\n")
        return self.do_exit(options)

    def _complete_options(self, text, line, begidx, endidx, options):
        '''
        Helper to autocomplete one or more options out of options, without any
        ordering considerations.
        '''
        # TODO Add middle-of-line completion
        prev_options = line.split()[1:]
        if text:
            prev_options = prev_options[:-1]
        return ["%s " % name for name in options
                if name.startswith(text)
                if name.strip() not in prev_options]

    def _complete_one_option(self, text, line, begidx, endidx, options):
        '''
        Helper to autocomplete a single option out of options.
        '''
        # TODO Add middle-of-line completion
        prev_options = line.split()[1:]
        if text:
            prev_options = prev_options[:-1]
        return ["%s " % name for name in options
                if name.startswith(text)
                if not prev_options]

    def _complete_path(self, text, line, begidx, endidx, prefix=None):
        '''
        Helper to autocomplete a configuration path.
        '''
        # TODO Add middle-of-line completion
        pattern = line.partition(' ')[2]
        if prefix is None:
            prefix = ''

        # Are we completing an attr/obj value/id or a group?
        nodes_last_key = self.config.search(("%s %s.*"
                                             % (prefix, pattern)).strip())
        # Or an attr/obj name/class ?
        nodes_first_key = [node for node
                           in self.config.search(("%s %s.* .*"
                                                 % (prefix, pattern)).strip())
                           if node.data['type'] != 'group']
        completions = []
        completions.extend(node.key[-1] for node in nodes_last_key)
        completions.extend(node.key[0] for node in nodes_first_key)
        return ["%s " % c for c in completions if c.startswith(text)]

    def _complete_filepath(self, text, line, begidx, endidx):
        '''
        Helper to autocomplete file paths.
        '''
        # TODO Implement this
        return []

    def save_history(self):
        '''
        Saves the command history.
        '''
        if not self.do_save_history:
            return
        try:
            readline.write_history_file(self.history_path)
        except Exception, e:
            raise CliError("Failed to save command history, disabling: %s", e)
            self.do_save_history = False

    def load_history(self):
        '''
        Loads the command history.
        '''
        try:
            readline.read_history_file(self.history_path)
        except IOError, e:
            log.debug("Error while reading history: %s" % e)

    def clear_history(self):
        '''
        Clears the command history.
        '''
        readline.clear_history()

    def emptyline(self):
        '''
        Just go on with a new prompt line if the user enters an empty line.
        '''
        pass

    def cmdloop(self):
        '''
        The main REPL loop.
        '''
        intro = self.intro
        while True:
            try:
                cmd.Cmd.cmdloop(self, intro=intro)
            except KeyboardInterrupt:
                sys.stdout.write("^C\n")
                intro = ''
            else:
                break

    def onecmd(self, line):
        '''
        Executes a command line.
        '''
        try:
            result = cmd.Cmd.onecmd(self, line)
        except pp.ParseException, e:
            log.error("Unknown syntax: %s at char %d" % (e.msg, e.loc))
            return None
        except ConfigError, e:
            self.last_traceback = traceback.format_exc()
            log.error(str(e))
        except CliError, e:
            self.last_traceback = traceback.format_exc()
            log.error(str(e))
        except Exception, e:
            self.last_traceback = traceback.format_exc()
            log.error("%s: %s\n" % (e.__class__.__name__, e))
            return None
        else:
            self.save_history()
            return result

    def completenames(self, text, *ignored):
        return ["%s " % name[3:] for name in self.get_names()
                if name.startswith("do_%s" % text)
                if not name in ['do_EOF']]

    def getchar(self):
        '''
        Returns the first character read from stdin, without waiting for the
        user to hit enter.
        '''
        fd = sys.stdin.fileno()
        tcattr_backup = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            char = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, tcattr_backup)
            return char

    def yes_no(self, question, default=None):
        '''
        Asks a yes/no question to be answered by typing a single 'y' or 'n'
        character. If we do not run in interactive mode, returns None. Else
        returns True for yes and False for not.

        default can either be True (yes is the default), False (no is the
        default) or None (no default).
        '''
        keys = {'\x03': '^C', '\x04': '^D'}
        if not self.interactive:
            result = None
        else:
            if default is None:
                choices = "y/n"
            elif default is True:
                choices = "Y/n"
                dfl_key = 'y'
            elif default is False:
                choices = "y/N"
                dfl_key = 'n'
            key = None
            replies = ['y', 'n', 'Y', 'N']
            if default is not None:
                replies.append('\r')
            while key not in replies:
                log.debug("Got key %r" % key)
                sys.stdout.write("%s [%s] " % (question, choices))
                key = self.getchar()
                key = keys.get(key, key)
                if key == '\r' and default is not None:
                    sys.stdout.write("%s\n" % dfl_key)
                else:
                    sys.stdout.write("%s\n" % key)
                if key in ['^C', '^D']:
                    raise CliError("Aborted")
            if key == '\r':
                result = default
            elif key.lower() == 'y':
                result = True
            else:
                result = False

        log.debug("yes_no(%s) -> %r" % (question, result))
        return result

    def parse(self, line, header, grammar):
        '''
        Parses line using a pyparsing grammar.
        Returns the parse tree as a list.
        '''
        if not grammar:
            grammar = pp.Empty()
        grammar = pp.Literal(header) + grammar
        line = "%s %s" % (header, line)
        log.debug("Parsing line '%s'" % line)
        tokens = grammar.parseString(line, parseAll=True).asList()
        log.debug("Got parse tree %s" % tokens)
        return tokens

    def do_trace(self, options):
        '''
        trace

        Displays the last exception trace for the current mode.

        This is useful only for debugging the application. Your lio support
        team might ask you to run this command to help understanding an issue
        you're experimenting.
        '''
        options = self.parse(options, 'trace', '')[1:]
        if self.last_traceback is not None:
            log.error(self.last_traceback)
        else:
            log.error("No previous exception traceback.")

    def do_debug(self, options):
        '''
        debug [off|cli|api|all]

        Controls the debug messages level:

            off disables all debug message
            cli enables only cli debug messages
            api also enables Config API messages
            all adds even more details to api debug

        With no option, displays the current debug level.
        '''
        syntax = pp.Optional(pp.oneOf(["off", "cli", "api", "all"]))
        options = self.parse(options, 'debug', syntax)[1:]

        if not options:
            log.info("Current debug level: %s" % self.debug_level)
        else:
            self.debug_level = options[0]
            if self.debug_level == 'off':
                log.setLevel(self.log_levels['info'])
                rtslib.config.log.setLevel(self.log_levels['info'])
                rtslib.config_tree.log.setLevel(self.log_levels['info'])
            elif self.debug_level == 'cli':
                log.setLevel(self.log_levels['debug'])
                rtslib.config.log.setLevel(self.log_levels['info'])
                rtslib.config_tree.log.setLevel(self.log_levels['info'])
            elif self.debug_level == 'api':
                log.setLevel(self.log_levels['debug'])
                rtslib.config.log.setLevel(self.log_levels['debug'])
                rtslib.config_tree.log.setLevel(self.log_levels['info'])
            elif self.debug_level == 'all':
                log.setLevel(self.log_levels['debug'])
                rtslib.config.log.setLevel(self.log_levels['debug'])
                rtslib.config_tree.log.setLevel(self.log_levels['debug'])

            log.info("Debug level is now: %s" % self.debug_level)

    def complete_debug(self, text, line, begidx, endidx):
        return self._complete_one_option(text, line, begidx, endidx,
                                         ["off", "cli", "api", "all"])

redpajama_set_name: RedPajamaGithub


text:
class Event:

    def __init__(self, publisher_id, event_type, event_body):
        self.publisher_id = publisher_id
        self.event_type = event_type
        self.body = event_body

    @classmethod
    def create_from_packed(cls, packed):
        return cls(*packed)

    def packed_object(self):
        body = self.body
        if hasattr(body, "packed_object"):
            body = self.body.packed_object()
        return (self.publisher_id, self.event_type, body)


text:
<!DOCTYPE HTML>

    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>PhoneGap</title>
    <link rel="stylesheet" href="../master.css" type="text/css" media="screen" title="no title" charset="utf-8">

Acceleration

Stopped

X:

Y:

Z:

Action

    Get Acceleration
    Start Watch
    Clear Watch

&nbsp
Back


text:
package edu.harvard.iq.dataverse.authorization.providers.builtin;

import edu.harvard.iq.dataverse.ValidateEmail;
import edu.harvard.iq.dataverse.authorization.AuthenticatedUserDisplayInfo;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotBlank;

/**
 *
 * @author xyang
 * @author mbarsinai
 */
@NamedQueries({
		@NamedQuery( name="BuiltinUser.findAll",
				query = "SELECT u FROM BuiltinUser u ORDER BY u.lastName"),
		@NamedQuery( name="BuiltinUser.findByUserName",
				query = "SELECT u FROM BuiltinUser u WHERE u.userName=:userName"),
		@NamedQuery( name="BuiltinUser.findByEmail",
				query = "SELECT o FROM BuiltinUser o WHERE LOWER(o.email) = LOWER(:email)"),
		@NamedQuery( name="BuiltinUser.listByUserNameLike",
				query = "SELECT u FROM BuiltinUser u WHERE u.userName LIKE :userNameLike")
})
@Entity
@Table(indexes = {@Index(columnList="lastName")})  // for sorting the NamedQuery BuiltinUser.findAll
public class BuiltinUser implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Please enter a username.")
    @Size(min=2, max=60, message ="Username must be between 2 and 60 characters.")
    @Pattern(regexp = "[a-zA-Z0-9\\_\\-\\.]*", message = "Found an illegal character(s). Valid characters are a-Z, 0-9, '_', '-', and '.'.")
    @Column(nullable = false, unique=true)
    private String userName;

    @NotBlank(message = "Please enter a valid email address.")
    @ValidateEmail(message = "Please enter a valid email address.")
    @Column(nullable = false, unique=true)
    private String email;

    @NotBlank(message = "Please enter your first name.")
    private String firstName;

    @NotBlank(message = "Please enter your last name.")
    private String lastName;

    private int passwordEncryptionVersion;
    private String encryptedPassword;
    private String affiliation;
    private String position;

    public void updateEncryptedPassword( String encryptedPassword, int algorithmVersion ) {
        setEncryptedPassword(encryptedPassword);
        setPasswordEncryptionVersion(algorithmVersion);
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEncryptedPassword() {
        return encryptedPassword;
    }

    /**
     * JPA-use only. Humans should call {@link #updateEncryptedPassword(java.lang.String, int)}
     * and update the password and the algorithm at the same time.
     *
     * @param encryptedPassword
     * @deprecated
     */
    @Deprecated()
    public void setEncryptedPassword(String encryptedPassword) {
        this.encryptedPassword = encryptedPassword;
    }

    public String getAffiliation() {
        return affiliation;
    }

    public void setAffiliation(String affiliation) {
        this.affiliation = affiliation;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public String getDisplayName(){
        return this.getFirstName() + " " + this.getLastName();
    }

    public AuthenticatedUserDisplayInfo getDisplayInfo() {
        return new AuthenticatedUserDisplayInfo(getFirstName(), getLastName(), getEmail(), getAffiliation(), getPosition() );
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        if (!(object instanceof BuiltinUser)) {
            return false;
        }
        BuiltinUser other = (BuiltinUser) object;
        return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)));
    }

	@Override
	public String toString() {
		return "BuiltinUser{" + "id=" + id + ", userName=" + userName + ", email=" + email + '}';
	}

    public int getPasswordEncryptionVersion() {
        return passwordEncryptionVersion;
    }

    public void setPasswordEncryptionVersion(int passwordEncryptionVersion) {
        this.passwordEncryptionVersion = passwordEncryptionVersion;
    }

}


text:
package Package;

import java.lang.Thread;

public class Timer extends Thread {
	public static volatile int x = 0;
	public volatile boolean isRunning;
	private static String str;
	private volatile int delayValue = 1000;
	private volatile int totalMinutes = 0;
	private volatile int totalHours = 0;
	private volatile int totalDays = 0;
	private volatile int totalWeeks = 0;
	private volatile int totalYears = 0; // I'm sorry, God
	private volatile int mins = 0;
	private volatile int hrs = 0;
	private volatile int days = 0;
	private volatile int wks = 0;
	private volatile int yrs = 0;
	private volatile int secs = 0;

	/**
	 * The Timer class counts either up or down one integer per second in the
	 * background of any given program. Users can also set the timer to any
	 * value at any time. Time is counted both linearly and separately in years,
	 * weeks, days, hours, minutes, and seconds. Currently does not account for
	 * leap days/leap seconds because that would require more work. See specific
	 * method documentation for more info.
	 *
	 * @author github.com/MeanMrMustard42
	 * @version 1.1
	 * @since 2017-4-8, JDK 8
	 */

	/**
	 * Counts up from set number (default is 0) one second at a time until stop
	 * command is true or max value is reached.
	 *
	 * @throws InterruptedException
	 */

	public Timer(String str2) {
		str = str2;

	}

	@Override
	public void run() {
		if (str.equals("increment")) {
			try {
				isRunning = true;
				increment();
			} catch (InterruptedException e) {
				System.out.print("Error: Thread interrupted. Timer unexpectedly disabled. ");
				e.printStackTrace();
			}
		} else if (str.toLowerCase().equals("decrement")) {
			try {
				isRunning = true;
				decrement();
			} catch (InterruptedException e) {
				System.out.print("Error: Thread interrupted. Timer unexpectedly disabled. ");
				e.printStackTrace();
			}
		}

	}

	private void updateTotalTime() {
		if (x == 60 || x % 60 == 0) {
			++totalMinutes;
		}
		if (totalMinutes == 60 || totalMinutes % 60 == 0) {
			++totalHours;
		}
		if (totalHours == 24 || totalHours % 24 == 0) {
			++totalDays;
		}
		if (totalDays == 7 || totalDays % 7 == 0) {
			++totalWeeks;
		}
		if (totalWeeks == 52 || totalWeeks % 52 == 0) {
			++totalYears;
		}
	}

	private void updateLinearTime() {
		if (secs == 60) {
			++mins;
			secs = 0; // my life story
		}
		if (mins == 60) {
			++hrs;
			mins = 0;
		}
		if (hrs == 24) {
			++days;
			hrs = 0;
		}
		if (days == 7) {
			++wks;
			days = 0;
		}
		if (wks == 52) {
			++yrs;
			wks = 0;
		}

	}

	private void increment() throws InterruptedException {
		while (x < Integer.MAX_VALUE && isRunning) {
			++x;
			++secs;
			updateTotalTime();
			updateLinearTime();
			System.out.println(x);
			Thread.sleep(delayValue);

		}

		// while(!isRunning) {
		// if(isRunning) {
		// increment();
		// }
	}

	/**
	 * Counts down from set number (default is 0) one second at a time until
	 * stop command is true or min value is reached. Users will have to use the
	 * preset the timer using the set() function in order to avoid the counter
	 * reaching the negatives.
	 *
	 * @throws InterruptedException
	 */
	private void decrement() throws InterruptedException {
		while (x > Integer.MIN_VALUE && isRunning) {
			--x;
			updateTotalTime();
			updateLinearTime();
			// totalDays/totalHours/min could return negative if values are not
			// pre-set with set()
			// It's not a bug, it's a feature. I swear.
			Thread.sleep(delayValue);
		}
	}

	/**
	 * Sets boolean to true which disables timer. However timer value will
	 * remain the same.
	 */
	public void disable() {
		delayValue = Integer.MAX_VALUE; // I promise this'll be fixed someday
		System.out.println("Timer disabled successfully");

	}

	/**
	 * Enables timer by setting isRunning to true. Directly calling
	 * timer.start() again would only create an IllegalThreadStateException.
	 */
	public void enable() {
		delayValue = 1000; // this will also be eventually fixed
		System.out.println("Timer enabled successfully. I don't think this'll work though.");
	}

	/**
	 * Resets timer to it's default value of 0, does not stop timer however
	 */
	public void reset() {
		x = 0;
	}

	/**
	 * delays timer by desired amount of milliseconds before returning to
	 * 1-second default
	 *
	 * @param millis
	 * @throws InterruptedException
	 */
	public void delay(int millis) throws InterruptedException {
		delayValue = millis;
		Thread.sleep(1000);
		delayValue = 1000;
	}

/// ****************************Getters/Setters for time values************************\\\
	/*
	 * TO BE CLEAR: Total(x) values return the total amount of time in that time
	 * form ex: getTotalHours may return 48, while getHrs() will return 0
	 * (because it has already hit 24 hours at that point). getX returns amount
	 * of time in linear form (ex. 1 day, 3 hours, and 2 mins). This makes sense
	 * trust me
	 */
	/**
	 * @return the x
	 */
	public static int get() {
		return x;
	}

	/**
	 * @param x
	 *            the x to set
	 */
	public static void set(int x) {
		Timer.x = x;
	}

	/**
	 * @return the count direction (increment or decrement)
	 */
	public static String getCountDirection() {
		return str;
	}

	/**
	 * @param the
	 *            specified count direction ("increment" or "decrement").
	 */
	public static void setCountDirection(String str) {
		Timer.str = str;
	}

	/**
	 * @return the delayValue
	 */
	public int getDelayValue() {
		return delayValue;
	}

	/**
	 * @param delayValue
	 *            the delayValue to set
	 */
	public void setDelayValue(int delayValue) {
		this.delayValue = delayValue;
	}

	/**
	 * @return the totalMinutes
	 */
	public int getTotalMinutes() {
		return totalMinutes;
	}

	/**
	 * @param totalMinutes
	 *            the totalMinutes to set
	 */
	public void setTotalMinutes(int totalMinutes) {
		this.totalMinutes = totalMinutes;
	}

	/**
	 * @return the totalHours
	 */
	public int getTotalHours() {
		return totalHours;
	}

	/**
	 * @param totalHours
	 *            the totalHours to set
	 */
	public void setTotalHours(int totalHours) {
		this.totalHours = totalHours;
	}

	/**
	 * @return the totalDays
	 */
	public int getTotalDays() {
		return totalDays;
	}

	/**
	 * @param totalDays
	 *            the totalDays to set
	 */
	public void setTotalDays(int totalDays) {
		this.totalDays = totalDays;
	}

	/**
	 * @return the totalWeeks
	 */
	public int getTotalWeeks() {
		return totalWeeks;
	}

	/**
	 * @param totalWeeks
	 *            the totalWeeks to set
	 */
	public void setTotalWeeks(int totalWeeks) {
		this.totalWeeks = totalWeeks;
	}

	/**
	 * @return the totalYears
	 */
	public int getTotalYears() {
		return totalYears;
	}

	/**
	 * @param totalYears
	 *            the totalYears to set
	 */
	public void setTotalYears(int totalYears) {
		this.totalYears = totalYears;
	}

	/**
	 * @return the mins
	 */
	public int getMinutes() {
		return mins;
	}

	/**
	 * @param mins
	 *            the mins to set
	 */
	public void setMinutes(int mins) {
		this.mins = mins;
	}

	/**
	 * @return the hrs
	 */
	public int getHours() {
		return hrs;
	}

	/**
	 * @param hrs
	 *            the hrs to set
	 */
	public void setHours(int hrs) {
		this.hrs = hrs;
	}

	/**
	 * @return the days
	 */
	public int getDays() { // Automation is beautiful
		return days;
	}

	/**
	 * @param days
	 *            the days to set
	 */
	public void setDays(int days) {
		this.days = days;
	}

	/**
	 * @return the wks
	 */
	public int getWeeks() {
		return wks;
	}

	/**
	 * @param wks
	 *            the wks to set
	 */
	public void setWeeks(int wks) {
		this.wks = wks;
	}

	/**
	 * @return the yrs
	 */
	public int getYears() {
		return yrs;
	}

	/**
	 * @param yrs
	 *            the yrs to set
	 */
	public void setYears(int yrs) {
		this.yrs = yrs;
	}

	/**
	 * @return the secs
	 */
	public int getSecs() { // huehuehue
		return secs;
	}

	/**
	 * @param secs
	 *            the secs to set
	 */
	public void setSecs(int secs) {
		this.secs = secs;
	}

	public String getTotalTime() {
		return "Timer has run for " + totalYears + " years, or " + totalWeeks + " weeks, " + totalDays + "days, or " + totalHours + " hours, " + totalMinutes
				+ " minutes, or " + x + " seconds in total.";
	}
     public boolean isAtZero() {
         if (x == 0) {
          return true;
           } else {
            return false;
     》    }
	     }
/// ***********************************************************************************\\\

	public String toString() {
		return "Timer has run for " + yrs + " years, " + wks + " weeks, " + days + " days, " + hrs + " hours, " + mins
				+ " minutes, and " + secs + " seconds.";

	}
}

// dank kush


text:
Shindo.tests("Fog::Compute[:openstack] | security_group", ['openstack']) do
  tests('success') do
    begin
      fog = Fog::Compute[:openstack]

      security_group = fog.security_groups.create(
        :name        => 'my_group',
        :description => 'my group'
      )

      tests('#create').succeeds do
        security_group = fog.security_groups.create(
          :name        => 'my_group',
          :description => 'my group'
        )

        returns('my_group') { security_group.name }
        returns('my group') { security_group.description }
        returns([])         { security_group.security_group_rules }
        returns(true, "Tenant Id is not nil")       { security_group.tenant_id != nil }
      end

      tests('#rules').succeeds do
        tests("#create").succeeds do
          rules_count = security_group.security_group_rules.count
          rule        = security_group.security_group_rules.create(
            :parent_group_id => security_group.id,
            :ip_protocol     => 'tcp',
            :from_port       => 1234,
            :to_port         => 1234,
            :ip_range        => { "cidr" => "0.0.0.0/0" }
          )
          returns(true, "added security group rule") { security_group.security_group_rules.count == (rules_count + 1) }
          security_group_rule = security_group.security_group_rules.find { |r| r.id == rule.id }
          returns(true, "security group rule has rule attributes") { security_group_rule.attributes == rule.attributes }
        end

        tests("#destroy").succeeds do
          rule        = security_group.security_group_rules.create(
            :parent_group_id => security_group.id,
            :ip_protocol     => 'tcp',
            :from_port       => 1234,
            :to_port         => 1234,
            :ip_range        => { "cidr" => "0.0.0.0/0" }
          )
          rule.destroy
          returns(true, "successfully destroyed rule") { rule.reload == nil }
        end
      end
    ensure
      security_group.destroy if security_group
    end
  end
end


text:
using System;
using SIPSorcery.Sys;
using log4net;

namespace SIPSorcery.SIP.App
{
    /// <remarks>
    /// A To tag MUST be set on all non 100 Trying responses, see RFC 3261 "8.2.6.2 Headers and Tags".
    /// </remarks>
    public class SIPServerUserAgent : ISIPServerUserAgent
    {
        private static ILog logger = AppState.logger;

        private SIPMonitorLogDelegate Log_External = (e) => { }; //SIPMonitorEvent.DefaultSIPMonitorLogger;
        private SIPAuthenticateRequestDelegate SIPAuthenticateRequest_External;
        private SIPAssetGetDelegate<SIPAccount> GetSIPAccount_External;

        private SIPTransport m_sipTransport;
        private UASInviteTransaction m_uasTransaction;
        private SIPEndPoint m_outboundProxy;                   // If the system needs to use an outbound proxy for every request this will be set and overrides any user supplied values.
        private SIPDialogue m_sipDialogue;
        private bool m_isAuthenticated;
        private bool m_isCancelled;
        private string m_owner;
        private string m_adminMemberId;
        private string m_sipUsername;
        private string m_sipDomain;
        private SIPCallDirection m_sipCallDirection;
        public bool IsB2B { get { return false; } }
        public bool IsInvite
        {
            get { return true; }
        }
        public string Owner { get { return m_owner; } }

        public SIPCallDirection CallDirection
        {
            get { return m_sipCallDirection; }
        }

        public SIPDialogue SIPDialogue
        {
            get { return m_sipDialogue; }
        }

        private SIPAccount m_sipAccount;
        public SIPAccount SIPAccount
        {
            get { return m_sipAccount; }
            set { m_sipAccount = value; }
        }

        public bool IsAuthenticated
        {
            get { return m_isAuthenticated; }
            set { m_isAuthenticated = value; }
        }

        public bool IsCancelled
        {
            get { return m_isCancelled; }
        }

        public SIPRequest CallRequest
        {
            get { return m_uasTransaction.TransactionRequest; }
        }

        public string CallDestination
        {
            get { return m_uasTransaction.TransactionRequest.URI.User; }
        }

        public bool IsUASAnswered
        {
            get { return m_uasTransaction != null && m_uasTransaction.TransactionFinalResponse != null; }
        }

        public event SIPUASDelegate CallCancelled;
        public event SIPUASDelegate NoRingTimeout;
        public event SIPUASDelegate TransactionComplete;
        public event SIPUASStateChangedDelegate UASStateChanged;

        public SIPServerUserAgent(
            SIPTransport sipTransport,
            SIPEndPoint outboundProxy,
            string sipUsername,
            string sipDomain,
            SIPCallDirection callDirection,
            SIPAssetGetDelegate<SIPAccount> getSIPAccount,
            SIPAuthenticateRequestDelegate sipAuthenticateRequest,
            SIPMonitorLogDelegate logDelegate,
            UASInviteTransaction uasTransaction)
        {
            m_sipTransport = sipTransport;
            m_outboundProxy = outboundProxy;
            m_sipUsername = sipUsername;
            m_sipDomain = sipDomain;
            m_sipCallDirection = callDirection;
            GetSIPAccount_External = getSIPAccount;
            SIPAuthenticateRequest_External = sipAuthenticateRequest;
            Log_External = logDelegate ?? Log_External;
            m_uasTransaction = uasTransaction;

            m_uasTransaction.TransactionTraceMessage += TransactionTraceMessage;
            m_uasTransaction.UASInviteTransactionTimedOut += ClientTimedOut;
            m_uasTransaction.UASInviteTransactionCancelled += UASTransactionCancelled;
            m_uasTransaction.TransactionRemoved += new SIPTransactionRemovedDelegate(UASTransaction_TransactionRemoved);
            //m_uasTransaction.TransactionStateChanged += (t) => { logger.Debug("Transaction state change to " + t.TransactionState + ", uri=" + t.TransactionRequestURI.ToString() + "."); };
        }

        private void UASTransaction_TransactionRemoved(SIPTransaction sipTransaction)
        {
            if (TransactionComplete != null)
            {
                TransactionComplete(this);
            }
        }

        public void SetTraceDelegate(SIPTransactionTraceMessageDelegate traceDelegate)
        {
            m_uasTransaction.TransactionTraceMessage += traceDelegate;

            traceDelegate(m_uasTransaction, SIPMonitorEventTypesEnum.SIPTransaction + "=>" + "Request received " + m_uasTransaction.LocalSIPEndPoint +
                "<-" + m_uasTransaction.RemoteEndPoint + "\r\n" + m_uasTransaction.TransactionRequest.ToString());
        }

        public bool LoadSIPAccountForIncomingCall()
        {
            try
            {
                bool loaded = false;

                if (GetSIPAccount_External == null)
                {
                    // No point trying to authenticate if we haven't been given a delegate to load the SIP account.
                    Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
                }
                else
                {
                    m_sipAccount = GetSIPAccount_External(s => s.SIPUsername == m_sipUsername && s.SIPDomain == m_sipDomain);

                    if (m_sipAccount == null)
                    {
                        // A full lookup failed. Now try a partial lookup if the incoming username is in a dotted domain name format.
                        if (m_sipUsername.Contains("."))
                        {
                            string sipUsernameSuffix = m_sipUsername.Substring(m_sipUsername.LastIndexOf(".") + 1);
                            m_sipAccount = GetSIPAccount_External(s => s.SIPUsername == sipUsernameSuffix && s.SIPDomain == m_sipDomain);
                        }

                        if (m_sipAccount == null)
                        {
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Rejecting public call for " + m_sipUsername + "@" + m_sipDomain + ", SIP account not found.", null));
                            Reject(SIPResponseStatusCodesEnum.NotFound, null, null);
                        }
                        else
                        {
                            loaded = true;
                        }
                    }
                    else
                    {
                        loaded = true;
                    }
                }

                if (loaded)
                {
                    SetOwner(m_sipAccount.Owner, m_sipAccount.AdminMemberId);
                }

                return loaded;
            }
            catch (Exception excp)
            {
                logger.Error("Exception LoadSIPAccountForIncomingCall. " + excp.Message);
                Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
                return false;
            }
        }

        public bool AuthenticateCall()
        {
            m_isAuthenticated = false;

            try
            {
                if (SIPAuthenticateRequest_External == null)
                {
                    // No point trying to authenticate if we haven't been given an authentication delegate.
                    Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
                }
                else if (GetSIPAccount_External == null)
                {
                    // No point trying to authenticate if we haven't been given a  delegate to load the SIP account.
                    Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
                }
                else
                {
                    m_sipAccount = GetSIPAccount_External(s => s.SIPUsername == m_sipUsername && s.SIPDomain == m_sipDomain);

                    if (m_sipAccount == null)
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Rejecting authentication required call for " + m_sipUsername + "@" + m_sipDomain + ", SIP account not found.", null));
                        Reject(SIPResponseStatusCodesEnum.Forbidden, null, null);
                    }
                    else
                    {
                        SIPRequest sipRequest = m_uasTransaction.TransactionRequest;
                        SIPEndPoint localSIPEndPoint = (!sipRequest.Header.ProxyReceivedOn.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedOn) : sipRequest.LocalSIPEndPoint;
                        SIPEndPoint remoteEndPoint = (!sipRequest.Header.ProxyReceivedFrom.IsNullOrBlank()) ? SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxyReceivedFrom) : sipRequest.RemoteSIPEndPoint;

                        SIPRequestAuthenticationResult authenticationResult = SIPAuthenticateRequest_External(localSIPEndPoint, remoteEndPoint, sipRequest, m_sipAccount, Log_External);
                        if (authenticationResult.Authenticated)
                        {
                            if (authenticationResult.WasAuthenticatedByIP)
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "New call from " + remoteEndPoint.ToString() + " successfully authenticated by IP address.", m_sipAccount.Owner));
                            }
                            else
                            {
                                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "New call from " + remoteEndPoint.ToString() + " successfully authenticated by digest.", m_sipAccount.Owner));
                            }

                            SetOwner(m_sipAccount.Owner,  m_sipAccount.AdminMemberId);
                            m_isAuthenticated = true;
                        }
                        else
                        {
                            // Send authorisation failure or required response
                            SIPResponse authReqdResponse = SIPTransport.GetResponse(sipRequest, authenticationResult.ErrorResponse, null);
                            authReqdResponse.Header.AuthenticationHeader = authenticationResult.AuthenticationRequiredHeader;
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "Call not authenticated for " + m_sipUsername + "@" + m_sipDomain + ", responding with " + authenticationResult.ErrorResponse + ".", null));
                            m_uasTransaction.SendFinalResponse(authReqdResponse);
                        }
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPServerUserAgent AuthenticateCall. " + excp.Message);
                Reject(SIPResponseStatusCodesEnum.InternalServerError, null, null);
            }

            return m_isAuthenticated;
        }

        public void Progress(SIPResponseStatusCodesEnum progressStatus, string reasonPhrase, string[] customHeaders, string progressContentType, string progressBody)
        {
            try
            {
                if (!IsUASAnswered)
                {
                    if ((int)progressStatus >= 200)
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "UAS call was passed an invalid response status of " + (int)progressStatus + ", ignoring.", m_owner));
                    }
                    else
                    {
                        if (UASStateChanged != null)
                        {
                            UASStateChanged(this, progressStatus, reasonPhrase);
                        }

                        // Allow all Trying responses through as some may contain additional useful information on the call state for the caller.
                        // Also if the response is a 183 Session Progress with audio forward it.
                        if (m_uasTransaction.TransactionState == SIPTransactionStatesEnum.Proceeding && progressStatus != SIPResponseStatusCodesEnum.Trying &&
                            !(progressStatus == SIPResponseStatusCodesEnum.SessionProgress && progressBody != null))
                        {
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "UAS call ignoring progress response with status of " + (int)progressStatus + " as already in " + m_uasTransaction.TransactionState + ".", m_owner));
                        }
                        else
                        {
                            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "UAS call progressing with " + progressStatus + ".", m_owner));
                            SIPResponse progressResponse = SIPTransport.GetResponse(m_uasTransaction.TransactionRequest, progressStatus, reasonPhrase);

                            if (progressResponse.Status != SIPResponseStatusCodesEnum.Trying)
                            {
                                progressResponse.Header.To.ToTag = m_uasTransaction.LocalTag;
                            }

                            if (!progressBody.IsNullOrBlank())
                            {
                                progressResponse.Body = progressBody;
                                progressResponse.Header.ContentType = progressContentType;
                                progressResponse.Header.ContentLength = progressBody.Length;
                            }

                            if (customHeaders != null && customHeaders.Length > 0)
                            {
                                foreach (string header in customHeaders)
                                {
                                    progressResponse.Header.UnknownHeaders.Add(header);
                                }
                            }

                            m_uasTransaction.SendInformationalResponse(progressResponse);
                        }
                    }
                }
                else
                {
                    logger.Warn("SIPServerUserAgent Progress fired on already answered call.");
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPServerUserAgent Progress. " + excp.Message);
            }
        }

        public SIPDialogue Answer(string contentType, string body, SIPDialogue answeredDialogue, SIPDialogueTransferModesEnum transferMode)
        {
            return Answer(contentType, body, null, answeredDialogue, transferMode);
        }

        public SIPDialogue Answer(string contentType, string body, string toTag, SIPDialogue answeredDialogue, SIPDialogueTransferModesEnum transferMode)
        {
            try
            {
                if (m_uasTransaction.TransactionFinalResponse != null)
                {
                    Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "UAS Answer was called on an already answered call, ignoring.", m_owner));
                    return null;
                }
                else
                {
                    if (UASStateChanged != null)
                    {
                        UASStateChanged(this, SIPResponseStatusCodesEnum.Ok, null);
                    }

                    if (!toTag.IsNullOrBlank())
                    {
                        m_uasTransaction.SetLocalTag(toTag);
                    }

                    SIPResponse okResponse = m_uasTransaction.GetOkResponse(m_uasTransaction.TransactionRequest, m_uasTransaction.TransactionRequest.LocalSIPEndPoint, contentType, body);

                    if (body != null)
                    {
                        okResponse.Header.ContentType = contentType;
                        okResponse.Header.ContentLength = body.Length;
                        okResponse.Body = body;
                    }

                    m_uasTransaction.SendFinalResponse(okResponse);

                    m_sipDialogue = new SIPDialogue(m_uasTransaction, m_owner, m_adminMemberId);
                    m_sipDialogue.TransferMode = transferMode;

                    return m_sipDialogue;
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPServerUserAgent Answer. " + excp.Message);
                throw;
            }
        }

        public void AnswerNonInvite(SIPResponseStatusCodesEnum answerStatus, string reasonPhrase, string[] customHeaders, string contentType, string body)
        {
            throw new NotImplementedException();
        }

        public void Reject(SIPResponseStatusCodesEnum failureStatus, string reasonPhrase, string[] customHeaders)
        {
            try
            {
                if (m_uasTransaction.TransactionFinalResponse == null)
                {
                    if ((int)failureStatus < 400)
                    {
                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "UAS Reject was passed an invalid response status of " + (int)failureStatus + ", ignoring.", m_owner));
                    }
                    else
                    {
                        if (UASStateChanged != null)
                        {
                            UASStateChanged(this, failureStatus, reasonPhrase);
                        }

                        string failureReason = (!reasonPhrase.IsNullOrBlank()) ? " and " + reasonPhrase : null;

                        Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.AppServer, SIPMonitorEventTypesEnum.DialPlan, "UAS call failed with a response status of " + (int)failureStatus + failureReason + ".", m_owner));
                        SIPResponse failureResponse = SIPTransport.GetResponse(m_uasTransaction.TransactionRequest, failureStatus, reasonPhrase);

                        if (customHeaders != null && customHeaders.Length > 0)
                        {
                            foreach (string header in customHeaders)
                            {
                                failureResponse.Header.UnknownHeaders.Add(header);
                            }
                        }

                        m_uasTransaction.SendFinalResponse(failureResponse);
                    }
                }
                else
                {
                    logger.Warn("SIPServerUserAgent Reject fired on already answered call.");
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPServerUserAgent Reject. " + excp.Message);
            }
        }

        public void Redirect(SIPResponseStatusCodesEnum redirectCode, SIPURI redirectURI)
        {
            try
            {
                if (m_uasTransaction.TransactionFinalResponse == null)
                {
                    SIPResponse redirectResponse = SIPTransport.GetResponse(m_uasTransaction.TransactionRequest, redirectCode, null);
                    redirectResponse.Header.Contact = SIPContactHeader.CreateSIPContactList(redirectURI);
                    m_uasTransaction.SendFinalResponse(redirectResponse);
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPServerUserAgent Redirect. " + excp.Message);
            }
        }

        public void NoCDR()
        {
            m_uasTransaction.CDR = null;
        }

        private void UASTransactionCancelled(SIPTransaction sipTransaction)
        {
            logger.Debug("SIPServerUserAgent got cancellation request.");
            m_isCancelled = true;
            if (CallCancelled != null)
            {
                CallCancelled(this);
            }
        }

        private void ClientTimedOut(SIPTransaction sipTransaction)
        {
            try
            {
                Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentServer, SIPMonitorEventTypesEnum.DialPlan, "UAS for " + m_uasTransaction.TransactionRequest.URI.ToString() + " timed out in transaction state " + m_uasTransaction.TransactionState + ".", null));
                //SIPResponse rejectResponse = SIPTransport.GetResponse(m_uasTransaction.TransactionRequest, SIPResponseStatusCodesEnum.ServerTimeout, "No info or final response received within timeout");
                //m_uasTransaction.SendFinalResponse(rejectResponse);

                if (m_uasTransaction.TransactionState == SIPTransactionStatesEnum.Calling && NoRingTimeout != null)
                {
                    NoRingTimeout(this);
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception ClientTimedOut. " + excp.Message);
            }
        }

        public void SetOwner(string owner, string adminMemberId)
        {
            m_owner = owner;
            m_adminMemberId = adminMemberId;

            if (m_uasTransaction.CDR != null)
            {
                m_uasTransaction.CDR.Owner = owner;
                m_uasTransaction.CDR.AdminMemberId = adminMemberId;

                m_uasTransaction.CDR.Updated();
            }
        }

        private void TransactionTraceMessage(SIPTransaction sipTransaction, string message)
        {
            Log_External(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.UserAgentServer, SIPMonitorEventTypesEnum.SIPTransaction, message, null));
        }

        public void SetDialPlanContextID(Guid dialPlanContextID)
        {
            if (m_uasTransaction.CDR != null)
            {
                m_uasTransaction.CDR.DialPlanContextID = dialPlanContextID;

                m_uasTransaction.CDR.Updated();
            }
        }
    }
}


text:
const fs = require('fs');
const file = '/../.babelrc';
const absolutePath = __dirname + file;
const babelConfig = JSON.parse(fs.readFileSync(absolutePath));
require('babel-core/register')(babelConfig);
require('./server/');


text:
using Fluent_CQRS.Extensions;

namespace Fluent_CQRS.Fluentation
{
    public class AfterInvocation<TAggregate> where TAggregate : Aggregate
    {
        private readonly TAggregate _aggregate;
        private readonly Aggregates _aggregates;

        public AfterInvocation(TAggregate aggregate, Aggregates aggregates)
        {
            _aggregate = aggregate;
            _aggregates = aggregates;
        }

        public EventPublishing FinallySaveIt()
        {
            _aggregates.SaveChangesBy(_aggregate);

            if(_aggregates.PublishNewState.IsNotDefined())
                _aggregate.Changes.Clear();

            return new EventPublishing(_aggregates, _aggregate);
        }
    }
}


text:
package ru.otus.base.dataSets;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;

/**
 * Created by tully.
 */
@Entity
@Table(name = "phones")
public class PhoneDataSet extends DataSet {

    @Column(name = "number")
    private String number;

    public PhoneDataSet() {
    }

    public PhoneDataSet(String number) {
        this.number = number;
    }

    public String getNumber() {
        return number;
    }

    @Override
    public String toString() {
        return "PhoneDataSet{" +
                "number='" + number + '\'' +
                '}';
    }
}


text:
package org.dromelvan.modell.persistence;

import org.dromelvan.modell.Mal;

public interface MalDAO extends DataAccessObject<Mal> {

}


text:
#pragma once
#include <aws/cognito-idp/CognitoIdentityProvider_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/DateTime.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/cognito-idp/model/ExplicitAuthFlowsType.h>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace CognitoIdentityProvider
{
namespace Model
{

  /**
   *
A user pool of the client type.

   */
  class AWS_COGNITOIDENTITYPROVIDER_API UserPoolClientType
  {
  public:
    UserPoolClientType();
    UserPoolClientType(const Aws::Utils::Json::JsonValue& jsonValue);
    UserPoolClientType& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The user pool ID for the user pool client.

     */
    inline const Aws::String& GetUserPoolId() const{ return m_userPoolId; }

    /**
     *
The user pool ID for the user pool client.

     */
    inline void SetUserPoolId(const Aws::String& value) { m_userPoolIdHasBeenSet = true; m_userPoolId = value; }

    /**
     *
The user pool ID for the user pool client.

     */
    inline void SetUserPoolId(Aws::String&& value) { m_userPoolIdHasBeenSet = true; m_userPoolId = value; }

    /**
     *
The user pool ID for the user pool client.

     */
    inline void SetUserPoolId(const char* value) { m_userPoolIdHasBeenSet = true; m_userPoolId.assign(value); }

    /**
     *
The user pool ID for the user pool client.

     */
    inline UserPoolClientType& WithUserPoolId(const Aws::String& value) { SetUserPoolId(value); return *this;}

    /**
     *
The user pool ID for the user pool client.

     */
    inline UserPoolClientType& WithUserPoolId(Aws::String&& value) { SetUserPoolId(value); return *this;}

    /**
     *
The user pool ID for the user pool client.

     */
    inline UserPoolClientType& WithUserPoolId(const char* value) { SetUserPoolId(value); return *this;}

    /**
     *
The client name from the user pool request of the client type.

     */
    inline const Aws::String& GetClientName() const{ return m_clientName; }

    /**
     *
The client name from the user pool request of the client type.

     */
    inline void SetClientName(const Aws::String& value) { m_clientNameHasBeenSet = true; m_clientName = value; }

    /**
     *
The client name from the user pool request of the client type.

     */
    inline void SetClientName(Aws::String&& value) { m_clientNameHasBeenSet = true; m_clientName = value; }

    /**
     *
The client name from the user pool request of the client type.

     */
    inline void SetClientName(const char* value) { m_clientNameHasBeenSet = true; m_clientName.assign(value); }

    /**
     *
The client name from the user pool request of the client type.

     */
    inline UserPoolClientType& WithClientName(const Aws::String& value) { SetClientName(value); return *this;}

    /**
     *
The client name from the user pool request of the client type.

     */
    inline UserPoolClientType& WithClientName(Aws::String&& value) { SetClientName(value); return *this;}

    /**
     *
The client name from the user pool request of the client type.

     */
    inline UserPoolClientType& WithClientName(const char* value) { SetClientName(value); return *this;}

    /**
     *
The ID of the client associated with the user pool.

     */
    inline const Aws::String& GetClientId() const{ return m_clientId; }

    /**
     *
The ID of the client associated with the user pool.

     */
    inline void SetClientId(const Aws::String& value) { m_clientIdHasBeenSet = true; m_clientId = value; }

    /**
     *
The ID of the client associated with the user pool.

     */
    inline void SetClientId(Aws::String&& value) { m_clientIdHasBeenSet = true; m_clientId = value; }

    /**
     *
The ID of the client associated with the user pool.

     */
    inline void SetClientId(const char* value) { m_clientIdHasBeenSet = true; m_clientId.assign(value); }

    /**
     *
The ID of the client associated with the user pool.

     */
    inline UserPoolClientType& WithClientId(const Aws::String& value) { SetClientId(value); return *this;}

    /**
     *
The ID of the client associated with the user pool.

     */
    inline UserPoolClientType& WithClientId(Aws::String&& value) { SetClientId(value); return *this;}

    /**
     *
The ID of the client associated with the user pool.

     */
    inline UserPoolClientType& WithClientId(const char* value) { SetClientId(value); return *this;}

    /**
     *
The client secret from the user pool request of the client type.

     */
    inline const Aws::String& GetClientSecret() const{ return m_clientSecret; }

    /**
     *
The client secret from the user pool request of the client type.

     */
    inline void SetClientSecret(const Aws::String& value) { m_clientSecretHasBeenSet = true; m_clientSecret = value; }

    /**
     *
The client secret from the user pool request of the client type.

     */
    inline void SetClientSecret(Aws::String&& value) { m_clientSecretHasBeenSet = true; m_clientSecret = value; }

    /**
     *
The client secret from the user pool request of the client type.

     */
    inline void SetClientSecret(const char* value) { m_clientSecretHasBeenSet = true; m_clientSecret.assign(value); }

    /**
     *
The client secret from the user pool request of the client type.

     */
    inline UserPoolClientType& WithClientSecret(const Aws::String& value) { SetClientSecret(value); return *this;}

    /**
     *
The client secret from the user pool request of the client type.

     */
    inline UserPoolClientType& WithClientSecret(Aws::String&& value) { SetClientSecret(value); return *this;}

    /**
     *
The client secret from the user pool request of the client type.

     */
    inline UserPoolClientType& WithClientSecret(const char* value) { SetClientSecret(value); return *this;}

    /**
     *
The last modified date from the user pool request of the client type.

     */
    inline const Aws::Utils::DateTime& GetLastModifiedDate() const{ return m_lastModifiedDate; }

    /**
     *
The last modified date from the user pool request of the client type.

     */
    inline void SetLastModifiedDate(const Aws::Utils::DateTime& value) { m_lastModifiedDateHasBeenSet = true; m_lastModifiedDate = value; }

    /**
     *
The last modified date from the user pool request of the client type.

     */
    inline void SetLastModifiedDate(Aws::Utils::DateTime&& value) { m_lastModifiedDateHasBeenSet = true; m_lastModifiedDate = value; }

    /**
     *
The last modified date from the user pool request of the client type.

     */
    inline UserPoolClientType& WithLastModifiedDate(const Aws::Utils::DateTime& value) { SetLastModifiedDate(value); return *this;}

    /**
     *
The last modified date from the user pool request of the client type.

     */
    inline UserPoolClientType& WithLastModifiedDate(Aws::Utils::DateTime&& value) { SetLastModifiedDate(value); return *this;}

    /**
     *
The creation date from the user pool request of the client type.

     */
    inline const Aws::Utils::DateTime& GetCreationDate() const{ return m_creationDate; }

    /**
     *
The creation date from the user pool request of the client type.

     */
    inline void SetCreationDate(const Aws::Utils::DateTime& value) { m_creationDateHasBeenSet = true; m_creationDate = value; }

    /**
     *
The creation date from the user pool request of the client type.

     */
    inline void SetCreationDate(Aws::Utils::DateTime&& value) { m_creationDateHasBeenSet = true; m_creationDate = value; }

    /**
     *
The creation date from the user pool request of the client type.

     */
    inline UserPoolClientType& WithCreationDate(const Aws::Utils::DateTime& value) { SetCreationDate(value); return *this;}

    /**
     *
The creation date from the user pool request of the client type.

     */
    inline UserPoolClientType& WithCreationDate(Aws::Utils::DateTime&& value) { SetCreationDate(value); return *this;}

    /**
     *
The validity of the refresh token.

     */
    inline int GetRefreshTokenValidity() const{ return m_refreshTokenValidity; }

    /**
     *
The validity of the refresh token.

     */
    inline void SetRefreshTokenValidity(int value) { m_refreshTokenValidityHasBeenSet = true; m_refreshTokenValidity = value; }

    /**
     *
The validity of the refresh token.

     */
    inline UserPoolClientType& WithRefreshTokenValidity(int value) { SetRefreshTokenValidity(value); return *this;}

    /**
     *
The Read-only attributes.

     */
    inline const Aws::Vector<Aws::String>& GetReadAttributes() const{ return m_readAttributes; }

    /**
     *
The Read-only attributes.

     */
    inline void SetReadAttributes(const Aws::Vector<Aws::String>& value) { m_readAttributesHasBeenSet = true; m_readAttributes = value; }

    /**
     *
The Read-only attributes.

     */
    inline void SetReadAttributes(Aws::Vector<Aws::String>&& value) { m_readAttributesHasBeenSet = true; m_readAttributes = value; }

    /**
     *
The Read-only attributes.

     */
    inline UserPoolClientType& WithReadAttributes(const Aws::Vector<Aws::String>& value) { SetReadAttributes(value); return *this;}

    /**
     *
The Read-only attributes.

     */
    inline UserPoolClientType& WithReadAttributes(Aws::Vector<Aws::String>&& value) { SetReadAttributes(value); return *this;}

    /**
     *
The Read-only attributes.

     */
    inline UserPoolClientType& AddReadAttributes(const Aws::String& value) { m_readAttributesHasBeenSet = true; m_readAttributes.push_back(value); return *this; }

    /**
     *
The Read-only attributes.

     */
    inline UserPoolClientType& AddReadAttributes(Aws::String&& value) { m_readAttributesHasBeenSet = true; m_readAttributes.push_back(value); return *this; }

    /**
     *
The Read-only attributes.

     */
    inline UserPoolClientType& AddReadAttributes(const char* value) { m_readAttributesHasBeenSet = true; m_readAttributes.push_back(value); return *this; }

    /**
     *
The writeable attributes.

     */
    inline const Aws::Vector<Aws::String>& GetWriteAttributes() const{ return m_writeAttributes; }

    /**
     *
The writeable attributes.

     */
    inline void SetWriteAttributes(const Aws::Vector<Aws::String>& value) { m_writeAttributesHasBeenSet = true; m_writeAttributes = value; }

    /**
     *
The writeable attributes.

     */
    inline void SetWriteAttributes(Aws::Vector<Aws::String>&& value) { m_writeAttributesHasBeenSet = true; m_writeAttributes = value; }

    /**
     *
The writeable attributes.

     */
    inline UserPoolClientType& WithWriteAttributes(const Aws::Vector<Aws::String>& value) { SetWriteAttributes(value); return *this;}

    /**
     *
The writeable attributes.

     */
    inline UserPoolClientType& WithWriteAttributes(Aws::Vector<Aws::String>&& value) { SetWriteAttributes(value); return *this;}

    /**
     *
The writeable attributes.

     */
    inline UserPoolClientType& AddWriteAttributes(const Aws::String& value) { m_writeAttributesHasBeenSet = true; m_writeAttributes.push_back(value); return *this; }

    /**
     *
The writeable attributes.

     */
    inline UserPoolClientType& AddWriteAttributes(Aws::String&& value) { m_writeAttributesHasBeenSet = true; m_writeAttributes.push_back(value); return *this; }

    /**
     *
The writeable attributes.

     */
    inline UserPoolClientType& AddWriteAttributes(const char* value) { m_writeAttributesHasBeenSet = true; m_writeAttributes.push_back(value); return *this; }

    /**
     *
The explicit authentication flows.

     */
    inline const Aws::Vector<ExplicitAuthFlowsType>& GetExplicitAuthFlows() const{ return m_explicitAuthFlows; }

    /**
     *
The explicit authentication flows.

     */
    inline void SetExplicitAuthFlows(const Aws::Vector<ExplicitAuthFlowsType>& value) { m_explicitAuthFlowsHasBeenSet = true; m_explicitAuthFlows = value; }

    /**
     *
The explicit authentication flows.

     */
    inline void SetExplicitAuthFlows(Aws::Vector<ExplicitAuthFlowsType>&& value) { m_explicitAuthFlowsHasBeenSet = true; m_explicitAuthFlows = value; }

    /**
     *
The explicit authentication flows.

     */
    inline UserPoolClientType& WithExplicitAuthFlows(const Aws::Vector<ExplicitAuthFlowsType>& value) { SetExplicitAuthFlows(value); return *this;}

    /**
     *
The explicit authentication flows.

     */
    inline UserPoolClientType& WithExplicitAuthFlows(Aws::Vector<ExplicitAuthFlowsType>&& value) { SetExplicitAuthFlows(value); return *this;}

    /**
     *
The explicit authentication flows.

     */
    inline UserPoolClientType& AddExplicitAuthFlows(const ExplicitAuthFlowsType& value) { m_explicitAuthFlowsHasBeenSet = true; m_explicitAuthFlows.push_back(value); return *this; }

    /**
     *
The explicit authentication flows.

     */
    inline UserPoolClientType& AddExplicitAuthFlows(ExplicitAuthFlowsType&& value) { m_explicitAuthFlowsHasBeenSet = true; m_explicitAuthFlows.push_back(value); return *this; }

  private:
    Aws::String m_userPoolId;
    bool m_userPoolIdHasBeenSet;
    Aws::String m_clientName;
    bool m_clientNameHasBeenSet;
    Aws::String m_clientId;
    bool m_clientIdHasBeenSet;
    Aws::String m_clientSecret;
    bool m_clientSecretHasBeenSet;
    Aws::Utils::DateTime m_lastModifiedDate;
    bool m_lastModifiedDateHasBeenSet;
    Aws::Utils::DateTime m_creationDate;
    bool m_creationDateHasBeenSet;
    int m_refreshTokenValidity;
    bool m_refreshTokenValidityHasBeenSet;
    Aws::Vector<Aws::String> m_readAttributes;
    bool m_readAttributesHasBeenSet;
    Aws::Vector<Aws::String> m_writeAttributes;
    bool m_writeAttributesHasBeenSet;
    Aws::Vector<ExplicitAuthFlowsType> m_explicitAuthFlows;
    bool m_explicitAuthFlowsHasBeenSet;
  };

} // namespace Model
} // namespace CognitoIdentityProvider
} // namespace Aws


text:
Version 1.0.0.4
===============

* Bumped network and transformers dependency version.

Version 1.0.0.3
===============

* Made some tweaks so that the tests run on older versions of GHC.

Version 1.0.0.2
===============

* Bumped lens dependency version.

Version 1.0.0.1
===============

* Improved performance.

* Now notices are logged when workers connect and disconnect.

* Exposed `getCurentStatistics` in the `RequestQueueMonad`, allowing one to
  obtain the statistics at any time during the run.

* Fixed the documentation.

* Now ImplicitParams are used instead of a monad to ensure sockets
  initialization.

* Bumped dependency bounds.


text:
package org.gwtproject.safehtml.client;

import junit.framework.TestCase;
import org.gwtproject.safecss.shared.SafeStylesUtils;
import org.gwtproject.safehtml.shared.SafeHtmlUtils;
import org.gwtproject.safehtml.shared.UriUtils;

/** Tests the SafeHtmlTemplates compile-time binding mechanism. */
public class SafeHtmlTemplatesTest extends TestCase {

  private static final String HTML_MARKUP = "woo whee";

  private static final String GOOD_URL_ESCAPED = "http://foo.com/foo<bar>&baz=dootz";
  private static final String GOOD_URL_ENCODED = "http://foo.com/foo%3Cbar%3E&baz=dootz";
  private static final String GOOD_URL = "http://foo.com/foo<bar>&baz=dootz";
  private static final String BAD_URL = "javascript:evil(1<2)";
  private static final String BAD_URL_ESCAPED = "javascript:evil(1<2)";

  private SafeHtmlTestTemplates templates = new SafeHtmlTestTemplatesImpl();

  public void testSimpleTemplate() {
    assertEquals(
        "foo<barwoo whee",
        templates
            .simpleTemplate("foo<bar", SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
  }

  public void testTemplateWithUriAttribute() {
    // as String: sanitized by the template
    assertEquals(
        "" + HTML_MARKUP + "",
        templates
            .templateWithUriAttribute(GOOD_URL, SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
    assertEquals(
        "" + HTML_MARKUP + "",
        templates
            .templateWithUriAttribute(BAD_URL, SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
    // UriUtils.fromString: sanitized by fromString
    assertEquals(
        "" + HTML_MARKUP + "",
        templates
            .templateWithUriAttribute(
                UriUtils.fromString(GOOD_URL), SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
    assertEquals(
        "" + HTML_MARKUP + "",
        templates
            .templateWithUriAttribute(
                UriUtils.fromString(BAD_URL), SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
    // UriUtils.fromTrustedString: not sanitized
    assertEquals(
        "" + HTML_MARKUP + "",
        templates
            .templateWithUriAttribute(
                UriUtils.fromTrustedString(GOOD_URL), SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
    assertEquals(
        "" + HTML_MARKUP + "",
        templates
            .templateWithUriAttribute(
                UriUtils.fromTrustedString(BAD_URL), SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
  }

  public void testTemplateWithRegularAttribute() {
    assertEquals(
        "
" + HTML_MARKUP + "
",
        templates
            .templateWithRegularAttribute(GOOD_URL, SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());

    // Values inserted into non-URI-valued attributes should not be sanitized,
    // but still escaped.
    assertEquals(
        "
" + HTML_MARKUP + "
",
        templates
            .templateWithRegularAttribute(BAD_URL, SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
  }

  public void testTemplateWithSafeStyleAttributeComplete() {
    assertEquals(
        "
" + HTML_MARKUP + "
",
        templates
            .templateWithSafeStyleAttributeComplete(
                SafeStylesUtils.fromTrustedString("width:10px;"),
                SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
  }

  public void testTemplateWithSafeStyleAttributeStart() {
    assertEquals(
        "
" + HTML_MARKUP + "
",
        templates
            .templateWithSafeStyleAttributeStart(
                SafeStylesUtils.fromTrustedString("width:10px;"),
                15,
                SafeHtmlUtils.fromSafeConstant(HTML_MARKUP))
            .asString());
  }

  public void testTemplateWithTwoPartUriAttribute() {
    // sanitized by the template
    assertEquals(
        "",
        templates.templateWithTwoPartUriAttribute(GOOD_URL, "x&y").asString());
    assertEquals(
        "",
        templates.templateWithTwoPartUriAttribute(BAD_URL, "x&y").asString());
  }

  public void testTemplateWithStyleAttribute() {
    assertEquals(
        "",
        templates.templateWithStyleAttribute("background: purple").asString());
  }
}


text:
package com.github.staslev.storm.metrics;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Holds configuration options for the {@link StormMetricProcessor} metric consumer.
 * Implements List in order to be compliant with Storm's configuration serialization mechanism,
 * while exposing type safe getters.
 */
public class MetricReporterConfig extends ArrayList<String> {

  public MetricReporterConfig(final String allowedMetricNames, final String stormMetricProcessorClassName) {
    super(2);
    add(allowedMetricNames);
    add(stormMetricProcessorClassName);
  }

  public static MetricReporterConfig from(final List<String> params) {
    return new MetricReporterConfig(params.get(0), params.get(1));
  }

  public String getAllowedMetricNames() {
    return get(0);
  }

  public String getStormMetricProcessorClassName() {
    return get(1);
  }

  /**
   * Creates an instance of the configured {@link StormMetricProcessor} class.
   *
   * @param stormConf configuration parameters
   * @return A new GaugeReporter instance of the specified class.
   */
  public StormMetricProcessor getStormMetricProcessor(final Map stormConf) {
    try {
      final Constructor<?> constructor = Class.forName(getStormMetricProcessorClassName()).getConstructor(Map.class);
      return (StormMetricProcessor) constructor.newInstance(stormConf);
    } catch (final Exception e) {
      throw new RuntimeException(e);
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="190dp"
    android:background="@drawable/blue_background"
    android:orientation="vertical"
    >

    <de.hdodenhof.circleimageview.CircleImageView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/profile_image"
        android:layout_width="76dp"
        android:layout_height="76dp"
        android:src="@drawable/profile"
        app:border_color="#FF000000"
        android:layout_marginLeft="24dp"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginStart="24dp" />

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="14sp"
        android:textColor="#FFF"
        android:textStyle="bold"
        android:gravity="left"
        android:paddingBottom="4dp"
        android:layout_above="@+id/email"
        android:layout_alignLeft="@+id/profile_image"
        android:layout_alignStart="@+id/profile_image" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:id="@+id/email"
        android:gravity="left"
        android:layout_marginBottom="8dp"
        android:textSize="14sp"
        android:textColor="#fff"
        android:layout_alignParentBottom="true"
        android:layout_alignLeft="@+id/username"
        android:layout_alignStart="@+id/username" />

</RelativeLayout>


text:
package org.neo4j.cypher.internal.compiler.v2_3.commands.expressions

import org.neo4j.cypher.internal.compiler.v2_3._
import org.neo4j.cypher.internal.compiler.v2_3.pipes.QueryStateHelper
import org.neo4j.cypher.internal.frontend.v2_3.test_helpers.CypherFunSuite

class SimpleCaseTest extends CypherFunSuite {

  test("case_with_single_alternative_works") {
    //GIVEN
    val caseExpr = case_(1,
      1 -> "one"
    )

    //WHEN
    val result = caseExpr(ExecutionContext.empty)(QueryStateHelper.empty)

    //THEN
    result should equal("one")
  }

  test("case_with_two_alternatives_picks_the_second") {
    //GIVEN
    val caseExpr = case_(2,
      1 -> "one",
      2 -> "two"
    )

    //WHEN
    val result = caseExpr(ExecutionContext.empty)(QueryStateHelper.empty)

    //THEN
    result should equal("two")
  }

  test("case_with_no_match_returns_null") {
    //GIVEN
    val caseExpr = case_(3,
      1 -> "one",
      2 -> "two"
    )

    //WHEN
    val result = caseExpr(ExecutionContext.empty)(QueryStateHelper.empty)

    //THEN
    result should equal(null.asInstanceOf[Any])
  }

  test("case_with_no_match_returns_default") {
    //GIVEN
    val caseExpr = case_(3,
      1 -> "one",
      2 -> "two"
    ) defaultsTo "default"

    //WHEN
    val result = caseExpr(ExecutionContext.empty)(QueryStateHelper.empty)

    //THEN
    result should equal("default")
  }

  test("when_the_input_expression_is_null_return_the_else_case") {
    //GIVEN
    val caseExpr = case_(null,
      1 -> "one",
      2 -> "two"
    ) defaultsTo "default"

    //WHEN
    val result = caseExpr(ExecutionContext.empty)(QueryStateHelper.empty)

    //THEN
    assert(result == "default")
  }

  private def case_(in: Any, alternatives: (Any, Any)*): SimpleCase = {
    val mappedAlt: Seq[(Expression, Expression)] = alternatives.map {
      case (a, b) => (Literal(a), Literal(b))
    }

    SimpleCase(Literal(in), mappedAlt, None)
  }

  implicit class SimpleCasePimp(in:SimpleCase) {
    def defaultsTo(a:Any): SimpleCase = SimpleCase(in.expression, in.alternatives, Some(Literal(a)))
  }
}


text:
@interface APPaginalContainerViewScrollView : UIScrollView
@property (nonatomic, assign) UIEdgeInsets panRecognizeInsets;
@end

@implementation APPaginalContainerViewScrollView
@synthesize panRecognizeInsets = _panRecognizeInsets;
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    BOOL shouldBegin = YES;

    if (gestureRecognizer == self.panGestureRecognizer) {
        CGPoint touchLocation = [self.panGestureRecognizer locationInView:gestureRecognizer.view];

        CGRect panRecognizeFrame = UIEdgeInsetsInsetRect(self.bounds, self.panRecognizeInsets);
        shouldBegin = !CGRectContainsPoint(panRecognizeFrame, touchLocation);
    }

    return shouldBegin;
}
@end

#pragma mark -

@interface APPaginalContainerView () < UIScrollViewDelegate,
                                       UIGestureRecognizerDelegate >
@property (nonatomic, assign) CGPoint pageSizeRelative;
@property (nonatomic, readonly) CGSize pageSizeAbsolute;
@end

#pragma mark -

@implementation APPaginalContainerView {
    APPaginalContainerViewScrollView *_scrollView;
    NSMutableArray *_pages;

    BOOL _isUpdateInProgress;
    NSMutableIndexSet *_insertedIndexes;
    NSMutableIndexSet *_deletedIndexes;

    APPaginalContainerViewPage *_tempCurrentPage;
}

#pragma mark - Properties

@synthesize dataSource = _dataSource;
@synthesize delegate = _delegate;

@synthesize pageSizeRelative = _pageSizeRelative;
@dynamic pageSizeAbsolute;

#pragma mark - UIView Override

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _scrollView = [[APPaginalContainerViewScrollView alloc] initWithFrame:self.bounds];
        _scrollView.panRecognizeInsets = UIEdgeInsetsMake(0, 30, 0, 25);
        _scrollView.delegate = self;
        _scrollView.pagingEnabled = YES;
        _scrollView.showsVerticalScrollIndicator = NO;
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.clipsToBounds = NO;
        _scrollView.alwaysBounceHorizontal = YES;
        _scrollView.scrollsToTop = NO;
        [self addSubview:_scrollView];

        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

        _pageSizeRelative = CGPointMake(1.f, 1.f);

        _pages = [NSMutableArray array];

        _insertedIndexes = [NSMutableIndexSet indexSet];
        _deletedIndexes = [NSMutableIndexSet indexSet];
    }
    return self;
}

#pragma mark - Properties Override

- (void)setDataSource:(id <APPaginalContainerViewDataSource>)dataSource
{
    _dataSource = dataSource;

    if (_dataSource) {
        [self reloadData];
    }
}

- (NSInteger)numberOfPages
{
    return _pages.count;
}

- (void)setPageSizeRelative:(CGPoint)pageSizeRelative
{
    NSParameterAssert(CGRectContainsPoint(CGRectMake(0.f, 0.f, 1.f, 1.f), pageSizeRelative));

    _pageSizeRelative = pageSizeRelative;
}

- (CGSize)pageSizeAbsolute
{
    CGSize pageSizeAbsolute = CGSizeMake(ceilf(_scrollView.bounds.size.width * self.pageSizeRelative.x),
                                         ceilf(_scrollView.bounds.size.height * self.pageSizeRelative.y));
    return pageSizeAbsolute;
}

#pragma mark - Methods

- (void)reloadData
{
    [self deleteAllPages];

    NSInteger numPages = [self.dataSource numberOfPagesInPaginalContainerView:self];

    for (NSInteger i = 0; i < numPages; i++) {
        APPaginalContainerViewPage *newPage = [self.dataSource paginalContainerView:self pageAtIndex:i];

        [_pages insertObject:newPage atIndex:i];
        [_scrollView addSubview:newPage];
    }

    [self layoutPages];
}

- (void)beginUpdates
{
    _isUpdateInProgress = YES;

    [_insertedIndexes removeAllIndexes];
    [_deletedIndexes removeAllIndexes];

    _tempCurrentPage = [self currentPage];
}

- (void)insertPageAtIndex:(NSInteger)index
{
    NSAssert(_isUpdateInProgress, @"You must call beginUpdate before inserting new pages");

    [_insertedIndexes addIndex:index];
}

- (void)deletePageAtIndex:(NSInteger)index
{
    NSAssert(_isUpdateInProgress, @"You must call beginUpdate before deleting pages");
    NSAssert(_pages[index] != nil, @"Element should exist for deleting");

    [_deletedIndexes addIndex:index];
}

- (void)endUpdates
{
    if ([self hasChanges]) {
        NSMutableIndexSet *oldlIndexes = [NSMutableIndexSet indexSetWithIndexesInRange:NSMakeRange(0, _pages.count)];
        NSMutableArray *newPages = [NSMutableArray array];

        [_deletedIndexes enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop)
        {
            [_pages[index] removeFromSuperview];
        }];

        __block NSUInteger newIndex = 0;
        [oldlIndexes enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop)
        {
            if (![_deletedIndexes containsIndex:index]) {

                while ([_insertedIndexes containsIndex:newIndex]) {
                    APPaginalContainerViewPage *newPage = [self.dataSource paginalContainerView:self pageAtIndex:newIndex];
                    [newPages insertObject:newPage atIndex:newIndex];
                    [_scrollView addSubview:newPage];

                    [_insertedIndexes removeIndex:newIndex];
                    newIndex++;
                }

                APPaginalContainerViewPage *page = _pages[index];
                [newPages insertObject:page atIndex:newIndex];

                newIndex++;
            }
        }];

        [_insertedIndexes enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop)
        {
            APPaginalContainerViewPage *newPage = [self.dataSource paginalContainerView:self pageAtIndex:index];
            [newPages insertObject:newPage atIndex:index];
            [_scrollView addSubview:newPage];
        }];

        _pages = newPages;
    }

    _isUpdateInProgress = NO;

    [_insertedIndexes removeAllIndexes];
    [_deletedIndexes removeAllIndexes];

    [self layoutPages];

    _scrollView.contentOffset = [self offsetForPageAtIndex:[self indexOfPage:_tempCurrentPage]];
    _tempCurrentPage = nil;
}

- (BOOL)hasChanges
{
    BOOL hasChanges = _insertedIndexes.count != 0 || _deletedIndexes.count != 0;
    return hasChanges;
}

- (void)scrollToPageAtIndex:(NSInteger)index completion:(void (^)(BOOL))completion animated:(BOOL)animated
{
    [self onBeginScrolling];

    CGPoint offset = [self offsetForPageAtIndex:index];

    void (^blockAnimation)(void) = ^(void)
    {
        _scrollView.contentOffset = offset;
	};

	void (^blockCompletion)(BOOL) = ^(BOOL finished)
    {
        [self onEndScrolling];

        if (completion) {
            completion(finished);
        }
	};

    if (animated) {
        [UIView animateWithDuration:0.25 animations:blockAnimation completion:blockCompletion];
    }
    else {
        blockAnimation();
        blockCompletion(YES);
    }
}

- (NSInteger)indexOfCurrentPage
{
    NSInteger index = [self indexOfPageForOffset:_scrollView.contentOffset];
    return index;
}

- (APPaginalContainerViewPage *)currentPage
{
    APPaginalContainerViewPage *currentPage = [self pageAtIndex:self.indexOfCurrentPage];
    return currentPage;
}

- (NSInteger)indexOfPage:(APPaginalContainerViewPage *)page
{
    NSParameterAssert(page);
    NSInteger index = [_pages indexOfObject:page];
    return index;
}

- (APPaginalContainerViewPage *)pageAtIndex:(NSInteger)index
{
    NSParameterAssert((index >= 0 && index < self.numberOfPages) || (index == NSNotFound));

    APPaginalContainerViewPage *page = nil;

    if (index != NSNotFound) {
        page = [_pages objectAtIndex:index];
        NSParameterAssert(page);
    }

    return page;
}

- (NSInteger)indexOfPageForOffset:(CGPoint)offset
{
    NSInteger index = roundf(offset.x / self.pageSizeAbsolute.width);
    index = MAX(0, MIN(index, self.numberOfPages - 1));
    return index;
}

- (CGPoint)offsetForPageAtIndex:(NSInteger)index
{
    NSParameterAssert((0 <= index && index < self.numberOfPages) || (index == NSNotFound));

    CGPoint offset = (index == NSNotFound)? CGPointZero : CGPointMake(self.pageSizeAbsolute.width * index, 0.f);

    NSParameterAssert(offset.x <= _scrollView.contentSize.width && offset.y <= _scrollView.contentSize.height);
    return offset;
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
	[self onBeginScrolling];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self onEndScrolling];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    [self onEndScrolling];
}

#pragma mark - Internal

- (void)deleteAllPages
{
    [_pages makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [_pages removeAllObjects];
}

- (void)layoutPages
{
    _scrollView.contentSize = CGSizeMake(self.numberOfPages * self.pageSizeAbsolute.width, self.pageSizeAbsolute.height);

    for (NSUInteger i = 0; i < _pages.count; i++) {
        APPaginalContainerViewPage *page = [_pages objectAtIndex:i];
        page.frame = (CGRect){.origin = CGPointMake(self.pageSizeAbsolute.width * i, 0.f), .size = self.pageSizeAbsolute};
    }
}

- (void)onBeginScrolling
{
    if ([self.delegate respondsToSelector:@selector(paginalContainerView:willScrollFromPageAtIndex:)]) {
        [self.delegate paginalContainerView:self willScrollFromPageAtIndex:[self indexOfCurrentPage]];
    }
}

- (void)onEndScrolling
{
    if ([self.delegate respondsToSelector:@selector(paginalContainerView:didScrollToPageAtIndex:)]) {
        [self.delegate paginalContainerView:self didScrollToPageAtIndex:[self indexOfCurrentPage]];
    }
}

@end


text:
const BaseStore = require('./../common/store');

/**
 * ServerStore module
 * @module ServerStore
 */
class Store extends BaseStore {
    /**
     * @extends BaseStore
     * @param {string} name
     * @param {Array} [initialState=[]]
     * @param {Object} [options={}]
     *
     * @alias module:ServerStore
     */
     constructor(name, intialState = [], options = {}) {
         super(name, intialState, options);
     }
}

module.exports = Store;


text:
/**
 * This file isn't used in this project. It was created by express-generator.
 */
//var express = require('express');
//var router = express.Router();
//
///* GET home page. */
//router.get('/', function(req, res, next) {
//  res.render('index', { title: 'Express' });
//});
//
//module.exports = router;


text:
export interface ISignupData {
    email: string,
    password: string,
    firstName: string,
    lastName: string,
    phone?: string,
    company: string,
    country: string
}

export interface ISignupFormController extends ng.IFormController {
    email: ng.INgModelController,
    password: ng.INgModelController,
    firstName: ng.INgModelController,
    lastName: ng.INgModelController,
    phone: ng.INgModelController,
    company: ng.INgModelController,
    country: ng.INgModelController
}


text:
var ApiMethod = require('bla').ApiMethod;
var config = require('./../../config/config');
var vowHandyHttp = require('../../lib/vow-handy-http');
var extend = require('extend');
var xml2js = require('xml2js');
var parser = new xml2js.Parser();
var vow = require('vow');

/**
 * Возвращает список элементов в каталоге
 *
 * curl -v -X PROPFIND -H 'Depth: 1' -H 'Authorization: OAuth b56608838c7f4550a88ca629d2f565cd' https://webdav.yandex.ru/
 */
module.exports = new ApiMethod({
    name: 'get-list',
    description: 'Returns files and folders from server',
    params: {
        folder: {
            type: 'String',
            description: 'Start folder',
            defaultValue: '/',
            required: true
        },
        depth: {
            type: 'Number',
            description: 'depth',
            defaultValue: 1
        },
        amount: {
            type: 'Number',
            description: 'amount of files'
        },
        offset: {
            type: 'Number',
            description: 'start offset'
        }
    },
    action: function (params) {
        var options = {
            method: 'PROPFIND',
            headers: {
                Depth: params.depth
            }
        };
        var ext = extend(true, {}, config.auth, options);
        ext.url += params.folder;

        if (params.start && params.offset) {
            ext.url += '?offset=' + params.offset + '&amount=' + params.start;
        }

        return vowHandyHttp(ext)
            .then(function (data) {
                var defer = vow.defer();
                if (data && data.toString() && data.toString().indexOf('authoriz') !== -1) {
                    defer.reject('Authorize error');
                }

                parser.parseString(data, function (err, result) {
                    if (err) {
                        defer.reject('Cannot parse xml. ' + err + data.toString());
                    }
                    defer.resolve(result);
                });

                return defer.promise();
            })
            .then(function (data) {
                return data['d:multistatus']['d:response'] || null;
            });
    }
});