text:
#include "TrafficLight.h"
#include "RegionTLR.h"
#include "TrafficLightDetector.h"

#define BLACK CV_RGB(0, 0, 0)
#define WHITE CV_RGB(255, 255, 255)

struct regionCandidate {
  cv::Point  center;
  int    idx;
  double circleLevel;
  bool   isBlacked;
};

//#define SHOW_DEBUG_INFO
extern thresholdSet thSet;      // declared in traffic_light_lkf.cpp

/*
  check if val is in range from lower to uppper
  This function also consider circulation
*/
static inline  bool IsRange(const double lower, const double upper, const double val)
{
  if (lower <= upper) {
    if (lower <= val && val <= upper) {
      return true;
    }
  } else {
    if (val <= upper || lower <= val)
      return true;
  }

  return false;
} /* static inline  bool IsRange() */

static void colorExtraction(const cv::Mat& src, // input HSV image
                            cv::Mat*       dst, // specified color extracted binarized image
                            const double   hue_lower, const double hue_upper, // hue thresholds
                            const double   sat_lower, const double sat_upper, // satulation thresholds
                            const double   val_lower, const double val_upper) // value thresholds
{
  /* create imput image copy */
  cv::Mat input_img = src.clone();

  *dst = cv::Scalar::all(0);

  /*
    ref:
    http://qiita.com/crakaC/items/65fab9d0b0ac29e68ab6
   */

  /* create LookUp Table */
  cv::Mat lut(256, 1, CV_8UC3);
  for (int i=0; i<256; i++)
    {
	  lut.at<cv::Vec3b>(i)[0] = (IsRange(hue_lower, hue_upper, Actual_Hue(i))) ? 255 : 0;
	  lut.at<cv::Vec3b>(i)[1] = (IsRange(sat_lower, sat_upper, Actual_Sat(i))) ? 255 : 0;
	  lut.at<cv::Vec3b>(i)[2] = (IsRange(val_lower, val_upper, Actual_Val(i))) ? 255 : 0;
    }

  /* apply LUT to input image */
  cv::Mat extracted(input_img.rows, input_img.cols, CV_8UC3);
  LUT(input_img, lut, extracted);

  /* divide image into each channel */
  std::vector<cv::Mat> channels;
  split(extracted, channels);

  /* create mask */
  bitwise_and(channels[0], channels[1], *dst);
  bitwise_and(*dst, channels[2], *dst);

} /* static void colorExtraction() */

static bool checkExtinctionLight(const cv::Mat&  src_img,
                                 const cv::Point top_left,
                                 const cv::Point bot_right,
                                 const cv::Point bright_center)
{

  /* check whether new roi is included by source image */
  cv::Point roi_top_left;
  roi_top_left.x = (top_left.x < 0) ? 0 :
    (src_img.cols < top_left.x) ? src_img.cols : top_left.x;
  roi_top_left.y = (top_left.y < 0) ? 0 :
    (src_img.rows < top_left.y) ? src_img.rows : top_left.y;

  cv::Point roi_bot_right;
  roi_bot_right.x = (bot_right.x < 0) ? 0 :
    (src_img.cols < bot_right.x) ? src_img.cols : bot_right.x;
  roi_bot_right.y = (bot_right.y < 0) ? 0 :
    (src_img.rows < bot_right.y) ? src_img.rows : bot_right.y;

  cv::Mat roi = src_img(cv::Rect(roi_top_left, roi_bot_right));

  cv::Mat roi_HSV;
  cvtColor(roi, roi_HSV, CV_BGR2HSV);

  cv::Mat hsv_channel[3];
  split(roi_HSV, hsv_channel);

  int anchor = 3;
  cv::Mat kernel = getStructuringElement(cv::MORPH_ELLIPSE, cv::Size(2*anchor + 1, 2*anchor + 1), cv::Point(anchor, anchor));

  cv::Mat topHat_dark;
  morphologyEx(hsv_channel[2], topHat_dark, cv::MORPH_TOPHAT, kernel, cv::Point(anchor, anchor), 5);

  /* sharpening */
  cv::Mat tmp;
  threshold(topHat_dark, tmp, 0.1*255, 255, cv::THRESH_BINARY_INV);
  tmp.copyTo(topHat_dark);

  /* filter by its shape and search dark region */
  std::vector< std::vector<cv::Point> > dark_contours;
  std::vector<cv::Vec4i> dark_hierarchy;
  findContours(topHat_dark,
               dark_contours,
               dark_hierarchy,
               CV_RETR_CCOMP,
               CV_CHAIN_APPROX_NONE);

  int contours_idx = 0;
  bool isThere_dark = false;

  /* check whether "turned off light" like region are in this roi */
  for (unsigned int i=0; i<dark_contours.size(); i++)
    {
      cv::Rect bound = boundingRect(dark_contours.at(contours_idx));
      double area = contourArea(dark_contours.at(contours_idx));
      double perimeter = arcLength(dark_contours.at(contours_idx), true);
      double circleLevel = (IsNearlyZero(perimeter)) ? 0.0f : (4.0f * CV_PI * area / pow(perimeter, 2));

      if (std::max(bound.width, bound.height) < 2*std::min(bound.width, bound.height) && // dimension ratio
          CIRCLE_LEVEL_THRESHOLD <= circleLevel)                                         // round enough

        {
          isThere_dark = true;
          // std::cerr << "there is dark region" << std::endl;
        }

      contours_idx = dark_hierarchy[contours_idx][0];
      if (contours_idx < 0)
        break;
    }

  return isThere_dark;

} /* static bool checkExtinctionLight() */

