text:
@implementation ModalPresentationFromPointConfig
@end

static const CGFloat modalDimmingViewAlpha = 0.5f;
static const NSTimeInterval modalTransitionDuration = 0.3f;
static const NSTimeInterval modalDismissTransitionDuration = 0.3f;
//初始动画和结束动画(centerStyle) view长宽各为
static const CGFloat modalCenterInitialViewSizeRatio = 0.1f;
static const CGFloat modalCenterInitialViewAlpha = 0.5f;

@interface ModalPresentationController () <UIViewControllerAnimatedTransitioning>
@property (nonatomic, strong) UIView *dimmingView;
@end

@implementation ModalPresentationController
#pragma mark - life cycle
- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController presentingViewController:(UIViewController *)presentingViewController {
    self = [super initWithPresentedViewController:presentedViewController presentingViewController:presentingViewController];
    if (self) {
        presentedViewController.modalPresentationStyle = UIModalPresentationCustom;
    }

    return self;
}

- (void)presentationTransitionWillBegin {
    //加入 dimmingView
    [self.containerView addSubview:self.dimmingView];
    self.dimmingView.userInteractionEnabled = YES;
    [self.dimmingView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dimmingViewTapped:)]];

    //获取转场协调器
    id<UIViewControllerTransitionCoordinator> transitionCoordinator = self.presentingViewController.transitionCoordinator;

    //渐变的 dimmingView,使该动画和转场动画并行
    self.dimmingView.alpha = 0.f;
    [transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        self.dimmingView.alpha = modalDimmingViewAlpha;
    } completion: NULL];
}

- (void)dismissalTransitionWillBegin
{
    id<UIViewControllerTransitionCoordinator> transitionCoordinator = self.presentingViewController.transitionCoordinator;

    [transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> context) {
        self.dimmingView.alpha = 0.f;
    } completion:NULL];
}

#pragma mark - about layout
- (CGSize)sizeForChildContentContainer:(id<UIContentContainer>)container withParentContainerSize:(CGSize)parentSize {
    if (container == self.presentedViewController) {
        return ((UIViewController *)container).preferredContentSize;
    } else {
        return [super sizeForChildContentContainer:container withParentContainerSize:parentSize];
    }
}

- (CGRect)frameOfPresentedViewInContainerView
{
    CGRect containerViewBounds = self.containerView.bounds;
    CGSize presentedViewContentSize = [self sizeForChildContentContainer:self.presentedViewController withParentContainerSize:containerViewBounds.size];

    CGRect presentedViewControllerFrame;
    presentedViewControllerFrame.size.width = presentedViewContentSize.width;
    presentedViewControllerFrame.size.height = presentedViewContentSize.height;

    switch (self.modalStyle) {
        case CHYCModalPresentationStyleFromTop:
            presentedViewControllerFrame.origin.y = 0;
            presentedViewControllerFrame.origin.x = (CGRectGetMaxX(containerViewBounds) - presentedViewContentSize.width) / 2;
            break;
        case CHYCModalPresentationStyleFromBottom:
            presentedViewControllerFrame.origin.y = CGRectGetMaxY(containerViewBounds) - presentedViewContentSize.height;
            presentedViewControllerFrame.origin.x = (CGRectGetMaxX(containerViewBounds) - presentedViewContentSize.width) / 2;
            break;
        case CHYCModalPresentationStyleCenter:
            presentedViewControllerFrame.origin.y = (CGRectGetMaxY(containerViewBounds) - presentedViewContentSize.height) / 2;
            presentedViewControllerFrame.origin.x = (CGRectGetMaxX(containerViewBounds) - presentedViewContentSize.width) / 2;
            break;
        case CHYCModalPresentationStyleFromPoint:
            presentedViewControllerFrame.origin.y = self.config.frame.origin.y;
            presentedViewControllerFrame.origin.x = self.config.frame.origin.x;
            break;
    }

    return presentedViewControllerFrame;
}

//出现动画的 presentedView 的初始状态
- (CGRect)toViewInitialFrameForStyle:(CHYCModalPresentationStyle)modalStyle containterViewBounds:(CGRect)bounds finalSize:(CGSize)finalSize {
    CGRect toViewInitialFrame;

    //置中偏移量
    CGFloat XOffset = CGRectGetMidX(bounds) - finalSize.width / 2;
    CGFloat YOffset = CGRectGetMidY(bounds) - finalSize.height / 2;
    switch (modalStyle) {
        case CHYCModalPresentationStyleFromTop:
            toViewInitialFrame.origin = CGPointMake(XOffset, - CGRectGetMaxY(bounds));
            toViewInitialFrame.size = finalSize;
            break;
        case CHYCModalPresentationStyleFromBottom:
            toViewInitialFrame.origin = CGPointMake(XOffset, CGRectGetMaxY(bounds));
            toViewInitialFrame.size = finalSize;
            break;
        case CHYCModalPresentationStyleCenter:
            toViewInitialFrame.origin = CGPointMake(XOffset, YOffset);
            toViewInitialFrame.size = finalSize;
            break;
        case CHYCModalPresentationStyleFromPoint:
            toViewInitialFrame.origin = self.config.frame.origin;
//            toViewInitialFrame.origin = CGPointMake(self.config.frame.origin.x + 0.5 * self.config.frame.size.width, self.config.frame.origin.y + 0.5 * self.config.frame.size.height);
            toViewInitialFrame.size = finalSize;
            break;
    }
    return toViewInitialFrame;
}

//结束动画的 presentedView 的最终状态
- (CGRect)fromViewFinalFrameForStyle:(CHYCModalPresentationStyle)modalStyle fromViewFrame:(CGRect)fromViewFrame {
    CGRect fromViewFinalFrame = CGRectZero;

    switch (modalStyle) {
        case CHYCModalPresentationStyleFromTop:
            fromViewFinalFrame = CGRectOffset(fromViewFrame, 0, - CGRectGetHeight(fromViewFrame));
            break;
        case CHYCModalPresentationStyleFromBottom:
            fromViewFinalFrame = CGRectOffset(fromViewFrame, 0, CGRectGetHeight(fromViewFrame));
            break;
        case CHYCModalPresentationStyleCenter:
            //do nothing
            break;
        case CHYCModalPresentationStyleFromPoint:
            break;
    }
    return fromViewFinalFrame;
}

#pragma mark - UIViewControllerAnimatedTransitioning
- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext {
    //点开的展现动画,或 dismiss 动画
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    BOOL isPresenting = (fromViewController == self.presentingViewController);

    //返回设定的时间
    if ([transitionContext isAnimated]) {
        if (isPresenting) {
            return modalTransitionDuration;
        } else {
            return modalDismissTransitionDuration;
        }
    } else {
        return 0;
    }
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
    UIViewController *fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];

    UIView *containerView = transitionContext.containerView;
    // For a Presentation:
    //      fromView = The presenting view.
    //      toView   = The presented view.
    // For a Dismissal:
    //      fromView = The presented view.
    //      toView   = The presenting view.
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];

    //点开的展现动画,或 dismiss 动画
    BOOL isPresenting = (fromViewController == self.presentingViewController);

    CGRect __unused fromViewInitialFrame = [transitionContext initialFrameForViewController:fromViewController];
    CGRect fromViewFinalFrame = [transitionContext finalFrameForViewController:fromViewController];
    CGRect toViewInitialFrame = [transitionContext initialFrameForViewController:toViewController];
    CGRect toViewFinalFrame = [transitionContext finalFrameForViewController:toViewController];

    [containerView addSubview:toView];

    if (isPresenting) {
        //出现动画
        toViewInitialFrame = [self toViewInitialFrameForStyle:self.modalStyle containterViewBounds:containerView.bounds finalSize:toViewFinalFrame.size];;
        toView.frame = toViewInitialFrame;

        if (self.modalStyle == CHYCModalPresentationStyleCenter) {
            //缩小并半透明化
            toView.alpha = modalCenterInitialViewAlpha;
            toView.transform = CGAffineTransformMakeScale(modalCenterInitialViewSizeRatio, modalCenterInitialViewSizeRatio);
        }
        if (self.modalStyle == CHYCModalPresentationStyleFromPoint) {
            toView.alpha = self.config.initAlpha;
            //anchorPoint改变时frame会改变
            toView.layer.anchorPoint = self.config.anchorPoint;
            toView.frame = toViewInitialFrame;
            toView.transform = CGAffineTransformMakeScale(self.config.initSizeRatio, self.config.initSizeRatio);
        }
    } else {
        //结束动画
        fromViewFinalFrame = [self fromViewFinalFrameForStyle:self.modalStyle fromViewFrame:fromView.frame];
    }

    NSTimeInterval transitionDuration = [self transitionDuration:transitionContext];

    if (self.modalStyle == CHYCModalPresentationStyleCenter) {
        [UIView animateWithDuration:transitionDuration delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
            if (isPresenting) {
                //恢复正常态
                toView.alpha = 1.0f;
                toView.transform = CGAffineTransformIdentity;
            } else {
                fromView.alpha = 0.0f;
                fromView.transform = CGAffineTransformMakeScale(modalCenterInitialViewSizeRatio, modalCenterInitialViewSizeRatio);
            }
        } completion:^(BOOL finished) {
            toView.frame = toViewFinalFrame;
            [transitionContext completeTransition:YES];
        }];
    } else if (self.modalStyle == CHYCModalPresentationStyleFromPoint) {
        fromView.layer.anchorPoint = self.config.anchorPoint;
        [UIView animateWithDuration:transitionDuration delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
            if (isPresenting) {
                //恢复正常态
                toView.alpha = 1.0f;
                toView.transform = CGAffineTransformIdentity;
            } else {
                fromView.alpha = 0.0f;
                fromView.transform = CGAffineTransformMakeScale(self.config.initSizeRatio, self.config.initSizeRatio);
            }
        } completion:^(BOOL finished) {
            toView.frame = toViewFinalFrame;
            [transitionContext completeTransition:YES];
        }];
    } else {
        [UIView animateWithDuration:transitionDuration delay:0.0f options:UIViewAnimationOptionCurveEaseOut animations:^{
            if (isPresenting) {
                toView.frame = toViewFinalFrame;
            } else {
                fromView.frame = fromViewFinalFrame;
            }
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:YES];
        }];
    }
}

#pragma mark - UIViewControllerTransitioningDelegate
- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source {
    NSAssert(self.presentedViewController == presented, @"You didn't initialize %@ with the correct presentedViewController.  Expected %@, got %@.",
             self, presented, self.presentedViewController);
    return self;
}

//返回 self 作为 animator
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source
{
    return self;
}

//返回 self  作为 animator
- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed
{
    return self;
}

#pragma mark - event response
- (void)dimmingViewTapped:(UITapGestureRecognizer*)sender
{
    [self.presentingViewController dismissViewControllerAnimated:YES completion:NULL];

}

#pragma mark - getters and setters
- (UIView *)dimmingView {
    if (!_dimmingView) {
        _dimmingView = [[UIView alloc] initWithFrame:self.containerView.bounds];
        _dimmingView.backgroundColor = [UIColor blackColor];
        _dimmingView.opaque = NO;
    }
    return _dimmingView;
}
@end


text:
package com.deem.excord.util;

public interface Constants {

    String STATUS_PASSED = "PASSED";
    String STATUS_FAILED = "FAILED";
    String STATUS_BLOCKED = "BLOCKED";
    String STATUS_NOT_COMPLETED = "NOT_COMPLETED";
    String STATUS_NOT_RUN = "NOT_RUN";
    String STATUS_OTHER = "OTHER";

