text:
'use strict';

var AppDispatcher = require('../AppDispatcher'),
    EventEmitter = require('events').EventEmitter,
    AppConstants = require('../AppConstants'),
    Immutable = require('immutable'),
    CHANGE_EVENT = 'change',
    _dispatchToken,
    _state;

class WeatherStore extends EventEmitter {

  constructor() {
    super();

    _dispatchToken = AppDispatcher.register((action) => {
      switch (action.type) {

        case AppConstants.INITIALIZE:
          this.initialize(action.payload);
          this.emit(CHANGE_EVENT);
          break;

        default:
          console.error(new Error('noop'));
      }
    });
  }

  initialize(payload) {
    _state = Immutable.Map(payload);
  }

  getState() {
    return _state;
  }

}

module.exports = new WeatherStore();

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.component.cxf.jaxrs;

import org.apache.camel.Processor;
import org.apache.camel.Suspendable;
import org.apache.camel.component.cxf.interceptors.UnitOfWorkCloserInterceptor;
import org.apache.camel.component.cxf.util.CxfUtils;
import org.apache.camel.support.DefaultConsumer;
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.phase.Phase;
import org.apache.cxf.transport.MessageObserver;

/**
 * A Consumer of exchanges for a JAXRS service in CXF.  CxfRsConsumer acts a CXF
 * service to receive REST requests, convert them to a normal java object invocation,
 * and forward them to Camel route for processing.
 * It is also responsible for converting and sending back responses to CXF client.
 */
public class CxfRsConsumer extends DefaultConsumer implements Suspendable {
    private Server server;

    public CxfRsConsumer(CxfRsEndpoint endpoint, Processor processor) {
        super(endpoint, processor);
        server = createServer();
    }

    protected Server createServer() {
        CxfRsEndpoint endpoint = (CxfRsEndpoint) getEndpoint();
        CxfRsInvoker cxfRsInvoker = new CxfRsInvoker(endpoint, this);
        JAXRSServerFactoryBean svrBean = endpoint.createJAXRSServerFactoryBean();
        Bus bus = endpoint.getBus();

        // We need to apply the bus setting from the CxfRsEndpoint which does not use the default bus
        if (bus != null) {
            svrBean.setBus(bus);

        }

        svrBean.setInvoker(cxfRsInvoker);
        // setup the UnitOfWorkCloserInterceptor for OneWayMessageProcessor
        svrBean.getInInterceptors().add(new UnitOfWorkCloserInterceptor(Phase.POST_INVOKE, true));
        // close the UnitOfWork normally
        svrBean.getOutInterceptors().add(new UnitOfWorkCloserInterceptor());

        Server server = svrBean.create();

        final MessageObserver originalOutFaultObserver = server.getEndpoint().getOutFaultObserver();
        //proxy OutFaultObserver so we can close org.apache.camel.spi.UnitOfWork in case of error
        server.getEndpoint().setOutFaultObserver(message -> {
            CxfUtils.closeCamelUnitOfWork(message);
            originalOutFaultObserver.onMessage(message);
        });

        return server;
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();
        if (server == null) {
            server = createServer();
        }
        server.start();
    }

    @Override
    protected void doStop() throws Exception {
        if (server != null) {
            server.stop();
            server.destroy();
            server = null;
        }
        super.doStop();
    }

    public Server getServer() {
        return server;
    }

}


text:
package com.amazonaws.services.storagegateway.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.storagegateway.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.IdempotentUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * DescribeTapeArchivesRequest Marshaller
 */
public class DescribeTapeArchivesRequestMarshaller
        implements
        Marshaller<Request<DescribeTapeArchivesRequest>, DescribeTapeArchivesRequest> {

    public Request<DescribeTapeArchivesRequest> marshall(
            DescribeTapeArchivesRequest describeTapeArchivesRequest) {

        if (describeTapeArchivesRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<DescribeTapeArchivesRequest> request = new DefaultRequest<DescribeTapeArchivesRequest>(
                describeTapeArchivesRequest, "AWSStorageGateway");
        request.addHeader("X-Amz-Target",
                "StorageGateway_20130630.DescribeTapeArchives");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            final SdkJsonGenerator jsonGenerator = new SdkJsonGenerator();

            jsonGenerator.writeStartObject();

            com.amazonaws.internal.SdkInternalList<String> tapeARNsList = (com.amazonaws.internal.SdkInternalList<String>) describeTapeArchivesRequest
                    .getTapeARNs();
            if (!tapeARNsList.isEmpty() || !tapeARNsList.isAutoConstruct()) {
                jsonGenerator.writeFieldName("TapeARNs");
                jsonGenerator.writeStartArray();
                for (String tapeARNsListValue : tapeARNsList) {
                    if (tapeARNsListValue != null) {
                        jsonGenerator.writeValue(tapeARNsListValue);
                    }
                }
                jsonGenerator.writeEndArray();
            }
            if (describeTapeArchivesRequest.getMarker() != null) {
                jsonGenerator.writeFieldName("Marker").writeValue(
                        describeTapeArchivesRequest.getMarker());
            }
            if (describeTapeArchivesRequest.getLimit() != null) {
                jsonGenerator.writeFieldName("Limit").writeValue(
                        describeTapeArchivesRequest.getLimit());
            }

            jsonGenerator.writeEndObject();

            byte[] content = jsonGenerator.getBytes();
            request.setContent(new ByteArrayInputStream(content));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", "application/x-amz-json-1.1");
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
<?php

namespace Ensoul\Rankz\Init;

/**
 *
 * You can enable/disable this feature in functions.php (or lib/setup.php if you're using Sage):
 * add_theme_support('rankz-init');
 */

function init() {
  // Check if rankz_activation already exists and if not sets theme options
  if (!get_option('rankz_activation')) {
    // Change rankz_activtion value
    add_option('rankz_activation', 'actived');
    // Change default users role
    update_option('default_role', 'editor');
    // Change default blog description
    update_option('blogdescription', '');
    // Delete WordPress default post
    wp_delete_post(1, true);
    // Delete WordPress default page
    wp_delete_post(2, true);
    // Create Primary Navigation menu if doesn't exists
    if (!wp_get_nav_menu_object('Primary Navigation')) {
      set_theme_mod('nav_menu_locations', ['primary_navigation' => wp_create_nav_menu('Primary Navigation')]);
    }
  }
}
init();


text:
using System.Collections.Generic;
namespace Reconfig.Common.CQRS
{
    public interface IQueryHandler<in TQuery, out TResult> where TQuery : IQuery<TResult>
    {
        TResult Handle(TQuery param);
    }
}


text:
package cn.com.bluemoon.jeesite.modules.sys.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import cn.com.bluemoon.jeesite.common.config.Global;
import cn.com.bluemoon.jeesite.common.utils.StringUtils;
import cn.com.bluemoon.jeesite.common.web.BaseController;
import cn.com.bluemoon.jeesite.modules.sys.entity.Office;
import cn.com.bluemoon.jeesite.modules.sys.entity.User;
import cn.com.bluemoon.jeesite.modules.sys.service.OfficeService;
import cn.com.bluemoon.jeesite.modules.sys.utils.DictUtils;
import cn.com.bluemoon.jeesite.modules.sys.utils.UserUtils;

/**
 * 机构Controller
 * @author ThinkGem
 * @version 2013-5-15
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/office")
public class OfficeController extends BaseController {

	@Autowired
	private OfficeService officeService;

	@ModelAttribute("office")
	public Office get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			return officeService.get(id);
		}else{
			return new Office();
		}
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = {""})
	public String index(Office office, Model model) {
//        model.addAttribute("list", officeService.findAll());
		return "modules/sys/officeIndex";
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = {"list"})
	public String list(Office office, Model model) {
        model.addAttribute("list", officeService.findList(office));
		return "modules/sys/officeList";
	}

	@RequiresPermissions("sys:office:view")
	@RequestMapping(value = "form")
	public String form(Office office, Model model) {
		User user = UserUtils.getUser();
		if (office.getParent()==null || office.getParent().getId()==null){
			office.setParent(user.getOffice());
		}
		office.setParent(officeService.get(office.getParent().getId()));
		if (office.getArea()==null){
			office.setArea(user.getOffice().getArea());
		}
		// 自动获取排序号
		if (StringUtils.isBlank(office.getId())&&office.getParent()!=null){
			int size = 0;
			List<Office> list = officeService.findAll();
			for (int i=0; i<list.size(); i++){
				Office e = list.get(i);
				if (e.getParent()!=null && e.getParent().getId()!=null
						&& e.getParent().getId().equals(office.getParent().getId())){
					size++;
				}
			}
			office.setCode(office.getParent().getCode() + StringUtils.leftPad(String.valueOf(size > 0 ? size+1 : 1), 3, "0"));
		}
		model.addAttribute("office", office);
		return "modules/sys/officeForm";
	}

	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "save")
	public String save(Office office, Model model, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式,不允许操作!");
			return "redirect:" + adminPath + "/sys/office/";
		}
		if (!beanValidator(model, office)){
			return form(office, model);
		}
		officeService.save(office);

		if(office.getChildDeptList()!=null){
			Office childOffice = null;
			for(String id : office.getChildDeptList()){
				childOffice = new Office();
				childOffice.setName(DictUtils.getDictLabel(id, "sys_office_common", "未知"));
				childOffice.setParent(office);
				childOffice.setArea(office.getArea());
				childOffice.setType("2");
				childOffice.setGrade(String.valueOf(Integer.valueOf(office.getGrade())+1));
				childOffice.setUseable(Global.YES);
				officeService.save(childOffice);
			}
		}

		addMessage(redirectAttributes, "保存机构'" + office.getName() + "'成功");
		String id = "0".equals(office.getParentId()) ? "" : office.getParentId();
		return "redirect:" + adminPath + "/sys/office/list?id="+id+"&parentIds="+office.getParentIds();
	}

	@RequiresPermissions("sys:office:edit")
	@RequestMapping(value = "delete")
	public String delete(Office office, RedirectAttributes redirectAttributes) {
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式,不允许操作!");
			return "redirect:" + adminPath + "/sys/office/list";
		}
//		if (Office.isRoot(id)){
//			addMessage(redirectAttributes, "删除机构失败, 不允许删除顶级机构或编号空");
//		}else{
			officeService.delete(office);
			addMessage(redirectAttributes, "删除机构成功");
//		}
		return "redirect:" + adminPath + "/sys/office/list?id="+office.getParentId()+"&parentIds="+office.getParentIds();
	}

	/**
	 * 获取机构JSON数据。
	 * @param extId 排除的ID
	 * @param type	类型(1:公司;2:部门/小组/其它:3:用户)
	 * @param grade 显示级别
	 * @param response
	 * @return
	 */
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type,
			@RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Office> list = officeService.findList(isAll);
		for (int i=0; i<list.size(); i++){
			Office e = list.get(i);
			if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(e.getId()) && e.getParentIds().indexOf(","+extId+",")==-1))
					&& (type == null || (type != null && (type.equals("1") ? type.equals(e.getType()) : true)))
					&& (grade == null || (grade != null && Integer.parseInt(e.getGrade()) <= grade.intValue()))
					&& Global.YES.equals(e.getUseable())){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getId());
				map.put("pId", e.getParentId());
				map.put("pIds", e.getParentIds());
				map.put("name", e.getName());
				if (type != null && "3".equals(type)){
					map.put("isParent", true);
				}
				mapList.add(map);
			}
		}
		return mapList;
	}
}


