text:
package it.softphone.rd.gwt.client.resources;

import it.softphone.rd.gwt.client.resources.base.CommentBoxCss;
import it.softphone.rd.gwt.client.resources.base.FeedBoxCss;
import it.softphone.rd.gwt.client.resources.base.FilterCalendarCss;
import it.softphone.rd.gwt.client.resources.base.FilterPopupPanelCss;
import it.softphone.rd.gwt.client.resources.base.FilterTextBoxCss;
import it.softphone.rd.gwt.client.resources.base.FormDetailDataGridCss;
import it.softphone.rd.gwt.client.resources.base.HTMLLinkCss;
import it.softphone.rd.gwt.client.resources.base.HintTextBoxCss;
import it.softphone.rd.gwt.client.resources.base.MaskCss;
import it.softphone.rd.gwt.client.resources.base.NamedColumnCss;
import it.softphone.rd.gwt.client.resources.base.PortraitCss;
import it.softphone.rd.gwt.client.resources.base.RatingBoxCss;
import it.softphone.rd.gwt.client.resources.base.ReplyBoxCss;
import it.softphone.rd.gwt.client.resources.base.RichTextAreaHintCss;
import it.softphone.rd.gwt.client.resources.base.RichTextToolbarCss;
import it.softphone.rd.gwt.client.resources.base.SearchBoxCss;
import it.softphone.rd.gwt.client.resources.base.SocialBoxCss;
import it.softphone.rd.gwt.client.resources.base.SortFilterButtonCellCss;
import it.softphone.rd.gwt.client.resources.base.TabCommandLinkCss;
import it.softphone.rd.gwt.client.resources.base.TabHeaderCloseButtonCss;
import it.softphone.rd.gwt.client.resources.base.TagBoxCss;
import it.softphone.rd.gwt.client.resources.base.TagElementCss;

import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.DataResource;
import com.google.gwt.user.cellview.client.DataGrid;

public interface CommonWidgetsCssResource extends ClientBundle {

	@Source("base/css/tabHeaderCloseButton.css")
	public TabHeaderCloseButtonCss tabHeaderCloseButtonCss();

	@Source("base/css/tagBox.css")
	public TagBoxCss tagBox();

	@Source("base/css/tagElement.css")
	public TagElementCss tagElement();

	@Source("base/css/htmlLink.css")
	public HTMLLinkCss htmlLink();

	@Source("base/css/commentBox.css")
	public CommentBoxCss commentBox();

	@Source("base/css/hintTextBox.css")
	public HintTextBoxCss hintTextBoxCss();

	@Source("base/css/replyBox.css")
	public ReplyBoxCss replyBox();

	@Source("base/css/socialBox.css")
	public SocialBoxCss socialBox();

	@Source( {"base/css/socialBox.css",
	  		  "base/css/feedBox.css"})
	public FeedBoxCss feedBox();

	@Source( {"base/css/hintTextBox.css",
			  "base/css/filterTextBox.css"})
	public FilterTextBoxCss filterTextBox();

	@Source("base/css/filterCalendar.css")
	public FilterCalendarCss filterCalendar();

	@Source( {DataGrid.Style.DEFAULT_CSS,
	 "base/css/formDetailDataGrid.css"})
	public FormDetailDataGridCss formDetailDataGrid();

	@Source("base/css/filterDialog.css")
	public FilterPopupPanelCss filterDialog();

	@Source("base/css/tabCommandLink.css")
	public TabCommandLinkCss tabCommandLink();

	@Source("base/css/richTextToolbar.css")
	public RichTextToolbarCss richTextToolbar();

	@Source("base/css/richTextAreaHint.css")
	public RichTextAreaHintCss richTextAreaHint();

	@Source("base/css/mask.css")
	public MaskCss mask();

	@Source("base/css/sortFilterButtonCell.css")
	public SortFilterButtonCellCss sortFilterButtonCell();

	@Source("base/css/portrait.css")
	public PortraitCss portrait();

	@Source("base/css/searchBox.css")
	public SearchBoxCss searchBox();

	@Source("base/css/ratingBox.css")
	public RatingBoxCss ratingBox();

	@Source("base/css/namedColumn.css")
	public NamedColumnCss namedColumn();

	@Source("img/search20x20.png")
	DataResource search();

}


text:
class Region < ActiveRecord::Base
	has_many :notifications
	has_many :users, through: :notifications

  def self.find_by_location(lat, long)
    Region.where("ST_DISTANCE_SPHERE(ST_CollectionExtract(geom, 3), ST_MakePoint(#{long}, #{lat})) <= 0").first
  end

  def cleaning_days
    months = { month_4: 4, month_5: 5, month_6: 6, month_7: 7, month_8: 8,
               month_9: 9, month_10: 10, month_11: 11 }
    days = []
    months.keys.each do |key|
      day_string = self.send(key)
      if day_string
        day_string.split(",").each do |day|
          days << Date.new(2014,months[key],day.to_i)
        end
      end
    end
    days
  end

  def future_cleaning_days
    cleaning_days.select { |day| day >= Date.today }
  end

  def future_cleaning_days_formatted
    collect_dates = Hash.new
    future_cleaning_days.each do |date|
      month_name = Date::MONTHNAMES[date.month]
      collect_dates[month_name] ||= []
      collect_dates[month_name] << date.day.ordinalize
    end
    collect_dates

    collect_dates.map{|month, days| [month, days]}
  end

  def next_cleaning_day
    today = Date.today
    cleaning_days.sort.find { |day| day >= today }
  end

  def swept_soon?
    week_from_now = Date.today + 7
    if next_cleaning_day
      week_from_now >= next_cleaning_day
    else
      false
    end
  end

  def swept_in_date_range?(start_date=Date.today, end_date=Date.today + 7)
    swept = false
    cleaning_days.each { |day| swept = true if (day >= start_date && day <= end_date) }
    swept
  end

  def display_self
    if next_cleaning_day
      next_cleaning = "#{Date::MONTHNAMES[next_cleaning_day.month]} #{next_cleaning_day.day}"
    else
      next_cleaning = "none"
    end
    { name: "Ward #{ward_num} Area #{sweep}", next_sweep: "Next cleaning day: #{next_cleaning}" }
  end

  def to_geojson
    Region.select("*, ST_AsGeoJSON(geom) as my_geo").where(gid: id)
  end

  def self.get_regions(location, distance)
    Region.select("*, ST_AsGeoJSON(geom) as my_geo").where("ST_DISTANCE_SPHERE(ST_CollectionExtract(geom, 3), 'MULTIPOINT(#{location[1]} #{location[0]})') <= #{distance} * 1609.34")
  end

  def self.areas_by_date_range(location, start_date=(Date.today), end_date=(Date.today + 7))
    results = [[],[]]
    regions = Region.get_regions(location, 0.25)
    regions.each do |ward|
      if ward.swept_in_date_range?(start_date, end_date)
        results[0] << ward.my_geo
      else
        results[1] << ward.my_geo
      end
    end
    results
  end
end

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by AlexLiu on 2015/6/2.
 */

var React = require('react');
var Reflux = require('reflux');

var tableStore = require('../../stores/table-store');
var actions = require('../../actions/app-actions');

var EditItem = React.createClass({
    render(){

        return (
            <span onClick={this.editItem}>
                edit
            </span>
        );
    },
    editItem: function(){

        actions.editItem(this.props.item);
    }
});

module.exports = EditItem;


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>glm::gtx::transform Namespace Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Modules

Namespaces

Classes

Files

Namespace List

Namespace Members

glm

gtx

transform

Functions

glm::gtx::transform Namespace Reference

< GLM_GTX_transform extension: Add transformation matrices
More...

Functions

template<typename T >

detail::tmat4x4< T > 	rotate (T angle, T x, T y, T z)

template<typename T >

detail::tmat4x4< T > 	rotate (T angle, detail::tvec3< T > const &v)

template<typename T >

detail::tmat4x4< T > 	rotate (detail::tmat4x4< T > const &m, T angle, T x, T y, T z)

template<typename T >

detail::tmat4x4< T > 	scale (detail::tvec3< T > const &v)

template<typename T >

detail::tmat4x4< T > 	scale (detail::tmat4x4< T > const &m, T x, T y, T z)

template<typename T >

detail::tmat4x4< T > 	scale (T x, T y, T z)

template<typename T >

detail::tmat4x4< T > 	translate (detail::tmat4x4< T > const &m, T x, T y, T z)

template<typename T >

detail::tmat4x4< T > 	translate (T x, T y, T z)

template<typename T >

detail::tmat4x4< T > 	translate (detail::tvec3< T > const &v)

Detailed Description

< GLM_GTX_transform extension: Add transformation matrices

<address class="footer">Generated by

 1.7.4 </address>


text:
package parser

import "errors"

// ErrQuoteLeftOpen is the error returned by ExtractStrings when the input
// shows an unclosed quoted string.
var ErrQuoteLeftOpen = errors.New("Unclosed quote in a W3C log line")

// ErrEndlineInsideQuotes is the error returned when the input shows an
// endline character inside a quoted string.
var ErrEndlineInsideQuotes = errors.New("Endline character appears in a quoted string")

// ErrNoEndline is the error returned by ExtractStrings when the input
// does not end with an endline character.
var ErrNoEndline = errors.New("No endline at end of input")


text:
import { Component, Input } from '@angular/core';
import { FormControl } from '@angular/forms';

import {
    AppLanguageDto,
    EditContentForm,
    FieldDto,
    ImmutableArray
} from '@app/shared';

@Component({
    selector: 'sqx-field-editor',
    styleUrls: ['./field-editor.component.scss'],
    templateUrl: './field-editor.component.html'
})
export class FieldEditorComponent {
    @Input()
    public form: EditContentForm;

    @Input()
    public field: FieldDto;

    @Input()
    public control: FormControl;

    @Input()
    public language: AppLanguageDto;

    @Input()
    public languages: ImmutableArray<AppLanguageDto>;
}


text:
import rospy
import cv2
import numpy as np
import os
from datetime import datetime
from time import clock, time
from sensor_msgs.msg import CompressedImage
from aidu_elevator.msg import Button
from images import convert
from pymongo import MongoClient

data_path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../data/'))
detection_directory = os.path.abspath(os.path.join(data_path, 'detection'))

n = 0
benchmarking = False
benchmark_convert = []
benchmark_detect = []
benchmark_threshold = []

def millis(dt):
    """
    Converts a datetime object to milliseconds
    """
    return (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0

def threshold(image):
    """
    Thresholds an image
    """
    global n
    n += 1
    if benchmarking:
        start = datetime.now()

    # Pre process image
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    #image = cv2.equalizeHist(image)

    m = 1 + n / 2
    #adapt_gaus = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 75, 7)
    #cv2.imwrite('/home/rolf/Desktop/Assignment 6/thresholding/%s_%d.jpg' % ("adaptive_gaussian", m), adapt_gaus)

    adapt_mean = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 75, 7)
    #cv2.imwrite('/home/rolf/Desktop/Assignment 6/thresholding/%s_%d.jpg' % ("adaptive_mean", m), adapt_mean)
    #
    #reg_binary = cv2.threshold(image, 128, 255, cv2.THRESH_BINARY)[1]
    #cv2.imwrite('/home/rolf/Desktop/Assignment 6/thresholding/%s_%d.jpg' % ("binary", m), reg_binary)
    #
    #reg_tozero = cv2.threshold(image, 128, 255, cv2.THRESH_TOZERO)[1]
    #cv2.imwrite('/home/rolf/Desktop/Assignment 6/thresholding/%s_%d.jpg' % ("to_zero", m), reg_tozero)

    image = adapt_mean

    if benchmarking:
        benchmark_threshold.append(millis(datetime.now() - start))

    # Return output
    return image