static cv::Mat signalDetect_inROI(const cv::Mat& roi,
                                  const cv::Mat&     src_img,
                                  const double       estimatedRadius,
                                  const cv::Point roi_topLeft,
                                  bool in_turn_signal //if true it will not try to mask by using "circularity""
                                  )
{
  /* reduce noise */
  cv::Mat noiseReduced(roi.rows, roi.cols, CV_8UC3);
  GaussianBlur(roi, noiseReduced, cv::Size(3, 3), 0, 0);

  /* extract color information */
  cv::Mat red_mask(roi.rows, roi.cols, CV_8UC1);
  colorExtraction(noiseReduced       ,
                  &red_mask          ,
                  thSet.Red.Hue.lower, thSet.Red.Hue.upper,
                  thSet.Red.Sat.lower, thSet.Red.Sat.upper,
                  thSet.Red.Val.lower, thSet.Red.Val.upper);

  cv::Mat yellow_mask(roi.rows, roi.cols, CV_8UC1);
  colorExtraction(noiseReduced          ,
                  &yellow_mask          ,
                  thSet.Yellow.Hue.lower, thSet.Yellow.Hue.upper,
                  thSet.Yellow.Sat.lower, thSet.Yellow.Sat.upper,
                  thSet.Yellow.Val.lower, thSet.Yellow.Val.upper);

  cv::Mat green_mask(roi.rows, roi.cols, CV_8UC1);
  colorExtraction(noiseReduced         ,
                  &green_mask          ,
                  thSet.Green.Hue.lower, thSet.Green.Hue.upper,
                  thSet.Green.Sat.lower, thSet.Green.Sat.upper,
                  thSet.Green.Val.lower, thSet.Green.Val.upper);

  /* combine all color mask and create binarized image */
  cv::Mat binarized = cv::Mat::zeros(roi.rows, roi.cols, CV_8UC1);
  bitwise_or(red_mask, yellow_mask, binarized);
  bitwise_or(binarized, green_mask, binarized);
  threshold(binarized, binarized, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU);

  /* filter by its shape and index each bright region */
  std::vector< std::vector<cv::Point> > bright_contours;
  std::vector<cv::Vec4i> bright_hierarchy;
  findContours(binarized,
               bright_contours,
               bright_hierarchy,
               CV_RETR_CCOMP,
               CV_CHAIN_APPROX_NONE);

  cv::Mat bright_mask = cv::Mat::zeros(roi.rows, roi.cols, CV_8UC1);

  int contours_idx = 0;
  std::vector<regionCandidate> candidates;
  for (unsigned int i=0; i<bright_contours.size(); i++)
    {
      cv::Rect bound = boundingRect(bright_contours.at(contours_idx));
      cv::Scalar rangeColor = BLACK;
      struct regionCandidate cnd;
      double area = contourArea(bright_contours.at(contours_idx)); // unit : pixel
      double perimeter = arcLength(bright_contours.at(contours_idx), true);
      double circleLevel = (IsNearlyZero(perimeter)) ? 0.0f : (4.0f * CV_PI * area / pow(perimeter, 2));

      double area_lower_limit = (3*sqrt(3)) * pow(estimatedRadius / 3.0, 2) / 4; // the area of inscribed triangle of 1/3 circle
      double area_upper_limit = pow(estimatedRadius, 2) * M_PI;                  // the area of the circle

      if (std::max(bound.width, bound.height) < 2*std::min(bound.width, bound.height) && /* dimension ratio */
          CIRCLE_LEVEL_THRESHOLD <= circleLevel                                       &&
          area_lower_limit <= area && area <= area_upper_limit)
        {
          // std::cerr << "circleLevel: " << circleLevel << std::endl;
          rangeColor    = WHITE;
          cnd.center.x  = bound.x + bound.width/2;
          cnd.center.y  = bound.y + bound.height/2;
          cnd.idx       = contours_idx;
          cnd.circleLevel = (IsNearlyZero(perimeter)) ? 0.0f : (4.0 * CV_PI * area / pow(perimeter, 2));
          cnd.isBlacked = false;
          candidates.push_back(cnd);
        }

      drawContours(bright_mask,
                   bright_contours,
                   contours_idx,
                   rangeColor,
                   CV_FILLED,
                   8,
                   bright_hierarchy,
                   0);

      /* only contours on toplevel are considered */
      contours_idx = bright_hierarchy[contours_idx][0];
      if (contours_idx < 0)
        break;
    }

#ifdef SHOW_DEBUG_INFO
  imshow("bright_mask", bright_mask);
  cv::waitKey(10);
#endif

  unsigned int candidates_num = candidates.size();

  // std::cerr << "before checkExtrinctionLight. candidates: " << candidates_num << std::endl;

  /* decrease candidates by checking existence of turned off light in their neighborhood */
  if (!in_turn_signal && candidates_num > 1)    /* if there are multipule candidates */
    {
      for (unsigned int i=0; i<candidates.size(); i++)
        {
          /* check wheter this candidate seems to be green lamp */
          cv::Point check_roi_topLeft  = cv::Point(candidates.at(i).center.x - 2*estimatedRadius + roi_topLeft.x,
                                                   candidates.at(i).center.y - 2*estimatedRadius + roi_topLeft.y);
          cv::Point check_roi_botRight = cv::Point(candidates.at(i).center.x + 6*estimatedRadius + roi_topLeft.x,
                                                   candidates.at(i).center.y + 2*estimatedRadius + roi_topLeft.y);
          bool likeGreen = checkExtinctionLight(src_img, check_roi_topLeft, check_roi_botRight, candidates.at(i).center);

          /* check wheter this candidate seems to be yellow lamp */
          check_roi_topLeft  = cv::Point(candidates.at(i).center.x - 4*estimatedRadius + roi_topLeft.x,
                                     candidates.at(i).center.y - 2*estimatedRadius + roi_topLeft.y);
          check_roi_botRight = cv::Point(candidates.at(i).center.x + 4*estimatedRadius + roi_topLeft.x,
                                     candidates.at(i).center.y + 2*estimatedRadius + roi_topLeft.y);
          bool likeYellow = checkExtinctionLight(src_img, check_roi_topLeft, check_roi_botRight, candidates.at(i).center);

          /* check wheter this candidate seems to be red lamp */
          check_roi_topLeft  = cv::Point(candidates.at(i).center.x - 6*estimatedRadius + roi_topLeft.x,
                                     candidates.at(i).center.y - 2*estimatedRadius + roi_topLeft.y);
          check_roi_botRight = cv::Point(candidates.at(i).center.x + 2*estimatedRadius + roi_topLeft.x,
                                     candidates.at(i).center.y + 2*estimatedRadius + roi_topLeft.y);
          bool likeRed = checkExtinctionLight(src_img, check_roi_topLeft, check_roi_botRight, candidates.at(i).center);

          if (!likeGreen && !likeYellow && !likeRed) /* this region may not be traffic light */
            {
              candidates_num--;
              drawContours(bright_mask,
                           bright_contours,
                           candidates.at(i).idx,
                           BLACK,
                           CV_FILLED,
                           8,
                           bright_hierarchy,
                           0);
              candidates.at(i).isBlacked = true;
            }
        }
    }

  // std::cerr << "after checkExtrinctionLight. candidates: " << candidates_num << std::endl;

  /* choose one candidate by comparing degree of circularity */
  if (!in_turn_signal && candidates_num > 1)       /* if there are still multiple candidates */
    {
      double min_diff = DBL_MAX;
      unsigned int min_idx = 0;

      /* search the region that has nearest degree of circularity to 1 */
      for (unsigned int i=0; i<candidates.size(); i++)
        {
          if(candidates.at(i).isBlacked)
            continue;

          double diff = fabs(1 - candidates.at(i).circleLevel);
          if (min_diff > diff)
            {
              min_diff = diff;
              min_idx = i;
            }
        }

      /* fill region of non-candidate */
      for (unsigned int i=0; i<candidates.size(); i++)
        {

          if(candidates.at(i).isBlacked)
            continue;

          cv::Scalar regionColor = BLACK;
          candidates.at(i).isBlacked = true;
          if (i == min_idx)
            {
              regionColor = WHITE;
              candidates.at(i).isBlacked = false;
            }

          drawContours(bright_mask,
                       bright_contours,
                       candidates.at(i).idx,
                       regionColor,
                       CV_FILLED,
                       8,
                       bright_hierarchy,
                       0);
        }
    }

  return bright_mask;

} /* static void signalDetect_inROI() */

/* constructor for non initialize value */
TrafficLightDetector::TrafficLightDetector() {}

void TrafficLightDetector::brightnessDetect(const cv::Mat &input) {

  cv::Mat tmpImage;
  input.copyTo(tmpImage);

  /* contrast correction */
  cv::Mat tmp;
  cvtColor(tmpImage, tmp, CV_BGR2HSV);
  std::vector<cv::Mat> hsv_channel;
  split(tmp, hsv_channel);

  float correction_factor = 10.0;
  uchar lut[256];
  for (int i=0; i<256; i++) {
    lut[i] = 255.0 / (1 + exp(-correction_factor*(i-128)/255));
  }

  LUT(hsv_channel[2], cv::Mat(cv::Size(256, 1), CV_8U, lut), hsv_channel[2]);
  merge(hsv_channel, tmp);
  cvtColor(tmp, tmpImage, CV_HSV2BGR);

  for (int i = 0; i < static_cast<int>(contexts.size()); i++) {
    Context context = contexts.at(i);

    if (context.topLeft.x > context.botRight.x)
      continue;

    /* extract region of interest from input image */
    cv::Mat roi = tmpImage(cv::Rect(context.topLeft, context.botRight));

    /* convert color space (BGR -> HSV) */
    cv::Mat roi_HSV;
    cvtColor(roi, roi_HSV, CV_BGR2HSV);

    /* search the place where traffic signals seem to be */
    cv::Mat    signalMask    = signalDetect_inROI(roi_HSV, input.clone(),
                                                  context.lampRadius,
                                                  context.topLeft,
                                                  context.leftTurnSignal || context.rightTurnSignal);

    /* detect which color is dominant */
    cv::Mat extracted_HSV;
    roi.copyTo(extracted_HSV, signalMask);

#ifdef SHOW_DEBUG_INFO
    extracted_HSV.copyTo(roi);
    imshow("tmpImage", tmpImage);
    cv::waitKey(5);
#endif

    cvtColor(extracted_HSV, extracted_HSV, CV_BGR2HSV);

    int red_pixNum    = 0;
    int yellow_pixNum = 0;
    int green_pixNum  = 0;
    int valid_pixNum  = 0;
    for (int y=0; y<extracted_HSV.rows; y++)
      {
        for (int x=0; x<extracted_HSV.cols; x++)
          {
            /* extract H, V value from pixel */
            double hue = Actual_Hue(extracted_HSV.at<cv::Vec3b>(y, x)[0]);
            uchar  val = extracted_HSV.at<cv::Vec3b>(y, x)[2];

            if (val == 0) {
              continue;         // this is masked pixel
            }
            valid_pixNum++;

            /* search which color is actually bright */
            if (IsRange(thSet.Red.Hue.lower, thSet.Red.Hue.upper, hue)) {
              red_pixNum++;
            }

            if (IsRange(thSet.Yellow.Hue.lower, thSet.Yellow.Hue.upper, hue)) {
              yellow_pixNum++;
            }

            if (IsRange(thSet.Green.Hue.lower, thSet.Green.Hue.upper, hue)) {
              green_pixNum++;
            }
          }
    }

    // std::cout << "(green, yellow, red) / valid = (" << green_pixNum << ", " << yellow_pixNum << ", " << red_pixNum << ") / " << valid_pixNum <<std::endl;

    bool isRed_bright;
    bool isYellow_bright;
    bool isGreen_bright;

    if (valid_pixNum > 0) {
      isRed_bright    = ( ((double)red_pixNum / valid_pixNum)    > 0.5) ? true : false;
      isYellow_bright = ( ((double)yellow_pixNum / valid_pixNum) > 0.5) ? true : false;
      isGreen_bright  = ( ((double)green_pixNum / valid_pixNum)  > 0.5) ? true : false;
    } else {
      isRed_bright    = false;
      isYellow_bright = false;
      isGreen_bright  = false;
    }

    int currentLightsCode = getCurrentLightsCode(isRed_bright, isYellow_bright, isGreen_bright);
    contexts.at(i).lightState = determineState(contexts.at(i).lightState, currentLightsCode, &(contexts.at(i).stateJudgeCount));

    roi.setTo(cv::Scalar(0));
  }
}