text: Profile for {{userId}}


text:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<script src="../js/resources/js-test-pre.js"></script>
</head>
<body>
<script>
description("This tests keyboard events with KeyLocationCode argument.");

var lastKeyboardEvent;
var VK_SHIFT = 16;
var VK_CONTROL = 17;
var VK_MENU = 18;
var KEY_LOCATION_LEFT = 1;
var KEY_LOCATION_RIGHT = 2;

function recordKeyEvent(ev) {
    ev = ev || event;
    ev.keyCode = (ev.which || ev.keyCode);
    if (window.eventSender) {
        lastKeyboardEvent = ev;
    } else {
        debug('Type=' + ev.type + ',' +
              'keyCode=' + ev.keyCode + ',' +
              'ctrlKey=' + ev.ctrlKey + ',' +
              'shiftKey=' + ev.shiftKey + ',' +
              'altKey=' + ev.altKey + ',' +
              'metaKey=' + ev.metaKey + ',' +
              'location=' + ev.keyLocation);
    }
}

function testKeyEventWithLocation(evString, expectedKeyCode, expectedLocation) {
    eventSender.keyDown(evString, []);
    shouldBe("lastKeyboardEvent.type", '"keydown"');
    shouldEvaluateTo("lastKeyboardEvent.keyCode", expectedKeyCode);
    shouldEvaluateTo("lastKeyboardEvent.keyLocation", expectedLocation);
}

var textarea = document.createElement("textarea");
textarea.addEventListener("keydown", recordKeyEvent, false);
document.body.insertBefore(textarea, document.body.firstChild);
textarea.focus();

if (window.eventSender) {
    // location=0 indicates that we send events as standard keys.
    testKeyEventWithLocation("leftShift", VK_SHIFT, "KEY_LOCATION_LEFT");
    testKeyEventWithLocation("leftControl", VK_CONTROL, "KEY_LOCATION_LEFT");
    testKeyEventWithLocation("leftAlt", VK_MENU, "KEY_LOCATION_LEFT");

    testKeyEventWithLocation("rightShift", VK_SHIFT, "KEY_LOCATION_RIGHT");
    testKeyEventWithLocation("rightControl", VK_CONTROL, "KEY_LOCATION_RIGHT");
    testKeyEventWithLocation("rightAlt", VK_MENU, "KEY_LOCATION_RIGHT");
} else {
    debug("This test requires DumpRenderTree.");
}
</script>
<script src="../js/resources/js-test-post.js"></script>
</body>
</html>


text:
package org.drools.marshalling.impl;

import java.util.HashMap;
import java.util.Map;

import org.drools.common.BaseNode;
import org.drools.common.InternalRuleBase;
import org.drools.reteoo.LeftTupleSink;
import org.drools.reteoo.LeftTupleSource;
import org.drools.reteoo.ObjectSink;
import org.drools.reteoo.ObjectSource;
import org.drools.reteoo.ObjectTypeNode;
import org.drools.reteoo.PropagationQueuingNode;
import org.drools.reteoo.QueryRiaFixerNode;
import org.drools.reteoo.QueryTerminalNode;
import org.drools.reteoo.RuleTerminalNode;

public class RuleBaseNodes {
    public static Map<Integer, BaseNode> getNodeMap(InternalRuleBase ruleBase) {
        Map<Integer, BaseNode> nodes = new HashMap<Integer, BaseNode>();
        buildNodeMap( ruleBase, nodes );
        return nodes;
    }

    private static void buildNodeMap(InternalRuleBase ruleBase,
                                     Map<Integer, BaseNode> nodes) {
        for ( ObjectTypeNode sink : ruleBase.getRete().getObjectTypeNodes() ) {
            nodes.put( sink.getId(),
                       sink );
            addObjectSink( ruleBase,
                           sink,
                           nodes );
        }
    }

    private static void addObjectSink(InternalRuleBase ruleBase,
                                     ObjectSink sink,
                                     Map<Integer, BaseNode> nodes) {
        // we don't need to store alpha nodes, as they have no state to serialise
        if ( sink instanceof PropagationQueuingNode ) {
            nodes.put( sink.getId(),
                       ((BaseNode)sink) );
        }
        if ( sink instanceof LeftTupleSource ) {
            LeftTupleSource node = (LeftTupleSource) sink;
            for ( LeftTupleSink leftTupleSink : node.getSinkPropagator().getSinks() ) {
                addLeftTupleSink( ruleBase,
                                  leftTupleSink,
                                  nodes );
            }
        } else {
            ObjectSource node = ( ObjectSource ) sink;
            for ( ObjectSink objectSink : node.getSinkPropagator().getSinks() ) {
                addObjectSink( ruleBase,
                               objectSink,
                               nodes );
            }
        }
    }

    private static void addLeftTupleSink(InternalRuleBase ruleBase,
                                        LeftTupleSink sink,
                                        Map<Integer, BaseNode> nodes) {
        if ( sink instanceof QueryRiaFixerNode ) {
            nodes.put( sink.getId(),
                       (LeftTupleSource) sink );
            addLeftTupleSink( ruleBase,
                              ((QueryRiaFixerNode)sink).getBetaNode(),
                              nodes );
        } else if ( sink instanceof LeftTupleSource ) {
            nodes.put( sink.getId(),
                       (LeftTupleSource) sink );
            for ( LeftTupleSink leftTupleSink : ((LeftTupleSource) sink).getSinkPropagator().getSinks() ) {
                addLeftTupleSink( ruleBase,
                                  leftTupleSink,
                                  nodes );
            }
        } else if ( sink instanceof ObjectSource ) {
            // it may be a RIAN
            nodes.put( sink.getId(),
                       (ObjectSource) sink );
            for ( ObjectSink objectSink : ((ObjectSource)sink).getSinkPropagator().getSinks() ) {
                addObjectSink( ruleBase,
                               objectSink,
                               nodes );
            }
        } else if ( sink instanceof RuleTerminalNode ) {
            nodes.put( sink.getId(),
                       (RuleTerminalNode) sink );
        } else if ( sink instanceof QueryTerminalNode ) {
            nodes.put( sink.getId(),
                       (QueryTerminalNode) sink );
        }
    }
}


text:
$identify("org/mathdox/formulaeditor/modules/permutation1/permutation.js");

$require("org/mathdox/formulaeditor/parsing/openmath/OpenMathParser.js");
$require("org/mathdox/formulaeditor/parsing/expression/ExpressionContextParser.js");
$require("org/mathdox/formulaeditor/semantics/MultaryListOperation.js");

$main(function(){

  /**
   * Defines a semantic tree node that represents an absolute value.
   */
  org.mathdox.formulaeditor.semantics.Cycle =
    $extend(org.mathdox.formulaeditor.semantics.MultaryListOperation, {

      symbol : {

        mathml   : ["<mo>(</mo>","<mo>,</mo>","<mo>)</mo>"],
        onscreen : ["(",",",")"],
        openmath : "<OMS cd='permutation1' name='cycle'/>"

      },

      precedence : 0

    });

  /**
   * Defines a semantic tree node that represents an absolute value.
   */
  org.mathdox.formulaeditor.semantics.Permutation =
    $extend(org.mathdox.formulaeditor.semantics.MultaryOperation, {

      symbol : {

        mathml   : ["","",""],
        onscreen : ["","",""],
        openmath : "<OMS cd='permutation1' name='permutation'/>"

      },

      precedence : 0

    });

  /**
   * Extend the OpenMathParser object with parsing code for arith1.abs.
   */
  org.mathdox.formulaeditor.parsing.openmath.OpenMathParser =
    $extend(org.mathdox.formulaeditor.parsing.openmath.OpenMathParser, {

      /**
      * Returns a cycle object based on the OpenMath node.
      */
      handlePermutation1Cycle : function(node) {
        var operands = [];
        var result;
        var i;

        for (i=1; i<node.childNodes.length; i++) {
          operands.push(this.handle(node.childNodes.item(i)));
        }
        result = new org.mathdox.formulaeditor.semantics.Cycle();
        result.initialize.apply(result, operands);

        return result;
      },

      /**
      * Returns a permutation object based on the OpenMath node.
      */
      handlePermutation1Permutation : function(node) {
        var operands = [];
        var result;
        var i;

        for (i=1; i<node.childNodes.length; i++) {
          operands.push(this.handle(node.childNodes.item(i)));
        }
        result = new org.mathdox.formulaeditor.semantics.Permutation();
        result.initialize.apply(result, operands);

        return result;

      }

    });

  /**
   * Add the parsing code for permutations.
   */
  var semantics = org.mathdox.formulaeditor.semantics;
  var pG = new org.mathdox.parsing.ParserGenerator();

  org.mathdox.formulaeditor.parsing.expression.ExpressionContextParser.addFunction(
    function(context) { return {

        // expression160 = permutation | super.expression160
        expression160 : function() {
          var parent = arguments.callee.parent;
          pG.alternation(
            pG.rule("permutation"),
            parent.expression160).apply(this, arguments);
        },

        // permutation = "(" (omString | integer) ("," (omString | integer))+ ")"
        permutation :
          pG.transform(
            pG.repetitionplus(
              pG.concatenation(
                pG.literal("("),
                pG.alternation(
                  pG.rule("integer"),
                  pG.rule("omString")
                ),
                pG.repetitionplus(
                  pG.concatenation(
                    pG.literal(context.listSeparator),
                    pG.alternation(
                      pG.rule("integer"),
                      pG.rule("omString")
                    )
                  )
                ),
                pG.literal(")")
              )
            ),
            function(result) {
              var cycles = [];
              var entries;
              var i=0;
              var perm;
              while (i<result.length) {
                // result[i] = '('
                i++;

                entries = [];
                while (i<result.length && result[i] != ')') {
                  entries.push(result[i]);
                  i++;
                  // result[i] = ')' or ','
                  if (i<result.length && result[i] == context.listSeparator) {
                    i++;
                  }
                  // result[i] = ')' or result[i] = <entry>
                }
                // result[i] == ')'
                i++;

                var cycle = new semantics.Cycle();
                cycle.initialize.apply(cycle, entries);
                cycles.push(cycle);
              }

              perm = new semantics.Permutation();
              perm.initialize.apply(perm, cycles);
              return perm;
            }
          )
        };
      });

});


text:
class Check < ApplicationRecord
end


text:
layout: frontpage
header:
  image_fullwidth: header.jpg
widget1:
  title: "Getting Started"
  url: '/gettingStarted'
  image: 'https://simplecircuits.bingen.dev/assets/img/getstartph.png'
  text: 'Your first visit? Please take the guided tour :)'
