text:
import heapq
import re
import sys
import time
import cPickle

from apiary.tools.debug import *
from apiary.tools import mergetools
from apiary.tools import timestamp

__all__ = [
    'Event',
    'CoalescedEvent',
    'Sequence',
    'parse_stanza',
    'EventReader',
    'input_events',
    'FollowSequences',
    'CoalesceSequences'
]

headerRE = re.compile(r'^(?P<time>\d+\.\d+)\t(?P<id>[\d.:]+)\t?(?P<source>\S*)\t(?P<state>\w+)$')
breakRE = re.compile(r'^\*{3,}$')
commentRE = re.compile(r'^\-{2,}.*$')
timeRE = re.compile(r'^# Time: (\d+ [\d\w:.]+)$')
clientRE = re.compile(r'^# Client: ([\d.:]+)$')
threadRE = re.compile(r'# Thread_id: (\d+)$')
admin_commandRE = re.compile(r'^# administrator command: (\w+);$')
query_log_commentRE = re.compile(r'^#')

class EventFile(object):
    def __init__(self, name):
        if name == "-":
            self._file = sys.stdin
        else:
            self._file = open(name, 'r')

        self._lines = []

    def readline(self):
        if self._lines:
            return self._lines.pop()
        else:
            return self._file.readline()

    def unreadline(self, line):
        self._lines.append(line)

class Event(object):
    # state values
    Query = 'QueryStart'
    Response = 'QueryResponse'
    End = 'Quit'

    #@traced_method
    def __init__(self, time, id, source, state, body):
        self.time = time
        if type(time) is not timestamp.TimeStamp:
            self.time = timestamp.TimeStamp(time)
        self.id = id
        self.source = source
        self.state = state
        self.body = body

    def __cmp__(self, other):
        c = cmp(self.time, other.time)
        if c == 0:
            if self.state == "Quit" and other.state != "Quit":
                return 1
            if self.state != "Quit" and other.state == "Quit":
                return -1
        return c

    def __str__(self):
        return ("%s\t%s\t%s\t%s\n%s\n**************************************\n" %
                (self.time, self.id, self.source, self.state, self.body))

    def events(self):
        es = []
        for event in self.body.split("\n+++\n"):
            parts = event.split(":", 1)
            if len(parts) == 2:
                (time, body) = parts
                status = Event.Query
                if body == "Quit":
                    status = Event.End
                es.append(Event(time, self.id, self.source, status, body))
        return es

class CoalescedEvent(Event):
    Sequence = 'Sequence'

    def __init__(self, shelf_life=None, max_life=None):
        self.time = None
        self.id = None
        self.source = None
        self.state = CoalescedEvent.Sequence
        self.body = ""
        self.ended = False
        self.lasttime = None
        self.staletime = None
        self.maxtime = None
        self.shelf_life = None
        if shelf_life:
            self.shelf_life = timestamp.TimeStamp(shelf_life)
        self.max_life = None
        if max_life:
            self.max_life = timestamp.TimeStamp(max_life)

    def add(self, event):
        if self.time is None:
            self.time = event.time
            if self.max_life:
                self.maxtime = self.time + self.max_life
            self.id = event.id
            self.source = event.source
        self.lasttime = event.time
        if self.shelf_life:
            self.staletime = self.lasttime + self.shelf_life
        if event.state == Event.End:
            self.body += "%s:Quit\n+++\n" % (event.time)
            self.ended = True
        elif event.state == Event.Query:
            self.body += "%s:%s\n+++\n" % (event.time, event.body)
        # Ignore Event.QueryResponse, because we only care about queries sent.

    def endIfNeeded(self):
        if not self.ended:
            self.add(Event(self.lasttime, self.id, self.source,
                            Event.End, 'Quit'))

#@traced_func
def parse_stanza(input):

    # This function is a bit gnarly because it can handle either the output of
    # mk-query-digest or the output of mysql_watcher/mysql_logger.
    #
    # mk-query-digest parsing code borrowed from Dante Linden.

    seconds = 0
    id = ''
    source = ''
    state = Event.Query
    admin_command = ''
    line = ''
    body = ''
    match = None
    while not match and not query_log_commentRE.match(line):
        line = input.readline()
        if line == '':  # empty string means EOF
            return None
        if commentRE.match(line):  # catch comments before the headers
            line = input.readline()  # Skip the line
        # parse the header in case it's a seq log
        match = headerRE.match(line)

    if match:
        seconds = match.group('time')
        id = match.group('id')
        source = match.group('source') or ''
        state = match.group('state')

        line = input.readline()

    # if processing a mk-query-digest query log, extract info from comments
    while query_log_commentRE.match(line):
        if timeRE.match(line):
            # if seconds, then you've hit another query in a digest log because
            # the previous query had no body (i.e., the comments from one query
            # border the comments for the next query)
            if seconds:
                # seek backward so we can process this timestamp as part of the
                # next stanza
                input.unreadline(line)
                return Event(float(seconds), id, source, state, body)

            timestamp = timeRE.match(line).groups()[0]
            # convert timestamp into seconds since epoch:
            # strip off subseconds, convert remainder to seconds,
            # append subseconds
            parts = timestamp.split('.')
            if len(parts) == 2:
                date_time, subseconds = timestamp.split('.')
            else:
                date_time = timestamp
                subseconds = 0
            seconds = str(int(time.mktime(time.strptime(date_time, "%y%m%d %H:%M:%S")))) + ".%s" % subseconds
        if clientRE.match(line):
            id = clientRE.match(line).groups()[0]
        if threadRE.match(line):
            id += ':%s' % threadRE.match(line).groups(0)
        if admin_commandRE.match(line):
            admin_command = admin_commandRE.match(line).groups()[0]
            if admin_command == "Quit":
                state = Event.End

        line = input.readline()
        if line == '':
            return None

    # we should be to the body of the stanza now
    while True:
        while commentRE.match(line):
            line = input.readline()  # Skip the line
        if line == '':  # EOF
            break
        if breakRE.match(line):
            break
        if query_log_commentRE.match(line):
            break
        body += line
        line = input.readline()

    # any admin commands follow the body
    if admin_commandRE.match(line):
        admin_command = admin_commandRE.match(line).groups()[0]
        if admin_command == "Quit":
            state = Event.End
    else:
        # the last line we read was a comment.  seek backwards
        # so that we see it the next time we read from input
        input.unreadline(line)
    #print "seconds=%s, id=%s, body=%s" % (seconds, id, body)
    return Event(float(seconds), id, source, state, body)

class Sequence(object):
    def __init__(self):
        self._count = 0
        self._time_start = None
        self._last_event = None

    def note(self, event):
        self._count += 1
        if self._time_start is None:
            self._time_start = event.time
        self._last_event = event

    def count(self):
        return self._count

    def time(self):
        return self._last_event.time - self._time_start

    def timeto(self, event):
        if self._last_event is None:
            return None
        return event.time - self._last_event.time

    def ended(self):
        return self._last_event.state == Event.End

    def generateEnd(self, t=None):
        e = self._last_event
        if t is None:
            t = e.time
        return Event(t, e.id, e.source, Event.End, "")

class RawEventReader(object):
    def __init__(self, input):
        self._input = input

    def __iter__(self):
        while True:
            s = parse_stanza(self._input)
            if s is None:
                return
            yield s

class EventReader(object):
    def __init__(self, input):
        self._input = input

    def __iter__(self):
        while True:
            s = parse_stanza(self._input)
            if s is None:
                return
            if s.state == CoalescedEvent.Sequence:
                for t in s.events():
                    yield t
            else:
                yield s

#@traced_func
def input_events(specs):
    if len(specs) == 0:
        specs = ['-']
    evs = [EventReader(EventFile(spec)) for spec in specs]
    return mergetools.imerge(*evs)