double getBrightnessRatioInCircle(const cv::Mat &input, const cv::Point center, const int radius) {

  int whitePoints = 0;
  int blackPoints = 0;

  for (int i = center.x - radius; i < center.x + radius; i++) {
    for (int j = center.y - radius; j < center.y + radius; j++) {
      if ((i - center.x)*(i - center.x) + (j - center.y)*(j - center.y) < radius*radius) {
        (input.at<uchar>(j,i) == 0) ? blackPoints++ : whitePoints++;
      }
    }
  }
  //printf("Ratio: %f\n", ((double)whitePoints) / (whitePoints + blackPoints));
  //std::cout << "(" << center.x << ", " << center.y << ") "<< "  white:" << whitePoints << " black: " << blackPoints << std::endl;
  return ((double)whitePoints) / (whitePoints + blackPoints);
}

int getCurrentLightsCode(bool display_red, bool display_yellow, bool display_green) {
  return (int)display_red + 2 * ((int) display_yellow) + 4 * ((int) display_green);
}

LightState determineState(LightState previousState, int currentLightsCode, int* stateJudgeCount) {
  //printf("Previous state: %d, currentCode: %d, Switched state to %d\n", previousState, currentLightsCode, STATE_TRANSITION_MATRIX[previousState][currentLightsCode]);
  LightState current = STATE_TRANSITION_MATRIX[previousState][currentLightsCode];

  if (current == UNDEFINED) {
    /* if current state is UNDEFINED, return previous state tentatively */
    return previousState;
  }

  if(*stateJudgeCount > CHANGE_STATE_THRESHOLD)
    {
      *stateJudgeCount = 0;
      return current;
    }
  else
    {
      (*stateJudgeCount)++;
      return previousState;
    }
}

/*
 *  Attempt to recognize by color tracking in HSV. Detects good only green, but need to
 *  play also with S and V parameters range.
 */
void TrafficLightDetector::colorDetect(const cv::Mat &input, cv::Mat &output, const cv::Rect coords, int Hmin, int Hmax) {

  if (input.channels() != 3) {
    return;
  }

  cv::Mat hsv, thresholded;
  cvtColor(input, hsv, CV_RGB2HSV, 0);
  inRange(hsv, cv::Scalar(Hmin,0,0), cv::Scalar(Hmax,255,255), thresholded);

  cvtColor(thresholded, thresholded, CV_GRAY2RGB);
  thresholded.copyTo(output);

  rectangle(output, coords, MY_COLOR_RED);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
	Copyright 2014 Bernd Vogt and others.

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.sourcepit.b2</groupId>
		<artifactId>b2</artifactId>
		<version>0.21.0-SNAPSHOT</version>
	</parent>
	<artifactId>b2-bootstrapper</artifactId>

	<dependencies>
		<dependency>
			<groupId>org.sourcepit.common</groupId>
			<artifactId>org.sourcepit.common.utils</artifactId>
		</dependency>
		<dependency>
			<groupId>org.sourcepit.tools</groupId>
			<artifactId>maven-bootstrap-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-core</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-model</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-model-builder</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.sourcepit.b2</groupId>
			<artifactId>b2-test-resources</artifactId>
			<type>test-jar</type>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-core</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
			</resource>
			<resource>
				<directory>src/dev/resources</directory>
				<targetPath>${project.build.directory}/dev/resources</targetPath>
				<filtering>true</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.codehaus.plexus</groupId>
				<artifactId>plexus-component-metadata</artifactId>
				<version>1.5.5</version>
				<executions>
					<execution>
						<goals>
							<goal>generate-metadata</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-shade-plugin</artifactId>
				<version>1.4</version>
				<executions>
					<execution>
						<phase>package</phase>
						<goals>
							<goal>shade</goal>
						</goals>
						<configuration>
							<filters>
								<filter>
									<artifact>*:*</artifact>
									<excludes>
										<exclude>META-INF/*.SF</exclude>
										<exclude>META-INF/*.DSA</exclude>
										<exclude>META-INF/*.RSA</exclude>
									</excludes>
								</filter>
							</filters>
							<transformers>
								<transformer implementation="org.apache.maven.plugins.shade.resource.ComponentsXmlResourceTransformer" />
								<transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
									<resource>META-INF/sisu/javax.inject.Named</resource>
								</transformer>
							</transformers>
						</configuration>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>

redpajama_set_name: RedPajamaGithub


text:
package com.hybris.service;

import com.google.common.base.Function;
import com.hybris.dao.GuestDao;
import com.hybris.dao.model.Guest;
import com.hybris.service.dto.GuestDto;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import static com.google.common.collect.Lists.transform;

@Service
@Transactional
public class DtoMappingGuestService implements GuestService {

    private GuestDao guestDao;

    private static final GuestToDto GUEST_TO_DTO_CONVERTER = new GuestToDto();
    private static final DtoToGuest DTO_TO_GUEST_CONVERTER = new DtoToGuest();

    @Autowired
    public DtoMappingGuestService(GuestDao guestDao) {
        this.guestDao = guestDao;
    }

    public List<GuestDto> getAllGuests() {

        return transform(guestDao.findAllByOrderByCreatedAsc(), GUEST_TO_DTO_CONVERTER);
    }

    @Override
    public GuestDto signGuest(GuestDto guest) {
        Guest newGuest = DTO_TO_GUEST_CONVERTER.apply(guest);
        newGuest.setCreated(DateTime.now());
        Guest savedGuest = guestDao.save(newGuest);
        return GUEST_TO_DTO_CONVERTER.apply(savedGuest);
    }

    private static class GuestToDto implements Function<Guest, GuestDto> {
        @Override
        public GuestDto apply(final Guest guest) {
            return new GuestDto(guest);
        }
    }

    private static class DtoToGuest implements Function<GuestDto, Guest> {
        @Override
        public Guest apply(final GuestDto guest) {
            Guest guestEntity = new Guest();
            guestEntity.setFirstname(guest.getFirstname());
            guestEntity.setLastname(guest.getLastname());
            guestEntity.setCreated(guest.getCreated());
            return guestEntity;
        }
    }
}


text:
INSERT INTO todo (description, created)
VALUES ('Fahrrad reparieren', CURRENT_TIMESTAMP),
('Einkaufen', CURRENT_TIMESTAMP);


text:
package org.assertj.core.internal.longarrays;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.assertj.core.error.ShouldNotHaveDuplicates.shouldNotHaveDuplicates;
import static org.assertj.core.test.LongArrays.*;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.assertj.core.util.Sets.newLinkedHashSet;

import static org.mockito.Mockito.verify;

import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.LongArrays;
import org.assertj.core.internal.LongArraysBaseTest;
import org.junit.jupiter.api.Test;

/**
 * Tests for <code>{@link LongArrays#assertDoesNotHaveDuplicates(AssertionInfo, long[])}</code>.
 *
 * @author Alex Ruiz
 * @author Joel Costigliola
 */
class LongArrays_assertDoesNotHaveDuplicates_Test extends LongArraysBaseTest {

  @Override
  protected void initActualArray() {
    actual = arrayOf(6L, 8L);
  }

  @Test
  void should_pass_if_actual_does_not_have_duplicates() {
    arrays.assertDoesNotHaveDuplicates(someInfo(), actual);
  }

  @Test
  void should_pass_if_actual_is_empty() {
    arrays.assertDoesNotHaveDuplicates(someInfo(), emptyArray());
  }

  @Test
  void should_fail_if_actual_is_null() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arrays.assertDoesNotHaveDuplicates(someInfo(), null))
                                                   .withMessage(actualIsNull());
  }

  @Test
  void should_fail_if_actual_contains_duplicates() {
    AssertionInfo info = someInfo();
    actual = arrayOf(6L, 8L, 6L, 8L);

    Throwable error = catchThrowable(() -> arrays.assertDoesNotHaveDuplicates(info, actual));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldNotHaveDuplicates(actual, newLinkedHashSet(6L, 8L)));
  }

  @Test
  void should_pass_if_actual_does_not_have_duplicates_according_to_custom_comparison_strategy() {
    arraysWithCustomComparisonStrategy.assertDoesNotHaveDuplicates(someInfo(), actual);
  }

  @Test
  void should_pass_if_actual_is_empty_whatever_custom_comparison_strategy_is() {
    arraysWithCustomComparisonStrategy.assertDoesNotHaveDuplicates(someInfo(), emptyArray());
  }

  @Test
  void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
    assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> arraysWithCustomComparisonStrategy.assertDoesNotHaveDuplicates(someInfo(), null))
                                                   .withMessage(actualIsNull());
  }

  @Test
  void should_fail_if_actual_contains_duplicates_according_to_custom_comparison_strategy() {
    AssertionInfo info = someInfo();
    actual = arrayOf(6L, -8L, 6L, -8L);

    Throwable error = catchThrowable(() -> arraysWithCustomComparisonStrategy.assertDoesNotHaveDuplicates(info, actual));

    assertThat(error).isInstanceOf(AssertionError.class);
    verify(failures).failure(info, shouldNotHaveDuplicates(actual, newLinkedHashSet(6L, -8L), absValueComparisonStrategy));
  }
}