widget2:
  title: "The theory behind"
  url: '/theory'
  image: 'https://simplecircuits.bingen.dev/assets/img/theoryph.png'
  text: "Trying to know why some things works and others not? I'll try to explain, but don't take me too seriously"
widget3:
  title: "Beyond the paper"
  url: '/beyond'
  image: 'https://simplecircuits.bingen.dev/assets/img/beyondph.png'
  text: "experiments that didn't fit here"
#
# Use the call for action to show a button on the frontpage
#
# To make internal links, just use a permalink like this
# url: /getting-started/
#
# To style the button in different colors, use no value
# to use the main color or success, alert or secondary.
# To change colors see sass/_01_settings_colors.scss
#
#callforaction:
#  url: https://tinyletter.com/feeling-responsive
#  text: Inform me about new updates and features ›
#  style: alert
permalink: /index.html
---


text:
class BatchPrintsController < ApplicationController
  skip_before_action :get_tcc
  before_action :check_permission

  def index

    authorize(Tcc, :show_scope?)
    @current_moodle_user = current_moodle_user
    @tcc_definition = TccDefinition.includes(:chapter_definitions).find(@tp.custom_params['tcc_definition'])

    tccList = Tcc.includes(:student, :orientador, :abstract, :chapters).
                  joins(:student).
                  joins(:orientador).
                  where(tcc_definition_id: @tcc_definition.id).
                  where.not(orientador: nil).
                  order('orientadors_tccs.name, people.name')

    show_graded_before = @tp.custom_params['show_graded_before']
    show_graded_before = show_graded_before.nil? ? '' : show_graded_before.gsub('\'', '')

    show_graded_after = @tp.custom_params['show_graded_after']
    show_graded_after = show_graded_after.nil? ? '': show_graded_after.gsub('\'', '')
    where = ''
    if  (!show_graded_before.empty? and !show_graded_after.empty? )
      where = "( grade_updated_at between ? and ? )"
      where = "grade_updated_at is null or #{where}"
      tccList = tccList.where(where, show_graded_after, show_graded_before)
    else
      if ( !show_graded_after.empty? )
        where += '( grade_updated_at > ?)'
        where = "grade_updated_at is null or #{where}"
        tccList = tccList.where(where, show_graded_after)
      elsif ( !show_graded_before.empty? )#or show_graded_after.empty?
        where += '( grade_updated_at < ? )'
        where = "grade_updated_at is null or #{where}"
        tccList = tccList.where(where, show_graded_before)
      end
    end

    tccs = policy_scope(tccList)
    @tccs = tccs
  end

  def print
    authorize(Tcc, :show_scope?)
    @tcc_definition = TccDefinition.includes(:chapter_definitions).find(@tp.custom_params['tcc_definition'])
    arr_moodle_ids = params[:moodle_ids].split(',')
    if arr_moodle_ids.size > 0
      BatchTccsWorker.perform_async(arr_moodle_ids, @tp.lis_person_name_full, @tp.lis_person_contact_email_primary,
                                    @tcc_definition.pdf_link_hours)
      flash[:success] = "A impressão será enviada por e-mail para: #{@tp.lis_person_name_full} - #{@tp.lis_person_contact_email_primary}"
    else
      flash[:alert] = "Deve haver ao menos um TCC selecionado para a impressão!"
    end
    redirect_to batch_select_path

  end

  protected

  def check_permission
    unless current_user.view_all? || current_user.instructor?
      raise Authentication::UnauthorizedError, t('cannot_access_page_without_enough_permission')
      redirect_user_to_start_page
    end
  end

end


text:
from distutils.core import setup, Extension

module1 = Extension('spi', sources = ['spi.c'])

setup (
    name = 'SPI-Py',
    author='Louis Thiery',
    url='https://github.com/lthiery/SPI-Py',
    download_url='https://github.com/lthiery/SPI-Py/archive/master.zip',
    version = '1.0',
    description = 'SPI-Py: Hardware SPI as a C Extension for Python',
    license='GPL-v2',
    platforms=['Linux'],
    ext_modules = [module1]
)


text:
import time
import RPi.GPIO as GPIO

#pin definitions
ledR = 2
ledG = 3
ledB = 5

#GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(ledR, GPIO.OUT)
GPIO.setup(ledG, GPIO.OUT)
GPIO.setup(ledB, GPIO.OUT)

#set initial LED states
GPIO.output(ledR, 1)
GPIO.output(ledG, 1)
GPIO.output(ledB, 1)

#main loop
try:
    while 1:
        tempStore = open("/sys/bus/w1/devices/28-0315902106ff/w1_slave")	#change this number to the Device ID of your sensor
        data = tempStore.read()
        tempStore.close()
        tempData = data.split("\n")[1].split(" ")[9]
        temperature = float(tempData[2:])
        temperature = temperature/1000
        print temperature

        if temperature < 20:	#change this value to adjust the 'too cold' threshold
            GPIO.output(ledR, 1)
            GPIO.output(ledG, 1)
            GPIO.output(ledB, 0)

        if temperature > 20 and temperature < 24:	#change these values to adjust the 'comfortable' range
            GPIO.output(ledR, 1)
            GPIO.output(ledG, 0)
            GPIO.output(ledB, 1)

        if temperature > 24:	#change this value to adjust the 'too hot' threshold
            GPIO.output(ledR, 0)
            GPIO.output(ledG, 1)
            GPIO.output(ledB, 1)

        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()
    print ("Program Exited Cleanly")


text:
require 'test_helper'

class PiesHelperTest < ActionView::TestCase
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

001package org.maltparser.parser.algorithm.covington;
002
003import org.maltparser.core.exception.MaltChainedException;
004import org.maltparser.core.feature.FeatureRegistry;
005import org.maltparser.core.feature.function.Function;
006import org.maltparser.parser.AbstractParserFactory;
007import org.maltparser.parser.AlgoritmInterface;
008import org.maltparser.parser.DependencyParserConfig;
009import org.maltparser.parser.ParserConfiguration;
010import org.maltparser.parser.ParserRegistry;
011/**
012 * @author Johan Hall
013 *
014 */
015public abstract class CovingtonFactory implements AbstractParserFactory {
016        protected final DependencyParserConfig manager;
017
018        public CovingtonFactory(DependencyParserConfig _manager) {
019                this.manager = _manager;
020        }
021
022        public ParserConfiguration makeParserConfiguration() throws MaltChainedException {
023                boolean allowRoot = (Boolean)manager.getOptionValue("covington", "allow_root");
024                boolean allowShift = (Boolean)manager.getOptionValue("covington", "allow_shift");
025                if (manager.isLoggerInfoEnabled()) {
026                        manager.logInfoMessage("  Parser configuration : Covington with allow_root="+allowRoot+" and allow_shift="+allowShift+"\n");
027                }
028                CovingtonConfig config = new CovingtonConfig(allowRoot, allowShift);
029                return config;
030        }
031
032        public Function makeFunction(String subFunctionName, FeatureRegistry registry) throws MaltChainedException {
033                AlgoritmInterface algorithm = ((ParserRegistry)registry).getAlgorithm();
034                return new CovingtonAddressFunction(subFunctionName, algorithm);
035        }
036}


text:
from unittest import TestCase

class YamlRulesTest(TestCase):

    def test_all_kinds(self):
        """
        Test that we've enumerated all the possible values for kind and
        kind_detail in the YAML files.
        """

        from vectordatasource.meta import find_yaml_path
        from vectordatasource.meta.kinds import parse_all_kinds
        import os.path

        yaml_path = find_yaml_path()
        sort_rank_path = os.path.join(
            os.path.split(yaml_path)[0], 'spreadsheets', 'sort_rank')

        # should be able to execute this without throwing an exception.
        all_kinds = parse_all_kinds(yaml_path, sort_rank_path, True)

        # and we should get some data back
        self.assertTrue(all_kinds)


text:
package edu.valelab.gaussianfit.spotoperations;

import ags.utils.KdTree;
import ags.utils.KdTree.Entry;
import ags.utils.KdTree.SqrEuclid;
import java.awt.geom.Point2D;
import java.util.List;

/**
 * Class that finds the closest by point in a point collection given a single point
 *
 * The method findKDWSE uses a kd tree approach based written by Rednaxela
 *
 *
 * @author nico
 */
public class NearestPoint2D {
   private final List<Point2D.Double> theList_;
   private final double maxDistance_;
   private final double maxDistanceSquared_;
   private KdTree<Integer> we_;

   //private final ArrayList<Point2D.Double> sortedByX_;
   //private final ArrayList<Point2D.Double> sortedByY_;

   public NearestPoint2D(List<Point2D.Double> unsorted, double maxDistance) {
      theList_ = unsorted;
      maxDistance_ = maxDistance;
      maxDistanceSquared_ = maxDistance * maxDistance;
   }

   /**
    *  method to find the nearest point in the collection of Points
    * Uses Squared Euclidian distance method from Rednaxela
    *
    * @param input - point for which we want to find the nearest neighbor
    * @return point found or null when it was farther away than the cutoff set
    * in the constructor
    */
   public Point2D.Double findKDWSE(Point2D.Double input) {
      // construct a new KD tree if needed
      if (we_ == null) {
         we_ = new SqrEuclid<Integer>(2, 50 * theList_.size());
         for (int i = 0; i < theList_.size(); i++) {
            Point2D.Double p = theList_.get(i);
            double[] point = {p.x, p.y};
            we_.addPoint(point, i);
         }
      }
      double[] testPoint = {input.x, input.y};
      List<Entry<Integer>> result = we_.nearestNeighbor(testPoint, 1, false);

      Integer index = result.get(0).value;
      double distance = result.get(0).distance;

      Point2D.Double ret = (Point2D.Double) theList_.get(index).clone();

      if (distance < maxDistanceSquared_)
         return ret;

      return null;
   }

   /**
    * Brute force method to find the nearest point in the collection of Points
    *
    * @param input - point for which we want to find the nearest neighbor
    * @return point found or null when it was farther away than the cutoff set
    * in the constructor
    */
   public Point2D.Double findBF(Point2D.Double input) {
      Point2D.Double closestPoint = input;
      double minDist2 = Double.MAX_VALUE;
      for (Point2D.Double p : theList_) {
         double dist2 = distance2(input, p);
         if (dist2 < minDist2) {
            minDist2 = dist2;
            closestPoint = p;
         }
      }

      double dist = Math.sqrt(distance2(input, closestPoint));
      if (dist < maxDistance_)
         return closestPoint;
      return null;
   }

   /**
    * Calculates the square of the distance between two points as
    * square(difference in x) + square (difference in y)
    *
    * @param p1 first point
    * @param p2 second point
    * @return square of the distance
    */
   public static double distance2(Point2D.Double p1, Point2D.Double p2) {
      double x = p1.getX() - p2.getX();
      double y = p1.getY() - p2.getY();
      return ( (x * x) + (y * y) );
   }

