text:
<?php
/**
 * Order Customer Details
 *
 * This template can be overridden by copying it to yourtheme/woocommerce/order/order-details-customer.php.
 *
 * HOWEVER, on occasion WooCommerce will need to update template files and you (the theme developer).
 * will need to copy the new files to your theme to maintain compatibility. We try to do this.
 * as little as possible, but it does happen. When this occurs the version of the template file will.
 * be bumped and the readme will list any important changes.
 *
 * @see 	    http://docs.woothemes.com/document/template-structure/
 * @author  WooThemes
 * @package WooCommerce/Templates
 * @version 2.4.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
?>

<?php _e( 'Customer Details', 'woocommerce' ); ?>

		<?php if ( $order->customer_note ) : ?>

				<?php _e( 'Note:', 'woocommerce' ); ?>
				<?php echo wptexturize( $order->customer_note ); ?>

		<?php endif; ?>

		<?php if ( $order->billing_email ) : ?>

				<?php _e( 'Email:', 'woocommerce' ); ?>
				<?php echo esc_html( $order->billing_email ); ?>

		<?php endif; ?>

		<?php if ( $order->billing_phone ) : ?>

				<?php _e( 'Telephone:', 'woocommerce' ); ?>
				<?php echo esc_html( $order->billing_phone ); ?>

		<?php endif; ?>

		<?php do_action( 'woocommerce_order_details_after_customer_details', $order ); ?>

	<?php if ( ! wc_ship_to_billing_address_only() && $order->needs_shipping_address() ) : ?>

	<?php endif; ?>

<?php _e( 'Billing Address', 'woocommerce' ); ?>

		<address>
			<?php echo ( $address = $order->get_formatted_billing_address() ) ? $address : __( 'N/A', 'woocommerce' ); ?>
		</address>

	<?php if ( ! wc_ship_to_billing_address_only() && $order->needs_shipping_address() ) : ?>

<?php _e( 'Shipping Address', 'woocommerce' ); ?>

			<address>
				<?php echo ( $address = $order->get_formatted_shipping_address() ) ? $address : __( 'N/A', 'woocommerce' ); ?>
			</address>

	<?php endif; ?>


text:
@import UIKit;

@interface MJBViewController : UIViewController

@end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="CoreNLP-to-HTML.xsl" type="text/xsl"?>
<root>
  <document>
    <sentences>
      <sentence id="1">
        <tokens>
          <token id="1">
            <word>fat</word>
            <lemma>fat</lemma>
            <CharacterOffsetBegin>0</CharacterOffsetBegin>
            <CharacterOffsetEnd>3</CharacterOffsetEnd>
            <POS>JJ</POS>
          </token>
          <token id="2">
            <word>pipe</word>
            <lemma>pipe</lemma>
            <CharacterOffsetBegin>4</CharacterOffsetBegin>
            <CharacterOffsetEnd>8</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
          <token id="3">
            <word>broadband</word>
            <lemma>broadband</lemma>
            <CharacterOffsetBegin>9</CharacterOffsetBegin>
            <CharacterOffsetEnd>18</CharacterOffsetEnd>
            <POS>NN</POS>
          </token>
        </tokens>
        <parse>(ROOT (FRAG (NP (JJ fat) (NN pipe) (NN broadband)))) </parse>
        <dependencies type="basic-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="3">broadband</dependent>
          </dep>
          <dep type="amod">
            <governor idx="3">broadband</governor>
            <dependent idx="1">fat</dependent>
          </dep>
          <dep type="nn">
            <governor idx="3">broadband</governor>
            <dependent idx="2">pipe</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="3">broadband</dependent>
          </dep>
          <dep type="amod">
            <governor idx="3">broadband</governor>
            <dependent idx="1">fat</dependent>
          </dep>
          <dep type="nn">
            <governor idx="3">broadband</governor>
            <dependent idx="2">pipe</dependent>
          </dep>
        </dependencies>
        <dependencies type="collapsed-ccprocessed-dependencies">
          <dep type="root">
            <governor idx="0">ROOT</governor>
            <dependent idx="3">broadband</dependent>
          </dep>
          <dep type="amod">
            <governor idx="3">broadband</governor>
            <dependent idx="1">fat</dependent>
          </dep>
          <dep type="nn">
            <governor idx="3">broadband</governor>
            <dependent idx="2">pipe</dependent>
          </dep>
        </dependencies>
      </sentence>
    </sentences>
  </document>
</root>


text:
<?php

namespace Kcs\ApiConnectorBundle;

use Kcs\ApiConnectorBundle\DependencyInjection\Compiler\AddAuthenticatorsPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

class KcsApiConnectorBundle extends Bundle
{
    /**
     * @inheritDoc
     */
    public function build(ContainerBuilder $container)
    {
        $container
            ->addCompilerPass(new AddAuthenticatorsPass())
        ;
    }
}


text:
package org.springframework.security.web.access.channel;

/**
 * Commences an insecure channel by retrying the original request using HTTP.
 * <p>
 * This entry point should suffice in most circumstances. However, it is not intended to
 * properly handle HTTP POSTs or other usage where a standard redirect would cause an
 * issue.
 *
 * @author Ben Alex
 */
public class RetryWithHttpEntryPoint extends AbstractRetryEntryPoint {

	public RetryWithHttpEntryPoint() {
		super("http://", 80);
	}

	protected Integer getMappedPort(Integer mapFromPort) {
		return getPortMapper().lookupHttpPort(mapFromPort);
	}
}


text:
import {LegacyPluginThis} from './plugin_this';

/**
 * The value of `this` in the context of a [[LegacyImporter]] function.
 *
 * @category Legacy
 * @deprecated This is only used by the legacy [[render]] and [[renderSync]]
 * APIs. Use [[Importer]] with [[compile]], [[compileString]], [[compileAsync]],
 * and [[compileStringAsync]] instead.
 */
interface LegacyImporterThis extends LegacyPluginThis {
  /**
   * Whether the importer is being invoked because of a Sass `@import` rule, as
   * opposed to a `@use` or `@forward` rule.
   *
   * This should *only* be used for determining whether or not to load
   * [import-only files](https://sass-lang.com/documentation/at-rules/import#import-only-files).
   *
   * @compatibility dart: "1.33.0", node: false
   */
  fromImport: boolean;
}

/**
 * The result of running a [[LegacyImporter]]. It must be one of the following
 * types:
 *
 * * An object with the key `contents` whose value is the contents of a stylesheet
 *   (in SCSS syntax). This causes Sass to load that stylesheet's contents.
 *
 * * An object with the key `file` whose value is a path on disk. This causes Sass
 *   to load that file as though it had been imported directly.
 *
 * * `null`, which indicates that it doesn't recognize the URL and another
 *   importer should be tried instead.
 *
 * * An [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error)
 *   object, indicating that importing failed.
 *
 * @category Legacy
 * @deprecated This only works with the legacy [[render]] and [[renderSync]]
 * APIs. Use [[ImporterResult]] with [[compile]], [[compileString]],
 * [[compileAsync]], and [[compileStringAsync]] instead.
 */
export type LegacyImporterResult =
  | {file: string}
  | {contents: string}
  | Error
  | null;

/**
 * A synchronous callback that implements custom Sass loading logic for
 * [`@import` rules](https://sass-lang.com/documentation/at-rules/import) and
 * [`@use` rules](https://sass-lang.com/documentation/at-rules/use). This can be
 * passed to [[LegacySharedOptions.importer]] for either [[render]] or
 * [[renderSync]].
 *
 * See [[LegacySharedOptions.importer]] for more detailed documentation.
 *
 * ```js
 * sass.renderSync({
 *   file: "style.scss",
 *   importer: [
 *     function(url, prev) {
 *       if (url != "big-headers") return null;
 *
 *       return {
 *         contents: 'h1 { font-size: 40px; }'
 *       };
 *     }
 *   ]
 * });
 * ```
 *
 * @param url - The `@use` or `@import` rule's URL as a string, exactly as it
 * appears in the stylesheet.
 *
 * @param prev - A string identifying the stylesheet that contained the `@use`
 * or `@import`. This string's format depends on how that stylesheet was loaded:
 *
 * * If the stylesheet was loaded from the filesystem, it's the absolute path of
 *   its file.
 * * If the stylesheet was loaded from an importer that returned its contents,
 *   it's the URL of the `@use` or `@import` rule that loaded it.
 * * If the stylesheet came from the data option, it's the string "stdin".
 *
 * @category Legacy
 * @deprecated This only works with the legacy [[render]] and [[renderSync]]
 * APIs. Use [[Importer]] with [[compile]], [[compileString]], [[compileAsync]],
 * and [[compileStringAsync]] instead.
 */
type LegacySyncImporter = (
  this: LegacyImporterThis,
  url: string,
  prev: string
) => LegacyImporterResult;

/**
 * An asynchronous callback that implements custom Sass loading logic for
 * [`@import` rules](https://sass-lang.com/documentation/at-rules/import) and
 * [`@use` rules](https://sass-lang.com/documentation/at-rules/use). This can be
 * passed to [[LegacySharedOptions.importer]] for either [[render]] or
 * [[renderSync]].
 *
 * An asynchronous importer must return `undefined`, and then call `done` with
 * the result of its [[LegacyImporterResult]] once it's done running.
 *
 * See [[LegacySharedOptions.importer]] for more detailed documentation.
 *
 * ```js
 * sass.render({
 *   file: "style.scss",
 *   importer: [
 *     function(url, prev, done) {
 *       if (url != "big-headers") done(null);
 *
 *       done({
 *         contents: 'h1 { font-size: 40px; }'
 *       });
 *     }
 *   ]
 * });
 * ```
 *
 * @param url - The `@use` or `@import` rule's URL as a string, exactly as it
 * appears in the stylesheet.
 *
 * @param prev - A string identifying the stylesheet that contained the `@use`
 * or `@import`. This string's format depends on how that stylesheet was loaded:
 *
 * * If the stylesheet was loaded from the filesystem, it's the absolute path of
 *   its file.
 * * If the stylesheet was loaded from an importer that returned its contents,
 *   it's the URL of the `@use` or `@import` rule that loaded it.
 * * If the stylesheet came from the data option, it's the string "stdin".
 *
 * @param done - The callback to call once the importer has finished running.
 *
 * @category Legacy
 * @deprecated This only works with the legacy [[render]] and [[renderSync]]
 * APIs. Use [[Importer]] with [[compile]], [[compileString]], [[compileAsync]],
 * and [[compileStringAsync]] instead.
 */
type LegacyAsyncImporter = (
  this: LegacyImporterThis,
  url: string,
  prev: string,
  done: (result: LegacyImporterResult) => void
) => void;

/**
 * A callback that implements custom Sass loading logic for [`@import`
 * rules](https://sass-lang.com/documentation/at-rules/import) and [`@use`
 * rules](https://sass-lang.com/documentation/at-rules/use). For [[renderSync]],
 * this must be a [[LegacySyncImporter]] which returns its result directly; for
 * [[render]], it may be either a [[LegacySyncImporter]] or a
 * [[LegacyAsyncImporter]] which calls a callback with its result.
 *
 * See [[LegacySharedOptions.importer]] for more details.
 *
 * @category Legacy
 * @deprecated This only works with the legacy [[render]] and [[renderSync]]
 * APIs. Use [[Importer]] with [[compile]], [[compileString]], [[compileAsync]],
 * and [[compileStringAsync]] instead.
 */
export type LegacyImporter<sync = 'sync' | 'async'> = sync extends 'async'
  ? LegacySyncImporter | LegacyAsyncImporter
  : LegacySyncImporter;


text:
from __future__ import division
import cv2
from cv2 import cv
from copy import copy
import numpy as np
import multiprocessing.dummy as mp
from multiprocessing import Lock
import sys
import math

import rospy
import roslib
import cv_bridge
from sensor_msgs.msg import Image
from numpy import dtype

class ImageProcessor():