text:
package com.bt.openlink.tinder.message;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import org.dom4j.Element;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;

import com.bt.openlink.message.CallStatusMessageBuilder;
import com.bt.openlink.tinder.internal.TinderPacketUtil;
import com.bt.openlink.type.CallStatus;

public class CallStatusMessage extends OpenlinkPubSubMessage {

    private static final String STANZA_DESCRIPTION = "call status";

    @Nullable private final CallStatus callStatus;

    private CallStatusMessage(@Nonnull final Builder builder, @Nullable final List<String> parseErrors) {
        super(builder, parseErrors);
        this.callStatus = builder.getCallStatus().orElse(null);
        final Element messageElement = getElement();
        final Element itemElement = TinderPacketUtil.addPubSubMetaData(messageElement, builder);
        getCallStatus().ifPresent(status->TinderPacketUtil.addCallStatus(itemElement, status));
        TinderPacketUtil.addDelay(messageElement, builder);
    }

    @Nonnull
    public Optional<CallStatus> getCallStatus() {
        return Optional.ofNullable(callStatus);
    }

    @Nonnull
    public static CallStatusMessage from(@Nonnull final Message message) {
        final List<String> parseErrors = new ArrayList<>();
        final Builder builder = Builder.start();
        final Element itemElement = TinderPacketUtil.setPubSubMetaData(message, builder, STANZA_DESCRIPTION, parseErrors);
        TinderPacketUtil.getCallStatus(itemElement, "callstatus message", parseErrors).ifPresent(builder::setCallStatus);
        return builder.build(parseErrors);
    }

    public static final class Builder extends CallStatusMessageBuilder<Builder, JID> {

        private Builder() {
        }

        @Nonnull
        public static Builder start() {
            return new Builder();
        }

        @Nonnull
        public CallStatusMessage build() {
            super.validate();
            return new CallStatusMessage(this, null);
        }

        @Nonnull
        protected CallStatusMessage build(final List<String> parseErrors) {
            super.validate(parseErrors);
            return new CallStatusMessage(this, parseErrors);
        }
    }
}


text:
package com.kelveden.rastajax.cli;

import com.kelveden.rastajax.core.ClassLoaderRootResourceScanner;
import com.kelveden.rastajax.core.RestDescriber;
import com.kelveden.rastajax.representation.flat.FlatRepresentationBuilder;
import com.kelveden.rastajax.representation.flat.FlatResource;
import com.kelveden.rastajax.representation.flat.FlatResourceMethod;
import com.kelveden.rastajax.representation.flat.FlatResourceMethodParameter;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;

public class Runner {

    private static final Logger LOGGER = LoggerFactory.getLogger(Runner.class);

    private static final String SUB_TEXT_PADDING = "    ";
    private static final String SUB_SUB_TEXT_PADDING = "       - ";

    private static final String ANSI_RESET = "\u001B[0m";
    private static final String ANSI_RED = "\u001B[31m";
    private static final String ANSI_GREEN = "\u001B[32m";
    private static final String ANSI_BLUE = "\u001B[34m";
    private static final String ANSI_CYAN = "\u001B[36m";

    public static void main(String[] args) throws CliExecutionException {

        if (args.length == 0) {
            System.out.println("Usage: rastajax <war file> [<comma-separated packages]");
            return;
        }

        final File warFile = args.length > 0 ? new File(args[0]) : findWar();
        final String packages = args.length > 1 ? args[1] : "com,org,net";

        LOGGER.info("Loading war from " + warFile.getAbsolutePath());

        final File workingDirectory = ensureWorkingDirectory();
        extractWarFile(warFile, workingDirectory);

        final List<URL> urls = getClasspathURLs(workingDirectory);

        final Set<FlatResource> representation = loadRepresentation(urls, packages);

        for (FlatResource f : representation) {
            printInfo("");
            printInfo(ANSI_GREEN + f.getUriTemplate() + ANSI_RESET);
            for (FlatResourceMethod m : f.getResourceMethods()) {
                writeResourceMethod(m);
            }
        }
    }

    private static Set<FlatResource> loadRepresentation(List<URL> urls, String packages) {

        final ClassLoader classLoader = new URLClassLoader(urls.toArray(new URL[] {}), Runner.class.getClassLoader());

        final ClassLoaderRootResourceScanner scanner = new ClassLoaderRootResourceScanner(
                classLoader,
                packages.split(",")).allowInterfaceInheritance();

        return RestDescriber.describeApplication(
                scanner.scan(),
                new FlatRepresentationBuilder());
    }

    private static List<URL> getClasspathURLs(File workingDirectory) throws CliExecutionException {

        final File classesFolder = new File(workingDirectory, "WEB-INF/classes");
        final File libFolder = new File(workingDirectory, "WEB-INF/lib");

        final List<URL> urls = new ArrayList<URL>();
        try {
            urls.add(classesFolder.toURI().toURL());

        } catch (final MalformedURLException e) {
            throw new CliExecutionException("Could not get the URL for '" + classesFolder.getAbsolutePath() + "'.", e);
        }

        for (File file : FileUtils.listFiles(libFolder, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE)) {
            try {
                urls.add(file.toURI().toURL());

            } catch (final MalformedURLException e) {
                throw new CliExecutionException("Could not get the URL for '" + file.getAbsolutePath() + "'.", e);
            }
        }

        return urls;
    }

    private static void extractWarFile(File warFile, File workingDirectory) throws CliExecutionException {
        try {
            ZipFile zipFile = new ZipFile(warFile);
            zipFile.extractAll(workingDirectory.getAbsolutePath());

        } catch (final ZipException e) {
            throw new CliExecutionException("Could not extract WAR file.", e);
        }
    }

    private static File ensureWorkingDirectory() throws CliExecutionException {

        final File tempFolder = new File(FileUtils.getTempDirectory(), "rastajax-explode");

        try {
            FileUtils.forceMkdir(tempFolder);
            FileUtils.cleanDirectory(tempFolder);

        } catch (final IOException e) {
            throw new CliExecutionException("Failed to ensure presence of working folder.", e);
        }

        return tempFolder;
    }

    private static File findWar() {
        final Collection<File> wars = FileUtils.listFiles(new File(System.getProperty("user.dir")), new String[] { "war" }, true);

        LOGGER.info("Found the following wars: " + wars.toString());

        if (wars.size() > 0) {
            return wars.iterator().next();
        } else {
            return null;
        }
    }