def detect_buttons(image, min_button_size=0.002, max_button_size=0.8, max_stretch=0.08):
    """
    Attempts to detect buttons in given image
    """
    global n
    if benchmarking:
        start = datetime.now()

    n += 1
    height, width = image.shape

    # Find all contours
    contours, hierarchy = cv2.findContours(image, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    buttons = []

    # Iterate over contours, determining if there's a button on each contour
    for cnt in contours:
        if min_button_size * width * height < cv2.contourArea(cnt) < max_button_size * height * width:  # remove very small and very large areas (noise)
            hull = cv2.convexHull(cnt)
            hull = cv2.approxPolyDP(hull, 0.1 * cv2.arcLength(hull, True), True)
            if 4 <= len(hull) <= 6:
                x,y,w,h = cv2.boundingRect(cnt)
                button = Button()
                button.x = x + w/2; button.y = y + h/2; button.w = w; button.h = h;
                if button.w > 0 and button.h > 0 and (1.0 - max_stretch) < (float(button.w) / button.h) < (1.0 + max_stretch):
                    buttons.append(button)

    if benchmarking:
        benchmark_detect.append(millis(datetime.now() - start))

    return buttons

def test():
    """
    Tests the button detection algorithm on our dataset
    """
    db = MongoClient()
    fotos = db['aidu']['elevator_fotos']
    for idx, foto in enumerate(fotos.find()):
        #if idx not in [143, 196, 206, 524]:
        #    continue

        rospy.loginfo("Processing foto %d" % idx)
        convert_start = datetime.now()
        image = convert(foto['image'], input_type='ros', output_type='cv2')
        benchmark_convert.append(millis(datetime.now() - convert_start))

        original_image = np.array(image)

        # Threshold
        image = threshold(image)
        threshold_image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)

        # Detect buttons
        buttons = detect_buttons(image)

        rospy.loginfo('Foto %d - convert: %fms - threshold: %fms - detect: %fms' % (idx, benchmark_convert[-1],
                                                                                benchmark_threshold[-1],
                                                                                benchmark_detect[-1]))
        rospy.loginfo('Bytes: %d' % len(foto['image']))
        rospy.loginfo('Detected %d buttons' % len(buttons))

        # Show button
        for button in buttons:
            x0 = int(button.x - button.w/2)
            y0 = int(button.y - button.h/2)
            x1 = int(button.x + button.w/2)
            y1 = int(button.y + button.h/2)
            cv2.rectangle(original_image, (x0, y0), (x1, y1), (0, 0, 255), 2)
            cv2.rectangle(threshold_image, (x0, y0), (x1, y1), (0, 0, 255), 2)
        out = np.vstack((original_image, threshold_image))
        cv2.imshow('Button detector', cv2.resize(out, (640, 720)))
        cv2.waitKey()

        if rospy.is_shutdown():
            break

def callback(image):
    global benchmarking, benchmark_convert, benchmark_detect, benchmark_threshold

    if benchmarking:
        convert_start = datetime.now()

    image = convert(image.data, input_type='ros', output_type='cv2')
    original_image = np.array(image)

    if benchmarking:
        benchmark_convert.append(millis(datetime.now() - convert_start))

    image = threshold(image)
    buttons = detect_buttons(image)

    button = Button()
    button.image.data = convert(image, input_type='cv2', output_type='ros')
    image_publisher.publish(button.image)

    for button in buttons:
        x0 = int(button.x - button.w/2)
        y0 = int(button.y - button.h/2)
        x1 = int(button.x + button.w/2)
        y1 = int(button.y + button.h/2)
        thumbnail = original_image[y0:y1,x0:x1]
        button.image.data = convert(cv2.resize(thumbnail, (100, 100)), input_type='cv2', output_type='ros')
        #image_publisher.publish(button.image)

	button_publisher.publish(button)

    rospy.loginfo('Detected %d buttons' % len(buttons))

    #image_publisher.publish(image)
    #mongo_image = convert(image.data, input_type='ros', output_type='mongo')
    #cv2_image = convert(image.data, input_type='ros', output_type='cv2')
    #cv2_image = cv2.resize(cv2_image, (1280/2, 720/2))
    #cv2.imshow('t', cv2_image)
    #cv2.waitKey(0)
    #fotos.insert({'foto': mongo_image})

def main():
    global benchmarking, benchmark_convert, benchmark_detect, benchmark_threshold, button_publisher, image_publisher

    rospy.init_node('button_detector', anonymous=True)

    if rospy.has_param('~benchmark'):
        benchmarking = True

    if rospy.has_param('~test'):
        test()
        cv2.destroyAllWindows()
    else:
        rospy.Subscriber("/image_raw/compressed", CompressedImage, callback)
        image_publisher = rospy.Publisher("/elevator/button/image/compressed", CompressedImage)
        button_publisher = rospy.Publisher("/elevator/button", Button)

    rospy.spin()

    if benchmarking:
        arr_convert = np.array(benchmark_convert)
        arr_detect = np.array(benchmark_detect)
        arr_threshold = np.array(benchmark_threshold)
        rospy.loginfo('Number of images processed: %d' % n)
        rospy.loginfo('Image Conversion - Avg: %f ms - Std: %f ms' % (arr_convert.mean(), arr_convert.std()))
        rospy.loginfo('Image Threshold  - Avg: %f ms - Std: %f ms' % (arr_threshold.mean(), arr_threshold.std()))
        rospy.loginfo('Button Detection - Avg: %f ms - Std: %f ms' % (arr_detect.mean(), arr_detect.std()))

if __name__ == '__main__':
    main()


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Alectoria guatemalana Gyeln.

### Remarks
null


text:
package collisions.basicShapes;

import java.util.LinkedList;
import java.util.List;

import collisions.AABB;
import collisions.CollisionShape;
import main.MathUtil;
import main.Vector2D;

public class EllipseAABB extends CollisionShape {

	public EllipseAABB(AABB bb) {
		super(bb);
	}

	@Override
	protected boolean getPreciseCollision(Vector2D point) {
		return MathUtil.Sqr((point.X-BoundingBox.getCenter().X)/BoundingBox.getWidth())+MathUtil.Sqr((point.Y-BoundingBox.getCenter().Y)/BoundingBox.getHeight())<=0.25d;
	}

	@Override
	public void translateTo(Vector2D newPos) {
		BoundingBox.Location.X=newPos.X-(BoundingBox.getWidth()/2);
		BoundingBox.Location.Y=newPos.Y-(BoundingBox.getHeight()/2);
	}

	@Override
	public List<Vector2D> getPointMap() {
		List<Vector2D> a=new LinkedList<Vector2D>();
		for(int i=0;i<32;++i) a.add(new Vector2D(BoundingBox.Location.X+BoundingBox.Size.X*0.5*(1+Math.cos(i*Math.PI/16)),BoundingBox.Location.Y+BoundingBox.Size.Y*0.5*(1+Math.sin(i*Math.PI/16))));
		return a;
	}

}


text:
set(find_package_args)
if(gflagsAlt_FIND_VERSION)
  list(APPEND find_package_args ${gflagsAlt_FIND_VERSION})
endif()
if(gflagsAlt_FIND_QUIETLY)
  list(APPEND find_package_args QUIET)
endif()
find_package(gflags ${find_package_args})
if(gflags_FOUND)
  set(gflagsAlt_FOUND TRUE)
  return()
endif()

# TODO: Support version detection.

if(gflags_ROOT)
  find_library(gflags_LIB
               NAMES gflags
               PATHS ${gflags_ROOT}
               PATH_SUFFIXES ${ARROW_LIBRARY_PATH_SUFFIXES}
               NO_DEFAULT_PATH)
  find_path(GFLAGS_INCLUDE_DIR
            NAMES gflags/gflags.h
            PATHS ${gflags_ROOT}
            NO_DEFAULT_PATH
            PATH_SUFFIXES ${ARROW_INCLUDE_PATH_SUFFIXES})
else()
  find_library(gflags_LIB NAMES gflags)
  find_path(GFLAGS_INCLUDE_DIR
            NAMES gflags/gflags.h
            PATH_SUFFIXES ${ARROW_INCLUDE_PATH_SUFFIXES})
endif()

find_package_handle_standard_args(gflagsAlt REQUIRED_VARS gflags_LIB GFLAGS_INCLUDE_DIR)

if(gflagsAlt_FOUND)
  add_library(gflags::gflags UNKNOWN IMPORTED)
  set_target_properties(gflags::gflags
                        PROPERTIES IMPORTED_LOCATION "${gflags_LIB}"
                                   INTERFACE_INCLUDE_DIRECTORIES "${GFLAGS_INCLUDE_DIR}")
  set(GFLAGS_LIBRARIES gflags::gflags)
endif()


text:
"""
Translate out of SSA.
"""

from __future__ import print_function, division, absolute_import
from pykit.transform import reg2mem
from .utils import update_context

# TODO: This is not an optimization, move it elsewhere?

def run(func, env):
    vars, loads = reg2mem.reg2mem(func, env)
    context = env['flypy.typing.context']

    if context is not None:
        update_context(env, env, vars)
        update_context(env, env, loads)


text:
package gov.opm.scrd.entities.application;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import gov.opm.scrd.TestsHelper;
import junit.framework.JUnit4TestAdapter;

import org.junit.Before;
import org.junit.Test;

/**
 *

 * Unit tests for {@link PaymentTransactionNote} class.
 *

 *
 * @author sparemax
 * @version 1.0
 * @since OPM - Data Migration - Entities Update Module Assembly 1.0
 */
public class PaymentTransactionNoteUnitTests {
    /**
     *

     * Represents the PaymentTransactionNote instance used in tests.
     *

     */
    private PaymentTransactionNote instance;