# Processing Mode
# mode = 0 : Do nothing
# mode = 1 : Automatic gamma adjustment
# mode = 2 : Convertion to Illumination-invariant color space

    def __init__ (self, processMode=0, subscribedImageTopic='', publishedImageTopic='', maskPath=None, **kwargs):
        self.imageSub = rospy.Subscriber(subscribedImageTopic, Image, self.imageCallback, queue_size=100)
        self.publisher = rospy.Publisher(publishedImageTopic, Image, queue_size=100)
        self.bridge = cv_bridge.CvBridge()
        self.mask = cv2.imread (maskPath, cv2.cv.CV_LOAD_IMAGE_GRAYSCALE)
        self.cImage = None
        self.resultImage = None
        self.cImageHsv = None
        self.isMono = None
        self.imageMutex = Lock ()
        self.mode = processMode
        try:
            self.doSmearDetection = bool(kwargs['smearDetection'])
            self.iiAlpha = kwargs['IlluminatiAlpha']
        except KeyError:
            self.doSmearDetection = False
            self.iiAlpha = 0.394
#         cv2.namedWindow('xyz')

    def imageCallback (self, imageMsg):
#         print ("Callback called")
#         self.imageMutex.acquire()
        self.cImage = self.bridge.imgmsg_to_cv2(imageMsg, 'bgr8')
        self.isMono = False
#         self.imageMutex.release()

        self.process()

        if self.isMono:
            msg = self.bridge.cv2_to_imgmsg(self.resultImage, 'mono8')
        else:
            msg = self.bridge.cv2_to_imgmsg(self.resultImage, 'bgr8')
        msg.header.stamp = rospy.Time.now()
        self.publisher.publish(msg)

    def process (self):
        if self.cImage is None :
            return

#         self.imageMutex.acquire ()

        # Preparation
        imghsv = cv2.cvtColor(self.cImage, cv.CV_BGR2HSV)
        self.cImageHsv = cv2.split(imghsv)

        if self.doSmearDetection:
            smearQual = self.detectSmear(self.cImageHsv[2])
            print ("Smear: {}".format(smearQual))

        if self.mode == 0:
            self.resultImage = self.cImage
            self.isMono = False

        elif self.mode == 1 :
            self.resultImage = ImageProcessor.autoAdjustGammaRGB(self.cImage, self.mask)
            self.isMono = False

        elif self.mode == 2 :
            self.resultImage = ImageProcessor.toIlluminatiInvariant(self.cImage, self.iiAlpha)
            self.isMono = True

#         self.imageMutex.release ()

    @staticmethod
    def autoAdjustGammaRGB (rgbImage, mask=None, gammaOnly=False):
        monoimg = cv2.cvtColor(rgbImage, cv.CV_BGR2GRAY)
        g = ImageProcessor.autoAdjustGammaMono(monoimg, mask, gammaOnly=True)
        if gammaOnly:
            return g
        img_b = ImageProcessor.setGamma(rgbImage[:,:,0], g)
        img_g = ImageProcessor.setGamma(rgbImage[:,:,1], g)
        img_r = ImageProcessor.setGamma(rgbImage[:,:,2], g)
        return cv2.merge([img_b, img_g, img_r])

    @staticmethod
    def autoAdjustGammaMono (grayImage, mask=None, gammaOnly=False):
        roicdf = ImageProcessor.cdf(grayImage, mask)
#         Try to find midtone; it is X when cdf[X] = 0.5
        midtone = 0
        for i in range(len(roicdf)):
            if roicdf[i]>=0.5:
                midtone = i
                break
        target = 0.5
        midtone /= 255.0
        gamma = math.log(target) / math.log(midtone)
        if (gammaOnly):
            return gamma
        if (midtone >= 0.5):
            return grayImage
        return ImageProcessor.setGamma (grayImage, gamma)

    @staticmethod
    def toIlluminatiInvariant (imageRgb, alpha):
        imgf = np.array(imageRgb, dtype=np.float32) / 255.0
        imgf = 0.5 + np.log(imgf[:,:,1]) - alpha*np.log(imgf[:,:,0]) - (1-alpha)*np.log(imgf[:,:,2])
        return np.array(imgf*255.0, dtype=np.uint8)
#         return cv2.cvtColor(img, cv.CV_GRAY2BGR)

    def beautify (self):
        midall = self.allcdf[127]
        midroi = self.roicdf[127]

        def needBeautify ():
            if (midall >= 0.4 and midall <= 0.6):
                return False
            if (midall > 0.6 and midroi < midall):
                return False
            if (midall > 0.6 and midroi-midall>=0.16):
                return True
#         if abs(midall-midroi) <

        if (needBeautify()):
            self.cImageHsv[2] = ImageProcessor.equalizeByMask(self.cImageHsv[2], self.mask)
            self.noProcess = False
        else:
            return

    @staticmethod
    def getNormalizedVerticalSum (chan):
        channorm = chan / 256.0
        tv = np.zeros(channorm.shape[1], dtype=np.float32)
        for i in range(channorm.shape[1]):
            tv[i] = np.sum(channorm[:,i])
        tv /= float(channorm.shape[0])
        return tv

    @staticmethod
    def detectSmear (VchanSrc, tolerance=0.1):
        threshold1 = 0.15 * VchanSrc.shape[1]
        # Normalize V channel
        tv = ImageProcessor.getNormalizedVerticalSum(VchanSrc)
        nc = 0
        for i in range(VchanSrc.shape[1]) :
            if tv[i] >= 1.0-tolerance:
                nc += 1
        if nc==0:
            return -1
        else:
            print ("Cols: {}".format(nc))
            if nc >= threshold1:
                return 1
            else:
                return float(nc) / float(threshold1)

    @staticmethod
    def setGamma (source, gamma):
        LUT = np.array(
            [ ((i/255.0)**gamma)*255.0 for i in range(256)]
        , dtype=np.uint8)
        return cv2.LUT(source, LUT)

    @staticmethod
    def equalizeByMask (source, mask=None):
        LUT = np.zeros((256,1), dtype=np.uint8)
        output = np.zeros(source.shape, dtype=source.dtype)
        hist = cv2.calcHist ([source], [0], mask, [256], [0,256])

        p = 0
        while (hist[p]==0):
            p += 1

        total = source.shape[0]*source.shape[1]
        miz = hist[p]
        scale = 256.0 / (total-miz)
        sum = 0
        for i in range (p, 256):
            sum += int (hist[i])
            l = sum * scale
            if l > 255:
                LUT[i] = 255
            else:
                LUT[i] = l

        cv2.LUT(source, LUT, output)
        return output
#         for (LUT.at<uchar>(i++)=0; i<256; ++i) {
#             sum += (int)hist.at<float>(i);
#             LUT.at<uchar>(i) = cv::saturate_cast<uchar>(sum * scale);
#         }

#     def needEqualize (self):
#         pass

    @staticmethod
    def cdf (grayImage, mask=None, normalized=True):
        hist = cv2.calcHist ([grayImage], [0], mask, [256], [0,256])
        rcdf = np.cumsum(hist)
        if normalized:
            return rcdf / sum(hist)
        else:
            return rcdf

# class Downsampler:
#     def __init__ (self, imgproc, publishedTopic, rate=10.0):
#         self.rate = rospy.Rate(rate)
#         self.imgproc = imgproc
#         self.publisher = rospy.Publisher(publishedTopic, Image, queue_size=10)
#         self.bridge = cv_bridge.CvBridge()
#
#         self.stop = False
#         self.process = mp.Process(target=self.start)
#         self.process.start()
#
#     def start (self):
#         while self.stop==False:
#
#             currentImage = None
#             self.imgproc.process()
#             currentImage = self.imgproc.resultImage
#
#             if currentImage is not None:
#                 if self.imgproc.isMono:
#                     msg = self.bridge.cv2_to_imgmsg(currentImage, 'mono8')
#                 else:
#                     msg = self.bridge.cv2_to_imgmsg(currentImage, 'bgr8')
#                 msg.header.stamp = rospy.Time.now()
#                 self.publisher.publish(msg)
#             self.rate.sleep()

if __name__ == '__main__' :

    maskpath = sys.argv[1]

    mode = 0
    try:
        mode = int (sys.argv[2])
    except IndexError:
        pass
    if mode == 0:
        print ("Images will be untouched")
    else:
        print ("Images will be modified")

    rospy.init_node("imgprocx", anonymous=True)
    imgproc = ImageProcessor (mode, "/camera/image_raw", "/camera/image_hs", maskpath, smearDetection=False, IlluminatiAlpha=0.3975)
#     downsample = Downsampler (imgproc, "/camera/image_hs", rate=10.0)
    rospy.spin()
#     downsample.stop = True

    pass


text:
package farmsim.tasks;

import farmsim.resource.SimpleResource;
import farmsim.buildings.AbstractBuilding;
import farmsim.buildings.Jetty;
import farmsim.entities.agents.Agent;
import farmsim.entities.agents.AgentManager;
import farmsim.entities.tileentities.TileEntity;
import farmsim.entities.tileentities.objects.Water;
import farmsim.entities.tools.ToolType;
import farmsim.inventory.SimpleResourceHandler;
import farmsim.util.Point;
import farmsim.world.World;
import farmsim.world.WorldManager;

import java.util.List;
import java.util.Set;

/**
 * FishTask allows users to fish in a body of water. Fishing is possible on
 * Water tiles and will be successful randomly.
 *
 * @author rachelcatchpoole for Team Adleman
 *
 */
public class FishTask extends AgentRoleTask {

    private static final int BASE_DURATION = 5000;
    private static final String NAME = "Fish";
    private static final String ID = "fish";
    private Point jettyPoint;

    public FishTask(Point point, World world) {
        super(point, BASE_DURATION, world, NAME, ID);
        // Adjust duration depending on agent level
        this.duration *= defaultRoleLevelTimeModifier();
        setRequiredTool(ToolType.FISHING_ROD);
        isValid();
    }

    @Override
    public Agent.RoleType relatedRole() {
        return Agent.RoleType.FARMER;
    }

    @Override
    public int experienceGained() {
        return 1;
    }

    /**
     * @return the assigned agent for this task
     */
    public Agent getAssignedAgent() {
        AgentManager agentManager = AgentManager.getInstance();
        List<Agent> agents = agentManager.getAgents();

        for (Agent agent : agents) {
            if (agent.getTask().equals(this)) {
                return agent;
            }
        }
        return null;
    }

    @Override
    public void preTask() {
        // Do nothing
    }

    @Override
    public void postTask() {

        Agent agent = getAssignedAgent();

        double random = Math.random();
        if (random >= 0.75) {
            SimpleResource fish = SimpleResourceHandler.getInstance().fish;
            agent.getRucksack().addToRucksack(new SimpleResource(fish.getType(),
                    fish.getAttributes(), 1));
        }

    }

    /**
     * Returns the point from which the agent should fish.
     *
     * @return Point the Point on the jetty where the agent should fish from.
     */
    @Override
    public Point getDestination() {
        return jettyPoint;
    }

    /**
     *
     * @param jetty
     *            the jetty building to examine
     * @return true if
     */
    private boolean nearJetty(Jetty jetty) {
        double fishX = location.getX();
        double fishY = location.getY();
        double jettyX = jetty.getWorldX();
        double jettyY = jetty.getWorldY();
        jettyPoint = new Point(jetty.getWorldX() + 2, jetty.getWorldY());
        int radius = jetty.getRadius();

        return fishX >= jettyX - radius && fishX <= jettyX + radius
                && fishY >= jettyY - radius && fishY <= jettyY + radius;

    }

    /**
     * Fishing is valid if done on a water tile near a jetty.
     */
    @Override
    public boolean isValid() {
        boolean nearJetty = false;
        World world = WorldManager.getInstance().getWorld();
        Set<AbstractBuilding> buildings = world.getBuildings();
        for (AbstractBuilding building : buildings) {
            if (building instanceof Jetty) {
                nearJetty = nearJetty((Jetty) building);
            }
            if (nearJetty) {
                break;
            }
        }

        TileEntity entity = tile.getTileEntity();
        return nearJetty && entity instanceof Water
                && entity.getTileType().equals("water");
    }

    @Override
    public AbstractTask copy() {
        return new FishTask(location, world);
    }

}


text:
package container

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/docker/docker/api/types"
	containertypes "github.com/docker/docker/api/types/container"
	"github.com/docker/docker/pkg/system"
)

const (
	containerSecretMountPath         = `C:\ProgramData\Docker\secrets`
	containerInternalSecretMountPath = `C:\ProgramData\Docker\internal\secrets`
	containerInternalConfigsDirPath  = `C:\ProgramData\Docker\internal\configs`

	// DefaultStopTimeout is the timeout (in seconds) for the shutdown call on a container
	DefaultStopTimeout = 30
)