def split_events(specs, dest_prefix, num_splits):
    if len(specs) == 0:
        specs = ['-']

    dests = [open(dest_prefix + str(n), 'w') for n in xrange(num_splits)]

    evs = [EventReader(EventFile(spec)) for spec in specs]
    merged = mergetools.imerge(*evs)

    start_time = time.time()

    for num, event in enumerate(merged):
        if num % 10000 == 0:
            elapsed = time.time() - start_time
            print "split %d events in %s seconds (%.2f events/sec)..." % (num, elapsed, float(num) / float(elapsed))

        dests[num % num_splits].write(str(event))

def pickle_events(specs, dest):
    if len(specs) == 0:
        specs = ['-']

    if not isinstance(dest, file):
        dest = open(dest, 'w')

    evs = [EventReader(EventFile(spec)) for spec in specs]
    merged = mergetools.imerge(*evs)

    start_time = time.time()

    for num, event in enumerate(merged):
        if num % 10000 == 0:
            elapsed = time.time() - start_time
            print "pickled %d events in %s seconds (%.2f events/sec)..." % (num, elapsed, float(num) / float(elapsed))

        if event.state == CoalescedEvent.Sequence:
            for subevent in event.events():
                cPickle.dump(subevent, file=dest)
        else:
            cPickle.dump(event, file=dest)

def input_pickled_events(specs):
    for spec in specs:
        sequence_file = open(spec)

        while True:
            try:
                event = cPickle.load(sequence_file)
                if event.state == CoalescedEvent.Sequence:
                    for subevent in event.events():
                        yield subevent
                else:
                    yield event
            except EOFError:
                break

class FollowSequences(object):
    def replay(self, events):
        connections = {}
        lastt = None
        for e in events:
            id = e.id
            lastt = e.time
            if id not in connections:
                s = connections[id] = Sequence()
                self.addingSequence(s, e)
            else:
                s = connections[id]
            self.notingEvent(s, e)
            s.note(e)
            if s.ended():
                self.removingSequence(s, e)
                del connections[id]
            if False:
                expired = []
                for (id, s) in connections.iteritems():
                    w = s.timeto(e)
                    if w and float(w) > 60.0:
                        expired.append((id, s))
                for (id, s) in expired:
                    f = s.generateEnd(e.time)
                    self.forcedEnd(s, f)
                    self.removingSequence(s, f)
                    del connections[id]
        for s in connections.itervalues():
            f = s.generateEnd(lastt)
            self.forcedEnd(s, f)
            self.removingSequence(s, f)

    def addingSequence(self, s, e):
        pass

    def notingEvent(self, s, e):
        pass

    def forcedEnd(self, s, e):
        pass

    def removingSequence(self, s, e):
        pass

class CoalesceSequences(object):
    def __init__(self):
        self.connections = {}
        self.bytime = []
        self.starttime = None
        self.lasttime = None

    def heartbeat(self, n):
        if self.bytime:
            sys.stderr.write("front of the queue = %s\n" % self.bytime[0].id)
        sys.stderr.write("%s: %d events... (%d connections, %d waiting)\n" %
                         (str(self.lasttime - self.starttime),
                          n,
                          len(self.connections),
                          len(self.bytime)))

        # The stuff below summarizes the queue in this format:
        # : <item> : <item> : <item>
        # Where <item> is one of:
        #   connection id(time since last message seen)
        #   -- n -- where n is a number of ended connections just waiting to be printed
        #
        # Up to the first 5 connections found will be printed, along with the gaps of ended connections
        # between them.

        n = 0
        i = 0
        l = len(self.bytime)
        s = ""
        while n < 5 and i < l:
            en = 0
            while i < l and self.bytime[i].ended:
                en += 1
                i += 1
            if en > 0:
                s += " : --%d--" % en
            else:
                n += 1
                s += " : %s(%s)" % (self.bytime[i].id, str(self.lasttime - self.bytime[i].lasttime))
                i += 1
        sys.stderr.write("                          ")
        sys.stderr.write(s)
        sys.stderr.write("\n")

    def age_out(self, c):
        if c.staletime and self.lasttime >= c.staletime:
            sys.stderr.write("                           expiring %s, stale\n" % c.id)
        elif c.maxtime and self.lasttime >= c.maxtime:
            sys.stderr.write("                           expiring %s, maxed out\n" % c.id)
        else:
            return False
        c.endIfNeeded()
        del self.connections[c.id]
        return True

    def flush_completed(self):
        """Print query sequences that have completed.

        Query sequences are always printed in order of the time the
        sequence started.  Sequence endings are sometimes not present
        in the event stream, in which case we must wait until the
        sequence times out before printing it out.  No sequences after
        the "stuck" sequence will be printed until it times out.
        """

        bytime = self.bytime

        while bytime:
            c = bytime[0]
            if not c.ended:
                if not self.age_out(c):
                    return
            heapq.heappop(bytime)
            self.fullSequence(c)

    def flush_all(self):
        """Flush all sequences.

        Sequences are flushed even if no end event has been seen and
        they have not timed out yet.
        """

        while self.bytime:
            c = heapq.heappop(self.bytime)
            c.endIfNeeded()
            self.fullSequence(c)

    def replay(self, events):
        """Correlate an interleaved query stream into sequences of queries."""

        # n = number of events seen
        n = 0

        # s = number of sequences seen
        s = 0

        # self.connections tracks open connections for which we have not seen an end event.
        connections = self.connections

        # bytime contains all queries that have not yet been printed as
        # sequences.  It is a min-heap ordered by time, so that the
        # earliest event is always first in the list.
        bytime = self.bytime

        for e in events:
            id = e.id
            self.lasttime = e.time
            if self.starttime is None:
                self.starttime = self.lasttime

            n += 1
            if n % 10000 == 0:
                # Print stats every 10000 events.
                self.heartbeat(n)

            # If this connection is already in the lsit of open connections,
            # see if it's stale or too old.  Sometimes the query stream doesn't
            # contain the End event for a given connection, so we need to time
            # it out.
            if id in connections:
                c = connections[id]
                self.age_out(c)

            # At this point, the connection may have been aged out and removed from
            # self.connections.  Otherwise, this could be the first message seen
            # for this connection.  In either case, make a new connection.
            if id not in connections:
                s += 1
                c = connections[id] = CoalescedEvent(300.0, 900.0)
                c.add(e)
                heapq.heappush(bytime, c)
            else:
                c.add(e)

            # Check if the connection is closing.  If so, remove it from
            # self.connections, but don't print it out yet.  Events must
            # be printed in order.
            if e.state == Event.End:
                del connections[id]

            self.flush_completed()

        for d in connections.itervalues():
            d.endIfNeeded()
        self.flush_all()

        print >> sys.stderr, "%d events processed; %d sequences produced" % (n, s)

    def fullSequence(self, e):
        raise NotImplemented("fullSequence() should be implemented by a child class")


text:
'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  DataPoint = mongoose.model('DataPoint'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller'));

// Create the chat configuration
module.exports = function (io, socket) {
  // Emit the status event when a new socket client is connected
  /*
  io.emit('chatMessage', {
    type: 'status',
    text: 'Is now connected',
    created: Date.now(),
    profileImageURL: socket.request.user.profileImageURL,
    username: socket.request.user.username
  });*/

  // Send a chat messages to all connected sockets when a message is received
  socket.on('chatMessage', function (message) {
    message.type = 'message';
    message.created = Date.now();
    message.profileImageURL = socket.request.user.profileImageURL;
    message.username = socket.request.user.username;

    // Emit the 'chatMessage' event
    io.emit('chatMessage', message);
  });

  var emitName = 'dbChange';
  io.on('connection', function(socket){
    socket.on(emitName, function(msg) {
      console.log('message: ' + msg);
      io.emit('newResult', msg);

      //Save the information to MongoDB

      var datapoint = new DataPoint({ value: msg });
      datapoint.save(function (err) {
        if (err) {
          console.log('Error Did not save');
        } else {
          console.log('Saved Fine');
        }
      });
    });
  });

  /*
  // Emit the status event when a socket client is disconnected
  socket.on('disconnect', function () {
    io.emit('chatMessage', {
      type: 'status',
      text: 'disconnected',
      created: Date.now(),
      username: socket.request.user.username
    });
  });
*/
};