    /**
     *

     * Adapter for earlier versions of JUnit.
     *

     *
     * @return a test suite.
     */
    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(PaymentTransactionNoteUnitTests.class);
    }

    /**
     *

     * Sets up the unit tests.
     *

     *
     * @throws Exception
     *             to JUnit.
     */
    @Before
    public void setUp() throws Exception {
        instance = new PaymentTransactionNote();
    }

    /**
     *

     * Accuracy test for the constructor PaymentTransactionNote().

     * Instance should be correctly created.
     *

     */
    @Test
    public void testCtor() {
        instance = new PaymentTransactionNote();

        assertNull("'payTransactionKey' should be correct.", TestsHelper.getField(instance, "payTransactionKey"));
        assertNull("'note' should be correct.", TestsHelper.getField(instance, "note"));
    }

    /**
     *

     * Accuracy test for the method getPayTransactionKey().

     * The value should be properly retrieved.
     *

     */
    @Test
    public void test_getPayTransactionKey() {
        Long value = 1L;
        instance.setPayTransactionKey(value);

        assertEquals("'getPayTransactionKey' should be correct.",
            value, instance.getPayTransactionKey());
    }

    /**
     *

     * Accuracy test for the method setPayTransactionKey(Long payTransactionKey).

     * The value should be properly set.
     *

     */
    @Test
    public void test_setPayTransactionKey() {
        Long value = 1L;
        instance.setPayTransactionKey(value);

        assertEquals("'setPayTransactionKey' should be correct.",
            value, TestsHelper.getField(instance, "payTransactionKey"));
    }

    /**
     *

     * Accuracy test for the method getNote().

     * The value should be properly retrieved.
     *

     */
    @Test
    public void test_getNote() {
        String value = "new_value";
        instance.setNote(value);

        assertEquals("'getNote' should be correct.",
            value, instance.getNote());
    }

    /**
     *

     * Accuracy test for the method setNote(String note).

     * The value should be properly set.
     *

     */
    @Test
    public void test_setNote() {
        String value = "new_value";
        instance.setNote(value);

        assertEquals("'setNote' should be correct.",
            value, TestsHelper.getField(instance, "note"));
    }
}


text:
/**
 * @description [Converts RGB color to HEX equivalent.]
 * @param  {String}  rgb           [The RGB color to convert.]
 * @param  {Boolean} to_lowercase  [Flag indicating whether to return lowercase HEX.]
 * @return {String}                [The HEX color equivalent.]
 */
var rgb2hex = function(rgb, to_lowercase) {

    //parse the rgb
    var parts = rgb.replace(/rgba?|\(|\)|;/g, "").split(","),
        table = "0123456789ABCDEF".split(""),
        final_hex = [];

    // reuse rgb var to store parsed color components
    rgb = [parts[0] * 1, parts[1] * 1, parts[2] * 1];

    for (var i = 0, l = rgb.length; i < l; i++) {
        // cache the current color component + divide by 16
        var current_color_component = rgb[i];
        // divide current color component by 16
        var cc = Math.floor(current_color_component / 16);
        final_hex.push(table[cc] + "" + table[current_color_component - ((cc) * 16)]);
    }

    // if to_lowercase flag is provided lowercase the HEX value...else return upper case HEX
    return ("#" + final_hex.join(""))[!to_lowercase ? "toString" : "toLowerCase"]();

};

// examples

console.log(rgb2hex("rgb(45, 124, 223);", true)); // #2d7cdf
console.log(rgb2hex("rgb(45, 124, 223)", true)); // #2d7cdf
console.log(rgb2hex("(45, 124, 223);", true)); // #2d7cdf
console.log(rgb2hex("45, 124, 223", true)); // #2d7cdf

console.log(rgb2hex("rgb(45, 124, 223);")); // #2D7CDF
console.log(rgb2hex("rgb(45, 124, 223)")); // #2D7CDF
console.log(rgb2hex("(45, 124, 223);")); // #2D7CDF
console.log(rgb2hex("45, 124, 223")); // #2D7CDF


text:
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Testura.Code.Factories;
using Testura.Code.Generators.Common.Arguments.ArgumentTypes;
using Testura.Code.Generators.Common.BinaryExpressions;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;

namespace Testura.Code.Statements;

/// <summary>
/// Provides the functionality to generate selection statements.
/// </summary>
public class SelectionStatement
{
    /// <summary>
    /// Create the statement syntax for a if-conditional.
    /// </summary>
    /// <param name="leftArgument">The left argument of the if-statement.</param>
    /// <param name="rightArgument">The right argument of the if-statement.</param>
    /// <param name="conditional">The conditional.</param>
    /// <param name="block">The block containing all statements.</param>
    /// <returns>The declared statement syntax.</returns>
    public StatementSyntax If(IArgument leftArgument, IArgument rightArgument, ConditionalStatements conditional, BlockSyntax block)
    {
        if (leftArgument == null)
        {
            throw new ArgumentNullException(nameof(leftArgument));
        }

        if (rightArgument == null)
        {
            throw new ArgumentNullException(nameof(rightArgument));
        }

        return
            IfStatement(
                BinaryExpression(
                    ConditionalFactory.GetSyntaxKind(conditional),
                    leftArgument.GetArgumentSyntax().Expression,
                    rightArgument.GetArgumentSyntax().Expression),
                block);
    }

    /// <summary>
    /// Create the statement syntax for a if-conditional with a single statement.
    /// </summary>
    /// <param name="leftArgument">The left argument of the if-statement.</param>
    /// <param name="rightArgument">The right argument of the if-statement.</param>
    /// <param name="conditional">The conditional.</param>
    /// <param name="expressionStatement">Statement inside the if.</param>
    /// <returns>The declared statement syntax.</returns>
    public StatementSyntax If(IArgument leftArgument, IArgument rightArgument, ConditionalStatements conditional, ExpressionStatementSyntax expressionStatement)
    {
        if (leftArgument == null)
        {
            throw new ArgumentNullException(nameof(leftArgument));
        }

        if (rightArgument == null)
        {
            throw new ArgumentNullException(nameof(rightArgument));
        }

        return
            IfStatement(
                BinaryExpression(
                    ConditionalFactory.GetSyntaxKind(conditional),
                    leftArgument.GetArgumentSyntax().Expression,
                    rightArgument.GetArgumentSyntax().Expression),
                expressionStatement);
    }

    /// <summary>
    /// Create the statement syntax for a if-conditional.
    /// </summary>
    /// <param name="binaryExpression">The binary expression to generate.</param>
    /// <param name="block">The block containing all statements.</param>
    /// <returns>The declared statement syntax.</returns>
    public StatementSyntax If(IBinaryExpression binaryExpression, BlockSyntax block)
    {
        if (binaryExpression == null)
        {
            throw new ArgumentNullException(nameof(binaryExpression));
        }

        return IfStatement(binaryExpression.GetBinaryExpression(),  block);
    }

    /// <summary>
    /// Create the statement syntax for a if-conditional with a single statement.
    /// </summary>
    /// <param name="binaryExpression">The binary expression to generate.</param>
    /// <param name="expressionStatement">Statement inside the if.</param>
    /// <returns>The declared statement syntax.</returns>
    public StatementSyntax If(IBinaryExpression binaryExpression, ExpressionStatementSyntax expressionStatement)
    {
        if (binaryExpression == null)
        {
            throw new ArgumentNullException(nameof(binaryExpression));
        }

        return IfStatement(binaryExpression.GetBinaryExpression(), expressionStatement);
    }
}


text:
CoolLayout
==========

UICollectionView layout experiment