   /**
    * Calculates the orientation of these points with respect to each other.
    * Draw a circle with point 1 at the center, and p2 on the perimeter
    * Return the sine of the line connecting p1 and p2
    *
    * @param p1
    * @param p2
    * @return sine of the line connecting p1 and p2 in relation to their shared
    * coordinate system
    */
   public static double orientation(Point2D.Double p1, Point2D.Double p2) {
      double x = p2.getX() - p1.getX();
      double y = p2.getY() - p1.getY();
      double hyp = Math.sqrt( (x * x) + (y * y));

      if (hyp > 0.0) {
       return y /hyp;
      }

      return 0.0;
   }

}


text:
package bark

import (
	"os"
	"testing"

	cv "github.com/glycerine/goconvey/convey"
)

func TestProcessTable(t *testing.T) {

	cv.Convey("Sanity check ProcessTable(): ProcessTable should give us a map of length > 2", t, func() {
		cv.Convey("and should contain our and our parents pid", func() {
			ptab := *ProcessTable()
			me := os.Getpid()
			par := os.Getppid()

			_, meFound := ptab[me]
			_, parFound := ptab[par]

			cv.So(len(ptab), cv.ShouldBeGreaterThan, 2)
			cv.So(meFound, cv.ShouldEqual, true)
			cv.So(parFound, cv.ShouldEqual, true)

			Q("Sysname = '%s'\n", Sysname)
			Q("ptab is: %#v\n", ptab)
		})
	})
}


text:
<?php
/*
  Template Name: About Me Template
 */
get_header();
?>

<?php echo get_template_part('parts/content', 'banner'); ?>

    <?php while (have_posts()) : the_post(); ?>

                <img src="<?php echo get_template_directory_uri(); ?>/img/svg/davidlogo.svg" alt="David Cullimore Photography">

<?php the_field('about_title'); ?>

                    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="svg-triangle-big">
                        <defs>
                            <pattern id="img1" patternUnits="userSpaceOnUse" width="200" height="200">
                                <image xlink:href="<?php the_field('profile_picture'); ?>" x="0" y="0" width="200" height="200" />
                            </pattern>
                        </defs>
                        <polygon points="100,175 0,0 200,0" fill="url(#img1)"/>
                    </svg>

Hello, I'm Dave!

                <?php the_field('content_1'); ?>

                <?php the_field('content_2'); ?>

        <?php
    endwhile;
    rewind_posts();
    ?>

<?php echo get_template_part('parts/content', 'get-in-touch-cta'); ?>
<?php get_footer(); ?>


text:
import React, { Component } from 'react'
import { propType } from 'v2/util/inlinedGraphqlAnywhere'
import styled from 'styled-components'

import Box from 'v2/components/UI/Box'
import Text from 'v2/components/UI/Text'
import NotificationObjectLink from 'v2/components/NotificationsDropdown/components/Notification/components/NotificationObjectLink'

import notificationSentenceFragment from 'v2/components/NotificationsDropdown/components/Notification/fragments/notificationSentence'

const RelativeTime = styled(Text).attrs({
  f: 0,
  color: 'gray.medium',
  mt: 2,
})`
  text-transform: uppercase;
`

const Label = styled(Text).attrs({
  f: 1,
  display: 'inline',
})``

const Container = styled(Box).attrs({
  my: 3,
})`
  ${x =>
    x.isUnread &&
    `
    border-left: 2px solid ${x.theme.colors.state.alert};
    padding-left: ${x.theme.space[4]};
  `}
`

export default class Notification extends Component {
  static propTypes = {
    notification: propType(notificationSentenceFragment).isRequired,
  }

  render() {
    const {
      notification: {
        is_read,
        owner,
        action,
        item,
        connector,
        target,
        created_at,
        item_title,
      },
    } = this.props

    return (
      <Container my={3} pr={6} isUnread={!is_read}>

          <NotificationObjectLink obj={owner} />

          {item.__typename === 'Comment' && (

                {action === 'commented on'
                  ? ' said '
                  : ' mentioned you in a comment: '}
                "

                "{action === 'commented on' && ' on '}

              {action === 'commented on' && (
                <NotificationObjectLink obj={target} />
              )}

          )}

          {item.__typename !== 'Comment' && (

              {` ${action} `}

              <NotificationObjectLink obj={item} label={item_title} />

              {connector && {` ${connector} `}}

              {target && <NotificationObjectLink obj={target} />}

          )}

        <RelativeTime>{created_at}</RelativeTime>
      </Container>
    )
  }
}


text:
namespace MediatR.Examples.StructureMap.WebAPI.Areas.HelpPage.ModelDescriptions
{
    public class CollectionModelDescription : ModelDescription
    {
        public ModelDescription ElementDescription { get; set; }
    }
}


text:
<?php

namespace Dan\CommonBundle\Test;

use Behat\Mink\Driver\Selenium2Driver;
use Behat\Mink\Session;
use Behat\Mink\Mink;
use Behat\Mink\Selector\CssSelector;
use Behat\Mink\Selector\SelectorsHandler;

use Dan\CommonBundle\Test\Exception\ElementNotFoundException;

class MinkTestCase extends WebTestCase
{
    protected $webDir;
    protected $baseUrl;

    protected function getFixturesToLoad()
    {
        return array();
    }

    public function setUp()
    {
        parent::setUp();
        $this->webDir = $this->getContainer()->get('kernel')->getRootDir().'/../web';
        $this->baseUrl = $this->getContainer()->getParameter('base_url');
    }

    protected function getMinkSession($driver = 'firefox')
    {
        $selector = new CssSelector();
        $handler  = new SelectorsHandler(array(
            'css' => $selector
        ));
        switch ($driver) {
            case 'phantomjs':
            case 'firefox':
                $driver = new Selenium2Driver($driver);
                break;

            case 'symfony':
                $driver = new BrowserKitDriver($this->createClient());
                break;

            default:
                throw new \Exception("I can't configure a session for $driver");
                break;
        }

        $session = new Session($driver, $handler);
        $session->start();
        $session->resizeWindow(1280, 960);

        return $session;
    }

    public function setBaseUrl($url)
    {
        $this->baseUrl = $url;
        return $this;
    }

    public function getBaseUrl($default='')
    {
        if ($this->baseUrl) {
            return $this->baseUrl;
        }
        return $default;
    }

    public function visit($session, $url)
    {
        $session->visit($this->getBaseUrl().$url);
    }

    public function getScreenshot($session = null)
    {
        if (!$session) {
            $session = $this->session;
        }
        $content = $session->getScreenshot();
        $now = new \DateTime();
        return $this->saveContent($now->format('Y-m-d_H.i.s').'.png', $content);
    }

    public function getPage($session = null)
    {
        if (!$session) {
            $session = $this->session;
        }
        $content = $session->getPage()->getContent();
        $now = new \DateTime();
        return $this->saveContent($now->format('Y-m-d_H.i.s').'.html', $content);
    }

    private function saveContent($filename, $content)
    {
        $dir = $this->webDir.'/media/test';
        if (!file_exists($dir)) {
            mkdir($dir, 0777);
        }
        file_put_contents($dir.'/'.$filename, $content);
        return $this->getBaseUrl().'/media/test/'.$filename;
    }

    public function find(Session $session, $selector, $el=null)
    {
        try {
            $el = $this->checkFind($session, $selector, $el);
        } catch (ElementNotFoundException $e ) {
            $this->throwElementNotFoundException($session, $selector);
        }
        return $el->find('css', $selector);
    }

    public function findAll($session, $selector, $el=null)
    {
        try {
            $el = $this->checkFind($session, $selector, $el);
        } catch (ElementNotFoundException $e ) {}
        return $el->findAll('css', $selector);
    }

    public function checkFind($session, $selector, $el=null)
    {
        if (!$el) {
            $el = $session->getPage();
        }
        if (!$el->has('css', $selector)) {
            throw new ElementNotFoundException('element "'.$selector.'" not found ');
        }

        return $el;
    }

    public function throwElementNotFoundException($session, $selector=null)
    {
        $url = $this->getScreenshot($session);
        $page = $this->getPage($session);
        if ($selector) {
            $selector = '"'.$selector.'" ';
        }
        throw new ElementNotFoundException('element '.$selector.'not found '. $url.' '. $page);
    }

    public function close(Session $session) {
        $session->stop();
    }

    public function waitFor(Session $session, $selector, $timeout=30)
    {
        $session->wait($timeout * 1000, "$('".$selector."').length > 0");
        return $this->find($session, $selector);
    }

    public function waitIsVisible($el)
    {
        $time = time();
        while (!$el->isVisible()) {
            if ($time+10<time()) {
                throw new \Exception;('the element wont be visible');
            }
            sleep(1);
        }
        return $el;
    }
}


text:
package com.itellity.sys.io.file;

import com.itellity.sys.util.StringUtilities;

import junit.framework.TestCase;

public class FileUploadServiceTest extends TestCase {

	public void testEnsureValidFileName() {
		String fileNameInput = StringUtilities.normalizeUriPart("http://maps.google.com/maps?q=4711+Quebec+Street+Northwest,+Washington,+DC,+United+States&hl=en&ll=38.938482,-77.09336&spn=0.009747,0.019827&sll=37.0625,-95.677068&sspn=40.545434,81.210938&oq=4711+Quebec+Street,+Was&hnear=4711+Quebec+St+NW,+Washington,+District+of+Columbia+20016&t=m&z=16&iwloc=A");
		String s = new FileUploadService().ensureValidFileName(fileNameInput);
		assertTrue(s.length() < 256);
	}

}


text:
package com.hortonworks.streamline.streams.layout.component.rule.expression;

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

/**
 * Projection of fields in a rule
 */
public class Projection implements Serializable {
    private final List<Expression> expressions = new ArrayList<>();

    public Projection() {
    }

    public Projection(List<? extends Expression> expressions) {
        this.expressions.addAll(expressions);
    }

    public List<Expression> getExpressions() {
        return expressions;
    }

    public void setExpressions(List<? extends Expression> projectionExpressions) {
        this.expressions.addAll(projectionExpressions);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Projection that = (Projection) o;

        return expressions != null ? expressions.equals(that.expressions) : that.expressions == null;

    }

    @Override
    public int hashCode() {
        return expressions != null ? expressions.hashCode() : 0;
    }

    @Override
    public String toString() {
        return "Projection{" +
                "expressions=" + expressions +
                '}';
    }
}


text:
package com.thoughtworks.go.server.service.datasharing;

import com.thoughtworks.go.domain.UsageStatisticsReporting;
import com.thoughtworks.go.server.cache.CacheKeyGenerator;
import com.thoughtworks.go.server.cache.GoCache;
import com.thoughtworks.go.server.service.result.HttpLocalizedOperationResult;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.thoughtworks.go.server.dao.*;

import java.sql.Timestamp;