// UnmountIpcMount unmounts Ipc related mounts.
// This is a NOOP on windows.
func (container *Container) UnmountIpcMount(unmount func(pth string) error) error {
	return nil
}

// IpcMounts returns the list of Ipc related mounts.
func (container *Container) IpcMounts() []Mount {
	return nil
}

// CreateSecretSymlinks creates symlinks to files in the secret mount.
func (container *Container) CreateSecretSymlinks() error {
	for _, r := range container.SecretReferences {
		if r.File == nil {
			continue
		}
		resolvedPath, _, err := container.ResolvePath(getSecretTargetPath(r))
		if err != nil {
			return err
		}
		if err := system.MkdirAll(filepath.Dir(resolvedPath), 0, ""); err != nil {
			return err
		}
		if err := os.Symlink(filepath.Join(containerInternalSecretMountPath, r.SecretID), resolvedPath); err != nil {
			return err
		}
	}

	return nil
}

// SecretMounts returns the mount for the secret path.
// All secrets are stored in a single mount on Windows. Target symlinks are
// created for each secret, pointing to the files in this mount.
func (container *Container) SecretMounts() []Mount {
	var mounts []Mount
	if len(container.SecretReferences) > 0 {
		mounts = append(mounts, Mount{
			Source:      container.SecretMountPath(),
			Destination: containerInternalSecretMountPath,
			Writable:    false,
		})
	}

	return mounts
}

// UnmountSecrets unmounts the fs for secrets
func (container *Container) UnmountSecrets() error {
	return os.RemoveAll(container.SecretMountPath())
}

// CreateConfigSymlinks creates symlinks to files in the config mount.
func (container *Container) CreateConfigSymlinks() error {
	for _, configRef := range container.ConfigReferences {
		if configRef.File == nil {
			continue
		}
		resolvedPath, _, err := container.ResolvePath(configRef.File.Name)
		if err != nil {
			return err
		}
		if err := system.MkdirAll(filepath.Dir(resolvedPath), 0, ""); err != nil {
			return err
		}
		if err := os.Symlink(filepath.Join(containerInternalConfigsDirPath, configRef.ConfigID), resolvedPath); err != nil {
			return err
		}
	}

	return nil
}

// ConfigMounts returns the mount for configs.
// All configs are stored in a single mount on Windows. Target symlinks are
// created for each config, pointing to the files in this mount.
func (container *Container) ConfigMounts() []Mount {
	var mounts []Mount
	if len(container.ConfigReferences) > 0 {
		mounts = append(mounts, Mount{
			Source:      container.ConfigsDirPath(),
			Destination: containerInternalConfigsDirPath,
			Writable:    false,
		})
	}

	return mounts
}

// DetachAndUnmount unmounts all volumes.
// On Windows it only delegates to `UnmountVolumes` since there is nothing to
// force unmount.
func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
	return container.UnmountVolumes(volumeEventLog)
}

// TmpfsMounts returns the list of tmpfs mounts
func (container *Container) TmpfsMounts() ([]Mount, error) {
	var mounts []Mount
	return mounts, nil
}

// UpdateContainer updates configuration of a container. Callers must hold a Lock on the Container.
func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error {
	resources := hostConfig.Resources
	if resources.CPUShares != 0 ||
		resources.Memory != 0 ||
		resources.NanoCPUs != 0 ||
		resources.CgroupParent != "" ||
		resources.BlkioWeight != 0 ||
		len(resources.BlkioWeightDevice) != 0 ||
		len(resources.BlkioDeviceReadBps) != 0 ||
		len(resources.BlkioDeviceWriteBps) != 0 ||
		len(resources.BlkioDeviceReadIOps) != 0 ||
		len(resources.BlkioDeviceWriteIOps) != 0 ||
		resources.CPUPeriod != 0 ||
		resources.CPUQuota != 0 ||
		resources.CPURealtimePeriod != 0 ||
		resources.CPURealtimeRuntime != 0 ||
		resources.CpusetCpus != "" ||
		resources.CpusetMems != "" ||
		len(resources.Devices) != 0 ||
		len(resources.DeviceCgroupRules) != 0 ||
		resources.DiskQuota != 0 ||
		resources.KernelMemory != 0 ||
		resources.MemoryReservation != 0 ||
		resources.MemorySwap != 0 ||
		resources.MemorySwappiness != nil ||
		resources.OomKillDisable != nil ||
		resources.PidsLimit != 0 ||
		len(resources.Ulimits) != 0 ||
		resources.CPUCount != 0 ||
		resources.CPUPercent != 0 ||
		resources.IOMaximumIOps != 0 ||
		resources.IOMaximumBandwidth != 0 {
		return fmt.Errorf("resource updating isn't supported on Windows")
	}
	// update HostConfig of container
	if hostConfig.RestartPolicy.Name != "" {
		if container.HostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
			return fmt.Errorf("Restart policy cannot be updated because AutoRemove is enabled for the container")
		}
		container.HostConfig.RestartPolicy = hostConfig.RestartPolicy
	}
	return nil
}

// BuildHostnameFile writes the container's hostname file.
func (container *Container) BuildHostnameFile() error {
	return nil
}

// EnableServiceDiscoveryOnDefaultNetwork Enable service discovery on default network
func (container *Container) EnableServiceDiscoveryOnDefaultNetwork() bool {
	return true
}

// GetMountPoints gives a platform specific transformation to types.MountPoint. Callers must hold a Container lock.
func (container *Container) GetMountPoints() []types.MountPoint {
	mountPoints := make([]types.MountPoint, 0, len(container.MountPoints))
	for _, m := range container.MountPoints {
		mountPoints = append(mountPoints, types.MountPoint{
			Type:        m.Type,
			Name:        m.Name,
			Source:      m.Path(),
			Destination: m.Destination,
			Driver:      m.Driver,
			RW:          m.RW,
		})
	}
	return mountPoints
}


text:
DROP SCHEMA  IF EXISTS report_manager_schema CASCADE;

CREATE SCHEMA report_manager_schema
  AUTHORIZATION postgres;


text:
{% extends "layout.html" %}
{% from "macros.html" import render_field, back_button %}
{% block title %}Edit Challenge{% endblock %}
{% block head %}
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