text:
body {
  margin:0px;
  background-image:none;
  position:static;
  left:auto;
  width:2048px;
  margin-left:0;
  margin-right:0;
  text-align:left;
}
#base {
  position:absolute;
  z-index:0;
}
#u0 {
  position:absolute;
  left:0px;
  top:0px;
  width:2048px;
  height:1536px;
}
#u0_img {
  position:absolute;
  left:0px;
  top:0px;
  width:2048px;
  height:1536px;
}
#u1 {
  position:absolute;
  left:2px;
  top:760px;
  width:2044px;
  visibility:hidden;
  word-wrap:break-word;
}
#u3 {
  position:absolute;
  left:2px;
  top:259px;
  width:637px;
  height:360px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u4 {
  position:absolute;
  left:0px;
  top:619px;
  width:637px;
  height:360px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u5 {
  position:absolute;
  left:3px;
  top:979px;
  width:637px;
  height:360px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u6 {
  position:absolute;
  left:3px;
  top:1339px;
  width:637px;
  height:206px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u8 {
  position:absolute;
  left:0px;
  top:127px;
  width:194px;
  height:131px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u9 {
  position:absolute;
  left:194px;
  top:127px;
  width:292px;
  height:131px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u10 {
  position:absolute;
  left:486px;
  top:127px;
  width:154px;
  height:131px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u11 {
  position:absolute;
  left:29px;
  top:45px;
  width:136px;
  height:82px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u12 {
  position:absolute;
  left:1700px;
  top:1400px;
  width:250px;
  height:110px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u13 {
  position:absolute;
  left:1350px;
  top:1260px;
  width:230px;
  height:70px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u14 {
  position:absolute;
  left:1680px;
  top:700px;
  width:280px;
  height:70px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u15 {
  position:absolute;
  left:1680px;
  top:890px;
  width:210px;
  height:80px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u16 {
  position:absolute;
  left:960px;
  top:380px;
  width:280px;
  height:90px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u17 {
  position:absolute;
  left:1260px;
  top:380px;
  width:360px;
  height:90px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u18 {
  position:absolute;
  left:705px;
  top:380px;
  width:245px;
  height:90px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}
#u19 {
  position:absolute;
  left:1190px;
  top:504px;
  width:310px;
  height:100px;
  overflow:hidden;
  background-image:url('../../resources/images/transparent.gif');
}


text:
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title>
    <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% else %}{{ site.description }}{% endif %}">

    <!-- for ios 7 style, multi-resolution icon of 152x152 -->
  <meta name="apple-mobile-web-app-title" content="anticoag service">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-barstyle" content="black-translucent">
  <link rel="apple-touch-icon" href="{{ "/logo152.png" | prepend: site.baseurl }}">
  <!-- for Chrome on Android, multi-resolution icon of 196x196 -->
  <meta name="mobile-web-app-capable" content="yes">
  <link rel="shortcut icon" sizes="196x196" href="{{ "/logo196.png" | prepend: site.baseurl }}">
  <!-- windows live tile-->
  <meta name="application-name" content="anticoag service">
  <meta name="msapplication-TileImage" content="{{ "/logo196.png" | prepend: site.baseurl }}">
  <meta name="msapplication-TileColor" content="#8a8a8a">

    <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
    <link rel="stylesheet" href="{{ "/css/font-awesome.min.css" | prepend: site.baseurl }}">
    <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic,500" type="text/css">

    <link rel="shortcut icon" href="{{ "/favicon.ico?1" | prepend: site.baseurl }}">
    {% seo %}

    <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
    <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}" />
</head>


text:
import { graphql } from 'react-apollo'
import React from 'react'
import LoginWithFacebook from '../components/auth/LoginWithFacebook'
import SignUp from '../components/auth/SignUp'
import Login from '../components/auth/Login'
import Logout from '../components/auth/Logout'
import Forget from '../components/auth/Forget'
import userProfile from './userProfile.gql'
import PropTypes from 'prop-types'

const UserProfile = ({ loading, user, errors, authen }) => {
  if (loading) {
    return
Loading

  }

  // Logged in
  if (authen && authen.isLoggedIn) {
    if (user) {
      return
Welcome : {user.name}<Logout />

    }
  }

  // Not logged in
  let info = errors && errors[0] ? errors[0].message : ''
  if (user) {
    switch (user.status) {
      case 'WAIT_FOR_EMAIL_VERIFICATION':
      case 'WAIT_FOR_EMAIL_RESET':
        info = 'Please check you email'
        break
    }
  }
  return

{info}
<LoginWithFacebook />
<SignUp />
<Login /> <Forget />

}

UserProfile.propTypes = () => ({
  loading: PropTypes.boolean.isRequired,
  user: PropTypes.object.isRequired,
  errors: PropTypes.array.isRequired,
  authen: PropTypes.object.isRequired,
})

export default graphql(userProfile, {
  options: { fetchPolicy: 'cache-and-network' },
  props: ({ data: { loading, user, errors, authen } }) => (
    { loading, user, errors, authen }
  )
})(UserProfile)


text:
        <input type="text" placeholder="idx">
        <input type="text" placeholder="Test Case">
        <input type="text" placeholder="Error code">
        <input type="text" placeholder="Output">


text:
var config = require(__dirname + '/config');
var logger = require(__dirname + '/logger');
var fs = require('fs');

var log = {
	oldContent: "",
	contents: [],

	getContents: function(meta, socket) {
		logger.debug("Get file contents");

		var _this = this;
		var path = (meta) ? config.log.pathMeta : config.log.pathGame;

		fs.readFile(path, {
			encoding: 'utf8',
			flag: 'r'
		}, function(err, data) {
			if (err) {
				logger.error(err);
				socket.emit('error', err);
				return;
			}

			var lines = data.split("\n");
			lines.reverse();

			_this.contents = lines;
			_this.oldContent = data;

			socket.emit('init', {
				contents: lines
			});
		});
	},

	getChanges: function(meta, socket) {
		logger.debug("Get file changes");

		var _this = this;
		var path = (meta) ? config.log.pathMeta : config.log.pathGame;

		fs.readFile(path, {
			encoding: 'utf8',
			flag: 'r'
		}, function(err, data) {
			if (err) {
				logger.error(err);
				socket.emit('error', err);
				return;
			}

			var newContents = data.replace(_this.oldContent, "");
			_this.contents.push(newContents);

			socket.emit('logchanges', {
				changes: newContents
			});
		});
	}
};

module.exports = log;


text:
QUnit.module('JSHint | helpers/module-for-acceptance.js');
QUnit.test('should pass jshint', function(assert) {
  assert.expect(1);
  assert.ok(true, 'helpers/module-for-acceptance.js should pass jshint.');
});


text:
Pipeline Configuration
======================


text:
<!--
  ~ 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.
  -->
<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">
  <parent>
    <groupId>com.twitter</groupId>
    <artifactId>parquet</artifactId>
    <relativePath>../pom.xml</relativePath>
    <version>1.6.0rc6-SNAPSHOT</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>

  <artifactId>parquet-scala_${scala.binary.version}</artifactId>
  <packaging>jar</packaging>

  <name>Apache Parquet Scala (Incubating)</name>
  <url>https://parquet.incubator.apache.org</url>

  <repositories>
    <repository>
      <id>scala-tools.org</id>
      <name>Scala-tools Maven2 Repository</name>
      <url>http://scala-tools.org/repo-releases</url>
    </repository>
  </repositories>
  <pluginRepositories>
    <pluginRepository>
      <id>scala-tools.org</id>
      <name>Scala-tools Maven2 Repository</name>
      <url>http://scala-tools.org/repo-releases</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>com.twitter</groupId>
      <artifactId>parquet-column</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>
    <dependency>
      <groupId>org.scalatest</groupId>
      <artifactId>scalatest_${scala.binary.version}</artifactId>
      <version>2.2.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.scala-tools</groupId>
        <artifactId>maven-scala-plugin</artifactId>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>


text:
<?php
/**
 * WPSEO plugin file.
 *
 * @package WPSEO\XML_Sitemaps
 */

/**
 * Rewrite setup and handling for sitemaps functionality.
 */
class WPSEO_Sitemaps_Router {

	/**
	 * Sets up init logic.
	 */
	public function __construct() {

		add_action( 'init', array( $this, 'init' ), 1 );
		add_filter( 'redirect_canonical', array( $this, 'redirect_canonical' ) );
		add_action( 'template_redirect', array( $this, 'template_redirect' ), 0 );
	}

	/**
	 * Sets up rewrite rules.
	 */
	public function init() {

		global $wp;

		$wp->add_query_var( 'sitemap' );
		$wp->add_query_var( 'sitemap_n' );
		$wp->add_query_var( 'yoast-sitemap-xsl' );

		add_rewrite_rule( 'sitemap_index\.xml$', 'index.php?sitemap=1', 'top' );
		add_rewrite_rule( '([^/]+?)-sitemap([0-9]+)?\.xml$', 'index.php?sitemap=$matches[1]&sitemap_n=$matches[2]', 'top' );
		add_rewrite_rule( '([a-z]+)?-?sitemap\.xsl$', 'index.php?yoast-sitemap-xsl=$matches[1]', 'top' );
	}

	/**
	 * Stop trailing slashes on sitemap.xml URLs.
	 *
	 * @param string $redirect The redirect URL currently determined.
	 *
	 * @return bool|string $redirect
	 */
	public function redirect_canonical( $redirect ) {

		if ( get_query_var( 'sitemap' ) || get_query_var( 'yoast-sitemap-xsl' ) ) {
			return false;
		}

		return $redirect;
	}

	/**
	 * Redirects sitemap.xml to sitemap_index.xml.
	 */
	public function template_redirect() {
		if ( ! $this->needs_sitemap_index_redirect() ) {
			return;
		}

		header( 'X-Redirect-By: Yoast SEO' );
		wp_redirect( home_url( '/sitemap_index.xml' ), 301, 'Yoast SEO' );
		exit;
	}

	/**
	 * Checks whether the current request needs to be redirected to sitemap_index.xml.
	 *
	 * @global WP_Query $wp_query Current query.
	 *
	 * @return bool True if redirect is needed, false otherwise.
	 */
	public function needs_sitemap_index_redirect() {
		global $wp_query;

		$protocol = 'http://';
		if ( ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on' ) {
			$protocol = 'https://';
		}

		$domain = '';
		if ( isset( $_SERVER['SERVER_NAME'] ) ) {
			$domain = sanitize_text_field( wp_unslash( $_SERVER['SERVER_NAME'] ) );
		}

		$path = '';
		if ( isset( $_SERVER['REQUEST_URI'] ) ) {
			$path = sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) );
		}

		// Due to different environment configurations, we need to check both SERVER_NAME and HTTP_HOST.
		$check_urls = array( $protocol . $domain . $path );
		if ( ! empty( $_SERVER['HTTP_HOST'] ) ) {
			$check_urls[] = $protocol . sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) . $path;
		}

		return $wp_query->is_404 && in_array( home_url( '/sitemap.xml' ), $check_urls, true );
	}

	/**
	 * Create base URL for the sitemap.
	 *
	 * @param string $page Page to append to the base URL.
	 *
	 * @return string base URL (incl page)
	 */
	public static function get_base_url( $page ) {

		global $wp_rewrite;

		$base = $wp_rewrite->using_index_permalinks() ? 'index.php/' : '/';

		/**
		 * Filter the base URL of the sitemaps.
		 *
		 * @param string $base The string that should be added to home_url() to make the full base URL.
		 */
		$base = apply_filters( 'wpseo_sitemaps_base_url', $base );

		/*
		 * Get the scheme from the configured home URL instead of letting WordPress
		 * determine the scheme based on the requested URI.
		 */
		return home_url( $base . $page, wp_parse_url( get_option( 'home' ), PHP_URL_SCHEME ) );
	}
}


text:
package br.com.jsn.noleggio.modules.agencia.model;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.br.CNPJ;

import com.google.gson.annotations.Expose;

import br.com.jsn.noleggio.main.validation.BusinessValidation;
import br.com.jsn.noleggio.modules.veiculo.model.Veiculo;

/**
 * The persistent class for the agencia database table.
 */
@Entity
@Table(name="agencia")
@NamedQuery(name="Agencia.findAll", query="SELECT a FROM Agencia a")
public class Agencia extends BusinessValidation implements Serializable {
	private static final long serialVersionUID = 3048129896182422262L;

	@Id
	@GeneratedValue(strategy=GenerationType.AUTO)
	@Column(name="id_agencia")
	@Expose
	private int idAgencia;

	@Column(name = "ativo", columnDefinition = "BIT", length = 1)
	private boolean ativo;

	private String bairro;

	@NotNull(message = "CEP é Obrigatório")
	private String cep;

	private String cidade;

	@CNPJ(message = "CNPJ informado é invalido")
	private String cnpj;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name="data_cadastro")
	private Date dataCadastro;

	@Temporal(TemporalType.TIMESTAMP)
	@Column(name="data_manutencao")
	private Date dataManutencao;

	@Size(min = 4, max = 64,
			message = "Domínio deve conter entre 4 e 80 caracteres")
	private String dominio;

	@Email(message = "E-mail informado é invalido")
	private String email;

	@Size(min = 4, max = 80,
			message = "Fantasia deve conter entre 4 e 80 caracteres")
	@Expose
	private String fantasia;

	@Column(name="insc_estadual")
	private String inscEstadual;

	private String logradouro;

	private int numero;
	@Size(min = 4, max = 120,
			message = "Razão social deve conter entre 4 e 120 caracteres")
	@Column(name="razao_social")
	private String razaoSocial;

	private String responsavel;

	private String telefone;

	@Expose
	private String uf;

	//bi-directional many-to-one association to Veiculo
	@OneToMany(mappedBy="agencia")
	private List<Veiculo> listaVeiculo;

	public Agencia() {
	}

	public int getIdAgencia() {
		return this.idAgencia;
	}

	public void setIdAgencia(int idAgencia) {
		this.idAgencia = idAgencia;
	}

	public boolean isAtivo() {
		return this.ativo;
	}

	public void setAtivo(boolean ativo) {
		this.ativo = ativo;
	}

	public String getBairro() {
		return this.bairro;
	}

	public void setBairro(String bairro) {
		this.bairro = bairro;
	}

	public String getCep() {
		return this.cep;
	}

	public void setCep(String cep) {
		this.cep = cep.replaceAll("[^0-9]", "");
	}

	public String getCidade() {
		return this.cidade;
	}

	public void setCidade(String cidade) {
		this.cidade = cidade;
	}

	public String getCnpj() {
		return this.cnpj;
	}

	public void setCnpj(String cnpj) {
		this.cnpj = cnpj;
	}

	public Date getDataCadastro() {
		return this.dataCadastro;
	}

	public void setDataCadastro(Date dataCadastro) {
		this.dataCadastro = dataCadastro;
	}

	public Date getDataManutencao() {
		return this.dataManutencao;
	}

	public void setDataManutencao(Date dataManutencao) {
		this.dataManutencao = dataManutencao;
	}

	public String getDominio() {
		return dominio;
	}

	public void setDominio(String dominio) {
		this.dominio = dominio;
	}

	public String getEmail() {
		return this.email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getFantasia() {
		return this.fantasia;
	}

	public void setFantasia(String fantasia) {
		this.fantasia = fantasia;
	}

	public String getInscEstadual() {
		return this.inscEstadual;
	}

	public void setInscEstadual(String inscEstadual) {
		this.inscEstadual = inscEstadual;
	}

	public String getLogradouro() {
		return this.logradouro;
	}

	public void setLogradouro(String logradouro) {
		this.logradouro = logradouro;
	}

	public int getNumero() {
		return this.numero;
	}

	public void setNumero(int numero) {
		this.numero = numero;
	}

	public String getRazaoSocial() {
		return this.razaoSocial;
	}

	public void setRazaoSocial(String razaoSocial) {
		this.razaoSocial = razaoSocial;
	}

	public String getResponsavel() {
		return this.responsavel;
	}

	public void setResponsavel(String responsavel) {
		this.responsavel = responsavel;
	}

	public String getTelefone() {
		return this.telefone;
	}

	public void setTelefone(String telefone) {
		this.telefone = telefone;
	}

	public String getUf() {
		return this.uf;
	}

	public void setUf(String uf) {
		this.uf = uf;
	}

	public List<Veiculo> getListaVeiculo() {
		return this.listaVeiculo;
	}

	public void setListaVeiculo(List<Veiculo> listaVeiculo) {
		this.listaVeiculo = listaVeiculo;
	}

	public String getStatusAtivoDisplay() {
		if (isAtivo()) {
			return "Ativo";
		} else {
			return "Inativo";
		}
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + idAgencia;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		Agencia other = (Agencia) obj;
		if (idAgencia != other.idAgencia) {
			return false;
		}
		return true;
	}
}


text:
namespace Apache.Ignite.Core.Events
{
    using System;
    using Apache.Ignite.Core.Binary;

    /// <summary>
    /// Event reader.
    /// </summary>
    internal static class EventReader
    {
        /// <summary>
        /// Reads an event.
        /// </summary>
        /// <typeparam name="T">Type of the event</typeparam>
        /// <param name="reader">Reader.</param>
        /// <returns>Deserialized event.</returns>
        /// <exception cref="System.InvalidCastException">Incompatible event type.</exception>
        public static T Read<T>(IBinaryRawReader reader) where T : IEvent
        {
            var clsId = reader.ReadInt();

            if (clsId == -1)
                return default(T);

            return (T) CreateInstance(clsId, reader);
        }

        /// <summary>
        /// Creates an event instance by type id.
        /// </summary>
        /// <param name="clsId">Type id.</param>
        /// <param name="reader">Reader.</param>
        /// <returns>Created and deserialized instance.</returns>
        /// <exception cref="System.InvalidOperationException">Invalid event class id:  + clsId</exception>
        private static IEvent CreateInstance(int clsId, IBinaryRawReader reader)
        {
            switch (clsId)
            {
                case 2: return new CacheEvent(reader);
                case 3: return new CacheQueryExecutedEvent(reader);
                case 4: return new CacheQueryReadEvent(reader);
                case 5: return new CacheRebalancingEvent(reader);
                case 6: return new CheckpointEvent(reader);
                case 7: return new DiscoveryEvent(reader);
                case 8: return new JobEvent(reader);
                case 9: return new SwapSpaceEvent(reader);
                case 10: return new TaskEvent(reader);
            }

            throw new InvalidOperationException("Invalid event class id: " + clsId);
        }
    }
}


text:
var Zeta=require('../../'),
    request=require('supertest'),
    demo=Zeta.module('demo',[]),
    should=require('chai').should(),
    formidable=require('formidable');
    demo.load();
//we use node-formidable as our form service
//so there is only one simple test
describe('$form',function(){
    it('should get the same form as node-formidable',function(){
        var myForm=demo.factory('$form')();
        var form=new formidable.IncomingForm();
        myForm.should.eql(form);
    });
});


text:
SPL: RecursiveIteratorIterator with custom iterator class
--FILE--
<?php

$ar = array(1, 2, array(31, 32, array(331)), 4);

foreach(new RecursiveIteratorIterator(new ArrayObject($ar, 0, "RecursiveArrayIterator")) as $v) echo "$v\n";

$it = new ArrayObject($ar);
var_dump($it->getIteratorClass());

try
{
	foreach(new RecursiveIteratorIterator(new ArrayObject($ar)) as $v) echo "$v\n";
}
catch (InvalidArgumentException $e)
{
	echo $e->getMessage() . "\n";
}

echo "===MANUAL===\n";

$it->setIteratorClass("RecursiveArrayIterator");
var_dump($it->getIteratorClass());
foreach(new RecursiveIteratorIterator($it) as $v) echo "$v\n";

?>
===DONE===
<?php exit(0); ?>
--EXPECT--
1
2
31
32
331
4
string(13) "ArrayIterator"
An instance of RecursiveIterator or IteratorAggregate creating it is required
===MANUAL===
string(22) "RecursiveArrayIterator"
1
2
31
32
331
4
===DONE===


text:
package jhazm.test.reader;

import edu.stanford.nlp.ling.TaggedWord;
import jhazm.reader.PeykareReader;
import org.junit.Test;

import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 * Created by Mojtaba on 30/10/2015.
 */
public class PeykareReaderTest {

    @Test
    public void coarsePOSTest() {
        List<String> input = Arrays.asList(new String[]{ "N", "COM", "SING" });
        String expected = "N";
        String actual = PeykareReader.coarsePOS(input);
        assertEquals("Failed to find coarse pos.", expected, actual);
    }

    @Test
    public void joinVerbPartsTest() {
        List<TaggedWord> input = Arrays.asList(new TaggedWord[] {
                new TaggedWord("اولین", "AJ"),
                new TaggedWord("سیاره", "Ne"),
                new TaggedWord("", "AJ"),
                new TaggedWord("از", "P"),
                new TaggedWord("منظومه", "Ne"),
                new TaggedWord("شمسی", "AJ"),
                new TaggedWord("دیده", "AJ"),
                new TaggedWord("شد", "V"),
                new TaggedWord(".", "PUNC")
        });

        List<TaggedWord> expected = Arrays.asList(new TaggedWord[] {
                new TaggedWord("اولین", "AJ"),
                new TaggedWord("سیاره", "Ne"),
                new TaggedWord("خارج", "AJ"),
                new TaggedWord("از", "P"),
                new TaggedWord("منظومه", "Ne"),
                new TaggedWord("شمسی", "AJ"),
                new TaggedWord("دیده شد", "V"),
                new TaggedWord(".", "PUNC")
        });
        List<TaggedWord> actual = PeykareReader.joinVerbParts(input);

        assertEquals("Failed to join verb parts of sentence", expected.size(), actual.size());
        for (int i = 0; i < expected.size(); i++)
        {
            TaggedWord actualTaggedWord = actual.get(i);
            TaggedWord expectedTaggedWord = expected.get(i);
            if (!actualTaggedWord.tag().equals(expectedTaggedWord.tag()))
                assertEquals("Failed to join verb parts of sentence", expectedTaggedWord, actualTaggedWord);
        }
    }
}


text:
import datetime
from pyspark.sql.types import *
from pytz import utc

def local_datetime(utc_year, utc_month, utc_day, utc_hour):
    """This works around the fact that Spark SQL doesn't handle timezones"""
    dt = datetime.datetime(utc_year, utc_month, utc_day, utc_hour)
    epoch = datetime.datetime.utcfromtimestamp(0)
    seconds = (dt - epoch).total_seconds()
    return datetime.datetime.fromtimestamp(seconds)

def load_wiki_rdd(sc, path):
    """Creates an RDD of (timestamp, page, views).

    Parameters
    ----------
    sc - SparkContext to create the RDD in.
    path - Path to data.

    Returns
    -------
    An RDD of tuples (timestamp, page, views) of types (datetime.datetime, string, float)
    """
    def parse_line(line):
        tokens = line.split('\t')
        timestamp = local_datetime(int(tokens[0]), int(tokens[1]), int(tokens[2]), int(tokens[3]))
        page = tokens[4]
        views = float(tokens[5])
        return (timestamp, page, views)
    return sc.textFile(path).map(parse_line)

def load_wiki_df(sql_context, path):
    """Creates a Spark DataFrame of (timestamp, page, views).

    Parameters
    ----------
        sqlContext - SqlContext to create the RDD in.
        path - Path to data.

    Returns
    -------
        A Spark DataFrame with column names ('timestamp', 'page', 'views') of types (Timestamp, String, Double)
    """
    rdd = load_wiki_rdd(sql_context._sc, path)
    fields = [ \
        StructField('timestamp', TimestampType(), True), \
        StructField('page', StringType(), True), \
        StructField('views', DoubleType(), True)]
    schema = StructType(fields)
    return sql_context.createDataFrame(rdd, schema)

def load_ticker_rdd(sc, path):
    """Creates an RDD of (timestamp, symbol, price) for stock ticker data.

    Parameters
    ----------
        sc - SparkContext to create the RDD in.
        path - Path to data.

    Returns
    -------
        An RDD of tuples where ech tuple has the type (datetime.datetime, string, float).
    """
    def parse_line(line):
        tokens = line.split('\t')
        timestamp = local_datetime(int(tokens[0]), int(tokens[1]), int(tokens[2]), int(tokens[3]))
        symbol = tokens[4]
        price = float(tokens[6])
        return (timestamp, symbol, price)
    return sc.textFile(path).map(parse_line)

def load_ticker_df(sql_context, path):
    """Creates a Spark DataFrame of (timestamp, symbol, price).

    Parameters
    ----------
        sqlContext - SqlContext to create the RDD in.
        path - Path to data.

    Returns
    -------
        A Spark DataFrame with column names (timestamp, symbol, price) of types (Timestamp, String, Double)
    """
    rdd = load_ticker_rdd(sql_context._sc, path)
    fields = [ \
        StructField('timestamp', TimestampType(), True), \
        StructField('symbol', StringType(), True), \
        StructField('price', DoubleType(), True)]
    schema = StructType(fields)
    return sql_context.createDataFrame(rdd, schema)


text:
using Microsoft.Practices.EnterpriseLibrary.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Text;

namespace XCLCMS.Data.DAL
{
    /// <summary>
    /// 数据访问类:SysRole
    /// </summary>
    public partial class SysRole : XCLCMS.Data.DAL.Common.BaseDAL
    {
        /// <summary>
        ///  增加一条数据
        /// </summary>
        public bool Add(XCLCMS.Data.Model.SysRole model)
        {
            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetStoredProcCommand("sp_SysRole_ADD");
            db.AddInParameter(dbCommand, "SysRoleID", DbType.Int64, model.SysRoleID);
            db.AddInParameter(dbCommand, "ParentID", DbType.Int64, model.ParentID);
            db.AddInParameter(dbCommand, "RoleName", DbType.String, model.RoleName);
            db.AddInParameter(dbCommand, "Code", DbType.AnsiString, model.Code);
            db.AddInParameter(dbCommand, "Sort", DbType.Int32, model.Sort);
            db.AddInParameter(dbCommand, "Weight", DbType.Int32, model.Weight);
            db.AddInParameter(dbCommand, "Remark", DbType.AnsiString, model.Remark);
            db.AddInParameter(dbCommand, "FK_MerchantID", DbType.Int64, model.FK_MerchantID);
            db.AddInParameter(dbCommand, "RecordState", DbType.AnsiString, model.RecordState);
            db.AddInParameter(dbCommand, "CreateTime", DbType.DateTime, model.CreateTime);
            db.AddInParameter(dbCommand, "CreaterID", DbType.Int64, model.CreaterID);
            db.AddInParameter(dbCommand, "CreaterName", DbType.String, model.CreaterName);
            db.AddInParameter(dbCommand, "UpdateTime", DbType.DateTime, model.UpdateTime);
            db.AddInParameter(dbCommand, "UpdaterID", DbType.Int64, model.UpdaterID);
            db.AddInParameter(dbCommand, "UpdaterName", DbType.String, model.UpdaterName);

            db.AddOutParameter(dbCommand, "ResultCode", DbType.Int32, 4);
            db.AddOutParameter(dbCommand, "ResultMessage", DbType.String, 1000);
            db.ExecuteNonQuery(dbCommand);

            var result = XCLCMS.Data.DAL.Common.Common.GetProcedureResult(dbCommand.Parameters);
            if (result.IsSuccess)
            {
                return true;
            }
            else
            {
                throw new Exception(result.ResultMessage);
            }
        }

        /// <summary>
        ///  更新一条数据
        /// </summary>
        public bool Update(XCLCMS.Data.Model.SysRole model)
        {
            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetStoredProcCommand("sp_SysRole_Update");
            db.AddInParameter(dbCommand, "SysRoleID", DbType.Int64, model.SysRoleID);
            db.AddInParameter(dbCommand, "ParentID", DbType.Int64, model.ParentID);
            db.AddInParameter(dbCommand, "RoleName", DbType.String, model.RoleName);
            db.AddInParameter(dbCommand, "Code", DbType.AnsiString, model.Code);
            db.AddInParameter(dbCommand, "Sort", DbType.Int32, model.Sort);
            db.AddInParameter(dbCommand, "Weight", DbType.Int32, model.Weight);
            db.AddInParameter(dbCommand, "Remark", DbType.AnsiString, model.Remark);
            db.AddInParameter(dbCommand, "FK_MerchantID", DbType.Int64, model.FK_MerchantID);
            db.AddInParameter(dbCommand, "RecordState", DbType.AnsiString, model.RecordState);
            db.AddInParameter(dbCommand, "CreateTime", DbType.DateTime, model.CreateTime);
            db.AddInParameter(dbCommand, "CreaterID", DbType.Int64, model.CreaterID);
            db.AddInParameter(dbCommand, "CreaterName", DbType.String, model.CreaterName);
            db.AddInParameter(dbCommand, "UpdateTime", DbType.DateTime, model.UpdateTime);
            db.AddInParameter(dbCommand, "UpdaterID", DbType.Int64, model.UpdaterID);
            db.AddInParameter(dbCommand, "UpdaterName", DbType.String, model.UpdaterName);

            db.AddOutParameter(dbCommand, "ResultCode", DbType.Int32, 4);
            db.AddOutParameter(dbCommand, "ResultMessage", DbType.String, 1000);
            db.ExecuteNonQuery(dbCommand);

            var result = XCLCMS.Data.DAL.Common.Common.GetProcedureResult(dbCommand.Parameters);
            if (result.IsSuccess)
            {
                return true;
            }
            else
            {
                throw new Exception(result.ResultMessage);
            }
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public XCLCMS.Data.Model.SysRole GetModel(long SysRoleID)
        {
            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand("select * from SysRole  WITH(NOLOCK)  where SysRoleID=@SysRoleID");
            db.AddInParameter(dbCommand, "SysRoleID", DbType.Int64, SysRoleID);
            using (var dr = db.ExecuteReader(dbCommand))
            {
                return XCLNetTools.DataSource.DataReaderHelper.DataReaderToEntity<XCLCMS.Data.Model.SysRole>(dr);
            }
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public List<XCLCMS.Data.Model.SysRole> GetModelList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * FROM SysRole WITH(NOLOCK)   ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            Database db = base.CreateDatabase();
            using (var dr = db.ExecuteReader(CommandType.Text, strSql.ToString()))
            {
                return XCLNetTools.DataSource.DataReaderHelper.DataReaderToList<XCLCMS.Data.Model.SysRole>(dr);
            }
        }

        /// <summary>
        /// 获取指定userid的角色
        /// </summary>
        public List<XCLCMS.Data.Model.SysRole> GetListByUserID(long userId)
        {
            string strSql = @"SELECT
                                        a.*
                                        FROM dbo.SysRole AS a WITH(NOLOCK)
                                        INNER JOIN dbo.SysUserRole AS b  WITH(NOLOCK)  ON b.FK_UserInfoID=@FK_UserInfoID AND b.RecordState='N' AND a.RecordState='N' and a.SysRoleID=b.FK_SysRoleID";
            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "FK_UserInfoID", DbType.Int64, userId);
            using (var dr = db.ExecuteReader(dbCommand))
            {
                return XCLNetTools.DataSource.DataReaderHelper.DataReaderToList<XCLCMS.Data.Model.SysRole>(dr);
            }
        }

        /// <summary>
        /// 判断角色标识是否存在
        /// </summary>
        public bool IsExistCode(string code)
        {
            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand("select top 1 1 from SysRole WITH(NOLOCK)   where Code=@Code");
            db.AddInParameter(dbCommand, "Code", DbType.AnsiString, code);
            return db.ExecuteScalar(dbCommand) != null;
        }

        /// <summary>
        /// 获取指定SysRoleID所属的层级list,如:根目录/子目录/文件
        /// </summary>
        public List<XCLCMS.Data.Model.Custom.SysRoleSimple> GetLayerListBySysRoleID(long sysRoleID)
        {
            string str = string.Format(@"
                                                        WITH Info1 AS (
	                                                        SELECT SysRoleID, ParentID, RoleName FROM dbo.SysRole  WITH(NOLOCK) WHERE SysRoleID={0}
	                                                        UNION ALL
	                                                        SELECT a.SysRoleID, a.ParentID,a.RoleName FROM dbo.SysRole AS a  WITH(NOLOCK)
	                                                        INNER JOIN Info1 AS b ON a.SysRoleID=b.ParentID
                                                        )
                                                        SELECT SysRoleID, ParentID,RoleName FROM Info1
                              ", sysRoleID);
            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand(str.ToString());
            List<XCLCMS.Data.Model.Custom.SysRoleSimple> lst = null;
            using (var dr = db.ExecuteReader(dbCommand))
            {
                lst = XCLNetTools.DataSource.DataReaderHelper.DataReaderToList<XCLCMS.Data.Model.Custom.SysRoleSimple>(dr);
            }
            if (null != lst)
            {
                lst.Reverse();
            }
            return lst;
        }

        /// <summary>
        /// 删除指定SysRoleID下面的子节点
        /// </summary>
        public bool DelChild(XCLCMS.Data.Model.SysRole model)
        {
            string strSql = string.Format("update SysRole set RecordState='{0}',UpdateTime=@UpdateTime,UpdaterID=@UpdaterID,UpdaterName=@UpdaterName where ParentID=@SysRoleID and RecordState='{1}' and ParentID>0",
                                    XCLCMS.Data.CommonHelper.EnumType.RecordStateEnum.D.ToString(), XCLCMS.Data.CommonHelper.EnumType.RecordStateEnum.N.ToString());

            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "SysRoleID", DbType.Int64, model.SysRoleID);
            db.AddInParameter(dbCommand, "UpdateTime", DbType.DateTime, model.UpdateTime);
            db.AddInParameter(dbCommand, "UpdaterID", DbType.Int64, model.UpdaterID);
            db.AddInParameter(dbCommand, "UpdaterName", DbType.String, model.UpdaterName);
            return db.ExecuteNonQuery(dbCommand) > 0;
        }

        /// <summary>
        /// 根据SysRoleID查询其子项
        /// </summary>
        public List<XCLCMS.Data.Model.SysRole> GetChildListByID(long sysRoleID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"SELECT
                                        a.*
                                        FROM dbo.SysRole AS a WITH(NOLOCK)
                                        where ParentID=@ParentID and RecordState='N'
                                        ");
            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "ParentID", DbType.Int64, sysRoleID);
            using (var dr = db.ExecuteReader(dbCommand))
            {
                return XCLNetTools.DataSource.DataReaderHelper.DataReaderToList<XCLCMS.Data.Model.SysRole>(dr);
            }
        }

        /// <summary>
        /// 根据code查询model
        /// </summary>
        public XCLCMS.Data.Model.SysRole GetModelByCode(string code)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append(@"SELECT
                                        top 1
                                        a.*
                                        FROM dbo.SysRole AS a WITH(NOLOCK)
                                        where a.RecordState='N' and a.Code=@Code
                                        ");

            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand(strSql.ToString());
            db.AddInParameter(dbCommand, "Code", DbType.AnsiString, code);
            using (var dr = db.ExecuteReader(dbCommand))
            {
                return XCLNetTools.DataSource.DataReaderHelper.DataReaderToEntity<XCLCMS.Data.Model.SysRole>(dr);
            }
        }

        /// <summary>
        /// 根据id批量获取实体
        /// </summary>
        public List<XCLCMS.Data.Model.SysRole> GetModelList(List<long> roleIdList)
        {
            if (null == roleIdList || roleIdList.Count == 0)
            {
                return new List<Model.SysRole>();
            }
            Database db = base.CreateDatabase();
            DbCommand dbCommand = db.GetSqlStringCommand(@"
                                                                                SELECT a.* FROM dbo.SysRole AS a WITH(NOLOCK)
                                                                                INNER JOIN @TVP_RoleID AS b ON a.SysRoleID=b.ID
                                                                                ");
            dbCommand.Parameters.Add(new SqlParameter("@TVP_RoleID", SqlDbType.Structured)
            {
                TypeName = "TVP_IDTable",
                Direction = ParameterDirection.Input,
                Value = XCLNetTools.DataSource.DataTableHelper.ToSingleColumnDataTable<long, long>(roleIdList)
            });
            using (var dr = db.ExecuteReader(dbCommand))
            {
                return XCLNetTools.DataSource.DataReaderHelper.DataReaderToList<XCLCMS.Data.Model.SysRole>(dr);
            }
        }
    }
}


text:
class BiblePassage::InvalidReference < BiblePassage::Reference

  attr_reader :error

  def initialize(message)
    @error = message
  end

  def valid?
    false
  end

end


text:
<?php

namespace RatePAY\Model\Request;

use RatePAY\Model\Request\SubModel\Content;

trait TraitRequestContent
{

    /**
     * @var Content
     */
    private $content;

    /**
     * Sets the value for $content
     *
     * @return Content
     */
    public function getContent()
    {
        return $this->content;
    }

    /**
     * Returns the value of $content
     *
     * @param Content $content'
     */
    public function setContent(Content $content)
    {
        $this->content = $content;
    }

    /**
     * Returns all values as Array
     *
     * @return array
     */
    public function toArray()
    {
        return array_merge(
            parent::toArray(),
            [
                'content' => $this->getContent()->toArray()
            ]
        );
    }

}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.machinelearningservices.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Details of customized scripts to execute for setting up the cluster. */
@Fluent
public final class SetupScripts {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(SetupScripts.class);

    /*
     * Customized setup scripts
     */
    @JsonProperty(value = "scripts")
    private ScriptsToExecute scripts;

    /**
     * Get the scripts property: Customized setup scripts.
     *
     * @return the scripts value.
     */
    public ScriptsToExecute scripts() {
        return this.scripts;
    }

    /**
     * Set the scripts property: Customized setup scripts.
     *
     * @param scripts the scripts value to set.
     * @return the SetupScripts object itself.
     */
    public SetupScripts withScripts(ScriptsToExecute scripts) {
        this.scripts = scripts;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (scripts() != null) {
            scripts().validate();
        }
    }
}


text:
/*
 * LMSubspaceOptimizer.h
 *
 *  Created on: Apr 30, 2014
 *      Author: afriesen
 */

#ifndef RDIS_LMSUBSPACEOPTIMIZER_H_
#define RDIS_LMSUBSPACEOPTIMIZER_H_

#include "common.h"
#include "SubspaceOptimizer.h"

#include "OptimizableFunction.h"

namespace rdis {

// Levenberg-Marquardt based subspace optimizer
class LMSubspaceOptimizer
		: public rdis::SubspaceOptimizer {

	typedef rdis::SubspaceOptimizer super;

public:
	LMSubspaceOptimizer( OptimizableFunction & f_ );
	virtual ~LMSubspaceOptimizer();

public:
	// parameters are the vars and factors that define this subfunction, the
	// starting values of those variables in the same order as the <vars>
	// vector (will contain the final values after optimization completes), and
	// the change in f(x) as a result of the optimization = f(x_end) - f(x_init)
	virtual Numeric optimize( const VariablePtrVec & vars,
			const FactorPtrVec & factors, NumericVec & xval,
			Numeric & deltaFval, const bool printdbg );

protected:

	// store for memory efficiency
//	NumericVec initstate;
	NumericVec initeval;
	NumericVec finaleval;
	PartialGradient pgtemp;
};

namespace LMSSOpt {

// struct containing auxiliary data for function evaluation
struct AuxData {
	AuxData( const VariablePtrVec & va, const FactorPtrVec & fac,
			OptimizableFunction & func,
			PartialGradient & pgt_ )
		: vars( va )
		, factors( fac )
		, f( func )
		, pgt( pgt_ )
	{}

	const VariablePtrVec & vars;
	const FactorPtrVec & factors;
	OptimizableFunction & f;

	// store for memory efficiency
	PartialGradient & pgt;
};

// evaluate the function and the jacobian of the function at the specified
// point p
void evalFunc( double * p, double * hx, int m, int n, void * adata );
void evalJacf( double * p, double * j, int m, int n, void * adata );

void quickAssignVals( AuxData & aux, int m, double * p );

} // namespace LMSSOpt

} // namespace rdis
#endif // RDIS_LMSUBSPACEOPTIMIZER_H_


text:
package com.raulsuarezdabo.flight.dao;

import com.raulsuarezdabo.flight.entity.BookEntity;
import com.raulsuarezdabo.flight.entity.CityEntity;
import com.raulsuarezdabo.flight.entity.FlightEntity;
import com.raulsuarezdabo.flight.entity.SeatEntity;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * Interface for defining the methods to access to flight information
 * @author raulsuarez
 */
public interface FlightDAO {
    /**
     * Get all airplane
     * @return List
     */
    public List<FlightEntity> findAll();

    /**
     * Find airplane by id
     * @param id    int
     * @return  AirplaneEntity
     */
    public FlightEntity findById(int id);

    /**
     * Find flight by code
     * @param code  String
     * @return  FlightEntity   airport
     */
    public FlightEntity findByCode(String code);

    /**
     * Find flights by date of takes off
     * @param from  Date
     * @param to    Date
     * @return  List of Flights
     */
    public List<FlightEntity> findByDate(Date from, Date to);

    /**
     * Add new airplane
     * @param flight
     */
    public void addFlight(FlightEntity flight);

    /**
     * Update an airplane
     * @param flight
     * @return AirplaneEntity    returns the entity or null if error
     */
    public boolean updateFlight(FlightEntity flight);

    /**
     * Delete an airplane
     * @param flight
     * @return boolean  with success or not
     */
    public boolean deleteFlight(FlightEntity flight);

    /**
     * Method for searching results of flights with the specific criteria
     * @param from  CityEntity
     * @param to    CityEntity
     * @param when  Date
     * @return  List flights available with this criteria
     */
    public List<FlightEntity> findFlights(CityEntity from, CityEntity to, Date when);

    /**
     * Method that sets a couple of seats
     * @param flight    FlightEntity
     * @param seats SeatEntity
     * @param book  BookEntity
     * @return  boolean
     */
    public boolean setSeatsToFlight(FlightEntity flight, Set<SeatEntity> seats, BookEntity book);

    /**
     * Method that sets a couple of seats
     * @param flight    FlightEntity
     * @param seat  SeatEntity
     * @param book  BookEntity
     * @return  boolean
     */
    public boolean setSeatToFlight(FlightEntity flight, SeatEntity seat, BookEntity book);

    /**
     * Method to find list of flights for tracking
     * @param days  int
     * @return  List
     */
    public List findCountFlightsByDate(int days);

    /**
     *
     * @param flight    FlightEntity
     * @param type  int
     * @return  List of seats
     */
    public List<SeatEntity> getSeatsByFlightClass(FlightEntity flight, int type);

    /**
     * Find flights that takes off by date
     * @param date
     * @return  List
     */
    public List<FlightEntity> findByDate(Date date);

}


text:
/* eslint no-useless-escape: 0 */

// Adding weapon in the weapon window.
exports = function(browser, weapon) {
    Object.keys(weapon).forEach(key => {
        let weapons = '';
        let keyFormated = key.toLowerCase().replace(/\s/g, '_');

        weapon[key].forEach(weaponData => {
            weapons += `<div class="item weapon" data-hash="${weaponData.hash}">${weaponData.name}</div>`;
        });

        let query = `

            ${key}

            ${weapons}

`;

        let queryFormated = query.replace(/\n/g, '').replace(/"/g, '\"');

        browser.execute(`$('#weapon_window .window_body').append('${queryFormated}')`);
    });
};


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Core.PropertyEditors;
using Videolizer.Umbraco;

namespace Videolizer.Umbraco.PropertyValueConverter {
    [PropertyValueType(typeof(VideolizerVideo))]
    [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)]
    public class VideoPickerPVC : PropertyValueConverterBase {

        public override bool IsConverter(PublishedPropertyType propertyType) {
            return propertyType.PropertyEditorAlias.Equals("DigitalMomentum.Videolizer");
        }

        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) {
            if (source == null) return new UmbVideolizerVideo();

            var sourceString = source.ToString();

            try {
                var obj = JsonConvert.DeserializeObject<UmbVideolizerVideo>(sourceString);

                if (obj != null) {
                    return obj;
                }
                return new UmbVideolizerVideo();

            } catch {
                try {
					//Not a Videolizer Object. Maybe its just a URL string and we can convert it?
					UmbVideolizerVideo newVideo = new UmbVideolizerVideo(sourceString);
                    return newVideo;
                } catch {
                    return new UmbVideolizerVideo();
                }

            }

        }

    }
}


text:
Stop Gradle Now!
================

Plugin for Android Studio to stop gradle by invoking the `./gradlew --stop` command.

I wrote this plugin in response [this reddit post](https://www.reddit.com/r/androiddev/comments/48x000/literally_the_only_dev_environment_incapable_of/). Also, I was curious how to write plugins to intellij. I've written extensions for Visual Studio for previous jobs, but never Android Studio (and never in Java).

Truth be told, this is the first time I've downloaded intellij.

After developing and verifying the plugin worked in Android Studio, I realized I never did my due diligence in searching to see if anyone else had actually done something similar.

Looks like I'm not the first to come up with this plugin.

* GradleKillerIdeaPlugin - ([JetBrains link](https://plugins.jetbrains.com/plugin/7794?pr=idea)) ([Github](https://github.com/KanbanApps/GradleKillerIdeaPlugin))

Our solutions are different (killing the gradle process vs executing the `gradle --stop` command), but because `GradleKillerIdeaPlugin` is already on JetBrain's site and does the same thing mine does, I won't be posting mine to JetBrains unless someone wants me to. I'll leave the repo up, however, as a learning experience.

### How to write plugins for intellij
* http://www.jetbrains.org/intellij/sdk/docs/basics.html
* http://www.jetbrains.org/intellij/sdk/docs/faq.html
* https://intellij-support.jetbrains.com/hc/en-us/community/posts/206756455-Question-about-Actions


text:
@implementation TestListenUtil

+(void)pushNectRequestResult:(NSString *)reqUrl error:(NSError *)error responseObject:(id)responseObject{

    if (!DEBUG) {
        return;
    }
    if (![[[NSUserDefaults standardUserDefaults] valueForKey:@"isListen_nect"] isEqualToString:@"1"]) {
//        return;
    }

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //子线程内部(耗时代码写在这里)
        //H回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            //主线程内容
            NSString *testUrl = @"http://192.168.2.5:8082/MyJFinalApp/Listen/pushResult";

            AFHTTPSessionManager *session = [[MyAFHTTPSessionManager sharedManager] getSessionManager];

            //    AFHTTPRequestSerializer            二进制格式
            //    AFJSONRequestSerializer            JSON
            //    AFPropertyListRequestSerializer    PList(是一种特殊的XML,解析起来相对容易)
            session.requestSerializer = [AFJSONRequestSerializer serializer]; // 上传普通格式
            [session.requestSerializer setValue: @"application/json" forHTTPHeaderField:@"Content-type"];//设置请求的头
            //Responses 响应Header参数
            session.responseSerializer = [AFJSONResponseSerializer serializer];
            //系统参数
            session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"text/html", @"text/plain",nil];

            NSMutableDictionary *params = [NSMutableDictionary dictionary];
            params[@"requestUrl"] = @"133";
            params[@"params"] = @"params";
            if (error) {
                params[@"result"] = @"请求失败";
                params[@"resultInfo"] = error.userInfo[@"NSLocalizedDescription"];
            }else{
                params[@"result"] = @"请求成功";
                params[@"resultInfo"] = responseObject;
            }

            [session POST:testUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                DLog(@"监控发送成功");
                [[MyAFHTTPSessionManager sharedManager] returnToSessionManager:session];
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error1) {
                DLog(@"监控发送失败");
                DLog(@"error:%@",error1.userInfo)
                [[MyAFHTTPSessionManager sharedManager] returnToSessionManager:session];
            }];

        });
    });

}

@end


text:
namespace content_settings {

namespace {

// Obsolete prefs to be removed from the pref file.
// TODO(msramek): Remove this cleanup code after two releases (i.e. in M48).
const char kObsoleteDefaultContentSettings[] =
    "profile.default_content_settings";
const char kObsoleteMigratedDefaultContentSettings[] =
    "profile.migrated_default_content_settings";
const char kObsoleteMigratedDefaultMediaStreamSetting[] =
    "profile.migrated_default_media_stream_content_settings";
// TODO(msramek): Remove this cleanup code after two releases (i.e. in M50).
const char kObsoleteMetroSwitchToDesktopSetting[] =
    "profile.default_content_setting_values.metro_switch_to_desktop";

ContentSetting GetDefaultValue(const WebsiteSettingsInfo* info) {
  const base::Value* initial_default = info->initial_default_value();
  if (!initial_default)
    return CONTENT_SETTING_DEFAULT;
  int result = 0;
  bool success = initial_default->GetAsInteger(&result);
  DCHECK(success);
  return static_cast<ContentSetting>(result);
}

ContentSetting GetDefaultValue(ContentSettingsType type) {
  return GetDefaultValue(WebsiteSettingsRegistry::GetInstance()->Get(type));
}

const std::string& GetPrefName(ContentSettingsType type) {
  return WebsiteSettingsRegistry::GetInstance()
      ->Get(type)
      ->default_value_pref_name();
}

class DefaultRuleIterator : public RuleIterator {
 public:
  explicit DefaultRuleIterator(const base::Value* value) {
    if (value)
      value_.reset(value->DeepCopy());
  }

  bool HasNext() const override { return value_.get() != NULL; }

  Rule Next() override {
    DCHECK(value_.get());
    return Rule(ContentSettingsPattern::Wildcard(),
                ContentSettingsPattern::Wildcard(),
                value_.release());
  }

 private:
  scoped_ptr<base::Value> value_;
};

}  // namespace

// static
void DefaultProvider::RegisterProfilePrefs(
    user_prefs::PrefRegistrySyncable* registry) {
  // Register the default settings' preferences.
  WebsiteSettingsRegistry* website_settings =
      WebsiteSettingsRegistry::GetInstance();
  for (const WebsiteSettingsInfo* info : *website_settings) {
    registry->RegisterIntegerPref(info->default_value_pref_name(),
                                  GetDefaultValue(info),
                                  info->GetPrefRegistrationFlags());
  }

  // Obsolete prefs -------------------------------------------------------

  // The deprecated dictionary preference.
  registry->RegisterDictionaryPref(
      kObsoleteDefaultContentSettings,
      new base::DictionaryValue(),
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);

  // Whether the deprecated dictionary preference has already been migrated
  // into the individual preferences in this profile.
  registry->RegisterBooleanPref(
      kObsoleteMigratedDefaultContentSettings,
      false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);

  // Whether the deprecated mediastream default setting has already been
  // migrated into microphone and camera default settings.
  registry->RegisterBooleanPref(kObsoleteMigratedDefaultMediaStreamSetting,
                                false);

  // The removed content settings type METRO_SWITCH_TO_DESKTOP.
  registry->RegisterIntegerPref(
      kObsoleteMetroSwitchToDesktopSetting,
      0,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
}

DefaultProvider::DefaultProvider(PrefService* prefs, bool incognito)
    : prefs_(prefs),
      is_incognito_(incognito),
      updating_preferences_(false) {
  DCHECK(prefs_);

  // Remove the obsolete preferences from the pref file.
  DiscardObsoletePreferences();

  // Read global defaults.
  ReadDefaultSettings();

  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultCookiesSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_COOKIES))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultImagesSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_IMAGES))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultJavaScriptSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_JAVASCRIPT))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultPluginsSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_PLUGINS))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultPopupsSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_POPUPS))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultLocationSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_GEOLOCATION))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultNotificationsSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_NOTIFICATIONS))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultMouseCursorSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_MOUSELOCK))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultMediaStreamMicSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_MEDIASTREAM_MIC))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultMediaStreamCameraSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_MEDIASTREAM_CAMERA))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultMIDISysExSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_MIDI_SYSEX))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultPushMessagingSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_PUSH_MESSAGING))),
      CONTENT_SETTING_NUM_SETTINGS);
  UMA_HISTOGRAM_ENUMERATION(
      "ContentSettings.DefaultKeygenSetting",
      IntToContentSetting(prefs_->GetInteger(
          GetPrefName(CONTENT_SETTINGS_TYPE_KEYGEN))),
      CONTENT_SETTING_NUM_SETTINGS);

  pref_change_registrar_.Init(prefs_);
  PrefChangeRegistrar::NamedChangeCallback callback = base::Bind(
      &DefaultProvider::OnPreferenceChanged, base::Unretained(this));
  WebsiteSettingsRegistry* website_settings =
      WebsiteSettingsRegistry::GetInstance();
  for (const WebsiteSettingsInfo* info : *website_settings)
    pref_change_registrar_.Add(info->default_value_pref_name(), callback);
}