import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
        "classpath:/applicationContext-global.xml",
        "classpath:/applicationContext-dataLocalAccess.xml",
        "classpath:/testPropertyConfigurer.xml",
        "classpath:/spring-all-servlet.xml",
})
public class DataSharingUsageStatisticsReportingServiceIntegrationTest {
    @Autowired
    private DataSharingUsageStatisticsReportingService dataSharingUsageStatisticsReportingService;
    @Autowired
    private DataSharingSettingsService dataSharingSettingsService;
    @Autowired
    private UsageStatisticsReportingSqlMapDao usageStatisticsReportingSqlMapDao;
    @Autowired
    private DatabaseAccessHelper dbHelper;
    @Autowired
    private GoCache goCache;

    private CacheKeyGenerator cacheKeyGenerator = new CacheKeyGenerator(UsageStatisticsReportingSqlMapDao.class);

    @Before
    public void setup() throws Exception {
        dbHelper.onSetUp();
        dataSharingUsageStatisticsReportingService.initialize();
        dataSharingSettingsService.initialize();
    }

    @After
    public void teardown() throws Exception {
        dbHelper.onTearDown();
        goCache.remove(cacheKey());
    }

    @Test
    public void shouldInitializeGoStatsReportingOnFirstStartup() throws Exception {
        dbHelper.onTearDown();//to start on a clean slate
        goCache.remove(cacheKey());

        assertNull(usageStatisticsReportingSqlMapDao.load());
        dataSharingUsageStatisticsReportingService.initialize();
        UsageStatisticsReporting usageStatisticsReporting = usageStatisticsReportingSqlMapDao.load();
        assertNotNull(usageStatisticsReporting);
        assertNotNull(usageStatisticsReporting.getServerId());
        assertThat(usageStatisticsReporting.lastReportedAt(), is(new Timestamp(0)));
    }

    @Test
    public void shouldNotUpdateServerIdOfGoStatsReportingOnSubsequentStartups() throws Exception {
        dbHelper.onTearDown();//to start on a clean slate
        goCache.remove(cacheKey());

        assertNull(usageStatisticsReportingSqlMapDao.load());
        dataSharingUsageStatisticsReportingService.initialize();
        UsageStatisticsReporting saved = usageStatisticsReportingSqlMapDao.load();
        assertNotNull(saved);
        dataSharingUsageStatisticsReportingService.initialize();
        UsageStatisticsReporting loaded = usageStatisticsReportingSqlMapDao.load();
        assertThat(saved.getServerId(), is(loaded.getServerId()));
    }

    @Test
    public void shouldUpdateUsageStatisticsReporting() {
        UsageStatisticsReporting existing = dataSharingUsageStatisticsReportingService.get();
        assertNotNull(existing);
        Timestamp existingReportedTime = existing.lastReportedAt();
        assertNotNull(existingReportedTime);
        dataSharingUsageStatisticsReportingService.startReporting(new HttpLocalizedOperationResult());

        HttpLocalizedOperationResult result = new HttpLocalizedOperationResult();
        dataSharingUsageStatisticsReportingService.completeReporting(result);
        assertTrue(result.isSuccessful());

        UsageStatisticsReporting loaded = dataSharingUsageStatisticsReportingService.get();

        assertThat(loaded.lastReportedAt().getTime(), greaterThan(existingReportedTime.getTime()));
    }

    private String cacheKey() {
        return cacheKeyGenerator.generate("dataSharing_reporting");
    }
}


text:
<!DOCTYPE html>

            E

                        e-Cards — see CDC Health-e-Cards

                        E. coli Infection [Escherichia coli Infection]

                        EAIPP (Etiologic Agent Import Permit Program)

                        Ear Infection [Otitis Media]

                        Early Hearing Detection and Intervention (EHDI) — see Hearing, Early Detection & Intervention

                        Earthquakes

                        Eastern Equine Encephalitis (EEE)

                        Ebola Hemorrhagic Fever (Ebola HF)

                        Ebola HF (Ebola Hemorrhagic Fever)

                        EBV Infection (Epstein-Barr Virus Infection)

                        Echinococcosis

                        Education

                        Educational, ABC's to Public Health — see Laboratory Education, ABC's

                        EEE (Eastern Equine Encephalitis)

                        EGAPP (Evaluation of Genomic Applications in Practice and Prevention)

                        EHDI (Early Hearing Detection and Intervention)

                        EHR (Electronic Health Records)

                        Ehrlichiosis, Human

                        EID Journal (Emerging Infectious Diseases Journal)

                        EIP (Emerging Infections Programs)

                        EIS (Epidemic Intelligence Service)

                        Elder Maltreatment

                        Electric and Magnetic Fields (EMF)

                        Electrical Safety

                        Electronic Health Records (EHR) — see Meaningful Use

                        Elephantiasis — see Lymphatic Filariasis

                        Emergency Medical Services Workers (EMS)

                        see also Emergency Responders

                        see also Healthcare Workers

                        Emergency Preparedness & Response

                        Emergency Preparedness (Vaccine Safety)

                        Emergency Responders

                        see also Emergency Medical Services Workers (EMS)

                        see also Fire Fighters

                        Emergency Sanitation & Hygiene

                        Emergency Water Treatment — see Water Treatment, Emergency

                        Emerging Infections Programs (EIP)

                        Emerging Infectious Diseases

                        Emerging Infectious Diseases Journal (EID Journal)

                        EMF (Electric and Magnetic Fields)

                        EMS (Emergency Medical Services Workers)

                        Engineering Controls

                        see also Engineering Controls

                        see also Prevention Through Design (Workplace Safety and Health) (PTD)

                        Entamoeba histolytica infection — see Amebiasis, Intestinal

                        Enteric Diseases from Animals — see Gastrointestinal Diseases from Animals

                        Enterobius vermicularis Infection — see Pinworm Infection

                        Enterovirus Infections (Non-Polio) — see Non-Polio Enterovirus Infections

                        Environmental Chemicals, National Report on Human Exposure to — see National Report on Human Exposure to Environmental Chemicals

                        Environmental Health

                        Environmental Health Laboratory — see National Report on Human Exposure to Environmental Chemicals

                        Epi Info™

                        Epidemic Intelligence Service (EIS)

                        Epidemiology & Prevention of Vaccine-Preventable Diseases (Pink Book)

                        Epidemiology Elective Program for Senior Medical and Veterinary Students

                        Epilepsy

                        Epstein-Barr Virus Infection (EBV Infection)

                        Ergonomic and Musculoskeletal Disorders

                        Escherichia coli Infection — see E. coli Infection

                        Esophageal Candidiasis — see Thrush

                        Ethics Program Activity, CDC and ATSDR

                        Ethics, Public Health — see Public Health Ethics

                        Ethylene Glycol

                        Ethylene Oxide

                        Etiologic Agent Import Permit Program (EAIPP)

                        Evaluation of Genomic Applications in Practice and Prevention (EGAPP)

                        Evaluations with Nonrandomized Designs, Transparent Reporting of — see Transparent Reporting of Evaluations with Nonrandomized Designs

                        Exercise — see Physical Activity

                        Exercise for Seniors — see Physical Activity for Seniors

                        Expectancy, Life — see Life Expectancy

                        Exposomes

                        see also Genomics and Disease Prevention

                        see also Genomics and Public Health

                        Exserohilum rostratum (Other Pathogenic Fungi)

                        see also Fungal diseases [Mycotic diseases]

                        Extensively Drug-Resistant TB (XDR TB)

                        External Quality Assessment

                        Extramural Research — see Public Health Research

                        Extreme Cold [Hypothermia]

                        Extreme Heat [Hyperthermia]

                        Extreme Weather Conditions

                        Eye and Vision Health

                        Eye Safety

Page last reviewed:

Page last updated: Mar 19, 2014

Content source: Centers for Disease Control and Prevention

Page maintained by: Office of the Associate Director for Communication, Division of News and Electronic Media


text:
package com.netflix.simianarmy.aws.janitor.crawler.edda;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.netflix.simianarmy.Resource;
import com.netflix.simianarmy.aws.AWSResource;
import com.netflix.simianarmy.aws.AWSResourceType;
import com.netflix.simianarmy.client.edda.EddaClient;
import com.netflix.simianarmy.janitor.JanitorCrawler;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.codehaus.jackson.JsonNode;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.Date;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The crawler to crawl AWS auto scaling groups for janitor monkey using Edda.
 */
public class EddaASGJanitorCrawler implements JanitorCrawler {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(EddaASGJanitorCrawler.class);

    /** The name representing the additional field name of instance ids. */
    public static final String ASG_FIELD_INSTANCES = "INSTANCES";

    /** The name representing the additional field name of max ASG size. */
    public static final String ASG_FIELD_MAX_SIZE = "MAX_SIZE";

    /** The name representing the additional field name of ELB names. */
    public static final String ASG_FIELD_ELBS = "ELBS";

    /** The name representing the additional field name of launch configuration name. */
    public static final String ASG_FIELD_LC_NAME = "LAUNCH_CONFIGURATION_NAME";

    /** The name representing the additional field name of launch configuration creation time. */
    public static final String ASG_FIELD_LC_CREATION_TIME = "LAUNCH_CONFIGURATION_CREATION_TIME";

    /** The name representing the additional field name of ASG suspension time from ELB. */
    public static final String ASG_FIELD_SUSPENSION_TIME = "ASG_SUSPENSION_TIME";

    /** The name representing the additional field name of ASG's last change/activity time. */
    public static final String ASG_FIELD_LAST_CHANGE_TIME = "ASG_LAST_CHANGE_TIME";

    /** The regular expression patter below is for the termination reason added by AWS when
     * an ASG is suspended from ELB's traffic.
     */
    private static final Pattern SUSPENSION_REASON_PATTERN =
            Pattern.compile("User suspended at (\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}).*");

    private final EddaClient eddaClient;
    private final List<String> regions = Lists.newArrayList();
    private final Map<String, Map<String, Long>> regionToAsgToLastChangeTime = Maps.newHashMap();

    /**
     * Instantiates a new basic ASG crawler.
     * @param eddaClient
     *            the Edda client
     * @param regions
     *            the regions the crawler will crawl resources for
     */
    public EddaASGJanitorCrawler(EddaClient eddaClient, String... regions) {
        Validate.notNull(eddaClient);
        this.eddaClient = eddaClient;
        Validate.notNull(regions);
        for (String region : regions) {
            this.regions.add(region);
        }
    }

    @Override
    public EnumSet<?> resourceTypes() {
        return EnumSet.of(AWSResourceType.ASG);
    }

    @Override
    public List<Resource> resources(Enum resourceType) {
        if ("ASG".equals(resourceType.name())) {
            return getASGResources();
        }
        return Collections.emptyList();
    }

    @Override
    public List<Resource> resources(String... asgNames) {
        return getASGResources(asgNames);
    }

    @Override
    public String getOwnerEmailForResource(Resource resource) {
        return null;
    }

    private List<Resource> getASGResources(String... asgNames) {
        refreshAsgLastChangeTime();
        List<Resource> resources = Lists.newArrayList();
        for (String region : regions) {
            resources.addAll(getASGResourcesInRegion(region, asgNames));
        }
        return resources;
    }