{% endblock %}
{% block content %}

            {{ back_button(challenge.name, url_for('main.challenge', group_id=challenge.group, challenge_id=challenge)) }}

    <form class="form-group {{ 'has-danger' if form.errors }}" action="" method="POST">
        {{ form.hidden_tag() }}
        {{ render_field(form.name, maxlength=30) }}
        {{ render_field(form.description) }}
        {{ render_field(form.judge_id) }}
        {{ render_field(form.date_range) }}
        {# { render_field(form.utc_end_time) } #}

<button class="btn btn-primary" type="submit">Edit</button>
    </form>

Please note all times are {{ config.DEFAULT_TIMEZONE }}

{% endblock %}
{% block scripts %}

{% endblock %}


text:
<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" src="bootstrap.min.css" />
  <link rel="stylesheet" type="text/css" src="application.css" />

Flatlander Crafted Gems

– an Angular store –

        {{product.name}}
        {{product.price | currency}}

            Description

            Specs

            Reviews

Description

{{product.description}}

Specs

Shine: {{product.shine}}

Reviews

                {{review.stars}} Stars
                {{review.body}}
                —{{review.author}}

          <form name="reviewForm" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewCtrl.addReview(product)">

              {{reviewCtrl.review.stars}} Stars
              {{reviewCtrl.review.body}}
              -{{reviewCtrl.review.author}}

Submit a Review

            <fieldset>
              <select ng-model="reviewCtrl.review.stars" ng-options="stars for stars in [5,4,3,2,1]" title="Stars">
                <option value="">Rate the Product</option>
              </select>
            </fieldset>
            <fieldset>
              <textarea ng-model="reviewCtrl.review.body" placeholder="Write a short review of the product..." title="Review"></textarea>
            </fieldset>
            <fieldset>
              <input ng-model="reviewCtrl.review.author" type="email" placeholder="jimmyDean@example.org" title="Email" />
            </fieldset>
            <fieldset>
              <input type="submit" value="Submit Review" />
            </fieldset>
          </form>


text:
#ifndef __MESOS_MODULE_AUTHORIZER_HPP__
#define __MESOS_MODULE_AUTHORIZER_HPP__

#include <mesos/module.hpp>

#include <mesos/authorizer/authorizer.hpp>

namespace mesos {
namespace modules {

template <>
inline const char* kind<mesos::Authorizer>()
{
  return "Authorizer";
}

template <>
struct Module<mesos::Authorizer> : ModuleBase
{
  Module(
      const char* _moduleApiVersion,
      const char* _mesosVersion,
      const char* _authorName,
      const char* _authorEmail,
      const char* _description,
      bool (*_compatible)(),
      mesos::Authorizer* (*_create)(const Parameters& parameters))
    : ModuleBase(
        _moduleApiVersion,
        _mesosVersion,
        mesos::modules::kind<mesos::Authorizer>(),
        _authorName,
        _authorEmail,
        _description,
        _compatible),
      create(_create) {}

  mesos::Authorizer* (*create)(const Parameters& parameters);
};

} // namespace modules {
} // namespace mesos {

#endif // __MESOS_MODULE_AUTHORIZER_HPP__


text:
function pd=angled(h)
% ANGLED: Returns the phase angles in degrees of a matrix with complex elements
%   Usage:  deg=angled(h)
%        h = complex matrix
%      deg = angle in math convention (degrees counterclockwise from "east")
pd=angle(h)*180/pi;


text:
var wordChooser = require('../lib/words');

// using nodejs's build in asserts that throw on failure
var assert = require('assert')

exports['test placeholder'] = function() {
  assert.equal(3+4, 7, 'should always pass');
}

/*
exports['test first word'] = function() {
  assert.equal(wordChooser.getAt(0), 'abbreviation', 'first word doesn\'t match');
}
*/

if (module == require.main) require('test').run(exports)


text:
package org.apache.commons.jexl3.internal;

import org.apache.commons.jexl3.JexlContext;
import org.apache.commons.jexl3.JexlFeatures;
import org.apache.commons.jexl3.JexlInfo;
import org.apache.commons.jexl3.JexlOptions;
import org.apache.commons.jexl3.JexlEngine;
import org.apache.commons.jexl3.JexlScript;
import org.apache.commons.jexl3.JexlExpression;
import org.apache.commons.jexl3.parser.ASTJexlScript;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
 *
A JexlScript implementation.

 * @since 1.1
 */
public class Script implements JexlScript, JexlExpression {
    /**
     * The engine for this expression.
     */
    protected final Engine jexl;
    /**
     * Original expression stripped from leading and trailing spaces.
     */
    protected final String source;
    /**
     * The resulting AST we can interpret.
     */
    protected final ASTJexlScript script;
    /**
     * The engine version (as class loader change count) that last evaluated this script.
     */
    protected int version;

    /**
     * @return the script AST
     */
    protected ASTJexlScript getScript() {
        return script;
    }

    /**
     * Do not let this be generally instantiated with a 'new'.
     *
     * @param engine the interpreter to evaluate the expression
     * @param expr   the expression source.
     * @param ref    the parsed expression.
     */
    protected Script(final Engine engine, final String expr, final ASTJexlScript ref) {
        jexl = engine;
        source = expr;
        script = ref;
        version = jexl.getUberspect().getVersion();
    }

    /**
     * Checks that this script cached methods (wrt introspection) matches the engine version.
     *

     * If the engine class loader has changed since we last evaluated this script, the script local cache
     * is invalidated to drop references to obsolete methods. It is not strictly necessary since the tryExecute
     * will fail because the class won't match but it seems cleaner nevertheless.
     *

     */
    protected void checkCacheVersion() {
        final int uberVersion = jexl.getUberspect().getVersion();
        if (version != uberVersion) {
            // version 0 of the uberSpect is an illusion due to order of construction; no need to clear cache
            if (version > 0) {
                script.clearCache();
            }
            version = uberVersion;
        }
    }

    /**
     * Creates this script frame for evaluation.
     * @param args the arguments to bind to parameters
     * @return the frame (may be null)
     */
    protected Frame createFrame(final Object[] args) {
        return script.createFrame(args);
    }

    /**
     * Creates this script interpreter.
     * @param context the context
     * @param frame the calling frame
     * @return  the interpreter
     */
    protected Interpreter createInterpreter(final JexlContext context, final Frame frame) {
        return createInterpreter(context, frame, null);
    }

    /**
     * Creates this script interpreter.
     * @param context the context
     * @param frame the calling frame
     * @param options the interpreter options
     * @return  the interpreter
     */
    protected Interpreter createInterpreter(final JexlContext context, final Frame frame, final JexlOptions options) {
        return jexl.createInterpreter(context, frame, options != null? options : jexl.evalOptions(script, context));
    }

    /**
     * @return the engine that created this script
     */
    public JexlEngine getEngine() {
        return jexl;
    }

    @Override
    public String getSourceText() {
        return source;
    }

    @Override
    public String getParsedText() {
        return getParsedText(2);
    }

    @Override
    public String getParsedText(final int indent) {
        final Debugger debug = new Debugger();
        debug.outputPragmas(true).indentation(indent).debug(script, false);
        return debug.toString();
    }

    @Override
    public String toString() {
        CharSequence src = source;
        if (src == null) {
            final Debugger debug = new Debugger();
            debug.debug(script, false);
            src = debug.toString();
        }
        return src.toString();
    }

    @Override
    public int hashCode() {
        // CSOFF: Magic number
        int hash = 17;
        hash = 31 * hash + (this.jexl != null ? this.jexl.hashCode() : 0);
        hash = 31 * hash + (this.source != null ? this.source.hashCode() : 0);
        return hash;
        // CSON: Magic number
    }

    @Override
    public boolean equals(final Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Script other = (Script) obj;
        if (this.jexl != other.jexl) {
            return false;
        }
        if (!Objects.equals(this.source, other.source)) {
            return false;
        }
        return true;
    }

    @Override
    public Object evaluate(final JexlContext context) {
        return execute(context);
    }

    @Override
    public Object execute(final JexlContext context) {
        checkCacheVersion();
        final Frame frame = createFrame(null);
        final Interpreter interpreter = createInterpreter(context, frame);
        return interpreter.interpret(script);
    }

    @Override
    public Object execute(final JexlContext context, final Object... args) {
        checkCacheVersion();
        final Frame frame = createFrame(args != null && args.length > 0 ? args : null);
        final Interpreter interpreter = createInterpreter(context, frame);
        return interpreter.interpret(script);
    }

    @Override
    public JexlScript curry(final Object... args) {
        final String[] parms = script.getParameters();
        if (parms == null || parms.length == 0) {
            return this;
        }
        return new Closure(this, args);
    }

    @Override
    public String[] getParameters() {
        return script.getParameters();
    }

    @Override
    public String[] getUnboundParameters() {
        return getParameters();
    }

    @Override
    public String[] getLocalVariables() {
        return script.getLocalVariables();
    }

    /**
     * Gets this script captured variable, i.e. symbols captured from outer scopes.
     * @return the captured variable names
     */
    public String[] getCapturedVariables() {
        return script.getCapturedVariables();
    }

    /**
     * @return the info
     */
    public JexlInfo getInfo() {
        return script.jexlInfo();
    }

    /**
     * @return the script features
     */
    public JexlFeatures getFeatures() {
        return script.getFeatures();
    }

    /**
     * Gets this script variables.
     *
Note that since variables can be in an ant-ish form (ie foo.bar.quux), each variable is returned as
     * a list of strings where each entry is a fragment of the variable ({"foo", "bar", "quux"} in the example.

     * @return the variables or null
     */
    @Override
    public Set<List<String>> getVariables() {
        return jexl.getVariables(script);
    }

    /**
     * Get this script pragmas
     *
Pragma keys are ant-ish variables, their values are scalar literals..
     * @return the pragmas
     */
    @Override
    public Map<String, Object> getPragmas() {
        return script.getPragmas();
    }

    /**
     * Creates a Callable from this script.
     *
This allows to submit it to an executor pool and provides support for asynchronous calls.

     *
The interpreter will handle interruption/cancellation gracefully if needed.

     * @param context the context
     * @return the callable
     */
    @Override
    public Callable callable(final JexlContext context) {
        return callable(context, (Object[]) null);
    }

    /**
     * Creates a Callable from this script.
     *
This allows to submit it to an executor pool and provides support for asynchronous calls.

     *
The interpreter will handle interruption/cancellation gracefully if needed.

     * @param context the context
     * @param args    the script arguments
     * @return the callable
     */
    @Override
    public Callable callable(final JexlContext context, final Object... args) {
        return new Callable(createInterpreter(context, script.createFrame(args)));
    }

    /**
     * Implements the Future and Callable interfaces to help delegation.
     */
    public class Callable implements java.util.concurrent.Callable<Object> {
        /** The actual interpreter. */
        protected final Interpreter interpreter;
        /** Use interpreter as marker for not having run. */
        protected volatile Object result;

        /**
         * The base constructor.
         * @param intrprtr the interpreter to use
         */
        protected Callable(final Interpreter intrprtr) {
            this.interpreter = intrprtr;
            this.result = intrprtr;
        }

        /**
         * Run the interpreter.
         * @return the evaluation result
         */
        protected Object interpret() {
            return interpreter.interpret(script);
        }

        @Override
        public Object call() throws Exception {
            synchronized(this) {
                if (result == interpreter) {
                    checkCacheVersion();
                    result = interpret();
                }
                return result;
            }
        }

        /**
         * Soft cancel the execution.
         * @return true if cancel was successful, false otherwise
         */
        public boolean cancel() {
            return interpreter.cancel();
        }

        /**
         * @return true if evaluation was cancelled, false otherwise
         */
        public boolean isCancelled() {
            return interpreter.isCancelled();
        }

        /**
         * @return true if interruption will throw a JexlException.Cancel, false otherwise
         */
        public boolean isCancellable() {
            return interpreter.isCancellable();
        }
    }
}


text:
export default class User {
  constructor(fields) {
    this.id = fields.id
    this.email = fields.email
    this.password = fields.password
    this.role = fields.role
    this.firstName = fields.firstName
    this.lastName = fields.lastName
  }
}


text:
    #include <regex>

    namespace regex_namespace = std;
#else
    #include <boost/regex.hpp>

    namespace regex_namespace = boost;
#endif

#include <cctype>
#include <cassert>
#include <algorithm>

namespace reflectionzeug
{

namespace util
{

template <>
char fromString<char>(const std::string & string)
{
    std::stringstream stream(string);
    int value;
    stream >> value;
    return static_cast<char>(value);
}

template <>
unsigned char fromString<unsigned char>(const std::string & string)
{
    std::stringstream stream(string);
    unsigned int value;
    stream >> value;
    return static_cast<unsigned char>(value);
}

template <>
std::string toString<char>(const char & value)
{
    std::stringstream stream;
    stream << static_cast<int>(value);
    return stream.str();
}

template <>
std::string toString<unsigned char>(const unsigned char & value)
{
    std::stringstream stream;
    stream << static_cast<unsigned int>(value);
    return stream.str();
}

bool matchesRegex(const std::string & string, const std::string & regex)
{
    return regex_namespace::regex_match(string, regex_namespace::regex(regex));
}

std::vector<std::string> extract(const std::string & string, const std::string & regex)
{
    std::vector<std::string> values;

    regex_namespace::smatch matchResults;

    std::string s = string;
    while (regex_namespace::regex_search(s, matchResults, regex_namespace::regex(regex)))
    {
        values.push_back(matchResults[0]);
        s = matchResults.suffix().str();
    };

    return values;
}

std::string trim(const std::string & string, bool enclosed)
{
    const regex_namespace::regex regex(enclosed ? "\\s+" : "(^\\s+|\\s+$)");

    return regex_namespace::regex_replace(string, regex, "");
}

std::vector<std::string> splitArray(size_t size, const std::string & string)
{
    std::string regexString = "\\s*\\(";
    for (size_t i = 0; i < size - 1; ++i)
        regexString.append("([^,]*),");
    regexString.append("([^,]*)\\)\\s*");

    regex_namespace::smatch match;
    regex_namespace::regex regex(regexString);

    if (!regex_namespace::regex_match(string, match, regex))
        return {};

    std::vector<std::string> result;
    for (size_t i = 1; i < match.size(); ++i)
        result.push_back(trim(match[i].str(), false));

    assert(result.size() == size);
    return result;
}

std::vector<std::string> split(const std::string & input, char delimiter)
{
    std::vector<std::string> result;
    result.push_back(std::string());
    for (const char & c : input)
	{
		if (c == delimiter)
		{
			result.push_back(std::string());
			continue;
		}

		result.back().push_back(c);
	}
	return result;
}

} // namespace util

} // namespace reflectionzeug


text:
webbpsf\_ext.opds.plot\_opd
===========================

.. currentmodule:: webbpsf_ext.opds

.. autofunction:: plot_opd


text:
package vnmr.ui.shuf;

import vnmr.util.*;

import java.awt.*;
import java.util.*;
import javax.swing.*;

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

 * Summary: Holds one command/macro for DB
 *
 * @author  Glenn Sullivan
 *

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

public class CommandDefinition {
    String commandName=null;
    Hashtable attrList; // List of attributes besides the two above.

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

     * Summary: Constructor, Save info for one command/macro.
     *
     * Details:
     *	Retrieve the name from the attr list and save in CommandName.
     *	Remove name from the attr list, then save whats left in
     *  the list in attrList.
     *

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

    public CommandDefinition(Hashtable list, String type) {
	attrList = list;

	if(!attrList.containsKey("name")) {
	    Messages.postError("All command/macro definitions " +
                               "MUST have a 'name' attribute!");
	    return;
	}

	commandName = (String)attrList.get("name");

	// We needed name separate, so now get it out of the attrList.
	attrList.remove("name");

	// Now put the type into the hashtable as a normal attribute
	attrList.put("exectype", type);
    }

    public String getcommandName() {
	return commandName;
    }

    public Hashtable getattrList() {
	return attrList;
    }

    public String toString(){
    	return commandName+" "+attrList.toString();
    }
}


text:
<?php

require_once __DIR__.'/../Base.php';

use Kanboard\Core\DateParser;
use Kanboard\Model\ProjectModel;
use Kanboard\Model\TaskCreationModel;
use Kanboard\Model\TaskFinderModel;
use Kanboard\Model\TaskModel;
use Kanboard\Model\TaskRecurrenceModel;
use Kanboard\Model\TaskTagModel;

class TaskRecurrenceModelTest extends Base
{
    public function testRecurrenceSettings()
    {
        $taskRecurrenceModel = new TaskRecurrenceModel($this->container);

        $statuses = $taskRecurrenceModel->getRecurrenceStatusList();
        $this->assertCount(2, $statuses);
        $this->assertArrayHasKey(TaskModel::RECURRING_STATUS_NONE, $statuses);
        $this->assertArrayHasKey(TaskModel::RECURRING_STATUS_PENDING, $statuses);
        $this->assertArrayNotHasKey(TaskModel::RECURRING_STATUS_PROCESSED, $statuses);

        $triggers = $taskRecurrenceModel->getRecurrenceTriggerList();
        $this->assertCount(3, $triggers);
        $this->assertArrayHasKey(TaskModel::RECURRING_TRIGGER_FIRST_COLUMN, $triggers);
        $this->assertArrayHasKey(TaskModel::RECURRING_TRIGGER_LAST_COLUMN, $triggers);
        $this->assertArrayHasKey(TaskModel::RECURRING_TRIGGER_CLOSE, $triggers);

        $dates = $taskRecurrenceModel->getRecurrenceBasedateList();
        $this->assertCount(2, $dates);
        $this->assertArrayHasKey(TaskModel::RECURRING_BASEDATE_DUEDATE, $dates);
        $this->assertArrayHasKey(TaskModel::RECURRING_BASEDATE_TRIGGERDATE, $dates);

        $timeframes = $taskRecurrenceModel->getRecurrenceTimeframeList();
        $this->assertCount(3, $timeframes);
        $this->assertArrayHasKey(TaskModel::RECURRING_TIMEFRAME_DAYS, $timeframes);
        $this->assertArrayHasKey(TaskModel::RECURRING_TIMEFRAME_MONTHS, $timeframes);
        $this->assertArrayHasKey(TaskModel::RECURRING_TIMEFRAME_YEARS, $timeframes);
    }

    public function testCalculateRecurringTaskDueDate()
    {
        $taskRecurrenceModel = new TaskRecurrenceModel($this->container);

        $values = array('date_due' => 0);
        $taskRecurrenceModel->calculateRecurringTaskDueDate($values);
        $this->assertEquals(0, $values['date_due']);

        $values = array('date_due' => 0, 'recurrence_factor' => 0, 'recurrence_basedate' => TaskModel::RECURRING_BASEDATE_TRIGGERDATE, 'recurrence_timeframe' => TaskModel::RECURRING_TIMEFRAME_DAYS);
        $taskRecurrenceModel->calculateRecurringTaskDueDate($values);
        $this->assertEquals(0, $values['date_due']);

        $values = array('date_due' => 1431291376, 'recurrence_factor' => 1, 'recurrence_basedate' => TaskModel::RECURRING_BASEDATE_TRIGGERDATE, 'recurrence_timeframe' => TaskModel::RECURRING_TIMEFRAME_DAYS);
        $taskRecurrenceModel->calculateRecurringTaskDueDate($values);
        $this->assertEquals(time() + 86400, $values['date_due'], '', 1);

        $values = array('date_due' => 1431291376, 'recurrence_factor' => -2, 'recurrence_basedate' => TaskModel::RECURRING_BASEDATE_TRIGGERDATE, 'recurrence_timeframe' => TaskModel::RECURRING_TIMEFRAME_DAYS);
        $taskRecurrenceModel->calculateRecurringTaskDueDate($values);
        $this->assertEquals(time() - 2 * 86400, $values['date_due'], '', 1);

        $values = array('date_due' => 1431291376, 'recurrence_factor' => 1, 'recurrence_basedate' => TaskModel::RECURRING_BASEDATE_DUEDATE, 'recurrence_timeframe' => TaskModel::RECURRING_TIMEFRAME_DAYS);
        $taskRecurrenceModel->calculateRecurringTaskDueDate($values);
        $this->assertEquals(1431291376 + 86400, $values['date_due'], '', 1);

        $values = array('date_due' => 1431291376, 'recurrence_factor' => -1, 'recurrence_basedate' => TaskModel::RECURRING_BASEDATE_DUEDATE, 'recurrence_timeframe' => TaskModel::RECURRING_TIMEFRAME_DAYS);
        $taskRecurrenceModel->calculateRecurringTaskDueDate($values);
        $this->assertEquals(1431291376 - 86400, $values['date_due'], '', 1);

        $values = array('date_due' => 1431291376, 'recurrence_factor' => 2, 'recurrence_basedate' => TaskModel::RECURRING_BASEDATE_DUEDATE, 'recurrence_timeframe' => TaskModel::RECURRING_TIMEFRAME_MONTHS);
        $taskRecurrenceModel->calculateRecurringTaskDueDate($values);
        $this->assertEquals(1436561776, $values['date_due'], '', 1);

        $values = array('date_due' => 1431291376, 'recurrence_factor' => 2, 'recurrence_basedate' => TaskModel::RECURRING_BASEDATE_DUEDATE, 'recurrence_timeframe' => TaskModel::RECURRING_TIMEFRAME_YEARS);
        $taskRecurrenceModel->calculateRecurringTaskDueDate($values);
        $this->assertEquals(1494449776, $values['date_due'], '', 1);
    }

    public function testDuplicateRecurringTask()
    {
        $taskRecurrenceModel = new TaskRecurrenceModel($this->container);
        $taskCreationModel = new TaskCreationModel($this->container);
        $taskFinderModel = new TaskFinderModel($this->container);
        $projectModel = new ProjectModel($this->container);
        $dateParser = new DateParser($this->container);
        $taskTagModel = new TaskTagModel($this->container);

        $this->assertEquals(1, $projectModel->create(array('name' => 'test1')));

        $this->assertEquals(1, $taskCreationModel->create(array(
            'title' => 'test',
            'project_id' => 1,
            'date_due' => 1436561776,
            'recurrence_status' => TaskModel::RECURRING_STATUS_PENDING,
            'recurrence_trigger' => TaskModel::RECURRING_TRIGGER_CLOSE,
            'recurrence_factor' => 2,
            'recurrence_timeframe' => TaskModel::RECURRING_TIMEFRAME_DAYS,
            'recurrence_basedate' => TaskModel::RECURRING_BASEDATE_TRIGGERDATE,
            'tags' => array('T1', 'T2'),
        )));

        $this->assertEquals(2, $taskRecurrenceModel->duplicateRecurringTask(1));

        $task = $taskFinderModel->getById(1);
        $this->assertNotEmpty($task);
        $this->assertEquals(TaskModel::RECURRING_STATUS_PROCESSED, $task['recurrence_status']);
        $this->assertEquals(2, $task['recurrence_child']);
        $this->assertEquals(1436561776, $task['date_due'], '', 2);

        $task = $taskFinderModel->getById(2);
        $this->assertNotEmpty($task);
        $this->assertEquals(TaskModel::RECURRING_STATUS_PENDING, $task['recurrence_status']);
        $this->assertEquals(TaskModel::RECURRING_TRIGGER_CLOSE, $task['recurrence_trigger']);
        $this->assertEquals(TaskModel::RECURRING_TIMEFRAME_DAYS, $task['recurrence_timeframe']);
        $this->assertEquals(TaskModel::RECURRING_BASEDATE_TRIGGERDATE, $task['recurrence_basedate']);
        $this->assertEquals(1, $task['recurrence_parent']);
        $this->assertEquals(2, $task['recurrence_factor']);
        $this->assertEquals(strtotime('+2 days'), $task['date_due'], '', 2);

        $tags = $taskTagModel->getList(2);
        $this->assertCount(2, $tags);
        $this->assertArrayHasKey(1, $tags);
        $this->assertArrayHasKey(2, $tags);
    }
}


text:
package com.polidea.rxandroidble2.internal.connection;

import com.polidea.rxandroidble2.ConnectionSetup;
import com.polidea.rxandroidble2.RxBleConnection;

import io.reactivex.Observable;

public interface Connector {

    Observable<RxBleConnection> prepareConnection(ConnectionSetup autoConnect);
}


text:
package ucar.nc2.iosp.hdf5;

import ucar.ma2.DataType;
import ucar.ma2.Section;
import ucar.nc2.iosp.LayoutTiled;
import ucar.nc2.iosp.Layout;
import java.io.IOException;

/**
 * Iterator to read/write subsets of an array.
 * This calculates byte offsets for HD5 chunked datasets.
 * Assumes that the data is stored in chunks, indexed by a Btree.
 * for unfiltered data only
 *
 * @author caron
 */
public class H5tiledLayout implements Layout {
  private LayoutTiled delegate;

  private Section want;
  private int[] chunkSize; // from the StorageLayout message (exclude the elemSize)
  private int elemSize; // last dimension of the StorageLayout message

  private boolean debug;

  /**
   * Constructor.
   * This is for HDF5 chunked data storage. The data is read by chunk, for efficency.
   *
   * @param vinfo the vinfo object for this variable
   * @param dtype type of data. may be different from v2.
   * @param wantSection the wanted section of data, contains a List of Range objects, must be complete
   * @throws java.io.IOException on io error
   */
  public H5tiledLayout(H5header.Vinfo vinfo, DataType dtype, Section wantSection) throws IOException {
    assert vinfo.isChunked;
    assert vinfo.btree != null;

    // we have to translate the want section into the same rank as the storageSize, in order to be able to call
    // Section.intersect(). It appears that storageSize (actually msl.chunkSize) may have an extra dimension, relative
    // to the Variable.
    if ((dtype == DataType.CHAR) && (wantSection.getRank() < vinfo.storageSize.length)) {
      this.want = Section.builder().appendRanges(wantSection.getRanges()).appendRange(1).build();
    } else {
      this.want = wantSection;
    }

    // one less chunk dimension, except in the case of char
    int nChunkDims = (dtype == DataType.CHAR) ? vinfo.storageSize.length : vinfo.storageSize.length - 1;
    this.chunkSize = new int[nChunkDims];
    System.arraycopy(vinfo.storageSize, 0, chunkSize, 0, nChunkDims);

    this.elemSize = vinfo.storageSize[vinfo.storageSize.length - 1]; // last one is always the elements size
    if (debug)
      System.out.println(" H5tiledLayout: " + this);

    // create the data chunk iterator
    LayoutTiled.DataChunkIterator iter = vinfo.btree.getDataChunkIteratorNoFilter(this.want, nChunkDims);
    delegate = new LayoutTiled(iter, chunkSize, elemSize, this.want);
  }

  public long getTotalNelems() {
    return delegate.getTotalNelems();
  }

  public int getElemSize() {
    return delegate.getElemSize();
  }

  public boolean hasNext() {
    return delegate.hasNext();
  }

  public Chunk next() {
    return delegate.next();
  }

  public String toString() {
    StringBuilder sbuff = new StringBuilder();
    sbuff.append("want=").append(want).append("; ");
    sbuff.append("chunkSize=[");
    for (int i = 0; i < chunkSize.length; i++) {
      if (i > 0)
        sbuff.append(",");
      sbuff.append(chunkSize[i]);
    }
    sbuff.append("] totalNelems=").append(getTotalNelems());
    sbuff.append(" elemSize=").append(elemSize);
    return sbuff.toString();
  }

}


text:
/*
 * winston-mixlib-log.js: Tests for instances of the Mixlib Log Transport
 *
 * (C) 2012 Josh Toft
 * MIT LICENSE
 */

var path = require('path'),
    vows = require('vows'),
    assert = require('assert'),
    winston = require('winston'),
    helpers = require('winston/test/helpers'),
    transport = require('winston/test/transports/transport'),
    MixlibLog = require('../lib/winston-mixlib-log').MixlibLog

vows.describe('winston-mixlib-log').addBatch({
  "An instance of the Mixlib Log Transport": transport(MixlibLog, {})
}).export(module);


text:
#!/bin/bash
#
# seafile-server-installer/seafile-server-ubuntu-16-04-amd64
#
# Copyright 2015, Alexander Jackson <alexander.jackson@seafile.de>
# Copyright 2016, Zheng Xie <xie.zheng@seafile.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#
usage() {
   echo "Usage: $0 [-u <admin_email>] [-d <full_domain>] [-p <admin_pass>] [-s <seafile_version>]"
   echo "       admin_email is used to login seafile server, i.e. admin@seafile.local"
   echo "       full_domain is the full qualified domain name, i.e. mybox.southeastasia.cloudapp.azure.com"
   echo "       admin_pass is optional, if you do not specify it, a random string is generated"
   echo "       seafile_version is optional, default 6.1.1 is used"
   exit 1
}

if [[ $HOME == "" ]]; then
    export HOME=/root
fi

if [[ $SEAFILE_DEBUG != "" ]]; then
    set -x
fi
set -e

SEAFILE_VERSION="6.1.1"
SEAFILE_PRO=0
ZPOOL_NAME="MyDiskPool"
ZFS_DATASET="MyData"

while getopts ":u:p:d:s:" o; do
    case "${o}" in
     u)
       SEAFILE_ADMIN=${OPTARG}
       ;;
     p)
       SEAFILE_ADMIN_PW=${OPTARG}
       ;;
     d)
       IP_OR_DOMAIN=${OPTARG}
       ;;
     s)
       SEAFILE_VERSION=${OPTARG}
       ;;
     *)
       usage
       ;;
    esac