DefaultProvider::~DefaultProvider() {
}

bool DefaultProvider::SetWebsiteSetting(
    const ContentSettingsPattern& primary_pattern,
    const ContentSettingsPattern& secondary_pattern,
    ContentSettingsType content_type,
    const ResourceIdentifier& resource_identifier,
    base::Value* in_value) {
  DCHECK(CalledOnValidThread());
  DCHECK(prefs_);

  // Ignore non default settings
  if (primary_pattern != ContentSettingsPattern::Wildcard() ||
      secondary_pattern != ContentSettingsPattern::Wildcard()) {
    return false;
  }

  // The default settings may not be directly modified for OTR sessions.
  // Instead, they are synced to the main profile's setting.
  if (is_incognito_)
    return false;

  // Put |in_value| in a scoped pointer to ensure that it gets cleaned up
  // properly if we don't pass on the ownership.
  scoped_ptr<base::Value> value(in_value);
  {
    base::AutoReset<bool> auto_reset(&updating_preferences_, true);
    // Lock the memory map access, so that values are not read by
    // |GetRuleIterator| at the same time as they are written here. Do not lock
    // the preference access though; preference updates send out notifications
    // whose callbacks may try to reacquire the lock on the same thread.
    {
      base::AutoLock lock(lock_);
      ChangeSetting(content_type, value.get());
    }
    WriteToPref(content_type, value.get());
  }

  NotifyObservers(ContentSettingsPattern(),
                  ContentSettingsPattern(),
                  content_type,
                  ResourceIdentifier());

  return true;
}

