text:
package org.wildfly.swarm.ejb.runtime;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jboss.as.controller.PathAddress;
import org.jboss.as.controller.PathElement;
import org.jboss.dmr.ModelNode;
import org.jboss.dmr.ValueExpression;
import org.wildfly.apigen.invocation.Marshaller;
import org.wildfly.swarm.config.ejb3.subsystem.cache.Cache;
import org.wildfly.swarm.config.ejb3.subsystem.service.Async;
import org.wildfly.swarm.config.ejb3.subsystem.service.TimerService;
import org.wildfly.swarm.config.ejb3.subsystem.service.fileDataStore.FileDataStore;
import org.wildfly.swarm.config.ejb3.subsystem.strictMaxBeanInstancePool.StrictMaxBeanInstancePool;
import org.wildfly.swarm.config.ejb3.subsystem.threadPool.ThreadPool;
import org.wildfly.swarm.container.runtime.AbstractServerConfiguration;
import org.wildfly.swarm.ejb.EJBFraction;

import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.ADD;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.EXTENSION;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;

/**
 * @author Ken Finnigan
 */
public class EJBConfiguration extends AbstractServerConfiguration<EJBFraction> {

    private PathAddress address = PathAddress.pathAddress(PathElement.pathElement(SUBSYSTEM, "ejb3"));

    public EJBConfiguration() {
        super(EJBFraction.class);
    }

    @Override
    public EJBFraction defaultFraction() {

        Map threadPoolSettings = new HashMap<>();
        threadPoolSettings.put("time", "100");
        threadPoolSettings.put("unit", "MILLISECONDS");

        EJBFraction fraction = new EJBFraction();
        fraction.defaultStatefulBeanAccessTimeout(5000L)
                .defaultSingletonBeanAccessTimeout(5000L)
                .defaultSfsbCache("simple")
                .defaultSecurityDomain("other")
                .defaultMissingMethodPermissionsDenyAccess(true)
                .logSystemExceptions(true)
                .defaultResourceAdapterName(
                        new ValueExpression("${ejb.resource-adapter-name:activemq-ra.rar}").resolveString())
                .strictMaxBeanInstancePool(new StrictMaxBeanInstancePool("slsb-strict-max-pool")
                        .maxPoolSize(20)
                        .timeout(5L)
                        .timeoutUnit("MINUTES"))
                .strictMaxBeanInstancePool(new StrictMaxBeanInstancePool("mdb-strict-max-pool")
                        .maxPoolSize(20)
                        .timeout(5L)
                        .timeoutUnit("MINUTES"))
                .cache(new Cache("simple"))
                .async(new Async().threadPoolName("default"))
                        .timerService(new TimerService()
                        .threadPoolName("default")
                        .defaultDataStore("default-file-store")
                        .fileDataStore(new FileDataStore("default-file-store")
                                .path("timer-service-data")
                                .relativeTo("jboss.server.data.dir")))
                        .threadPool(new ThreadPool("default")
                                .maxThreads(10)
                                .keepaliveTime(threadPoolSettings));

        return fraction;
    }

    @Override
    public List<ModelNode> getList(EJBFraction fraction) {
        List<ModelNode> list = new ArrayList<>();

        ModelNode node = new ModelNode();
        node.get(OP_ADDR).set(EXTENSION, "org.jboss.as.ejb3");
        node.get(OP).set(ADD);
        list.add(node);

        try {
            list.addAll(Marshaller.marshal(fraction));
        } catch (Exception e) {
            System.err.println("Cannot configure EJB subsystem. " + e);
        }
        return list;
    }
}


text:
//
//  UIImage+ABFramework.m
//  ABFramework
//
//  Created by Alexander Blunck on 10/23/12.
//  Copyright (c) 2012 Ablfx. All rights reserved.
//

#import "UIImage+ABFramework.h"

//@import Accelerate;
#import <Accelerate/Accelerate.h>
#import <float.h>

@implementation UIImage (ABFramework)

#pragma mark - Save / Load / Delete
-(void) saveImage:(NSString*)imageName
{
    //Convert image into .png format
    NSData *imageData = UIImageJPEGRepresentation(self, 1.0f);
    //Create instance of NSFileManager
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //Create an array and store result of our search for the documents directory in it
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    //Create NSString object, that holds our exact path to the documents directory
    NSString *documentsDirectory = [paths safeObjectAtIndex:0];
    //Add our image to the path
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", imageName]];
    //Finally save the path (image)
    [fileManager createFileAtPath:fullPath contents:imageData attributes:nil];
}

+(void) removeImage:(NSString*)fileName
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths safeObjectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]];
    [fileManager removeItemAtPath: fullPath error:NULL];
}

+(UIImage*) loadImage:(NSString*)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths safeObjectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", fileName]];
    return [UIImage imageWithContentsOfFile:fullPath];
}

#pragma mark - Resize
-(UIImage*) resizedImageWithMaxSize:(CGSize)maxSize
{
    return [self resizedImageWithMaxSize:maxSize compression:1.0f];
}

-(UIImage*) resizedImageWithMaxSize:(CGSize)maxSize compression:(CGFloat)compression
{
    float actualHeight = self.size.height;
    float actualWidth = self.size.width;
    float imgRatio = actualWidth/actualHeight;
    float maxRatio = maxSize.width/maxSize.height;

    if(imgRatio!=maxRatio){
        if(imgRatio < maxRatio){
            imgRatio = maxSize.height / actualHeight;
            actualWidth = imgRatio * actualWidth;
            actualHeight = maxSize.height;
        }
        else{
            imgRatio = maxSize.width / actualWidth;
            actualHeight = imgRatio * actualHeight;
            actualWidth = maxSize.width;
        }
    }
    CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
    UIGraphicsBeginImageContext(rect.size);
    [self drawInRect:rect];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    if (compression > 1.0f)
    {
        compression = 1.0f;
    }

    return [UIImage imageWithData:UIImageJPEGRepresentation(img, compression)];
}

#pragma mark - Info
+(CGSize) sizeForImageName:(NSString*)imageName
{
    UIImage *image = [UIImage imageNamed:imageName];
    CGSize size = image.size;
    image = nil;
    return size;
}

#pragma mark - Blur

-(UIImage*) applyBlurWithRadius:(CGFloat)blurRadius
                      tintColor:(UIColor*)tintColor
          saturationDeltaFactor:(CGFloat)saturationDeltaFactor
                      maskImage:(UIImage*)maskImage
{
    // Check pre-conditions.
    if (self.size.width < 1 || self.size.height < 1) {
        NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
        return nil;
    }
    if (!self.CGImage) {
        NSLog (@"*** error: image must be backed by a CGImage: %@", self);
        return nil;
    }
    if (maskImage && !maskImage.CGImage) {
        NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
        return nil;
    }

    CGRect imageRect = { CGPointZero, self.size };
    UIImage *effectImage = self;

    BOOL hasBlur = blurRadius > __FLT_EPSILON__;
    BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
    if (hasBlur || hasSaturationChange) {
        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectInContext = UIGraphicsGetCurrentContext();
        CGContextScaleCTM(effectInContext, 1.0, -1.0);
        CGContextTranslateCTM(effectInContext, 0, -self.size.height);
        CGContextDrawImage(effectInContext, imageRect, self.CGImage);

        vImage_Buffer effectInBuffer;
        effectInBuffer.data     = CGBitmapContextGetData(effectInContext);
        effectInBuffer.width    = CGBitmapContextGetWidth(effectInContext);
        effectInBuffer.height   = CGBitmapContextGetHeight(effectInContext);
        effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);

        UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
        CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
        vImage_Buffer effectOutBuffer;
        effectOutBuffer.data     = CGBitmapContextGetData(effectOutContext);
        effectOutBuffer.width    = CGBitmapContextGetWidth(effectOutContext);
        effectOutBuffer.height   = CGBitmapContextGetHeight(effectOutContext);
        effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);

        if (hasBlur) {
            // A description of how to compute the box kernel width from the Gaussian
            // radius (aka standard deviation) appears in the SVG spec:
            // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
            //
            // For larger values of 's' (s >= 2.0), an approximation can be used: Three
            // successive box-blurs build a piece-wise quadratic convolution kernel, which
            // approximates the Gaussian kernel to within roughly 3%.
            //
            // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
            //
            // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
            //
            CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
            NSUInteger radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
            if (radius % 2 != 1) {
                radius += 1; // force radius to be odd so that the three box-blur methodology works.
            }
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, (int)radius, (int)radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, (int)radius, (int)radius, 0, kvImageEdgeExtend);
            vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, (int)radius, (int)radius, 0, kvImageEdgeExtend);
        }
        BOOL effectImageBuffersAreSwapped = NO;
        if (hasSaturationChange) {
            CGFloat s = saturationDeltaFactor;
            CGFloat floatingPointSaturationMatrix[] = {
                0.0722 + 0.9278 * s,  0.0722 - 0.0722 * s,  0.0722 - 0.0722 * s,  0,
                0.7152 - 0.7152 * s,  0.7152 + 0.2848 * s,  0.7152 - 0.7152 * s,  0,
                0.2126 - 0.2126 * s,  0.2126 - 0.2126 * s,  0.2126 + 0.7873 * s,  0,
                0,                    0,                    0,  1,
            };
            const int32_t divisor = 256;
            NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
            int16_t saturationMatrix[matrixSize];
            for (NSUInteger i = 0; i < matrixSize; ++i) {
                saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
            }
            if (hasBlur) {
                vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
                effectImageBuffersAreSwapped = YES;
            }
            else {
                vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
            }
        }
        if (!effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();

        if (effectImageBuffersAreSwapped)
            effectImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }

    // Set up output context.
    UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
    CGContextRef outputContext = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(outputContext, 1.0, -1.0);
    CGContextTranslateCTM(outputContext, 0, -self.size.height);

    // Draw base image.
    CGContextDrawImage(outputContext, imageRect, self.CGImage);

    // Draw effect image.
    if (hasBlur) {
        CGContextSaveGState(outputContext);
        if (maskImage) {
            CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
        }
        CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
        CGContextRestoreGState(outputContext);
    }

    // Add in color tint.
    if (tintColor) {
        CGContextSaveGState(outputContext);
        CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
        CGContextFillRect(outputContext, imageRect);
        CGContextRestoreGState(outputContext);
    }

    // Output image is ready.
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return outputImage;
}