done
shift $((OPTIND-1))
if [ -z "${SEAFILE_ADMIN}" ] || [ -z "${IP_OR_DOMAIN}" ]; then
   usage
fi

clear
cat <<EOF

  This script installs the community edition of the Seafile Server on a Ubuntu 16.04 (Xenial) 64bit
  - Newest Seafile server version, MariaDB, Memcached, NGINX -
  -----------------------------------------------------------------

  This installer is meant to run on a freshly installed machine
  only. If you run it on a production server things can and
  probably will go terrible wrong and you will loose valuable
  data!

  For questions or suggestions please contact us at
  support@seafile.com

  -----------------------------------------------------------------

  Possible options:
  1 = Seafile Community (Free) Edition (CE)
  2 = Seafile Professional Edition (PRO)

EOF

if [[ ${SEAFILE_PRO} == "" ]]; then
    PS3="Which Seafile version would you like to install? "
    select SEAFILE_SERVER_VERSION in CE PRO ABORT; do
        case "${SEAFILE_SERVER_VERSION}" in
            ABORT)
                echo "Aborting"
                break
                ;;
            "")
                echo "$REPLY: Wrong value. Select 1 or 2."
                ;;
            *)
                if [[ ${SEAFILE_SERVER_VERSION} = "PRO" ]]; then
                    SEAFILE_PRO=1
                else
                    SEAFILE_PRO=0
                fi
                break
        esac
    done