scoped_ptr<RuleIterator> DefaultProvider::GetRuleIterator(
    ContentSettingsType content_type,
    const ResourceIdentifier& resource_identifier,
    bool incognito) const {
  base::AutoLock lock(lock_);
  if (resource_identifier.empty()) {
    auto it(default_settings_.find(content_type));
    if (it != default_settings_.end())
      return scoped_ptr<RuleIterator>(
          new DefaultRuleIterator(it->second.get()));
    NOTREACHED();
  }
  return scoped_ptr<RuleIterator>(new EmptyRuleIterator());
}

void DefaultProvider::ClearAllContentSettingsRules(
    ContentSettingsType content_type) {
  // TODO(markusheintz): This method is only called when the
  // |DesktopNotificationService| calls |ClearAllSettingsForType| method on the
  // |HostContentSettingsMap|. Don't implement this method yet, otherwise the
  // default notification settings will be cleared as well.
}

void DefaultProvider::ShutdownOnUIThread() {
  DCHECK(CalledOnValidThread());
  DCHECK(prefs_);
  RemoveAllObservers();
  pref_change_registrar_.RemoveAll();
  prefs_ = NULL;
}

void DefaultProvider::ReadDefaultSettings() {
  base::AutoLock lock(lock_);
  WebsiteSettingsRegistry* website_settings =
      WebsiteSettingsRegistry::GetInstance();
  for (const WebsiteSettingsInfo* info : *website_settings)
    ChangeSetting(info->type(), ReadFromPref(info->type()).get());
}