redpajama_set_name: RedPajamaGithub


text:
<?php

class Google_Service_ShoppingContent_Collection extends Google_Collection
{
  protected $collection_key = 'imageLink';
  public $customLabel0;
  public $customLabel1;
  public $customLabel2;
  public $customLabel3;
  public $customLabel4;
  protected $featuredProductType = 'Google_Service_ShoppingContent_CollectionFeaturedProduct';
  protected $featuredProductDataType = 'array';
  public $headline;
  public $id;
  public $imageLink;
  public $language;
  public $link;
  public $mobileLink;
  public $productCountry;

  public function setCustomLabel0($customLabel0)
  {
    $this->customLabel0 = $customLabel0;
  }
  public function getCustomLabel0()
  {
    return $this->customLabel0;
  }
  public function setCustomLabel1($customLabel1)
  {
    $this->customLabel1 = $customLabel1;
  }
  public function getCustomLabel1()
  {
    return $this->customLabel1;
  }
  public function setCustomLabel2($customLabel2)
  {
    $this->customLabel2 = $customLabel2;
  }
  public function getCustomLabel2()
  {
    return $this->customLabel2;
  }
  public function setCustomLabel3($customLabel3)
  {
    $this->customLabel3 = $customLabel3;
  }
  public function getCustomLabel3()
  {
    return $this->customLabel3;
  }
  public function setCustomLabel4($customLabel4)
  {
    $this->customLabel4 = $customLabel4;
  }
  public function getCustomLabel4()
  {
    return $this->customLabel4;
  }
  /**
   * @param Google_Service_ShoppingContent_CollectionFeaturedProduct[]
   */
  public function setFeaturedProduct($featuredProduct)
  {
    $this->featuredProduct = $featuredProduct;
  }
  /**
   * @return Google_Service_ShoppingContent_CollectionFeaturedProduct[]
   */
  public function getFeaturedProduct()
  {
    return $this->featuredProduct;
  }
  public function setHeadline($headline)
  {
    $this->headline = $headline;
  }
  public function getHeadline()
  {
    return $this->headline;
  }
  public function setId($id)
  {
    $this->id = $id;
  }
  public function getId()
  {
    return $this->id;
  }
  public function setImageLink($imageLink)
  {
    $this->imageLink = $imageLink;
  }
  public function getImageLink()
  {
    return $this->imageLink;
  }
  public function setLanguage($language)
  {
    $this->language = $language;
  }
  public function getLanguage()
  {
    return $this->language;
  }
  public function setLink($link)
  {
    $this->link = $link;
  }
  public function getLink()
  {
    return $this->link;
  }
  public function setMobileLink($mobileLink)
  {
    $this->mobileLink = $mobileLink;
  }
  public function getMobileLink()
  {
    return $this->mobileLink;
  }
  public function setProductCountry($productCountry)
  {
    $this->productCountry = $productCountry;
  }
  public function getProductCountry()
  {
    return $this->productCountry;
  }
}


text:
//
//  nextStage1.m
//  Ninjaboy
//
//  Created by Objectsol on 16/06/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "tutorial.h"
#import "SimpleAudioEngine.h"

@implementation tutorial

+(id) scene
{

	CCScene *scene = [CCScene node];

    HUDsound *hud = [HUDsound node];
    [scene addChild:hud z:1];

    tutorial *layer = [[[tutorial alloc] initWithHUD:hud] autorelease];
    [scene addChild:layer];

    return scene;
}

- (id)initWithHUD:(HUDsound *)hud
{
    if ((self = [super init]))
	{
		[self startOfGame];
    }
    return self;
}

-(void) startOfGame
{
	// always call "super" init

		[[SimpleAudioEngine sharedEngine]stopBackgroundMusic];

		[[CCDirector sharedDirector] resume] ;

		CCSprite *backGround = [CCSprite spriteWithFile:@"start.png"];
		backGround.position = ccp(240, 160);

		[self addChild:backGround  z:-2];

		self.isTouchEnabled = YES;

	    scrollView1 = [[UIScrollView alloc] initWithFrame:CGRectMake(15, 158,242,110)];
	    [scrollView1 setBackgroundColor:[UIColor clearColor]];
	    scrollView1.clipsToBounds = YES;		// default is NO, we want to restrict drawing within our scrollview
	    scrollView1.scrollEnabled = YES;
	    scrollView1.showsHorizontalScrollIndicator=NO;
	    scrollView1.showsVerticalScrollIndicator=NO;
	    scrollView1.pagingEnabled=NO;
	    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"screen3n.png"]];
	    [scrollView1 addSubview:imageView];
	    [scrollView1 setContentSize:CGSizeMake(scrollView1.frame.size.width, imageView.frame.size.height)];
	    [scrollView1 setScrollEnabled:YES];
	    [imageView release];
	    [[[CCDirector sharedDirector]openGLView] addSubview:scrollView1];

		/*[self schedule:@selector(particleBubble) interval:1.4];
		[[SimpleAudioEngine sharedEngine]stopBackgroundMusic];
		[[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"Background.wav"];*/
        CCMenuItem *starMenuItem14 = [CCMenuItemImage
								  itemFromNormalImage:@"MainMenuUp.png" selectedImage:@"MainMenuDown.png"
								  target:self selector:@selector(goToMain)];
	    starMenuItem14.position = ccp(220, 260);

	    CCMenu *starMenu14 = [CCMenu menuWithItems:starMenuItem14, nil];
	    starMenu14.position = CGPointZero;
	    starMenu14.scale=1.2;
	    [self addChild:starMenu14 z:44];

}

-(void)goToMain
{
	[scrollView1   removeFromSuperview];
	scrollView1=nil;
	[[CCDirector sharedDirector] pause] ;
	[[CCDirector sharedDirector] replaceScene:[menuPage scene]];

}

- (void) dealloc
{
	[[CCDirector sharedDirector] purgeCachedData];
	[self unscheduleAllSelectors];
	[[CCSpriteFrameCache sharedSpriteFrameCache] removeUnusedSpriteFrames];
	[[CCTextureCache sharedTextureCache] removeAllTextures];
	[super dealloc];
}

@end


text:
<?php

namespace DevPortal\TomasBlatnyEu\Presenters;

use Nette;

class Error4xxPresenter extends Nette\Application\UI\Presenter
{

	public function startup()
	{
		parent::startup();
		if (!$this->getRequest()->isMethod(Nette\Application\Request::FORWARD)) {
			$this->error();
		}
	}

	public function renderDefault(Nette\Application\BadRequestException $exception)
	{
		// load template 403.latte or 404.latte or ... 4xx.latte
		$file = __DIR__ . "/templates/Error/{$exception->getCode()}.latte";
		$this->template->setFile(is_file($file) ? $file : __DIR__ . '/templates/Error/4xx.latte');
	}

}


text:
<?php

	require_once('class.session.php');

	Class Cookie{

		private $_index;
		private $_session;

		private $_timeout;
		private $_path;
		private $_domain;

		public function __construct($index, $timeout = 0, $path = '/', $domain=NULL, $session_table='tbl_sessions') {
			$this->_index = $index;
			$this->_timeout = $timeout;
			$this->_path = $path;
			$this->_domain = $domain;
			$this->_session = false;
			$this->_session_table = $session_table;

			$this->__init();
		}

		public function set($name, $value) {
			if (!$this->_session) {
				$this->__init();
			}

			$_SESSION[$this->_index][$name] = $value;
		}

		public function get($name) {
			if (!$this->_session) {
				$this->__init();
			}

			if (!isset($_SESSION[$this->_index][$name])) {
				return null;
			}

			return $_SESSION[$this->_index][$name];
		}

		public function expire() {
			if (!$this->_session) {
				$this->__init();
			}

			if(!is_array($_SESSION[$this->_index]) || empty($_SESSION[$this->_index])) return;

			unset($_SESSION[$this->_index]);
		}

		private function __init() {
			if ($this->_session) return $this->_session;

			$this->_session = Session::start($this->_timeout, $this->_path, $this->_domain, $this->_session_table);
			if (!$this->_session) return false;

			if (!isset($_SESSION[$this->_index])) $_SESSION[$this->_index] = array();

			// Class FrontendPage uses $_COOKIE directly (inside it's __buildPage() function), so try to emulate it.
			$_COOKIE[$this->_index] = &$_SESSION[$this->_index];

			return $this->_session;
		}

	}