fi

is_pro() {
    if [[ "$SEAFILE_PRO" == "1" ]]; then
        return 0
    else
        return 1
    fi
}

echo
if is_pro; then
    echo "This script will install Seafile Professional Edition for you."
else
    echo "This script will install Seafile Community Edition for you."
fi
echo

# -------------------------------------------
# Vars
# -------------------------------------------

TIME_ZONE=Asia/Shanghai

if is_pro; then
    SEAFILE_SERVER_PACKAGE=seafile-pro-server_${SEAFILE_VERSION}_x86-64.tar.gz
    if [[ ! -e /opt/$SEAFILE_SERVER_PACKAGE ]]; then
        echo
        echo "You must download \"$SEAFILE_SERVER_PACKAGE\" to the /opt/ folder before running this script!"
        echo
        exit 1
    fi
    INSTALLPATH=/opt/seafile/seafile-pro-server-${SEAFILE_VERSION}/
else
    SEAFILE_SERVER_PACKAGE=seafile-server_${SEAFILE_VERSION}_x86-64.tar.gz
    SEAFILE_SERVER_PACKAGE_URL=https://download.seadrive.org/${SEAFILE_SERVER_PACKAGE}
    INSTALLPATH=/opt/seafile/seafile-server-${SEAFILE_VERSION}/
fi

# -------------------------------------------
# Ensure we are running the installer as root
# -------------------------------------------
if [[ $EUID -ne 0 ]]; then
  echo "  Aborting because you are not root" ; exit 1
fi

# -------------------------------------------
# Abort if directory /opt/seafile/ exists
# -------------------------------------------
if [[ -d "/opt/seafile/" ]] ;
then
  echo "  Aborting because directory /opt/seafile/ already exist" ; exit 1
fi

# -------------------------------------------
# Additional requirements
# -------------------------------------------
apt-get update
apt-get install -y python2.7 sudo python-pip python-setuptools python-imaging python-mysqldb python-ldap python-urllib3 \
openjdk-8-jre memcached python-memcache pwgen curl openssl poppler-utils libpython2.7 libreoffice \
libreoffice-script-provider-python ttf-wqy-microhei ttf-wqy-zenhei xfonts-wqy nginx python-requests zfs

# -------------------------------------------
# Create seafile-data with the help of ZFS
# -------------------------------------------
zpool create -f ${ZPOOL_NAME} /dev/sdc
zpool set cachefile=/etc/zfs/zpool.cache ${ZPOOL_NAME}
zfs create ${ZPOOL_NAME}/${ZFS_DATASET}
zfs set compression=gzip ${ZPOOL_NAME}/${ZFS_DATASET}

rm /etc/nginx/sites-enabled/*

cat > /etc/nginx/sites-available/seafile.conf <<'EOF'
server {
      listen 80;
      server_name  "${SEAFILE_ADMIN}";

      proxy_set_header X-Forwarded-For $remote_addr;

      location / {
          fastcgi_pass    127.0.0.1:8000;
          fastcgi_param   SCRIPT_FILENAME     $document_root$fastcgi_script_name;
          fastcgi_param   PATH_INFO           $fastcgi_script_name;
          fastcgi_param   SERVER_PROTOCOL     $server_protocol;
          fastcgi_param   QUERY_STRING        $query_string;
          fastcgi_param   REQUEST_METHOD      $request_method;
          fastcgi_param   CONTENT_TYPE        $content_type;
          fastcgi_param   CONTENT_LENGTH      $content_length;
          fastcgi_param   SERVER_ADDR         $server_addr;
          fastcgi_param   SERVER_PORT         $server_port;
          fastcgi_param   SERVER_NAME         $server_name;
          fastcgi_param   REMOTE_ADDR         $remote_addr;

          access_log      /var/log/nginx/seahub.access.log;
          error_log       /var/log/nginx/seahub.error.log;
      }
      location /seafhttp {
          rewrite ^/seafhttp(.*)$ $1 break;
          proxy_pass http://127.0.0.1:8082;
          client_max_body_size 0;
          proxy_connect_timeout  36000s;
          proxy_read_timeout  36000s;
      }
      location /media {
          root /opt/seafile/seafile-server-latest/seahub;
      }
     location /seafdav {
        fastcgi_pass    127.0.0.1:8080;
        fastcgi_param   SCRIPT_FILENAME     $document_root$fastcgi_script_name;
        fastcgi_param   PATH_INFO           $fastcgi_script_name;
        fastcgi_param   SERVER_PROTOCOL     $server_protocol;
        fastcgi_param   QUERY_STRING        $query_string;
        fastcgi_param   REQUEST_METHOD      $request_method;
        fastcgi_param   CONTENT_TYPE        $content_type;
        fastcgi_param   CONTENT_LENGTH      $content_length;
        fastcgi_param   SERVER_ADDR         $server_addr;
        fastcgi_param   SERVER_PORT         $server_port;
        fastcgi_param   SERVER_NAME         $server_name;
        fastcgi_param   REMOTE_ADDR         $remote_addr;

        client_max_body_size 0;

        access_log      /var/log/nginx/seafdav.access.log;
        error_log       /var/log/nginx/seafdav.error.log;
    }
}
EOF

ln -sf /etc/nginx/sites-available/seafile.conf /etc/nginx/sites-enabled/seafile.conf

service nginx restart

# -------------------------------------------
# MariaDB
# -------------------------------------------
if [[ -f "/root/.my.cnf" ]] ;
then
  echo "MariaDB installed before, skip this part"
  SQLROOTPW=`sed -n 's/password=//p' /root/.my.cnf`
else
  DEBIAN_FRONTEND=noninteractive apt-get install -y mariadb-server

  SQLROOTPW=$(pwgen)

  mysqladmin -u root password $SQLROOTPW

  cat > /root/.my.cnf <<EOF
[client]
user=root
password=$SQLROOTPW
EOF

  chmod 600 /root/.my.cnf
fi

# -------------------------------------------
# Seafile init script
# -------------------------------------------
cat > /etc/init.d/seafile-server <<'EOF'
#!/bin/bash
### BEGIN INIT INFO
# Provides:          seafile-server
# Required-Start:    $remote_fs $syslog mysql
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Seafile server
# Description:       Start Seafile server
### END INIT INFO

# Author: Alexander Jackson <alexander.jackson@seafile.com.de>

# Change the value of "seafile_dir" to your path of seafile installation
seafile_dir=/opt/seafile
script_path=${seafile_dir}/seafile-server-latest
seafile_init_log=${seafile_dir}/logs/seafile.init.log
seahub_init_log=${seafile_dir}/logs/seahub.init.log

# Change the value of fastcgi to true if fastcgi is to be used
fastcgi=true
# Set the port of fastcgi, default is 8000. Change it if you need different.
fastcgi_port=8000

case "$1" in
        start)
                ${script_path}/seafile.sh start >> ${seafile_init_log}
                if [  $fastcgi = true ];
                then
                        ${script_path}/seahub.sh start-fastcgi ${fastcgi_port} >> ${seahub_init_log}
                else
                        ${script_path}/seahub.sh start >> ${seahub_init_log}
                fi
        ;;
        restart)
                ${script_path}/seafile.sh restart >> ${seafile_init_log}
                if [  $fastcgi = true ];
                then
                        ${script_path}/seahub.sh restart-fastcgi ${fastcgi_port} >> ${seahub_init_log}
                else
                        ${script_path}/seahub.sh restart >> ${seahub_init_log}
                fi
        ;;
        stop)
                ${script_path}/seafile.sh $1 >> ${seafile_init_log}
                ${script_path}/seahub.sh $1 >> ${seahub_init_log}
        ;;
        *)
                echo "Usage: /etc/init.d/seafile-server {start|stop|restart}"
                exit 1
        ;;
esac
EOF

chmod +x /etc/init.d/seafile-server
update-rc.d seafile-server defaults

# -------------------------------------------
# Seafile
# -------------------------------------------
mkdir -p /opt/seafile/installed
cd /opt/seafile/
if ! is_pro && [[ ! -e /opt/${SEAFILE_SERVER_PACKAGE} ]]; then
    curl -OL ${SEAFILE_SERVER_PACKAGE_URL}
else
    cp /opt/${SEAFILE_SERVER_PACKAGE} .
fi
tar xzf ${SEAFILE_SERVER_PACKAGE}

mv ${SEAFILE_SERVER_PACKAGE} installed

# -------------------------------------------
# Seafile DB
# -------------------------------------------
if [[ -f "/opt/seafile.my.cnf" ]] ;
then
  echo "MariaDB installed before, skip this part"
  SQLSEAFILEPW=`sed -n 's/password=//p' /opt/seafile.my.cnf`
else
  SQLSEAFILEPW=$(pwgen)

  cat > /opt/seafile.my.cnf <<EOF
[client]
user=seafile
password=$SQLSEAFILEPW
EOF

  chmod 600 /opt/seafile.my.cnf
fi

# -------------------------------------------
# Go to /opt/seafile/seafile-pro-server-${SEAFILE_VERSION}
# -------------------------------------------
cd $INSTALLPATH

# -------------------------------------------
# Vars - Don't touch these unless you really know what you are doing!
# -------------------------------------------
TOPDIR=$(dirname "${INSTALLPATH}")
DEFAULT_CONF_DIR=${TOPDIR}/conf

if [[ ! -e /${ZPOOL_NAME}/${ZFS_DATASET}/seafile-data ]]; then
   SEAFILE_DATA_DIR=/${ZPOOL_NAME}/${ZFS_DATASET}/seafile-data
else
   SEAFILE_DATA_DIR=/${ZPOOL_NAME}/${ZFS_DATASET}/seafile-data`date +%Y%m%d%H%M%S`
fi
DEST_SETTINGS_PY=${TOPDIR}/conf/seahub_settings.py

mkdir -p ${DEFAULT_CONF_DIR}

# -------------------------------------------
# Create ccnet, seafile, seahub conf using setup script
# -------------------------------------------

./setup-seafile-mysql.sh auto -u seafile -w ${SQLSEAFILEPW} -r ${SQLROOTPW} -d $SEAFILE_DATA_DIR

# -------------------------------------------
# Configure Seafile WebDAV Server(SeafDAV)
# -------------------------------------------
sed -i 's/enabled = .*/enabled = true/' ${DEFAULT_CONF_DIR}/seafdav.conf
sed -i 's/fastcgi = .*/fastcgi = true/' ${DEFAULT_CONF_DIR}/seafdav.conf
sed -i 's/share_name = .*/share_name = \/seafdav/' ${DEFAULT_CONF_DIR}/seafdav.conf

# -------------------------------------------
# Configuring seahub_settings.py
# -------------------------------------------
cat >> ${DEST_SETTINGS_PY} <<EOF

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
    'LOCATION': '127.0.0.1:11211',
    }
}

# EMAIL_USE_TLS                       = False
# EMAIL_HOST                          = 'localhost'
# EMAIL_HOST_USER                     = ''
# EMAIL_HOST_PASSWORD                 = ''
# EMAIL_PORT                          = '25'
# DEFAULT_FROM_EMAIL                  = EMAIL_HOST_USER
# SERVER_EMAIL                        = EMAIL_HOST_USER

TIME_ZONE                           = '${TIME_ZONE}'
SITE_BASE                           = 'http://${IP_OR_DOMAIN}'
SITE_NAME                           = 'Seafile Server'
SITE_TITLE                          = 'Seafile Server'
SITE_ROOT                           = '/'
ENABLE_SIGNUP                       = False
ACTIVATE_AFTER_REGISTRATION         = False
SEND_EMAIL_ON_ADDING_SYSTEM_MEMBER  = True
SEND_EMAIL_ON_RESETTING_USER_PASSWD = True
CLOUD_MODE                          = False
FILE_PREVIEW_MAX_SIZE               = 30 * 1024 * 1024
SESSION_COOKIE_AGE                  = 60 * 60 * 24 * 7 * 2
SESSION_SAVE_EVERY_REQUEST          = False
SESSION_EXPIRE_AT_BROWSER_CLOSE     = False

FILE_SERVER_ROOT                    = 'http://${IP_OR_DOMAIN}/seafhttp'
EOF

