text:
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/module.h>		/* For module specific items */
#include <linux/moduleparam.h>		/* For new moduleparam's */
#include <linux/types.h>		/* For standard types (like size_t) */
#include <linux/errno.h>		/* For the -ENODEV/... values */
#include <linux/kernel.h>		/* For printk/panic/... */
#include <linux/fs.h>			/* For file operations */
#include <linux/miscdevice.h>		/* For struct miscdevice */
#include <linux/watchdog.h>		/* For the watchdog specific items */
#include <linux/init.h>			/* For __init/__exit/... */
#include <linux/platform_device.h>	/* For platform_driver framework */
#include <linux/spinlock.h>		/* For spin_lock/spin_unlock/... */
#include <linux/uaccess.h>		/* For copy_to_user/put_user/... */
#include <linux/io.h>			/* For devm_ioremap_nocache */

#include <asm/mach-rc32434/integ.h>	/* For the Watchdog registers */

#define VERSION "1.0"

static struct {
	unsigned long inuse;
	spinlock_t io_lock;
} rc32434_wdt_device;

static struct integ __iomem *wdt_reg;

static int expect_close;

/* Board internal clock speed in Hz,
 * the watchdog timer ticks at. */
extern unsigned int idt_cpu_freq;

/* translate wtcompare value to seconds and vice versa */
#define WTCOMP2SEC(x)	(x / idt_cpu_freq)
#define SEC2WTCOMP(x)	(x * idt_cpu_freq)

/* Use a default timeout of 20s. This should be
 * safe for CPU clock speeds up to 400MHz, as
 * ((2 ^ 32) - 1) / (400MHz / 2) = 21s.  */
#define WATCHDOG_TIMEOUT 20

static int timeout = WATCHDOG_TIMEOUT;
module_param(timeout, int, 0);
MODULE_PARM_DESC(timeout, "Watchdog timeout value, in seconds (default="
		__MODULE_STRING(WATCHDOG_TIMEOUT) ")");

static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default="
	__MODULE_STRING(WATCHDOG_NOWAYOUT) ")");

/* apply or and nand masks to data read from addr and write back */
#define SET_BITS(addr, or, nand) \
	writel((readl(&addr) | or) & ~nand, &addr)

static int rc32434_wdt_set(int new_timeout)
{
	int max_to = WTCOMP2SEC((u32)-1);

	if (new_timeout < 0 || new_timeout > max_to) {
		pr_err("timeout value must be between 0 and %d\n", max_to);
		return -EINVAL;
	}
	timeout = new_timeout;
	spin_lock(&rc32434_wdt_device.io_lock);
	writel(SEC2WTCOMP(timeout), &wdt_reg->wtcompare);
	spin_unlock(&rc32434_wdt_device.io_lock);

	return 0;
}

static void rc32434_wdt_start(void)
{
	u32 or, nand;

	spin_lock(&rc32434_wdt_device.io_lock);

	/* zero the counter before enabling */
	writel(0, &wdt_reg->wtcount);

	/* don't generate a non-maskable interrupt,
	 * do a warm reset instead */
	nand = 1 << RC32434_ERR_WNE;
	or = 1 << RC32434_ERR_WRE;

	/* reset the ERRCS timeout bit in case it's set */
	nand |= 1 << RC32434_ERR_WTO;

	SET_BITS(wdt_reg->errcs, or, nand);

	/* set the timeout (either default or based on module param) */
	rc32434_wdt_set(timeout);

	/* reset WTC timeout bit and enable WDT */
	nand = 1 << RC32434_WTC_TO;
	or = 1 << RC32434_WTC_EN;

	SET_BITS(wdt_reg->wtc, or, nand);

	spin_unlock(&rc32434_wdt_device.io_lock);
	pr_info("Started watchdog timer\n");
}

static void rc32434_wdt_stop(void)
{
	spin_lock(&rc32434_wdt_device.io_lock);

	/* Disable WDT */
	SET_BITS(wdt_reg->wtc, 0, 1 << RC32434_WTC_EN);

	spin_unlock(&rc32434_wdt_device.io_lock);
	pr_info("Stopped watchdog timer\n");
}

static void rc32434_wdt_ping(void)
{
	spin_lock(&rc32434_wdt_device.io_lock);
	writel(0, &wdt_reg->wtcount);
	spin_unlock(&rc32434_wdt_device.io_lock);
}

static int rc32434_wdt_open(struct inode *inode, struct file *file)
{
	if (test_and_set_bit(0, &rc32434_wdt_device.inuse))
		return -EBUSY;

	if (nowayout)
		__module_get(THIS_MODULE);

	rc32434_wdt_start();
	rc32434_wdt_ping();

	return nonseekable_open(inode, file);
}

static int rc32434_wdt_release(struct inode *inode, struct file *file)
{
	if (expect_close == 42) {
		rc32434_wdt_stop();
		module_put(THIS_MODULE);
	} else {
		pr_crit("device closed unexpectedly. WDT will not stop!\n");
		rc32434_wdt_ping();
	}
	clear_bit(0, &rc32434_wdt_device.inuse);
	return 0;
}

static ssize_t rc32434_wdt_write(struct file *file, const char *data,
				size_t len, loff_t *ppos)
{
	if (len) {
		if (!nowayout) {
			size_t i;

			/* In case it was set long ago */
			expect_close = 0;

			for (i = 0; i != len; i++) {
				char c;
				if (get_user(c, data + i))
					return -EFAULT;
				if (c == 'V')
					expect_close = 42;
			}
		}
		rc32434_wdt_ping();
		return len;
	}
	return 0;
}

static long rc32434_wdt_ioctl(struct file *file, unsigned int cmd,
				unsigned long arg)
{
	void __user *argp = (void __user *)arg;
	int new_timeout;
	unsigned int value;
	static const struct watchdog_info ident = {
		.options =		WDIOF_SETTIMEOUT |
					WDIOF_KEEPALIVEPING |
					WDIOF_MAGICCLOSE,
		.identity =		"RC32434_WDT Watchdog",
	};
	switch (cmd) {
	case WDIOC_GETSUPPORT:
		if (copy_to_user(argp, &ident, sizeof(ident)))
			return -EFAULT;
		break;
	case WDIOC_GETSTATUS:
	case WDIOC_GETBOOTSTATUS:
		value = 0;
		if (copy_to_user(argp, &value, sizeof(int)))
			return -EFAULT;
		break;
	case WDIOC_SETOPTIONS:
		if (copy_from_user(&value, argp, sizeof(int)))
			return -EFAULT;
		switch (value) {
		case WDIOS_ENABLECARD:
			rc32434_wdt_start();
			break;
		case WDIOS_DISABLECARD:
			rc32434_wdt_stop();
			break;
		default:
			return -EINVAL;
		}
		break;
	case WDIOC_KEEPALIVE:
		rc32434_wdt_ping();
		break;
	case WDIOC_SETTIMEOUT:
		if (copy_from_user(&new_timeout, argp, sizeof(int)))
			return -EFAULT;
		if (rc32434_wdt_set(new_timeout))
			return -EINVAL;
		/* Fall through */
	case WDIOC_GETTIMEOUT:
		return copy_to_user(argp, &timeout, sizeof(int));
	default:
		return -ENOTTY;
	}

	return 0;
}

static const struct file_operations rc32434_wdt_fops = {
	.owner		= THIS_MODULE,
	.llseek		= no_llseek,
	.write		= rc32434_wdt_write,
	.unlocked_ioctl	= rc32434_wdt_ioctl,
	.open		= rc32434_wdt_open,
	.release	= rc32434_wdt_release,
};

static struct miscdevice rc32434_wdt_miscdev = {
	.minor	= WATCHDOG_MINOR,
	.name	= "watchdog",
	.fops	= &rc32434_wdt_fops,
};

static int rc32434_wdt_probe(struct platform_device *pdev)
{
	int ret;
	struct resource *r;

	r = platform_get_resource_byname(pdev, IORESOURCE_MEM, "rb532_wdt_res");
	if (!r) {
		pr_err("failed to retrieve resources\n");
		return -ENODEV;
	}

	wdt_reg = devm_ioremap_nocache(&pdev->dev, r->start, resource_size(r));
	if (!wdt_reg) {
		pr_err("failed to remap I/O resources\n");
		return -ENXIO;
	}

	spin_lock_init(&rc32434_wdt_device.io_lock);

	/* Make sure the watchdog is not running */
	rc32434_wdt_stop();

	/* Check that the heartbeat value is within it's range;
	 * if not reset to the default */
	if (rc32434_wdt_set(timeout)) {
		rc32434_wdt_set(WATCHDOG_TIMEOUT);
		pr_info("timeout value must be between 0 and %d\n",
			WTCOMP2SEC((u32)-1));
	}

	ret = misc_register(&rc32434_wdt_miscdev);
	if (ret < 0) {
		pr_err("failed to register watchdog device\n");
		return ret;
	}

	pr_info("Watchdog Timer version " VERSION ", timer margin: %d sec\n",
		timeout);

	return 0;
}

static int rc32434_wdt_remove(struct platform_device *pdev)
{
	misc_deregister(&rc32434_wdt_miscdev);
	return 0;
}

static void rc32434_wdt_shutdown(struct platform_device *pdev)
{
	rc32434_wdt_stop();
}

static struct platform_driver rc32434_wdt_driver = {
	.probe		= rc32434_wdt_probe,
	.remove		= rc32434_wdt_remove,
	.shutdown	= rc32434_wdt_shutdown,
	.driver		= {
			.name = "rc32434_wdt",
	}
};

module_platform_driver(rc32434_wdt_driver);

MODULE_AUTHOR("Ondrej Zajicek <santiago@crfreenet.org>,"
		"Florian Fainelli <florian@openwrt.org>");
MODULE_DESCRIPTION("Driver for the IDT RC32434 SoC watchdog");
MODULE_LICENSE("GPL");


text:
(function() {
	"use strict";
	// commonly used properties
	R.eachIn({
		Value: 'value',
		Text: ('textContent' in document.documentElement) ? 'textContent' : 'innerText',
		HTML: 'innerHTML',
		Checked: 'checked',
		Disabled: 'disabled'
	}, function(val, key) {
		R.extendElement('get' + key, function(elem) {
			return elem[val];
		}, { canReturnSingle: true });

		R.extendElement('set' + key, function(elem, value) {
			elem[val] = value;
			return elem;
		});
	});

	R.extendElement('check', function(elem) {
		return elem.setChecked(true);
	});

	R.extendElement('uncheck', function(elem) {
		return elem.setChecked(false);
	});

	R.extendElement('enable', function(elem) {
		return elem.setDisabled(false);
	});

	R.extendElement('disable', function(elem) {
		return elem.setDisabled(true);
	});

	R.extendElement('isDisabled', function(elem) {
		return elem.disabled;
	}, { canReturnSingle: true });

	R.extendElement('isEnabled', function(elem) {
		return !elem.disabled;
	}, { canReturnSingle: true });

	R.extendElement('setReadOnly', function(readOnly, elem) {
		if ('readOnly' in elem) {
			if (readOnly === undefined) {
				readOnly = true;
			}
			elem.readOnly = readOnly;
		}
		return elem;
	});

	R.extendElement('isReadOnly', function(elem) {
		return elem.readOnly;
	}, { canReturnSingle: true });

	R.extendElement('isReadWrite', function(elem) {
		return !elem.readOnly;
	}, { canReturnSingle: true });

	R.extendElement('focus', function(elems) {
		if (!elems.length) {
			return;
		}
		elems[0].focus();
		return elems;
	}, { usesCollection: true });
}());

redpajama_set_name: RedPajamaGithub


text:
<?php
use Kahlan\Filter\Filter;
use Kahlan\Reporter\Coverage;
use Kahlan\Reporter\Coverage\Driver\Xdebug;
use Kahlan\Reporter\Coverage\Exporter\Coveralls;
use Kahlan\Reporter\Coverage\Exporter\CodeClimate;

$args = $this->args();
$args->argument('coverage', 'default', 3);