    private List<Resource> getASGResourcesInRegion(String region, String... asgNames) {
        String url = eddaClient.getBaseUrl(region) + "/aws/autoScalingGroups;";
        if (asgNames != null && asgNames.length != 0) {
            url += StringUtils.join(asgNames, ',');
            LOGGER.info(String.format("Getting ASGs in region %s for %d ids", region, asgNames.length));
        } else {
            LOGGER.info(String.format("Getting all ASGs in region %s", region));
        }
        url += ";_expand:(autoScalingGroupName,createdTime,maxSize,suspendedProcesses:(processName,suspensionReason),"
               + "tags:(key,value),instances:(instanceId),loadBalancerNames,launchConfigurationName)";

        JsonNode jsonNode = null;
        try {
            jsonNode = eddaClient.getJsonNodeFromUrl(url);
        } catch (Exception e) {
            LOGGER.error(String.format(
                    "Failed to get Jason node from edda for ASGs in region %s.", region), e);
        }

        if (jsonNode == null || !jsonNode.isArray()) {
            throw new RuntimeException(String.format("Failed to get valid document from %s, got: %s", url, jsonNode));
        }

        Map<String, Long> lcNameToCreationTime = getLaunchConfigCreationTimes(region);
        List<Resource> resources = Lists.newArrayList();
        for (Iterator<JsonNode> it = jsonNode.getElements(); it.hasNext();) {
            resources.add(parseJsonElementToresource(region, it.next(), lcNameToCreationTime));
        }
        return resources;
    }

    private Resource parseJsonElementToresource(String region, JsonNode jsonNode
            , Map<String, Long> lcNameToCreationTime) {
        Validate.notNull(jsonNode);

        String asgName = jsonNode.get("autoScalingGroupName").getTextValue();
        long createdTime = jsonNode.get("createdTime").getLongValue();

        Resource resource = new AWSResource().withId(asgName).withRegion(region)
                .withResourceType(AWSResourceType.ASG)
                .withLaunchTime(new Date(createdTime));

        JsonNode tags = jsonNode.get("tags");
        if (tags == null || !tags.isArray() || tags.size() == 0) {
            LOGGER.debug(String.format("No tags is found for %s", resource.getId()));
        } else {
            for (Iterator<JsonNode> it = tags.getElements(); it.hasNext();) {
                JsonNode tag = it.next();
                String key = tag.get("key").getTextValue();
                String value = tag.get("value").getTextValue();
                resource.setTag(key, value);
            }
        }

        String owner = getOwnerEmailForResource(resource);
        if (owner != null) {
            resource.setOwnerEmail(owner);
        }
        JsonNode maxSize = jsonNode.get("maxSize");
        if (maxSize != null) {
            resource.setAdditionalField(ASG_FIELD_MAX_SIZE, String.valueOf(maxSize.getIntValue()));
        }
        // Adds instances and ELBs as additional fields.
        JsonNode instances = jsonNode.get("instances");
        resource.setDescription(String.format("%d instances", instances.size()));
        List<String> instanceIds = Lists.newArrayList();
        for (Iterator<JsonNode> it = instances.getElements(); it.hasNext();) {
            instanceIds.add(it.next().get("instanceId").getTextValue());
        }
        resource.setAdditionalField(ASG_FIELD_INSTANCES, StringUtils.join(instanceIds, ","));
        JsonNode elbs = jsonNode.get("loadBalancerNames");
        List<String> elbNames = Lists.newArrayList();
        for (Iterator<JsonNode> it = elbs.getElements(); it.hasNext();) {
            elbNames.add(it.next().getTextValue());
        }
        resource.setAdditionalField(ASG_FIELD_ELBS, StringUtils.join(elbNames, ","));

        JsonNode lc = jsonNode.get("launchConfigurationName");
        if (lc != null) {
            String lcName = lc.getTextValue();
            Long lcCreationTime = lcNameToCreationTime.get(lcName);
            resource.setAdditionalField(ASG_FIELD_LC_NAME, lcName);
            if (lcCreationTime != null) {
                resource.setAdditionalField(ASG_FIELD_LC_CREATION_TIME, String.valueOf(lcCreationTime));
            }
        }
        // sets the field for the time when the ASG's traffic is suspended from ELB
        JsonNode suspendedProcesses = jsonNode.get("suspendedProcesses");
        for (Iterator<JsonNode> it = suspendedProcesses.getElements(); it.hasNext();) {
            JsonNode sp = it.next();
            if ("AddToLoadBalancer".equals(sp.get("processName").getTextValue())) {
                String suspensionTime = getSuspensionTimeString(sp.get("suspensionReason").getTextValue());
                if (suspensionTime != null) {
                    LOGGER.info(String.format("Suspension time of ASG %s is %s",
                            asgName, suspensionTime));
                    resource.setAdditionalField(ASG_FIELD_SUSPENSION_TIME, suspensionTime);
                    break;
                }
            }
        }
        Long lastChangeTime = regionToAsgToLastChangeTime.get(region).get(asgName);
        if (lastChangeTime != null) {
            resource.setAdditionalField(ASG_FIELD_LAST_CHANGE_TIME, String.valueOf(lastChangeTime));
        }
        return resource;

    }

    private Map<String, Long> getLaunchConfigCreationTimes(String region) {
        LOGGER.info(String.format("Getting launch configuration creation times in region %s", region));

        String url = eddaClient.getBaseUrl(region)
                + "/aws/launchConfigurations;_expand:(launchConfigurationName,createdTime)";
        JsonNode jsonNode = null;
        try {
            jsonNode = eddaClient.getJsonNodeFromUrl(url);
        } catch (Exception e) {
            LOGGER.error(String.format(
                    "Failed to get Jason node from edda for lc creation times in region %s.", region), e);
        }

        if (jsonNode == null || !jsonNode.isArray()) {
            throw new RuntimeException(String.format("Failed to get valid document from %s, got: %s", url, jsonNode));
        }

        Map<String, Long> nameToCreationTime = Maps.newHashMap();
        for (Iterator<JsonNode> it = jsonNode.getElements(); it.hasNext();) {
            JsonNode elem = it.next();
            nameToCreationTime.put(elem.get("launchConfigurationName").getTextValue(),
                    elem.get("createdTime").getLongValue());
        }
        return nameToCreationTime;
    }

    private String getSuspensionTimeString(String suspensionReason) {
        if (suspensionReason == null) {
            return null;
        }
        Matcher matcher = SUSPENSION_REASON_PATTERN.matcher(suspensionReason);
        if (matcher.matches()) {
            return matcher.group(1);
        }
        return null;
    }