# -------------------------------------------
# Backup check_init_admin.py befor applying changes
# -------------------------------------------
cp ${INSTALLPATH}/check_init_admin.py ${INSTALLPATH}/check_init_admin.py.backup

# -------------------------------------------
# Set admin credentials in check_init_admin.py
# -------------------------------------------
SEAFILE_ADMIN_PW=${SEAFILE_ADMIN_PW:-$(pwgen)}
eval "sed -i 's/= ask_admin_email()/= \"${SEAFILE_ADMIN}\"/' ${INSTALLPATH}/check_init_admin.py"
eval "sed -i 's/= ask_admin_password()/= \"${SEAFILE_ADMIN_PW}\"/' ${INSTALLPATH}/check_init_admin.py"

# -------------------------------------------
# Start and stop Seafile eco system. This generates the initial admin user.
# -------------------------------------------
${INSTALLPATH}/seafile.sh start
${INSTALLPATH}/seahub.sh start
sleep 2                         # sleep for a while, otherwise seahub will not be stopped
${INSTALLPATH}/seahub.sh stop
sleep 1
${INSTALLPATH}/seafile.sh stop

# -------------------------------------------
# Restore original check_init_admin.py
# -------------------------------------------
mv ${INSTALLPATH}/check_init_admin.py.backup ${INSTALLPATH}/check_init_admin.py

if is_pro; then
    PRO_PY=${INSTALLPATH}/pro/pro.py
    $PYTHON ${PRO_PY} setup --mysql --mysql_host=127.0.0.1 --mysql_port=3306 --mysql_user=seafile --mysql_password=${SQLSEAFILEPW} --mysql_db=seahub_db
    sed -i 's/enabled = false/enabled = true/' ${TOPDIR}/conf/seafevents.conf
fi

# -------------------------------------------
# Start seafile server
# -------------------------------------------
echo "Starting productive Seafile server"
service seafile-server start

# -------------------------------------------
# Final report
# -------------------------------------------
cat > ${TOPDIR}/aio_seafile-server.log<<EOF

  Your Seafile server is installed
  -----------------------------------------------------------------

  Server Address:      http://${IP_OR_DOMAIN}

  Seafile Admin:       ${SEAFILE_ADMIN}
  Admin Password:      ${SEAFILE_ADMIN_PW}

  Seafile Data Dir:    ${SEAFILE_DATA_DIR}

  Seafile DB Credentials:  Check /opt/seafile.my.cnf
  Root DB Credentials:     Check /root/.my.cnf

  This report is also saved to ${TOPDIR}/aio_seafile-server.log

  Next you should manually complete the following steps
  -----------------------------------------------------------------

  1) Run seafile-server-change-address to add your Seafile servers DNS name

  2) If this server is behind a firewall, you need to ensure that
     tcp port 80 is open.

  3) Seahub tries to send emails via the local server. Install and
     configure Postfix for this to work.

  Optional steps
  -----------------------------------------------------------------

  1) Check seahub_settings.py and customize it to fit your needs. Consult
     http://manual.seafile.com/config/seahub_settings_py.html for possible switches.

  2) Setup NGINX with official SSL certificate.

  3) Secure server with iptables based firewall. For instance: UFW or shorewall

  4) Harden system with port knocking, fail2ban, etc.

  5) Enable unattended installation of security updates. Check
     https://wiki.Ubuntu.org/UnattendedUpgrades for details.

  6) Implement a backup routine for your Seafile server.

  7) Update NGINX worker processes to reflect the number of CPU cores.

  Seafile support options
  -----------------------------------------------------------------

  For free community support visit:   https://bbs.seafile.com
  For paid commercial support visit:  https://seafile.com

EOF

chmod 600 ${TOPDIR}/aio_seafile-server.log

clear

cat ${TOPDIR}/aio_seafile-server.log


text:
<?php
/**
 * Базовый класс для всех классов, описывающих наборы задач.
 *
 * PHP version 5
 *
 * @package Meme
 * @author  Andrey Filippov <afi@runtime.pro>
 */

namespace Meme;

abstract class TargetDefinition implements ITargetDefinition
{
	protected $fn;

	/**
	 * Задает функцию, описывающую набор задач
	 *
	 * @param mixed $fn
	 */
	public function setFunction($fn)
	{
		$this->fn = $fn;
	}

	/**
	 * Возвращает функцию, описывающую набор задач
	 *
	 * @return mixed
	 */
	public function getFunction()
	{
		return $this->fn;
	}

}


text:
#ifndef __ROM_INITIAL_CONFIG_HPP__
#define __ROM_INITIAL_CONFIG_HPP__

#include "../rc_inc.hpp"

#include "Logger.hpp"

namespace RomCommon {

	/*
	*	A helpful Converter class
	*
	*	Converts types to std::string and back
	*	TODO: Check if needs to go to a seperate file collection
	*/

	class ROMCOMMON_API Convert
	{
	public:
		template <typename T>
		static std::string T_to_string(T const &val)
		{
			std::ostringstream ostr;
			ostr << val;

			return ostr.str();
		}

		template <typename T>
		static T string_to_T(std::string const &val)
		{
			std::istringstream istr(val);
			T returnVal;

#ifdef _DEBUG
			assert((istr >> returnVal));
#endif
			if(!(istr >> returnVal))
			{
				Logger::getInstance()->Log("Conver => Failed to convert value");
			}

			return returnVal;

		}

		template <>
		static std::string string_to_T(std::string const &val)
		{
			return val;
		}
	};

	/*
	*	Initial Config Class
	*
	*	Used to fetch and store the initial configuration options
	*	For the engine
	*/
	class ROMCOMMON_API ConfigFile
	{
	public:

		ConfigFile(){};
		ConfigFile(const std::string &filename);
		~ConfigFile(){};

		void loadFile(const std::string &filename);
		bool keyExists(const std::string &key) const;

		template <typename Y>
		Y getValueOfKey(const std::string &key, Y const &defaultValue = Y()) const
		{
			if(!keyExists(key))
				return defaultValue;

			return Convert::string_to_T<Y>(_contents.find(key)->second);
		}

		// Debug
		void debugTest();

	protected:

		// temp
		std::map<std::string, std::string> _contents;
		std::string _filename;

		void removeComment(std::string &line) const;
		bool onlyWhitespace(const std::string &line) const;
		bool validLine(const std::string &line) const;
		void extractKey(std::string &key, size_t const &sepPos, const std::string &line) const;
		void extractValue(std::string &value, size_t const &sepPos, const std::string &line) const;
		void extractContents(const std::string &line);

		void parseLine(const std::string &line, size_t const lineNo);
		void extractKeys();

	};

}

#endif


text:
/**
 * The `content` command
 * @module
 */
"use strict"

let {withContentOf} = require('./adr_util.js')

/**
 * Output the content of the given ID, if availablem to the console.
 *
 * @param {number} id - The ID of the ADR to output
 */
let contentCmd = (id) => {
    withContentOf(id
                , content => {
                    console.info(content)
                }
    )
}

module.exports = contentCmd


text:
function PasswordValidation ( password ) {

	// Configuration settings
	config = {
		size : 10,
		uppercase : 1,
		numbers : 2,
		special : "$#%&-!?"
	};

	// Construct the regHex using the values provided by the configuration object and escaping the characters
	function polulateRegHex(){
		var regHex='';
		for (i=0; i<config.special.length; i++){
			regHex += '\\'+config.special[i];
		}
		return '['+regHex+']';
	}

	// Object.prototype.toString.call() = "object RegHex"
	var regHex = new RegExp( polulateRegHex() );

	// Password can't be empty
	if ( password == undefined ){
		return false;

	// Check for any Uppercase present
	} else if ( password.match(/[A-Z]/g) == null ){
		return false;

	// Check for configired Uppercase present
	} else if ( password.match(/[A-Z]/g).length < config.uppercase ){
		return false;

	// At least any numbers present
	} else if ( password.match(/[0-9]/g).length == null ){
		return false;

	// At least configured numbers present
	} else if ( password.match(/[0-9]/g).length < config.numbers ){
		return false;

	// At least one of these symbols in config.special present
	} else if ( password.match(regHex) == null ){
		return false;

	// Check length
	} else if ( password.length < config.size ){
		return false;

	// Everything went well. Password valid.
	} else {
	return true;
	}

}


text:
from swiftbackmeup import configuration
from swiftbackmeup import parser
from swiftbackmeup import utils
from swiftbackmeup import lists
from swiftbackmeup.items.databases import *  # noqa: F403
from swiftbackmeup.items.filesystems import *  # noqa: F403

_CONF = {
    "clean_local_copy": True,
    "create_container": True,
    "purge_backup": False,
}

_METHODS = ["list", "list_items"]

def main():

    options = parser.parse()

    if options.conf:
        _CONF["file_path"] = options.conf

    global_configuration = configuration.load_configuration(_CONF)

    backups = configuration.expand_configuration(global_configuration)
    backups = utils.filter_databases(options.items, backups)
    modes = global_configuration.get("modes")

    # swiftbackmeup restore ...
    if "version" in options:
        for backup in backups:
            if backup["type"] == "postgresql":
                cur_backup = postgresql.PostgreSQL(backup)  # noqa: F405
            elif backup["type"] == "mariadb":
                cur_backup = mariadb.MariaDB(backup)  # noqa: F405
            elif backup["type"] == "file":
                cur_backup = file.File(backup)  # noqa: F405
            elif backup["type"] == "git":
                cur_backup = git.Git(backup)  # noqa: F405
            if options.force:
                cur_backup.restore(options.version)
            elif utils.query_yes_no(
                "Are you sure you want to restore the backup?", default="no"
            ):
                cur_backup.restore(options.version)
            else:
                print("Exiting without restoring the database")

    # swiftbackmeup purge ...
    elif "noop" in options:
        purge = False
        purged_backups = []

        if options.force:
            purge = True
        elif not options.force and utils.query_yes_no(
            "Are you sure you want to purge the backups?", default="no"
        ):
            purge = True
        else:
            print("Exiting without purging the backups")
        if purge:
            for backup in backups:
                if backup["type"] == "postgresql":
                    cur_backup = postgresql.PostgreSQL(backup)  # noqa: F405
                elif backup["type"] == "mariadb":
                    cur_backup = mariadb.MariaDB(backup)  # noqa: F405
                elif backup["type"] == "file":
                    cur_backup = file.File(backup)  # noqa: F405
                elif backup["type"] == "git":
                    cur_backup = git.Git(backup)  # noqa: F405
                purged_backups += cur_backup.purge(modes, options.mode, options.noop)
            lists.list_purged_backups(purged_backups, options.noop)

    # swiftbackmeup backup ...
    else:
        # If a --list-* options has been specified, call the proper method
        # and exit
        #
        for method in _METHODS:
            if getattr(options, method):
                if method == "list_items":
                    lists.list_items(backups, options)
                elif method == "list":
                    lists.list_remote_backups(backups, options, modes)
                return

        for backup in backups:
            if options.mode in backup["subscriptions"]:
                backup["filename"] = utils.build_filename(backup, modes[options.mode])
                if backup["type"] == "postgresql":
                    cur_backup = postgresql.PostgreSQL(backup)  # noqa: F405
                elif backup["type"] == "mariadb":
                    cur_backup = mariadb.MariaDB(backup)  # noqa: F405
                elif backup["type"] == "file":
                    cur_backup = file.File(backup)  # noqa: F405
                elif backup["type"] == "git":
                    cur_backup = git.Git(backup)  # noqa: F405
                cur_backup.run()
                cur_backup.upload()


text:
package main

import (
	"time"

	"k8s.io/autoscaler/vertical-pod-autoscaler/updater/eviction"
	"k8s.io/autoscaler/vertical-pod-autoscaler/updater/priority"

	apiv1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/fields"
	"k8s.io/apimachinery/pkg/labels"
	vpa_types "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis/poc.autoscaling.k8s.io/v1alpha1"
	vpa_clientset "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/client/clientset/versioned"
	vpa_lister "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/client/listers/poc.autoscaling.k8s.io/v1alpha1"
	vpa_api_util "k8s.io/autoscaler/vertical-pod-autoscaler/pkg/utils/vpa"
	kube_client "k8s.io/client-go/kubernetes"
	v1lister "k8s.io/client-go/listers/core/v1"
	"k8s.io/client-go/tools/cache"

	"github.com/golang/glog"
)