Filter::register('kahlan.coverage', function($chain) {
    if (!extension_loaded('xdebug')) {
        return;
    }
    $reporters = $this->reporters();
    $coverage = new Coverage([
        'verbosity' => $this->args()->get('coverage'),
        'driver'    => new Xdebug(),
        'path'      => $this->args()->get('src'),
        'exclude'   => [
            //Exclude init script
            'src/init.php',
            //Exclude Workflow from code coverage reporting
            'src/Cli/Kahlan.php',
            //Exclude coverage classes from code coverage reporting (don't know how to test the tester)
            'src/Reporter/Coverage/Collector.php',
            'src/Reporter/Coverage/Driver/Xdebug.php',
            'src/Reporter/Coverage/Driver/HHVM.php',
            'src/Reporter/Coverage/Driver/Phpdbg.php',
            //Exclude text based reporter classes from code coverage reporting (a bit useless)
            'src/Reporter/Dot.php',
            'src/Reporter/Bar.php',
            'src/Reporter/Verbose.php',
            'src/Reporter/Terminal.php',
            'src/Reporter/Reporter.php',
            'src/Reporter/Coverage.php',
            'src/Reporter/Json.php',
            'src/Reporter/Tap.php',
        ],
        'colors'    => !$this->args()->get('no-colors')
    ]);
    $reporters->add('coverage', $coverage);
});

Filter::apply($this, 'coverage', 'kahlan.coverage');

Filter::register('kahlan.coverage-exporter', function($chain) {
    $reporter = $this->reporters()->get('coverage');
    if (!$reporter) {
        return;
    }
    Coveralls::write([
        'collector'      => $reporter,
        'file'           => 'coveralls.json',
        'service_name'   => 'travis-ci',
        'service_job_id' => getenv('TRAVIS_JOB_ID') ?: null
    ]);
    CodeClimate::write([
        'collector'  => $reporter,
        'file'       => 'codeclimate.json',
        'branch'     => getenv('TRAVIS_BRANCH') ?: null,
        'repo_token' => 'a4b5637db5629f60a5d3fc1a070b2339479ff8989c6491dfc6a19cada5e4ffaa'
    ]);
    return $chain->next();
});

Filter::apply($this, 'reporting', 'kahlan.coverage-exporter');


text:
layout: page
title: Mercer - Fowler Wedding
date: 2016-05-24
author: Mark Doyle
tags: weekly links, java
status: published
summary: Aenean sollicitudin tortor quis odio maximus fringilla.
banner: images/banner/people.jpg
booking:
  startDate: 06/02/2018
  endDate: 06/03/2018
  ctyhocn: FLLWEHX
  groupCode: MFW
published: true
---
Maecenas facilisis arcu sed tortor commodo hendrerit. Pellentesque ipsum ante, volutpat rhoncus convallis id, tempus sed lacus. Nam vitae laoreet est, at consequat sem. Morbi leo mauris, dignissim eget egestas luctus, pellentesque eget mauris. Integer libero sapien, gravida id orci sit amet, convallis tincidunt metus. Maecenas non venenatis libero. Nam in lacinia turpis. Proin lacus justo, pretium consectetur diam aliquam, mattis dignissim mauris. Nam eu eleifend est. Duis varius massa sed ullamcorper malesuada. Maecenas mi urna, elementum id finibus et, facilisis eu nisi. Maecenas eget nisl sed nibh ullamcorper rutrum. Duis tincidunt, lorem nec tincidunt sagittis, urna massa lacinia erat, in rhoncus diam lectus id diam. Nunc accumsan viverra odio, blandit tristique massa pretium in.

1 Duis et augue a nunc lobortis posuere
1 Nulla fermentum eros quis eros faucibus blandit
1 Integer eget est eget felis suscipit porttitor sollicitudin sed lectus.

Ut cursus blandit felis et venenatis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nullam placerat diam ligula, vel lacinia ex vestibulum sed. Nulla placerat quis neque a tristique. Nam eget purus arcu. Praesent elementum tempus imperdiet. Donec auctor ut mauris at rutrum. Donec interdum libero sed quam ornare sollicitudin. Etiam mauris nibh, efficitur in pellentesque eget, volutpat ut lectus.