    String ROLE_USER = "USER";
    String USER_AUTOMATION = "AUTOMATION";
    String USER_SYSTEM = "SYSTEM";

    String PRIORITY_P1 = "P1";
    String PRIORITY_P2 = "P2";
    String PRIORITY_P3 = "P3";
    String PRIORITY_P4 = "P4";

    String REQ_STATUS_ACTIVE = "ACTIVE";
    String REQ_STATUS_DEPRECATED = "DEPRECATED";
    String REQ_STATUS_PROPOSED = "PROPOSED";

    String TYPE_MANUAL = "MANUAL";

    Long TRASH_NODE = 2L;

    String PATH_DELIMITER = "/";

}

redpajama_set_name: RedPajamaGithub


text:
using Grafika.Utilities;
using System.Collections.Generic;

namespace Grafika.Configurations
{
    public class ServerConfiguration
    {
        public string Url { get; set; }
        public string ApiUrl => Utility.CombineUrl(Url, "api");
        public string Name { get; set; }
        public string Description { get; set; }
        public string Version { get; set; }
        public string Secret { get; set; }

        public string OAuthCallbackPath { get; set; }

        public string PrivacyPath { get; set; }
        public string EulaPath { get; set; }
        public string BackdropsPath { get; set; }

        public string DefaultAvatarPath { get; set; }
        public string DefaultBackdropPath { get; set; }

        public IEnumerable<string> HandpickedAnimationIds { get; set; }
        public int UsersCount { get; set; }
        public int UsersSearchableCount { get; set; } = 100;
        public int AnimationsCount { get; set; }
        public int AnimationsSearchableCount { get; set; } = 150;

        public string PageTitle { get; set; } = "A stop-motion animation maker | Grafika";
        public string PageDescription { get; set; } = "A super simple stop-motion animation maker, viewer, sharer and community for the web and Android by animators like you provided by Grafika";
        public string PageKeyword { get; set; } = "grafika, animation,stop-motion animation, stop-motion animation maker, online animation maker,animation creator";
    }
}