bool DefaultProvider::IsValueEmptyOrDefault(ContentSettingsType content_type,
                                            base::Value* value) {
  if (!value) return true;
  return ValueToContentSetting(value) == GetDefaultValue(content_type);
}

void DefaultProvider::ChangeSetting(ContentSettingsType content_type,
                                    base::Value* value) {
  default_settings_[content_type] =
      value ? make_scoped_ptr(value->DeepCopy())
            : ContentSettingToValue(GetDefaultValue(content_type));
}

void DefaultProvider::WriteToPref(ContentSettingsType content_type,
                                  base::Value* value) {
  if (IsValueEmptyOrDefault(content_type, value)) {
    prefs_->ClearPref(GetPrefName(content_type));
    return;
  }

  int int_value = GetDefaultValue(content_type);
  bool is_integer = value->GetAsInteger(&int_value);
  DCHECK(is_integer);
  prefs_->SetInteger(GetPrefName(content_type), int_value);
}

void DefaultProvider::OnPreferenceChanged(const std::string& name) {
  DCHECK(CalledOnValidThread());
  if (updating_preferences_)
    return;

  // Find out which content setting the preference corresponds to.
  ContentSettingsType content_type = CONTENT_SETTINGS_TYPE_DEFAULT;

  WebsiteSettingsRegistry* website_settings =
      WebsiteSettingsRegistry::GetInstance();
  for (const WebsiteSettingsInfo* info : *website_settings) {
    if (info->default_value_pref_name() == name) {
      content_type = info->type();
      break;
    }
  }

  if (content_type == CONTENT_SETTINGS_TYPE_DEFAULT) {
    NOTREACHED() << "A change of the preference " << name << " was observed, "
                    "but the preference could not be mapped to a content "
                    "settings type.";
    return;
  }

  {
    base::AutoReset<bool> auto_reset(&updating_preferences_, true);
    // Lock the memory map access, so that values are not read by
    // |GetRuleIterator| at the same time as they are written here. Do not lock
    // the preference access though; preference updates send out notifications
    // whose callbacks may try to reacquire the lock on the same thread.
    {
      base::AutoLock lock(lock_);
      ChangeSetting(content_type, ReadFromPref(content_type).get());
    }
  }

  NotifyObservers(ContentSettingsPattern(),
                  ContentSettingsPattern(),
                  content_type,
                  ResourceIdentifier());
}