#pragma mark - Color
+(instancetype) imageWithColor:(UIColor*)color size:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    UIBezierPath* rPath = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, size.width, size.height)];
    [color setFill];
    [rPath fill];
    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Stat\EnseignantBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * MdlFeedback
 *
 * @ORM\Table(name="mdl_feedback", indexes={@ORM\Index(name="mdl_feed_cou_ix", columns={"course"})})
 * @ORM\Entity
 */
class MdlFeedback
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="course", type="bigint", nullable=false)
     */
    private $course = '0';

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, nullable=false)
     */
    private $name = '';

    /**
     * @var string
     *
     * @ORM\Column(name="intro", type="text", nullable=false)
     */
    private $intro;

    /**
     * @var integer
     *
     * @ORM\Column(name="introformat", type="smallint", nullable=false)
     */
    private $introformat = '0';

    /**
     * @var boolean
     *
     * @ORM\Column(name="anonymous", type="boolean", nullable=false)
     */
    private $anonymous = '1';

    /**
     * @var boolean
     *
     * @ORM\Column(name="email_notification", type="boolean", nullable=false)
     */
    private $emailNotification = '1';

    /**
     * @var boolean
     *
     * @ORM\Column(name="multiple_submit", type="boolean", nullable=false)
     */
    private $multipleSubmit = '1';

    /**
     * @var boolean
     *
     * @ORM\Column(name="autonumbering", type="boolean", nullable=false)
     */
    private $autonumbering = '1';

    /**
     * @var string
     *
     * @ORM\Column(name="site_after_submit", type="string", length=255, nullable=false)
     */
    private $siteAfterSubmit = '';

    /**
     * @var string
     *
     * @ORM\Column(name="page_after_submit", type="text", nullable=false)
     */
    private $pageAfterSubmit;

    /**
     * @var boolean
     *
     * @ORM\Column(name="page_after_submitformat", type="boolean", nullable=false)
     */
    private $pageAfterSubmitformat = '0';

    /**
     * @var boolean
     *
     * @ORM\Column(name="publish_stats", type="boolean", nullable=false)
     */
    private $publishStats = '0';

    /**
     * @var integer
     *
     * @ORM\Column(name="timeopen", type="bigint", nullable=false)
     */
    private $timeopen = '0';

    /**
     * @var integer
     *
     * @ORM\Column(name="timeclose", type="bigint", nullable=false)
     */
    private $timeclose = '0';

    /**
     * @var integer
     *
     * @ORM\Column(name="timemodified", type="bigint", nullable=false)
     */
    private $timemodified = '0';

    /**
     * @var boolean
     *
     * @ORM\Column(name="completionsubmit", type="boolean", nullable=false)
     */
    private $completionsubmit = '0';

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

    /**
     * Set course
     *
     * @param integer $course
     * @return MdlFeedback
     */
    public function setCourse($course)
    {
        $this->course = $course;

        return $this;
    }

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

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

        return $this;
    }

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

    /**
     * Set intro
     *
     * @param string $intro
     * @return MdlFeedback
     */
    public function setIntro($intro)
    {
        $this->intro = $intro;

        return $this;
    }

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

    /**
     * Set introformat
     *
     * @param integer $introformat
     * @return MdlFeedback
     */
    public function setIntroformat($introformat)
    {
        $this->introformat = $introformat;

        return $this;
    }

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

    /**
     * Set anonymous
     *
     * @param boolean $anonymous
     * @return MdlFeedback
     */
    public function setAnonymous($anonymous)
    {
        $this->anonymous = $anonymous;

        return $this;
    }

    /**
     * Get anonymous
     *
     * @return boolean
     */
    public function getAnonymous()
    {
        return $this->anonymous;
    }

    /**
     * Set emailNotification
     *
     * @param boolean $emailNotification
     * @return MdlFeedback
     */
    public function setEmailNotification($emailNotification)
    {
        $this->emailNotification = $emailNotification;

        return $this;
    }

    /**
     * Get emailNotification
     *
     * @return boolean
     */
    public function getEmailNotification()
    {
        return $this->emailNotification;
    }

    /**
     * Set multipleSubmit
     *
     * @param boolean $multipleSubmit
     * @return MdlFeedback
     */
    public function setMultipleSubmit($multipleSubmit)
    {
        $this->multipleSubmit = $multipleSubmit;

        return $this;
    }

    /**
     * Get multipleSubmit
     *
     * @return boolean
     */
    public function getMultipleSubmit()
    {
        return $this->multipleSubmit;
    }

    /**
     * Set autonumbering
     *
     * @param boolean $autonumbering
     * @return MdlFeedback
     */
    public function setAutonumbering($autonumbering)
    {
        $this->autonumbering = $autonumbering;

        return $this;
    }

    /**
     * Get autonumbering
     *
     * @return boolean
     */
    public function getAutonumbering()
    {
        return $this->autonumbering;
    }

    /**
     * Set siteAfterSubmit
     *
     * @param string $siteAfterSubmit
     * @return MdlFeedback
     */
    public function setSiteAfterSubmit($siteAfterSubmit)
    {
        $this->siteAfterSubmit = $siteAfterSubmit;

        return $this;
    }

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

    /**
     * Set pageAfterSubmit
     *
     * @param string $pageAfterSubmit
     * @return MdlFeedback
     */
    public function setPageAfterSubmit($pageAfterSubmit)
    {
        $this->pageAfterSubmit = $pageAfterSubmit;

        return $this;
    }

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

    /**
     * Set pageAfterSubmitformat
     *
     * @param boolean $pageAfterSubmitformat
     * @return MdlFeedback
     */
    public function setPageAfterSubmitformat($pageAfterSubmitformat)
    {
        $this->pageAfterSubmitformat = $pageAfterSubmitformat;

        return $this;
    }

    /**
     * Get pageAfterSubmitformat
     *
     * @return boolean
     */
    public function getPageAfterSubmitformat()
    {
        return $this->pageAfterSubmitformat;
    }

    /**
     * Set publishStats
     *
     * @param boolean $publishStats
     * @return MdlFeedback
     */
    public function setPublishStats($publishStats)
    {
        $this->publishStats = $publishStats;

        return $this;
    }

    /**
     * Get publishStats
     *
     * @return boolean
     */
    public function getPublishStats()
    {
        return $this->publishStats;
    }

    /**
     * Set timeopen
     *
     * @param integer $timeopen
     * @return MdlFeedback
     */
    public function setTimeopen($timeopen)
    {
        $this->timeopen = $timeopen;

        return $this;
    }

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

    /**
     * Set timeclose
     *
     * @param integer $timeclose
     * @return MdlFeedback
     */
    public function setTimeclose($timeclose)
    {
        $this->timeclose = $timeclose;

        return $this;
    }

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

    /**
     * Set timemodified
     *
     * @param integer $timemodified
     * @return MdlFeedback
     */
    public function setTimemodified($timemodified)
    {
        $this->timemodified = $timemodified;

        return $this;
    }

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

    /**
     * Set completionsubmit
     *
     * @param boolean $completionsubmit
     * @return MdlFeedback
     */
    public function setCompletionsubmit($completionsubmit)
    {
        $this->completionsubmit = $completionsubmit;

        return $this;
    }

    /**
     * Get completionsubmit
     *
     * @return boolean
     */
    public function getCompletionsubmit()
    {
        return $this->completionsubmit;
    }
}


text:
package edu.cmu.sv.trailscribe.utils;

import java.io.File;
import java.util.ArrayList;

import edu.cmu.sv.trailscribe.model.AsyncTaskCompleteListener;
import edu.cmu.sv.trailscribe.model.data.Kml;
import edu.cmu.sv.trailscribe.model.data.Map;
import edu.cmu.sv.trailscribe.model.data.SyncItem;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;

public class Downloader extends AsyncTask<Void, Integer, Void> {
	private ArrayList<SyncItem> mSyncItems;
	private Context mContext;
	private ProgressDialog mDownloadProgressDialog;
	private DownloadReceiver mDownloadReceiver;
	private NetworkMonitor mNetworkReceiver;
	private AsyncTaskCompleteListener<Boolean> mTaskCompletedCallback;
	private ArrayList<Long> mPendingDownloads = new ArrayList<Long>();
	private String mDownloadDirectory;
	private SyncItem mCurrentDownload = null;
	private int mAmountOfDownloads = 0;
	final DownloadManager mDownloadManager;

	public Downloader (ArrayList<SyncItem> mSyncItems, Context context, String downloadDirectory, ProgressDialog downloadProgressDialog, AsyncTaskCompleteListener<Boolean> callback){
		this.mSyncItems	 = mSyncItems;
		this.mContext = context;
		this.mTaskCompletedCallback = callback;
		this.mDownloadReceiver = new DownloadReceiver();
		this.mNetworkReceiver = new NetworkMonitor();
		this.mDownloadProgressDialog = downloadProgressDialog;
		this.mDownloadDirectory = downloadDirectory;
		this.mContext.registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		this.mContext.registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
		mDownloadManager = (DownloadManager)
					mContext.getSystemService(Context.DOWNLOAD_SERVICE);
	}