    private static void writeResourceMethod(FlatResourceMethod resourceMethod) {

        printInfo(SUB_TEXT_PADDING + ANSI_CYAN + resourceMethod.getRequestMethodDesignator() + ANSI_RESET + " [" + resourceMethod.getResourceClass() + "]");

        printInfo(SUB_SUB_TEXT_PADDING + ANSI_RED + resourceMethod.getName() + ANSI_RESET + "(" + parametersToString(resourceMethod) + ")");
        printInfo(mediaTypesToString(ANSI_CYAN + "Produces: " + ANSI_RESET, resourceMethod.getProduces()));
        printInfo(mediaTypesToString(ANSI_BLUE + "Consumes: " + ANSI_RESET, resourceMethod.getConsumes()));
    }

    private static String parametersToString(final FlatResourceMethod method) {

        final List<String> parameterNames = new ArrayList<String>();

        for (Map.Entry<String, List<FlatResourceMethodParameter>> parameterEntry : method.getParameters().entrySet()) {
            for (FlatResourceMethodParameter parameter : parameterEntry.getValue()) {
                parameterNames.add(ANSI_CYAN + parameter.getType() + ANSI_RESET + " " + parameter.getName());
            }
        }

        return StringUtils.join(parameterNames.toArray(new String[parameterNames.size()]), ", ");
    }

    private static String mediaTypesToString(final String header, final List<String> mediaTypes) {

        if (mediaTypes.size() == 0) {
            return null;
        } else {
            return SUB_SUB_TEXT_PADDING + header + StringUtils.join(mediaTypes.toArray(new String[mediaTypes.size()]), ", ");
        }
    }

    private static void printInfo(final String info) {
        if (info != null) {
            System.out.println(info);
        }
    }
}


text:
module SumTrees

export SumTree

import Base: show, setindex!, getindex, sum
import Base: start, next, done, length, eltype

immutable SumTree{T, NCells}
    tree::Vector{T}
end

function SumTree{T}(::Type{T}, ncells::Integer)
    SumTree{T, ncells}(zeros(T, 2 * ncells - 1))
end

# default type is Float64
SumTree(ncells::Integer) = SumTree(Float64, ncells)

function setindex!{T, NCells}(tree::SumTree{T, NCells}, value::T, idx::Integer)
    if idx < 1 || idx > NCells
        throw(BoundsError(tree, idx))
    end

    idx += NCells - 1
    tree.tree[idx] = value

    # bubble up sums
    while idx > 1
        tree.tree[idx >>> 1] = tree.tree[idx] + tree.tree[idx $ 1]
        idx >>>= 1
    end

    return nothing
end

function setindex!{T, NCells}(tree::SumTree{T, NCells}, value, idx::Integer)
    setindex!(tree, convert(T, value), idx)
end

function getindex{T, NCells}(tree::SumTree{T, NCells}, idx)
    if idx < 1 || idx > NCells
        throw(BoundsError(tree, idx))
    end

    tree.tree[idx + NCells - 1]
end

sum(tree::SumTree) = tree.tree[1]

length{T, NCells}(tree::SumTree{T, NCells}) = NCells

start{T, NCells}(tree::SumTree{T, NCells}) = NCells
next{T, NCells}(tree::SumTree{T, NCells}, state) = (tree.tree[state]::T, state + 1)
done{T, NCells}(tree::SumTree{T, NCells}, state) = state >= 2 * NCells

eltype{T, NCells}(tree::SumTree{T, NCells}) = T

function show{T, NCells}(io::IO, tree::SumTree{T, NCells})
    println(io, "SumTree{$T, $(NCells)} ::")

    level = 1
    while level <= NCells
        print(io, "    (")
        next_level = level * 2
        for i = level:(next_level - 1)
            print(io, "$(tree.tree[i]),")
        end
        println(io, ")")

        level = next_level
    end
end

end # module


text:
package org.gradoop.utils.statistics;

import org.apache.flink.api.common.ProgramDescription;
import org.gradoop.examples.AbstractRunner;
import org.gradoop.flink.model.impl.operators.matching.common.statistics.GraphStatisticsReader;
import org.gradoop.flink.model.impl.operators.statistics.OutgoingVertexDegreeDistribution;
import org.gradoop.flink.model.impl.operators.statistics.writer.StatisticWriter;

/**
 * Computes {@link OutgoingVertexDegreeDistribution} for a given logical graph.
 */
public class VertexOutgoingDegreeDistributionRunner extends AbstractRunner implements ProgramDescription {

  /**
   * args[0] - path to input directory
   * args[1] - input format (json, csv)
   * args[2] - path to output directory
   *
   * @param args arguments
   * @throws Exception if something goes wrong
   */
  public static void main(String[] args) throws Exception {

    StatisticWriter.writeCSV(new OutgoingVertexDegreeDistribution()
        .execute(readLogicalGraph(args[0], args[1])),
        appendSeparator(args[2]) + GraphStatisticsReader.OUTGOING_VERTEX_DEGREE_DISTRIBUTION);

    getExecutionEnvironment().execute("Statistics: Vertex outgoing degree distribution");
  }

  @Override
  public String getDescription() {
    return VertexOutgoingDegreeDistributionRunner.class.getName();
  }
}


text:
echo $GCLOUD_KEY | base64 --decode > gcloud.p12
gcloud config set account ACCOUNT
gcloud auth activate-service-account $GCLOUD_EMAIL --key-file gcloud.p12
ssh-keygen -f ~/.ssh/google_compute_engine -N ""


text:
package com.nevernote.fragments;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.evernote.client.android.login.EvernoteLoginFragment;
import com.nevernote.R;
import com.nevernote.presenters.NeverNoteLoginPresenter;
import com.nevernote.presenters.NeverNoteLoginPresenterImpl;
import com.nevernote.views.NeverNoteLoginView;

/**
 * Created by Roberto on 23/7/15.
 *
 * Login UI with a button that connects with Evernote's SDK to authenticate users. Uses MVP pattern
 * with a {@link NeverNoteLoginPresenter} instance that calls the authentication process and
 * notifies with the results.
 */
public class NeverNoteLoginFragment extends Fragment implements NeverNoteLoginView, View.OnClickListener {

    public static final String TAG = NeverNoteLoginFragment.class.getSimpleName();

    private NeverNoteLoginPresenter loginPresenter;

    private Button loginButton;

    public NeverNoteLoginFragment() {}

    @Override
    public void onCreate(Bundle savedInstanceState){

        super.onCreate(savedInstanceState);
        loginPresenter = new NeverNoteLoginPresenterImpl(this);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_never_note_login, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){

        super.onViewCreated(view, savedInstanceState);

        loginButton = (Button) view.findViewById(R.id.fragment_never_note_login_button);
        loginButton.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        //Call Evernote authentication through the presenter
        if (v.getId() == R.id.fragment_never_note_login_button)
            loginPresenter.onEvernoteAuthenticate(getActivity());
    }

    @Override
    public void enableLoginButton() {
        loginButton.setEnabled(true);
    }

    @Override
    public void disableLoginButton() {
        loginButton.setEnabled(false);
    }

    @Override
    public void onDestroy(){

        loginPresenter.setLoginView(null);
        loginPresenter = null;
        super.onDestroy();
    }

}


text:
package master

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

	"k8s.io/kubernetes/pkg/util"

	"github.com/stretchr/testify/assert"
)

// TestSecondsSinceSync verifies that proper results are returned
// when checking the time between syncs
func TestSecondsSinceSync(t *testing.T) {
	tunneler := &SSHTunneler{}
	assert := assert.New(t)

	tunneler.lastSync = time.Date(2015, time.January, 1, 1, 1, 1, 1, time.UTC).Unix()

	// Nano Second. No difference.
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.January, 1, 1, 1, 1, 2, time.UTC)}
	assert.Equal(int64(0), tunneler.SecondsSinceSync())

	// Second
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.January, 1, 1, 1, 2, 1, time.UTC)}
	assert.Equal(int64(1), tunneler.SecondsSinceSync())

	// Minute
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.January, 1, 1, 2, 1, 1, time.UTC)}
	assert.Equal(int64(60), tunneler.SecondsSinceSync())

	// Hour
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.January, 1, 2, 1, 1, 1, time.UTC)}
	assert.Equal(int64(3600), tunneler.SecondsSinceSync())

	// Day
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.January, 2, 1, 1, 1, 1, time.UTC)}
	assert.Equal(int64(86400), tunneler.SecondsSinceSync())

	// Month
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.February, 1, 1, 1, 1, 1, time.UTC)}
	assert.Equal(int64(2678400), tunneler.SecondsSinceSync())

	// Future Month. Should be -Month.
	tunneler.lastSync = time.Date(2015, time.February, 1, 1, 1, 1, 1, time.UTC).Unix()
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.January, 1, 1, 1, 1, 1, time.UTC)}
	assert.Equal(int64(-2678400), tunneler.SecondsSinceSync())
}