scoped_ptr<base::Value> DefaultProvider::ReadFromPref(
    ContentSettingsType content_type) {
  int int_value = prefs_->GetInteger(GetPrefName(content_type));
  return ContentSettingToValue(IntToContentSetting(int_value)).Pass();
}

void DefaultProvider::DiscardObsoletePreferences() {
  prefs_->ClearPref(kObsoleteDefaultContentSettings);
  prefs_->ClearPref(kObsoleteMigratedDefaultContentSettings);
  prefs_->ClearPref(kObsoleteMigratedDefaultMediaStreamSetting);
  prefs_->ClearPref(kObsoleteMetroSwitchToDesktopSetting);
}

}  // namespace content_settings


text:
module Unenviable
  # Wraps the ENV variable to catch calls to ENV where the value
  # is missing or not specified in Unenviable's YAML file.
  class ENVWrapper
    def initialize
      @saved_env = ENV
      @closed = false
      @missing_descriptions = []
    end

    def [](key)
      fail "Requested ENV[#{key}] after initialization finished!" if @closed
      value = @saved_env[key]
      @missing_descriptions << key unless Unenviable.described?(key)
      return value unless value.nil?
      'MISSING VALUE'
    end

    def []=(key, value)
      @saved_env[key] = value
    end

    def restore_saved
      Object.send(:remove_const, :ENV)
      Object.const_set(:ENV, @saved_env)
    end

    def close_wrapper
      @closed = true
      fail "Requested Keys [#{@missing_descriptions.join(', ')}] which are not described!" unless @missing_descriptions.empty?
    end
  end
end


text:
using System;
using System.Threading.Tasks;
namespace AngularJSAuthRefreshToken.AspNetIdentity
{
    public interface IRefreshTokenStore : IDisposable
    {
        Task<RefreshTokenClientApp> FindClientAppByIdAsync(string id);
        Task<bool> ContainsClientAppByIdAsync(string id);
        Task CreateTokenAsync(RefreshToken token);
        Task DeleteTokenAsync(string id);
        Task<RefreshToken> FindTokenByIdAsync(string id);
    }
}