	@Override
	protected void onPreExecute()
	{
		//Set the progress dialog to display a horizontal progress bar
		mDownloadProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		//Set the dialog title to 'Loading...'
		mDownloadProgressDialog.setTitle("Synchronizing...");
		//Set the dialog message to 'Loading application View, please wait...'
		mDownloadProgressDialog.setMessage("Synchronizing items, please wait...");
		//This dialog can't be canceled by pressing the back key
		mDownloadProgressDialog.setCancelable(false);
		//This dialog isn't indeterminate
		mDownloadProgressDialog.setIndeterminate(false);
		//The maximum number of items is 100
		mDownloadProgressDialog.setMax(100);
		//Set the current progress to zero
		mDownloadProgressDialog.setProgress(0);
		//Display the progress dialog
		mDownloadProgressDialog.show();
		//Register callback for connection events
		mNetworkReceiver.setCallback(new Runnable() {
            @Override
            public void run() {
            	cancelPendingDownloads();
            	mTaskCompletedCallback.onTaskCompleted(false);
            }
        });

	}

	@Override
	protected void onPostExecute(Void result)
	{
		this.mContext.unregisterReceiver(mDownloadReceiver);
		this.mContext.unregisterReceiver(mNetworkReceiver);
		if(mDownloadProgressDialog!= null){
			mDownloadProgressDialog.dismiss();
		}
		boolean success = true;
		if(this.mPendingDownloads.size() != 0){
			success = false;
		}
		this.mTaskCompletedCallback.onTaskCompleted(success);
	}

	@Override
	protected Void doInBackground(Void... params) {
		for (SyncItem item: mSyncItems){
			int subStringIndex = item.getFilename().lastIndexOf("/") +1;
			String mapFileName = item.getFilename().substring(subStringIndex);

			//Using Android DownloadManager to handle downloads
			boolean isDownloading = false;

			DownloadManager.Query query = new DownloadManager.Query();
			query.setFilterByStatus(
					DownloadManager.STATUS_PAUSED|
					DownloadManager.STATUS_PENDING|
					DownloadManager.STATUS_RUNNING|
					DownloadManager.STATUS_SUCCESSFUL|
					DownloadManager.STATUS_FAILED);

			Cursor cursor = mDownloadManager.query(query);
			int pathNameColumn = cursor.getColumnIndex(
					DownloadManager.COLUMN_LOCAL_FILENAME);
			for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
				isDownloading = isDownloading || (mapFileName == cursor.getString(pathNameColumn));
			}
			cursor.close();

			// Download the file if it is not already downloaded
			if (!isDownloading) {
				// Check for connectivity
				if (isInternetConnectionAvailable() == true){
					startDownload(item, mapFileName, mDownloadManager);
				}
				else {
					if(mDownloadProgressDialog!= null){
						mDownloadProgressDialog.dismiss();
					}
					cancelPendingDownloads();
					this.mTaskCompletedCallback.onTaskCompleted(false);
				}
			}
		}
		return null;
	}

	private boolean isInternetConnectionAvailable() {
		ConnectivityManager cm =
				(ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);

		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
		return (activeNetwork != null &&
				activeNetwork.isConnectedOrConnecting());
	}

	private void verifyDirectory(String directory) {
		if (!StorageSystemHelper.verifyDirectory(directory)){
			StorageSystemHelper.createFolder(directory);
		}
		else{
			StorageSystemHelper.removeDirectoryContent(directory);
		}
	}

	private void startDownload(SyncItem item, String mapFileName,
			final DownloadManager downloadManager) {
		Uri source = Uri.parse(item.getFilename());
		String folderName = getFolderNameBaseOnItemType(item);
		String directory = this.mDownloadDirectory + folderName + "/"+ item.getName()+ "/";

		//Verify the directory prior to download. Clear its content if it is already there
		verifyDirectory(directory);

		Uri destination = Uri.fromFile(new File(directory + mapFileName));
		DownloadManager.Request request =
				new DownloadManager.Request(source);
		request.setTitle(item.getName());
		request.setDestinationUri(destination);
		request.setNotificationVisibility(DownloadManager
				.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
		request.allowScanningByMediaScanner();
		final long id = downloadManager.enqueue(request);

		// Keeping the pending downloads in a list. The list is being cleared as soon as downloads finish successfully
		mPendingDownloads.add(id);
		// This counter helps in displaying the progress bar
		mAmountOfDownloads ++;
		// The current item helps in displaying the name in the progress bar
		mCurrentDownload = item;

		boolean downloading = true;
		while (downloading) {
			downloading = writeFile(downloadManager, id, downloading);
		}
	}

	private String getFolderNameBaseOnItemType(SyncItem item) {
		String folderName = null;
		if(item instanceof Map){
			folderName = "maps";
		}
		else if(item instanceof Kml){
			folderName = "kmls";
		}
		return folderName;
	}

	private boolean writeFile(final DownloadManager downloadManager,
			final long id, boolean downloading) {
		DownloadManager.Query q = new DownloadManager.Query();
		q.setFilterById(id);

		Cursor cursor = downloadManager.query(q);
		cursor.moveToFirst();
		int bytes_downloaded = cursor.getInt(cursor
				.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
		int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

		if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
			downloading = false;
		}

		final int dl_progress = (int) ((double)bytes_downloaded / (double)bytes_total * 100f);

		// Publishing download progress
		((Activity)mContext).runOnUiThread(new Runnable() {
			@Override
			public void run() {
				publishProgress((int) dl_progress);
			}
		});
		cursor.close();
		return downloading;
	}

	protected void onProgressUpdate(Integer... progress) {
		mDownloadProgressDialog.setProgress(progress[0]);
		if(mPendingDownloads != null) {
			mDownloadProgressDialog.setMessage("Synchronizing " + this.mCurrentDownload.getName() + ". Item "+ mAmountOfDownloads + "/" + this.mSyncItems.size());
		}

	}

	// This receiver is being invoked when the download is complete
	class DownloadReceiver extends BroadcastReceiver{
		@Override
		public void onReceive(Context context, Intent intent) {
			long receivedID = intent.getLongExtra(
					DownloadManager.EXTRA_DOWNLOAD_ID, -1L);
			DownloadManager mgr = (DownloadManager)
					context.getSystemService(Context.DOWNLOAD_SERVICE);

			DownloadManager.Query query = new DownloadManager.Query();
			query.setFilterById(receivedID);
			Cursor cursor = mgr.query(query);
			int status = cursor.getColumnIndex(
					DownloadManager.COLUMN_STATUS);
			if(cursor.moveToFirst()) {
				if(cursor.getInt(status) == DownloadManager.STATUS_SUCCESSFUL){
					mPendingDownloads.remove(receivedID);
				}
			}
			cursor.close();
		}
	}

	private void cancelPendingDownloads(){
		for(Long downloadId: mPendingDownloads){
			mDownloadManager.remove(downloadId);
		}
	}
}


text:
function __processArg(obj, key) {
    var arg = null;
    if (obj) {
        arg = obj[key] || null;
        delete obj[key];
    }
    return arg;
}