// TestRefreshTunnels verifies that the function errors when no addresses
// are associated with nodes
func TestRefreshTunnels(t *testing.T) {
	tunneler := &SSHTunneler{}
	tunneler.getAddresses = func() ([]string, error) { return []string{}, nil }
	assert := assert.New(t)

	// Fail case (no addresses associated with nodes)
	assert.Error(tunneler.refreshTunnels("test", "/tmp/undefined"))

	// TODO: pass case without needing actual connections?
}

// TestIsTunnelSyncHealthy verifies that the 600 second lag test
// is honored.
func TestIsTunnelSyncHealthy(t *testing.T) {
	tunneler := &SSHTunneler{}
	master, etcdserver, _, assert := setUp(t)
	defer etcdserver.Terminate(t)
	master.tunneler = tunneler

	// Pass case: 540 second lag
	tunneler.lastSync = time.Date(2015, time.January, 1, 1, 1, 1, 1, time.UTC).Unix()
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.January, 1, 1, 9, 1, 1, time.UTC)}
	err := master.IsTunnelSyncHealthy(nil)
	assert.NoError(err, "IsTunnelSyncHealthy() should not have returned an error.")

	// Fail case: 720 second lag
	tunneler.clock = &util.FakeClock{Time: time.Date(2015, time.January, 1, 1, 12, 1, 1, time.UTC)}
	err = master.IsTunnelSyncHealthy(nil)
	assert.Error(err, "IsTunnelSyncHealthy() should have returned an error.")
}

// generateTempFile creates a temporary file path
func generateTempFilePath(prefix string) string {
	tmpPath, _ := filepath.Abs(fmt.Sprintf("%s/%s-%d", os.TempDir(), prefix, time.Now().Unix()))
	return tmpPath
}