    private void refreshAsgLastChangeTime() {
        regionToAsgToLastChangeTime.clear();
        for (String region : regions) {
            LOGGER.info(String.format("Getting ASG last change time in region %s", region));
            Map<String, Long> asgToLastChangeTime = regionToAsgToLastChangeTime.get(region);
            if (asgToLastChangeTime == null) {
                asgToLastChangeTime = Maps.newHashMap();
                regionToAsgToLastChangeTime.put(region, asgToLastChangeTime);
            }
            String url = eddaClient.getBaseUrl(region) + "/aws/autoScalingGroups;"
                    + ";_expand;_meta:(stime,data:(autoScalingGroupName))";

            JsonNode jsonNode = null;
            try {
                jsonNode = eddaClient.getJsonNodeFromUrl(url);
            } catch (Exception e) {
                LOGGER.error(String.format(
                        "Failed to get Jason node from edda for ASG last change time in region %s.", region), e);
            }

            if (jsonNode == null || !jsonNode.isArray()) {
                throw new RuntimeException(String.format("Failed to get valid document from %s, got: %s",
                        url, jsonNode));
            }

            for (Iterator<JsonNode> it = jsonNode.getElements(); it.hasNext();) {
                JsonNode asg = it.next();
                String asgName = asg.get("data").get("autoScalingGroupName").getTextValue();
                Long lastChangeTime = asg.get("stime").asLong();
                LOGGER.debug(String.format("The last change time of ASG %s is %s", asgName,
                        new DateTime(lastChangeTime)));
                asgToLastChangeTime.put(asgName, lastChangeTime);
            }
        }
    }

}


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BitArray64
{
    public class BitArray64: IEnumerable<int>
    {
        private int[] bitArray = new int[64];
        private ulong number;

        public BitArray64(ulong number)
        {
            this.number = number;
            for (int i = 0; i < 64; i++)
            {
                bitArray[i] = (int)(number % 2);
                number /= 2;
            }
        }

        public ulong Number
        {
            get { return this.number; }
        }

        public IEnumerator<int> GetEnumerator()
        {
            for (int i = 63; i >= 0; i--)
            {
                yield return this.bitArray[i];
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public override bool Equals(object obj)
        {
            BitArray64 bitArray = obj as BitArray64;

            if ((object)bitArray == null)
            {
                return false;
            }

            if (Object.Equals(this.number, bitArray.number))
            {
                return true;
            }

            return false;
        }

        public static bool operator ==(BitArray64 firstNumber,
                                  BitArray64 secondNumber)
        {
            return BitArray64.Equals(firstNumber, secondNumber);
        }

        public static bool operator !=(BitArray64 firstNumber,
                           BitArray64 secondNumber)
        {
            return !(BitArray64.Equals(firstNumber, secondNumber));
        }

        public int this[int key]
        {
            get { return this.bitArray[key]; }
            set
            {
                if (value == 1 || value == 0)
                {
                    this.bitArray[key] = value;
                    ChangeNumber();
                }
                else
                {
                    throw new ArgumentException("Bits can be only 1 or 0");
                }
            }
        }

        public override int GetHashCode()
        {
            return this.number.GetHashCode() ^ this.bitArray.GetHashCode();
        }

        private void ChangeNumber()
        {
            this.number = 0;
            for (int i = 0; i < 64; i++)
            {
                this.number += (ulong)(this.bitArray[i] << i);
            }
        }
    }
}


text:
The plugin provides nothing but syntax highlighting at the moment.

## Installation

To install plugin open `Settings > Plugins > Browse repositories`, and search for TOML.

## Contributing

See [Contributing](https://github.com/intellij-rust/intellij-rust/blob/master/CONTRIBUTING.md) in the IntelliJ-Rust plugin.

## Extending

It's possible to extend TOML support from other plugins:

  * The PSI structure is expected remain backwards compatible.
  * `TomlKey` and `TomlValue` are `ContributedReferenceHost`s, so
    it's possible to inject references into them from third-party plugins,
    and provide completion and goto definition.

See https://github.com/intellij-rust/intellij-rust/pull/1982/ for an example.


text:
/**
 * @fileoverview Disallows or enforces spaces inside computed properties.
 * @author Jamund Ferguson
 */
"use strict";

const astUtils = require("../ast-utils");

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

module.exports = {
    meta: {
        docs: {
            description: "enforce consistent spacing inside computed property brackets",
            category: "Stylistic Issues",
            recommended: false
        },

        fixable: "whitespace",

        schema: [
            {
                enum: ["always", "never"]
            }
        ]
    },

    create(context) {
        const sourceCode = context.getSourceCode();
        const propertyNameMustBeSpaced = context.options[0] === "always"; // default is "never"

        //--------------------------------------------------------------------------
        // Helpers
        //--------------------------------------------------------------------------

        /**
         * Reports that there shouldn't be a space after the first token
         * @param {ASTNode} node - The node to report in the event of an error.
         * @param {Token} token - The token to use for the report.
         * @param {Token} tokenAfter - The token after `token`.
         * @returns {void}
         */
        function reportNoBeginningSpace(node, token, tokenAfter) {
            context.report({
                node,
                loc: token.loc.start,
                message: "There should be no space after '{{tokenValue}}'.",
                data: {
                    tokenValue: token.value
                },
                fix(fixer) {
                    return fixer.removeRange([token.range[1], tokenAfter.range[0]]);
                }
            });
        }

        /**
         * Reports that there shouldn't be a space before the last token
         * @param {ASTNode} node - The node to report in the event of an error.
         * @param {Token} token - The token to use for the report.
         * @param {Token} tokenBefore - The token before `token`.
         * @returns {void}
         */
        function reportNoEndingSpace(node, token, tokenBefore) {
            context.report({
                node,
                loc: token.loc.start,
                message: "There should be no space before '{{tokenValue}}'.",
                data: {
                    tokenValue: token.value
                },
                fix(fixer) {
                    return fixer.removeRange([tokenBefore.range[1], token.range[0]]);
                }
            });
        }

        /**
         * Reports that there should be a space after the first token
         * @param {ASTNode} node - The node to report in the event of an error.
         * @param {Token} token - The token to use for the report.
         * @returns {void}
         */
        function reportRequiredBeginningSpace(node, token) {
            context.report({
                node,
                loc: token.loc.start,
                message: "A space is required after '{{tokenValue}}'.",
                data: {
                    tokenValue: token.value
                },
                fix(fixer) {
                    return fixer.insertTextAfter(token, " ");
                }
            });
        }

        /**
         * Reports that there should be a space before the last token
         * @param {ASTNode} node - The node to report in the event of an error.
         * @param {Token} token - The token to use for the report.
         * @returns {void}
         */
        function reportRequiredEndingSpace(node, token) {
            context.report({
                node,
                loc: token.loc.start,
                message: "A space is required before '{{tokenValue}}'.",
                data: {
                    tokenValue: token.value
                },
                fix(fixer) {
                    return fixer.insertTextBefore(token, " ");
                }
            });
        }

        /**
         * Returns a function that checks the spacing of a node on the property name
         * that was passed in.
         * @param {string} propertyName The property on the node to check for spacing
         * @returns {Function} A function that will check spacing on a node
         */
        function checkSpacing(propertyName) {
            return function(node) {
                if (!node.computed) {
                    return;
                }

                const property = node[propertyName];

                const before = sourceCode.getTokenBefore(property),
                    first = sourceCode.getFirstToken(property),
                    last = sourceCode.getLastToken(property),
                    after = sourceCode.getTokenAfter(property);

                if (astUtils.isTokenOnSameLine(before, first)) {
                    if (propertyNameMustBeSpaced) {
                        if (!sourceCode.isSpaceBetweenTokens(before, first) && astUtils.isTokenOnSameLine(before, first)) {
                            reportRequiredBeginningSpace(node, before);
                        }
                    } else {
                        if (sourceCode.isSpaceBetweenTokens(before, first)) {
                            reportNoBeginningSpace(node, before, first);
                        }
                    }
                }

                if (astUtils.isTokenOnSameLine(last, after)) {
                    if (propertyNameMustBeSpaced) {
                        if (!sourceCode.isSpaceBetweenTokens(last, after) && astUtils.isTokenOnSameLine(last, after)) {
                            reportRequiredEndingSpace(node, after);
                        }
                    } else {
                        if (sourceCode.isSpaceBetweenTokens(last, after)) {
                            reportNoEndingSpace(node, after, last);
                        }
                    }
                }
            };
        }

        //--------------------------------------------------------------------------
        // Public
        //--------------------------------------------------------------------------

        return {
            Property: checkSpacing("key"),
            MemberExpression: checkSpacing("property")
        };

    }
};


text:
.demo-listReorderer-container ol li {
    padding: 5px;
    margin-bottom: 5px;
    list-style-position: inside;
    border-right: 3px solid #6d6e71; /* thicker right border acts as a grab indicator. */
}

.demo-listReorderer-container ul {
    margin-top: 0px;
    margin-bottom: 0px;
}

.demo-listReorderer-container ul li {
    list-style-type: none;
    margin:0px;
    padding:0px;
    padding-left:1em;
    border-right: none;
}

.demo-listReorderer-container {
    width: 95%;
}

.demo-listReorderer-movable-default{
    background-color: #e7e8e9;
}

.demo-listReorderer-movable-hover, .demo-listReorderer-movable-selected{
    background-color: #fff;
    outline: none;
    cursor: move;

    /* Change the left, top, and bottom borders on hover and select.
       Leave the right border alone as it serves as the grab indicator. */
    border-top: 1px solid #00a651;
    border-left: 1px solid #00a651;
    border-bottom: 1px solid #00a651;

    /* set the 5px padding inherited (ol li) to 4px to compensate for
       1px hover border. */
    padding: 4px;
}

.demo-listReorderer-movable-dragging {
    position: relative;
    left: 10px;
    border: 1px solid #00a651;
    background-color: #d2f7d8;
}

.demo-listReorderer-movable-mousedrag {
    visibility: hidden;
}

.demo-listReorderer-avatar {
    opacity: 0.55;
    filter: alpha(opacity=55); /* ie opacity fix */
    border: 0;
    color: #2bb673;
    background-color: #2bb673;
}

.demo-listReorderer-dropMarker {
    background-color : #00a651;
    height:3px;
    padding:0 0 0 0;
    border-width: 0px;
    list-style-type:none;
    font-size:0px;
    line-height:0px;
    overflow:hidden;
}


text:
require 'ascii_binder/helpers'
require 'trollop'

include AsciiBinder::Helpers

module AsciiBinder
  class TopicEntity
    attr_reader :name, :dir, :file, :topic_alias, :distro_keys, :subitems, :raw, :parent, :depth

    def initialize(topic_entity,actual_distro_keys,dir_path='',parent_group=nil,depth=0)
      @raw                = topic_entity
      @parent             = parent_group
      @dir_path           = dir_path
      @name               = topic_entity['Name']
      @dir                = topic_entity['Dir']
      @file               = topic_entity['File']
      @topic_alias        = topic_entity['Alias']
      @depth              = depth
      @actual_distro_keys = actual_distro_keys
      @distro_keys        = topic_entity.has_key?('Distros') ? parse_distros(topic_entity['Distros']) : actual_distro_keys
      @nav_trees          = {}
      @alias_lists        = {}
      @path_lists         = {}
      @subitems           = []
      if topic_entity.has_key?('Topics')
        entity_dir  = @dir.nil? ? '<nil_dir>' : @dir
        subdir_path = dir_path == '' ? entity_dir : File.join(dir_path,entity_dir)
        topic_entity['Topics'].each do |sub_entity|
          @subitems << AsciiBinder::TopicEntity.new(sub_entity,actual_distro_keys,subdir_path,self,depth+1)
        end
      end
    end

    def repo_path
      @repo_path ||= begin
        this_step = '<nil_item>'
        if is_group?
          this_step = dir
        elsif is_topic?
          this_step = file.end_with?('.adoc') ? file : "#{file}.adoc"
        end
        @dir_path == '' ? this_step : File.join(@dir_path,this_step)
      end
    end

    def basename_path
      @basename_path ||= File.join(File.dirname(repo_path),File.basename(repo_path,'.adoc'))
    end

    def repo_path_html
      @repo_path_html ||= is_topic? ? File.join(File.dirname(repo_path),File.basename(repo_path,'.adoc')) + ".html" : repo_path
    end

    def source_path
      @source_path ||= File.join(docs_root_dir,repo_path)
    end

    def preview_path(distro_key,branch_dir)
      File.join(preview_dir,distro_key,branch_dir,repo_path_html)
    end

    def topic_publish_url(distro_url,branch_dir)
      File.join(distro_url,branch_dir,repo_path_html)
    end

    def package_path(site_id,branch_dir)
      File.join(package_dir,site_id,branch_dir,repo_path_html)
    end

    def group_filepaths
      @group_filepaths ||= begin
        group_filepaths = []
        if is_topic? and not is_alias?
          group_filepaths << File.join(File.dirname(repo_path),File.basename(repo_path,'.adoc'))
        elsif is_group?
          subitems.each do |subitem|
            group_filepaths.concat(subitem.group_filepaths)
          end
          group_filepaths.uniq!
        end
        group_filepaths
      end
    end

    def nav_tree(distro_key)
      @nav_trees[distro_key] ||= begin
        nav_tree = {}
        if distro_keys.include?(distro_key) and not is_alias?
          nav_tree[:id]   = id
          nav_tree[:name] = name
          if is_topic?
            nav_tree[:path] = "../" + repo_path_html
          elsif is_group?
            sub_nav_items = []
            subitems.each do |subitem|
              sub_nav = subitem.nav_tree(distro_key)
              next if sub_nav.empty?
              sub_nav_items << sub_nav
            end
            if sub_nav_items.empty?
              nav_tree = {}
            else
              nav_tree[:topics] = sub_nav_items
            end
          end
        end
        nav_tree
      end
    end

    def alias_list(distro_key)
      @alias_lists[distro_key] ||= begin
        sub_aliases = []
        if distro_keys.include?(distro_key)
          if is_group?
            subitems.each do |subitem|
              sub_list = subitem.alias_list(distro_key)
              sub_list.each do |sub_list_alias|
                sub_aliases << sub_list_alias
              end
            end
          elsif is_alias?
            sub_aliases << { :alias_path => basename_path, :redirect_path => topic_alias }
          end
        end
        sub_aliases
      end
    end

    def path_list(distro_key)
      @path_lists[distro_key] ||= begin
        sub_paths = []
        if distro_keys.include?(distro_key)
          if is_group?
            subitems.each do |subitem|
              sub_list = subitem.path_list(distro_key)
              sub_list.each do |sub_list_path|
                sub_paths << sub_list_path
              end
            end
          elsif is_topic? and not is_alias?
            sub_paths << basename_path
          end
        end
        sub_paths
      end
    end

    # Is this topic entity or any of its children used in
    # the specified distro / single page chain
    def include?(distro_key,single_page_path)
      # If this entity isn't for this distro, bail out
      return false unless distro_keys.include?(distro_key)

      # If we're building a single page, check if we're on the right track.
      if single_page_path.length > 0
        if is_group?
          return false unless single_page_path[depth] == dir
        elsif is_topic?
          return false unless single_page_path[depth] == file
        else
          return false
        end
      elsif is_group?
        # If this is a topic group that -is- okay for this distro, but
        # none of its subitems are okay for this distro, then bail out.
        subitems_for_distro = false
        subitems.each do |subitem|
          if subitem.include?(distro_key,[])
            subitems_for_distro = true
            break
          end
        end
        return false unless subitems_for_distro
      end

      return true
    end

    def breadcrumb
      @breadcrumb ||= hierarchy.map{ |entity| { :id => entity.id, :name => entity.name, :url => entity.repo_path_html } }
    end

    def id
      @id ||= hierarchy.map{ |entity| camelize(entity.name) }.join('::')
    end

    def is_group?
      @is_group ||= file.nil? and not name.nil? and not dir.nil? and subitems.length > 0
    end

    def is_topic?
      @is_topic ||= dir.nil? and not name.nil? and not file.nil? and subitems.length == 0
    end

    def is_alias?
      @is_alias ||= is_topic? and not topic_alias.nil?
    end

    def is_valid?
      validate
    end

    def errors
      validate(true)
    end

    private

    def parse_distros(entity_distros)
      values = entity_distros.split(',').map(&:strip)
      # Don't bother with glob expansion if 'all' is in the list.
      return @actual_distro_keys if values.include?('all')

      # Expand globs and return the list
      values.flat_map do |value|
        value_regex = Regexp.new("\\A#{value.gsub("*", ".*")}\\z")
        @actual_distro_keys.select { |k| value_regex.match(k) }
      end.uniq
    end

    def validate(verbose=false)
      errors = []

      # Check common fields - Name and Distros
      if not valid_string?(name)
        if verbose
          errors << "Topic entity with missing or invalid 'Name' value: '#{raw.inspect}'"
        else
          return false
        end
      end
      distro_keys.each do |distro_key|
        next if @actual_distro_keys.include?(distro_key)
        if verbose
          errors << "#{entity_id} 'Distros' filter includes nonexistent distro key '#{distro_key}'"
        else
          return false
        end
      end

      # Check the depth.
      if (depth > AsciiBinder::DEPTH) and (AsciiBinder::DEPTH != 0)
        if verbose
          errors << "#{entity_id} exceeds the maximum nested depth."
        else
          return false
        end
      end

      # For groups, test the 'Dir' value and the sub-items.
      if is_group?
        if not valid_string?(dir)
          if verbose
            errors << "#{entity_id} has invalid 'Dir' value."
          else
            return false
          end
        end
        if not topic_alias.nil?
          if verbose
            errors << "#{entity_id} is a topic group with an Alias entry. Aliases are only supported for topic items."
          else
            return false
          end
        end
        subitems.each do |subitem|
          next if subitem.is_valid?
          if verbose
            errors = errors.concat(subitem.errors)
          else
            return false
          end
        end
      elsif is_topic?
        if not valid_string?(file)
          if verbose
            errors << "#{entity_id} has invalid 'File' value."
          else
            return false
          end
        end
        # We can do basic validation of the 'Alias' string here, but real validation has
        # to be done after the whole topic map is loaded.
        if not topic_alias.nil? and not valid_string?(topic_alias)
          if verbose
            errors << "#{entity_id} has invalid 'Alias' value."
          else
            return false
          end
        end
      else
        if verbose
          errors << "#{entity_id} is not parseable as a group or a topic: '#{raw.inspect}'"
        else
          return false
        end
      end
      return errors if verbose
      return true
    end

    def hierarchy
      @hierarchy ||= begin
        entity   = self
        ancestry = []
        loop do
          ancestry << entity
          break if entity.parent.nil?
          entity = entity.parent
        end
        ancestry.reverse
      end
    end

    def entity_id
      if hierarchy.length == 1
        return "Top level topic entity '#{name}'"
      else
        return "Topic entity at '#{breadcrumb.map{ |node| node[:name] }.join(' -> ')}'"
      end
    end
  end
end


text:
package io.machinecode.chainlink.repository.jpa;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.InvalidTransactionException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;

/**
 * @author Brent Douglas
 * @since 1.0
 */
public class ResourceLocalTransactionManager implements ExtendedTransactionManager {

    private final EntityTransaction delegate;

    public ResourceLocalTransactionManager(final EntityManager entityManager) {
        this.delegate = entityManager.getTransaction();
    }

    @Override
    public boolean isResourceLocal() {
        return true;
    }

    @Override
    public void begin() throws NotSupportedException, SystemException {
        delegate.begin();
    }

    public void commit() throws RollbackException, HeuristicMixedException, HeuristicRollbackException, SecurityException, SystemException {
        delegate.commit();
    }

    public void rollback() throws IllegalStateException, SystemException {
        delegate.rollback();
    }

    public void setRollbackOnly() throws IllegalStateException, SystemException {
        delegate.setRollbackOnly();
    }

    public int getStatus() throws SystemException {
        return -1;
    }

    @Override
    public Transaction getTransaction() throws SystemException {
        return null;
    }

    @Override
    public void setTransactionTimeout(final int seconds) throws SystemException {
        //
    }

    @Override
    public Transaction suspend() throws SystemException {
        return null;
    }

    @Override
    public void resume(final Transaction transaction) throws InvalidTransactionException, IllegalStateException, SystemException {
        //
    }
}


text:
import _ from 'lodash'

export default class EventTarget {
  _handlers = {}
  _pools = {}

  constructor(target) {
    this.target = target
  }

  // ------------------------------------
  // Utils
  // ------------------------------------

  _emit = name => (event) => {
    _.forEach(this._pools, (pool, poolName) => {
      const { [name]: handlers } = pool

      if (!handlers) return
      if (poolName === 'default') {
        _.forEach(handlers, handler => handler(event))
        return
      }
      _.last(handlers)(event)
    })
  }

  _normalize = handlers => (_.isArray(handlers) ? handlers : [handlers])

  // ------------------------------------
  // Listeners handling
  // ------------------------------------

  _listen = (name) => {
    if (_.has(this._handlers, name)) return
    const handler = this._emit(name)

    this.target.addEventListener(name, handler)
    this._handlers[name] = handler
  }

  _unlisten = (name) => {
    if (_.some(this._pools, name)) return
    const { [name]: handler } = this._handlers

    this.target.removeEventListener(name, handler)
    delete this._handlers[name]
  }

  // ------------------------------------
  // Pub/sub
  // ------------------------------------

  empty = () => _.isEmpty(this._handlers)

  sub = (name, handlers, pool = 'default') => {
    const events = _.uniq([
      ..._.get(this._pools, `${pool}.${name}`, []),
      ...this._normalize(handlers),
    ])

    this._listen(name)
    _.set(this._pools, `${pool}.${name}`, events)
  }

  unsub = (name, handlers, pool = 'default') => {
    const events = _.without(
      _.get(this._pools, `${pool}.${name}`, []),
      ...this._normalize(handlers),
    )

    if (events.length > 0) {
      _.set(this._pools, `${pool}.${name}`, events)
      return
    }

    _.set(this._pools, `${pool}.${name}`, undefined)
    this._unlisten(name)
  }
}


text:
struct Piece
{
	bool TL;
	bool TR;
	bool BL;
	bool BR;
	unsigned int IntType;
	unsigned int GetIntType();
};
class ConvexHull;
class MapArray;
class MarchingSquares
{
public:
	MarchingSquares();
	~MarchingSquares();

	void Create(std::string Name, MapArray Map, bool FillType = false);

	void MarchSquares(MapArray Map, int ScreenHeight, int TileSize);

	void PrintMap();

	void DrawMap(sf::RenderWindow& Window);
private:
	Piece** m_PieceMap;
	std::string m_MapName;
	unsigned int m_Width;
	unsigned int m_Height;
	std::vector<ConvexHull> m_Hulls;

	sf::Image Tex;
};


text:
/*
Package session contains an fake implementation of a Redis session manager
that (for whatever reason) needs to talk to the Database, but we don't want to
import that package for a couple reasons:

1. The Database implementation also needs to use the session manager, and Go
   doesn't allow cyclic imports
2. It's just bad form to tightly couple your concrete implementations - you'd get
   bit by a different problem if cyclic imports *were* allowed.

Don't look too far into why the classes are talking with each other - it's a
contrived example to demonstrate Go's implicit interfaces.
*/
package session

import (
	"fmt"
)

// DataStore defines the methods we need to access from our DataStore, without
// knowing or caring what the concrete type is. We're interfacing out a type
// without telling that it!
type DataStore interface {
	// ValidateUser checks if a username/password is valid, returning the unique user ID
	ValidateUser(username string, password string) (int64, error)

	// LockOutUser records that a user account can no longer be accessed, due to bad login attempts
	LockOutUser(username string) error
}

// RedisSessionManager is a session implementation that validates logins with the database, and stores the
// session info in Redis
type RedisSessionManager struct {
	dataStore     DataStore // avoid coupling to the concrete Database type by using the DataStore interface
	redisHost     string    // internal Redis stuff
	redisLogin    string    // internal Redis stuff
	redisPassword string    // internal Redis stuff
}

// NewRedisSessionManager creates a new RedisSessionManager
// Note that we don't pass in the sessionManager - that's because our session manager and data store
// need each other. The top-level code that wires them together should set each other's properties
// immediately after instantiating them.
func NewRedisSessionManager(redisHost string, redisLogin string, redisPassword string) (*RedisSessionManager, error) {
	ret := RedisSessionManager{
		redisHost:     redisHost,
		redisLogin:    redisLogin,
		redisPassword: redisPassword,
	}
	return &ret, nil
}

// SetDataStore sets the DataStore
func (rs *RedisSessionManager) SetDataStore(dataStore DataStore) error {
	rs.dataStore = dataStore
	return nil
}

// AuthenticateUser authenticates the input user, returning the session key, and
// error when not valid or a problem occurred.
func (rs *RedisSessionManager) AuthenticateUser(username string, password string) (string, error) {
	if rs.dataStore == nil {
		panic("You forgot to set the DataStore!")
	}

	_, authErr := rs.dataStore.ValidateUser(username, password)
	if authErr != nil {
		// this system doesn't allow a single bad login, because: reasons
		if lockOutErr := rs.dataStore.LockOutUser(username); lockOutErr != nil {
			// TODO: log this
		}
		return "", fmt.Errorf("Error validating user %s: %s", username, authErr)
	}

	// valid login - TODO: actually store this in Redis

	return "your-session-key", nil
}

// ValidateSession checks if the input session key is a valid logged-in user, and returns the
// username and id if so.
func (rs *RedisSessionManager) ValidateSession(sessionKey string) (string, int64, error) {
	// TODO: this is just stubbed-out
	return "fprefect", 42, nil
}


text:
package main

import "strconv"

const (
	columnRowIndex = "row_index"
)

type ColumnRowIndex struct {
	TypedColumnBase
}

func (column ColumnRowIndex) Value(chunk *Chunk) (string, error) {
	return strconv.Itoa(chunk.index), nil
}