text:
<?xml version="1.0"?>
<document>
  <properties>
    <title>Graphical Administration</title>
    <author email="brett@apache.org">Brett Porter</author>
  </properties>

          Archiva has a comprehensive web-based administration interface for configuring repositories,
          remote proxies, scheduled jobs and more. The configuration is kept in sync with the XML
          configuration files so that they can also be hand-edited if necessary.

          Previous: Artifact Upload |
          Graphical Administration |
          Next: Virtual Repositories

</document>


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Authorization.Models
{
    /// <summary> Role definition list operation result. </summary>
    public partial class RoleDefinitionListResult
    {
        /// <summary> Initializes a new instance of RoleDefinitionListResult. </summary>
        internal RoleDefinitionListResult()
        {
            Value = new ChangeTrackingList<RoleDefinition>();
        }

        /// <summary> Initializes a new instance of RoleDefinitionListResult. </summary>
        /// <param name="value"> Role definition list. </param>
        /// <param name="nextLink"> The URL to use for getting the next set of results. </param>
        internal RoleDefinitionListResult(IReadOnlyList<RoleDefinition> value, string nextLink)
        {
            Value = value;
            NextLink = nextLink;
        }

        /// <summary> Role definition list. </summary>
        public IReadOnlyList<RoleDefinition> Value { get; }
        /// <summary> The URL to use for getting the next set of results. </summary>
        public string NextLink { get; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GA.Nucleus.Gene;
using GA.Nucleus.Population;

namespace GA.Nucleus.Chromosome {
    public interface IChromosome : IList<IGene>, ICloneable {

		#region Methods

		string GeneSequence();
		void FillRandomly(List<IGene> genepool, int count);

		#endregion Methods
	}
}


text:
<?php

namespace Oro\Bundle\EmailBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

use JMS\Serializer\Annotation as JMS;

use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Translatable\Translatable;

use Symfony\Component\Validator\Constraints as Assert;

use Oro\Bundle\OrganizationBundle\Entity\Organization;
use Oro\Bundle\EntityConfigBundle\Metadata\Annotation\Config;
use Oro\Bundle\EmailBundle\Model\EmailTemplateInterface;
use Oro\Bundle\UserBundle\Entity\User;

/**
 * EmailTemplate
 *
 * @ORM\Table(name="oro_email_template",
 *      uniqueConstraints={@ORM\UniqueConstraint(name="UQ_NAME", columns={"name", "entityName"})},
 *      indexes={@ORM\Index(name="email_name_idx", columns={"name"}),
 * @ORM\Index(name="email_is_system_idx", columns={"isSystem"}),
 * @ORM\Index(name="email_entity_name_idx", columns={"entityName"})})
 * @ORM\Entity(repositoryClass="Oro\Bundle\EmailBundle\Entity\Repository\EmailTemplateRepository")
 * @Gedmo\TranslationEntity(class="Oro\Bundle\EmailBundle\Entity\EmailTemplateTranslation")
 * @Config(
 *      defaultValues={
 *          "ownership"={
 *              "owner_type"="USER",
 *              "owner_field_name"="owner",
 *              "owner_column_name"="user_owner_id",
 *              "organization_field_name"="organization",
 *              "organization_column_name"="organization_id"
 *          },
 *          "security"={
 *              "type"="ACL",
 *              "group_name"="",
 *              "category"="account_management"
 *          },
 *          "note"={
 *              "immutable"=true
 *          },
 *          "activity"={
 *              "immutable"=true
 *          },
 *          "attachment"={
 *              "immutable"=true
 *          }
 *      }
 * )
 * @JMS\ExclusionPolicy("ALL")
 */
class EmailTemplate implements EmailTemplateInterface, Translatable
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @JMS\Type("integer")
     * @JMS\Expose
     */
    protected $id;

    /**
     * @var boolean
     *
     * @ORM\Column(name="isSystem", type="boolean")
     * @JMS\Type("boolean")
     * @JMS\Expose
     */
    protected $isSystem;

    /**
     * @var boolean
     *
     * @ORM\Column(name="isEditable", type="boolean")
     * @JMS\Type("boolean")
     * @JMS\Expose
     */
    protected $isEditable;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     * @JMS\Type("string")
     * @JMS\Expose
     */
    protected $name;

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="Oro\Bundle\UserBundle\Entity\User")
     * @ORM\JoinColumn(name="user_owner_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $owner;

    /**
     * @var integer
     *
     * @ORM\Column(name="parent", type="integer", nullable=true)
     * @JMS\Type("integer")
     * @JMS\Expose
     */
    protected $parent;

    /**
     * @var string
     *
     * @ORM\Column(name="subject", type="string", length=255, nullable=true)
     * @Gedmo\Translatable
     * @JMS\Type("string")
     * @JMS\Expose
     */
    protected $subject;

    /**
     * @var string
     *
     * @ORM\Column(name="content", type="text", nullable=true)
     * @Gedmo\Translatable
     * @JMS\Type("string")
     * @JMS\Expose
     */
    protected $content;

    /**
     * @var string
     *
     * @ORM\Column(name="entityName", type="string", length=255, nullable=true)
     * @JMS\Type("string")
     * @JMS\Expose
     */
    protected $entityName;

    /**
     * Template type:
     *  - html
     *  - text
     *
     * @var string
     *
     * @ORM\Column(name="type", type="string", length=20)
     * @JMS\Type("string")
     * @JMS\Expose
     */
    protected $type = 'html';

    /**
     * @var string
     *
     * @Gedmo\Locale()
     */
    protected $locale;

    /**
     * @ORM\OneToMany(
     *     targetEntity="Oro\Bundle\EmailBundle\Entity\EmailTemplateTranslation",
     *     mappedBy="object",
     *     cascade={"persist", "remove"}
     * )
     * @Assert\Valid(deep = true)
     */
    protected $translations;

    /**
     * @var Organization
     *
     * @ORM\ManyToOne(targetEntity="Oro\Bundle\OrganizationBundle\Entity\Organization")
     * @ORM\JoinColumn(name="organization_id", referencedColumnName="id", onDelete="SET NULL")
     */
    protected $organization;

    /**
     * @ORM\Column(type="boolean", options={"default"=true})
     * @var bool
     */
    protected $visible = true;

    /**
     * @param        $name
     * @param string $content
     * @param string $type
     * @param bool   $isSystem
     */
    public function __construct($name = '', $content = '', $type = 'html', $isSystem = false)
    {
        // name can be overridden from email template
        $this->name = $name;
        // isSystem can be overridden from email template
        $this->isSystem = $isSystem;
        // isEditable can be overridden from email template
        $this->isEditable = false;

        $parsedContent = self::parseContent($content);
        foreach ($parsedContent['params'] as $param => $val) {
            $this->$param = $val;
        }

        // make sure that user's template is editable
        if (!$this->isSystem && !$this->isEditable) {
            $this->isEditable = true;
        }

        $this->type         = $type;
        $this->content      = $parsedContent['content'];
        $this->translations = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     *
     * @return EmailTemplate
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Gets owning user
     *
     * @return User
     */
    public function getOwner()
    {
        return $this->owner;
    }

    /**
     * Sets owning user
     *
     * @param User $owningUser
     *
     * @return EmailTemplate
     */
    public function setOwner($owningUser)
    {
        $this->owner = $owningUser;

        return $this;
    }

    /**
     * Set parent
     *
     * @param integer $parent
     *
     * @return EmailTemplate
     */
    public function setParent($parent)
    {
        $this->parent = $parent;

        return $this;
    }

    /**
     * Get parent
     *
     * @return integer
     */
    public function getParent()
    {
        return $this->parent;
    }

    /**
     * {@inheritdoc}
     */
    public function setSubject($subject)
    {
        $this->subject = $subject;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getSubject()
    {
        return $this->subject;
    }

    /**
     * {@inheritdoc}
     */
    public function setContent($content)
    {
        $this->content = $content;

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Set entityName
     *
     * @param string $entityName
     *
     * @return EmailTemplate
     */
    public function setEntityName($entityName)
    {
        $this->entityName = $entityName;

        return $this;
    }

    /**
     * Get entityName
     *
     * @return string
     */
    public function getEntityName()
    {
        return $this->entityName;
    }

    /**
     * Set a flag indicates whether a template is system or not.
     *
     * @param boolean $isSystem
     *
     * @return EmailTemplate
     */
    public function setIsSystem($isSystem)
    {
        $this->isSystem = $isSystem;

        return $this;
    }

    /**
     * Get a flag indicates whether a template is system or not.
     * System templates cannot be removed or changed.
     *
     * @return boolean
     */
    public function getIsSystem()
    {
        return $this->isSystem;
    }

    /**
     * Get a flag indicates whether a template can be changed.
     *
     * @param boolean $isEditable
     *
     * @return EmailTemplate
     */
    public function setIsEditable($isEditable)
    {
        $this->isEditable = $isEditable;

        return $this;
    }

    /**
     * Get a flag indicates whether a template can be changed.
     * For user's templates this flag has no sense (these templates always have this flag true)
     * But editable system templates can be changed (but cannot be removed or renamed).
     *
     * @return boolean
     */
    public function getIsEditable()
    {
        return $this->isEditable;
    }

    /**
     * Set locale
     *
     * @param string $locale
     *
     * @return EmailTemplate
     */
    public function setLocale($locale)
    {
        $this->locale = $locale;

        return $this;
    }

    /**
     * Get locale
     *
     * @return string
     */
    public function getLocale()
    {
        return $this->locale;
    }

    /**
     * Set template type
     *
     * @param string $type
     *
     * @return EmailTemplate
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get template type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set translations
     *
     * @param ArrayCollection $translations
     *
     * @return EmailTemplate
     */
    public function setTranslations($translations)
    {
        /** @var EmailTemplateTranslation $translation */
        foreach ($translations as $translation) {
            $translation->setObject($this);
        }

        $this->translations = $translations;

        return $this;
    }

    /**
     * Get translations
     *
     * @return ArrayCollection|EmailTemplateTranslation[]
     */
    public function getTranslations()
    {
        return $this->translations;
    }

    /**
     * Set organization
     *
     * @param Organization $organization
     *
     * @return EmailTemplate
     */
    public function setOrganization(Organization $organization = null)
    {
        $this->organization = $organization;

        return $this;
    }

    /**
     * Get organization
     *
     * @return Organization
     */
    public function getOrganization()
    {
        return $this->organization;
    }

    /**
     * @return bool
     */
    public function isVisible()
    {
        return $this->visible;
    }

    /**
     * @param bool $visible
     *
     * @return $this
     */
    public function setVisible($visible = true)
    {
        $this->visible = $visible;

        return $this;
    }

    /**
     * Clone template
     */
    public function __clone()
    {
        // cloned entity will be child
        $this->parent     = $this->id;
        $this->id         = null;
        $this->isSystem   = false;
        $this->isEditable = true;

        if ($this->getTranslations() instanceof ArrayCollection) {
            $clonedTranslations = new ArrayCollection();
            foreach ($this->getTranslations() as $translation) {
                $clonedTranslations->add(clone $translation);
            }
            $this->setTranslations($clonedTranslations);
        }
    }

    /**
     * Convert entity to string
     *
     * @return string
     */
    public function __toString()
    {
        return (string)$this->getName();
    }

    /**
     * @param string $content
     *
     * @return array With keys 'content', 'params'
     */
    public static function parseContent($content)
    {
        $params = [];

        $boolParams     = array('isSystem', 'isEditable');
        $templateParams = array('name', 'subject', 'entityName', 'isSystem', 'isEditable');
        foreach ($templateParams as $templateParam) {
            if (preg_match('#@' . $templateParam . '\s?=\s?(.*)\n#i', $content, $match)) {
                $val = trim($match[1]);
                if (isset($boolParams[$templateParam])) {
                    $val = (bool)$val;
                }
                $params[$templateParam] = $val;
                $content                = trim(str_replace($match[0], '', $content));
            }
        }

        return [
            'content' => $content,
            'params'  => $params,
        ];
    }
}


text:
cd ../bundle
hadoop-2.7.1/bin/hdfs namenode -format


text:
/** \file rangelib/random_range.hpp Random number range class */

#ifndef RANGELIB_INCL_RANGELIB_HPP_RANDOM_RANGE
#define RANGELIB_INCL_RANGELIB_HPP_RANDOM_RANGE

#ifndef STLSOFT_DOCUMENTATION_SKIP_SECTION
# define RANGELIB_VER_RANGELIB_HPP_RANDOM_RANGE_MAJOR      2
# define RANGELIB_VER_RANGELIB_HPP_RANDOM_RANGE_MINOR      2
# define RANGELIB_VER_RANGELIB_HPP_RANDOM_RANGE_REVISION   3
# define RANGELIB_VER_RANGELIB_HPP_RANDOM_RANGE_EDIT       30
#endif /* !STLSOFT_DOCUMENTATION_SKIP_SECTION */

/* /////////////////////////////////////////////////////////////////////////
 * Auto-generation and compatibility
 */

/*
[Incompatibilies-start]
STLSOFT_COMPILER_IS_MSVC:     _MSC_VER < 1200
STLSOFT_COMPILER_IS_MWERKS:   (__MWERKS__ & 0xFF00) < 0x3000
[Incompatibilies-end]
 */

/* /////////////////////////////////////////////////////////////////////////
 * Includes
 */

#ifndef RANGELIB_INCL_RANGELIB_HPP_RANGELIB
# include <rangelib/rangelib.hpp>
#endif /* !RANGELIB_INCL_RANGELIB_HPP_RANGELIB */
#ifndef RANGELIB_INCL_RANGELIB_HPP_RANGE_CATEGORIES
# include <rangelib/range_categories.hpp>
#endif /* !RANGELIB_INCL_RANGELIB_HPP_RANGE_CATEGORIES */
#ifndef STLSOFT_INCL_STLSOFT_UTIL_HPP_OPERATOR_BOOL
# include <stlsoft/util/operator_bool.hpp>
#endif /* !STLSOFT_INCL_STLSOFT_UTIL_HPP_OPERATOR_BOOL */

#ifndef STLSOFT_INCL_H_STDLIB
# define STLSOFT_INCL_H_STDLIB
# include <stdlib.h>                     // for rand(), srand()
#endif /* !STLSOFT_INCL_H_STDLIB */

/* /////////////////////////////////////////////////////////////////////////
 * Namespace
 */

#ifndef RANGELIB_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
     defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
/* There is no stlsoft namespace, so must define ::rangelib */
namespace rangelib
{
# else
/* Define stlsoft::rangelib_project */

namespace stlsoft
{

namespace rangelib_project
{

# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !RANGELIB_NO_NAMESPACE */

/* /////////////////////////////////////////////////////////////////////////
 * Classes
 */

/** \brief This range class represents a range of random numbers.
 *
 * \ingroup group__library__rangelib
 *
 * It is categoried as a Notional Range
 *
 * It could be used as follows
\code
  // Create a range of 10 values, whose value are between -100 and +100
  stlsoft::random_range   r(10, -100, +100);

  // Dump them to stdout
  stlsoft::r_copy(r, std::ostream_iterator<int>(" "));
\endcode
 */
class random_range
    : public notional_range_tag
{
/// \name Types
/// @{
public:
    typedef int                 value_type;
    typedef notional_range_tag  range_tag_type;
    typedef random_range        class_type;
/// @}

/// \name Construction
/// @{
public:
    /// Constructs a random range
    ///
    /// \param numValues The number of values in the range
    /// \param minValue The lower limit of the random number range
    /// \param maxValue The upper limit of the random number range
    random_range(ss_size_t numValues, value_type minValue = 0, value_type maxValue = RAND_MAX)
        : m_numValues(numValues)
        , m_minValue(minValue)
        , m_maxValue(maxValue)
        , m_position(0)
        , m_value(next_value_(minValue, maxValue))
    {
        STLSOFT_ASSERT(minValue <= maxValue);
        STLSOFT_ASSERT((maxValue - minValue) <= RAND_MAX);
    }
/// @}

/// \name Notional Range methods
/// @{
private:
    STLSOFT_DEFINE_OPERATOR_BOOL_TYPES(class_type, operator_bool_generator_type, operator_bool_type);
public:
    /// Indicates whether the range is open
    ss_bool_t is_open() const
    {
        return m_position != m_numValues;
    }
    /// Returns the current value in the range
    value_type current() const
    {
        STLSOFT_MESSAGE_ASSERT("Attempting to access the value of a closed range", is_open());

        return m_value;
    }
    /// Advances the current position in the range
    class_type& advance()
    {
        STLSOFT_MESSAGE_ASSERT("Attempting to advance a closed range", is_open());

        ++m_position;
        m_value = next_value_(m_minValue, m_maxValue);

        return *this;
    }

    /// Indicates whether the range is open
    operator operator_bool_type() const
    {
        return operator_bool_generator_type::translate(is_open());
    }
    /// Returns the current value in the range
    value_type operator *() const
    {
        return current();
    }
    /// Advances the current position in the range
    class_type& operator ++()
    {
        return advance();
    }
    /// Advances the current position in the range, returning a copy of the
    /// range prior to its being advanced
    class_type operator ++(int)
    {
        class_type  ret(*this);

        operator ++();

        return ret;
    }
/// @}

/// \name Attributes
/// @{
public:
    /// The lower limit of the random number range
    value_type minimum() const
    {
        return m_minValue;
    }
    /// The upper limit of the random number range
    value_type maximum() const
    {
        return m_maxValue;
    }
/// @}

/// \name Comparison
/// @{
public:
    /// Evaluates whether two ranges are equal
    bool operator ==(class_type const& /* rhs */) const
    {
        return false;
    }
    /// Evaluates whether two ranges are unequal
    bool operator !=(class_type const& rhs) const
    {
        return ! operator ==(rhs);
    }
/// @}

/// \name Implementation
/// @{
private:
    static value_type next_value_(value_type minValue, value_type maxValue)
    {
        return (maxValue - minValue) ? minValue + (rand() % (maxValue - minValue)) : 0;
    }
/// @}

// Members
private:
    const ss_size_t m_numValues;
    const int       m_minValue;
    const int       m_maxValue;
    ss_size_t       m_position;
    int             m_value;

// Not to be implemented
private:
    class_type& operator =(class_type const&);
};

////////////////////////////////////////////////////////////////////////////
// Unit-testing

#ifdef STLSOFT_UNITTEST
# include "./unittest/random_range_unittest_.h"
#endif /* STLSOFT_UNITTEST */

/* ////////////////////////////////////////////////////////////////////// */

#ifndef RANGELIB_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
     defined(STLSOFT_DOCUMENTATION_SKIP_SECTION)
} // namespace rangelib
# else
} // namespace rangelib_project
} // namespace stlsoft
# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !RANGELIB_NO_NAMESPACE */

/* ////////////////////////////////////////////////////////////////////// */

#endif /* !RANGELIB_INCL_RANGELIB_HPP_RANDOM_RANGE */

/* ///////////////////////////// end of file //////////////////////////// */


text:
using FluentValidation;
using Starcounter;

namespace KitchenSink {
    partial class ValidationPage : Page
    {/*
        private SettingsValidator _settingsValidator;
        protected override void OnData()
        {
            base.OnData();
            _settingsValidator = new SettingsValidator();
        }

        void Handle(Input.Validate action)
        {
            _settingsValidator.Validate(this);
        }
    }
    public class SettingsValidator : ValidatorHelper<ValidationPage>
    {
        public SettingsValidator()
        {
            RuleFor(item => item.Name).NotEmpty().BindError((item, err) => { item.ErrorName = err; });
            RuleFor(item => item.LastName).NotEmpty().BindError((item, err) => { item.ErrorLastName = err; });
        }*/
    }
}


text:
*Note:* This repository is **deprecated** in favour of [r-ci](https://github.com/eddelbuettel/r-ci)
which is a portable generalization suitable for GitHub Actions, Azure
Pipelines, Travi, and likely more.  This repo and its script `run.sh` still
work, but updates will happen over at [r-ci](https://eddelbuettel.github.io/r-ci/).

This repository ~~is~~ was  a maintained fork of the (now deprecated) original
[r-travis](https://github.com/craigcitro/r-travis) repository by Craig Citro et al.  I was an early
[contributor to this project](https://github.com/craigcitro/r-travis/graphs/contributors), and quite
like its design and features -- so I have been keeping it around, maintained and extended it. It is
my 'go-to' CI setup for a few dozen repositories affecting a fairly decent number of users.

### Status

Maintained and used across Travis and GitHub Actions -- and also usable with
Azure Pipelines, locally using Docker, ...

Its main advantages as are _strong portability_ as well as _ease of use_ and _customizability_.

Note that as it is used beyond just one Continuous Integration (CI) backend, we decided to change
the name away from reflecting only one of the backends. So please see the
[r-ci](https://github.com/eddelbuettel/r-ci) for the continuation of this work.

### Basic Usage

A minimal example of use with Travis follows:

```sh
language: c
sudo: required
dist: focal

before_install:
  - curl -OLs https://eddelbuettel.github.io/r-ci/run.sh && chmod 0755 run.sh
  - ./run.sh bootstrap

install:
  - ./run.sh install_deps

script:
  - ./run.sh run_tests
```

This downloads the `run.sh` script, uses it to _bootstrap_ the test environment, then installs
dependencies via `install_deps` and finally runs tests. For a realistic but real example see _e.g._
[this .travis.yml file of package
digest](https://github.com/eddelbuettel/digest/blob/master/.travis.yml).

For another example, see package [tidyCpp](https://github.com/eddelbuettel/tidycpp/) which shows how
to use the `run.sh` script [with Travis
CI](https://github.com/eddelbuettel/tidycpp/blob/master/.travis.yml) as well as [with GitHub
Actions](https://github.com/eddelbuettel/tidycpp/blob/master/.github/workflows/R-CMD-check.yaml).

Numerous variations are possible: running 'test matrices' across macOS and Linux, using BSPM for
binaries (both of those [are used by
digest](https://github.com/eddelbuettel/digest/blob/master/.travis.yml), running with several g++
versions (as used by
[RcppSimdjson](https://github.com/eddelbuettel/rcppsimdjson/blob/master/.travis.yml), ...

We also use the same approach of downloading `run.sh` and invoking it for the different steps in
with GitHub Actions (_e.g._ for
[tidyCpp](https://github.com/eddelbuettel/tidycpp/blob/master/.github/workflows/R-CMD-check.yaml)). Similarly,
Azure Pipelines can be used (as was done by a test repo on Azure).

There are also other options of use with PPAs and more---for fullest details see the source of the
shell script `run.sh`.

### More

See the [webpage for r-travis](http://eddelbuettel.github.io/r-travis/) for more on this repo, and
the [webpage for r-ci](http://eddelbuettel.github.io/r-ci/) for more on its successor and
continuation.

### Author

Dirk Eddelbuettel (for this maintained fork)

Craig Citro, Kirill Mueller, Dirk Eddelbuettel, ... (for the original r-travis)


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('data_log', '0014_auto_20190615_2100'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='magicboxcraftrunecraftdrop',
            name='ancient',
        ),
        migrations.RemoveField(
            model_name='riftdungeonrunecraftdrop',
            name='ancient',
        ),
        migrations.RemoveField(
            model_name='riftraidrunecraftdrop',
            name='ancient',
        ),
    ]


text:
script=$(readlink -f "$0")
scriptpath=$(dirname "$script")

model_location="/tmp/test_model"
audio_recordings_location="/tmp/test_audio_recordings"
dict_file="/tmp/test_dict_file.txt"

printf "hello\nworld\ntest phrases\nlast one now\n" > "$dict_file"

vmc model_name \
-create $model_location \
-newrecordings $audio_recordings_location $dict_file 1


text:
var rolesModel = require('../data/models/roles');
var async = require('async');

function findAll (req, res, next) {
    rolesModel.findOne({ name: 'admin' }, function(err, root) {
        if (err) {
            return next(err);
        }
        rolesModel.rebuildTree(root, root.lft, function() {
            rolesModel.find({})
            .populate('parentId')
            .exec(function (err, roles) {
                if (err) {
                    return next(err);
                }
                res.send(roles);
            });
        });
    });
}

function findById (req, res, next) {
    rolesModel.findOne({ name: 'admin' }, function(err, root) {
        if (err) {
            return next(err);
        }
        rolesModel.rebuildTree(root, root.lft, function() {
            rolesModel.findById(req.params.id)
            .populate('parentId')
            .exec(function (err, role) {
                if (err) {
                    return next(err);
                }
                res.send(role);
            });
        });
    });
}

function add (req, res, next) {
    rolesModel.findOne({ lft: 1 }, function (err, root) {
        if (err) {
            return next(err);
        }
        rolesModel.rebuildTree(root, root.lft, function () {
            rolesModel.findOne({ _id: req.body.parentId }, function (err, parent) {
                if (err) {
                    return next(err);
                }
                var newRole = new rolesModel({
                    name: req.body.name,
                    parentId: parent._id
                });
                newRole.save(function (err, role) {
                    if (err) {
                        return next(err);
                    }
                    res.send(role);
                });
            });
        });
    });
}

function update (req, res, next) {
    rolesModel.findOne({ lft: 1 }, function (err, root) {
        if (err) {
            return next(err);
        }
        rolesModel.rebuildTree(root, root.lft, function () {
            rolesModel.findOne({ _id: req.body.parentId }, function (err, parent) {
                if (err) {
                    return next(err);
                }
                if (parent) {
                    rolesModel.findOneAndUpdate({_id: req.params.id}, req.body, { upsert: true,'new': true }, function (err, rawResponse) {
                        if (err) {
                            return next(err);
                        }
                        res.send(rawResponse);
                    });
                }
                else {
                    res.status(404).send();
                }
            });
        });
    });

}

function del (req, res, next) {
    rolesModel.findOne({ lft: 1 }, function(err, root) {
        if (err) {
            return next(err);
        }
        rolesModel.rebuildTree(root, root.lft, function() {
            rolesModel.findById(req.params.id, function(err, role) {
                if (err) {
                    return next(err);
                }
                role.remove(function(err, result) {
                    if (err) {
                        return next(err);
                    }
                    role.unIndex(function(err) {
                        if (err) {
                            return next(err);
                        }
                    });
                    res.send(result);
                });
            });
        });
    });
}

function findDescendants (req, res, next) {
    rolesModel.findOne({ lft: 1 }, function(err, root) {
        if (err) {
            return next(err);
        }
        rolesModel.rebuildTree(root, root.lft, function() {
            rolesModel.findOne({ _id: req.user.role._id }, function (err, role) {
                if (err) {
                    return next(err);
                }
                role.descendants(function (err, roles) {
                    var roleIds = [];
                    roles.forEach(function (role) {
                        roleIds.push(role._id);
                    });
                    rolesModel.find({ _id: { $in: roleIds } })
                    .populate('parentId')
                    .exec(function (err, roles) {
                        if (err) {
                            return next(err);
                        }
                        res.send(roles);
                    });
                });
            });
        });
    });
}1

function findSelfAndDecendants (req, res, next) {
    rolesModel.findOne({ lft: 1 }, function(err, root) {
        if (err) {
            return next(err);
        }
        rolesModel.rebuildTree(root, root.lft, function() {
            rolesModel.findOne({ _id: req.user.role._id }, function (err, role) {
                if (err) {
                    return next(err);
                }
                role.selfAndDescendants(function (err, roles) {
                    var roleIds = [];
                    roles.forEach(function (role) {
                        roleIds.push(role._id);
                    });
                    rolesModel.find({ _id: { $in: roleIds } })
                    .populate('parentId')
                    .exec(function (err, roles) {
                        if (err) {
                            return next(err);
                        }
                        res.send(roles);
                    });
                });
            });
        });
    });
}

module.exports = {
    findAll: findAll,
    findById: findById,
    add: add,
    update: update,
    delete: del,
    findDescendants: findDescendants,
    findSelfAndDecendants: findSelfAndDecendants
}


text:
using IdentityManager.Resources;
using System;
using System.Reflection;

namespace IdentityManager
{
    public class ExpressionPropertyMetadata<TContainer, TProperty> : ExecutablePropertyMetadata
    {
        Func<TContainer, TProperty> get;
        Func<TContainer, TProperty, IdentityManagerResult> set;
        public ExpressionPropertyMetadata(string type, Func<TContainer, TProperty> get, Func<TContainer, TProperty, IdentityManagerResult> set)
            : this(type, type, get, set)
        {
        }

        public ExpressionPropertyMetadata(
            string type,
            string name,
            Func<TContainer, TProperty> get,
            Func<TContainer, TProperty, IdentityManagerResult> set)
        {
            if (String.IsNullOrWhiteSpace(type)) throw new ArgumentNullException("type");
            if (String.IsNullOrWhiteSpace(name)) throw new ArgumentNullException("name");
            if (get == null) throw new ArgumentNullException("get");
            if (set == null) throw new ArgumentNullException("set");

            this.Type = type;
            this.Name = name;
            this.get = get;
            this.set = set;

            this.DataType = typeof(TProperty).GetPropertyDataType();
        }

        public override string Get(object instance)
        {
            if (instance == null) throw new ArgumentNullException("instance");

            if (this.DataType == PropertyDataType.Password) return null;

            var value = get((TContainer)instance);
            if (value != null)
            {
                return value.ToString();
            }

            return null;
        }

        public override IdentityManagerResult Set(object instance, string value)
        {
            if (instance == null) throw new ArgumentNullException("instance");

            if (String.IsNullOrWhiteSpace(value))
            {
                return set((TContainer)instance, default(TProperty));
            }
            else
            {
                var type = typeof(TProperty);
                type = Nullable.GetUnderlyingType(type) ?? type;
                TProperty convertedValue = default(TProperty);
                try
                {
                    convertedValue = (TProperty)Convert.ChangeType(value, type);
                }
                catch
                {
                    return new IdentityManagerResult(Messages.ConversionFailed);
                }
                return set((TContainer)instance, convertedValue);
            }
        }
    }
}


text:
package lesson.localization;

import java.io.*;
import java.util.Locale;
import java.util.Properties;

/**
 * Created by igor on 19.06.2015.
 */
public class LoadProperties {
    public static void main(String[] args) {

        Properties resources = new Properties();

        try (InputStream stream = new FileInputStream("src/lesson.localization/strings.properties")) {

            Reader reader = new InputStreamReader(stream,"UTF-8");
            resources.load(reader);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        Locale current = Locale.getDefault();
        System.out.println(current);
        System.out.println(resources.getProperty("hello"));

    }
}


text:
'use strict';

process.on('uncaughtException',function(e) {
    console.log("Caught unhandled exception: ");
    console.dir(e);
    if(e.stack) {
        console.log(" ---> : " + e.stack);
    }
});

// include the helpers and get a reference to it's exports variable
var StoreHelper = require('../../helpers/DbHelper').StoreHelper;

const USERID = '575756A6587S1';
const AREA = 'room';
const USERKEY = 'room:users:';
const SOCKETID = '58765857856ZZZ';

var def_timeout2 = 9000;
var def_timeout = 10000;

var repo = require('../../../app/cast_room/dao/RedisUserDao');
var userData = {
    id: USERID,
    area: AREA,
    socketid: SOCKETID,
    email: 'a@a.a',
    raiseHand: '0',
    applause: '0',
    age: 1
};
var CUser = require('../../../app/cast_room/models/OnlineUser');
var user = new CUser(userData, SOCKETID);
var expire = 10; //seconds

/**
* Testing Redis Repository Module
*/
describe("Server Redis Repository Testing", function() {
    var oConn = null;

    /**
    * Testing each function returns a promise
    */
    describe("included methods returns a promise", function() {

        it("returns a promise", function(done) {
            var oRepo = repo({client: {}});
            var promise = oRepo.setUser( user, expire );
            expect(promise.constructor.name).toBe("Promise");
            promise = null;
            done();
        });
    });

    /**
    * Testing setUser method
    */
    describe("setUser method testing", function() {
        var oTestContext = null,
            dateStart = new Date();

        /**
        * test setup
        */
        beforeEach(function (beforeDone) {
          oTestContext = {};
          var store = new StoreHelper();
          store.openFreshConnection(function (err, connection) {
            if(err){
                beforeDone();
            } else {
                oConn = connection;
                beforeDone();
            }
          });

          waitsFor(function () {
            return oConn;
          }, "establishing a connection to the database & flushing all.", def_timeout);
        });

        afterEach(function (afterDone) {
          waitsFor(function () {
            return true;
          }, "waiting for the assertions to be called.", def_timeout2);

          runs(function () {
            if (typeof oConn !== 'undefined' && oConn !== null) {
                oConn.quit();
                afterDone();
                return;
            } else {
                afterDone();
            }

          });
        });

        /**
        * Test valid user inserted
        */
        it("Test: creating a valid user", function (itDone) {
          runs(function () {
            //arrange
            oTestContext.assertions = assertions;
            //spyOn(oTestContext, "assertions").andCallThrough();
            var oRepo = repo({client: oConn});
            //act (oTestContext.assertions invoked as callback)
            oRepo.setUser(user, expire).done(
                // oRepo.setUser Success
                function success( ret ) {
                    oRepo.getConnectedUser( USERKEY + USERID ).done(
                        // oRepo.getConnectedUsers Success
                        function success( ret ) {
                            assertions(null, ret);
                            itDone();
                            return;
                        },
                        // oRepo.getConnectedUsers Fail
                        function failure( err ) {
                            assertions(err, null);
                            itDone();
                            return;
                        }
                    );
                },
                // oRepo.setUser Fail
                function failure( err ) {
                    assertions(err);
                    itDone();
                    return;
                }
            );

            //assert
            function assertions(err, ret) {
                /**
                * Test all user fields are persist with proper value
                */
                expect(err).toBeFalsy();
                if(err){
                    return;
                }

                var dateEnd = new Date();

                expect(ret).toBeTruthy();

                expect(ret.id).toBe(USERID);
                expect(ret.socketid).toBe(SOCKETID);
                expect(ret.email).toBe('a@a.a');
                expect(ret.raiseHand).toBe(false);
                expect(ret.applause).toBe(false);
                expect(ret.age).toBeGreaterThan(dateStart);
                expect(ret.age).toBeLessThan(dateEnd);

                /**
                * Test all user fields are persist
                */

            }
          });
        });

        /**
        * Test duplicate user inserted by id
        */

        /**
        * Test valid user inserted by email
        */

        /**
        * Test not valid user fails
        */

        /**
        * Test network fails
        */
    });
});
/*
describe("Test Database setup", function() {
    beforeEach(function() {
        this.dbSuccess = false;
        self = this;
        runs(function() {
            database.setup({setup:true}, function(err, db) {
                if (err) {
                    throw new Error(JSON.stringify(err));
                } else {
                    self.dbSuccess = true;
                }
                setFixtures(db);
            });
        });
        waitsFor(function() {
            return self.dbSuccess === true;
        }, def_timeout, "DB Setup");
    });

    afterEach(function() {
        db.destroy();
    });

    it('should increment a variable', function () {
        console.log('test');
        var foo = 0;            // set up the world
        foo++;                  // call your application code
        expect(foo).toEqual(1); // passes because foo == 1
    });
});
*/


text:
require_relative '../../spec_helper'

describe "Kernel#=~" do
  it "returns nil matching any object" do
    o = Object.new

    suppress_warning do
      (o =~ /Object/).should   be_nil
      (o =~ 'Object').should   be_nil
      (o =~ Object).should     be_nil
      (o =~ Object.new).should be_nil
      (o =~ nil).should        be_nil
      (o =~ true).should       be_nil
    end
  end

  ruby_version_is "2.6" do
    it "is deprecated" do
      -> do
        Object.new =~ /regexp/
      end.should complain(/deprecated Object#=~ is called on Object/, verbose: true)
    end
  end
end


text:
import { routerRedux } from 'dva/router'
import { parse } from 'qs'
import { query, logout } from '../services/app'
import { config } from '../utils'

const { prefix } = config

export default {
  namespace: 'app',
  state: {
    user: {},
    menuPopoverVisible: false,
    siderFold: localStorage.getItem(`${prefix}siderFold`) === 'true',
    darkTheme: localStorage.getItem(`${prefix}darkTheme`) === 'true',
    isNavbar: document.body.clientWidth < 769,
    navOpenKeys: JSON.parse(localStorage.getItem(`${prefix}navOpenKeys`)) || [],
  },
  subscriptions: {

    setup ({ dispatch }) {
      dispatch({ type: 'query' })
      let tid
      window.onresize = () => {
        clearTimeout(tid)
        tid = setTimeout(() => {
          dispatch({ type: 'changeNavbar' })
        }, 300)
      }
    },

  },
  effects: {

    *query ({
      payload,
    }, { call, put }) {
      const data = yield call(query, parse(payload))
      if (data.success && data.user) {
        yield put({
          type: 'querySuccess',
          payload: data.user,
        })
        if (location.pathname === '/login') {
          yield put(routerRedux.push('/dashboard'))
        }
      } else {
        if (config.openPages && config.openPages.indexOf(location.pathname) < 0) {
          let from = location.pathname
          window.location = `${location.origin}/login?from=${from}`
        }
      }
    },

    *logout ({
      payload,
    }, { call, put }) {
      const data = yield call(logout, parse(payload))
      if (data.success) {
        yield put({ type: 'query' })
      } else {
        throw (data)
      }
    },

    *changeNavbar ({
      payload,
    }, { put, select }) {
      const { app } = yield (select(_ => _))
      const isNavbar = document.body.clientWidth < 769
      if (isNavbar !== app.isNavbar) {
        yield put({ type: 'handleNavbar', payload: isNavbar })
      }
    },

  },
  reducers: {
    querySuccess (state, { payload: user }) {
      return {
        ...state,
        user,
      }
    },

    switchSider (state) {
      localStorage.setItem(`${prefix}siderFold`, !state.siderFold)
      return {
        ...state,
        siderFold: !state.siderFold,
      }
    },

    switchTheme (state) {
      localStorage.setItem(`${prefix}darkTheme`, !state.darkTheme)
      return {
        ...state,
        darkTheme: !state.darkTheme,
      }
    },

    switchMenuPopver (state) {
      return {
        ...state,
        menuPopoverVisible: !state.menuPopoverVisible,
      }
    },

    handleNavbar (state, { payload }) {
      return {
        ...state,
        isNavbar: payload,
      }
    },

    handleNavOpenKeys (state, { payload: navOpenKeys }) {
      return {
        ...state,
        ...navOpenKeys,
      }
    },
  },
}