// Updater performs updates on pods if recommended by Vertical Pod Autoscaler
type Updater interface {
	// RunOnce represents single iteration in the main-loop of Updater
	RunOnce()
}

type updater struct {
	vpaLister       vpa_lister.VerticalPodAutoscalerLister
	podLister       v1lister.PodLister
	evictionFactory eviction.PodsEvictionRestrictionFactory
}

// NewUpdater creates Updater with given configuration
func NewUpdater(kubeClient kube_client.Interface, vpaClient *vpa_clientset.Clientset, minReplicasForEvicition int, evictionToleranceFraction float64) Updater {
	return &updater{
		vpaLister:       vpa_api_util.NewAllVpasLister(vpaClient, make(chan struct{})),
		podLister:       newPodLister(kubeClient),
		evictionFactory: eviction.NewPodsEvictionRestrictionFactory(kubeClient, minReplicasForEvicition, evictionToleranceFraction),
	}
}

// RunOnce represents single iteration in the main-loop of Updater
func (u *updater) RunOnce() {
	vpaList, err := u.vpaLister.List(labels.Everything())
	if err != nil {
		glog.Fatalf("failed get VPA list: %v", err)
	}

	vpas := make([]*vpa_types.VerticalPodAutoscaler, 0)

	for _, vpa := range vpaList {
		if vpa.Spec.UpdatePolicy.UpdateMode != vpa_types.UpdateModeAuto {
			glog.V(3).Infof("skipping VPA object %v because its mode is not \"Auto\"", vpa.Name)
			continue
		}
		vpas = append(vpas, vpa)
	}

	if len(vpas) == 0 {
		glog.Warningf("no VPA objects to process")
		return
	}

	podsList, err := u.podLister.List(labels.Everything())
	if err != nil {
		glog.Errorf("failed to get pods list: %v", err)
		return
	}
	livePods := filterDeletedPods(podsList)

	controlledPods := make(map[*vpa_types.VerticalPodAutoscaler][]*apiv1.Pod)
	for _, pod := range livePods {
		controllingVPA := vpa_api_util.GetControllingVPAForPod(pod, vpas)
		if controllingVPA != nil {
			controlledPods[controllingVPA] = append(controlledPods[controllingVPA], pod)
		}
	}

	for vpa, livePods := range controlledPods {
		evictionLimiter := u.evictionFactory.NewPodsEvictionRestriction(livePods)
		podsForUpdate := u.getPodsForUpdate(filterNonEvictablePods(livePods, evictionLimiter), vpa)

		for _, pod := range podsForUpdate {
			if !evictionLimiter.CanEvict(pod) {
				continue
			}
			glog.V(2).Infof("evicting pod %v", pod.Name)
			evictErr := evictionLimiter.Evict(pod)
			if evictErr != nil {
				glog.Warningf("evicting pod %v failed: %v", pod.Name, evictErr)
			}
		}
	}
}

// getPodsForUpdate returns list of pods that should be updated ordered by update priority
func (u *updater) getPodsForUpdate(pods []*apiv1.Pod, vpa *vpa_types.VerticalPodAutoscaler) []*apiv1.Pod {
	priorityCalculator := priority.NewUpdatePriorityCalculator(&vpa.Spec.ResourcePolicy, nil)
	recommendation := vpa.Status.Recommendation

	for _, pod := range pods {
		priorityCalculator.AddPod(pod, &recommendation)
	}

	return priorityCalculator.GetSortedPods()
}

func filterNonEvictablePods(pods []*apiv1.Pod, evictionRestriciton eviction.PodsEvictionRestriction) []*apiv1.Pod {
	result := make([]*apiv1.Pod, 0)
	for _, pod := range pods {
		if evictionRestriciton.CanEvict(pod) {
			result = append(result, pod)
		}
	}
	return result
}

func filterDeletedPods(pods []*apiv1.Pod) []*apiv1.Pod {
	result := make([]*apiv1.Pod, 0)
	for _, pod := range pods {
		if pod.DeletionTimestamp == nil {
			result = append(result, pod)
		}
	}
	return result
}

func newPodLister(kubeClient kube_client.Interface) v1lister.PodLister {
	selector := fields.ParseSelectorOrDie("spec.nodeName!=" + "" + ",status.phase!=" +
		string(apiv1.PodSucceeded) + ",status.phase!=" + string(apiv1.PodFailed))
	podListWatch := cache.NewListWatchFromClient(kubeClient.CoreV1().RESTClient(), "pods", apiv1.NamespaceAll, selector)
	store := cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc})
	podLister := v1lister.NewPodLister(store)
	podReflector := cache.NewReflector(podListWatch, &apiv1.Pod{}, store, time.Hour)
	stopCh := make(chan struct{})
	go podReflector.Run(stopCh)

	return podLister
}


text:
<?php
namespace Grav\Plugin;

use Grav\Common\Plugin;
use Grav\Common\Grav;
use Grav\Common\Page\Collection;
use Grav\Common\Page\Page;
use Grav\Common\Debugger;
use Grav\Common\Taxonomy;
use RocketTheme\Toolbox\Event\Event;

function rcopy($source, $dest, $exclude = array()) {
  if (!file_exists($dest))
    mkdir($dest, 0755, true);
  foreach (
   $iterator = new \RecursiveIteratorIterator(
    new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS),
    \RecursiveIteratorIterator::SELF_FIRST) as $item
  ) {
    $excluding = false;
    $pathName = $dest . DIRECTORY_SEPARATOR . $iterator->getSubPathName();
    foreach ($exclude as $word) {
      if (strpos($pathName, $word) !== false) {
        $excluding = true;
        break;
      }
    }

    if (!$excluding) {
      if ($item->isDir()) {
        if (!file_exists($pathName))
          mkdir($pathName);
      } else {
        copy($item, $pathName);
      }
    }
  }
}

function rrmdir($dir) {
  if (is_dir($dir)) {
    $objects = scandir($dir);
    foreach ($objects as $object) {
      if ($object != "." && $object != "..") {
        if (is_dir($dir."/".$object))
          rrmdir($dir."/".$object);
        else
          unlink($dir."/".$object);
      }
    }
    rmdir($dir);
  }
}

function rscan($dir, &$results = array()) {
  $files = scandir($dir);

  foreach($files as $key => $value){
    $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
    if (!is_dir($path)) {
      $results[] = $path;
    }
    else if ($value != "." && $value != "..") {
      rscan($path, $results);
    }
  }

  return $results;
}

/**
 * Class GeneratorPlugin
 * @package Grav\Plugin
 */
class GeneratorPlugin extends Plugin
{

    protected $displayPluginPage = false;

    /**
     * @return array
     *
     * The getSubscribedEvents() gives the core a list of events
     *     that the plugin wants to listen to. The key of each
     *     array section is the event that the plugin listens to
     *     and the value (in the form of an array) contains the
     *     callable (or function) as well as the priority. The
     *     higher the number the higher the priority.
     */
    public static function getSubscribedEvents()
    {
        return [
            'onOutputRendered' => ['onOutputRendered', 0],
            'onPageInitialized' => ['onPageInitialized', 0],
            'onPluginsInitialized' => ['onPluginsInitialized', 0],
        ];
    }

    private function dispatchActions($action) {
      if ($action == 'refreshRoutes' || $action == 'refreshAll') {
        foreach ($this->grav['pages']->routes() as $route => $folder) {
          $uri = "http://" . $_SERVER['HTTP_HOST'] . $route;
          $s = curl_init();
          curl_setopt($s, CURLOPT_URL, $uri);
          curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
          $a = curl_exec($s);
          curl_close($s);
        }
      }
      if ($action == 'refreshAssets' || $action == 'refreshAll') {

        error_reporting(-1);
        ini_set('display_errors', 'On');

        $exclude = $this->config->get('plugins.generator.exclude');
        $exclude = preg_replace("/\r\n|\r|\n/", ' ', $exclude);
        $exclude = explode(' ', $exclude);

        $include = $this->config->get('plugins.generator.include');
        $include = preg_replace("/\r\n|\r|\n/", ' ', $include);
        $include = explode(' ', $include);

        rrmdir($this->config->get('plugins.generator.destination_folder') . "user/pages");
        rrmdir($this->config->get('plugins.generator.destination_folder') . "user/themes");
        rcopy("user/pages", $this->config->get('plugins.generator.destination_folder') . "user/pages", $exclude);
        rcopy("user/themes", $this->config->get('plugins.generator.destination_folder') . "user/themes", $exclude);

        foreach ($include as $folderName)
          rcopy($folderName, $this->config->get('plugins.generator.destination_folder') . $folderName, []);

        // Generating cache manifest
        $cacheManifest = $this->config->get('plugins.generator.cache_manifest');
        if ($cacheManifest == 'on') {
          $cacheManifestFile = $this->config->get('plugins.generator.destination_folder') . '/website.appcache';
          $text = "CACHE MANIFEST\r\n";
          $text .= "\r\n" . "# Generated on " . date('F d, Y') . " at " . date('H:i:s') . "\r\n\r\n";

          $files = rscan($this->config->get('plugins.generator.destination_folder'));
          foreach ($files as $f)
            if (strpos($f, 'website.appcache') === false)
              $text .= str_replace(realpath($this->config->get('plugins.generator.destination_folder')), '', $f) . "\r\n";
          file_put_contents($cacheManifestFile, $text);
        }
      }
    }

    public function onPluginsInitialized()
    {
      if (!$this->isAdmin()) {
        return;
      }

      $uri = $this->grav['uri'];
      $route = $this->config->get('plugins.generator.route');

      if ($route && $route == $uri->path())
        $this->displayPluginPage = true;
    }

    public function onPageInitialized()
    {
      // Display plugin panel
      if ($this->displayPluginPage) {

        if (isset($_GET['action']) && !empty($_GET['action']))
          $this->dispatchActions($_GET['action']);

        include('dashboard.html');
        exit;
      }

      // Trigerring refresh of cached page and parents on page save / editing
      if ($this->isAdmin()) {

        $routes = $this->grav['pages']->routes();
        $routesToRefresh = [];

        // Admin page URL to real page URL
        $uri = $_SERVER['REQUEST_URI'];
        $uri = str_replace($this->config->get('plugins.admin.route') . "/pages", "", $uri);
        $routesToRefresh[] = $uri;

        // Getting this page directory (containing .md and assets)
        if (!array_key_exists($uri, $routes))
          return;
        $file = $routes[$uri];

        // Finding page aliases
        foreach ($routes as $route => $folder)
          if ($uri != $route && $folder == $file)
            $routesToRefresh[] = $route;

        // Finding parents
        foreach ($routes as $route => $folder)
          if (!in_array($route, $routesToRefresh))
            foreach ($routesToRefresh as $route2)
              if (strpos($route2, $route) !== false) {
                $routesToRefresh[] = $route;
                break;
              }

        // Finding parents aliases
        foreach ($routes as $route => $folder)
          if (!in_array($route, $routesToRefresh))
            foreach ($routesToRefresh as $route2)
              if ($routes[$route2] == $folder) {
                $routesToRefresh[] = $route;
                break;
              }

        foreach ($routesToRefresh as $route) {
          $uri = "http://" . $_SERVER['HTTP_HOST'] . $route;
          $s = curl_init();
          curl_setopt($s, CURLOPT_URL, $uri);
          curl_setopt($s, CURLOPT_RETURNTRANSFER, true);
          $a = curl_exec($s);
          curl_close($s);
        }
      }
    }

    // Save cached version of page
    public function onOutputRendered()
    {
        if ($this->isAdmin())
          return ;

        $filename = $this->getCacheFilename();

        $dir = dirname($filename);
        $error = false;
        if (!is_dir($dir)) {
          $res = @mkdir($dir, 0775, true);
          if (!$res)
            $error = true;
        }
        if (!$error) {
            $output = $this->grav->output;
            $output = str_replace('http://' . $_SERVER['HTTP_HOST'], $this->config->get('plugins.generator.destination_domain'), $output);

            @file_put_contents($filename, $output . '<!-- Generated: ' . date('c') . ' -->');
        }
    }

    protected function getCacheFilename() {
        $filename = array();
        $uri = trim($_SERVER['REQUEST_URI'], '/');

        $filename[] = $this->config->get('plugins.generator.destination_folder');
        if ($uri)
          $filename[] =  $uri;

        $filename[] = 'index.html';
        $filename = implode('/', $filename);

        $filename = str_replace("//", "/", $filename);

        return $filename;
    }
}