// TestGenerateSSHKey verifies that SSH key generation does indeed
// generate keys even with keys already exist.
func TestGenerateSSHKey(t *testing.T) {
	tunneler := &SSHTunneler{}
	assert := assert.New(t)

	privateKey := generateTempFilePath("private")
	publicKey := generateTempFilePath("public")

	// Make sure we have no test keys laying around
	os.Remove(privateKey)
	os.Remove(publicKey)

	// Pass case: Sunny day case
	err := tunneler.generateSSHKey("unused", privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Pass case: PrivateKey exists test case
	os.Remove(publicKey)
	err = tunneler.generateSSHKey("unused", privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Pass case: PublicKey exists test case
	os.Remove(privateKey)
	err = tunneler.generateSSHKey("unused", privateKey, publicKey)
	assert.NoError(err, "generateSSHKey should not have retuend an error: %s", err)

	// Make sure we have no test keys laying around
	os.Remove(privateKey)
	os.Remove(publicKey)

	// TODO: testing error cases where the file can not be removed?
}


text:
module Connection
  class HTTP < Base
    def connect!
      uri = parse_server(@server)
      @transport = Thrift::HTTPClientTransport.new(@server)
      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = uri.scheme == "https"
      http.get(uri.path)
    end

  private
    def parse_server(server)
      uri = URI.parse(server)
      raise ArgumentError, 'Servers must start with http' unless uri.scheme =~ /^http/
      uri
    end
  end
end


text:
package net.fortuna.ical4j.data;

import java.io.IOException;
import java.io.StringWriter;

import net.fortuna.ical4j.util.Strings;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import junit.framework.TestCase;

/**
 * $Id$
 *
 * Created on 21/01/2006
 *
 * Unit tests for FoldingWriter.
 * @author Ben Fortuna
 */
public class FoldingWriterTest extends TestCase {

    private static final Log LOG = LogFactory.getLog(FoldingWriterTest.class);

    /**
     * Test writing a line equal to fold length.
     */
    public void testLineLength73() throws IOException {
        StringWriter sw = new StringWriter();
        FoldingWriter writer = new FoldingWriter(sw);
        writer.write("BEGIN:VCALENDAR");
        writer.write(Strings.LINE_SEPARATOR);
        writer.write("PRODID:-//Open Source Applications Foundation//NONSGML Scooby Server//EN");
        writer.write(Strings.LINE_SEPARATOR);
        writer.write("VERSION:2.0");
        LOG.info(sw.getBuffer());
    }
}


text:
camera = {}
camera.settings = {}
camera.funcs = {}

camera.settings["max_view"]= 125;

camera.funcs["camera_update_check"] = function(self)
	if( self.XUVec == nil or self.YUVec == nil or self.ZUVec == nil or
		self.X == nil or self.Y == nil or self.Z == nil ) then
		error("Error reading memory in CCamera:update()");
	end

end


text:
import React from 'react';
import { StyleSheet, Image } from 'react-native';
import { NavigationComponentProps } from 'react-native-navigation';
import Root from '../components/Root';
import Button from '../components/Button';
import Navigation from '../services/Navigation';
import Screens from './Screens';

export default class StatusBarFirstTab extends React.Component<NavigationComponentProps> {
  visible = true;

  static options() {
    return {
      statusBar: {
        translucent: true,
        drawBehind: true,
      },
      topBar: {
        elevation: 0,
        drawBehind: true,
        background: {
          color: 'transparent',
        },
        title: {
          text: 'Pushed',
        },
      },
    };
  }

  render() {
    return (
      <Root componentId={this.props.componentId} style={style.root}>
        <Image style={style.image} source={require('../../img/city2.jpeg')} fadeDuration={0} />
        <Button label="Push" onPress={this.push} />
        <Button label="Toggle Tabs" onPress={this.toggleTabs} />
      </Root>
    );
  }

  push = () =>
    Navigation.push(this, Screens.Pushed, {
      bottomTabs: {
        visible: false,
        drawBehind: true,
      },
    });

  toggleTabs = () => {
    this.visible = !this.visible;
    Navigation.mergeOptions(this, {
      bottomTabs: {
        visible: this.visible,
        drawBehind: !this.visible,
        animate: true,
      },
    });
  };
}

const style = StyleSheet.create({
  root: {
    paddingTop: 0,
    paddingHorizontal: 0,
  },
  image: {
    height: 250,
    width: '100%',
    resizeMode: 'cover',
    marginBottom: 16,
  },
});


text:
A Jenkins utility job for analyzing and reporting the configuration of other freestyle jobs/projects

## Motivation
The configuration complexity of Jenkins freestyle jobs has increased, especially as we are now introducing dynamic parameter
behavior (using the [Active Choices](https://wiki.jenkins-ci.org/display/JENKINS/Active+Choices+Plugin) and other similar Jenkins plugins).
There is a need for a quick and concise way to review and access project parameters, builders, publishers, and Groovy code and plugin dependencies.

## What can JOB_CONFIG_ANALYZER do?
This utility Jenkins job allows you to select one of the jobs on your Jenkins server, analyze its configuration, and **create a concise report of the job's main elements** (parameters, scm, builders, publishers, build-wrappers) as well as the Groovy code, scripts and plugin dependencies.

By examining a JOB_CONFIG_ANALYZER build report you can immediately **visualize and access the target project's**:

1. parameters
2. SCM
3. builders
4. publishers
5. scriptlets, and Groovy code used
6. plugins used
7. order and sequence of these components

In addition, longitudinal builds of a project can be used as an annotated log/archive of the job's configuration changes.
Since **the configuration file of the analyzed project/job is archived**, it can be used to compare or even revert back to a particular configuration version by simply re-deploying it to the project folder on the server.

## Build Form
An example build form is shown below. Note that if the selected PROJECT_NAME (project) has been analyzed previously, those builds are listed in the PROJECT_HISTORY list.
The user can easily follow the links to review previous configuration analyses reports.
![Build Form](./userContent/assets/images/BuildForm.png?raw=true "Build Form")

## Console Report
The build console output is organized using the [Collapsing Console Sections Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Collapsing+Console+Sections+Plugin).
The console report displays a more detailed, textual view of the project configuration. Job component sections can be collapsed and expanded for easier inspection, and can be navigated to from a menu with section links.
![Console Report](./userContent/assets/images/ConsoleReport.png?raw=true "Console Report")

## Build report
The tabular build report uses the [Summary Display Plugin](https://wiki.jenkins-ci.org/display/JENKINS/Summary+Display+Plugin) to display each of the project configuration components in a separate tab.
This is somewhat similar to the Jenkins v2.+ tabular UI used for job configuration, but in a much more compact form.
Groovy code (whether embedded or managed in the scriptler catalog) and used in parameters, builders or publishers can be easily inspected and accessed from report links.
The names and versions of applicable plugins used in parameters, builders and publishers, and build-wrappers are also reported.

### Example Job Configuration Reports
![Example Report](./userContent/assets/images/ExampleReport.png?raw=true "example Report")
And here is the parameter report from a project with several dynamic parameters
![example Complex Param Report](./userContent/assets/images/ExampleReportComplexParam.png?raw=true "example Complex Param Report")

## Build Artifacts
Each build generates a number of archived artifacts as shown in the example below
![Build Artifacts](https://docs.google.com/drawings/d/1Gj9NMppm_3ElLFXQVX-LPQzNEHDkzCxDDWJbeuoKkmU/pub?w=639&h=600)

Archived artifacts are organized in **folders some of which reflect the typical layout of a Jenkins installation**. This makes it easier to package the job and as many of its dependencies for export to another server:

1. Folder `buildReportData` contains required data files for generating the tabbed build report
2. Folder `embeddedScripts` contains text files corresponding to embedded scripts (Groovy or command line script) in each of the project component. See naming convention for these scripts below.
3. Folder `externalScripts` contains external Groovy scripts used in build and post build steps
4. Folder `jobs/JOB_NAME` contains a copy of the `config.xml` file of the analyzed project.
5. Folder `scriptler/scripts` contains the script dependencies of the project. These include scriptlets used for Active Choice and other parameters, and build and post build steps.

The text scripts follow a naming convention `TYPE_SerialID_[parameterName||null]_script.txt` where file names use a *prefix indicating the component type where the script originated* (parameter, builder, publisher etc.) and it's *serial ID* (the sequence number by which the component is ordered in the configuration file). If the component is a parameter, the *parameter name is also included in the prefix*.

So, an embedded script used in the 10th job parameter named BUILD_LABEL it is identified by a name like: `parameter_10_BUILD_LABEL_script.txt`

## Limitations
It is possible that jobs using configuration components and build steps beyond the ones we have tested may not parse correctly.
We are using this utility primarily with freestyle projects that contain complex interacting parameters.

Pipeline, multi-configuration and multi-job projects have not been tested.
The [Cloudbees Folder Plugin](https://wiki.jenkins-ci.org/display/JENKINS/CloudBees+Folders+Plugin) is currently not supported. If your projects are organized using the Cloudbees Folder Plugin Jenkins-JobConfiguration Analyzer is not able to find the project configuration files.
If you would like to extend the parser, it should be possible to modify the code in [jobConfigParser](./scriptler/scripts/jobConfigParser.groovy) to detect new parameters types and build steps (these are always reported in the console).


text:
<meta content="text/html; charset=UTF-8"
http-equiv="content-type">
<title>Glossary of Terms</title>

Определение технических терминов

Хотя разработчики старались сделать PHD2 простой в использовании,
задача гидирования телескопа достаточно сложна.  Когда вы
пытаетесь решить проблемы с оборудованием или добиться хороших
результатов гидирования, вы можете столкнуться с незнакомыми
понятиями из областей статистики, астрономии и механики.
Некоторые из этих терминов используются в пользовательском
интерфейсе PHD2 и встречаются на форумах поддержки и в группах
рассылки, поэтому важно знать хотя бы в общих чертах, что они
означают.  Некоторые из терминов, с которыми вы, вероятно,
встретитесь, описаны ниже.

Среднее
квадратичное (RMS, "root-mean-square") - статистическая
величина, относящаяся к множеству данных.  В контексте PHD2 это
то же, что стандартное отклонение.  С помощью него можно
описать распределение данных вокруг некоей средней величины.
Применительно к задаче гидирования, нам интересно знать, как далеко
звезда перемещается по осям прямого восхождения и склонения.
Давайте рассмотрим последовательность точек, в которых оказывается
звезда в результате своего движения. Пусть их координаты выглядят
так:   1.0, -1.2, 1.5, -1.3, 1.0 -1.6, 1.4, -2.1, 1.2, -2.4,
1.2, -2.1 -1.1, 2.1, 0, 2.4, -1.2, 1.6, -1.5, 1.3, -1.0, 1.2 -1.6,
1.2.   Как мы можем оценить величину движения вокруг начальной
точки?  Мы можем вычислить среднее от этих отклонений - и
получим ноль!  Это нам не говорит вообще ни о чём, очевидно,
что 0 - негодная характеристика.  Причина такого результата в
том, что отклонения происходят в обоих направлениях и гасят друг
друга. В этом причина использования несколько более сложного
среднеквадратичного отклонения (RMS), которое не учитывает
направление смещения.  Для нашей последовательности среднее
квадратичное равно 1.5, что говорит нам намного больше.  За
достаточно продолжительный период  (длиннее того, что
представлен 25 точками в примере) мы будем ожидать, что 68%
отклонений будет меньше, чем  +- 1.5 пикселя, а 95% отклонений
будут лежать внутри +/- 2*RMS (3.0) угловой секунды.  Очевидно,
что это говорит нам намного больше о производительности гидирования
и является причиной использования среднеквадраточного в средствах
визуализации PHD2.

Люфт
(backlash) - типичный недостаток большинства монтировок с
червячной передачей по обеим осям (большинство, хотя и не все
монтировки используют именно её).  Вызван он зазором между
червяком и червячным колесом когда они соединяются вместе.
Некоторый зазор необходим для смены направления вращения, иначе
червячная передача заблокируется.  При смене направления на
краткое время система переходит в состояние мёртвого хода, когда
червяк и червячное колесо вообще не сцеплены.  В это время
мотор продолжает работать, но ось монтировки остаётся
неподвижной.  Это продолжается до тех пор, пока элементы
передачи не сцепятся снова.  У монтировок высшего класса люфт
очень маленький, практически не ощутимый при гидировании.
Однако, у монтировок попроще люфт может быть большим, а запаздывание
при движении в обратном направлении значительным.  Люфт не
является проблемой при движении по прямому восхождению, поскольку
скорость гидирования меньше или равна солнечной.  Поэтому
направление вращения никогда не меняется и люфт не даёт себя
проявить.  Однако, люфт является проблемой при гидировании по
склонению, где смена направления часто приводит к задержкам движения
из-за люфта.   Величину люфта можно измерить в PHD2 с
Помощником гидирования. Люфт является частой темой для обсуждения на
форумах поддержки. Избыточный люфт обычно исправляется регулировкой
червячной передачи.

Периодическая

ошибка (periodic error) - ещё одна типичная характеристика
монтировки с червячной передачей, которая касается только оси
прямого восхождения.  Вызывается она обычно небольшими
неточностями при изготовлении червяка в червячной передаче оси
прямого восхождения.  Периодической она называется поскольку
повторяется через каждый оборот червяка.  Проявляется она
небольшими предсказуемыми ошибками слежения.  Если дефекты
присутствуют и в других частях механизма, ошибка становится более
сложной, но принцип остаётся тем же.  Монтировки, рекламируемые
как предназначенные для фотографии, должны корректировать эту
ошибку, внося поправки в течение оборота червяка.  Этот
механизм называется корректировкой периодической ошибки (periodic
error correction), сокращённо PEC.  Обычно PEC прошивается в
ПЗУ монтировки и не мешает гидированию с помощью  PHD2, а, по
сути, даже помогает, поскольку  PHD2 приходится делать меньше
корректирующих движений.

Масштаб
изображения (image scale) - выражается соотношением
угловых секунд на пиксель и описывает преобразование угловых
размеров на небе в линейные размеры на сенсоре камеры.
Представьте, что монтировка при своём вращении делает некоторое
количество ошибочных движений.  В угловом выражении они очень
малы и равны нескольким угловым секундам.  Например, при
периодической ошибке в 10 угловых секунд гидируемаыя звезда
отклонится на это расстояние за один оборот червяка.  Но как
это отклонение отразиться на сенсоре камеры?  Ведь именно это
определяет реакцию программы.  При работе с длиннофокусным
телескопом масштаб будет небольшим, поскольку пикселям сенсора будут
соответствовать меньшие участки неба. Поэтому при данном угловом
отклонении линейное отклонение на сенсоре будет больше.  При
использовании той же камеры с телескопом, имеющим меньшее фокусное
расстояние, масштаб будет больше, а отклонения на сенсоре меньше,
поскольку пикселям будут соответствовать большие участки неба.
PHD2 правильно подсчитает масштаб если вы ввели верные значения
фокусного расстояния гидирующего телескопа и размер пикселей
гидирующей камеры.  После этого график гидирования будет
отображаться в угловых секундах, что позволит оценить эффективность
гидирования.  Это реальные единицы измерения, отражающие
физическое поведение системы гидирования, которые не зависят от
оптических характеристик гидирующего телескопа.

Соотношение
сигнал/шум (SNR) - используется PHD2 для определения того,
насколько легко можно выделить звезду из фонового шума. Это сродни
соотношению сигнал/шум в фотометрии, хотя и не одно и то же.
SNR может влиять на точность определения положения звезды, хотя при
значениях SNR от 10 и выше это влияние несущественно.  При этих
значениях влияние шума на гидирование будет значительно меньше
других факторов.

Пересвеченность

(saturation) - происходит когда яркость гидируемой звезды
превышает максимальную яркость, выдаваемую сенсором гидируемой
камеры.  Когда это происходит, профиль звезды (меню
Вид/Показать профиль звезды) имеет в центральной части плоский верх
вместо острой вершины, поскольку яркость центральной части
обрезается сенсором.  При этом точность вычисления положения
звезды уменьшается. Пересвечивания звезды необходимо всячески
избегать.

Звёздная
величина - в PHD2 выражает степень яркости и видимого
размера гидируемой звезды.  Её изменение может
свидетельствовать о таких событиях, как наступление облачности или
тумана. Используется в основном в закладке настроек "Гидирование" с
помощью управляющего элемента "Определение звёздной величины".


text:
obj-$(CONFIG_ANDROID_BINDER_IPC)	+= binder.o
obj-$(CONFIG_ASHMEM)			+= ashmem.o
obj-$(CONFIG_ANDROID_LOGGER)		+= logger.o
obj-$(CONFIG_ANDROID_PERSISTENT_RAM)	+= persistent_ram.o
obj-$(CONFIG_ANDROID_RAM_CONSOLE)	+= ram_console.o
obj-$(CONFIG_ANDROID_TIMED_OUTPUT)	+= timed_output.o
obj-$(CONFIG_ANDROID_TIMED_GPIO)	+= timed_gpio.o
obj-$(CONFIG_ANDROID_LOW_MEMORY_KILLER)	+= lowmemorykiller.o
obj-$(CONFIG_ANDROID_SWITCH)		+= switch/
obj-$(CONFIG_ANDROID_INTF_ALARM_DEV)	+= alarm-dev.o
obj-$(CONFIG_PERSISTENT_TRACER)		+= trace_persistent.o
obj-$(CONFIG_ANDROID_DEBUG_FD_LEAK)	+= fdleak_dbg.o

CFLAGS_REMOVE_trace_persistent.o = -pg


text:
<bill session="110" type="hr" number="1344" updated="2009-01-09T10:42:00-05:00">
	<status><vote date="1216848060" datetime="2008-07-23T18:21:00-04:00" where="h" result="pass" how="roll" roll="523"/></status>

	<introduced date="1216094400" datetime="2008-07-15"/>
	<titles>
		<title type="official" as="introduced">Providing for consideration of the bill (H.R. 3999) to amend title 23, United States Code, to improve the safety of Federal-aid highway bridges, to strengthen bridge inspection standards and processes, to increase investment in the reconstruction of structurally deficient bridges on the National Highway System, and for other purposes.</title>
	</titles>
	<sponsor id="412224"/>
	<cosponsors>

	</cosponsors>
	<actions>
		<action date="1216156500" datetime="2008-07-15T18:15:00-04:00"><text>The House Committee on Rules reported an original measure, H. Rept. 110-760, by Mr. Arcuri.</text></action>
		<action date="1216156500" datetime="2008-07-15T18:15:00-04:00"><text>All points of order against consideration of the bill are waived except those arising under clause 9 or 10 of rule XXI. It shall be in order to consider as an original bill for the purpose of amendment under the five-minute rule the amendment in the nature of a substitute printed in part A of the report of the Committee on Rules accompanying this resolution.</text></action>
		<calendar date="1216156500" datetime="2008-07-15T18:15:00-04:00" ><text>Placed on the House Calendar, Calendar No. 249.</text></calendar>
		<action date="1216844520" datetime="2008-07-23T17:22:00-04:00"><text>Considered as privileged matter.</text><reference label="consideration" ref="CR H7013-7018"/></action>
		<action date="1216844520" datetime="2008-07-23T17:22:00-04:00"><text>DEBATE - The House proceeded with one hour of debate on H. Res. 1344.</text></action>
		<action date="1216847520" datetime="2008-07-23T18:12:00-04:00"><text>On ordering the previous question Agreed to by the Yeas and Nays: (Roll No. 522).</text><reference label="consideration" ref="CR H7017"/></action>
		<vote date="1216848060" how="roll" roll="523" datetime="2008-07-23T18:21:00-04:00" where="h" type="vote" result="pass" ><text>On agreeing to the resolution Agreed to by the Yeas and Nays: 228 - 193 (Roll no. 523).</text><reference label="text" ref="CR H7013"/></vote>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>

	7/15/2008--Introduced.
Sets forth the rule for consideration of the bill (H.R. 3999) to amend title 23, United States Code, to improve the safety of Federal-aid highway bridges, to strengthen bridge inspection standards and processes, to increase investment in the reconstruction of structurally deficient bridges on the National Highway System.

</bill>


text:
ActionController::Base.session = {
  :key         => '_gradmx_session',
  :secret      => '635e12121d71659b8900a19258245e197cfbc0cdb041480e9003badd20028f851425a25254b170b130007f7a830cb5e58d9b7f2bc7ffc4a82b5bc40e64dae8f5'
}

# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
         android:textColor="#33ffff"
        android:textSize="30sp"
        android:text="未至深秋"
        android:gravity="center"
     />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"

        android:src="@drawable/logoshow" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:paddingBottom="5dp"
        android:paddingTop="5dp" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="V2" />

    </LinearLayout>

</LinearLayout>


text:
import select from 'select-dom';
import elementReady from 'element-ready';

export default async function onNewsfeedLoad(callback: VoidFunction): Promise<void> {
	const observer = new MutationObserver((([{addedNodes}]) => {
		callback();

		// If the newly-loaded fragments allows further loading, observe them
		for (const node of addedNodes) {
			if (node instanceof Element && select.exists('.ajax-pagination-form', node)) {
				observer.observe(node, {childList: true});
			}
		}
	}));

	// Start from the main container
	observer.observe((await elementReady('.news'))!, {childList: true});
}


text:
require 'rubygems'
require 'erb'
require 'active_support/core_ext/object/blank'
require 'active_support/core_ext/string/inflections'
require File.absolute_path(File.join(File.dirname(__FILE__), 'util'))

module Schematize
  class Parser
    attr_reader :directory

    def initialize(schema, options={:output_dir => File.absolute_path(File.join(File.dirname(__FILE__), '..', 'output')), :template_file_name => 'Schema.java.erb', :language => 'java', :test => false, :impl => false})
      @schema = schema

      @language = options[:language].blank? ? options[:language] : options[:template_file_name].split('.')[1]
      @template_file = File.read(File.join(File.dirname(__FILE__), '..', 'templates', options[:template_file_name]))
      @template = ERB.new(@template_file)
      @test = options[:test]
      @impl = options[:impl]

      @parsed_template = @template.result(binding)

      @directory = File.join(options[:output_dir], 'src', @test ? 'test' : 'main', @language, @schema.package.split('.'))
      @directory = File.join(@directory, 'impl') if @impl
    end

    def write_to_file
      Util.write_to_file("#{"Immutable" if @impl}#{@schema.type}#{"Test" if @test}.#{@language}", @directory, @parsed_template)
    end
  end
end