function Controller() {
    function doLeftClick() {
        alert("Left button clicked");
    }
    function doRightClick() {
        alert("Right button clicked");
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "index";
    this.args = arguments[0] || {};
    if (arguments[0]) {
        {
            __processArg(arguments[0], "__parentSymbol");
        }
        {
            __processArg(arguments[0], "$model");
        }
        {
            __processArg(arguments[0], "__itemTemplate");
        }
    }
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.__alloyId0 = Ti.UI.createWindow({
        title: "Proxy Shorthands",
        id: "__alloyId0"
    });
    $.__views.__alloyId2 = Ti.UI.createButton({
        title: "Left",
        id: "__alloyId2"
    });
    doLeftClick ? $.__views.__alloyId2.addEventListener("click", doLeftClick) : __defers["$.__views.__alloyId2!click!doLeftClick"] = true;
    $.__views.__alloyId0.leftNavButton = $.__views.__alloyId2;
    $.__views.__alloyId3 = Ti.UI.createButton({
        title: "Right",
        id: "__alloyId3"
    });
    $.__views.__alloyId0.rightNavButton = $.__views.__alloyId3;
    doRightClick ? $.__views.__alloyId3.addEventListener("click", doRightClick) : __defers["$.__views.__alloyId3!click!doRightClick"] = true;
    $.__views.index = Ti.UI.iOS.createNavigationWindow({
        backgroundColor: "#fff",
        fullscreen: false,
        exitOnClose: true,
        window: $.__views.__alloyId0,
        id: "index"
    });
    $.__views.index && $.addTopLevelView($.__views.index);
    exports.destroy = function() {};
    _.extend($, $.__views);
    $.index.open();
    __defers["$.__views.__alloyId2!click!doLeftClick"] && $.__views.__alloyId2.addEventListener("click", doLeftClick);
    __defers["$.__views.__alloyId3!click!doRightClick"] && $.__views.__alloyId3.addEventListener("click", doRightClick);
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
package net.fortuna.ical4j.vcard.property;

import net.fortuna.ical4j.model.Date;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Encodable;
import net.fortuna.ical4j.util.Strings;
import net.fortuna.ical4j.validate.ValidationException;
import net.fortuna.ical4j.vcard.Group;
import net.fortuna.ical4j.vcard.Parameter;
import net.fortuna.ical4j.vcard.Property;
import net.fortuna.ical4j.vcard.PropertyFactory;
import net.fortuna.ical4j.vcard.parameter.Value;

import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.List;

import static net.fortuna.ical4j.util.Strings.unescape;

/**
 * ANNIVERSARY property.
 *
 * $Id$ Created on 23/08/2008
 * @author Ben
 */
public final class Anniversary extends Property implements Encodable {

    private static final long serialVersionUID = 4298026868242865633L;

    public static final PropertyFactory<Anniversary> FACTORY = new Factory();

    private Date date;

    private String text;

    /**
     * @param date date of birth
     */
    public Anniversary(final Date date) {
        super(Id.ANNIVERSARY);
        this.date = date;
    }

    /**
     * @param text non-structured date of birth
     */
    public Anniversary(final String text) {
        super(Id.ANNIVERSARY);
        this.text = text;
        getParameters().add(Value.TEXT);
    }

    /**
     * Factory constructor.
     * @param params property parameters
     * @param value string representation of a property value
     * @throws ParseException if the property value is an invalid date
     */
    public Anniversary(final List<Parameter> params, final String value) throws ParseException {
        super(Id.ANNIVERSARY, params);
        if (Value.TEXT.equals(getParameter(Parameter.Id.VALUE))) {
            this.text = value;
        }
        else {

            // try default patterns first, then fall back on vCard-specific patterns
            try {
                this.date = new Date(value);
            }
            catch (ParseException e) {
                try {
                    this.date = new DateTime(value);
                }
                catch (ParseException e2) {
                    try {
                        this.date = new Date(value, "yyyy'-'MM'-'dd");
                    }
                    catch (ParseException e3) {
                        this.date = new DateTime(value, "yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'", true);
                    }
                }
            }
        }
    }

    /**
     * @return the date
     */
    public Date getDate() {
        return date;
    }

    /**
     * @return the text
     */
    public String getText() {
        return text;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getValue() {
        if (Value.TEXT.equals(getParameter(Parameter.Id.VALUE))) {
            return text;
        }
        return Strings.valueOf(date);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void validate() throws ValidationException {
        // ; Only value parameter allowed
        assertOneOrLess(Parameter.Id.VALUE);

        if (getParameters().size() > 1) {
            throw new ValidationException("Illegal parameter count");
        }

        for (Parameter param : getParameters()) {
            if (!Value.TEXT.equals(param)) {
                throw new ValidationException("Illegal parameter ["
                        + param.getId() + "]");
            }
        }
    }

    private static class Factory implements PropertyFactory<Anniversary> {

        /**
         * {@inheritDoc}
         */
	public Anniversary createProperty(final List<Parameter> params, final String value) throws ParseException {
            return new Anniversary(params, unescape(value));
        }

        /**
         * {@inheritDoc}
         */
	public Anniversary createProperty(final Group group, final List<Parameter> params, final String value)
                throws URISyntaxException, ParseException {
            // TODO Auto-generated method stub
            return null;
        }
    }
}


text:
'use strict';

require('mocha');
var assert = require('assert');
var lazyCache = require('../');

describe('lazy-cache', function() {
  afterEach(function() {
    delete require.cache[require.resolve('../index.js')];
    process.env.UNLAZY = false;
    lazyCache = require('../');
  });

  it('should return a function that lazyily requires a module', function() {
    var lazy = lazyCache(require);
    var yellow = lazy('ansi-yellow');
    assert.deepEqual(typeof yellow, 'function');
    assert.deepEqual(typeof yellow(), 'function');
  });

  it('should not invoke require until the module is used', function() {
    var calls = {};
    var lazy = lazyCache(function(name) {
      calls[name] = (calls[name] || 0) + 1;
      return require(name);
    });

    assert.deepEqual(calls, {});

    var yellow = lazy('ansi-yellow');

    if (process.env.TRAVIS) {
      assert.deepEqual(calls, {'ansi-yellow': 1});
    } else {
      assert.deepEqual(calls, {});
    }

    yellow('one');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    yellow('two');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    yellow('three');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    yellow('four');
    assert.deepEqual(calls, {'ansi-yellow': 1});
  });

  it('should add a property to the lazy function with the camelcased name', function() {
    var lazy = lazyCache(require);
    lazy('ansi-yellow');
    assert.deepEqual(typeof lazy.ansiYellow, 'function');
  });

  it('should only require a dependency once', function() {
    var calls = {};
    var lazy = lazyCache(function(name) {
      calls[name] = (calls[name] || 0) + 1;
      return require(name);
    });

    assert.deepEqual(calls, {});
    lazy('ansi-yellow');
    if (process.env.TRAVIS) {
      assert.deepEqual(calls, {'ansi-yellow': 1});
    } else {
      assert.deepEqual(calls, {});
    }

    lazy.ansiYellow('one');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.ansiYellow('two');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.ansiYellow('three');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.ansiYellow('four');
    assert.deepEqual(calls, {'ansi-yellow': 1});
  });

  it('should allow loading a dependency immediately with `process.env.UNLAZY` setting', function() {
    process.env.UNLAZY = true;
    var calls = {};
    var lazy = lazyCache(function(name) {
      calls[name] = (calls[name] || 0) + 1;
      return require(name);
    });

    assert.deepEqual(calls, {});

    lazy('ansi-yellow');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.ansiYellow('one');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.ansiYellow('two');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.ansiYellow('three');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.ansiYellow('four');
    assert.deepEqual(calls, {'ansi-yellow': 1});
  });

  it('should support an alias as the second argument:', function() {
    var calls = {};
    var lazy = lazyCache(function(name) {
      calls[name] = (calls[name] || 0) + 1;
      return require(name);
    });

    assert.deepEqual(calls, {});
    lazy('ansi-yellow', 'yellow');
    if (process.env.TRAVIS) {
      assert.deepEqual(calls, {'ansi-yellow': 1});
    } else {
      assert.deepEqual(calls, {});
    }

    lazy.yellow('one');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.yellow('two');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.yellow('three');
    assert.deepEqual(calls, {'ansi-yellow': 1});
    lazy.yellow('four');
    assert.deepEqual(calls, {'ansi-yellow': 1});
  });

  it('should support dot-notation in aliases', function() {
    var lazy = lazyCache(require);
    lazy('ansi-cyan', 'color.cyan');
    lazy('ansi-yellow', 'color.yellow');
    lazy('ansi-magenta', 'color.magenta');

    assert.deepEqual(typeof lazy.color, 'object');
    assert.deepEqual(typeof lazy.color.cyan, 'function');
    assert.deepEqual(typeof lazy.color.yellow, 'function');
    assert.deepEqual(typeof lazy.color.magenta, 'function');
  });

  it('should not use dot-notation in non-aliases', function() {
    var lazy = lazyCache(require);
    lazy('object.omit');
    lazy('object.pick');
    assert.deepEqual(typeof lazy.objectOmit, 'function');
    assert.deepEqual(typeof lazy.objectPick, 'function');
  });

  it('should load local files', function() {
    var lazy = lazyCache(require);
    lazy('./fixtures/utils');
    assert.deepEqual(typeof lazy.fixturesUtils, 'function');
    assert.deepEqual(typeof lazy.fixturesUtils.ansiYellow, 'function');
  });

  it('should load local files with an alias', function() {
    var lazy = lazyCache(require);
    lazy('./fixtures/utils', 'utils');
    assert.deepEqual(typeof lazy.utils, 'function');
    assert.deepEqual(typeof lazy.utils.ansiYellow, 'function');
  });

  it('should support dot-notation when `process.env.UNLAZY` is used', function() {
    process.env.UNLAZY = true;

    var calls = {};
    var lazy = lazyCache(function(name) {
      calls[name] = (calls[name] || 0) + 1;
      return require(name);
    });

    assert.deepEqual(calls, {});

    lazy('ansi-cyan', 'color.cyan');
    lazy('ansi-yellow', 'color.yellow');
    lazy('ansi-magenta', 'color.magenta');

    assert.deepEqual(calls, {
      'ansi-cyan': 1,
      'ansi-yellow': 1,
      'ansi-magenta': 1
    });
    lazy.color.cyan('one');
    lazy.color.yellow('one');
    lazy.color.magenta('one');
    assert.deepEqual(calls, {
      'ansi-cyan': 1,
      'ansi-yellow': 1,
      'ansi-magenta': 1
    });
    lazy.color.cyan('two');
    lazy.color.yellow('two');
    lazy.color.magenta('two');
    assert.deepEqual(calls, {
      'ansi-cyan': 1,
      'ansi-yellow': 1,
      'ansi-magenta': 1
    });
    lazy.color.cyan('three');
    lazy.color.yellow('three');
    lazy.color.magenta('three');
    assert.deepEqual(calls, {
      'ansi-cyan': 1,
      'ansi-yellow': 1,
      'ansi-magenta': 1
    });
    lazy.color.cyan('four');
    lazy.color.yellow('four');
    lazy.color.magenta('four');
    assert.deepEqual(calls, {
      'ansi-cyan': 1,
      'ansi-yellow': 1,
      'ansi-magenta': 1
    });

    assert.deepEqual(typeof lazy.color, 'object');
    assert.deepEqual(typeof lazy.color.cyan, 'function');
    assert.deepEqual(typeof lazy.color.yellow, 'function');
    assert.deepEqual(typeof lazy.color.magenta, 'function');
  });
});


text:
<!doctype html>

    <meta charset="utf-8"/>
    <title>Moon Lander Visualisation</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap-theme.min.css">
    <link rel="stylesheet" href="styles.css">

          Moon Lander Visualisation

Load trace

                  <button type="button" class="btn btn-primary" id="load-btn">Load</button>
                  <button type="button" class="btn btn-default stop-btn">Stop</button>

                  <button type="button" class="btn btn-primary" id="start-btn">Start evolution</button>
                  <button type="button" class="btn btn-default stop-btn">Stop</button>

              <textarea class="form-control" rows="5" id="pasted-trace" style="margin-bottom: 1em;"></textarea>

                  <button type="button" class="btn btn-primary" id="load-paste-btn">Load</button>
                  <button type="button" class="btn btn-default stop-btn">Stop</button>

          <button id="generation-copy-btn" class="btn btn-default btn-xs"> Copy to clipboard</button>

          <canvas id="display" width="640" height="480" style="background: url(images/background.jpg);"></canvas>

Score

Program


text:
package org.olat.test.util.testng;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Pattern;

import org.testng.ITestContext;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;
import org.testng.annotations.Test;

/**
 * Listener generating XML output suitable to be processed by JUnitReport. Copied from TestNG (www.testng.org) and modified
 *
 * @author Bela Ban
 * @version $Id: JUnitXMLReporter.java,v 1.6 2008-08-12 08:22:59 eglis Exp $
 */
public class JUnitXMLReporter extends TestListenerAdapter {
    private String output_dir = null;
    private String suffix = null;

    private static final String SUFFIX = "test.suffix";
    private static final String XML_DEF = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
    private static final String CDATA = "![CDATA[";
    private static final String LT = "<";
    private static final String GT = ">";
    private static final String SYSTEM_OUT = "system-out";
    private static final String SYSTEM_ERR = "system-err";

    PrintStream old_stdout = System.out;
    PrintStream old_stderr = System.err;

    private final ConcurrentMap<Class, List<ITestResult>> classes = new ConcurrentHashMap<Class, List<ITestResult>>();

    /** Map to keep systemout and systemerr associated with a class */
    final ConcurrentMap<Class, Tuple<ByteArrayOutputStream, ByteArrayOutputStream>> outputs = new ConcurrentHashMap<Class, Tuple<ByteArrayOutputStream, ByteArrayOutputStream>>();

    ByteArrayOutputStream unsolicitedOut = new ByteArrayOutputStream();
    ByteArrayOutputStream unsolicitedErr = new ByteArrayOutputStream();

    public static InheritableThreadLocal<Class> local = new InheritableThreadLocal<Class>();

    public JUnitXMLReporter() {
        System.out.println("Start");
    }

    public void onTestStart(ITestResult result) {
        Class real_class = result.getTestClass().getRealClass();
        local.set(real_class);
        print(old_stdout, "REAL CLASS: ", real_class.getName(), "");

        List<ITestResult> results = classes.get(real_class);
        if (results == null) {
            results = new LinkedList<ITestResult>();
            classes.putIfAbsent(real_class, results);
        }

        outputs.putIfAbsent(real_class, new Tuple<ByteArrayOutputStream, ByteArrayOutputStream>(new ByteArrayOutputStream(), new ByteArrayOutputStream()));
        // old_stdout.println(Thread.currentThread() + " running " + real_class.getName() + "." + result.getName() + "()");
    }

    /** Invoked each time a test succeeds */
    public void onTestSuccess(ITestResult tr) {
        Class real_class = tr.getTestClass().getRealClass();
        flushOtherOutput(real_class);
        addTest(real_class, tr);
        print(old_stdout, "OK:   ", real_class.getName(), tr.getName());
    }

    public void onTestFailedButWithinSuccessPercentage(ITestResult tr) {
        Class real_class = tr.getTestClass().getRealClass();
        flushOtherOutput(real_class);
        addTest(tr.getTestClass().getRealClass(), tr);
        print(old_stdout, "OK:   ", real_class.getName(), tr.getName());
    }

    /**
     * Invoked each time a test fails.
     */
    public void onTestFailure(ITestResult tr) {
        Class real_class = tr.getTestClass().getRealClass();
        flushOtherOutput(real_class);
        addTest(tr.getTestClass().getRealClass(), tr);
        print(old_stderr, "FAIL: ", real_class.getName(), tr.getName());
    }

    private void flushOtherOutput(Class real_class) {
        if (unsolicitedOut.size() > 0 || unsolicitedErr.size() > 0) {
            outputs.putIfAbsent(real_class, new Tuple<ByteArrayOutputStream, ByteArrayOutputStream>(unsolicitedOut, unsolicitedErr));
            unsolicitedOut = new ByteArrayOutputStream();
            unsolicitedErr = new ByteArrayOutputStream();
        }
    }

    /**
     * Invoked each time a test is skipped.
     */
    public void onTestSkipped(ITestResult tr) {
        Class real_class = tr.getTestClass().getRealClass();
        flushOtherOutput(real_class);
        addTest(tr.getTestClass().getRealClass(), tr);
        print(old_stdout, "SKIP: ", real_class.getName(), tr.getName());
    }

    private static void print(PrintStream out, String msg, String classname, String method_name) {
        out.println(msg + "[" + Thread.currentThread().getId() + "] " + classname + "." + method_name + "()");
        // out.println(msg + classname + "." + method_name + "()");
    }

    private void addTest(Class clazz, ITestResult result) {
        List<ITestResult> results = classes.get(clazz);
        if (results == null) {
            results = new LinkedList<ITestResult>();
            classes.putIfAbsent(clazz, results);
        }

        results = classes.get(clazz);
        results.add(result);
    }

    /**
     * Invoked after the test class is instantiated and before any configuration method is called.
     */
    public void onStart(ITestContext context) {
        System.out.println("Changing System.out...");
        while (System.out instanceof SysOutPrintStream) {
            System.setOut(((SysOutPrintStream) System.out).getOriginalSysOut());
        }
        while (System.err instanceof SysOutPrintStream) {
            System.setErr(((SysOutPrintStream) System.err).getOriginalSysOut());
        }
        old_stdout = System.out;
        old_stderr = System.err;
        unsolicitedOut = new ByteArrayOutputStream();
        unsolicitedErr = new ByteArrayOutputStream();
        suffix = System.getProperty(SUFFIX);
        if (suffix != null)
            suffix = suffix.trim();
        output_dir = context.getOutputDirectory(); // + File.separator + context.getName() + suffix + ".xml";

        System.setOut(new SysOutPrintStream(new JUnitXMLReporterOutputStream(this, 1), old_stdout));

        System.setErr(new SysOutPrintStream(new JUnitXMLReporterOutputStream(this, 2), old_stderr));
    }

    /**
     * Invoked after all the tests have run and all their Configuration methods have been called.
     */
    public void onFinish(ITestContext context) {
        System.out.println("Changing System.out back...");
        System.setOut(old_stdout);
        System.setErr(old_stderr);
        while (System.out instanceof SysOutPrintStream) {
            System.setOut(((SysOutPrintStream) System.out).getOriginalSysOut());
        }
        while (System.err instanceof SysOutPrintStream) {
            System.setErr(((SysOutPrintStream) System.err).getOriginalSysOut());
        }

        try {
            generateReport();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * generate the XML report given what we know from all the test results
     */
    protected void generateReport() throws IOException {
        for (Map.Entry<Class, List<ITestResult>> entry : classes.entrySet()) {
            Class clazz = entry.getKey();
            List<ITestResult> results = entry.getValue();

            int num_failures = getFailures(results);
            int num_skips = getSkips(results);
            int num_errors = getErrors(results);
            long total_time = getTotalTime(results);

            String file_name = output_dir + File.separator + "TEST-" + clazz.getName();
            if (suffix != null)
                file_name = file_name + "-" + suffix;
            file_name = file_name + ".xml";
            FileWriter out = new FileWriter(file_name, false); // don't append, overwrite
            try {
                out.write(XML_DEF + "\n");

                out.write("\n<testsuite " + " failures=\"" + num_failures + "\" errors=\"" + num_errors + "\" skips=\"" + num_skips + "\" name=\"" + clazz.getName());
                if (suffix != null)
                    out.write(" (" + suffix + ")");
                out.write("\" tests=\"" + results.size() + "\" time=\"" + (total_time / 1000.0) + "\">");

                out.write("\n<properties>");
                Properties props = System.getProperties();

                for (Map.Entry<Object, Object> tmp : props.entrySet()) {
                    out.write("\n    <property name=\"" + tmp.getKey() + "\"" + " value=\"" + tmp.getValue() + "\"/>");
                }
                out.write("\n</properties>\n");

                for (ITestResult result : results) {
                    if (result == null)
                        continue;
                    long time = result.getEndMillis() - result.getStartMillis();
                    out.write("\n    <testcase classname=\"" + clazz.getName());
                    if (suffix != null)
                        out.write(" (" + suffix + ")");
                    out.write("\" name=\"" + result.getMethod().getMethodName() + "\" time=\"" + (time / 1000.0) + "\">");

                    Throwable ex = result.getThrowable();

                    switch (result.getStatus()) {
                    case ITestResult.SUCCESS:
                    case ITestResult.SUCCESS_PERCENTAGE_FAILURE:
                        break;
                    case ITestResult.FAILURE:
                        writeFailure("failure", result.getMethod().getMethod(), ex, "exception", out);
                        break;
                    case ITestResult.SKIP:
                        writeFailure("error", result.getMethod().getMethod(), ex, "SKIPPED", out);
                        break;
                    default:
                        writeFailure("error", result.getMethod().getMethod(), ex, "exception", out);
                    }

                    out.write("\n</testcase>");
                }

                Tuple<ByteArrayOutputStream, ByteArrayOutputStream> stdout = outputs.get(clazz);
                if (stdout != null) {
                    ByteArrayOutputStream system_out = stdout.getVal1();
                    ByteArrayOutputStream system_err = stdout.getVal2();
                    writeOutput(out, system_out.toString(), 1);
                    out.write("\n");
                    writeOutput(out, system_err.toString(), 2);
                }

                out.write("\n</testsuite>\n");
            } finally {
                out.close();
            }
        }

    }

    private static String encode(String s) {
        if (s == null) {
            return null;
        }
        s = s.replaceAll(Pattern.quote("<"), "<");
        s = s.replaceAll(Pattern.quote(">"), ">");
        s = s.replaceAll(Pattern.quote("&"), "&");
        s = s.replaceAll(Pattern.quote("\""), """);
        s = s.replaceAll(Pattern.quote("'"), "'");
        return s;
    }

    private static void writeOutput(FileWriter out, String s, int type) throws IOException {
        if (s != null && s.length() > 0) {
            out.write("\n<" + (type == 2 ? SYSTEM_ERR : SYSTEM_OUT) + "><" + CDATA + "\n");
            out.write(encode(s));
            out.write("\n]]>");
            out.write("\n</" + (type == 2 ? SYSTEM_ERR : SYSTEM_OUT) + ">");
        }
    }

    private static void writeFailure(String type, Method method, Throwable ex, String msg, FileWriter out) throws IOException {
        Test annotation = method.getAnnotation(Test.class);
        if (annotation != null && ex != null) {
            Class[] expected_exceptions = annotation.expectedExceptions();
            for (int i = 0; i < expected_exceptions.length; i++) {
                Class expected_exception = expected_exceptions[i];
                if (expected_exception.equals(ex.getClass())) {
                    return;
                }
            }
        }

        out.write("\n<" + type + " type=\"");
        if (ex != null) {
            out.write(ex.getClass().getName() + "\" message=\"" + escape(ex.getMessage()) + "\">");
            printException(ex, out);
        } else
            out.write("exception\" message=\"" + msg + "\">");
        out.write("\n</" + type + ">");
    }

    private static void printException(Throwable ex, FileWriter out) throws IOException {
        if (ex == null)
            return;
        StackTraceElement[] stack_trace = ex.getStackTrace();
        out.write("\n<" + CDATA + "\n");
        out.write(ex.getClass().getName() + " \n");
        for (int i = 0; i < stack_trace.length; i++) {
            StackTraceElement frame = stack_trace[i];
            try {
                out.write("at " + frame.toString() + " \n");
            } catch (IOException e) {
            }
        }
        out.write("\n]]>");
    }

    private static String escape(String message) {
        return encode(message);
        // return message != null? message.replaceAll("<", LT).replaceAll(">", GT) : message;
    }

    private static long getTotalTime(List<ITestResult> results) {
        long start = 0, stop = 0;
        for (ITestResult result : results) {
            if (result == null)
                continue;
            long tmp_start = result.getStartMillis(), tmp_stop = result.getEndMillis();
            if (start == 0)
                start = tmp_start;
            else {
                start = Math.min(start, tmp_start);
            }

            if (stop == 0)
                stop = tmp_stop;
            else {
                stop = Math.max(stop, tmp_stop);
            }
        }
        return stop - start;
    }

    private static int getFailures(List<ITestResult> results) {
        int retval = 0;
        for (ITestResult result : results) {
            if (result != null && result.getStatus() == ITestResult.FAILURE)
                retval++;
        }
        return retval;
    }

    private static int getErrors(List<ITestResult> results) {
        int retval = 0;
        for (ITestResult result : results) {
            if (result != null && result.getStatus() != ITestResult.SUCCESS && result.getStatus() != ITestResult.SUCCESS_PERCENTAGE_FAILURE
                    && result.getStatus() != ITestResult.FAILURE)
                retval++;
        }
        return retval;
    }

    private static int getSkips(List<ITestResult> results) {
        int retval = 0;
        for (ITestResult result : results) {
            if (result != null && result.getStatus() == ITestResult.SKIP)
                retval++;
        }
        return retval;
    }

}


text:
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Heiko Kernbach
////////////////////////////////////////////////////////////////////////////////

#pragma once

#include "Containers/HashSet.h"

#include "Basics/ResourceUsage.h"

#include "Graph/Options/TwoSidedEnumeratorOptions.h"
#include "Graph/PathManagement/PathResult.h"

#include <set>

namespace arangodb {

namespace aql {
class TraversalStats;
}

namespace velocypack {
class Builder;
class HashedStringRef;
}  // namespace velocypack

namespace graph {

class PathValidatorOptions;
struct TwoSidedEnumeratorOptions;

template<class ProviderType, class Step>
class PathResult;

template<class QueueType, class PathStoreType, class ProviderType,
         class PathValidatorType>
class TwoSidedEnumerator {
 public:
  using Step = typename ProviderType::Step;  // public due to tracer access

 private:
  enum Direction { FORWARD, BACKWARD };

  using VertexRef = arangodb::velocypack::HashedStringRef;

  using Shell = std::multiset<Step>;
  using ResultList = std::vector<std::pair<Step, Step>>;
  using GraphOptions = arangodb::graph::TwoSidedEnumeratorOptions;

  class Ball {
   public:
    Ball(Direction dir, ProviderType&& provider, GraphOptions const& options,
         PathValidatorOptions validatorOptions,
         arangodb::ResourceMonitor& resourceMonitor);
    ~Ball();
    auto clear() -> void;
    auto reset(VertexRef center, size_t depth = 0) -> void;
    auto startNextDepth() -> void;
    [[nodiscard]] auto noPathLeft() const -> bool;
    [[nodiscard]] auto getDepth() const -> size_t;
    [[nodiscard]] auto shellSize() const -> size_t;
    [[nodiscard]] auto doneWithDepth() const -> bool;
    auto testDepthZero(Ball& other, ResultList& results) -> void;

    auto buildPath(Step const& vertexInShell,
                   PathResult<ProviderType, Step>& path) -> void;

    auto matchResultsInShell(Step const& match, ResultList& results,
                             PathValidatorType const& otherSideValidator)
        -> void;
    auto computeNeighbourhoodOfNextVertex(Ball& other, ResultList& results)
        -> void;

    // Ensure that we have fetched all vertices
    // in the _results list.
    // Otherwise we will not be able to
    // generate the resulting path
    auto fetchResults(ResultList& results) -> void;

    auto provider() -> ProviderType&;

   private:
    auto clearProvider() -> void;

   private:
    // Fast path, to test if we find a connecting vertex between left and right.
    Shell _shell{};

    // TODO: Double check if we really need the monitor here. Currently unused.
    arangodb::ResourceMonitor& _resourceMonitor;

    // This stores all paths processed by this ball
    PathStoreType _interior;

    // The next elements to process
    QueueType _queue;

    ProviderType _provider;

    PathValidatorType _validator;

    size_t _depth{0};
    size_t _searchIndex{std::numeric_limits<size_t>::max()};
    Direction _direction;
    size_t _minDepth{0};
    GraphOptions _graphOptions;
  };

 public:
  TwoSidedEnumerator(ProviderType&& forwardProvider,
                     ProviderType&& backwardProvider,
                     TwoSidedEnumeratorOptions&& options,
                     PathValidatorOptions validatorOptions,
                     arangodb::ResourceMonitor& resourceMonitor);
  TwoSidedEnumerator(TwoSidedEnumerator const& other) = delete;
  TwoSidedEnumerator& operator=(TwoSidedEnumerator const& other) = delete;
  TwoSidedEnumerator(TwoSidedEnumerator&& other) = delete;
  TwoSidedEnumerator& operator=(TwoSidedEnumerator&& other) = delete;

  ~TwoSidedEnumerator();

  auto clear() -> void;

  /**
   * @brief Quick test if the finder can prove there is no more data available.
   *        It can respond with false, even though there is no path left.
   * @return true There will be no further path.
   * @return false There is a chance that there is more data available.
   */
  [[nodiscard]] bool isDone() const;

  /**
   * @brief Reset to new source and target vertices.
   * This API uses string references, this class will not take responsibility
   * for the referenced data. It is caller's responsibility to retain the
   * underlying data and make sure the strings stay valid until next
   * call of reset.
   *
   * @param source The source vertex to start the paths
   * @param target The target vertex to end the paths
   */
  void reset(VertexRef source, VertexRef target, size_t depth = 0);

  /**
   * @brief Get the next path, if available written into the result build.
   * The given builder will be not be cleared, this function requires a
   * prepared builder to write into.
   *
   * @param result Input and output, this needs to be an open builder,
   * where the path can be placed into.
   * Can be empty, or an openArray, or the value of an object.
   * Guarantee: Every returned path matches the conditions handed in via
   * options. No path is returned twice, it is intended that paths overlap.
   * @return true Found and written a path, result is modified.
   * @return false No path found, result has not been changed.
   */
  bool getNextPath(arangodb::velocypack::Builder& result);

  /**
   * @brief Skip the next Path, like getNextPath, but does not return the path.
   *
   * @return true Found and skipped a path.
   * @return false No path found.
   */

  bool skipPath();
  auto destroyEngines() -> void;

  /**
   * @brief Return statistics generated since
   * the last time this method was called.
   */
  auto stealStats() -> aql::TraversalStats;

 private:
  [[nodiscard]] auto searchDone() const -> bool;
  auto startNextDepth() -> void;

  // Ensure that we have fetched all vertices
  // in the _results list.
  // Otherwise we will not be able to
  // generate the resulting path
  auto fetchResults() -> void;

  // Ensure that we have more valid paths in the _result stock.
  // May be a noop if _result is not empty.
  auto searchMoreResults() -> void;

 private:
  GraphOptions _options;
  Ball _left;
  Ball _right;
  bool _searchLeft{true};
  ResultList _results{};
  bool _resultsFetched{false};
  size_t _baselineDepth;

  PathResult<ProviderType, Step> _resultPath;
};
}  // namespace graph
}  // namespace arangodb


text:
Word embeddings are learned using a lookup table. Each word is assigned to a random vector within this table that is simply updated with the gradients coming from the network.

## Pretrained

When training with small amounts of data, performance can be improved by starting with pretrained embeddings. The arguments `-pre_word_vecs_dec` and `-pre_word_vecs_enc` can be used to specify these files.

The pretrained embeddings must be manually constructed Torch serialized tensors that correspond to the source and target dictionary files. For example:

```lua
local vocab_size = 50004
local embedding_size = 500

local embeddings = torch.Tensor(vocab_size, embedding_size):uniform()

torch.save('enc_embeddings.t7', embeddings)
```

where `embeddings[i]` is the embedding of the \(i\)-th word in the vocabulary.

To automate this process, OpenNMT provides a script `tools/embeddings.lua` than can download pretrained embeddings from [Polyglot](https://pypi.python.org/pypi/polyglot) or convert trained embeddings from [word2vec](https://github.com/dav/word2vec), [GloVe](https://nlp.stanford.edu/projects/glove/) or [FastText](https://github.com/facebookresearch/fastText) with regard to the word vocabularies generated by `preprocess.lua`. Supported format are:

* `word2vec-bin` (default): binary format generated by word2vec.
* `word2vec-txt`: textual word2vec format - starts with header line containing number of words and embedding size, and is then followed by one line per embedding: the first token is the word, and following fields are the embeddings values.
* `glove`: text format - same format than `word2vec-txt` but without header line.

!!! note "Note"
    The script requires the `lua-zlib` package.

For example, to generate pretrained English words embeddings:

```bash
th tools/embeddings.lua -lang en -dict_file data/demo.src.dict -save_data data/demo-src-emb
```

!!! note "Note"
    Languages codes are Polygot's [Wikipedia Language Codes](https://sites.google.com/site/rmyeid/projects/polyglot).

Or to map pretrained *word2vec* vectors to the built vocabulary:

```bash
th tools/embeddings.lua -embed_type word2vec -embed_file data/GoogleNews-vectors-negative300.bin -dict_file data/demo.src.dict\
                        -save_data data/demo-src-emb
```

!!! tip "Tip"
    If vocabs as-is are not found in the embeddings file, you can use `-approximate` option to also look for uppercase variants and variants without possible joiner marks. You can dump the non found vocabs by setting `-save_unknown_dict` parameter.

## Fixed

By default these embeddings will be updated during training, but they can be held fixed using `-fix_word_vecs_enc` and `-fix_word_vecs_dec` options. These options can be enabled or disabled during a retraining.

!!! tip "Tip"
    When using pretrained word embeddings, if you declare a larger `-word_vec_size` then the difference is uniformally initalized and you can use `-fix_word_vecs_enc pretrained` (or `-fix_word_vecs_dec pretrained`) to fix the pretrained part and optimize the remaining part.

## Extraction

The `tools/extract_embeddings.lua` script can be used to extract the model word embeddings into text files. They can then be easily transformed into another format for visualization or processing.


text:
using System;

namespace NHamcrest.Core
{
	public class IsLessThan<T> : Matcher<T> where T : IComparable<T>
	{
		private readonly T @object;

		public IsLessThan(T arg)
		{
			@object = arg;
		}

		public override void DescribeTo(IDescription description)
		{
			description.AppendText("less than ").AppendValue(@object);
		}

		public override bool Matches(T arg)
		{
			return arg.CompareTo(@object) < 0;
		}
	}

	public static partial class Is
	{
		public static IMatcher<T> LessThan<T>(T value) where T : IComparable<T>
		{
			return new IsLessThan<T>(value);
		}
	}
}


text:
[% BLOCK book_block %]

    [% IF isbn %]
        [% END %]
    [% title %]

    [% author %]

        [% IF link %]Read [% IF sample %]sample chapters[% ELSE %]the entire book free[% END %] online...
[% END %]
[% description %]

    [% IF isbn %]

        Buy from: [% INCLUDE "tpl/bookstore-links" style="text" %]

    [% END %]

[% END %]

Beginner books

Books commonly recommended

[% PROCESS book_block
    name => 'beginningperl',
    title => 'Beginning Perl',
    isbn => '1861003145',
    link => '/books/beginning-perl/',
    author => 'by Simon Cozens, Peter Wainwright. 700 pages. Wrox Press Inc. (May 25, 2000).',
    description => "
    Beginning Perl is a different kind of Perl book. It's written particularly with the beginning programmer in mind, but it doesn't treat you like an idiot, and experienced programmers will not feel patronized. It covers a lot of ground, from the very basics of programming, right through to developing CGI applications for the web. More importantly, it emphasizes good Perl practice, and readable and maintainable code.
    ",
%]

[% PROCESS book_block
    name => 'learnperl',
    title => 'Learning Perl, Sixth Edition',
    isbn => '1449303587',
    link => '',
    author => 'by Randal L. Schwartz, brian d foy, Tom Phoenix;
    390 pages;
    O\'Reilly Media, Inc.;
    (June 2011)',
    description => "
    A tutorial book, covering how
       you could spend the first 30 to 40 hours with Perl. The sixth edition
       covers up to Perl 5.14. Reflecting years of classroom testing and
       experience, this edition is packed with exercises that let you
       practice the concepts while you follow the text.
    ",
%]

Essentials

[% PROCESS book_block
    name => 'modernperl',
    title => 'Modern Perl',
    isbn => '0977920178',
    link => 'http://www.onyxneon.com/books/modern_perl/index.html',
    author => 'by chromatic (2012).',
    description => "Modern Perl is suitable for programmers of every level. It's more than a Perl tutorial—only Modern Perl focuses on Perl 5.12 and 5.14, to demonstrate the latest and most effective time-saving features. Only Modern Perl explains how and why the language works, to let you unlock the full power of Perl.",
%]

[% PROCESS book_block
    name => 'programmingperl',
    title => 'Programming Perl, 3rd Edition',
    isbn => '0596000278',
    link => '',
    author => 'by Larry Wall, Tom Christiansen, Jon Orwant;
    1092 pages;
    O\'Reilly Media, Inc.;
    (July 2000)',
    description => "
The reference book for Perl 5.
    ",
%]

[% PROCESS book_block
    name => 'perlcookbook',
    title => 'The Perl Cookbook, 2nd Edition',
    isbn => '0596003137',
    link => '',
    author => 'by Tom Christiansen, Nathan Torkington, Larry Wall;
    964 pages;
    O\'Reilly Media, Inc.;
    (August 21, 2003)',
    description => "

    'Precious few books can meet the needs of novices and experts
           simultaneously. The Perl Cookbook does, and on nearly every
           page. It has the perfect mix of instruction, revelation, and
           attitude.' --Jon Orwant, editor of The Perl Journal
    ",
%]

Intermediate books

[% PROCESS book_block
    name => 'intermediateperl',
    title => 'Intermediate Perl',
    isbn => '0596102062',
    link => '',
    author => 'by Randal L. Schwartz and brian d foy, with Tom Phoenix;
    278 pages;
    O\'Reilly Media, Inc.;
    (March 2006)',
    description => "
    Intermediate Perl picks up where
    Learning Perl leaves off. This new book offers a gentle introduction to the
    world of references, object-oriented programming, and the use of Perl
    modules that form the backbone of any effective Perl program. Following the
    successful format of Learning Perl, each chapter in the book is designed to
    be small enough to be read in just an hour or two. Each chapter ends with a
    series of exercises to help you practice what you've learned with answers
    in an appendix for your reference. In short, this book covers everything
    that separates the Perl dabbler from the Perl programmer.
    ",
%]

[% PROCESS book_block
    name => 'beginningperl2nd',
    title => 'Beginning Perl, 2nd Edition',
    isbn => '159059391X',
    link => '',
    author => 'by James Lee;
    464 pages;
    Apress, LLC;
    (August 2004)',
    description => "
    Beginning Perl is a different kind of Perl book. It's written
    particularly with the beginning programmer in mind, but  experienced programmers will not feel patronised.
    It covers a lot of ground, from the very basics of programming, right
    through to developing CGI applications for the web. More importantly, it
    emphasises good Perl practice, and readable and maintainable code.
    ",
%]

[% PROCESS book_block
    name => 'perllwp',
    title => 'Perl & LWP',
    isbn => '0596001789',
    link => 'http://lwp.interglacial.com/',
    author => 'by Sean M. Burke;
    264 pages;
     O\'Reilly Media; first edition (20 Jun 2002) with corrections (2007)',
    description => "
    Perl & LWP explains how to write programs that browse the Web,
    using the excellent Library for the World Wide Web or LWP. It is aimed
    at developers who already know both Perl and HTML, although you
    don't need to be an expert in either.
    ",
%]

Advanced

[% PROCESS book_block
    name => 'advancedperlprogramming',
    title => 'Advanced Perl Programming',
    isbn => '0596004567',
    link => '',
    author => 'by Simon Cozens;
    298 pages;
    O\'Reilly Media, Inc.;
    (June 28, 2005)',
    description => "
    Perl has proven to be the most effective language for the latest trends
    in computing and business. Every programmer must keep up with the
    latest tools and techniques. This updated version of Advanced Perl
    Programming from O'Reilly gives you the essential knowledge of the
    modern Perl programmer. Whatever your current level of Perl expertise,
    this book will help you push your skills to the next level and become a
    more accomplished programmer.
    ",
%]

[% PROCESS book_block
    name => 'higherorderperl',
    title => 'Higher Order Perl',
    isbn => '1558607013',
    link => '',
    author => 'by Mark Jason Dominus;
    Morgan Kauffman (April 2005)',
    description => "
    A must read for any competent Perl programmer.
    ",
%]

[% PROCESS book_block
    name => 'perldebugged',
    title => 'Perl Debugged',
    isbn => '0201700549',
    link => '',
    author => 'by Peter J. Scott, Ed Wright;
    288 pages;
    Addison-Wesley;
    (March 27, 2001)',
    description => "
        I highly recommend Perl Debugged to anyone at
                        the beginning or intermediate stage in Perl
                        programming, particularly to programmers who have
                        less than 2-4 years of debugging experience in
                        general. An experienced programmer, on the other
                        hand, will want to buy a copy (copies?) to browse
                        and then hand to his junior co-worker(s) with
                        stern instructions to 'read first, code later.'
                        — Joseph N. Hall (author of Effective Perl
                        Programming)
    ",
%]

[% PROCESS book_block
    name => 'effectiveperl',
    title => 'Effective Perl Programming, 2nd Edition',
    isbn => '0321496949',
    link => '',
    author => 'Joseph N. Hall, Joshua A. McAdams, brian d foy
    504 pages;
    Addison-Wesley Professional; 2 edition (April 29, 2010)',
    description => "

    ",
%]

[% PROCESS book_block
    name => 'apacheapimod_perl',
    title => 'Writing Apache Modules with Perl and C: The Apache API and mod_perl',
    isbn => '156592567X',
    link => '',
    author => 'by Lincoln Stein, Doug MacEachern, Linda Mui (Editor);
    724 pages;
    O\'Reilly Media, Inc.;
    (March 1999)',
    description => "
    Writing Apache Modules with Perl and C will allow you to enhance
    your Apache HTTP server in just about any way you'd like. Overall, it
    is an excellent book, and it has a lot of good information and terrific
    examples on everything from "Content Handlers" to customizing the
    Apache server configuration process. — Doug Beaver
    ",
%]

[% PROCESS book_block
    name => 'practicalmod_perl',
    title => 'Practical mod_perl',
    isbn => '0596002270',
    link => '',
    author => 'by Stas Bekman & Eric Cholet;
    924 pages;
    O\'Reilly Media, Inc.;
    (May 27, 2003)',
    description => "
    Mod_perl embeds the popular programming language Perl in
    the Apache web server, giving rise to a fast and powerful web programming
    environment. Written for Perl web developers and web administrators,
    Practical mod_perl is an extensive guide to the nuts and bolts of the
    powerful and popular combination of Apache and mod_perl. From writing and
    debugging scripts to keeping your server running without failures, the
    techniques in this book will help you squeeze every ounce of power out of
    your server. True to its title, this is the practical guide to mod_perl.
    ",
%]

[% PROCESS book_block
    name => 'mod_perl2_user',
    title => 'mod_perl2 User Guide',
    isbn => '0977920119',
    link => '',
    author => 'by Stas Bekman & Jim Brandt;
    OnyxNeon;
    (August 2007)',
    description => "
    mod_perl 2, the next generation of the Apache Perl module, gives you full access to the Apache 2 internals via the Perl programming language, just as mod_perl 1 gave you access to Apache 1. New features in Apache and Perl make mod_perl 2 even more powerful and useful than before, allowing you to quickly write and deploy fast, robust web applications.
    As with any major upgrade, there are new features and key changes to mod_perl from the 1.x generation. The mod_perl 2 User's Guide explains these key changes and demonstrates the tools that you can use to port modules and migrate your existing code.
    ",
%]

[% PROCESS book_block
    name => 'mod_perlcookbook',
    title => "mod_perl Developer's Cookbook",
    isbn => '0672322404',
    link => '',
    author => 'by Geoffrey Young, Paul Lindner, Randy Kobes;
    650 pages;
    Sams Publishing;
    (January 2002)',
    description => "
        A practical, hands-on guide that shows you how to exploit
        the power of mod_perl.
    ",
%]

[% PROCESS book_block
    name => 'masteringregexs',
    title => 'Mastering Regular Expressions, 3rd Edition',
    isbn => '0596528124',
    link => '',
    author => 'by Jeffrey E. Friedl;
    542 pages;
    O\'Reilly Media, Inc.;
    (August 2006)',
    description => "
    Mastering Regular Expressions, Third Edition has been thoroughly
    updated to include all the new features of Perl 5.8, as well as several
    other languages, including Java, VB.NET, C#, Python, JavaScript, Tcl,
    and Ruby. Written in the lucid, entertaining tone that made a complex,
    dry topic crystal-clear to thousands of programmers, and sprinkled with
    solutions to complex real-world problems, Mastering Regular Expressions
    offers a wealth information that you can put to immediate use.
    ",
%]

[% PROCESS book_block
    name => 'extendandembeddperl',
    title => 'Extending and Embedding Perl',
    isbn => '1930110820',
    link => '',
    author => 'by Tim Jenness and Simon Cozens;
    384 pages;
    Manning Publications Company;
    (July 2002)',
    description => "
    Extending and Embedding Perl explains how to expand the
    functionality and usefulness of the Perl programming language and how
    to use Perl from C programs. It begins simply but also covers complex
    issues using real code examples from the Perl source. The book
    discusses how to write interfaces to C libraries (as well as C++ and
    Fortran libraries). It shows you how to implement Perl callbacks for C
    libraries, how to pass Perl hashes and arrays between Perl and C, and
    how to use the Perl Data Language infrastructure to improve the speed
    of array operations.
    ",
%]

[% PROCESS book_block
    name => 'perldbi',
    title => 'Programming the Perl DBI',
    isbn => '1565926994',
    link => '',
    author => 'by Alligator Descartes, Tim Bunce;
    346 pages;
    O\'Reilly Media, Inc.;
    (February 2000)',
    description => "

    ",
%]

[% PROCESS book_block
    name => 'ooperl',
    title => 'Object Oriented Perl',
    isbn => '1884777791',
    link => '',
    author => 'by Damian Conway;
    490 pages;
    Manning Publications Company;
    (August 1999)',
    description => "
    Filled with syntactic tips and tricks, Object Oriented Perl is a
    sure bet for any programmer who wants to learn how to use Perl objects
    effectively.
    ",
%]

[% PROCESS book_block
    name => 'perltesting',
    title => 'Perl Testing: A Developer\'s Notebook',
    isbn => '0596100922',
    link => '',
    author => 'by Ian Langworth, chromatic;
    O\'Reilly; (July 2005)',
    description => "
    ",
%]


text: export { default } from 'ember-clock-face/components/hour-marker';


text:
layout: post
title: "010 - MMOs, MOBAs e afins"
redirect_from:
  - /10/
  - /010/
comments: true
share: true
no_author: true
mp3_url: http://www.buzzsprout.com/37513/253102-010-mmo-mobas-e-afins.mp3
mp3_length: 52181724
mp3_duration: "52:43"
mp3_filename: geekout-010.mp3
summary: Cada um com seu vício, cada um com sua tribo, especialmente quando o assunto é MMO, MOBAs a afins. Hoje vamos falar sobre esses jogos que consomem nosso tempo, nossas vidas e nós adoramos. Como sempre também temos dicas ligadas ao tema e um lugar bacana para você passear. Divirtam-se conosco :)
---

Bem-vind@s ao **Geek Out**, o podcast para geeks conectad@s.

Cada um com seu vício, cada um com sua tribo, especialmente quando o assunto é MMO, MOBAs a afins. Hoje vamos falar sobre esses jogos que consomem nosso tempo, nossas vidas e nós adoramos.

Também temos um sorteio para vocês, ouçam o episódio para saber o que estamos sorteando e como participar.

Como sempre também temos dicas ligadas ao tema e um lugar bacana para você passear. Divirtam-se conosco :)

Comentários são muito bem-vindos, tanto na página do site, [no nosso Twitter](https://twitter.com/geekoutfm)) ou na [nossa página do Facebook](https://www.facebook.com/geekoutfm). Se quiser entrar em contato direto conosco basta mandar e-mails para [contato@geekout.fm](mailto:contato@geekout.fm).

Para ficar sabendo dos próximos episódios assine o [feed do podcast](/feed.xml), [nos adicione e deixe seu review no iTunes](https://itunes.apple.com/br/podcast/geek-out/id956387481), [siga-nos no Twitter em @GeekOutFM](https://twitter.com/GeekoutFM), e ajude-nos a divulgar o programa se você curtiu. Seu feedback e apoio são muito importantes.

{% include mp3_player.html %}

## Shownotes
* [MMO](http://en.wikipedia.org/wiki/Massively_multiplayer_online_game)
* [Destiny](http://www.destinythegame.com/pt)
* [World of Warcraft](http://us.battle.net/wow/pt/)
* [Gunbound](http://gunbound.softnyxbrasil.com/)
* [Ragnarok online](http://levelupgames.uol.com.br/ragnarok/)
* [LevelUp Games](http://levelupgames.uol.com.br/)
* [Tibia](http://www.tibia.com/news/?subtopic=latestnews)
* [Everquest](https://www.everquest.com/home)
* [Lineage](http://en.wikipedia.org/wiki/Lineage_%28video_game%29)
* [MU online](http://muonline.webzen.com/main)
* [Revista Supergames](http://pt.wikipedia.org/wiki/Supergamepower)
* [MOBA](http://jogos.uol.com.br/ultimas-noticias/2012/01/31/league-of-legends-dota-etc-conheca-os-jogos-estilo-moba.htm)
* [SMITE](http://www.hirezstudios.com/smite)
* [League of Legends](http://br.leagueoflegends.com/)
* [DOTA](http://en.wikipedia.org/wiki/Defense_of_the_Ancients)
* [Starcraft](http://www.starcraft2brasil.com.br/)
* [Command and Conquer](http://en.wikipedia.org/wiki/Command_%26_Conquer)
* [Heroes Of The Storm](http://us.battle.net/heroes/pt/)
* [E-sports](http://en.wikipedia.org/wiki/Electronic_sports)
* [Counter Strike](http://blog.counter-strike.net/)
* [Street Fighter](http://en.wikipedia.org/wiki/Street_Fighter)
* ["Final do campeonato brasileiro de 'League of Legends' lota Maracanãzinho - Link Estadão – Cultura Digital - Estadao.com.br" on ](http://blogs.estadao.com.br/link/final-do-campeonato-brasileiro-de-league-of-legends-lota-maracanazinho/)
* [Twitch](http://www.twitch.tv/)
* [Trackmania](http://en.wikipedia.org/wiki/TrackMania)
* [Electronic Sports World Cup - ESWC](http://www.eswc.com/)
* [Carl Jr, campeão mundial de Trackmania](https://twitter.com/HyperX/status/529255371891032064)

## Picks
* MJ
  * [Hot Tub Time Machine](http://www.imdb.com/title/tt1231587/)
  * [Power Rangers Short](http://io9.com/holy-hell-this-power-rangers-reboot-is-dark-as-f-ck-1687689958)
  * [The Truth behind the Power Rangers short](http://io9.com/the-truth-behind-the-power-rangers-short-and-how-you-h-1688907857)
* Rafael
  * [Journey](http://en.wikipedia.org/wiki/Journey_%282012_video_game%29)
  * [Sheepfarmer's Daughter: The Deed of Paksenarrion, Book 1 Audiobook - Elizabeth Moon](http://www.audible.com/pd/Sci-Fi-Fantasy/Sheepfarmers-Daughter-Audiobook/B003C26RG4)
* Caffo
  * [Dungeons and desktops](http://www.goodreads.com/book/show/2796728-dungeons-and-desktops)

## Geek Out
* [Rock'n'Roll Burger - São Paulo](http://www.rocknrollburger.com.br/)


text:
public static bool isNotNull(dynamic AnyTypeValue) {
   //tratamentos por tipo
}

public static bool isNotNull(object AnyTypeValue) {
   //tratamentos por tipo
}

public static bool isNotNull<T>(T AnyTypeValue) {
   //não precisa fazer tratamentos por tipo
}

public static bool isNotNull<T>(T AnyTypeValue) where T : class {
   //se tiver que fazer tratamento por tipo, algo está errado
}

//https://pt.stackoverflow.com/q/57333/101