text:
{-# LANGUAGE OverloadedStrings #-}
{-
  Custom prettyprinter for JMacro AST
  - uses the jmacro prettyprinter for most of the work
  - fixme: need a better way to make a customized prettyprinter, without duplicating 5 cases
-}
module Gen2.Printer where

import           Data.Char                    (isAlpha, isDigit)
import qualified Data.Map                     as M
import qualified Data.Text.Lazy               as TL
import qualified Data.Text                    as T
import Prelude

import           Text.PrettyPrint.Leijen.Text (Doc, align, char, comma,
                                               fillSep, hcat, nest, parens,
                                               punctuate, text, vcat, (<+>))
import qualified Text.PrettyPrint.Leijen.Text as PP

import           Compiler.JMacro              (Ident, JExpr(..), JStat(..), JOp(..),
                                               JVal(..), jsToDocR, RenderJs(..), defaultRenderJs)

pretty :: JStat -> Doc
pretty = jsToDocR ghcjsRenderJs

ghcjsRenderJs :: RenderJs
ghcjsRenderJs = defaultRenderJs { renderJsV = ghcjsRenderJsV
                                , renderJsS = ghcjsRenderJsS
                                }

-- attempt to resugar some of the common constructs
ghcjsRenderJsS :: RenderJs -> JStat -> Doc
ghcjsRenderJsS r (BlockStat xs) = prettyBlock r (flattenBlocks xs)
ghcjsRenderJsS r s              = renderJsS defaultRenderJs r s

-- don't quote keys in our object literals, so closure compiler works
ghcjsRenderJsV :: RenderJs -> JVal -> Doc
ghcjsRenderJsV r (JHash m)
  | M.null m  = text "{}"
  | otherwise = braceNest . fillSep . punctuate comma .
                          map (\(x,y) -> quoteIfRequired x <> PP.colon <+> jsToDocR r y) $ M.toList m
  where
    quoteIfRequired x
      | isUnquotedKey x = text (TL.fromStrict x)
      | otherwise       = PP.squotes (text (TL.fromStrict x))

    isUnquotedKey x | T.null x        = False
                    | T.all isDigit x = True
                    | otherwise       = validFirstIdent (T.head x) && T.all validOtherIdent (T.tail x)

    -- fixme, this will quote some idents that don't really need to be quoted
    validFirstIdent c = c == '_' || c == '$' || isAlpha c
    validOtherIdent c = isAlpha c || isDigit c
ghcjsRenderJsV r v = renderJsV defaultRenderJs r v

prettyBlock :: RenderJs -> [JStat] -> Doc
prettyBlock r xs = vcat $ map addSemi (prettyBlock' r xs)

-- recognize common patterns in a block and convert them to more idiomatic/concise javascript
prettyBlock' :: RenderJs -> [JStat] -> [Doc]
-- resugar for loops with/without var declaration
prettyBlock' r ( (DeclStat i)
              : (AssignStat (ValExpr (JVar i')) v0)
              : (WhileStat False p (BlockStat bs))
              : xs
              )
     | i == i' && not (null flat) && isForUpdStat (last flat)
     = mkFor r True i v0 p (last flat) (init flat) : prettyBlock' r xs
        where
          flat = flattenBlocks bs
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) v0)
               : (WhileStat False p (BlockStat bs))
               : xs
               )
     | not (null flat) && isForUpdStat (last flat)
     = mkFor r False i v0 p (last flat) (init flat) : prettyBlock' r xs
        where
          flat = flattenBlocks bs

-- global function (does not preserve semantics but works for GHCJS)
prettyBlock' r ( (DeclStat i)
               : (AssignStat (ValExpr (JVar i')) (ValExpr (JFunc is b)))
               : xs
               )
      | i == i' = (text "function" <+> jsToDocR r i
                   <> parens (fillSep . punctuate comma . map (jsToDocR r) $ is)
                   $$ braceNest' (jsToDocR r b)
                  ) : prettyBlock' r xs
-- declare/assign
prettyBlock' r ( (DeclStat i)
               : (AssignStat (ValExpr (JVar i')) v)
               : xs
               )
      | i == i' = (text "var" <+> jsToDocR r i <+> char '=' <+> jsToDocR r v) : prettyBlock' r xs

-- modify/assign operators (fixme this should be more general, but beware of side effects like PPostExpr)
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr AddOp (ValExpr (JVar i')) (ValExpr (JInt 1))))
               : xs
               )
      | i == i' = ("++" <> jsToDocR r i) : prettyBlock' r xs
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr SubOp (ValExpr (JVar i')) (ValExpr (JInt 1))))
               : xs
               )
      | i == i' = ("--" <> jsToDocR r i) : prettyBlock' r xs
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr AddOp (ValExpr (JVar i')) e))
               : xs
               )
      | i == i' = (jsToDocR r i <+> text "+=" <+> jsToDocR r e) : prettyBlock' r xs
prettyBlock' r ( (AssignStat (ValExpr (JVar i)) (InfixExpr SubOp (ValExpr (JVar i')) e))
               : xs
               )
      | i == i' = (jsToDocR r i <+> text "-=" <+> jsToDocR r e) : prettyBlock' r xs

prettyBlock' r (x:xs) = jsToDocR r x : prettyBlock' r xs
prettyBlock' _ [] = []

-- build the for block
mkFor :: RenderJs -> Bool -> Ident -> JExpr -> JExpr -> JStat -> [JStat] -> Doc
mkFor r decl i v0 p s1 sb = text "for" <> forCond <+> braceNest'' (jsToDocR r $ BlockStat sb)
    where
      c0 | decl      = text "var" <+> jsToDocR r i <+> char '=' <+> jsToDocR r v0
         | otherwise =                jsToDocR r i <+> char '=' <+> jsToDocR r v0
      forCond = parens $ hcat $ interSemi
                            [ c0
                            , jsToDocR r p
                            , parens (jsToDocR r s1)
                            ]

-- check if a statement is suitable to be converted to something in the for(;;x) position
isForUpdStat :: JStat -> Bool
isForUpdStat UOpStat {}    = True
isForUpdStat AssignStat {} = True
isForUpdStat ApplStat {}   = True
isForUpdStat _             = False

interSemi :: [Doc] -> [Doc]
interSemi [] = [PP.empty]
interSemi [s] = [s]
interSemi (x:xs) = x <> text ";" : interSemi xs

addSemi :: Doc -> Doc
addSemi x = x <> text ";"

-- stuff below is from jmacro
infixl 5 $$, $+$
($+$), ($$), ($$$) :: Doc -> Doc -> Doc
x $+$ y = x PP.<$> y
x $$ y  = align (x $+$ y)
x $$$ y = align (nest 2 $ x $+$ y)

flattenBlocks :: [JStat] -> [JStat]
flattenBlocks (BlockStat y:ys) = flattenBlocks y ++ flattenBlocks ys
flattenBlocks (y:ys) = y : flattenBlocks ys
flattenBlocks [] = []

braceNest :: Doc -> Doc
braceNest x = char '{' <+> nest 2 x $$ char '}'

braceNest' :: Doc -> Doc
braceNest' x = nest 2 (char '{' $+$ x) $$ char '}'

-- somewhat more compact (egyptian style) braces
braceNest'' :: Doc -> Doc
braceNest'' x = nest 2 (char '{' PP.<$> x) PP.<$> char '}'


text:
TEST_GROUP (ConfigTest) {
    char config_buffer[1024];
    bootloader_config_t config, result;

    void setup(void)
    {
        memset(config_buffer, 0, sizeof(config_buffer));
        memset(&config, 0, sizeof(bootloader_config_t));
        memset(&result, 0, sizeof(bootloader_config_t));
    }

    void config_read_and_write()
    {
        config_write(config_buffer, &config, sizeof config_buffer);
        result = config_read(config_buffer, sizeof config_buffer);
    }
};

TEST(ConfigTest, WritesValidConfigCRC)
{
    config.ID = 0x42;

    config_write(config_buffer, &config, sizeof config_buffer);

    CHECK_TRUE(config_is_valid(config_buffer, sizeof(config_buffer)));
}

TEST(ConfigTest, DetectsCorruptedConfig)
{
    config.ID = 0x42;

    config_write(config_buffer, &config, sizeof config_buffer);

    config_buffer[42] ^= 0x2A;

    CHECK_FALSE(config_is_valid(config_buffer, sizeof(config_buffer)));
}

TEST(ConfigTest, CanSerializeNodeID)
{
    config.ID = 0x12;

    config_read_and_write();

    CHECK_EQUAL(config.ID, result.ID);
}

TEST(ConfigTest, CanSerializeNodeName)
{
    strncpy(config.board_name, "test.dummy", 64);

    config_read_and_write();

    STRCMP_EQUAL(config.board_name, result.board_name);
}

TEST(ConfigTest, CanSerializeNodeDeviceClass)
{
    strncpy(config.device_class, "CVRA.dummy.v1", 64);

    config_read_and_write();

    STRCMP_EQUAL(config.device_class, result.device_class);
}

TEST(ConfigTest, CanSerializeApplicationCRC)
{
    config.application_crc = 0xdeadbeef;

    config_read_and_write();

    CHECK_EQUAL(0xdeadbeef, result.application_crc);
}

TEST(ConfigTest, CanSerializeApplicationSize)
{
    config.application_size = 42;

    config_read_and_write();

    CHECK_EQUAL(42, result.application_size);
}

TEST(ConfigTest, CanSerializeUpdateCount)
{
    config.update_count = 23;

    config_read_and_write();

    CHECK_EQUAL(23, result.update_count);
}


text:
namespace EPiBootstrapArea
{
    public interface IControlVisibility
    {
        bool HideIfEmpty { get; }
    }
}


text:
extern crate meltdown;
extern crate url;

use url::Url;
use std::env;
use std::thread;
use std::path::Path;
use std::sync::mpsc::channel;
use std::time::Instant;

use meltdown::*;
mod config;

fn main() {
    let _ = config::setup_config_directories();
    let configurations = config::read_config();
    let url_string = env::args().skip(1).collect::<Vec<String>>();
    let submitted_tasks = url_string.len();
    print!("{:?}", url_string);
    if url_string.len() == 0 {
        println!("Welcome to meltdown download manager!");
        println!("Gimme a Url to download");
        return;
    }
    let (main_tx, main_rx) = channel();
    for i in url_string {
        let prefix = config::default_cache_dir().unwrap();
        let mut manager = DownloadManager::new();
        let download_url = Url::parse(&i).unwrap();
        let url_path_vec = download_url.path_segments().unwrap().collect::<Vec<&str>>();
        let file_name = url_path_vec[url_path_vec.len() - 1].to_owned();
        manager.add_url(download_url.clone())
               .max_connection(configurations.max_connection)
               .file(&file_name.clone())
               .finish();
        let complete_name = file_name.clone();
        let (tx, rx) = channel();
        let main_tx_clone = main_tx.clone();
        let _ = thread::spawn(move || {
            match manager.start(rx) {
                State::Completed(bytes) => {
                    let ext = Path::new(&complete_name);
                    let ext_str = ext.extension().unwrap().to_str();
                    join_part_files(&complete_name, prefix.to_str().unwrap(), ext_str.unwrap());
                    main_tx_clone.send(State::Completed(bytes));
                }
                _ => {}
            }
        });
    }
    let mut complete_tasks = 0;
    loop {
        match main_rx.try_recv() {
            Ok(state) => {
                match state {
                    State::Completed(bytes) => {
                        println!("Download Complete of {:?}", bytes);
                    }
                    _ => {}
                }
                complete_tasks += 1;
            }
            Err(_) => {}
        }
        if complete_tasks == submitted_tasks {
            println!("All tasks complete");
            return;
        }
    }
}


text:
import cx from 'classnames'
import * as dateFns from 'date-fns'
import * as R from 'ramda'
import * as React from 'react'
import { Link as RRLink } from 'react-router-dom'
import * as redux from 'react-redux'
import * as urql from 'urql'
import * as M from '@material-ui/core'
import { fade } from '@material-ui/core/styles'
import useComponentSize from '@rehooks/component-size'

import * as Pagination from 'components/Pagination'
import Skeleton from 'components/Skeleton'
import StackedAreaChart from 'components/StackedAreaChart'
import Thumbnail from 'components/Thumbnail'
import * as authSelectors from 'containers/Auth/selectors'
import * as APIConnector from 'utils/APIConnector'
import * as AWS from 'utils/AWS'
import AsyncResult from 'utils/AsyncResult'
import * as Config from 'utils/Config'
import Data, { useData } from 'utils/Data'
import * as LinkedData from 'utils/LinkedData'
import * as NamedRoutes from 'utils/NamedRoutes'
import * as SVG from 'utils/SVG'
import Link from 'utils/StyledLink'
import { readableBytes, readableQuantity, formatQuantity } from 'utils/string'

import * as Summarize from './Summarize'
import * as requests from './requests'
import BUCKET_CONFIG_QUERY from './OverviewBucketConfig.generated'

import bg from './Overview-bg.jpg'

const RODA_LINK = 'https://registry.opendata.aws'
const RODA_BUCKET = 'quilt-open-data-bucket'
const MAX_EXTS = 7
// must have length >= MAX_EXTS
const COLOR_MAP = [
  '#8ad3cb',
  '#d7ce69',
  '#bfbadb',
  '#f4806c',
  '#83b0d1',
  '#b2de67',
  '#bc81be',
  '#f0b5d3',
  '#7ba39f',
  '#9894ad',
  '#be7265',
  '#94ad6b',
]

function mkKeyedPool(pool) {
  const map = {}
  let poolIdx = 0
  const get = (key) => {
    if (!(key in map)) {
      // eslint-disable-next-line no-plusplus
      map[key] = pool[poolIdx++ % pool.length]
    }
    return map[key]
  }
  return { get }
}

function useConst(cons) {
  const ref = React.useRef(null)
  if (!ref.current) ref.current = { value: cons() }
  return ref.current.value
}

const useObjectsByExtStyles = M.makeStyles((t) => ({
  root: {
    display: 'grid',
    gridAutoRows: 20,
    gridColumnGap: t.spacing(1),
    gridRowGap: t.spacing(0.25),
    gridTemplateAreas: `
      ". heading heading"
    `,
    gridTemplateColumns: 'minmax(30px, max-content) 1fr minmax(30px, max-content)',
    gridTemplateRows: 'auto',
    [t.breakpoints.down('sm')]: {
      gridTemplateAreas: `
        "heading heading heading"
      `,
    },
  },
  heading: {
    ...t.typography.h6,
    gridArea: 'heading',
    marginBottom: t.spacing(1),
    [t.breakpoints.down('sm')]: {
      textAlign: 'center',
    },
  },
  ext: {
    color: t.palette.text.secondary,
    gridColumn: 1,
    fontSize: t.typography.overline.fontSize,
    fontWeight: t.typography.fontWeightMedium,
    letterSpacing: t.typography.subtitle2.letterSpacing,
    lineHeight: t.typography.pxToRem(20),
    textAlign: 'right',
  },
  count: {
    color: t.palette.text.secondary,
    gridColumn: 3,
    fontSize: t.typography.overline.fontSize,
    fontWeight: t.typography.fontWeightMedium,
    letterSpacing: t.typography.subtitle2.letterSpacing,
    lineHeight: t.typography.pxToRem(20),
  },
  bar: {
    background: t.palette.action.hover,
    gridColumn: 2,
  },
  gauge: {
    height: '100%',
    position: 'relative',
  },
  flip: {},
  size: {
    color: t.palette.common.white,
    fontSize: t.typography.overline.fontSize,
    fontWeight: t.typography.fontWeightMedium,
    letterSpacing: t.typography.subtitle2.letterSpacing,
    lineHeight: t.typography.pxToRem(20),
    position: 'absolute',
    right: t.spacing(1),
    '&$flip': {
      color: t.palette.text.hint,
      left: `calc(100% + ${t.spacing(1)}px)`,
      right: 'auto',
    },
  },
  skeleton: {
    gridColumn: '1 / span 3',
  },
  unavail: {
    ...t.typography.body2,
    alignItems: 'center',
    display: 'flex',
    gridColumn: '1 / span 3',
    gridRow: `2 / span ${MAX_EXTS}`,
    justifyContent: 'center',
  },
}))

function ObjectsByExt({ data, colorPool, ...props }) {
  const classes = useObjectsByExtStyles()
  return (
    <M.Box className={classes.root} {...props}>

Objects by File Extension

      {AsyncResult.case(
        {
          Ok: (exts) => {
            const capped = exts.slice(0, MAX_EXTS)
            const maxBytes = capped.reduce((max, e) => Math.max(max, e.bytes), 0)
            const max = Math.log(maxBytes + 1)
            const scale = (x) => Math.log(x + 1) / max
            return capped.map(({ ext, bytes, objects }, i) => {
              const color = colorPool.get(ext)
              return (
                <React.Fragment key={`ext:${ext}`}>

                    {ext || 'other'}

                    <div
                      className={classes.gauge}
                      style={{
                        background: color,
                        width: `${scale(bytes) * 100}%`,
                      }}
                    >
                      <div
                        className={cx(classes.size, {
                          [classes.flip]: scale(bytes) < 0.3,
                        })}
                      >
                        {readableBytes(bytes)}

                    {readableQuantity(objects)}

                </React.Fragment>
              )
            })
          },
          _: (r) => (
            <>
              {R.times(
                (i) => (
                  <Skeleton
                    key={`skeleton:${i}`}
                    className={classes.skeleton}
                    style={{ gridRow: i + 2 }}
                    animate={!AsyncResult.Err.is(r)}
                  />
                ),
                MAX_EXTS,
              )}
              {AsyncResult.Err.is(r) && (

Data unavailable

              )}
            </>
          ),
        },
        data,
      )}
    </M.Box>
  )
}

const skelData = R.times(
  R.pipe(
    () => R.times(Math.random, 30),
    R.scan(R.add, 0),
    R.drop(1),
    R.map((v) => Math.log(100 * v + 1)),
  ),
  8,
)

const skelColors = [
  [M.colors.grey[300], M.colors.grey[100]],
  [M.colors.grey[400], M.colors.grey[200]],
]

const mkPulsingGradient = ({ colors: [c1, c2], animate = false }) =>
  SVG.Paint.Server(
    <linearGradient>
      <stop offset="0%" stopColor={c2}>
        {animate && (
          <animate
            attributeName="stop-color"
            values={`${c1}; ${c2}; ${c1}`}
            dur="3s"
            repeatCount="indefinite"
          />
        )}
      </stop>
    </linearGradient>,
  )

function ChartSkel({
  height,
  width,
  lines = skelData.length,
  animate = false,
  children,
}) {
  const data = React.useMemo(
    () => R.times((i) => skelData[i % skelData.length], lines),
    [lines],
  )
  const fills = React.useMemo(
    () =>
      R.times(
        (i) => mkPulsingGradient({ colors: skelColors[i % skelColors.length], animate }),
        lines,
      ),
    [lines, animate],
  )
  return (
    <M.Box position="relative">
      <StackedAreaChart
        data={data}
        width={width}
        height={height}
        extendL
        extendR
        px={10}
        areaFills={fills}
        lineStroke={SVG.Paint.Color(M.colors.grey[500])}
      />
      {children}
    </M.Box>
  )
}

const ANALYTICS_WINDOW_OPTIONS = [
  { value: 31, label: 'Last 1 month' },
  { value: 91, label: 'Last 3 months' },
  { value: 182, label: 'Last 6 months' },
  { value: 365, label: 'Last 12 months' },
]

function DownloadsRange({ value, onChange, bucket, rawData }) {
  const [anchor, setAnchor] = React.useState(null)

  const open = React.useCallback(
    (e) => {
      setAnchor(e.target)
    },
    [setAnchor],
  )

  const close = React.useCallback(() => {
    setAnchor(null)
  }, [setAnchor])

  const choose = React.useCallback(
    (e) => {
      onChange(e.target.value)
      close()
    },
    [onChange, close],
  )

  const { label } = ANALYTICS_WINDOW_OPTIONS.find((o) => o.value === value) || {}

  return (
    <>
      <M.Button variant="outlined" size="small" onClick={open}>
        <M.Box component="span" width={5} />
        {label} <M.Icon>expand_more</M.Icon>
      </M.Button>
      <M.Menu anchorEl={anchor} open={!!anchor} onClose={close}>
        {ANALYTICS_WINDOW_OPTIONS.map((o) => (
          <M.MenuItem
            key={o.value}
            selected={o.value === value}
            value={o.value}
            onClick={choose}
          >
            {o.label}
          </M.MenuItem>
        ))}
        <M.Divider />
        <M.MenuItem
          onClick={close}
          component="a"
          href={rawData}
          download={`${bucket}.downloads.json`}
          disabled={!rawData}
        >
          Download to file
        </M.MenuItem>
      </M.Menu>
    </>
  )
}

const useStatsTipStyles = M.makeStyles((t) => ({
  root: {
    background: fade(t.palette.grey[700], 0.9),
    color: t.palette.common.white,
    padding: [[6, 8]],
  },
  head: {
    display: 'flex',
    justifyContent: 'space-between',
    marginBottom: 4,
  },
  date: {},
  total: {},
  extsContainer: {
    alignItems: 'center',
    display: 'grid',
    gridAutoRows: 'auto',
    gridColumnGap: 4,
    gridTemplateColumns: 'max-content max-content 1fr',
  },
  ext: {
    fontSize: 12,
    lineHeight: '16px',
    maxWidth: 70,
    opacity: 0.6,
    overflow: 'hidden',
    textAlign: 'right',
    textOverflow: 'ellipsis',
  },
  color: {
    borderRadius: '50%',
    height: 8,
    opacity: 0.6,
    width: 8,
  },
  number: {
    fontSize: 12,
    lineHeight: '16px',
    opacity: 0.6,
  },
  hl: {
    opacity: 1,
  },
}))

function StatsTip({ stats, colorPool, className, ...props }) {
  const classes = useStatsTipStyles()
  return (
    <M.Paper className={cx(classes.root, className)} elevation={8} {...props}>

{dateFns.format(stats.date, 'd MMM')}

          {readableQuantity(stats.combined.sum)} (+
          {readableQuantity(stats.combined.value)})

        {stats.byExt.map((s) => {
          const hl = stats.highlighted ? stats.highlighted.ext === s.ext : true
          return (
            <React.Fragment key={s.ext}>

{s.ext || 'other'}

                {readableQuantity(s.sum)} (+
                {readableQuantity(s.value)})

            </React.Fragment>
          )
        })}

    </M.Paper>
  )
}

const Transition = ({ TransitionComponent = M.Grow, children, ...props }) => {
  const contentsRef = React.useRef(null)
  if (props.in) contentsRef.current = children()
  return (
    contentsRef.current && (
      <TransitionComponent {...props}>{contentsRef.current}</TransitionComponent>
    )
  )
}

// use the same height as the bar chart: 20px per bar with 2px margin
const CHART_H = 22 * MAX_EXTS - 2

const useDownloadsStyles = M.makeStyles((t) => ({
  root: {
    display: 'grid',
    gridRowGap: t.spacing(0.25),
    gridTemplateAreas: `
      "heading period"
      "chart chart"
    `,
    gridTemplateColumns: 'min-content 1fr',
    gridTemplateRows: 'auto auto',
    [t.breakpoints.down('sm')]: {
      gridTemplateAreas: `
        "heading"
        "chart"
        "period"
      `,
      gridTemplateColumns: '1fr',
      gridTemplateRows: 'auto auto auto',
    },
  },
  heading: {
    ...t.typography.h6,
    gridArea: 'heading',
    marginBottom: t.spacing(1),
    whiteSpace: 'nowrap',
    [t.breakpoints.down('sm')]: {
      marginBottom: 0,
      textAlign: 'center',
    },
  },
  ext: {
    display: 'inline-block',
    maxWidth: 100,
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    verticalAlign: 'bottom',
  },
  period: {
    display: 'flex',
    gridArea: 'period',
    justifyContent: 'center',
    alignItems: 'center',
    [t.breakpoints.down('sm')]: {
      paddingBottom: t.spacing(1),
      paddingTop: t.spacing(2),
    },
    [t.breakpoints.up('md')]: {
      height: 37,
      justifyContent: 'flex-end',
    },
  },
  chart: {
    gridArea: 'chart',
    position: 'relative',
  },
  left: {},
  right: {},
  dateStats: {
    maxWidth: 180,
    position: 'absolute',
    top: 0,
    width: 'calc(50% - 8px)',
    zIndex: 1,
    '&$left': {
      left: 0,
    },
    '&$right': {
      right: 0,
    },
  },
  unavail: {
    ...t.typography.body2,
    alignItems: 'center',
    display: 'flex',
    height: '100%',
    justifyContent: 'center',
    position: 'absolute',
    top: 0,
    width: '100%',
  },
}))

function Downloads({ bucket, colorPool, ...props }) {
  const { analyticsBucket } = Config.useConfig()
  const s3 = AWS.S3.use()
  const today = React.useMemo(() => new Date(), [])
  const classes = useDownloadsStyles()
  const ref = React.useRef(null)
  const { width } = useComponentSize(ref)
  const [window, setWindow] = React.useState(ANALYTICS_WINDOW_OPTIONS[0].value)
  const [cursor, setCursor] = React.useState(null)
  const cursorStats = (counts) => {
    if (!cursor) return null
    const { date, ...combined } = counts.combined.counts[cursor.j]
    const byExt = counts.byExtCollapsed.map((e) => ({
      ext: e.ext,
      ...e.counts[cursor.j],
    }))
    const highlighted = cursor.i == null ? null : counts.byExtCollapsed[cursor.i]
    const firstHalf = cursor.j < counts.combined.counts.length / 2
    return { date, combined, byExt, highlighted, firstHalf }
  }

  const mkRawData = AsyncResult.case({
    Ok: (data) => `data:application/json,${JSON.stringify(data)}`,
    _: () => null,
  })

  if (!analyticsBucket) {
    return (
      <ChartSkel height={CHART_H} width={width}>

Requires CloudTrail

      </ChartSkel>
    )
  }

  return (
    <Data
      fetch={requests.bucketAccessCounts}
      params={{ s3, analyticsBucket, bucket, today, window }}
    >
      {(data) => (
        <M.Box className={classes.root} {...props} ref={ref}>

            <DownloadsRange
              value={window}
              onChange={setWindow}
              bucket={bucket}
              rawData={mkRawData(data)}
            />

            {AsyncResult.case(
              {
                Ok: (counts) => {
                  const stats = cursorStats(counts)
                  const hl = stats && stats.highlighted
                  const ext = hl ? hl.ext || 'other' : 'total'
                  const total = hl ? hl.total : counts.combined.total
                  if (!counts.byExtCollapsed.length) return 'Downloads'
                  return (
                    <>
                      Downloads ({ext}):{' '}
                      {readableQuantity(total)}
                    </>
                  )
                },
                _: () => 'Downloads',
              },
              data,
            )}

            {AsyncResult.case(
              {
                Ok: (counts) => {
                  if (!counts.byExtCollapsed.length) {
                    return (
                      <ChartSkel height={CHART_H} width={width}>

No Data

                      </ChartSkel>
                    )
                  }

                  const stats = cursorStats(counts)
                  return (
                    <>
                      <StackedAreaChart
                        data={counts.byExtCollapsed.map((e) =>
                          e.counts.map((i) => Math.log(i.sum + 1)),
                        )}
                        onCursor={setCursor}
                        height={CHART_H}
                        width={width}
                        areaFills={counts.byExtCollapsed.map((e) =>
                          SVG.Paint.Color(colorPool.get(e.ext)),
                        )}
                        lineStroke={SVG.Paint.Color(M.colors.grey[500])}
                        extendL
                        extendR
                        px={10}
                      />
                      <Transition in={!!stats && stats.firstHalf}>
                        {() => (
                          <StatsTip
                            stats={stats}
                            colorPool={colorPool}
                            className={cx(classes.dateStats, classes.right)}
                          />
                        )}
                      </Transition>
                      <Transition in={!!stats && !stats.firstHalf}>
                        {() => (
                          <StatsTip
                            stats={stats}
                            colorPool={colorPool}
                            className={cx(classes.dateStats, classes.left)}
                          />
                        )}
                      </Transition>
                    </>
                  )
                },
                _: () => <ChartSkel height={22 * MAX_EXTS - 2} width={width} animate />,
              },
              data,
            )}

        </M.Box>
      )}
    </Data>
  )
}

const useStatDisplayStyles = M.makeStyles((t) => ({
  root: {
    alignItems: 'baseline',
    display: 'flex',
    '& + &': {
      marginLeft: t.spacing(1.5),
      [t.breakpoints.up('sm')]: {
        marginLeft: t.spacing(4),
      },
      [t.breakpoints.up('md')]: {
        marginLeft: t.spacing(6),
      },
    },
  },
  value: {
    fontSize: t.typography.h6.fontSize,
    fontWeight: t.typography.fontWeightBold,
    letterSpacing: 0,
    lineHeight: '20px',
    [t.breakpoints.up('sm')]: {
      fontSize: t.typography.h4.fontSize,
      lineHeight: '32px',
    },
  },
  label: {
    ...t.typography.body2,
    color: t.palette.grey[300],
    lineHeight: 1,
    marginLeft: t.spacing(0.5),
    [t.breakpoints.up('sm')]: {
      marginLeft: t.spacing(1),
    },
  },
  skeletonContainer: {
    alignItems: 'center',
    height: 20,
    [t.breakpoints.up('sm')]: {
      height: 32,
    },
  },
  skeleton: {
    borderRadius: t.shape.borderRadius,
    height: t.typography.h6.fontSize,
    width: 96,
    [t.breakpoints.up('sm')]: {
      height: t.typography.h4.fontSize,
      width: 120,
    },
  },
}))

function StatDisplay({ value, label, format, fallback }) {
  const classes = useStatDisplayStyles()
  return R.pipe(
    AsyncResult.case({
      Ok: R.pipe(format || R.identity, AsyncResult.Ok),
      Err: R.pipe(fallback || R.identity, AsyncResult.Ok),
      _: R.identity,
    }),
    AsyncResult.case({
      Ok: (v) =>
        v != null && (

            {v}
            {!!label && {label}}

        ),
      _: () => (

          <Skeleton className={classes.skeleton} bgcolor="grey.400" />

      ),
    }),
  )(value)
}

const useHeadStyles = M.makeStyles((t) => ({
  root: {
    position: 'relative',
    [t.breakpoints.down('xs')]: {
      borderRadius: 0,
    },
    [t.breakpoints.up('sm')]: {
      marginTop: t.spacing(2),
    },
  },
  top: {
    background: `center / cover url(${bg}) ${t.palette.grey[700]}`,
    borderTopLeftRadius: t.shape.borderRadius,
    borderTopRightRadius: t.shape.borderRadius,
    color: t.palette.common.white,
    overflow: 'hidden',
    paddingBottom: t.spacing(3),
    paddingLeft: t.spacing(2),
    paddingRight: t.spacing(2),
    paddingTop: t.spacing(4),
    position: 'relative',
    [t.breakpoints.up('sm')]: {
      padding: t.spacing(4),
    },
    [t.breakpoints.down('xs')]: {
      borderRadius: 0,
    },
  },
  settings: {
    color: t.palette.common.white,
    position: 'absolute',
    right: t.spacing(2),
    top: t.spacing(2),
  },
}))

function Head({ s3, overviewUrl, bucket, description }) {
  const classes = useHeadStyles()
  const req = APIConnector.use()
  const isRODA = !!overviewUrl && overviewUrl.includes(`/${RODA_BUCKET}/`)
  const colorPool = useConst(() => mkKeyedPool(COLOR_MAP))
  const statsData = useData(requests.bucketStats, { req, s3, bucket, overviewUrl })
  const pkgCountData = useData(requests.countPackageRevisions, { req, bucket })
  const { urls } = NamedRoutes.use()
  const isAdmin = redux.useSelector(authSelectors.isAdmin)
  return (
    <M.Paper className={classes.root}>
      <M.Box className={classes.top}>
        <M.Typography variant="h5">{bucket}</M.Typography>
        {!!description && (
          <M.Box mt={1}>
            <M.Typography variant="body1">{description}</M.Typography>
          </M.Box>
        )}
        {isRODA && (
          <M.Box
            mt={1}
            position={{ md: 'absolute' }}
            right={{ md: 32 }}
            bottom={{ md: 31 }}
            color="grey.300"
            textAlign={{ md: 'right' }}
          >
            <M.Typography variant="body2">
              From the{' '}
              <M.Link href={RODA_LINK} color="inherit" underline="always">
                Registry of Open Data on AWS
              </M.Link>
            </M.Typography>
          </M.Box>
        )}
        <M.Box mt={{ xs: 2, sm: 3 }} display="flex" alignItems="baseline">
          <StatDisplay
            value={AsyncResult.prop('totalBytes', statsData.result)}
            format={readableBytes}
            fallback={() => '? B'}
          />
          <StatDisplay
            value={AsyncResult.prop('totalObjects', statsData.result)}
            format={readableQuantity}
            label="Objects"
            fallback={() => '?'}
          />
          <StatDisplay
            value={pkgCountData.result}
            format={formatQuantity}
            label="Packages"
            fallback={() => null}
          />
        </M.Box>
        {isAdmin && (
          <RRLink className={classes.settings} to={urls.adminBuckets(bucket)}>
            <M.IconButton color="inherit">
              <M.Icon>settings</M.Icon>
            </M.IconButton>
          </RRLink>
        )}
      </M.Box>
      <M.Box
        p={{ xs: 2, sm: 4 }}
        display="flex"
        flexDirection={{ xs: 'column', md: 'row' }}
        alignItems={{ md: 'flex-start' }}
        position="relative"
      >
        <ObjectsByExt
          data={AsyncResult.prop('exts', statsData.result)}
          width="100%"
          flexShrink={1}
          colorPool={colorPool}
        />
        <M.Box
          display="flex"
          flexDirection="column"
          justifyContent="center"
          flexShrink={0}
          height={{ xs: 32, md: '100%' }}
          width={{ xs: '100%', md: 32 }}
        >
          <M.Hidden mdUp>
            <M.Divider />
          </M.Hidden>
        </M.Box>
        <Downloads bucket={bucket} colorPool={colorPool} width="100%" flexShrink={1} />
      </M.Box>
    </M.Paper>
  )
}

const ImageGrid = M.styled(M.Box)(({ theme: t }) => ({
  display: 'grid',
  gridAutoRows: 'max-content',
  gridColumnGap: t.spacing(2),
  gridRowGap: t.spacing(2),
  gridTemplateColumns: '1fr',
  [t.breakpoints.up('sm')]: {
    gridTemplateColumns: '1fr 1fr 1fr',
  },
  [t.breakpoints.up('md')]: {
    gridTemplateColumns: '1fr 1fr 1fr 1fr',
  },
  [t.breakpoints.up('lg')]: {
    gridTemplateColumns: '1fr 1fr 1fr 1fr 1fr',
  },
}))

const useThumbnailsStyles = M.makeStyles({
  link: {
    overflow: 'hidden',
  },
  img: {
    display: 'block',
    marginLeft: 'auto',
    marginRight: 'auto',
    maxWidth: '100%',
  },
})

function Thumbnails({ images }) {
  const classes = useThumbnailsStyles()
  const { urls } = NamedRoutes.use()

  const scrollRef = React.useRef(null)
  const scroll = React.useCallback(
    (prev) => {
      if (prev && scrollRef.current) scrollRef.current.scrollIntoView()
    },
    [scrollRef],
  )

  const pagination = Pagination.use(images, { perPage: 25, onChange: scroll })

  return (
    <Summarize.Section
      heading={
        <>
          Images ({pagination.from}–{Math.min(pagination.to, images.length)} of{' '}
          {images.length})
        </>
      }
    >

      <ImageGrid>
        {pagination.paginated.map((i) => (
          <Link
            key={i.key}
            to={urls.bucketFile(i.bucket, i.key, i.version)}
            className={classes.link}
          >
            <Thumbnail handle={i} className={classes.img} alt={i.key} title={i.key} />
          </Link>
        ))}
      </ImageGrid>
      {pagination.pages > 1 && (
        <M.Box display="flex" justifyContent="flex-end" pt={2}>
          <Pagination.Controls {...pagination} />
        </M.Box>
      )}
    </Summarize.Section>
  )
}

function Readmes({ s3, overviewUrl, bucket }) {
  return (
    <Data fetch={requests.bucketReadmes} params={{ s3, overviewUrl, bucket }}>
      {AsyncResult.case({
        Ok: (rs) =>
          (rs.discovered.length > 0 || !!rs.forced) && (
            <>
              {!!rs.forced && (
                <Summarize.FilePreview
                  key="readme:forced"
                  headingOverride={false}
                  handle={rs.forced}
                  expanded
                />
              )}
              {rs.discovered.map((h) => (
                <Summarize.FilePreview
                  key={`readme:${h.bucket}/${h.key}`}
                  handle={h}
                  expanded
                />
              ))}
            </>
          ),
        _: () => <Summarize.FilePreviewSkel key="readme:skeleton" />,
      })}
    </Data>
  )
}

function Imgs({ s3, overviewUrl, inStack, bucket }) {
  const req = APIConnector.use()
  return (
    <Data fetch={requests.bucketImgs} params={{ req, s3, overviewUrl, inStack, bucket }}>
      {AsyncResult.case({
        Ok: (images) => (images.length ? <Thumbnails images={images} /> : null),
        _: () => (
          <Summarize.Section key="thumbs:skel" heading={<Summarize.HeadingSkel />}>
            <ImageGrid>
              {R.times(
                (i) => (
                  // eslint-disable-next-line react/no-array-index-key
                  <Skeleton key={i} height={200} />
                ),
                9,
              )}
            </ImageGrid>
          </Summarize.Section>
        ),
      })}
    </Data>
  )
}

export default function Overview({
  match: {
    params: { bucket },
  },
}) {
  const s3 = AWS.S3.use()
  const { noOverviewImages } = Config.use()
  const [{ data }] = urql.useQuery({
    query: BUCKET_CONFIG_QUERY,
    variables: { bucket },
  })
  const cfg = data?.bucketConfig
  const inStack = !!cfg
  const overviewUrl = cfg?.overviewUrl
  const description = cfg?.description
  return (
    <M.Box pb={{ xs: 0, sm: 4 }} mx={{ xs: -2, sm: 0 }} position="relative" zIndex={1}>
      {inStack && (
        <React.Suspense fallback={null}>
          <LinkedData.BucketData bucket={bucket} />
        </React.Suspense>
      )}
      {cfg ? (

      ) : (
        <M.Box
          pt={2}
          pb={{ xs: 2, sm: 0 }}
          px={{ xs: 2, sm: 0 }}
          textAlign={{ xs: 'center', sm: 'left' }}
        >
          <M.Typography variant="h5">{bucket}</M.Typography>
        </M.Box>
      )}
      <Readmes {...{ s3, bucket, overviewUrl }} />
      {!noOverviewImages && <Imgs {...{ s3, bucket, inStack, overviewUrl }} />}
      <Summarize.SummaryRoot {...{ s3, bucket, inStack, overviewUrl }} />
    </M.Box>
  )
}


text:
#ifndef ACCESS_H
#define ACCESS_H

void access_setup(char *, char *);
int  access_host(struct sockaddr_in *);

#endif /* ACCESS_H */


text:
<?php

/**
 * Adminhtml tags detail for customer report blocks content block
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */

class Mage_Adminhtml_Block_Report_Tag_Customer_Detail extends Mage_Adminhtml_Block_Widget_Grid_Container
{

    public function __construct()
    {
        $this->_controller = 'report_tag_customer_detail';

        $customer = Mage::getModel('customer/customer')->load($this->getRequest()->getParam('id'));
        $customerName = $this->escapeHtml($customer->getName());
        $this->_headerText = Mage::helper('reports')->__('Tags Submitted by %s', $customerName);
        parent::__construct();
        $this->_removeButton('add');
        $this->setBackUrl($this->getUrl('*/report_tag/customer/'));
        $this->_addBackButton();
    }

}


text:
package com.java110.intf.job;

import com.java110.config.feign.FeignConfiguration;
import com.java110.dto.task.TaskDto;
import com.java110.dto.task.TaskTemplateDto;
import com.java110.dto.task.TaskTemplateSpecDto;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * @ClassName ITaskInnerServiceSMO
 * @Description 定时任务接口类
 * @Author wuxw
 * @Date 2019/4/24 9:04
 * @Version 1.0
 * add by wuxw 2019/4/24
 **/
@FeignClient(name = "${java110.job-service}", configuration = {FeignConfiguration.class})
@RequestMapping("/taskApi")
public interface ITaskInnerServiceSMO {

    /**
     *
查询小区楼信息

     *
     *
     * @param taskDto 数据对象分享
     * @return TaskDto 对象数据
     */
    @RequestMapping(value = "/queryTasks", method = RequestMethod.POST)
    List<TaskDto> queryTasks(@RequestBody TaskDto taskDto);

    /**
     * 查询
小区楼
总记录数
     *
     * @param taskDto 数据对象分享
     * @return 小区下的小区楼记录数
     */
    @RequestMapping(value = "/queryTasksCount", method = RequestMethod.POST)
    int queryTasksCount(@RequestBody TaskDto taskDto);

    /**
     *
查询任务模板楼信息

     *
     *
     * @param taskTemplateDto  模板对象
     * @return TaskDto 对象数据
     */
    @RequestMapping(value = "/queryTaskTemplate", method = RequestMethod.POST)
    List<TaskTemplateDto> queryTaskTemplate(@RequestBody TaskTemplateDto taskTemplateDto);

    /**
     * 查询
任务模板
总记录数
     *
     * @param taskTemplateDto 模板对象
     * @return 小区下的小区楼记录数
     */
    @RequestMapping(value = "/queryTaskTemplateCount", method = RequestMethod.POST)
    int queryTaskTemplateCount(@RequestBody TaskTemplateDto taskTemplateDto);

    /**
     * 查询
任务模板
总记录数
     *
     * @param taskTemplateSpecDto 模板对象
     * @return 小区下的小区楼记录数
     */
    @RequestMapping(value = "/queryTaskTemplateSpecCount", method = RequestMethod.POST)
     int queryTaskTemplateSpecCount(@RequestBody TaskTemplateSpecDto taskTemplateSpecDto);

    /**
     * 查询
任务模板
总记录数
     *
     * @param taskTemplateSpecDto 模板对象
     * @return 小区下的小区楼记录数
     */
    @RequestMapping(value = "/queryTaskTemplateSpec", method = RequestMethod.POST)
     List<TaskTemplateSpecDto> queryTaskTemplateSpec(@RequestBody TaskTemplateSpecDto taskTemplateSpecDto);

    /**
     * 启动任务
     * @param taskDto
     * @return
     */
    @RequestMapping(value = "/startTask", method = RequestMethod.POST)
    int startTask(@RequestBody TaskDto taskDto);

    /**
     * 停止任务
     * @param taskDto
     * @return
     */
    @RequestMapping(value = "/stopTask", method = RequestMethod.POST)
    int stopTask(@RequestBody TaskDto taskDto);
}


text:
<?php

namespace Google\Service\Dataproc;

class DiagnoseClusterResults extends \Google\Model
{
  /**
   * @var string
   */
  public $outputUri;

  /**
   * @param string
   */
  public function setOutputUri($outputUri)
  {
    $this->outputUri = $outputUri;
  }
  /**
   * @return string
   */
  public function getOutputUri()
  {
    return $this->outputUri;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(DiagnoseClusterResults::class, 'Google_Service_Dataproc_DiagnoseClusterResults');


text:
using System;
using System.Web;
using System.Web.Mvc;
using RegTesting.Contracts.Services;
using RegTesting.Mvc.Extensions;

namespace RegTesting.Mvc.Filters
{

	/// <summary>
	/// A Attribute for Authorize
	/// </summary>
	public class RegAuthorizeAttribute : AuthorizeAttribute, IIoCFilter
	{
		private readonly ITestViewerService _testViewerService;

		/// <summary>
		/// Default constructor for global.asax
		/// </summary>
		public RegAuthorizeAttribute()
		{
		}

		/// <summary>
		/// Constructor
		/// </summary>
		/// <param name="testViewerService">the test viewer</param>
		public RegAuthorizeAttribute(ITestViewerService testViewerService) :this()
		{
			if (testViewerService == null)
				throw new ArgumentNullException("testViewerService");
			_testViewerService = testViewerService;
		}

		/// <summary>
		/// Add the ID of the current tester while authorizing.
		/// </summary>
		/// <param name="httpContext">the current httpContext</param>
		/// <returns>boolean, if the authorize was successful</returns>
		protected override bool AuthorizeCore(HttpContextBase httpContext)
		{
			bool bolAuthorized = base.AuthorizeCore(httpContext);
			if (!bolAuthorized)
			{
				return false;
			}
			if (httpContext.Session != null)
			{
				if (httpContext.Session["tester"] == null)
				{

					httpContext.Session["tester"] = _testViewerService.GetTesterIDByName(httpContext.User.Identity.GetLogin());
				}
			}
			return true;
		}
	}
}


text:
/*
 * @author max
 */
package com.intellij.util.messages.impl;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.messages.MessageBusConnection;
import com.intellij.util.messages.MessageHandler;
import com.intellij.util.messages.Topic;

import java.util.HashMap;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

public class MessageBusConnectionImpl implements MessageBusConnection {
  private static final Logger LOG = Logger.getInstance("#com.intellij.util.messages.impl.MessageBusConnectionImpl");

  private final MessageBusImpl myBus;
  private final ThreadLocal<Queue<Message>> myPendingMessages = new ThreadLocal<Queue<Message>>() {
    @Override
    protected Queue<Message> initialValue() {
      return new ConcurrentLinkedQueue<Message>();
    }
  };
  private MessageHandler myDefaultHandler;
  private final Map<Topic, Object> mySubscriptions = new HashMap<Topic, Object>();

  public MessageBusConnectionImpl(MessageBusImpl bus) {
    myBus = bus;
  }

  public <L> void subscribe(Topic<L> topic, L handler) {
    if (mySubscriptions.put(topic, handler) != null) {
      throw new IllegalStateException("Subscription to " + topic + " already exists");
    }
    myBus.notifyOnSubscription(this, topic);
  }

  public <L> void subscribe(Topic<L> topic) {
    if (myDefaultHandler == null) {
      throw new IllegalStateException("Connection must have default handler installed prior to any anonymous subscriptions.");
    }

    subscribe(topic, (L)myDefaultHandler);
  }

  public void setDefaultHandler(MessageHandler handler) {
    myDefaultHandler = handler;
  }

  public void disconnect() {
    Queue<Message> jobs = myPendingMessages.get();
    if (!jobs.isEmpty()) {
      LOG.error("Not delivered events in the queue: "+jobs);
    }
    myPendingMessages.remove();
    myBus.notifyConnectionTerminated(this);
  }

  public void dispose() {
    disconnect();
  }

  public void deliverImmediately() {
    while (!myPendingMessages.get().isEmpty()) {
      myBus.deliverSingleMessage();
    }
  }

  void deliverMessage(Message message) {
    final Message messageOnLocalQueue = myPendingMessages.get().poll();
    assert messageOnLocalQueue == message;

    final Topic topic = message.getTopic();
    final Object handler = mySubscriptions.get(topic);

    try {
      if (handler == myDefaultHandler) {
        myDefaultHandler.handle(message.getListenerMethod(), message.getArgs());
      }
      else {
        message.getListenerMethod().invoke(handler, message.getArgs());
      }
    }
    catch (AbstractMethodError e) {
      //Do nothing. This listener just does not implement something newly added yet.
    }
    catch(Throwable e) {
      LOG.error(e.getCause());
    }
  }

  void scheduleMessageDelivery(Message message) {
    myPendingMessages.get().offer(message);
  }

  public String toString() {
    return mySubscriptions.keySet().toString();
  }
}


text:
export default class {
  constructor($element) {
    'ngInject';

    this.$element = $element;
  }

  $onInit() {
    this.size = this.size || 'm';
  }

  $postLink() {
    // Add Classnames on root element
    this.$element.addClass(`oui-spinner oui-spinner_${this.size}`);
  }
}


text:
"""
Function to scan the sub-directory structure in a given directory.
"""

from __future__ import unicode_literals
from __future__ import absolute_import, division, print_function

__author__      = "Graham Klyne (GK@ACM.ORG)"
__copyright__   = "Copyright 2011-2013, Graham Klyne, University of Oxford"
__license__     = "MIT (http://opensource.org/licenses/MIT)"

from os.path import join, isdir, normpath
import os
import logging

logger = logging.getLogger("ScanDirectories")
#logger.setLevel(logging.INFO)

# Scan the sub-directory structure in a given directory
#
# Exceptions are left to the calling program.
#
# srcdir    directory to search, maybe including sub-directories
# DirFunc   a function to be called for each selected directory name
#           as DirFunc( dir ).  (NOTE:  this can be an
#           object method with access to the instance data of
#           the object to which it belongs.)
# FileFunc a function to be called for each selected file name
#           as FileFunc( file ).  (NOTE:  this can be an
#           object method with access to the instance data of
#           the object to which it belongs.)
# recursive is True if directories are to be scanned recursively,
#           otherwise only the named directory is scanned.
#
def ScanDirectoriesEx(srcdir, DirFunc, FileFunc=None, recursive=True):
    """
    Scan all sub-directories in a given source directory.
    Exceptions are thrown back to the calling program.
    """
    if not srcdir.endswith(os.path.sep): srcdir += os.path.sep
    directoryList = os.listdir(srcdir)
    for directoryComponent in directoryList:
        path = srcdir+directoryComponent
        if isdir(path):
            DirFunc(path)
            if recursive:
                logger.debug("Adding Directory %s " % (path))
                ScanDirectoriesEx(path, DirFunc, FileFunc, recursive)
        elif FileFunc:
            FileFunc(path)
    return

# Scan the sub-directory structure in a given directory
#
# This is just like 'ScanDirectoriesEx' above, except that an error
# is reported if an I/O exception occurs.
#
# srcdir    directory to search, maybe including sub-directories
# DirFunc  a function to be called for each selected directory name
#           as DirFunc( dir ).  (NOTE:  this can be an
#           object method with access to the instance data of
#           the object to which it belongs.)
# recursive is True if directories are to be scanned recursively,
#           otherwise only the named directory is scanned.
#
def ScanDirectories(srcdir, DirFunc, listFiles=False, recursive=True):
    try:
        ScanDirectoriesEx(srcdir, DirFunc, listFiles, recursive)
    except (IOError, os.error) as why:
        logger.warning("Can't scan %s: %s" % (repr(srcdir), str(why)))
    return

# Collect directories/sub-directories found under the source directory
#
# srcdir    directory to search, maybe including sub-directories
# baseDir   a base directory that is removed from all results returned.
# listFiles is True if files are to be included in the listing returned
# recursive is True if directories are to be scanned recursively,
#           otherwise only the named directory is scanned.
# appendSep is True if path separator character is to be appended to directory names
#
# Returns a list of directory contents
#
def CollectDirectoryContents(srcDir, baseDir="",
        listDirs=True, listFiles=False, recursive=True, appendSep=False):
    """
    Return a list of directory contents found under the source directory.
    """
    logger.debug("CollectDirectories: %s, %s, %s"%(srcDir,baseDir,str(os.path.sep)))
    dirsuffix = ""
    if appendSep: dirsuffix = os.path.sep
    collection = []
    if (baseDir != "") and (not baseDir.endswith(os.path.sep)):
        baseDir = baseDir+os.path.sep
    def CollectDir(path):
        logger.debug("- CollectDir base: %s, path: %s"%(baseDir, path))
        if listDirs: collection.append(path.replace(baseDir,"",1)+dirsuffix)
    def CollectFile(path):
        logger.debug("- CollectFile base: %s, path: %s"%(baseDir, path))
        if listFiles: collection.append(path.replace(baseDir,"",1))
    ScanDirectoriesEx(srcDir, CollectDir, CollectFile, recursive)
    return collection

if __name__ == "__main__":
    directoryCollection = CollectDirectoryContents(".", baseDir=".",
        listFiles=True, listDirs=False, appendSep=True)
    print("\n".join(directoryCollection))

# End.


text:
package com.snowplowanalytics.snowplow.enrich
package common
package enrichments
package registry
package apirequest

// specs2
import org.specs2.Specification
import org.specs2.scalaz.ValidationMatchers
import org.specs2.mock.Mockito

class HttpApiSpec extends Specification with ValidationMatchers with Mockito { def is =
    "This is a specification to test the HTTP API of API Request Enrichment" ^
                                                                          p^
      "Fail to build request string without all keys"                   ! e1^
      "Build request string from template context"                      ! e2^
      "Failure on failed HTTP connection"                               ! e3^
                                                                        end
  def e1 = {
    val httpApi = HttpApi("GET", "http://api.acme.com/{{user}}/{{ time}}/", anyInt, Authentication(None))
    val templateContext = Map("user" -> "admin")
    val request = httpApi.buildUrl(templateContext)
    request must beNone
  }

  def e2 = {
    val httpApi = HttpApi(anyString,
      "http://thishostdoesntexist31337:8123/{{  user }}/foo/{{ time}}/{{user}}",
      anyInt,
      Authentication(None))

    val templateContext = Map("user" -> "admin", "time" -> "November 2015")
    val request = httpApi.buildUrl(templateContext)
    request must beSome("http://thishostdoesntexist31337:8123/admin/foo/November+2015/admin")
  }

  // This one uses real actor system
  def e3 = {
    val enrichment = ApiRequestEnrichment(
      Nil,
      HttpApi("GET", "http://thishostdoesntexist31337:8123/endpoint",1000, Authentication(None)),
      List(Output("", Some(JsonOutput("")))),
      Cache(1,1))

    val event = new outputs.EnrichedEvent
    val request = enrichment.lookup(event, Nil, Nil, Nil)
    request must beFailing
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/instahood.iml" filepath="$PROJECT_DIR$/.idea/instahood.iml" />
    </modules>
  </component>
</project>


text:
import React from "react";
import renderer from "react-test-renderer";

import { StaticQuery, useStaticQuery } from "gatsby";

import * as mocks from "@/mocks";

import PostTemplate from "./PostTemplate";

const mockedStaticQuery = StaticQuery as jest.Mock;
const mockedUseStaticQuery = useStaticQuery as jest.Mock;

describe("PostTemplate", () => {
  const props = {
    data: {
      asciidoc: mocks.asciidoc,
    },
  };

  beforeEach(() => {
    mockedStaticQuery.mockImplementationOnce(({ render }) =>
      render(mocks.siteMetadata),
    );
    mockedUseStaticQuery.mockReturnValue(mocks.siteMetadata);
  });

  it("renders correctly", () => {
    const tree = renderer.create(<PostTemplate {...props} />).toJSON();
    expect(tree).toMatchSnapshot();
  });
});


text:
from json import loads, dumps

from oauthlib.common import add_params_to_uri

def weibo_compliance_fix(session):

    def _missing_token_type(r):
        token = loads(r.text)
        token['token_type'] = 'Bearer'
        r._content = dumps(token).encode('UTF-8')
        return r

    session._client.default_token_placement = 'query'
    session.register_compliance_hook('access_token_response',
                                     _missing_token_type)
    return session


text:
package org.assertj.core.groups;

import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.groups.FieldsOrPropertiesExtractor.extract;

import org.junit.jupiter.api.Test;

public class FieldsOrPropertiesExtractor_assertNotNull_Test {

  @Test
  public void should_throw_assertion_error_in_absence_of_iterable() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> extract((Iterable<?>) null, null))
                                                   .withMessageContaining("Expecting actual not to be null");
  }

  @Test
  public void should_throw_assertion_error_in_absence_of_array() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> extract((Object[]) null, null))
                                                   .withMessageContaining("Expecting actual not to be null");
  }
}


text:
package me.minidigger.voxelgameslib.api.module;

import com.google.inject.Injector;
import com.google.inject.Singleton;

import org.reflections.Reflections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.inject.Inject;

import me.minidigger.voxelgameslib.api.handler.Handler;
import me.minidigger.voxelgameslib.api.timings.Timings;

import lombok.extern.java.Log;

/**
 * The module handler takes care of all modules.
 */
@Log
@Singleton
public class ModuleHandler implements Handler {

    @Nonnull
    private List<Module> modules = new ArrayList<>();

    @Inject
    private Injector injector;

    @Override
    public void start() {
        log.info("Loading modules");
        findModules();

        modules.forEach(Module::enable);
    }

    @Override
    public void stop() {
        modules.forEach(Module::disable);
        modules.clear();
    }

    private void findModules() {
        Timings.time("RegisterModules", () -> {
            Set<Class<?>> modules = new Reflections().getTypesAnnotatedWith(ModuleInfo.class);

            for (Class<?> clazz : modules) {
                ModuleInfo info = clazz.getAnnotation(ModuleInfo.class);
                if (info == null) continue; // should not occur
                log.info("Loading module " + info.name() + " v" + info.version() + " by " + Arrays.toString(info.authors()));
                if (Module.class.isAssignableFrom(clazz)) {
                    Module module = (Module) injector.getInstance(clazz);
                    this.modules.add(module);
                } else {
                    log.warning("Class " + clazz.getSimpleName() + " has the ModuleInfo annotation but does not implement Module!");
                }
            }

            log.info("Loaded " + modules.size() + " modules!");
        });
    }
}


text:
package org.eclipse.mat.snapshot.model;

import java.io.Serializable;

/**
 * Describes a field of an object, i.e. its name and signature.
 */
public class FieldDescriptor implements Serializable
{
    private static final long serialVersionUID = 2L;

    protected String name;
    protected int type;

    public FieldDescriptor(String name, int type)
    {
        this.name = name;
        this.type = type;
    }

    public String getName()
    {
        return name;
    }

    public int getType()
    {
        return type;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public void setType(int type)
    {
        this.type = type;
    }

    public String getVerboseSignature()
    {
        if (type == IObject.Type.OBJECT)
            return "ref"; //$NON-NLS-1$

        String t = IPrimitiveArray.TYPE[type];
        return t.substring(0, t.length() - 2);
    }
}


text:
<?php

declare(strict_types=1);

namespace FondBot\Tests\Unit\Channels;

use FondBot\Channels\User;
use FondBot\Tests\TestCase;

class UserTest extends TestCase
{
    public function testFull(): void
    {
        $user = new User(
            $id = $this->faker()->uuid,
            $name = $this->faker()->name,
            $username = $this->faker()->userName,
            $data = ['foo' => 'bar']
        );

        $this->assertSame($id, $user->getId());
        $this->assertSame($name, $user->getName());
        $this->assertSame($username, $user->getUsername());
        $this->assertSame($data, $user->getData()->toArray());
    }

    public function testAcceptsNullsForNameAndUsername(): void
    {
        $user = new User($id = $this->faker()->uuid, null, null);

        $this->assertSame($id, $user->getId());
        $this->assertNull($user->getName());
        $this->assertNull($user->getUsername());
    }
}


text:
/* Automatically generated nanopb header */
/* Generated by nanopb-0.3.9.8 */

#ifndef PB_GOOGLE_PROTOBUF_EMPTY_NANOPB_H_INCLUDED
#define PB_GOOGLE_PROTOBUF_EMPTY_NANOPB_H_INCLUDED
#include <pb.h>

#include <string>

namespace firebase {
namespace firestore {

/* @@protoc_insertion_point(includes) */
#if PB_PROTO_HEADER_VERSION != 30
#error Regenerate this file with the current version of nanopb generator.
#endif

/* Struct definitions */
typedef struct _google_protobuf_Empty {
    char dummy_field;

    std::string ToString(int indent = 0) const;
/* @@protoc_insertion_point(struct:google_protobuf_Empty) */
} google_protobuf_Empty;

/* Default values for struct fields */

/* Initializer values for message structs */
#define google_protobuf_Empty_init_default       {0}
#define google_protobuf_Empty_init_zero          {0}

/* Field tags (for use in manual encoding/decoding) */

/* Struct field encoding specification for nanopb */
extern const pb_field_t google_protobuf_Empty_fields[1];

/* Maximum encoded size of messages (where known) */
#define google_protobuf_Empty_size               0

/* Message IDs (where set with "msgid" option) */
#ifdef PB_MSGID

#define EMPTY_MESSAGES \

#endif

}  // namespace firestore
}  // namespace firebase

/* @@protoc_insertion_point(eof) */

#endif


text:
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>

#include <lib/macros.h>
#include <lib/shell.h>

#include "condvar.h"
#include "main.h"
#include "mutex.h"
#include "panic.h"
#include "sw.h"
#include "thread.h"
#include "timer.h"

/*
 * Display interval, in seconds.
 */
#define SW_DISPLAY_INTERVAL 5

/*
 * Maximum wait time for the sw_wait command.
 */
#define SW_MAX_WAIT 30

/*
 * Stopwatch type.
 *
 * The mutex must be locked before accessing any member.
 */
struct sw {
    struct mutex mutex;
    struct condvar cv;
    struct timer timer;
    unsigned long ticks;
    bool timer_scheduled;
    bool thread_waiting;
    unsigned long wait_ticks;
};

/*
 * Singleton instance.
 */
static struct sw *sw_instance;

static struct sw *
sw_get_instance(void)
{
    assert(sw_instance);
    return sw_instance;
}

static void
sw_timer_run(void *arg)
{
    struct sw *sw;

    sw = arg;

    mutex_lock(&sw->mutex);

    if (!sw->timer_scheduled) {
        goto out;
    }

    sw->ticks++;

    if ((sw->ticks % (THREAD_SCHED_FREQ * SW_DISPLAY_INTERVAL)) == 0) {
        printf("%lu\n", sw->ticks);
    }

    if (sw->thread_waiting && timer_ticks_occurred(sw->wait_ticks, sw->ticks)) {
        sw->thread_waiting = false;
        condvar_signal(&sw->cv);
    }

    timer_schedule(&sw->timer, timer_get_time(&sw->timer) + 1);

out:
    mutex_unlock(&sw->mutex);
}

static struct sw *
sw_create(void)
{
    struct sw *sw;

    sw = malloc(sizeof(*sw));

    if (!sw) {
        return NULL;
    }

    mutex_init(&sw->mutex);
    condvar_init(&sw->cv);
    timer_init(&sw->timer, sw_timer_run, sw);
    sw->timer_scheduled = false;
    sw->thread_waiting = false;
    return sw;
}

static void
sw_schedule(struct sw *sw)
{
    if (sw->timer_scheduled) {
        return;
    }

    sw->timer_scheduled = true;
    timer_schedule(&sw->timer, timer_now() + 1);
}

static void
sw_start(struct sw *sw)
{
    mutex_lock(&sw->mutex);
    sw->ticks = 0;
    sw_schedule(sw);
    mutex_unlock(&sw->mutex);
}

static void
sw_stop(struct sw *sw)
{
    mutex_lock(&sw->mutex);
    sw->timer_scheduled = false;
    mutex_unlock(&sw->mutex);
}

static void
sw_resume(struct sw *sw)
{
    mutex_lock(&sw->mutex);
    sw_schedule(sw);
    mutex_unlock(&sw->mutex);
}

static unsigned long
sw_read(struct sw *sw)
{
    unsigned long ticks;

    mutex_lock(&sw->mutex);
    ticks = sw->ticks;
    mutex_unlock(&sw->mutex);

    return ticks;
}

static void
sw_wait(struct sw *sw, unsigned long seconds)
{
    mutex_lock(&sw->mutex);

    if (!sw->timer_scheduled) {
        printf("sw_wait: error: stopwatch disabled\n");
        goto out;
    } else if (sw->thread_waiting) {
        printf("sw_wait: error: thread already waiting\n");
        goto out;
    }

    sw->thread_waiting = true;
    sw->wait_ticks = sw->ticks + (seconds * THREAD_SCHED_FREQ);

    do {
        condvar_wait(&sw->cv, &sw->mutex);
    } while (sw->thread_waiting);

out:
    mutex_unlock(&sw->mutex);
}

static void
sw_shell_start(struct shell *shell, int argc, char **argv)
{
    (void)shell;
    (void)argc;
    (void)argv;

    sw_start(sw_get_instance());
}

static void
sw_shell_stop(struct shell *shell, int argc, char **argv)
{
    (void)shell;
    (void)argc;
    (void)argv;

    sw_stop(sw_get_instance());
}

static void
sw_shell_resume(struct shell *shell, int argc, char **argv)
{
    (void)shell;
    (void)argc;
    (void)argv;

    sw_resume(sw_get_instance());
}

static void
sw_shell_read(struct shell *shell, int argc, char **argv)
{
    (void)shell;
    (void)argc;
    (void)argv;

    printf("%lu\n", sw_read(sw_get_instance()));
}

static void
sw_shell_wait(struct shell *shell, int argc, char **argv)
{
    unsigned long seconds;
    int ret;

    (void)shell;

    if (argc != 2) {
        goto error;
    }

    ret = sscanf(argv[1], "%lu", &seconds);

    if ((ret != 1) || (seconds > SW_MAX_WAIT)) {
        goto error;
    }

    sw_wait(sw_get_instance(), seconds);
    return;

error:
    shell_printf(shell, "sw_wait: error: invalid arguments\n");
}

static struct shell_cmd sw_shell_cmds[] = {
    SHELL_CMD_INITIALIZER("sw_start", sw_shell_start,
        "sw_start",
        "start the stopwatch"),
    SHELL_CMD_INITIALIZER("sw_stop", sw_shell_stop,
        "sw_stop",
        "stop the stopwatch"),
    SHELL_CMD_INITIALIZER("sw_resume", sw_shell_resume,
        "sw_resume",
        "resume the stopwatch"),
    SHELL_CMD_INITIALIZER("sw_read", sw_shell_read,
        "sw_read",
        "read the stopwatch time"),
    SHELL_CMD_INITIALIZER("sw_wait", sw_shell_wait,
        "sw_wait <seconds>",
        "wait for up to " QUOTE(SW_MAX_WAIT) " seconds"),
};

void
sw_setup(void)
{
    sw_instance = sw_create();

    if (!sw_instance) {
        panic("sw: error: unable to create stopwatch");
    }

    SHELL_REGISTER_CMDS(sw_shell_cmds, main_get_shell_cmd_set());
}


text:
"""
Translation CLI.
"""
import argparse
import sys
import time
from contextlib import ExitStack
from typing import Generator, Optional, List

import mxnet as mx
from math import ceil

from sockeye.lexicon import TopKLexicon
from sockeye.log import setup_main_logger
from sockeye.output_handler import get_output_handler, OutputHandler
from sockeye.utils import acquire_gpus, get_num_gpus, log_basic_info, check_condition, grouper
from . import arguments
from . import constants as C
from . import data_io
from . import inference

logger = setup_main_logger(__name__, file_logging=False)

def main():
    params = arguments.ConfigArgumentParser(description='Translate CLI')
    arguments.add_translate_cli_args(params)
    args = params.parse_args()
    run_translate(args)

def run_translate(args: argparse.Namespace):

    if args.output is not None:
        global logger
        logger = setup_main_logger(__name__,
                                   console=not args.quiet,
                                   file_logging=True,
                                   path="%s.%s" % (args.output, C.LOG_NAME))

    if args.checkpoints is not None:
        check_condition(len(args.checkpoints) == len(args.models), "must provide checkpoints for each model")

    if args.beam_search_stop == C.BEAM_SEARCH_STOP_FIRST:
        check_condition(args.batch_size == 1,
                        "Early stopping (--beam-search-stop %s) not supported with batching" % (C.BEAM_SEARCH_STOP_FIRST))

    log_basic_info(args)

    output_handler = get_output_handler(args.output_type,
                                        args.output,
                                        args.sure_align_threshold)

    with ExitStack() as exit_stack:
        context = _setup_context(args, exit_stack)

        if args.override_dtype == C.DTYPE_FP16:
            logger.warning('Experimental feature \'--override-dtype float16\' has been used. '
                           'This feature may be removed or change its behaviour in future. '
                           'DO NOT USE IT IN PRODUCTION!')

        models, source_vocabs, target_vocab = inference.load_models(
            context=context,
            max_input_len=args.max_input_len,
            beam_size=args.beam_size,
            batch_size=args.batch_size,
            model_folders=args.models,
            checkpoints=args.checkpoints,
            softmax_temperature=args.softmax_temperature,
            max_output_length_num_stds=args.max_output_length_num_stds,
            decoder_return_logit_inputs=args.restrict_lexicon is not None,
            cache_output_layer_w_b=args.restrict_lexicon is not None,
            override_dtype=args.override_dtype)
        restrict_lexicon = None  # type: Optional[TopKLexicon]
        if args.restrict_lexicon:
            restrict_lexicon = TopKLexicon(source_vocabs[0], target_vocab)
            restrict_lexicon.load(args.restrict_lexicon, k=args.restrict_lexicon_topk)
        store_beam = args.output_type == C.OUTPUT_HANDLER_BEAM_STORE
        translator = inference.Translator(context=context,
                                          ensemble_mode=args.ensemble_mode,
                                          bucket_source_width=args.bucket_width,
                                          length_penalty=inference.LengthPenalty(args.length_penalty_alpha,
                                                                                args.length_penalty_beta),
                                          beam_prune=args.beam_prune,
                                          beam_search_stop=args.beam_search_stop,
                                          models=models,
                                          source_vocabs=source_vocabs,
                                          target_vocab=target_vocab,
                                          restrict_lexicon=restrict_lexicon,
                                          store_beam=store_beam,
                                          strip_unknown_words=args.strip_unknown_words)
        read_and_translate(translator=translator,
                           output_handler=output_handler,
                           chunk_size=args.chunk_size,
                           input_file=args.input,
                           input_factors=args.input_factors,
                           input_is_json=args.json_input)

def make_inputs(input_file: Optional[str],
                translator: inference.Translator,
                input_is_json: bool,
                input_factors: Optional[List[str]] = None) -> Generator[inference.TranslatorInput, None, None]:
    """
    Generates TranslatorInput instances from input. If input is None, reads from stdin. If num_input_factors > 1,
    the function will look for factors attached to each token, separated by '|'.
    If source is not None, reads from the source file. If num_source_factors > 1, num_source_factors source factor
    filenames are required.

    :param input_file: The source file (possibly None).
    :param translator: Translator that will translate each line of input.
    :param input_is_json: Whether the input is in json format.
    :param input_factors: Source factor files.
    :return: TranslatorInput objects.
    """
    if input_file is None:
        check_condition(input_factors is None, "Translating from STDIN, not expecting any factor files.")
        for sentence_id, line in enumerate(sys.stdin, 1):
            if input_is_json:
                yield inference.make_input_from_json_string(sentence_id=sentence_id, json_string=line)
            else:
                yield inference.make_input_from_factored_string(sentence_id=sentence_id,
                                                                factored_string=line,
                                                                translator=translator)
    else:
        input_factors = [] if input_factors is None else input_factors
        inputs = [input_file] + input_factors
        check_condition(translator.num_source_factors == len(inputs),
                        "Model(s) require %d factors, but %d given (through --input and --input-factors)." % (
                            translator.num_source_factors, len(inputs)))
        with ExitStack() as exit_stack:
            streams = [exit_stack.enter_context(data_io.smart_open(i)) for i in inputs]
            for sentence_id, inputs in enumerate(zip(*streams), 1):
                if input_is_json:
                    yield inference.make_input_from_json_string(sentence_id=sentence_id, json_string=inputs[0])
                else:
                    yield inference.make_input_from_multiple_strings(sentence_id=sentence_id, strings=list(inputs))

def read_and_translate(translator: inference.Translator,
                       output_handler: OutputHandler,
                       chunk_size: Optional[int],
                       input_file: Optional[str] = None,
                       input_factors: Optional[List[str]] = None,
                       input_is_json: bool = False) -> None:
    """
    Reads from either a file or stdin and translates each line, calling the output_handler with the result.

    :param output_handler: Handler that will write output to a stream.
    :param translator: Translator that will translate each line of input.
    :param chunk_size: The size of the portion to read at a time from the input.
    :param input_file: Optional path to file which will be translated line-by-line if included, if none use stdin.
    :param input_factors: Optional list of paths to files that contain source factors.
    :param input_is_json: Whether the input is in json format.
    """
    batch_size = translator.batch_size
    if chunk_size is None:
        if translator.batch_size == 1:
            # No batching, therefore there is not need to read segments in chunks.
            chunk_size = C.CHUNK_SIZE_NO_BATCHING
        else:
            # Get a constant number of batches per call to Translator.translate.
            chunk_size = C.CHUNK_SIZE_PER_BATCH_SEGMENT * translator.batch_size
    else:
        if chunk_size < translator.batch_size:
            logger.warning("You specified a chunk size (%d) smaller than the batch size (%d). This will lead to "
                           "a reduction in translation speed. Consider choosing a larger chunk size." % (chunk_size,
                                                                                batch_size))

    logger.info("Translating...")

    total_time, total_lines = 0.0, 0
    for chunk in grouper(make_inputs(input_file, translator, input_is_json, input_factors), size=chunk_size):
        chunk_time = translate(output_handler, chunk, translator)
        total_lines += len(chunk)
        total_time += chunk_time

    if total_lines != 0:
        logger.info("Processed %d lines in %d batches. Total time: %.4f, sec/sent: %.4f, sent/sec: %.4f",
                    total_lines, ceil(total_lines / batch_size), total_time,
                    total_time / total_lines, total_lines / total_time)
    else:
        logger.info("Processed 0 lines.")

def translate(output_handler: OutputHandler,
              trans_inputs: List[inference.TranslatorInput],
              translator: inference.Translator) -> float:
    """
    Translates each line from source_data, calling output handler after translating a batch.

    :param output_handler: A handler that will be called once with the output of each translation.
    :param trans_inputs: A enumerable list of translator inputs.
    :param translator: The translator that will be used for each line of input.
    :return: Total time taken.
    """
    tic = time.time()
    trans_outputs = translator.translate(trans_inputs)
    total_time = time.time() - tic
    batch_time = total_time / len(trans_inputs)
    for trans_input, trans_output in zip(trans_inputs, trans_outputs):
        output_handler.handle(trans_input, trans_output, batch_time)
    return total_time

def _setup_context(args, exit_stack):
    if args.use_cpu:
        context = mx.cpu()
    else:
        num_gpus = get_num_gpus()
        check_condition(num_gpus >= 1,
                        "No GPUs found, consider running on the CPU with --use-cpu "
                        "(note: check depends on nvidia-smi and this could also mean that the nvidia-smi "
                        "binary isn't on the path).")
        check_condition(len(args.device_ids) == 1, "cannot run on multiple devices for now")
        gpu_id = args.device_ids[0]
        if args.disable_device_locking:
            if gpu_id < 0:
                # without locking and a negative device id we just take the first device
                gpu_id = 0
        else:
            gpu_ids = exit_stack.enter_context(acquire_gpus([gpu_id], lock_dir=args.lock_dir))
            gpu_id = gpu_ids[0]

        context = mx.gpu(gpu_id)
    return context

if __name__ == '__main__':
    main()


text:
package models

var SpacedockFooLatestTag = &Tag{
  Tag: "latest",
  Namespace: "spacedock",
  Repo: "foo",
}


text:
module Faker
  module Address
    extend ModuleUtils
    extend self

    # @deprecated US specific address info. Moved into {AddressUS}
    def zip_code
      warn '[zip_code] is deprecated. For US addresses please use the AddressUS module'
      Faker::AddressUS.zip_code
    end

    def us_state
      warn '[us_state] is deprecated. For US addresses please use the AddressUS module'
      Faker::AddressUS.state
    end

    def us_state_abbr
      warn '[state_abbr] is deprecated. For US addresses please use the AddressUS module'
      Faker::AddressUS.state_abbr
    end
    # end US deprecation

    def city_prefix
      CITY_PREFIXES.rand
    end

    def city_suffix
      CITY_SUFFIXES.rand
    end

    def city
      case rand(4)
      when 0 then '%s %s%s' % [city_prefix, Name.first_name, city_suffix]
      when 1 then '%s %s'   % [city_prefix, Name.first_name]
      when 2 then '%s%s'    % [Name.first_name, city_suffix]
      when 3 then '%s%s'    % [Name.last_name, city_suffix]
      end
    end

    def street_suffix
      STREET_SUFFIX.rand
    end

    def street_name
      case rand(2)
      when 0 then "#{Name.last_name} #{street_suffix}"
      when 1 then "#{Name.first_name} #{street_suffix}"
      end
    end

    def street_address(include_secondary = false)
      str = ( "#" * rand(3) ) << ('### %s' % street_name)
      str << ' ' << secondary_address  if include_secondary

      Faker.numerify(str)
    end

    def secondary_address
      Faker.numerify(SEC_ADDR.rand)
    end

    # @deprecated UK specific address info. Moved into {AddressUK}
    # UK Variants
    def uk_county
      warn '[uk_county] is deprecated. For UK addresses please use the AddressUK module'
      Faker::AddressUK.county
    end

    def uk_country
      warn '[uk_country] is deprecated. For UK addresses please use the AddressUK module'
      Faker::AddressUK.country
    end

    def uk_postcode
      warn '[uk_postcode] is deprecated. For UK addresses please use the AddressUK module'
      Faker::AddressUK.postcode
    end
    # end UK deprecation

    def neighborhood
      NEIGHBORHOOD.rand
    end

    COMPASS_DIRECTIONS = k %w(North East West South)

    CITY_PREFIXES = k(COMPASS_DIRECTIONS + %w(New Lake Port))

    CITY_SUFFIXES = k %w(town ton land ville berg burgh borough bury view port
                        mouth stad furt chester mouth fort haven side shire)

    STREET_SUFFIX = k %w(Alley Avenue Branch Bridge Brook Brooks
      Burg Burgs Bypass Camp Canyon Cape Causeway Center Centers Circle Circles
      Cliff Cliffs Club Common Corner Corners Course Court Courts Cove Coves
      Creek Crescent Crest Crossing Crossroad Curve Dale Dam Divide Drive Drives
      Estate Estates Expressway Extension Extensions Fall Falls Ferry
      Field Fields Flat Flats Ford Fords Forest Forge Forges Fork Forks Fort
      Freeway Garden Gardens Gateway Glen Glens Green Greens Grove Groves Harbor
      Harbors Haven Heights Highway Hill Hills Hollow Inlet Island
      Islands Isle Junction Junctions Key Keys Knoll Knolls Lake
      Lakes Land Landing Lane Light Lights Loaf Lock Locks Lodge Loop
      Mall Manor Manors Meadow Meadows Mews Mill Mills Mission Motorway
      Mount Mountain Mountains Neck Orchard Oval Overpass Park
      Parks Parkway Parkways Pass Passage Path Pike Pine Pines Place Plain Plains
      Plaza Point Points Port Ports Prairie
      Radial Ramp Ranch Rapid Rapids Rest Ridge Ridges River Road Roads
      Route Row Rue Run Shoal Shoals Shore Shores Skyway Spring Springs
      Spur Spurs Square Squares Station Stravenue
      Stream Street Streets Summit Terrace
      Throughway Trace Track Trafficway Trail Tunnel
      Turnpike Underpass Union Unions Valley Valleys Via Viaduct View Views
      Village Villages Ville Vista Walk Walks Wall Way Ways Well Wells)

    SEC_ADDR = k ['Apt. ###', 'Suite ###']

    NEIGHBORHOOD = k ['East of Telegraph Road', 'North Norridge', 'Northwest Midlothian/Midlothian Country Club',
      'Mott Haven/Port Morris', 'Kingsbridge Heights', 'Bronxdale', 'Pennypack', 'Bridesburg',
      'Allegheny West', 'Bushwick South', 'Dyker Heights', 'Ocean Parkway South', 'Summerlin North',
      'Seven Hills Area', 'Greater Las Vegas National', 'phoenix', 'Central Chandler', 'South of Bell Road',
      'River Heights', 'White Plains Central', 'Mount Kisco West', 'Pound Ridge East', 'Babylon Bayside',
      'Sagaponack Seaside', 'South of Lake Ave', 'Far Rockaway/Bayswater', 'Jamaica Estates/Holliswood',
      'Murray Hill', 'East Renton', 'Renton West', 'Auburn North', 'Northwoods West', 'Florissant West',
      'Ladue South', 'Candlewood Country Club', 'West Covina East', 'North East Irwindale', 'Sunshine-Gardens',
      'Cipriani', 'Brentwood Central', 'Jupiter South/Abacoa', 'Sea Ranch Lakes', 'Schall Circle/Lakeside Green',
      'Olmsted Falls Central', 'South of Lake Shore Blvd', 'Gates Mills North', 'White Oak South of Columbia Pike',
      'Rockville East of Hungerford Dr', 'Cleveland Park']
  end
end


text:
module LetterGenerator
  class Runner < Thor
    include Thor::Actions

    def self.exit_on_failure?
      true
    end

    class_option :debug_mode, type: :boolean, default: LetterGenerator.config.debug_mode, desc: 'Enabled debug mode'

    option :output_file, default: 'letter-<%= to_s %>.tex', desc: 'Outputfile'
    desc 'generate', 'Generate template'
    def generate
      enable_debug_mode

      invoke 'letter_generator:generators:tex_file_generator', [LetterTemplate.new.file], output_file: options[:output_file]
    end

    option :build_directory, default: 'build', desc: 'Build directory'
    desc 'build', 'Build letter'
    def build
      enable_debug_mode

      invoke :generate, [], output_file: File.join(options[:build_directory], 'letter-<%= to_s %>.tex')

      Dir.chdir File.expand_path(options[:build_directory]) do
        Rake::FileList.new('*.tex').each do |f|
          run %(pdflatex #{f})
        end
      end
    end

    desc 'init', 'Init configuration'
    option :for, default: 'working-directory', enum: %(user working-directory), desc: 'Initialize user configuration'
    def init
      enable_debug_mode

      source_paths << File.expand_path('../../../templates', __FILE__)
      letter_template = LetterTemplate.new

      template_path = File.expand_path(File.join('templates', File.basename(letter_template.file)))

      case options[:for].to_s.to_sym
      when :user || :u
        copy_file letter_template.file, File.join(File.dirname(LetterGenerator.config.preferred_configuration_file), 'templates', File.basename(letter_template.file))
      when :'working-directory' || :wd

        template 'data', File.expand_path('data.yaml')
        copy_file letter_template.file, template_path
      else
        fail ArgumentError, "#{options[:for]} is not a valid value for \"for\"."
      end
    end

    no_commands do
      # Enable debug mode
      def enable_debug_mode
        LetterGenerator.enable_debug_mode if options[:debug_mode] == true
      end
    end
  end
end