text:
"""add password

Revision ID: 578150ae72c8
Revises: a4ddb77c0941
Create Date: 2017-02-07 19:02:35.725606

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '578150ae72c8'
down_revision = 'a4ddb77c0941'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('users', sa.Column('password_hash', sa.String(length=128), nullable=True))
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('users', 'password_hash')
    # ### end Alembic commands ###


text:
Observable.prototype.firstToPromise = function (PromiseCtr) {
  // Can't do in the global scope, as shim can be applied after Bacon is loaded.
  if (typeof PromiseCtr !== "function") {
    if (typeof Promise === "function") {
      PromiseCtr = Promise;
    } else {
      throw new Exception("There isn't default Promise, use shim or parameter");
    }
  }

  return new PromiseCtr((resolve, reject) =>
    this.subscribe((event) => {
      if (event.hasValue()) { resolve(event.value()); }
      if (event.isError()) { reject(event.error); }
      // One event is enough
      return Bacon.noMore;
    }));
};

Observable.prototype.toPromise = function (PromiseCtr) {
  return this.last().firstToPromise(PromiseCtr);
};


text:
package org.elasticsearch.rest.action.cat;

import org.elasticsearch.client.node.NodeClient;
import org.elasticsearch.rest.BaseRestHandler;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestStatus;

import java.io.IOException;
import java.util.List;

import static org.elasticsearch.rest.RestRequest.Method.GET;

public class RestCatAction extends BaseRestHandler {

    private static final String CAT = "=^.^=";
    private static final String CAT_NL = CAT + "\n";
    private final String HELP;

    public RestCatAction(List<AbstractCatAction> catActions) {
        StringBuilder sb = new StringBuilder();
        sb.append(CAT_NL);
        for (AbstractCatAction catAction : catActions) {
            catAction.documentation(sb);
        }
        HELP = sb.toString();
    }

    @Override
    public List<Route> routes() {
        return List.of(new Route(GET, "/_cat"));
    }

    @Override
    public String getName() {
        return "cat_action";
    }

    @Override
    public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
        return channel -> channel.sendResponse(new BytesRestResponse(RestStatus.OK, HELP));
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Templates</title>
    <link rel="stylesheet" href="CSS/main.css">

      <form onsubmit="login(); return false;">

        Username

        <input id="usrnme" type="text" placeholder="Example.1@example.net" required>
        <button class="sub" type="submit">Login</button>
      </form>

You can use 'Guest' to login


text:
<?php
/**
 * Wraps a filter
 *
 * @category    Xi
 * @package     Xi_Filter
 * @author      Eevert Saukkokoski <eevert.saukkokoski@brainalliance.com>
 */
class Xi_Filter_Outer implements Zend_Filter_Interface, Xi_Filter_Aggregate
{
    /**
     * @var Zend_Filter_Interface
     */
    protected $_filter;

    /**
     * @param Zend_Filter_Interface inner validator
     */
    public function __construct($filter)
    {
        $this->_filter = $filter;
    }

    /**
     * @return Zend_Filter_Interface
     */
    public function getFilter()
    {
        return $this->_filter;
    }

    public function filter($value)
    {
        return $this->getFilter()->filter($value);
    }
}


text:
package hdfs;

import hydra.CacheHelper;
import hydra.ConfigPrms;
import hydra.DistributedSystemHelper;
import hydra.FileUtil;
import hydra.HDFSStoreDescription;
import hydra.HDFSStoreHelper;
import hydra.HadoopDescription;
import hydra.HadoopHelper;
import hydra.HadoopPrms;
import hydra.HostDescription;
import hydra.HydraRuntimeException;
import hydra.HydraTimeoutException;
import hydra.Log;
import hydra.MasterController;
import hydra.PortHelper;
import hydra.Prms;
import hydra.ProcessMgr;
import hydra.RemoteTestModule;
import hydra.TestConfig;
import hydra.blackboard.SharedMap;

import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.rmi.RemoteException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import util.SummaryLogListener;
import util.TestException;
import util.TestHelper;
import util.ValueHolder;

import com.gemstone.gemfire.Statistics;
import com.gemstone.gemfire.StatisticsFactory;
import com.gemstone.gemfire.SystemFailure;
import com.gemstone.gemfire.cache.Cache;
import com.gemstone.gemfire.cache.EntryNotFoundException;
import com.gemstone.gemfire.cache.Operation;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.RegionAttributes;
import com.gemstone.gemfire.cache.RegionShortcut;
import com.gemstone.gemfire.cache.asyncqueue.internal.AsyncEventQueueStats;
import com.gemstone.gemfire.cache.hdfs.HDFSIOException;
import com.gemstone.gemfire.cache.hdfs.internal.HDFSStoreImpl;
import com.gemstone.gemfire.cache.hdfs.internal.PersistedEventImpl;
import com.gemstone.gemfire.cache.hdfs.internal.UnsortedHoplogPersistedEvent;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.HoplogSetReader.HoplogIterator;
import com.gemstone.gemfire.cache.hdfs.internal.hoplog.SequenceFileHoplog;
import com.gemstone.gemfire.cache.server.CacheServer;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.cache.tier.sockets.CacheServerHelper;

/**
 *  Generic utility methods for testing with Hoplogs/HDFS
 */

public class HDFSUtil {

public static final String HDFS_RESULT_REGION = "hdfsResultRegion";

public static void startMapReduceCluster() {
  HadoopHelper.startResourceManager(ConfigPrms.getHadoopConfig());
  HadoopHelper.startNodeManagers(ConfigPrms.getHadoopConfig());
}

public static void stopMapReduceCluster() {
  HadoopHelper.stopNodeManagers(ConfigPrms.getHadoopConfig());
  HadoopHelper.stopResourceManager(ConfigPrms.getHadoopConfig());
}

public static void startCluster() {
  if (HDFSPrms.useExistingCluster()) {
    if (HDFSPrms.manageMapReduceComponents()) {
      startMapReduceCluster();
    }
  } else {
    HadoopHelper.startCluster(ConfigPrms.getHadoopConfig());
  }
}

public static void stopCluster() {
  if (HDFSPrms.useExistingCluster()) {
    if (HDFSPrms.manageMapReduceComponents()) {
      stopMapReduceCluster();
    }
  } else {
    HadoopHelper.stopCluster(ConfigPrms.getHadoopConfig());
  }
}

public static void startHDFSCluster() {
  HadoopHelper.startHDFSCluster(ConfigPrms.getHadoopConfig());
}

public static void stopHDFSCluster() {
  HadoopHelper.stopHDFSCluster(ConfigPrms.getHadoopConfig());
}

public static void configureHDFSTask() {
  HadoopHelper.configureHDFS(ConfigPrms.getHadoopConfig());
}

public static void configureHadoopTask() {
  HadoopHelper.configureHadoop(ConfigPrms.getHadoopConfig());
}

public static void formatNameNodesTask() {
  HadoopHelper.formatNameNodes(ConfigPrms.getHadoopConfig());
}

public static void startNameNodesTask() {
  HadoopHelper.startNameNodes(ConfigPrms.getHadoopConfig());
}

public static void startDataNodesTask() {
  HadoopHelper.startDataNodes(ConfigPrms.getHadoopConfig());
}

public static synchronized void restartCluster() {
  String hadoopConfig = ConfigPrms.getHadoopConfig();
  MasterController.sleepForMs( HDFSPrms.hadoopStartWaitSec() * 1000 );
  HadoopHelper.startNameNodes(hadoopConfig);
  HadoopHelper.startDataNodes(hadoopConfig);
  HadoopHelper.startResourceManager(hadoopConfig);
  HadoopHelper.startNodeManagers(hadoopConfig);
  // give hadoop 30 seconds to get out of SafeMode
  MasterController.sleepForMs( HDFSPrms.hadoopReturnWaitSec() * 1000 );
}

public static void stopNameNodesTask() {
  HadoopHelper.stopNameNodes(ConfigPrms.getHadoopConfig());
}

public static void stopDataNodesTask() {
  HadoopHelper.stopDataNodes(ConfigPrms.getHadoopConfig());
}

public static void configureAndStartHadoop() {
  String hadoopConfig = ConfigPrms.getHadoopConfig();
  HadoopHelper.configureHadoop(hadoopConfig);
  HadoopHelper.startCluster(hadoopConfig);
}

public static void stopStartDataNodes() {
  String hadoopConfig = ConfigPrms.getHadoopConfig();
  MasterController.sleepForMs( HDFSPrms.hadoopStopWaitSec() * 1000 );
  HDFSUtilBB.getBB().getSharedCounters().increment(HDFSUtilBB.recycleInProgress);
  HadoopHelper.stopDataNodes(hadoopConfig);
  MasterController.sleepForMs( HDFSPrms.hadoopStartWaitSec() * 1000 );
  HadoopHelper.startDataNodes(hadoopConfig);
  MasterController.sleepForMs( HDFSPrms.hadoopReturnWaitSec() * 1000 );
  HDFSUtilBB.getBB().getSharedCounters().zero(HDFSUtilBB.recycleInProgress);
}

public static void stopStartNameNodes() {
  String hadoopConfig = ConfigPrms.getHadoopConfig();
  MasterController.sleepForMs( HDFSPrms.hadoopStopWaitSec() * 1000 );
  HDFSUtilBB.getBB().getSharedCounters().increment(HDFSUtilBB.recycleInProgress);
  HadoopHelper.stopNameNodes(hadoopConfig);
  MasterController.sleepForMs( HDFSPrms.hadoopStartWaitSec() * 1000 );
  HadoopHelper.startNameNodes(hadoopConfig);
  MasterController.sleepForMs( HDFSPrms.hadoopReturnWaitSec() * 1000 );
  HDFSUtilBB.getBB().getSharedCounters().zero(HDFSUtilBB.recycleInProgress);
}

public static void recycleDataNode() {
  String hadoopConfig = ConfigPrms.getHadoopConfig();
  HadoopDescription hdd = HadoopHelper.getHadoopDescription(hadoopConfig);
  List<HadoopDescription.DataNodeDescription> dnds = hdd.getDataNodeDescriptions();
  if (dnds.isEmpty()) {
    String s = "Cannot recycle data node, dataNodeDescriptions is empty";
    throw new HydraRuntimeException(s);
  }
  HadoopDescription.DataNodeDescription dnd = dnds.get(0);
  HostDescription hd = dnd.getHostDescription();
  String host = dnd.getHostName();

  String pidfn = dnd.getPIDDir() + "/hadoop-" + System.getProperty("user.name") + "-datanode.pid";
  // override if secure hdfs
  if (hdd.isSecure()) {
    Log.getLogWriter().info("Using secure mode (kerberos) as root");
    pidfn = dnd.getPIDDir() + "/hadoop_secure_dn.pid";
  }

  Integer pid = getPid(pidfn);
  if (!ProcessMgr.processExists(host, pid)) {
   String s = pid + " for data node is not running on " + host
            + " see " + dnd.getLogDir() + " for output";
   throw new HydraRuntimeException(s);
  }

  Log.getLogWriter().info("Killing data node on host " + host
                           + " pid = " + pid + ", see "
                           + dnd.getLogDir() + " for output");
  MasterController.sleepForMs(HDFSPrms.hadoopStopWaitSec() * 1000);

  Log.getLogWriter().info("Killing data node on host " + host
                           + " pid = " + pid + ", see "
                           + dnd.getLogDir() + " for output");

  HDFSUtilBB.getBB().getSharedCounters().increment(HDFSUtilBB.recycleInProgress);
  if (hdd.isSecure()) {   // do not do a mean kill here or jsvc will spawn another data node
    ProcessMgr.shutdownProcess(host, pid);
  } else {
    ProcessMgr.killProcess(host, pid);
  }

  Log.getLogWriter().info("Killed data node on host " + host
                           + " pid = " + pid + ", see "
                           + dnd.getLogDir() + " for output");

  MasterController.sleepForMs(HDFSPrms.hadoopStartWaitSec() * 1000);
  Log.getLogWriter().info("Restarting data node on host " + host
                          + " see " + dnd.getLogDir() + " for output");
  HadoopHelper.startDataNode(hadoopConfig, host);
  Log.getLogWriter().info("Restarted data node on host " + host
                          + " see " + dnd.getLogDir() + " for output");
  MasterController.sleepForMs(HDFSPrms.hadoopReturnWaitSec() * 1000);
  HDFSUtilBB.getBB().getSharedCounters().zero(HDFSUtilBB.recycleInProgress);
}

public static void recycleNameNode() {
  String hadoopConfig = ConfigPrms.getHadoopConfig();
  HadoopDescription hd = HadoopHelper.getHadoopDescription(hadoopConfig);
  List<HadoopDescription.NameNodeDescription> nnds = hd.getNameNodeDescriptions();
  if (nnds.isEmpty()) {
    String s = "Cannot recycle name node, nameNodeDescriptions is empty";
    throw new HydraRuntimeException(s);
  }
  HadoopDescription.NameNodeDescription nnd = nnds.get(0);
  String host = nnd.getHostName();

  String pidfn = nnd.getPIDDir() + "/hadoop-" + System.getProperty("user.name") + "-namenode.pid";
  Integer pid = getPid(pidfn);
  if (!ProcessMgr.processExists(host, pid)) {
    String s = pid + " for name node is not running on " + host
             + " see " + nnd.getLogDir() + " for output";
    throw new HydraRuntimeException(s);
  }

  Log.getLogWriter().info("Killing name node on host " + host
                          + " pid = " + pid + ", see "
                          + nnd.getLogDir() + " for output");
  MasterController.sleepForMs(HDFSPrms.hadoopStopWaitSec() * 1000);

  HDFSUtilBB.getBB().getSharedCounters().increment(HDFSUtilBB.recycleInProgress);
  ProcessMgr.killProcess(host, pid);
  Log.getLogWriter().info("Killed name node on host " + host
                          + " pid = " + pid + ", see "
                          + nnd.getLogDir() + " for output");

  MasterController.sleepForMs(HDFSPrms.hadoopStartWaitSec() * 1000);
  Log.getLogWriter().info("Restarting name node on host " + host
                          + " see " + nnd.getLogDir() + " for output");
  HadoopHelper.startNameNode(hadoopConfig, host);
  Log.getLogWriter().info("Restarted name node on host " + host
                          + " see " + nnd.getLogDir() + " for output");
  MasterController.sleepForMs(HDFSPrms.hadoopReturnWaitSec() * 1000);
  HDFSUtilBB.getBB().getSharedCounters().zero(HDFSUtilBB.recycleInProgress);
}

private static Integer getPid(String pidfn) {
  Integer pid = null;
  try {
    pid = new Integer(FileUtil.getContents(pidfn));
  } catch (NumberFormatException e) {
    String s = "Cannot read PID from file: " + pidfn;
    throw new HydraRuntimeException(s, e);
  } catch (RemoteException e) {
    String s = "Cannot read PID from file: " + pidfn;
    throw new HydraRuntimeException(s, e);
  } catch (IOException e) {
    String s = "Cannot read PID file: " + pidfn;
    throw new HydraRuntimeException(s, e);
  }
  return pid;
}

/** Utility method invoked by HydraTask_loadDataFromHDFS() for various streaming tests (e.g.  and ParRegTest).
 *  Given the the original region name (so we can access in HDFS), load a region with the operations stored
 *  in HDFS.  This is done in order (per bucket) ... so we should end up with the same region contents as the main workload vms.
 */
public static void loadDataFromHDFS(Region aRegion, String regionName) {
  Cache aCache = CacheHelper.getCache();
  GemFireCacheImpl cacheImpl = (GemFireCacheImpl)aCache;
  String hdfsStoreName = aRegion.getAttributes().getHDFSStoreName();
  HDFSStoreImpl storeImpl = (HDFSStoreImpl) cacheImpl.findHDFSStore(hdfsStoreName);
  Log.getLogWriter().info("validate() invoked for " + hdfsStoreName);

  FileSystem fs;
  try {
    fs = storeImpl.getFileSystem();
  } catch (IOException e1) {
    throw new HDFSIOException(e1.getMessage(), e1);
  }
  Log.getLogWriter().info("creating region based on files in HDFS directory: " + storeImpl.getHomeDir());
  try {
    Path basePath = new Path(storeImpl.getHomeDir());
    String pathPattern = regionName + "/*/*.*";

    String sep = File.separator;
    String hadoopCmd = " fs -ls " + basePath + sep + pathPattern;

    int vmid = RemoteTestModule.getMyVmid();
    String clientName = RemoteTestModule.getMyClientName();
    String host = RemoteTestModule.getMyHost();
    HostDescription hd = TestConfig.getInstance().getClientDescription( clientName ).getVmDescription().getHostDescription();
    String logfn = hd.getUserDir() + sep + "vm_" + vmid + "_" + clientName + "_" + host + "_loadDataFromHDFS.log";

    HadoopDescription hdd = HadoopHelper.getHadoopDescription(ConfigPrms.getHadoopConfig());
    if (hdd.isSecure()) { // kinit is required for mapreduce ... even with auth.to.local mapping
      Log.getLogWriter().info("HDFSUtil.loadDataFromHDFS()-execute kinit in secure mode");
      String userKinit = HadoopHelper.GFXD_SECURE_KEYTAB_FILE + " gfxd-secure@GEMSTONE.COM";
      HadoopHelper.executeKinitCommand(host, userKinit, 120);
    }

    HadoopHelper.runHadoopCommand(ConfigPrms.getHadoopConfig(), hadoopCmd, logfn);
    Path regionPath = new Path(basePath, pathPattern);
    FileStatus[] sortedListOfHoplogs = fs.globStatus(regionPath);

    for (int i = 0; i < sortedListOfHoplogs.length; i++) {
      Path hoplogPath = sortedListOfHoplogs[i].getPath();
      Log.getLogWriter().fine("Processing hoplog " + hoplogPath);
      try {
        loadSequenceFile(aRegion, fs, hoplogPath);
      } catch (FileNotFoundException fnfe) {
        if (hoplogPath.toString().endsWith(".tmp")) {
          Path newHoplogPath = getBaseHoplogPath(hoplogPath);  // returns the hoplogPath without a ".tmp" extension
          Log.getLogWriter().info("loadDataFromHDFS caught FileNotFoundException while processing " + hoplogPath + ", retrying with base filename " + newHoplogPath);
          loadSequenceFile(aRegion, fs, newHoplogPath);
        } else {
          throw new TestException("loadDataFromHDFS caught unexpected Exception for SequenceHoplog which is not a tmp file" + fnfe + "\n" + TestHelper.getStackTrace(fnfe));
        }
      }
    }
  } catch (TestException e) {
    throw e;
  } catch (Exception e) {
    throw new TestException("loadDataFromHDFS caught unexpected Exception " + e + ": " + TestHelper.getStackTrace(e));
  } finally {
    // if running with auth.to.local mapping, remove kerberos ticket created for running secure hdfs command
    HadoopDescription hdd = HadoopHelper.getHadoopDescription(ConfigPrms.getHadoopConfig());
    if (hdd.getSecurityAuthentication().equals(HadoopPrms.KERBEROS)) {
      HadoopHelper.executeKdestroyCommand(RemoteTestModule.getMyHost(), 120);
    }
  }
}

private static Path getBaseHoplogPath(Path hoplogPath) {
  String originalFilename = hoplogPath.toString();
  int tmpExtIndex = originalFilename.lastIndexOf(".tmp");
  String trimmedFilename = originalFilename.substring(0, tmpExtIndex);
  return new Path(trimmedFilename);
}

public static void loadSequenceFile(Region aRegion, FileSystem inputFS, Path sequenceFileName) throws Exception {
  SequenceFileHoplog hoplog = new SequenceFileHoplog(inputFS, sequenceFileName, null);
  HoplogIterator<byte[], byte[]> iter = hoplog.getReader().scan();
  boolean isSerialExecution = TestConfig.tab().booleanAt(hydra.Prms.serialExecution);

  while (iter.hasNext()) {
    iter.next();
    PersistedEventImpl te = UnsortedHoplogPersistedEvent.fromBytes((iter.getValue()));
    String stringkey = ((String)CacheServerHelper.deserialize(iter.getKey()));

    Operation op = te.getOperation();
    ValueHolder value = null;

    Object displayVal = null;
    if (te != null) {
      displayVal = (ValueHolder)te.getDeserializedValue();
    }
    Log.getLogWriter().fine("loadSequenceFile record: " + op.toString() + ": key = " + stringkey + ", value = " + displayVal);

    try {
      if (op.isCreate()) {
        aRegion.put(stringkey, (ValueHolder)te.getDeserializedValue());
      } else if (op.isUpdate()) {
        aRegion.put(stringkey, (ValueHolder)te.getDeserializedValue());
      }  else if (op.isDestroy()) {
        aRegion.destroy(stringkey);
      } else {
         Log.getLogWriter().info("StreamingValidator.loadSequenceFile(): Unexpected operation " + op.toString() + " : " + TestHelper.getStackTrace());
      }
    } catch (EntryNotFoundException e) {
      // If the operation is destroy and is a possibleDuplicate, ignore the entry not found exception,
      if (op.isDestroy() && te.isPossibleDuplicate()) {
        Log.getLogWriter().info("loadSequenceFile caught EntryNotFoundException for " + stringkey);
        continue;
      } else if (isSerialExecution) { // shouldn't happen with serial execution
        Log.getLogWriter().info("loadSequenceFile caught " + e + ":" +  TestHelper.getStackTrace(e));
        throw new TestException("loadSequenceFile caught unexpected Exception " + e + ":" + TestHelper.getStackTrace(e));
      }
    }
  }
  iter.close();
  hoplog.close();
}

/** Launch the MapReduce program specified by HDFSPrms.mapReduceClass
 *  by fgexec'ing a comand of the form:
 *    yarn --config jar <MapReduce>.class libjars <command-seperated-list of jars> <locator-host> <locator-port> <hdfs-home-dir> <test specific args>
 */
public static void execMapReduceJob() {
  String extraArgs = null;
  execMapReduceJob(extraArgs);
}

public static void execMapReduceJob(String extraArgs) {
  String mapReduceClassName = HDFSPrms.getMapReduceClassName();

  try {
    execMapReduceJob(mapReduceClassName, extraArgs);
  } finally {
    // if running without kinit, remove ticket created for mapreduce job
    HadoopDescription hdd = HadoopHelper.getHadoopDescription(ConfigPrms.getHadoopConfig());
    if (hdd.getSecurityAuthentication().equals(HadoopPrms.KERBEROS)) {
      HadoopHelper.executeKdestroyCommand(RemoteTestModule.getMyHost(), 120);
    }
  }
}

public static void execMapReduceJob(String mapReduceClassName, String extraArgs) {
  // Use the first locator for this distributed system
  List<DistributedSystemHelper.Endpoint> endpoints = DistributedSystemHelper.getSystemEndpoints();
  DistributedSystemHelper.Endpoint endpoint = endpoints.get(0);
  String locatorHost = endpoint.getHost();
  int locatorPort = endpoint.getPort();

  String sep = File.separator;
  String jtests = System.getProperty("JTESTS");
  String MRJarPath = jtests + sep + ".." + sep + "extraJars" + sep + "mapreduce.jar";
  String gemfireJarPath = jtests + sep + ".." + sep + ".." + sep + "product" + sep + "lib" + sep + "gemfire.jar";

  String gemfireLibPath = jtests + sep + ".." + sep + ".." + sep + "product" + sep + "lib";
  String hbaseJarPath = getHbaseJar(gemfireLibPath);

  String hdfsStoreConfig = ConfigPrms.getHDFSStoreConfig();
  HDFSStoreDescription hsd = HDFSStoreHelper.getHDFSStoreDescription(hdfsStoreConfig);
  String hdfsStoreName = hsd.getName();
  HadoopDescription hdd = HadoopHelper.getHadoopDescription(ConfigPrms.getHadoopConfig());
  String confDir = hdd.getResourceManagerDescription().getConfDir();
  String hdfsHomeDir = HDFSStoreHelper.getHDFSStore(hdfsStoreName).getHomeDir();

  String cmd = "env CLASSPATH=" + System.getProperty( "java.class.path" ) + " ";
  cmd += "env HADOOP_CLASSPATH=" + System.getProperty( "java.class.path" ) + " ";
  cmd += hdd.getHadoopDist() + sep + "bin" + sep + "yarn ";
  cmd += "--config " + confDir + " ";
  cmd += "jar " + MRJarPath + " ";
  cmd += mapReduceClassName + " ";
  cmd += " -libjars " + " " + MRJarPath + "," + gemfireJarPath + "," + hbaseJarPath + " ";
  cmd += locatorHost + " " + locatorPort + " " + hdfsHomeDir + " ";
  if (extraArgs != null) {
    cmd += extraArgs;
  }
  Log.getLogWriter().info("Executing " + cmd + "...");

  int vmid = RemoteTestModule.getMyVmid();
  String clientName = RemoteTestModule.getMyClientName();
  String host = RemoteTestModule.getMyHost();
  HostDescription hd = TestConfig.getInstance().getClientDescription( clientName ).getVmDescription().getHostDescription();

  String logfn = hd.getUserDir() + sep + "vm_" + vmid + "_" + clientName + "_" + host + "_" + mapReduceClassName + ".log";

  if (hdd.isSecure()) {   // execute kinit when running mapreduce, even when using auth.to.local mapping
    String userKinit = HadoopHelper.GFXD_SECURE_KEYTAB_FILE + " gfxd-secure@GEMSTONE.COM";
    HadoopHelper.executeKinitCommand(host, userKinit, 120);
  }

  int pid = ProcessMgr.bgexec(cmd, hd.getUserDir(), logfn);
  try {
    RemoteTestModule.Master.recordHDFSPIDNoDumps(hd, pid, false);
  } catch (RemoteException e) {
    String s = "Failed to record PID: " + pid;
    throw new HydraRuntimeException(s, e);
  }
  int maxWaitSec = (int)TestConfig.tab().longAt( Prms.maxResultWaitSec );
  if (!ProcessMgr.waitForDeath(host, pid, maxWaitSec)) {
    String s = "Waited more than " + maxWaitSec + " seconds for MapReduce Job";
    throw new HydraTimeoutException(s);
  }
  try {
    RemoteTestModule.Master.removeHDFSPIDNoDumps(hd, pid, false);
  } catch (RemoteException e) {
    Log.getLogWriter().info("execMapReduceJob caught " + e + ": " + TestHelper.getStackTrace(e));
    String s = "Failed to remove PID: " + pid;
    throw new HydraRuntimeException(s, e);
  }
  Log.getLogWriter().info("Completed MapReduce job  on host " + host +
                          " using command: " + cmd +
                          ", see " + logfn + " for output");
}

/** Returns the current hbase*gemfire*.jar file.
 *  Current file is:
 *     $GEMFIRE/lib/hbase-0.94.4-gemfire-r43816.jar
 */
private static String getHbaseJar(String gemfireLibPath) {
  class HbaseJarFilter implements FileFilter {
    public boolean accept(File fn) {
     return fn.getName().startsWith("hbase") &&
            fn.getName().contains("gemfire") &&
            fn.getName().endsWith(".jar");
    }
  };
  List<File> hbaseJars = FileUtil.getFiles(new File(gemfireLibPath),
                                           new HbaseJarFilter(),
                                           false);
  if (hbaseJars.size() != 1) {
    throw new TestException("TestException: cannot uniquely identify gemfire/lib/hbase*gemfire*.jar, please check for a change in hbase jar file naming");
  }
  File matchingJarFile = hbaseJars.get(0);
  return matchingJarFile.getAbsolutePath();
}

/** Exec a mapReduce job to find all updates for a particular entry and write
 *  those entries back out to a GemFire region (HDFS_RESULTS_REGION) as
 *  ("originalKey_EventNumber_Operation", value).  Note that destroyed keys have a value
 *  of "DESTORYED".  Creates the HDFSResultRegion if needed.
 */
public static synchronized void getAllHDFSEventsForKey(String keys) {
  Cache cache = CacheHelper.getCache();
  if (cache.getRegion(HDFS_RESULT_REGION) == null) {
    // make this a replicated region (so it doesn't affect rebalance, waitForRecovery, etc)
    Region hdfsResultRegion = cache.createRegionFactory(RegionShortcut.REPLICATE).
                addCacheListener(new SummaryLogListener()).
                create(HDFS_RESULT_REGION);
    Log.getLogWriter().info("Created hdfsResultRegion " + hdfsResultRegion.getFullPath() + " for dumping HDFS updates for " + keys);
    CacheServer cs = cache.addCacheServer();
    int port = PortHelper.getRandomPort();
    cs.setPort(port);
    try {
      cs.start();
      Log.getLogWriter().info("Started server listenening on port " + port);
    } catch (IOException e) {
      throw new TestException("getAllHDSEventsForKey caught " + e + " while starting a CacheServer " + TestHelper.getStackTrace(e));
    }
  }
  execMapReduceJob("hdfs.mapreduce.GetAllHDFSEventsForKey", keys);
}

/** Dump the HDFSResultRegion, created by the GetAllHDFSEventsForKey() mapreduce job.
 *  Useful for debugging lost events, etc in HDFS
 */
public static void dumpHDFSResultRegion() {
  StringBuffer hdfsOps = new StringBuffer();
  Region hdfsResultRegion = CacheHelper.getCache().getRegion(HDFS_RESULT_REGION);
  // We only create this if we need it, so perhaps there were no validation errors
  if (hdfsResultRegion == null) return;
  Set keySet = new TreeSet(hdfsResultRegion.keySet());
  for (Iterator it = keySet.iterator(); it.hasNext();) {
    String key = (String)it.next();
    Object o = hdfsResultRegion.get(key);
    hdfsOps.append("  " + key + ": " + o.toString() + "\n");
  }
  Log.getLogWriter().info("Contents of HDFSResultRegion = \n" + hdfsOps.toString());
}

public static String getHDFSStoreName(Region aRegion) {
  RegionAttributes attrs = aRegion.getAttributes();
  return attrs.getHDFSStoreName();
}

/**
 *  Utility methods to monitor and wait for HDFS AEQ to drain
 */
public static boolean serverAlive = true;

/**
 * Starts a thread to monitor HDFS AEQ queues (may be active across multiple vms).
 */
  public static synchronized void HydraTask_startQueueMonitor() {
    final StatisticsFactory statFactory = DistributedSystemHelper.getDistributedSystem();
    final String key = "AsyncEventQueueStatistics: eventQueueSize for vm_" + RemoteTestModule.getMyVmid();
    Log.getLogWriter().info("Starting event queue monitor with key: " + key);
    final SharedMap bb = HDFSBlackboard.getInstance().getSharedMap();

    Thread queueMonitor = new Thread(new Runnable() {

      public void run() {
        Statistics[] qStats = statFactory.findStatisticsByType(statFactory.findType(AsyncEventQueueStats.typeName));
        while(serverAlive) {
          SystemFailure.checkFailure(); // GemStoneAddition
          long qSize = 0;
          for(int i=0;i<qStats.length;i++) {
            qSize += qStats[i].getInt(AsyncEventQueueStats.getEventQueueSizeId());
          }
          Log.getLogWriter().fine("Updating " + key + " with eventQueueSize = " + qSize);
          bb.put(key, new Long(qSize));

          if(serverAlive) {
            try {
              Thread.sleep(1000);
            } catch(Exception e) {
              e.printStackTrace();
            }
          }
        }
      }

      protected void finalize() throws Throwable {
        Object o = bb.remove(key);
        Log.getLogWriter().severe("Removing HDFSBlackboard key " + key + " with value (HDFS AEQ size) = " + o);
        super.finalize();
      }

    }, "HDFS AEQ Monitor");

    queueMonitor.setDaemon(true);
    queueMonitor.start();
  }

/**
 * Waits {@link hydra.Prms#maxResultWaitSec} for HDFS AEQs to drain.
 * Suitable for use as a helper method or hydra task.
 */
  public static synchronized void HydraTask_waitForQueuesToDrain() {

    final SharedMap bb = HDFSBlackboard.getInstance().getSharedMap();
    long startTime = System.currentTimeMillis();

    HDFSStoreDescription hsd = HDFSStoreHelper.getHDFSStoreDescription(ConfigPrms.getHDFSStoreConfig());
    long maxWait = hsd.getBatchTimeInterval() + 180000;  // wait for batchTimeInterval(ms) + 3 minutes
    long entriesLeft = 0;
    while((System.currentTimeMillis()-startTime)<(maxWait)) {
      Set keySet = bb.getMap().keySet();
      Iterator kIt = keySet.iterator();
      boolean pass = true;
      while(kIt.hasNext()) {
        String k = (String)kIt.next();
        if(k.startsWith("AsyncEventQueueStatistics: eventQueueSize")) {
          Long value = (Long)bb.get(k);
          Log.getLogWriter().info("Checking event queue key: " + k + " found eventQueueSize = " + value);
          if(value.longValue()>0) {
            pass = false;
            entriesLeft = value.longValue();
            Log.getLogWriter().warning("Still waiting for " + k + " to drain. " + "Current value is " + value);
            break;
          }
        }
      }
      if(pass) {
        entriesLeft = 0;
        break;
      } else {
        try {
          Thread.sleep(1000);
        } catch(Exception e) {
          e.printStackTrace();
        }
      }
    }
    if(entriesLeft>0) {
      //Log.getLogWriter().info("TIMED OUT waiting for HDFS AEQ to drain.  eventQueueSize =  " + entriesLeft);
      throw new TestException("TIMED OUT waiting for HDFS AEQ to drain.  eventQueueSize =  " + entriesLeft);
    } else {
      Log.getLogWriter().info("QUEUES ARE DRAINED");
    }
  }
}


text:
layout: post
title: "Lab 8: Numerical Integration"
categories: lab
---

No new lab assignment this week. I will introduce Chapter 7 material.

You may use the remaining time to ask questions and work on your homework assignment.


text:
package io.core9.plugin.widgets.exceptions;

public class ComponentDoesNotExists extends Exception {

	private static final long serialVersionUID = 2735273956846447352L;

}


text:
<?php
class Advertisement_model extends CI_Model {
	public function __construct()
    {
		parent::__construct();
    }
    public $table = "advertisement";
    public $table_month = "advertisement_months";

    public function insert_advertiser_details($data=array()) {
		$data['created'] = date('Y-m-d H:i:s');
		$this->db->insert($this->table,$data);
		return $this->db->insert_id();
	}
    public function insert_advertiser_months($data=array()) {
		$data['created'] = date('Y-m-d H:i:s');
		$this->db->insert($this->table_month,$data);
		return $this->db->insert_id();
	}
    public function get_advertisement_details($param=null,$value=null,$company=true) {
		$this->db->select("*,advertisement.id as advertisement_id")
				->join("members","advertisement.member_id = members.id","left")
				->from($this->table);
		if($param && $value) {
			$this->db->where($this->table.".".$param,$value);
		}
		if($company) {
			$this->db->where($this->table.".".'company_id',$this->session->userdata['company_id']);
		}
		$query = $this->db->get();
		return $query->result_array();
	}

	public function getAdvertisementDetails($id)
	{
		$this->db->select('*')
			->from($this->table)
			->where('id', $id);

		$query = $this->db->get();

		if($query->row())
		{
			return $query->row();
		}

		return false;
	}
	public function edit_advertisement_details($id=null,$data=array()) {
		if($id) {
			$this->db->where('id',$id);
			$this->db->update($this->table,$data);
			return true;
		}
		return false;
	}

	public function estimate_cost($ids) {
		$sql = "SElECT sum(advertisement_amount) as total FROM advertisement_details where id IN (".$ids.")";
		$query = $this->db->query($sql);
		return $query->row()->total;
	}

	public function getLastPendingInvoiceByMemberId($member_id)
	{
		$sql = "SELECT advertisement.*,
				advertisement_details.advertisement_type, advertisement_details.advertisement_term,
				advertisement_details.advertisement_size,advertisement_details.advertisement_amount
				FROM advertisement
				LEFT JOIN advertisement_details ON advertisement_details.id = advertisement.advertisement_details_id
				WHERE member_id = '".$member_id."' ANd is_invoice = 0 ORDER BY advertisement.id LIMIT 0, 1";
		$query = $this->db->query($sql);
		return $query->row();
	}

	public function setInvoicedAdvertisementById($id = null)
	{
		if($id)
		{
			$sql = "UPDATE advertisement set is_invoice = 1 WHERE id = '" .$id. "'";

			return $this->db->query($sql);
		}

		return false;

	}
}


text:
import unittest

from idl.Environment import Environment
from idl.IDLError import IDLError

from idl.IDLImportError import IDLImportError
from test.TestBase import TestBase

class PackageTest(TestBase):
    def test_package_import(self):
        '''
        Basic package import test.
        '''

        src1 = '''
        package com.test1;

        typedef Src1Type;

        '''

        src2 = '''
        package com.test2;

        import com.test1;

        interface  Test{
            void test(Src1Type arg1);
        };

        typedef Src2Type;
        '''

        src3 = '''
        package other.test;

        import com.test1;

        import com.test2;

        struct Test{
            Src1Type field1;

            Src2Type field2;
        };

        '''

        env = Environment()

        env.compileSource(src1, 'module1')

        env.compileSource(src2, 'module2')

        env.compileSource(src3, 'module3')

    def test_type_import(self):
        '''
        Basic type import test.
        '''

        src1 = '''
        package com.test1;

        typedef Src1Type;

        '''

        src2 = '''
        package com.test2;

        import com.test1.Src1Type;

        interface  Test{
            void test(Src1Type arg1);
        };
        '''

        env = Environment()

        env.compileSource(src1, 'module1')

        env.compileSource(src2, 'module2')

    def test_errors(self):
        '''
        Package/import related errors test.
        '''

        # Missing package
        src = '''\
        package com.test;

        import com.unexisting;
        '''

        try:
            Environment().compileSource(src, 'test1')

            self.fail()
        except IDLImportError as e:
            self.assertEqual(e.line, 2)

        # Missing package declaration
        src = '''\

        typedef test;
        '''

        try:
            Environment().compileSource(src, 'test1')

            self.fail()
        except IDLError:
            pass

if __name__ == '__main__':
    unittest.main()


text:
using namespace ArduinoJson;

class DynamicJsonBuffer_Basic_Tests : public testing::Test {
 protected:
  DynamicJsonBuffer buffer;
};

TEST_F(DynamicJsonBuffer_Basic_Tests, InitialSizeIsZero) {
  ASSERT_EQ(0, buffer.size());
}

TEST_F(DynamicJsonBuffer_Basic_Tests, SizeIncreasesAfterAlloc) {
  buffer.alloc(1);
  ASSERT_LE(1U, buffer.size());
  buffer.alloc(1);
  ASSERT_LE(2U, buffer.size());
}

TEST_F(DynamicJsonBuffer_Basic_Tests, ReturnDifferentPointer) {
  void* p1 = buffer.alloc(1);
  void* p2 = buffer.alloc(2);
  ASSERT_NE(p1, p2);
}

TEST_F(DynamicJsonBuffer_Basic_Tests, Alignment) {
  size_t mask = sizeof(void*) - 1;

  for (size_t size = 1; size <= sizeof(void*); size++) {
    size_t addr = reinterpret_cast<size_t>(buffer.alloc(1));
    ASSERT_EQ(0, addr & mask);
  }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.08.09 at 09:22:32 PM IST
//

package org.w3.synthesis;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlMixed;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for sentence complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="sentence">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <group ref="{http://www.w3.org/2001/10/synthesis}sentence.class"/>
 *       <attribute ref="{http://www.w3.org/XML/1998/namespace}lang"/>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "sentence", propOrder = {
    "content"
})
public class Sentence {

    @XmlElementRef(name = "aws", namespace = "http://www.w3.org/2001/10/synthesis", type = JAXBElement.class, required = false)
    @XmlMixed
    protected List<Serializable> content;
    @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace")
    protected String lang;

    /**
     * Gets the value of the content property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the content property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getContent().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link JAXBElement }{@code <}{@link Sub }{@code >}
     * {@link JAXBElement }{@code <}{@link Prosody }{@code >}
     * {@link JAXBElement }{@code <}{@link SayAs }{@code >}
     * {@link JAXBElement }{@code <}{@link Object }{@code >}
     * {@link JAXBElement }{@code <}{@link Break }{@code >}
     * {@link String }
     * {@link JAXBElement }{@code <}{@link Voice }{@code >}
     * {@link JAXBElement }{@code <}{@link Audio }{@code >}
     * {@link JAXBElement }{@code <}{@link Phoneme }{@code >}
     * {@link JAXBElement }{@code <}{@link Emphasis }{@code >}
     * {@link JAXBElement }{@code <}{@link Mark }{@code >}
     *
     *
     */
    public List<Serializable> getContent() {
        if (content == null) {
            content = new ArrayList<Serializable>();
        }
        return this.content;
    }

    /**
     * Gets the value of the lang property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLang() {
        return lang;
    }

    /**
     * Sets the value of the lang property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLang(String value) {
        this.lang = value;
    }

}


text:
import TabNavigator from 'react-native-tab-navigator';
export default TabNavigator;


text:
(function ( $ ) {
	'use strict';

	$( document ).ready( function () {
		$( 'body' ).on( 'adding_to_cart', function ( event, $button, data ) {
			if ( $button && $button.hasClass( 'vc_gitem-link' ) ) {
				$button
					.addClass( 'vc-gitem-add-to-cart-loading-btn' )
					.parents( '.vc_grid-item-mini' )
					.addClass( 'vc-woocommerce-add-to-cart-loading' )
					.append( $( '

' ) );
			}
		} ).on( 'added_to_cart', function ( event, fragments, cart_hash, $button ) {
			if ( 'undefined' === typeof ($button) ) {
				$button = $( '.vc-gitem-add-to-cart-loading-btn' );
			}
			if ( $button && $button.hasClass( 'vc_gitem-link' ) ) {
				$button
					.removeClass( 'vc-gitem-add-to-cart-loading-btn' )
					.parents( '.vc_grid-item-mini' )
					.removeClass( 'vc-woocommerce-add-to-cart-loading' )
					.find( '.vc_wc-load-add-to-loader-wrapper' ).remove();
			}
		} );
	} );
})( window.jQuery );


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragments.DeveloperFragment">

    <!-- TODO: Update blank fragment layout -->
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:src="@drawable/digin_feature_graphic"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:background="@android:color/darker_gray"
        android:contentDescription="Logo for DigIn" />

</RelativeLayout>


text:
#include "base/polygraph.h"

#include "xstd/gadgets.h"
#include "loganalyzers/PhaseTrace.h"

Time PhaseTrace::TheWinLen = Time::Sec(60);

bool PhaseTraceWin::contains(Time tm) const {
	return start <= tm && tm < start + PhaseTrace::TheWinLen;
}

PhaseTrace::PhaseTrace() {
}

PhaseTrace::~PhaseTrace() {
	while (theWins.count()) delete theWins.pop().stats;
}

void PhaseTrace::configure(const StatIntvlRec &stats) {
	theAggr.merge(stats);
	theWins.stretch((int)(stats.theDuration/TheWinLen));
}

Time PhaseTrace::start() const {
	return theWins.count() ? theWins[0].start : Time();
}

Time PhaseTrace::winPos(int idx) const {
	Assert(0 <= idx && idx < theWins.count());
	return theWins[idx].start + TheWinLen/2;
}

const StatIntvlRec &PhaseTrace::winStats(int idx) const {
	Assert(0 <= idx && idx < theWins.count());
	Assert(theWins[idx].stats);
	return *theWins[idx].stats;
}

void PhaseTrace::addIntvl(Time tm, const StatIntvlRec &r) {
	PhaseTraceWin &w = allocWin(tm);
	w.stats->concat(r);
}

void PhaseTrace::mergeWin(const PhaseTraceWin &win) {
	PhaseTraceWin &w = allocWin(win.start);
	w.stats->merge(*win.stats);
}

void PhaseTrace::concatWin(const PhaseTraceWin &win) {
	PhaseTraceWin &w = allocWin(win.start);
	w.stats->concat(*win.stats);
}

PhaseTraceWin &PhaseTrace::allocWin(Time tm) {
	int idx = -1;
	if (!findWin(tm, idx)) {
		PhaseTraceWin win;
		win.stats = new StatIntvlRec;
		win.start = TheWinLen * (int)(tm/TheWinLen);
		theWins.insert(win, idx);
	}
	Assert(0 <= idx && idx < count());
	Assert(theWins[idx].stats);
	return theWins[idx];
}

// if tm belongs to a window, return that window's index
// otherwise, return index where a new window should be insterted to
// maintain win.start order
bool PhaseTrace::findWin(Time tm, int &idx) const {
	idx = 0;
	for (int left = 0, right = count() - 1; left <= right;) {
		idx = (left + right)/2;

		if (theWins[idx].contains(tm))
			return true;
		else
		if (theWins[idx].start < tm)
			left = ++idx;
		else
			right = idx-1;
	}
	return false;
}

void PhaseTrace::merge(const PhaseTrace &trace) {
	theAggr.merge(trace.theAggr);
	theWins.stretch(trace.theWins.count());

	for (int i = 0; i < trace.theWins.count(); ++i)
		mergeWin(trace.theWins[i]);
}

void PhaseTrace::concat(const PhaseTrace &trace) {
	theAggr.concat(trace.theAggr);
	theWins.stretch(theWins.count() + trace.theWins.count());

	for (int i = 0; i < trace.theWins.count(); ++i)
		concatWin(trace.theWins[i]);
}


text:
package com.crazyapps.crazynudgemail;

public enum TimeUnit {
	DAYS, HOURS;
}


text:
package hudson.plugins.jira;

import com.atlassian.jira.rest.client.api.RestClientException;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.google.common.base.Strings;
import hudson.Util;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.plugins.jira.selector.AbstractIssueSelector;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.AffectedFile;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.RepositoryBrowser;
import hudson.scm.SCM;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import static java.lang.String.format;

/**
 * Actual JIRA update logic.
 *
 * @author Kohsuke Kawaguchi
 */
class Updater {

    private SCM scm;
    private List<String> labels;

    private static final Logger LOGGER = Logger.getLogger(Updater.class.getName());

    /**
     * Debug flag.
     */
    public static boolean debug = false;

    public Updater(SCM scm) {
        this(scm, new ArrayList<String>());
    }

    public Updater(SCM scm, List<String> labels) {
        super();
        this.scm = scm;
        if (labels == null) {
            this.labels = new ArrayList<String>();
        } else {
            this.labels = labels;
        }
    }

    boolean perform(Run<?, ?> build, TaskListener listener, AbstractIssueSelector selector) {
        PrintStream logger = listener.getLogger();
        List<JiraIssue> issues = null;

        try {
            JiraSite site = JiraSite.get(build.getParent());
            if (site == null) {
                logger.println(Messages.Updater_NoJiraSite());
                build.setResult(Result.FAILURE);
                return true;
            }

            String rootUrl = Hudson.getInstance().getRootUrl();
            if (rootUrl == null) {
                logger.println(Messages.Updater_NoJenkinsUrl());
                build.setResult(Result.FAILURE);
                return true;
            }

            Set<String> ids = selector.findIssueIds(build, site, listener);

            if (ids.isEmpty()) {
                if (debug)
                    logger.println("No JIRA issues found.");
                return true;    // nothing found here.
            }

            JiraSession session = null;
            try {
                session = site.getSession();
            } catch (IOException e) {
                listener.getLogger().println(Messages.Updater_FailedToConnect());
                e.printStackTrace(listener.getLogger());
            }
            if (session == null) {
                logger.println(Messages.Updater_NoRemoteAccess());
                build.setResult(Result.FAILURE);
                return true;
            }

            boolean doUpdate = false;
            //in case of workflow, it may be null
            if (site.updateJiraIssueForAllStatus || build.getResult() == null) {
                doUpdate = true;
            } else {
                doUpdate = build.getResult().isBetterOrEqualTo(Result.UNSTABLE);
            }
            boolean useWikiStyleComments = site.supportsWikiStyleComment;

            issues = getJiraIssues(ids, session, logger);
            build.getActions().add(new JiraBuildAction(build, issues));

            if (doUpdate) {
                submitComments(build, logger, rootUrl, issues,
                        session, useWikiStyleComments, site.recordScmChanges, site.groupVisibility, site.roleVisibility);
            } else {
                // this build didn't work, so carry forward the issues to the next build
                build.addAction(new JiraCarryOverAction(issues));
            }
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Error updating JIRA issues. Saving issues for next build.", e);
            logger.println("Error updating JIRA issues. Saving issues for next build.\n" + e);
            if (issues != null && !issues.isEmpty()) {
                // updating issues failed, so carry forward issues to the next build
                build.addAction(new JiraCarryOverAction(issues));
            }
        }

        return true;
    }

    /**
     * Submits comments for the given issues.
     * Remvoes from issues issues which have been successfully updated or are invalid
     *
     * @param build
     * @param logger
     * @param jenkinsRootUrl
     * @param session
     * @param useWikiStyleComments
     * @param recordScmChanges
     * @param groupVisibility
     * @throws RestClientException
     */
    void submitComments(
            Run<?, ?> build, PrintStream logger, String jenkinsRootUrl,
            List<JiraIssue> issues, JiraSession session,
            boolean useWikiStyleComments, boolean recordScmChanges, String groupVisibility, String roleVisibility) throws RestClientException {

        // copy to prevent ConcurrentModificationException
        List<JiraIssue> copy = new ArrayList<JiraIssue>(issues);

        for (JiraIssue issue : copy) {
            logger.println(Messages.Updater_Updating(issue.id));

            try {
                session.addComment(
                        issue.id,
                        createComment(build, useWikiStyleComments, jenkinsRootUrl, recordScmChanges, issue),
                        groupVisibility, roleVisibility
                );
                if (!labels.isEmpty()) {
                    session.addLabels(issue.id, labels);
                }

            } catch (RestClientException e) {

                if (e.getStatusCode().or(0).equals(404)) {
                    logger.println(issue.id + " - JIRA issue not found. Dropping comment from update queue.");
                }

                if (e.getStatusCode().or(0).equals(403)) {
                    logger.println(issue.id + " - Jenkins JIRA user does not have permissions to comment on this issue. Preserving comment for future update.");
                    continue;
                }

                if (e.getStatusCode().or(0).equals(401)) {
                    logger.println(issue.id + " - Jenkins JIRA authentication problem. Preserving comment for future update.");
                    continue;
                }

                logger.println(Messages.Updater_FailedToCommentOnIssue(issue.id));
                logger.println(e.getLocalizedMessage());
            }

            // if no exception is thrown during update, remove from the list as succesfully updated
            issues.remove(issue);
        }

    }

    private static List<JiraIssue> getJiraIssues(Set<String> ids, JiraSession session, PrintStream logger) throws RemoteException {
        List<JiraIssue> issues = new ArrayList<JiraIssue>(ids.size());
        for (String id : ids) {

            Issue issue = session.getIssue(id);
            if (issue == null) {
                logger.println(id + " issue doesn't exist in JIRA");
                continue;
            }

            issues.add(new JiraIssue(issue));
        }
        return issues;
    }

    /**
     * Creates a comment to be used in JIRA for the build.
     * For example:
     *

     *  SUCCESS: Integrated in Job #nnnn (See [http://jenkins.domain/job/Job/nnnn/])\r
     *  JIRA-XXXX: Commit message. (Author _author@email.domain_:
     *  [https://bitbucket.org/user/repo/changeset/9af8e4c4c909/])\r
     *

     */
    private String createComment(Run<?, ?> build, boolean wikiStyle, String jenkinsRootUrl, boolean recordScmChanges, JiraIssue jiraIssue) {
        Result result = build.getResult();
        //if we run from workflow we dont known final result
        if(result == null)
            return format(
                    wikiStyle ?
                            "Integrated in [%2$s|%3$s]\n%4$s" :
                            "Integrated in Jenkins build %2$s (See [%3$s])\n%4$s",
                    jenkinsRootUrl,
                    build,
                    Util.encode(jenkinsRootUrl + build.getUrl()),
                    getScmComments(wikiStyle, build, recordScmChanges, jiraIssue));
        else
            return format(
                wikiStyle ?
                        "%6$s: Integrated in !%1$simages/16x16/%3$s! [%2$s|%4$s]\n%5$s" :
                        "%6$s: Integrated in Jenkins build %2$s (See [%4$s])\n%5$s",
                jenkinsRootUrl,
                build,
                result != null ? result.color.getImage() : null,
                Util.encode(jenkinsRootUrl + build.getUrl()),
                getScmComments(wikiStyle, build, recordScmChanges, jiraIssue),
                result.toString());
    }

    private String getScmComments(boolean wikiStyle, Run<?, ?> run, boolean recordScmChanges, JiraIssue jiraIssue) {
        StringBuilder comment = new StringBuilder();
        RepositoryBrowser repoBrowser = getRepositoryBrowser(run);
        for (ChangeLogSet<? extends Entry> set : RunScmChangeExtractor.getChanges(run)) {
            for (Entry change : set) {
                if (jiraIssue != null && !StringUtils.containsIgnoreCase(change.getMsg(), jiraIssue.id)) {
                    continue;
                }
                comment.append(createScmChangeEntryDescription(run, change, wikiStyle, recordScmChanges));
            }
        }

        if (jiraIssue != null) {
            final Run<?, ?> prev = run.getPreviousBuild();
            if (prev != null) {
                final JiraCarryOverAction a = prev.getAction(JiraCarryOverAction.class);
                if (a != null && a.getIDs().contains(jiraIssue.id)) {
                    comment.append(getScmComments(wikiStyle, prev, recordScmChanges, jiraIssue));
                }
            }
        }

        return comment.toString();
    }

    protected String createScmChangeEntryDescription(Run<?, ?> run, Entry change, boolean wikiStyle,
            boolean recordScmChanges) {
        StringBuilder description = new StringBuilder();
        RepositoryBrowser repoBrowser = getRepositoryBrowser(run);
        JiraSite site = JiraSite.get(run.getParent());

        if(change.getMsg() != null)
            description.append(change.getMsg());
        String revision = getRevision(change);
        if (revision != null) {
            description.append(" (");
            appendAuthorToDescription(change, description);
            if (site.isAppendChangeTimestamp() && change.getTimestamp() > 0) {
                appendChangeTimestampToDescription(description, site, change.getTimestamp());
                description.append(" ");
            }
            appendRevisionToDescription(change, wikiStyle, description, repoBrowser, revision);
            description.append(")");
        }
        description.append("\n");
        if (recordScmChanges) {
            appendAffectedFilesToDescription(change, description);
        }
        return description.toString();
    }

    protected void appendAuthorToDescription(Entry change, StringBuilder description) {
        if (change.getAuthor() != null) {
            change.getAuthor();
            String uid = change.getAuthor().getId();
            if (StringUtils.isNotBlank(uid)) {
                description.append(uid).append(": ");
            }
        }
    }

    protected void appendRevisionToDescription(Entry change, boolean wikiStyle, StringBuilder description,
            RepositoryBrowser repoBrowser, String revision) {
        URL url = null;
        if (repoBrowser != null) {
            try {
                url = repoBrowser.getChangeSetLink(change);
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, "Failed to calculate SCM repository browser link", e);
            }
        }
        if (url != null && StringUtils.isNotBlank(url.toExternalForm())) {
            if (wikiStyle) {
                description.append("[").append(revision).append("|");
                description.append(url.toExternalForm()).append("]");
            } else {
                description.append("[").append(url.toExternalForm()).append("]");
            }
        } else {
            description.append("rev ").append(revision);
        }
    }

    protected void appendAffectedFilesToDescription(Entry change, StringBuilder description) {
        // see http://issues.jenkins-ci.org/browse/JENKINS-2508
        // added additional try .. catch; getAffectedFiles is not supported
        // by all SCM implementations
        try {
            for (AffectedFile affectedFile : change.getAffectedFiles()) {
                description.append("* ");
                if(affectedFile.getEditType() != null)
                    description.append("(").append(affectedFile.getEditType().getName()).append(") ");
                if(affectedFile.getPath() != null)
                    description.append(affectedFile.getPath());
                description.append("\n");
            }
        } catch (UnsupportedOperationException e) {
            LOGGER.warning("Unsupported SCM operation 'getAffectedFiles'. Fall back to getAffectedPaths.");
            for (String affectedPath : change.getAffectedPaths()) {
                description.append("* ").append(affectedPath).append("\n");
            }
        }
    }

    protected void appendChangeTimestampToDescription(StringBuilder description, JiraSite site, long timestamp) {
        DateFormat df = null;
        if (!Strings.isNullOrEmpty(site.getDateTimePattern())) {
            df = new SimpleDateFormat(site.getDateTimePattern());
        } else {
            // default format for current locale
            df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
        }
        Date changeDate = new Date(timestamp);
        String dateTimeString = df.format(changeDate);
        description.append(dateTimeString);
    }

    private RepositoryBrowser<?> getRepositoryBrowser(Run<?, ?> run) {
        SCM scm = getScm();
        if (scm != null) {
            return scm.getEffectiveBrowser();
        }
        return null;
    }

    private static String getRevision(Entry entry) {
        String commitId = entry.getCommitId();
        if (commitId != null) {
            return commitId;
        }

        // fall back to old SVN-specific solution, if we have only installed an old subversion-plugin
        // which doesn't implement getCommitId, yet
        try {
            Class<?> clazz = entry.getClass();
            Method method = clazz.getMethod("getRevision", (Class[]) null);
            if (method == null) {
                return null;
            }
            Object revObj = method.invoke(entry, (Object[]) null);
            return (revObj != null) ? revObj.toString() : null;
        } catch (Exception e) {
            return null;
        }
    }

    private SCM getScm() {
        return scm;
    }

}


text:
<?php

defined('_JEXEC') or die('Restricted access');
?><?php if($this->values->filter){ ?>
	<input placeholder="<?php echo acymailing_translation('ACY_SEARCH'); ?>" type="text" name="search" id="acymailingsearch" value="<?php echo $this->escape($this->pageInfo->search); ?>" class="inputbox"/>
	<button class="btn button buttongo" onclick="this.form.submit();"><?php echo acymailing_translation('JOOMEXT_GO'); ?></button>
	<button class="btn button buttonreset" onclick="document.getElementById('acymailingsearch').value='';this.form.submit();"><?php echo acymailing_translation('JOOMEXT_RESET'); ?></button>
<?php }
echo $this->ordering;
$k = 1;
for($i = 0, $a = count($this->rows); $i < $a; $i++){
	$row =& $this->rows[$i];
	$row->subject = Emoji::Decode($row->subject);
	echo '
values->suffix.'">';

	if(!empty($row->thumb)) echo 'thumb.'"/>';
	echo 'config->get('open_popup', 1) ? 'class="modal" rel="{handler: \'iframe\', size: {x: '.intval($this->config->get('popup_width', 750)).', y: '.intval($this->config->get('popup_height', 550)).'}}"' : '').'href="'.acymailing_completeLink('archive&task=view&listid='.$row->listid.'&mailid='.$row->mailid.'-'.strip_tags($row->alias).$this->item, (bool)$this->config->get('open_popup', 1)).'">';
	echo acymailing_dispSearch($row->subject, $this->pageInfo->search).'';
	echo '';
	if($this->values->show_senddate && !empty($row->senddate)){
		echo ''.acymailing_translation_sprintf('ACY_SENT_ON', acymailing_getDate($row->senddate, acymailing_translation('DATE_FORMAT_LC3'))).'';
	}
	if($this->values->show_receiveemail){ ?>

				<input onclick="changeReceiveEmail(this.checked)" type="checkbox" name="receivemail[]" value="<?php echo $row->mailid; ?>" id="receive_<?php echo $row->mailid; ?>"/> <label for="receive_<?php echo $row->mailid; ?>"><?php echo acymailing_translation('RECEIVE_VIA_EMAIL'); ?>

		<?php
		if(!empty($row->summary)) echo '
';
	}
	if(!empty($row->summary)) echo ''.nl2br($row->summary).'';
	echo '
';
	$k = 3 - $k;
}
?>

	<div class="sectiontablefooter<?php echo $this->values->suffix; ?> pagination"><?php echo $this->pagination->getPagesLinks(); ?>

	<div class="sectiontablefooter<?php echo $this->values->suffix; ?>"><?php echo $this->pagination->getPagesCounter(); ?>


text:
package com.blackbear.flatworm.annotations;

import com.blackbear.flatworm.CardinalityMode;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Provides the ability to configure a Field Identity via annotations vs. the flatworm XML structure.
 *
 * @author Alan Henson
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD})
public @interface ForProperty {
    boolean enabled() default false;
    boolean isRecordStartLine() default false;
    boolean isRecordEndLine() default false;
    DataIdentity identity() default @DataIdentity;
    Cardinality cardinality() default @Cardinality(cardinalityMode = CardinalityMode.AUTO_RESOLVE);
}


text:
package com.xpedytor.resource.impl;

import com.xpedytor.model.Table;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import javax.ws.rs.core.Response;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

/**
 * Created by chakushy on 3/7/16.
 */
public class TableResourceImplTest {

    private TableResourceImpl resource;

    @Before
    public void setUp() {
        resource = new TableResourceImpl();
    }

    @After
    public void tearDown() {
        // nothing here yet
    }

    @Test
    public void test_getAllTables() {
        List<Table> tables = (List<Table>) resource.getAllTables().getEntity();
        assertNotNull(tables);
        assertEquals(2, tables.size());
    }

    // TODO implement a test that runs getAllTables and doesn't find anything

    @Test
    public void test_getTable() {
        Response res = resource.getTable(1);

        assertNotNull(res);
        assertEquals(Response.Status.OK.getStatusCode(), res.getStatus());

        Table table = (Table) res.getEntity();
        assertNotNull(table);
        assertEquals(1, table.getTableNumber());
    }

    @Test
    public void test_getTableNotFound() {
        Response res = resource.getTable(999); // does not exist

        assertNotNull(res);
        assertEquals(Response.Status.NOT_FOUND.getStatusCode(), res.getStatus());
    }

    @Test
    public void test_getTableInvalid() {
        Response res1 = resource.getTable(0);
        Response res2 = resource.getTable(-1);

        assertNotNull(res1);
        assertNotNull(res2);
        assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), res1.getStatus());
        assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), res2.getStatus());
    }
}


text:
from __future__ import print_function
from argparse import ArgumentParser, RawTextHelpFormatter
import os
import os.path
import platform
import re
import subprocess
import sys
import time
import glob

winsfx = ".exe"
testsfx = "_test.cpp"

def processCLIArgs():
    """
    Define and process the command line interface to the runTests.py script.
    """
    cli_description = "Generate and run stan math library tests."
    cli_epilog = "See more information at: https://github.com/stan-dev/stan"

    parser = ArgumentParser(
        description=cli_description,
        epilog=cli_epilog,
        formatter_class=RawTextHelpFormatter,
    )

    # Now define all the rules of the command line args and opts
    parser.add_argument(
        "-j", metavar="N", type=int, default=1, help="number of cores for make to use"
    )

    tests_help_msg = "The path(s) to the test case(s) to run.\n"
    tests_help_msg += "Example: 'src/test/unit', 'src/test/integration', and/or\n"
    tests_help_msg += "         'src/test/unit/version_test'"
    parser.add_argument("tests", nargs="+", type=str, help=tests_help_msg)
    parser.add_argument(
        "-m",
        "--make-only",
        dest="make_only",
        action="store_true",
        help="Don't run tests, just try to make them.",
    )
    # And parse the command line against those rules
    return parser.parse_args()

def stopErr(msg, returncode):
    """Report an error message to stderr and exit with a given code."""
    sys.stderr.write("%s\n" % msg)
    sys.stderr.write("exit now (%s)\n" % time.strftime("%x %X %Z"))
    sys.exit(returncode)

def isWin():
    return platform.system().lower().startswith(
        "windows"
    ) or os.name.lower().startswith("windows")

batchSize = 24 if isWin() else 200

def mungeName(name):
    """Set up the makefile target name"""
    if name.startswith("src") or name.startswith("./src"):
        name = name.replace("src/", "", 1)
    if name.endswith(testsfx):
        name = name.replace(testsfx, "_test")
        if isWin():
            name += winsfx
            name = name.replace("\\", "/")
    return name

def doCommand(command, exit_on_failure=True):
    """Run command as a shell command and report/exit on errors."""
    print("------------------------------------------------------------")
    print("%s" % command)
    if isWin() and command.startswith("make "):
        command = command.replace("make ", "mingw32-make ")
    p1 = subprocess.Popen(command, shell=True)
    p1.wait()
    if exit_on_failure and (not (p1.returncode is None) and not (p1.returncode == 0)):
        stopErr("%s failed" % command, p1.returncode)

def modelDependencies(tests):
    dependencies = []
    for filepath in tests:
        filepath = "src/" + filepath + ".cpp"
        if os.path.isfile(filepath) and filepath.endswith(testsfx):
            with open(filepath) as file:
                test_file_content = file.read()
                # look for TEST() and TEST_F()
                matches = re.findall(
                    r"#include <test/test-models/.*hpp>", test_file_content
                )
                for x in matches:
                    x = x.replace("#include <", "").replace(">", "")
                    dependencies.append(x)
    return dependencies

def makeTest(name, j):
    """Run the make command for a given single test."""
    doCommand("make -j%d %s" % (j or 1, name))

def runTest(name):
    executable = mungeName(name).replace("/", os.sep)
    xml = mungeName(name).replace(winsfx, "")
    command = '%s --gtest_output="xml:%s.xml"' % (executable, xml)
    doCommand(command)

def files_in_folder(folder):
    """Returns a list of files in the folder and all
    its subfolders recursively. The folder can be
    written with wildcards as with the Unix find command.
    """
    files = []
    for f in glob.glob(folder):
        if os.path.isdir(f):
            files.extend(files_in_folder(f + os.sep + "**"))
        else:
            files.append(f)
    return files

def findTests(base_path):
    files = []
    for test_path in base_path:
        files.extend(files_in_folder(test_path))
    tests = [f for f in files if f.endswith(testsfx)]
    return list(map(mungeName, tests))

def batched(tests):
    return [tests[i : i + batchSize] for i in range(0, len(tests), batchSize)]

def main():
    inputs = processCLIArgs()

    tests = findTests(inputs.tests)
    if not tests:
        stopErr("No matching tests found.", -1)

    for batch in batched(tests):
        modelHpp = modelDependencies(batch)
        if len(modelHpp) > 0:
            makeTest(" ".join(modelHpp), inputs.j)
        makeTest(" ".join(batch), inputs.j)

    if not inputs.make_only:
        for t in tests:
            runTest(t)

if __name__ == "__main__":
    main()


text:
Utilities for [Stylus](https://github.com/stylus/stylus).

**utilus** is trying to make styling process easier by hiding away the annoying parts, and adding new features with a nice to use APIs.

You'll get super comfy media queries, awesome flexgrid, and tons of CSS improvements and extensions. **utilus** also doesn't produce prefixes, that's what [autoprefixer](https://www.npmjs.com/package/autoprefixer) is for.

## Installation

```
npm install utilus --save-dev
```

## Usage

From within your styles, load the whole utilus:

```styl
@require 'utilus'
```

Or only the modules you are interested in:

```styl
@require 'utilus/media'
@require 'utilus/flexgrid'
```

## Examples

Comfy flexible grid system:

```styl
.container
	// define a custom grid for this element
	flexgrid: 12 columns 16px gutter around

	.item
		span: 4/12    // span item 4 out of 12 columns
		offset: 4/12  // offset item 4 out of 12 columns

// save a custom grid
utilus.flexgrid.main = flexgrid-type(12 columns 16px gutter around)

.container
	// and use later
	flexgrid: main
	// or use with some adjustments
	flexgrid: main gutter between
```

Easy media queries:

```styl
+media('screen <480px')
	color: red

// or with a shorthand
+screen('<480px')
	color: red

// or save custom query
utilus.media.mobile = media-query('screen <480px')

// and use later
+media('mobile')
	color: red
```

Tons of utility functions and CSS extensions:

```styl
clear: fix          // output clearfix
size: 100px         // set width & height to 100px
size: 100px 60px    // set width to 100px and height to 60px
margin: 5px _ 10px  // set top and bottom margin with underscore omission syntax
padding: 5px _ 10px // set top and bottom padding with underscore omission syntax
position: cover     // cover the parent relative element
position: center    // center within parent relative element
absolute: 5px _ _ 10px // position: absolute, top: 5px, left: 10px
overflow: ellipsis  // text ellipsis overflow
transition: all 300ms easing('in-quad') // easy easing references
width: rem(100px)   // style in `px` and respect the user browser settings at the same time
// and more!
```

## Documentation

[Documentation](https://github.com/darsain/utilus/blob/master/docs) is located in the `/docs` folder.

- **[Options](https://github.com/darsain/utilus/blob/master/docs/options.md)** - All **utilus** options.
- **[Flexgrid](https://github.com/darsain/utilus/blob/master/docs/flexgrid.md)** - Flexible grid based on flexbox and `calc()`.
- **[Media queries](https://github.com/darsain/utilus/blob/master/docs/media.md)** - Comfy media queries.
- **[CSS extensions](https://github.com/darsain/utilus/blob/master/docs/extensions.md)** - Extended and new CSS properties.
- **[Utilities](https://github.com/darsain/utilus/blob/master/docs/utilities.md)** - Helper mixins and plugins.

[List of available modules](https://github.com/darsain/utilus/blob/master/utilus) is located in the `/utilus` folder.

## License

[MIT](https://github.com/darsain/utilus/license.md)


text:
```javascript
// Shorthand for document ready
$(function(){
  styleItListener();
  // your code goes here.
});

var styleItListener = function(){
  var $form = $('#style_editor');
  $form.on('submit', function(){
    grabTheSelector();
    event.preventDefault();

  });
};

var grabTheSelector = function(){
  var $selector = $("input[name = 'selector']").val()
  var $property = $("input[name = 'property']").val()
  var $value = $("input[name = 'value']").val()
  // alert($property);

  $($selector).css($property,$value);
  alert("Did the color change?");
};
```
```javascript
$(document).ready(function () {
  switchTab();
});

var switchTab = function(){

  $(".tabs li").on("click", function(){
  $('li').removeClass("active");
  $(this).addClass("active");
  $('.tab-content').hide();
  var chosen = $(this).find("a").attr("href");
  $(chosen).show();
  })
};
```


text:
import random

from odoo import api, fields, models, _
from odoo.tools import email_split, email_split_and_format

class Order(models.Model):
    _name = 'plant.order'
    _description = 'Plant Order'
    _order = 'id DESC'
    _inherit = ['mail.thread', 'mail.activity.mixin', 'rating.mixin', 'utm.mixin']

    name = fields.Char(
        'Reference', default=lambda self: _('New'),
        required=True)
    user_id = fields.Many2one(
        'res.users', string='Responsible',
        index=True, required=True,
        default=lambda self: self.env.user)
    date_open = fields.Date(
        'Confirmation date', readonly=True)
    customer_id = fields.Many2one(
        'plant.customer', string='Customer',
        index=True, required=True)
    line_ids = fields.One2many(
        'plant.order.line', 'order_id', string='Order Lines')
    amount_total = fields.Integer(
        'Amount', compute='_compute_amount_total', store=True)
    company_id = fields.Many2one(
        'res.company', string='Company', related='user_id.company_id',
        reaodnly=True, store=True)
    currency_id = fields.Many2one(
        'res.currency', string='Currency', related='company_id.currency_id',
        readonly=True, required=True)
    state = fields.Selection([
        ('draft', 'Draft'),
        ('open', 'Open'),
        ('done', 'Done'),
        ('cancel', 'Canceled')], string='State',
        default='draft', index=True, required=True)

    @api.depends('line_ids.price')
    def _compute_amount_total(self):
        for order in self:
            order.amount_total = sum(order.mapped('line_ids.price'))

    def action_confirm(self):
        if self.state != 'draft':
            return
        return self.write({
            'state': 'open',
            'date_open': fields.Datetime.now(),
        })

    def action_get_ratings(self):
        action = self.env['ir.actions.act_window'].for_xml_id('rating', 'action_view_rating')
        return dict(
            action,
            domain=[('res_id', 'in', self.ids), ('res_model', '=', 'plant.order')],
        )

    def action_send_rating(self):
        rating_template = self.env.ref('plant_nursery.mail_template_plant_order_rating')
        for order in self:
            order.rating_send_request(rating_template, force_send=True)

    def message_new(self, msg_dict, custom_values=None):
        if custom_values is None:
            custom_values = {}

        # find or create customer
        email = email_split(msg_dict.get('email_from', False))[0]
        name = email_split_and_format(msg_dict.get('email_from', False))[0]
        customer = self.env['plant.customer'].find_or_create(email, name)

        # happy Xmas
        plants = self.env['plant.plant'].search([])
        plant = self.env['plant.plant'].browse([random.choice(plants.ids)])
        custom_values.update({
            'customer_id': customer.id,
            'line_ids': [(4, plant.id)],
        })
        return super(Order, self).message_new(msg_dict, custom_values=custom_values)

class OrderLine(models.Model):
    _name = 'plant.order.line'
    _description = 'Plant Order Line'
    _order = 'order_id DESC'
    _rec_name = 'order_id'

    order_id = fields.Many2one(
        'plant.order', string='Order',
        index=True, ondelete='cascade', required=True)
    plant_id = fields.Many2one(
        'plant.plant', string='Plant',
        index=True, ondelete='cascade', required=True)
    price = fields.Float('Price')

    @api.onchange('plant_id')
    def _onchange_plant_id(self):
        if self.plant_id:
            self.price = self.plant_id.price

    def create(self, values):
        if 'price' not in values:
            values['price'] = self.env['plant.plant'].browse(values['plant_id']).price
        return super(OrderLine, self).create(values)


text:
template <typename T>				class CEmptyClassTemplate	{};
template <typename T1, typename T2> class CEmptyClassTemplate2	{};

#include "manager_builder_allocator_constructor.h"

template <
	typename _algorithm,
	typename _manager,
	typename _builder,
	typename _allocator,
	template <typename _T> class _vertex = CEmptyClassTemplate,
	template <
		typename _1,
		typename _2
	>
	class	 _builder_allocator_constructor = CBuilderAllocatorConstructor,
	template <
		typename _1,
		typename _2,
		typename _3,
		template <
			typename _1,
			typename _2
		>
		class	 _4
	>
	class	 _manager_builder_allocator_constructor = CManagerBuilderAllocatorConstructor
>
struct CDataStorageConstructor :
	public _algorithm::template CDataStorage<
		_manager_builder_allocator_constructor<
			_manager,
			_builder,
			_allocator,
			_builder_allocator_constructor
		>,
		_vertex
	>
{
	typedef typename _algorithm::template CDataStorage<
		_manager_builder_allocator_constructor<
			_manager,
			_builder,
			_allocator,
			_builder_allocator_constructor
		>,
		_vertex
	> inherited;

	typedef typename inherited::CGraphVertex	CGraphVertex;
	typedef typename CGraphVertex::_index_type	_index_type;

	IC	CDataStorageConstructor (const u32 vertex_count) :
		inherited(vertex_count)
	{
	}
};


text:
//
// Copyright 2020 Google LLC
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//

using Google.Solutions.IapDesktop.Application.Services.Integration;
using Google.Solutions.IapDesktop.Application.Services.ProjectModel;
using Google.Solutions.IapDesktop.Application.Settings;
using Google.Solutions.IapDesktop.Application.Views.Properties;
using Google.Solutions.IapDesktop.Extensions.Shell.Services.ConnectionSettings;
using Google.Solutions.Mvvm.Binding;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Google.Solutions.IapDesktop.Extensions.Shell.Views.ConnectionSettings
{
    internal class ConnectionSettingsViewModel : ViewModelBase, IPropertiesInspectorViewModel
    {
        internal const string DefaultWindowTitle = "Connection settings";

        private readonly IConnectionSettingsService settingsService;
        private readonly IGlobalSessionBroker globalSessionBroker;

        private bool isInformationBarVisible = false;
        private IPersistentSettingsCollection inspectedObject = null;
        private string windowTitle = DefaultWindowTitle;

        public string InformationText => "Changes only take effect after reconnecting";

        public ConnectionSettingsViewModel(
            IConnectionSettingsService settingsService,
            IGlobalSessionBroker globalSessionBroker)
        {
            this.settingsService = settingsService;
            this.globalSessionBroker = globalSessionBroker;
        }

        //---------------------------------------------------------------------
        // Observable properties.
        //---------------------------------------------------------------------

        public bool IsInformationBarVisible
        {
            get => isInformationBarVisible;
            private set
            {
                this.isInformationBarVisible = value;
                RaisePropertyChange();
            }
        }

        public object InspectedObject
        {
            get => this.inspectedObject;
            private set
            {
                this.inspectedObject = (IPersistentSettingsCollection)value;
                RaisePropertyChange();
            }
        }

        public string WindowTitle
        {
            get => this.windowTitle;
            set
            {
                this.windowTitle = value;
                RaisePropertyChange();
            }
        }

        //---------------------------------------------------------------------
        // Actions.
        //---------------------------------------------------------------------

        public void SaveChanges()
        {
            Debug.Assert(this.inspectedObject != null);
            this.inspectedObject.Save();
        }

        public Task SwitchToModelAsync(IProjectModelNode node)
        {
            if (this.settingsService.IsConnectionSettingsAvailable(node))
            {
                this.IsInformationBarVisible =
                    node is IProjectModelInstanceNode vmNode &&
                    this.globalSessionBroker.IsConnected(vmNode.Instance);

                this.InspectedObject = this.settingsService.GetConnectionSettings(node);
                this.WindowTitle = DefaultWindowTitle + $": {node.DisplayName}";
            }
            else
            {
                // Unsupported node.
                this.InspectedObject = null;
                this.IsInformationBarVisible = false;
                this.WindowTitle = DefaultWindowTitle;
            }

            return Task.CompletedTask;
        }
    }
}