text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.raptor;

import com.facebook.presto.raptor.metadata.ShardInfo;
import com.facebook.presto.raptor.storage.StorageManager;
import com.facebook.presto.spi.ConnectorInsertTableHandle;
import com.facebook.presto.spi.ConnectorOutputTableHandle;
import com.facebook.presto.spi.ConnectorPageSink;
import com.facebook.presto.spi.ConnectorPageSinkProvider;
import com.facebook.presto.spi.ConnectorSession;
import com.facebook.presto.spi.PageSorter;
import io.airlift.json.JsonCodec;

import javax.inject.Inject;

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

import static com.facebook.presto.raptor.util.Types.checkType;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.stream.Collectors.toList;

public class RaptorPageSinkProvider
        implements ConnectorPageSinkProvider
{
    private final StorageManager storageManager;
    private final PageSorter pageSorter;
    private final JsonCodec<ShardInfo> shardInfoCodec;

    @Inject
    public RaptorPageSinkProvider(StorageManager storageManager, PageSorter pageSorter, JsonCodec<ShardInfo> shardInfoCodec)
    {
        this.storageManager = checkNotNull(storageManager, "storageManager is null");
        this.pageSorter = checkNotNull(pageSorter, "pageSorter is null");
        this.shardInfoCodec = checkNotNull(shardInfoCodec, "shardInfoCodec is null");
    }

    @Override
    public ConnectorPageSink createPageSink(ConnectorSession session, ConnectorOutputTableHandle tableHandle)
    {
        RaptorOutputTableHandle handle = checkType(tableHandle, RaptorOutputTableHandle.class, "tableHandle");
        return new RaptorPageSink(
                pageSorter,
                storageManager,
                shardInfoCodec,
                toColumnIds(handle.getColumnHandles()),
                handle.getColumnTypes(),
                optionalColumnId(handle.getSampleWeightColumnHandle()),
                toColumnIds(handle.getSortColumnHandles()),
                handle.getSortOrders());
    }

    @Override
    public ConnectorPageSink createPageSink(ConnectorSession session, ConnectorInsertTableHandle tableHandle)
    {
        RaptorInsertTableHandle handle = checkType(tableHandle, RaptorInsertTableHandle.class, "tableHandle");
        return new RaptorPageSink(
                pageSorter,
                storageManager,
                shardInfoCodec,
                toColumnIds(handle.getColumnHandles()),
                handle.getColumnTypes(),
                Optional.empty(),
                toColumnIds(handle.getSortColumnHandles()),
                handle.getSortOrders());
    }

    private static List<Long> toColumnIds(List<RaptorColumnHandle> columnHandles)
    {
        return columnHandles.stream().map(RaptorColumnHandle::getColumnId).collect(toList());
    }

    private static Optional<Long> optionalColumnId(RaptorColumnHandle handle)
    {
        return Optional.ofNullable(handle).map(RaptorColumnHandle::getColumnId);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<scenario xmlns="urn:perfcake:scenario:4.0">
    <properties>
        <property name="p1" value="newValue"/>
        <property name="newName" value="v2"/>
        <property name="newName3" value="newValue3"/>
        <property name="px" value="vx"/>
    </properties>
    <generator class="DefaultMessageGenerator" threads="10">
        <run type="time" value="10"/>
        <property name="name" value="value"/>
    </generator>
    <sender class="PlainSocketSender">
        <property name="target" value="value"/>
    </sender>
</scenario>

redpajama_set_name: RedPajamaGithub


text:
package org.cef;

public class OS {
    private static OSType osType = OSType.OSUndefined;

    ;

    public static final boolean isWindows() {
        return getOSType() == OSType.OSWindows;
    }

    public static final boolean isMacintosh() {
        return getOSType() == OSType.OSMacintosh;
    }

    public static final boolean isLinux() {
        return getOSType() == OSType.OSLinux;
    }

    private static final OSType getOSType() {
        if (osType == OSType.OSUndefined) {
            String os = System.getProperty("os.name").toLowerCase();
            if (os.startsWith("windows")) {
                osType = OSType.OSWindows;
            }
            else if (os.startsWith("linux")) {
                osType = OSType.OSLinux;
            }
            else if (os.startsWith("mac")) {
                osType = OSType.OSMacintosh;
            }
            else {
                osType = OSType.OSUnknown;
            }
        }
        return osType;
    }

    private static enum OSType {
        OSUndefined, OSLinux, OSWindows, OSMacintosh, OSUnknown,
    }
}


text:
define({
  root: ({
    addLayer: "Add Layer",
    layerName: "Layer",
    layerRefresh: "Refresh",
    layerLabel: "Label",
    actions: "Actions",
    mainPanelTextPlaceholder: "ex: Last Updated:",
    invalidInterval: "Only positive integers allowed",
    uploadImage: "Upload Image",
    iconColumnText: "Display",
    refreshInterval: "Time in Minutes",
    refreshIntervalTitle: "Evaluated as time in Minutes",
    mainPanelText: "Main Panel Text",
    mainPanelIcon: "Main Panel Image",
    refreshIntervalInstruction: "Refresh layers every:",
    optionsText: "Options",
    symbolOptionsText: "Map Symbology",
    iconOptionsText: "Panel Symbology",
    sympolPopupTitle: "Display Settings",
    rdoLayer: "Default symbol",
    rdoCustom: "Use an Image",
    chkCluster: "Enable Clustering",
    defineClusterSymbol: "Specify Cluster Symbol",
    rdoEsri: "Pick a symbol",
    rdoLayerIcon: "Use map symbol",
    rdoCustomIcon: "Use an image",
    editCustomSymbol: "Edit Custom Symbol",
    editCustomIcon: "Edit Custom Icon",
    missingRefreshValue: "Please provide a refresh interval value.",
    panelIconOption: "Display Logo Image",
    enableRefresh: "Enable layer refresh",
    disableRefresh: "Layer refresh only supported for feature collections.",
    refreshUnit: "minutes.",
    symbolOptions: "Symbol",
    panelFeatureDisplay: "Panel",
    chkGroup: "Group features",
    selectField: "Field",
    fieldLabel: "Label",
    addField: "Add Field",
    featureOptionsText: "Layer Options",
    groupOptionsText: "Group Options",
    panelCountOption: "Display Feature Counts",
    missingLayerInWebMap: "No operational layers found.",
    displayClusterCnt: "Display Feature Count",
    defineClusterFont: "Specify Font Color",
    max_records: "Maximum field limit reached",
    hidePanel: "Hide Panel",
    hidePanelHelp: "Enable/Disable main panel display.",
    continuousRefreshHelp: "Note: Feature collection refresh will occur continuously.",
    panelCountOptionHelp: "Enable/Disable display of feature counts.",
    panelIconOptionHelp: "Enable/Disable display of a logo on the main panel.",
    rdoGroupByField: "by field",
    rdoGroupByRenderer: "by renderer",
    expandList: "Expand List on Startup",
    expandListHelp: "Enable/Disable default expanding of the list.",
    chkFeatureDisplay: "Disable Feature List",
    showAllFeaturesHelp: "Enable/Disable display of all features regardless of extent.",
    showAllFeatures: "Show All Features",
    fieldsWarning: "No fields defined in popup. Optional: Use edit action to define panel display options."
  }),
  "ar": 1,
  "bs": 1,
  "cs": 1,
  "da": 1,
  "de": 1,
  "el": 1,
  "es": 1,
  "et": 1,
  "fi": 1,
  "fr": 1,
  "he": 1,
  "hi": 1,
  "hr": 1,
  "it": 1,
  "id": 1,
  "ja": 1,
  "ko": 1,
  "lt": 1,
  "lv": 1,
  "nb": 1,
  "nl": 1,
  "pl": 1,
  "pt-br": 1,
  "pt-pt": 1,
  "ro": 1,
  "ru": 1,
  "sr": 1,
  "sv": 1,
  "th": 1,
  "tr": 1,
  "vi": 1,
  "zh-cn": 1,
  "zh-hk": 1,
  "zh-tw": 1
});


text:
package azkaban.project.validator;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;

import azkaban.project.Project;
import azkaban.utils.HashUtils;
import azkaban.utils.Props;
import com.google.common.io.Resources;
import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.mockito.internal.util.reflection.FieldSetter;

public class XmlValidatorManagerTest {

  private final Props baseProps = new Props();

  /**
   * Test that no validator directory exists when there is no xml configuration.
   */
  @Test
  public void testNoValidatorsDir() {
    final Props props = new Props(this.baseProps);

    final XmlValidatorManager manager = new XmlValidatorManager(props);
    assertEquals(
        "XmlValidatorManager should contain 0 validator when no xml configuration "
            + "file is present.", manager.getValidatorsInfo().size(), 0);
  }

  /**
   * Test that if the xml config file specifies a validator classname that does not exist,
   * XmlValidatorManager should throw an exception.
   */
  @Test(expected = ValidatorManagerException.class)
  public void testValidatorDoesNotExist() {
    final Props props = new Props(this.baseProps);
    final URL validatorUrl = Resources.getResource("project/testValidators");
    final URL configUrl = Resources.getResource("test-conf/azkaban-validators-test1.xml");
    props.put(ValidatorConfigs.VALIDATOR_PLUGIN_DIR, validatorUrl.getPath());
    props.put(ValidatorConfigs.XML_FILE_PARAM, configUrl.getPath());

    new XmlValidatorManager(props);

  }

  /**
   * Test that if the xml config file is properly set, XmlValidatorManager loads the validator
   * specified in the xml file. The TestValidator class specified in the xml configuration file
   * is located with the jar file inside test resource directory project/testValidators.
   */
  @Test
  public void testLoadValidators() {
    final Props props = new Props(this.baseProps);
    final URL validatorUrl = Resources.getResource("project/testValidators");
    final URL configUrl = Resources.getResource("test-conf/azkaban-validators-test2.xml");
    props.put(ValidatorConfigs.VALIDATOR_PLUGIN_DIR, validatorUrl.getPath());
    props.put(ValidatorConfigs.XML_FILE_PARAM, configUrl.getPath());

    final XmlValidatorManager manager = new XmlValidatorManager(props);
    assertEquals("XmlValidatorManager should contain 1 validator.",
        manager.getValidatorsInfo().size(), 1);
    assertEquals(
        "XmlValidatorManager should contain the validator specified in the xml configuration file.",
        manager.getValidatorsInfo().get(0), "Test");
  }

  @Test
  public void testValidateProjectValidator() throws Exception {
    final Project project = mock(Project.class);
    final File projectDir = mock(File.class);
    final Props props = new Props();

    final ProjectValidator mockValidator = mock(ProjectValidator.class);
    final XmlValidatorManager manager = new XmlValidatorManager(props);

    // When we attempt to validate a project with our mock validator, return sampleReport
    final ValidationReport sampleReport = new ValidationReport();
    when(mockValidator.validateProject(project, projectDir, props)).thenReturn(sampleReport);

    Map<String, ProjectValidator> mockedValidators = new HashMap();
    mockedValidators.put("TEST", mockValidator);

    // This is brittle and hacky, but we're directly setting the private validators field with our own
    Field validatorsField = manager.getClass().getDeclaredField("validators");
    validatorsField.setAccessible(true);
    FieldSetter.setField(manager, validatorsField, mockedValidators);

    Map<String, ValidationReport> expectedResultingReports = new HashMap();
    expectedResultingReports.put("TEST", sampleReport);

    // Make sure we get the reports back that we expect
    assertEquals(expectedResultingReports, manager.validate(project, projectDir, props));
  }

  @Test
  public void testGetCacheKeyProjectValidatorCacheable() throws Exception {
    final Project project = mock(Project.class);
    final File projectDir = mock(File.class);
    final Props props = new Props();

    final ProjectValidatorCacheable mockValidatorCacheable = mock(ProjectValidatorCacheable.class);
    final ProjectValidator mockValidator = mock(ProjectValidator.class);
    final XmlValidatorManager manager = new XmlValidatorManager(props);

    // When we attempt to validate a project with our mock validator, return sampleReport
    final String cacheKey = "abc123";
    final String expectedResultingCacheKey = HashUtils.SHA1.getHashStr(cacheKey);
    when(mockValidatorCacheable.getCacheKey(project, projectDir, props)).thenReturn(cacheKey);

    Map<String, ProjectValidator> mockedValidators = new HashMap();
    // We add a non cacheable validator as well to ensure that it is ignored properly and no exceptions are thrown.
    mockedValidators.put("NORMAL", mockValidator);
    // Only this cacheable validator should contribute to the cacheKey
    mockedValidators.put("CACHEABLE", mockValidatorCacheable);

    // This is brittle and hacky, but we're directly setting the private validators field with our own
    Field validatorsField = manager.getClass().getDeclaredField("validators");
    validatorsField.setAccessible(true);
    FieldSetter.setField(manager, validatorsField, mockedValidators);

    // Make sure we get the cache key we expected (the SHA1 of the one cache key returned)
    assertEquals(expectedResultingCacheKey, manager.getCacheKey(project, projectDir, props));
  }
}


text:
package org.projectodd.wunderboss.ec;

public interface ClusterParticipant {
    boolean isMaster();

    void whenMasterAcquired(Runnable r);

    void whenMasterLost(Runnable r);
}


text:
<?php

/* @var $this yii\web\View */
/* @var $model app\models\Categoria */

$this->title = Yii::t('app', 'Create {modelClass}', ['modelClass' => $model::singularObjectName()]);
$this->params['breadcrumbs'][] = ['label' => $model::pluralObjectName(), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="categoria-create">

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>

</div>


text:
using Common.Logging;

namespace Leeroy
{
	/// <summary>
	/// <see cref="LoggerProxy"/> is a proxy that forwards log messages sent to a <see cref="Logos.Utility.Logging.Logger"/> instance
	/// to a <see cref="Common.Logging.ILog"/> logger with the same name.
	/// </summary>
	internal sealed class LoggerProxy : Logos.Utility.Logging.LoggerCore
	{
		public LoggerProxy(string name)
		{
			// create a new Common.Logging logger
			m_logger = LogManager.GetLogger(name);
		}

		protected override bool IsDebugEnabledCore
		{
			get { return m_logger.IsDebugEnabled; }
		}

		protected override bool IsInfoEnabledCore
		{
			get { return m_logger.IsInfoEnabled; }
		}

		protected override bool IsWarnEnabledCore
		{
			get { return m_logger.IsWarnEnabled; }
		}

		protected override bool IsErrorEnabledCore
		{
			get { return m_logger.IsErrorEnabled; }
		}

		protected override void DebugCore(string message, object[] args)
		{
			if (args == null)
				m_logger.Debug(message);
			else
				m_logger.DebugFormat(message, args);
		}

		protected override void InfoCore(string message, object[] args)
		{
			if (args == null)
				m_logger.Info(message);
			else
				m_logger.InfoFormat(message, args);
		}

		protected override void WarnCore(string message, object[] args)
		{
			if (args == null)
				m_logger.Warn(message);
			else
				m_logger.WarnFormat(message, args);
		}

		protected override void ErrorCore(string message, object[] args)
		{
			if (args == null)
				m_logger.Error(message);
			else
				m_logger.ErrorFormat(message, args);
		}

		readonly ILog m_logger;
	}
}


text:
package indexer

import (
	"sync"
	"time"

	"github.com/Sirupsen/logrus"
	"github.com/aslanides/gocrud/search"
	"github.com/aslanides/gocrud/store"
	"github.com/aslanides/gocrud/x"
)

// Incremental indexing server to continously regenerate
// and index entities to keep store and search in-sync.
type Server struct {
	ch chan x.Entity
	wg *sync.WaitGroup
}

// NewServer returns back a server which runs continously in
// a loop to find and re-index entities stored.
// You can control the amount of memory consumed by the server
// via buffer of pending entities in the channel, and the
// rate of processing of these entities via numRoutines.
func NewServer(buffer int, numRoutines int) *Server {
	if search.Get() == nil {
		log.Fatal("No search engine found")
	}
	s := new(Server)
	s.ch = make(chan x.Entity, buffer)
	s.wg = new(sync.WaitGroup)
	for i := 0; i < numRoutines; i++ {
		s.wg.Add(1)
		go s.regenerateAndIndex()
	}
	return s
}

func (s *Server) regenerateAndIndex() {
	defer s.wg.Done()

	for entity := range s.ch {
		idxr, ok := Get(entity.Kind)
		if !ok {
			continue
		}

		doc := idxr.Regenerate(entity)
		log.WithField("doc", doc).Debug("Regenerated doc")
		if err := search.Get().Update(doc); err != nil {
			x.LogErr(log, err).WithField("doc", doc).
				Error("While updating in search engine")
		}
	}
}

// LoopOnce would cycle over all entities in the store, and re-index them.
func (s *Server) LoopOnce() {
	var total uint64
	from := ""
	for {
		found, last, err := store.Get().Iterate(from, 1000, s.ch)
		if err != nil {
			x.LogErr(log, err).Error("While iterating")
			return
		}
		if found == 0 {
			log.WithField("total", total).Info("Reached end of cycle")
			return
		}
		log.WithFields(logrus.Fields{
			"num_processed": found,
			"last":          last,
		}).Debug("Iteration chunk done")
		total += uint64(found)
		from = last.Id
	}
	log.Fatal("This should never be reached.")
	return
}

// InfiniteLoop would infinitely cycle over all entities in the
// store, waiting for wait duration after each cycle.
func (s *Server) InfiniteLoop(wait time.Duration) {
	for {
		s.LoopOnce()
		log.Debug("Sleeping...")
		time.Sleep(wait)
	}
}

func (s *Server) Finish() {
	close(s.ch)
	s.wg.Wait()
}


text:
/**
 * Thrown to indicate that the given node
 * is not suitable for addition to within the relevant tree.
 * Implementation makes use of java.lang.IllegalArgumentException
 * @author Max Fisher
 *
 */
public class IllegalNodeException extends IllegalArgumentException {
	private static final long serialVersionUID = -2108960235681036527L;

	/**
	 * Creates exception with standard error message
	 */
	public <E> IllegalNodeException(TreeNode<E> v) {
		this("Illegal node type for Node " + v + ".");
	}

	/**
     * Constructs an IllegalNodeException with no
     * detail message.
     */
    public IllegalNodeException() {
        super();
    }

    /**
     * Constructs an IllegalNodeException with the
     * specified detail message.
     *
     * @param   s   the detail message.
     */
    public IllegalNodeException(String s) {
        super(s);
    }

    /**
     * Constructs a new exception with the specified detail message and
     * cause.
     *
     *
Note that the detail message associated with cause is
     * not automatically incorporated in this exception's detail
     * message.
     *
     * @param  message the detail message (which is saved for later retrieval
     *         by the {@link Throwable#getMessage()} method).
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link Throwable#getCause()} method).  (A <tt>null</tt> value
     *         is permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since 1.5
     */
    public IllegalNodeException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * Constructs a new exception with the specified cause and a detail
     * message of <tt>(cause==null ? null : cause.toString())</tt> (which
     * typically contains the class and detail message of <tt>cause</tt>).
     * This constructor is useful for exceptions that are little more than
     * wrappers for other throwables (for example, {@link
     * java.security.PrivilegedActionException}).
     *
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link Throwable#getCause()} method).  (A <tt>null</tt> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     * @since  1.5
     */
    public IllegalNodeException(Throwable cause) {
        super(cause);
    }
}


text:
'use strict';

const PublicApiOptions = require('./PublicApiOptions');

/**
 * Контекст, который используется на этапе подготовки запроса.
 * В него входит, например, список обычных и агрегирующийх функций,
 * доступных в системе
 */
class PreparingContext
{
	/**
	 *
	 * @param {SqlToJs} sqlToJs
	 * @param {FunctionsMap} functionsMap
	 * @returns {PreparingContext}
	 */
	constructor(sqlToJs, functionsMap)
	{
		this.sqlToJs = sqlToJs;
		this.functionsMap = functionsMap;

		/**
		 * @type {PublicApiOptions}
		 */
		this.options = new PublicApiOptions;
	}
}

module.exports = PreparingContext;


text:
import { Orbit } from '@orbit/core';
import { HasOneRelationshipDefinition } from '@orbit/records';

import Model from '../model';
import { getHasOneCache } from '../utils/property-cache';
import { defineRelationship } from '../utils/model-definition';

const { assert } = Orbit;

export interface TrackedHasOne {
  get(this: Model): Model | null;
  set(this: Model, value: Model | null): void;
}

export default function hasOne(type: string | string[]): any;
export default function hasOne(def: Partial<HasOneRelationshipDefinition>): any;
export default function hasOne(
  type: string | string[],
  def?: Partial<HasOneRelationshipDefinition>
): any;
export default function hasOne(
  typeOrDef: string | string[] | Partial<HasOneRelationshipDefinition>,
  def?: Partial<HasOneRelationshipDefinition>
): any {
  let relDef: Partial<HasOneRelationshipDefinition>;

  if (typeof typeOrDef === 'string' || Array.isArray(typeOrDef)) {
    relDef = def ?? {};
    relDef.type = typeOrDef;
  } else {
    relDef = typeOrDef;

    assert(
      '@hasOne can be defined with a `type` and `definition` object but not two `definition` objects',
      def === undefined
    );

    assert('@hasOne() requires a `type` argument.', relDef?.type !== undefined);
  }

  relDef.kind = 'hasOne';

  return (target: Model, property: string): TrackedHasOne => {
    function get(this: Model): Model | null {
      assert(
        `The ${this.type} record has been removed from its cache, so we cannot lookup the ${property} hasOne relationship.`,
        this._cache !== undefined
      );

      return getHasOneCache(this, property).value as Model | null;
    }

    function set(this: Model, value: Model | null) {
      const oldValue = this.$getRelatedRecord(property);

      if (value !== oldValue) {
        this.$replaceRelatedRecord(property, value);
      }
    }

    defineRelationship(
      target,
      property,
      relDef as HasOneRelationshipDefinition
    );

    return { get, set };
  };
}


text:
#include <string.h>
#include "nfc_uri_rec.h"
#include "nrf_error.h"

/**
 * @brief Type of description of the payload of a URI record.
 */
typedef struct
{
    nfc_uri_id_t    uri_id_code;  ///< URI identifier code.
    uint8_t const * p_uri_data;   ///< Pointer to a URI string.
    uint8_t         uri_data_len; ///< Length of the URI string.
} uri_payload_desc_t;

/**
 * @brief Function for constructing the payload for a URI record.
 *
 * This function encodes the payload according to the URI record definition. It implements an API
 * compatible with @ref p_payload_constructor_t.
 *
 * @param[in] p_input           Pointer to the description of the payload.
 * @param[out] p_buff           Pointer to payload destination. If NULL, function will
 *                              calculate the expected size of the URI record payload.
 *
 * @param[in,out] p_len         Size of available memory to write as input. Size of generated
 *                              payload as output.
 *
 * @retval NRF_SUCCESS          If the payload was encoded successfully.
 * @retval NRF_ERROR_NO_MEM     If the predicted payload size is bigger than the provided buffer space.
 */
static ret_code_t nfc_uri_payload_constructor( uri_payload_desc_t * p_input,
                                               uint8_t * p_buff,
                                               uint32_t * p_len)
{
    if (p_buff != NULL)
    {
        /* Verify if there is enough available memory */
        if (p_input->uri_data_len >= *p_len)
        {
            return NRF_ERROR_NO_MEM;
        }

        /* Copy descriptor content into the buffer */
        *(p_buff++) = p_input->uri_id_code;
        memcpy(p_buff, p_input->p_uri_data, p_input->uri_data_len );
    }

    *p_len      = p_input->uri_data_len + 1;

    return NRF_SUCCESS;
}

nfc_ndef_record_desc_t * nfc_uri_rec_declare( nfc_uri_id_t           uri_id_code,
                                              uint8_t const *  const p_uri_data,
                                              uint8_t                uri_data_len)
{
    static uri_payload_desc_t uri_payload_desc;
    static const uint8_t static_uri_type = 'U';

    NFC_NDEF_GENERIC_RECORD_DESC_DEF( uri_rec,
                                      TNF_WELL_KNOWN, // tnf <- well-known
                                      NULL,
                                      0,    // no id
                                      &static_uri_type,
                                      1, // type size 1B
                                      nfc_uri_payload_constructor,
                                      &uri_payload_desc);

   uri_payload_desc.uri_id_code  = uri_id_code;
   uri_payload_desc.p_uri_data   = p_uri_data;
   uri_payload_desc.uri_data_len = uri_data_len;

   return &NFC_NDEF_GENERIC_RECORD_DESC( uri_rec);
}


text:
require 'spec_helper'

module LAME
  describe Buffer do

    it "creates a buffer of given size and type" do
      input = [-42, 0, 42]
      buffer = Buffer.create(:short, input)

      expect(buffer).to be_a(::FFI::MemoryPointer)
      expect(buffer.size).to eql 6 # shorts are two bytes
      expect(buffer.type_size).to eql 2
      expect(buffer.get_array_of_short(0, 3)).to eql [-42, 0, 42]
    end

    it "creates an empty buffer" do
      buffer = Buffer.create_empty(:uchar, 100)

      expect(buffer).to be_a(::FFI::MemoryPointer)
      expect(buffer.size).to eql 100
      expect(buffer.type_size).to eql 1
      expect(buffer.get_array_of_uchar(0, 100)).to eql [0]*100
    end

  end
end


text:
/*
Font sizes for all selectors other than the body are given in percentages,
with 100% equal to 13px. To calculate a font size percentage, multiply the
desired size in pixels by 7.6923076923.

Here's a quick lookup table:

10px - 76.923%
11px - 84.615%
12px - 92.308%
13px - 100%
14px - 107.692%
15px - 115.385%
16px - 123.077%
17px - 130.769%
18px - 138.462%
19px - 146.154%
20px - 153.846%
*/

html {
    background: #fff;
    color: #333;
    overflow-y: scroll;
}

body {
    /*font: 13px/1.4 'Lucida Grande', 'Lucida Sans Unicode', 'DejaVu Sans', 'Bitstream Vera Sans', 'Helvetica', 'Arial', sans-serif;*/
    font: 13px/1.4 'Helvetica', 'Arial', sans-serif;
    margin: 0;
    padding: 0;
}

/* -- Links ----------------------------------------------------------------- */
a {
    color: #356de4;
    text-decoration: none;
}

.hidden {
    display: none;
}

a:hover { text-decoration: underline; }

/* "Jump to Table of Contents" link is shown to assistive tools, but hidden from
   sight until it's focused. */
.jump {
    position: absolute;
    padding: 3px 6px;
    left: -99999px;
    top: 0;
}

.jump:focus { left: 40%; }

/* -- Paragraphs ------------------------------------------------------------ */
p { margin: 1.3em 0; }
dd p, td p { margin-bottom: 0; }
dd p:first-child, td p:first-child { margin-top: 0; }

/* -- Headings -------------------------------------------------------------- */
h1, h2, h3, h4, h5, h6 {
    color: #D98527;/*was #f80*/
    font-family: 'Trebuchet MS', sans-serif;
    font-weight: bold;
    line-height: 1.1;
    margin: 1.1em 0 0.5em;
}

h1 {
    font-size: 184.6%;
    color: #30418C;
    margin: 0.75em 0 0.5em;
}

h2 {
    font-size: 153.846%;
    color: #E48A2B;
}

h3 { font-size: 138.462%; }

h4 {
    border-bottom: 1px solid #DBDFEA;
    color: #E48A2B;
    font-size: 115.385%;
    font-weight: normal;
    padding-bottom: 2px;
}

h5, h6 { font-size: 107.692%; }

/* -- Code and examples ----------------------------------------------------- */
code, kbd, pre, samp {
    font-family: Menlo, Monaco, 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New', Courier, monospace;
    font-size: 92.308%;
    line-height: 1.35;
}

p code, p kbd, p samp, li code {
    background: #FCFBFA;
    border: 1px solid #EFEEED;
    padding: 0 3px;
}

a code, a kbd, a samp,
pre code, pre kbd, pre samp,
table code, table kbd, table samp,
.intro code, .intro kbd, .intro samp,
.toc code, .toc kbd, .toc samp {
    background: none;
    border: none;
    padding: 0;
}

pre.code, pre.terminal, pre.cmd {
    overflow-x: auto;
    *overflow-x: scroll;
    padding: 0.3em 0.6em;
}

pre.code {
    background: #FCFBFA;
    border: 1px solid #EFEEED;
    border-left-width: 5px;
}

pre.terminal, pre.cmd {
    background: #F0EFFC;
    border: 1px solid #D0CBFB;
    border-left: 5px solid #D0CBFB;
}

/* Don't reduce the font size of <code>/<kbd>/<samp> elements inside <pre>
   blocks. */
pre code, pre kbd, pre samp { font-size: 100%; }

/* Used to denote text that shouldn't be selectable, such as line numbers or
   shell prompts. Guess which browser this doesn't work in. */
.noselect {
    -moz-user-select: -moz-none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
    user-select: none;
}

/* -- Lists ----------------------------------------------------------------- */
dd { margin: 0.2em 0 0.7em 1em; }
dl { margin: 1em 0; }
dt { font-weight: bold; }

/* -- Tables ---------------------------------------------------------------- */
caption, th { text-align: left; }

table {
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #fff;
    padding: 5px 12px;
    vertical-align: top;
}

td { background: #E6E9F5; }
td dl { margin: 0; }
td dl dl { margin: 1em 0; }
td pre:first-child { margin-top: 0; }

th {
    background: #D2D7E6;/*#97A0BF*/
    border-bottom: none;
    border-top: none;
    color: #000;/*#FFF1D5*/
    font-family: 'Trebuchet MS', sans-serif;
    font-weight: bold;
    line-height: 1.3;
    white-space: nowrap;
}

/* -- Layout and Content ---------------------------------------------------- */
#doc {
    margin: auto;
    min-width: 1024px;
}

.content { padding: 0 20px 0 25px; }

.sidebar {
    padding: 0 15px 0 10px;
}
#bd {
    padding: 7px 0 130px;
    position: relative;
    width: 99%;
}

/* -- Table of Contents ----------------------------------------------------- */

/* The #toc id refers to the single global table of contents, while the .toc
   class refers to generic TOC lists that could be used throughout the page. */

.toc code, .toc kbd, .toc samp { font-size: 100%; }
.toc li { font-weight: bold; }
.toc li li { font-weight: normal; }

/* -- Intro and Example Boxes ----------------------------------------------- */
/*
.intro, .example { margin-bottom: 2em; }
.example {
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
    -moz-box-shadow: 0 0 5px #bfbfbf;
    -webkit-box-shadow: 0 0 5px #bfbfbf;
    box-shadow: 0 0 5px #bfbfbf;
    padding: 1em;
}
.intro {
    background: none repeat scroll 0 0 #F0F1F8; border: 1px solid #D4D8EB; padding: 0 1em;
}
*/

/* -- Other Styles ---------------------------------------------------------- */

/* These are probably YUI-specific, and should be moved out of Selleck's default
   theme. */

.button {
    border: 1px solid #dadada;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
    color: #444;
    display: inline-block;
    font-family: Helvetica, Arial, sans-serif;
    font-size: 92.308%;
    font-weight: bold;
    padding: 4px 13px 3px;
    -moz-text-shadow: 1px 1px 0 #fff;
    -webkit-text-shadow: 1px 1px 0 #fff;
    text-shadow: 1px 1px 0 #fff;
    white-space: nowrap;

    background: #EFEFEF; /* old browsers */
    background: -moz-linear-gradient(top, #f5f5f5 0%, #efefef 50%, #e5e5e5 51%, #dfdfdf 100%); /* firefox */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f5f5f5), color-stop(50%,#efefef), color-stop(51%,#e5e5e5), color-stop(100%,#dfdfdf)); /* webkit */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#f5f5f5', endColorstr='#dfdfdf',GradientType=0 ); /* ie */
}

.button:hover {
    border-color: #466899;
    color: #fff;
    text-decoration: none;
    -moz-text-shadow: 1px 1px 0 #222;
    -webkit-text-shadow: 1px 1px 0 #222;
    text-shadow: 1px 1px 0 #222;

    background: #6396D8; /* old browsers */
    background: -moz-linear-gradient(top, #6396D8 0%, #5A83BC 50%, #547AB7 51%, #466899 100%); /* firefox */
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#6396D8), color-stop(50%,#5A83BC), color-stop(51%,#547AB7), color-stop(100%,#466899)); /* webkit */
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#6396D8', endColorstr='#466899',GradientType=0 ); /* ie */
}

.newwindow { text-align: center; }

.header .version em {
    display: block;
    text-align: right;
}

#classdocs .item {
    border-bottom: 1px solid #466899;
    margin: 1em 0;
    padding: 1.5em;
}

#classdocs .item .params p,
    #classdocs .item .returns p,{
    display: inline;
}

#classdocs .item em code, #classdocs .item em.comment {
    color: green;
}

#classdocs .item em.comment a {
    color: green;
    text-decoration: underline;
}

#classdocs .foundat {
    font-size: 11px;
    font-style: normal;
}

.attrs .emits {
    margin-left: 2em;
    padding: .5em;
    border-left: 1px dashed #ccc;
}

abbr {
    border-bottom: 1px dashed #ccc;
    font-size: 80%;
    cursor: help;
}

.prettyprint li.L0,
.prettyprint li.L1,
.prettyprint li.L2,
.prettyprint li.L3,
.prettyprint li.L4,
.prettyprint li.L5,
.prettyprint li.L6,
.prettyprint li.L7,
.prettyprint li.L9,
.prettyprint li.L8 {
    list-style: decimal;
}

ul li p {
    margin-top: 0;
}

.method .name {
    font-size: 110%;
}

.apidocs .methods .extends .method,
.apidocs .properties .extends .property,
.apidocs .attrs .extends .attr,
.apidocs .events .extends .event {
    font-weight: bold;
}

.apidocs .methods .extends .inherited,
.apidocs .properties .extends .inherited,
.apidocs .attrs .extends .inherited,
.apidocs .events .extends .inherited {
    font-weight: normal;
}

#hd {
    background: whiteSmoke;
    background: -moz-linear-gradient(top,#DCDBD9 0,#F6F5F3 100%);
    background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#DCDBD9),color-stop(100%,#F6F5F3));
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#dcdbd9',endColorstr='#F6F5F3',GradientType=0);
    border-bottom: 1px solid #DFDFDF;
    padding: 0 15px 1px 20px;
    margin-bottom: 15px;
}

#hd img {
    margin-right: 10px;
    vertical-align: middle;
}

/* -- API Docs CSS ---------------------------------------------------------- */

/*
This file is organized so that more generic styles are nearer the top, and more
specific styles are nearer the bottom of the file. This allows us to take full
advantage of the cascade to avoid redundant style rules. Please respect this
convention when making changes.
*/

/* -- Generic TabView styles ------------------------------------------------ */

/*
These styles apply to all API doc tabviews. To change styles only for a
specific tabview, see the other sections below.
*/

.yui3-js-enabled .apidocs .tabview {
/*     visibility: hidden; /* Hide until the TabView finishes rendering. */ */
    _visibility: visible;
}

.apidocs .tabview.yui3-tabview-content { visibility: visible; }
/* .apidocs .tabview .yui3-tabview-panel { background: #fff; } */

/* -- Generic Content Styles ------------------------------------------------ */

/* Headings */
h2, h3, h4, h5, h6 {
    border: none;
    color: #30418C;
    font-weight: bold;
    text-decoration: none;
}

.link-docs {
    float: right;
    font-size: 15px;
    margin: 4px 4px 6px;
    padding: 6px 30px 5px;
}

.apidocs { zoom: 1; }

/* Generic box styles. */
.apidocs .box {
    border: 1px solid;
    border-radius: 3px;
    margin: 1em 0;
    padding: 0 1em;
}

/* A flag is a compact, capsule-like indicator of some kind. It's used to
   indicate private and protected items, item return types, etc. in an
   attractive and unobtrusive way. */
.apidocs .flag {
    background: #bababa;
    border-radius: 3px;
    color: #fff;
    font-size: 11px;
    margin: 0 0.5em;
    padding: 2px 4px 1px;
}

/* Class/module metadata such as "Uses", "Extends", "Defined in", etc. */
.apidocs .meta {
    background: #f9f9f9;
    border-color: #efefef;
    color: #555;
    font-size: 11px;
    padding: 3px 6px;
}

.apidocs .meta p { margin: 0; }

/* Deprecation warning. */
.apidocs .box.deprecated,
.apidocs .flag.deprecated {
    background: #fdac9f;
    border: 1px solid #fd7775;
}

.apidocs .box.deprecated p { margin: 0.5em 0; }
.apidocs .flag.deprecated { color: #333; }

/* Module/Class intro description. */
.apidocs .intro {
    background: #f0f1f8;
    border-color: #d4d8eb;
}

/* Loading spinners. */
#bd.loading .apidocs,
#api-list.loading .yui3-tabview-panel {
    background: #fff url(../img/spinner.gif) no-repeat center 70px;
    min-height: 150px;
}

#bd.loading .apidocs .content,
#api-list.loading .yui3-tabview-panel .apis {
    display: none;
}

.apidocs .no-visible-items { color: #666; }

/* Generic inline list. */
.apidocs ul.inline {
    display: inline;
    list-style: none;
    margin: 0;
    padding: 0;
}

.apidocs ul.inline li { display: inline; }

/* Comma-separated list. */
.apidocs ul.commas li:after { content: ','; }
.apidocs ul.commas li:last-child:after { content: ''; }

/* Keyboard shortcuts. */
kbd .cmd { font-family: Monaco, Helvetica; }

/* -- Generic Access Level styles ------------------------------------------- */
.apidocs .item.protected,
.apidocs .item.private,
.apidocs .index-item.protected,
.apidocs .index-item.deprecated,
.apidocs .index-item.private {
    display: none;
}

.show-deprecated .item.deprecated,
.show-deprecated .index-item.deprecated,
.show-protected .item.protected,
.show-protected .index-item.protected,
.show-private .item.private,
.show-private .index-item.private {
    display: block;
}

.hide-inherited .item.inherited,
.hide-inherited .index-item.inherited {
    display: none;
}

/* -- Generic Item Index styles --------------------------------------------- */
/* .apidocs .index { margin: 1.5em 0 3em; } */

.apidocs .index h3 {
    border-bottom: 1px solid #efefef;
    color: #333;
    font-size: 13px;
    margin: 2em 0 0.6em;
    padding-bottom: 2px;
}

.apidocs .index .no-visible-items { margin-top: 2em; }

.apidocs .index-list {
    border-color: #efefef;
    font-size: 12px;
    list-style: none;
    margin: 0;
    padding: 0;
    -moz-column-count: 4;
    -moz-column-gap: 10px;
    -moz-column-width: 170px;
    -ms-column-count: 4;
    -ms-column-gap: 10px;
    -ms-column-width: 170px;
    -o-column-count: 4;
    -o-column-gap: 10px;
    -o-column-width: 170px;
    -webkit-column-count: 4;
    -webkit-column-gap: 10px;
    -webkit-column-width: 170px;
    column-count: 4;
    column-gap: 10px;
    column-width: 170px;
}

.apidocs .no-columns .index-list {
    -moz-column-count: 1;
    -ms-column-count: 1;
    -o-column-count: 1;
    -webkit-column-count: 1;
    column-count: 1;
}

.apidocs .index-item { white-space: nowrap; }

.apidocs .index-item .flag {
    background: none;
    border: none;
    color: #afafaf;
    display: inline;
    margin: 0 0 0 0.2em;
    padding: 0;
}

/* -- Generic API item styles ----------------------------------------------- */
.apidocs .args {
    display: inline;
    margin: 0 0.5em;
}

.apidocs .flag.chainable { background: #46ca3b; }
.apidocs .flag.protected { background: #9b86fc; }
.apidocs .flag.private { background: #fd6b1b; }
.apidocs .flag.async { background: #356de4; }
.apidocs .flag.required { background: #e60923; }

.apidocs .item {
    border-bottom: 1px solid #efefef;
    margin: 1.5em 0 2em;
    padding-bottom: 2em;
}

.apidocs .item h4,
.apidocs .item h5,
.apidocs .item h6 {
    color: #333;
    font-family: inherit;
    font-size: 100%;
}

.apidocs .item .description p,
.apidocs .item pre.code {
    margin: 1em 0 0;
}

.apidocs .item .meta {
    background: none;
    border: none;
    padding: 0;
}

.apidocs .item .name {
    display: inline;
    font-size: 14px;
}

.apidocs .item .type,
.apidocs .item .type a,
.apidocs .returns-inline {
    color: #555;
}

.apidocs .item .type,
.apidocs .returns-inline {
    font-size: 11px;
    margin: 0 0 0 0;
}

.apidocs .item .type a { border-bottom: 1px dotted #afafaf; }
.apidocs .item .type a:hover { border: none; }

/* -- Item Parameter List --------------------------------------------------- */
.apidocs .params-list {
    list-style: square;
    margin: 1em 0 0 2em;
    padding: 0;
}

.apidocs .param { margin-bottom: 1em; }

.apidocs .param .type,
.apidocs .param .type a {
    color: #666;
}

.apidocs .param .type {
    margin: 0 0 0 0.5em;
    *margin-left: 0.5em;
}

.apidocs .param-name { font-weight: bold; }

/* -- Item "Emits" block ---------------------------------------------------- */
.apidocs .item .emits {
    background: #f9f9f9;
    border-color: #eaeaea;
}

/* -- Item "Returns" block -------------------------------------------------- */
.apidocs .item .returns .type,
.apidocs .item .returns .type a {
    font-size: 100%;
    margin: 0;
}

/* -- Class Constructor block ----------------------------------------------- */
.apidocs .constructor .item {
    border: none;
    padding-bottom: 0;
}

/* -- File Source View ------------------------------------------------------ */
.apidocs .file pre.code,
#doc .apidocs .file pre.prettyprint {
    background: inherit;
    border: none;
    overflow: visible;
    padding: 0;
}

.apidocs .L0,
.apidocs .L1,
.apidocs .L2,
.apidocs .L3,
.apidocs .L4,
.apidocs .L5,
.apidocs .L6,
.apidocs .L7,
.apidocs .L8,
.apidocs .L9 {
    background: inherit;
}

/* -- Submodule List -------------------------------------------------------- */
.apidocs .module-submodule-description {
    font-size: 12px;
    margin: 0.3em 0 1em;
}

.apidocs .module-submodule-description p:first-child { margin-top: 0; }

/* -- Sidebar TabView ------------------------------------------------------- */
#api-tabview { margin-top: 0.6em; }

#api-tabview-filter,
#api-tabview-panel {
    border: 1px solid #dfdfdf;
}

#api-tabview-filter {
    border-bottom: none;
    border-top: none;
    padding: 0.6em 10px 0 10px;
}

#api-tabview-panel { border-top: none; }
#api-filter { width: 97%; }

/* -- Content TabView ------------------------------------------------------- */
#classdocs .yui3-tabview-panel { border: none; }

/* -- Source File Contents -------------------------------------------------- */
.prettyprint li.L0,
.prettyprint li.L1,
.prettyprint li.L2,
.prettyprint li.L3,
.prettyprint li.L4,
.prettyprint li.L5,
.prettyprint li.L6,
.prettyprint li.L7,
.prettyprint li.L9,
.prettyprint li.L8 {
    list-style: decimal;
}

/* -- API options ----------------------------------------------------------- */
#api-options {
    font-size: 11px;
    margin-top: 2.2em;
    position: absolute;
    right: 1.5em;
}

/*#api-options label { margin-right: 0.6em; }*/

/* -- API list -------------------------------------------------------------- */
#api-list {
    margin-top: 1.5em;
    *zoom: 1;
}

.apis {
    font-size: 12px;
    line-height: 1.4;
    list-style: none;
    margin: 0;
    padding: 0.5em 0 0.5em 0.4em;
}

.apis a {
    border: 1px solid transparent;
    display: block;
    margin: 0 0 0 -4px;
    padding: 1px 4px 0;
    text-decoration: none;
    _border: none;
    _display: inline;
}

.apis a:hover,
.apis a:focus {
    background: #E8EDFC;
    background: -moz-linear-gradient(top, #e8edfc 0%, #becef7 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#E8EDFC), color-stop(100%,#BECEF7));
    border-color: #AAC0FA;
    border-radius: 3px;
    color: #333;
    outline: none;
}

.api-list-item a:hover,
.api-list-item a:focus {
    font-weight: bold;
    text-shadow: 1px 1px 1px #fff;
}

.apis .message { color: #888; }
.apis .result a { padding: 3px 5px 2px; }

.apis .result .type {
    right: 4px;
    top: 7px;
}

.api-list-item .yui3-highlight {
    font-weight: bold;
}

.yui3-skin-sam #classdocs .yui3-tabview-panel {
    background-color: transparent;
}

.yui3-skin-sam #classdocs .yui3-tabview-panel {
    border: none;
}

.yui3-skin-sam .yui3-tabview .yui3-tab,
.yui3-skin-sam .yui3-tabview .yui3-tab-selected,
.yui3-skin-sam .yui3-tabview .yui3-tab-hover {
    background: -moz-linear-gradient(center top , #F4F0EC 0%, #D6D2CE 100%) repeat scroll 0 0 transparent;
    border-bottom: 1px solid #DEDCD9;
    border-right: 1px solid #CDCBC8;
    border-left: 1px solid #CDCBC8;
    border-top: 1px solid #DADADA;
    color: #333333;
    text-decoration: none;
}
.yui3-skin-sam .yui3-tabview .yui3-tab-label,
.yui3-skin-sam .yui3-tabview .yui3-tab-selected .yui3-tab-label {
    border: none;
    background: none;
    font-size: 100%;
    color: #000;
}

.yui3-skin-sam .yui3-tabview .yui3-tab-selected,
.yui3-skin-sam .yui3-tabview .yui3-tab-hover {
    background: none;
    background-color: #fff;
    border-bottom-color: #FFFFFF;
    border-top: 2px solid #8193C9;
    font-weight: bold;
    color: #000;

}

.yui3-skin-sam .yui3-tabview-list {
    border-color: #DFDFDF;
    border-width: 0 0 1px;
}


text:
layout: page
title: "Daniel Hickman"
comments: true
description: "blanks"
keywords: "Daniel Hickman,CU,Boulder"
---
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://dl.dropboxusercontent.com/s/pc42nxpaw1ea4o9/highcharts.js?dl=0"></script>
<!-- <script src="../assets/js/highcharts.js"></script> -->
<style type="text/css">@font-face {
	font-family: "Bebas Neue";
	src: url(https://www.filehosting.org/file/details/544349/BebasNeue Regular.otf) format("opentype");
	}
	h1.Bebas {
		font-family: "Bebas Neue", Verdana, Tahoma;
	}
</style>
</head>

#### TEACHING INFORMATION

**College**: College of Arts and Sciences

**Classes taught**: ECON 1078, ECON 3818

#### ECON 1078: MATH TOOLS FOR ECON 1

**Terms taught**: Fall 2007, Spring 2008, Fall 2009

**Instructor rating**: 5.54

**Standard deviation in instructor rating**: 0.01

**Average grade** (4.0 scale): 2.79

**Standard deviation in grades** (4.0 scale): 0.11

**Average workload** (raw): 2.15

**Standard deviation in workload** (raw): 0.08

#### ECON 3818: INTRO TO STAT W/COMPUTER

**Terms taught**: Spring 2009, Spring 2010

**Instructor rating**: 5.59

**Standard deviation in instructor rating**: 0.12

**Average grade** (4.0 scale): 2.94

**Standard deviation in grades** (4.0 scale): 0.03

**Average workload** (raw): 2.29

**Standard deviation in workload** (raw): 0.02


text:
import org.eclipse.paho.client.mqttv3._
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence

import org.apache.spark.storage.StorageLevel
import org.apache.spark.streaming._
import org.apache.spark.streaming.StreamingContext._
import org.apache.spark.streaming.mqtt._
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.hadoop.conf.Configuration
import org.bson.BSONObject
import org.bson.BasicBSONObject

object MQTTApp {
  def main(args: Array[String]) {
    val logFile = "README.md" // Should be some file on your system
    val conf = new SparkConf().setAppName("Simple Application")
    //val sc = new SparkContext(conf)

    val ssc =   new StreamingContext(conf,  Seconds(2))

    val lines = MQTTUtils.createStream(ssc, "tcp://localhost", "spark", StorageLevel.MEMORY_ONLY_SER_2)

    val words = lines.flatMap(x => x.split(" "))
    val wordCounts = words.map(x => (x, 1)).reduceByKey(_ + _)

    wordCounts.print()
    ssc.start()
    ssc.awaitTermination()
  }
}


text:
          1
          2
          3
          4

          1. Llena tus datos: Necesitamos algunos datos personales para contactarnos contigo.

        <form  id="formulario" action="<?= base_url()?>cita/solicitud" method="post">

                     Nombres
                    <input  type= "text"  name="p_nombre" class= "form-control" aria-describedby= "basic-addon1" required="required">

                      Ap. Paterno
                     <input  type= "text"  name="p_apPaterno" class= "form-control" aria-describedby= "basic-addon1" required="required">

                     Ap. Materno
                    <input  type= "text"  name="p_apMaterno" class= "form-control" aria-describedby= "basic-addon1" required="required">

                      Celular
                     <input  type= "tel" pattern="[0-9]{9}"  name="p_celular" class= "form-control" aria-describedby= "basic-addon1" required="required">

                     Telefono
                    <input  type= "tel" pattern="[0-9]\S{5,8}" name="p_telefono" class= "form-control" aria-describedby= "basic-addon1" required="required">

            <button type="submit"  id="btn_buscarmedico" class="btn btn-info btn-large form-control" >Buscar Médico</button>

        </form>

 A TENER EN CUENTA

La separación de una "pre-cita" significa que la hora que solicite será refrencial
            y dependerá de la disponibilidad de no haberse concretado una cita previa a su solicitud; por eso nos contactaremos con usted para Registrar la CITA en consultorio

Estamos trabajando para brindarle un mejor servicio


text:
package com.notlob.jgrid.styles;

public enum AlignmentStyle {
	TOP_LEFT,
	TOP_CENTER,
	TOP_RIGHT,
	LEFT_CENTER,
	CENTER,
	RIGHT_CENTER,
	BOTTOM_LEFT,
	BOTTOM_CENTER,
	BOTTOM_RIGHT,
}


text:
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from '../services/auth.service';

@Injectable()
export class UserAuthGuard implements CanActivate {

    constructor(private authService: AuthService, private router: Router) { }

    canActivate() {
        console.log('CanActivate User' + this.authService.isLogged());
        if (this.authService.isLogged()) {
            return true;
        }
        this.router.navigate(['/login']);
        return false;
    }
}


text:
package com.microsoft.azure.management.cognitiveservices.v2017_04_18.implementation;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * The access keys for the cognitive services account.
 */
public class CognitiveServicesAccountKeysInner {
    /**
     * Gets the value of key 1.
     */
    @JsonProperty(value = "key1")
    private String key1;

    /**
     * Gets the value of key 2.
     */
    @JsonProperty(value = "key2")
    private String key2;

    /**
     * Get gets the value of key 1.
     *
     * @return the key1 value
     */
    public String key1() {
        return this.key1;
    }

    /**
     * Set gets the value of key 1.
     *
     * @param key1 the key1 value to set
     * @return the CognitiveServicesAccountKeysInner object itself.
     */
    public CognitiveServicesAccountKeysInner withKey1(String key1) {
        this.key1 = key1;
        return this;
    }

    /**
     * Get gets the value of key 2.
     *
     * @return the key2 value
     */
    public String key2() {
        return this.key2;
    }

    /**
     * Set gets the value of key 2.
     *
     * @param key2 the key2 value to set
     * @return the CognitiveServicesAccountKeysInner object itself.
     */
    public CognitiveServicesAccountKeysInner withKey2(String key2) {
        this.key2 = key2;
        return this;
    }

}


text:
mactest
=======

Test repo for my mac

blah blah local change

more changes


text:
package io.druid.query;

import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.CountAggregatorFactory;
import io.druid.query.aggregation.DoubleSumAggregatorFactory;
import io.druid.query.aggregation.PostAggregator;
import io.druid.query.aggregation.post.ArithmeticPostAggregator;
import io.druid.query.aggregation.post.ConstantPostAggregator;
import io.druid.query.aggregation.post.FieldAccessPostAggregator;
import org.junit.Assert;
import org.junit.Test;

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

/**
 */
public class QueriesTest
{
  @Test
  public void testVerifyAggregations() throws Exception
  {
    List<AggregatorFactory> aggFactories = Arrays.<AggregatorFactory>asList(
        new CountAggregatorFactory("count"),
        new DoubleSumAggregatorFactory("idx", "index"),
        new DoubleSumAggregatorFactory("rev", "revenue")
    );

    List<PostAggregator> postAggs = Arrays.<PostAggregator>asList(
        new ArithmeticPostAggregator(
            "addStuff",
            "+",
            Arrays.<PostAggregator>asList(
                new FieldAccessPostAggregator("idx", "idx"),
                new FieldAccessPostAggregator("count", "count")
            )
        )
    );

    boolean exceptionOccured = false;

    try {
      Queries.verifyAggregations(aggFactories, postAggs);
    }
    catch (IllegalArgumentException e) {
      exceptionOccured = true;
    }

    Assert.assertFalse(exceptionOccured);
  }

  @Test
  public void testVerifyAggregationsMissingVal() throws Exception
  {
    List<AggregatorFactory> aggFactories = Arrays.<AggregatorFactory>asList(
        new CountAggregatorFactory("count"),
        new DoubleSumAggregatorFactory("idx", "index"),
        new DoubleSumAggregatorFactory("rev", "revenue")
    );

    List<PostAggregator> postAggs = Arrays.<PostAggregator>asList(
        new ArithmeticPostAggregator(
            "addStuff",
            "+",
            Arrays.<PostAggregator>asList(
                new FieldAccessPostAggregator("idx", "idx2"),
                new FieldAccessPostAggregator("count", "count")
            )
        )
    );

    boolean exceptionOccured = false;

    try {
      Queries.verifyAggregations(aggFactories, postAggs);
    }
    catch (IllegalArgumentException e) {
      exceptionOccured = true;
    }

    Assert.assertTrue(exceptionOccured);
  }

  @Test
  public void testVerifyAggregationsMultiLevel() throws Exception
  {
    List<AggregatorFactory> aggFactories = Arrays.<AggregatorFactory>asList(
        new CountAggregatorFactory("count"),
        new DoubleSumAggregatorFactory("idx", "index"),
        new DoubleSumAggregatorFactory("rev", "revenue")
    );

    List<PostAggregator> postAggs = Arrays.<PostAggregator>asList(
        new ArithmeticPostAggregator(
            "divideStuff",
            "/",
            Arrays.<PostAggregator>asList(
                new ArithmeticPostAggregator(
                    "addStuff",
                    "+",
                    Arrays.asList(
                        new FieldAccessPostAggregator("idx", "idx"),
                        new ConstantPostAggregator("const", 1)
                    )
                ),
                new ArithmeticPostAggregator(
                    "subtractStuff",
                    "-",
                    Arrays.asList(
                        new FieldAccessPostAggregator("rev", "rev"),
                        new ConstantPostAggregator("const", 1)
                    )
                )
            )
        ),
        new ArithmeticPostAggregator(
            "addStuff",
            "+",
            Arrays.<PostAggregator>asList(
                new FieldAccessPostAggregator("divideStuff", "divideStuff"),
                new FieldAccessPostAggregator("count", "count")
            )
        )
    );

    boolean exceptionOccured = false;

    try {
      Queries.verifyAggregations(aggFactories, postAggs);
    }
    catch (IllegalArgumentException e) {
      exceptionOccured = true;
    }

    Assert.assertFalse(exceptionOccured);
  }

  @Test
  public void testVerifyAggregationsMultiLevelMissingVal() throws Exception
  {
    List<AggregatorFactory> aggFactories = Arrays.<AggregatorFactory>asList(
        new CountAggregatorFactory("count"),
        new DoubleSumAggregatorFactory("idx", "index"),
        new DoubleSumAggregatorFactory("rev", "revenue")
    );

    List<PostAggregator> postAggs = Arrays.<PostAggregator>asList(
        new ArithmeticPostAggregator(
            "divideStuff",
            "/",
            Arrays.<PostAggregator>asList(
                new ArithmeticPostAggregator(
                    "addStuff",
                    "+",
                    Arrays.asList(
                        new FieldAccessPostAggregator("idx", "idx"),
                        new ConstantPostAggregator("const", 1)
                    )
                ),
                new ArithmeticPostAggregator(
                    "subtractStuff",
                    "-",
                    Arrays.asList(
                        new FieldAccessPostAggregator("rev", "rev2"),
                        new ConstantPostAggregator("const", 1)
                    )
                )
            )
        ),
        new ArithmeticPostAggregator(
            "addStuff",
            "+",
            Arrays.<PostAggregator>asList(
                new FieldAccessPostAggregator("divideStuff", "divideStuff"),
                new FieldAccessPostAggregator("count", "count")
            )
        )
    );

    boolean exceptionOccured = false;

    try {
      Queries.verifyAggregations(aggFactories, postAggs);
    }
    catch (IllegalArgumentException e) {
      exceptionOccured = true;
    }

    Assert.assertTrue(exceptionOccured);
  }
}


text:
namespace vespalib::eval {

namespace {

struct CopyValue {
    template <typename CT>
    static std::unique_ptr<Value> invoke(const Value &value,
                                         const ValueType &type,
                                         const ValueBuilderFactory &factory)
    {
        size_t num_mapped = type.count_mapped_dimensions();
        size_t dense_size = type.dense_subspace_size();
        const auto & idx = value.index();
        auto input_cells = value.cells().typify<CT>();
        auto builder = factory.create_value_builder<CT>(type, num_mapped, dense_size, idx.size());
        std::vector<string_id> addr(num_mapped);
        if (num_mapped == 0) {
            assert(idx.size() == 1);
            auto array_ref = builder->add_subspace(addr);
            for (size_t i = 0; i < dense_size; ++i) {
                array_ref[i] = input_cells[i];
            }
        } else {
            auto view = idx.create_view({});
            view->lookup({});
            std::vector<string_id*> addr_fetch;
            addr_fetch.reserve(num_mapped);
            for (auto & label : addr) {
                addr_fetch.push_back(&label);
            }
            size_t subspace_idx;
            while (view->next_result(addr_fetch, subspace_idx)) {
                auto array_ref = builder->add_subspace(addr);
                for (size_t i = 0; i < dense_size; ++i) {
                    array_ref[i] = input_cells[(dense_size * subspace_idx) + i];
                }
            }
        }
        return builder->build(std::move(builder));
    }
};

} // namespace <unnamed>

std::unique_ptr<Value>
ValueBuilderFactory::copy(const Value &value) const
{
    const auto & type = value.type();
    return typify_invoke<1,TypifyCellType,CopyValue>(type.cell_type(),
                                                     value, type, *this);
}

}


text:
/// Copyright (c) 2012 Ecma International.  All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms").   Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
 * @path ch15/15.2/15.2.3/15.2.3.7/15.2.3.7-6-a-25.js
 * @description Object.defineProperties - 'P' doesn't exist in 'O', test TypeError is thrown when 'O' is not extensible (8.12.9 step 3)
 */

function testcase() {
        var obj = {};
        Object.preventExtensions(obj);

        try {
            Object.defineProperties(obj, {
                prop: {
                    value: 12,
                    configurable: true
                }
            });
            return false;
        } catch (e) {
            return e instanceof TypeError && !obj.hasOwnProperty("prop");
        }
    }
runTestCase(testcase);


text:
package scanner

import (
	"bufio"
	"encoding/gob"
	"errors"
	"io"
	"os"
	"path"
	"time"

	"github.com/Cloud-Foundations/Dominator/lib/filesystem"
	"github.com/Cloud-Foundations/Dominator/lib/format"
	"github.com/Cloud-Foundations/Dominator/lib/fsutil"
	"github.com/Cloud-Foundations/Dominator/lib/hash"
	"github.com/Cloud-Foundations/Dominator/lib/image"
	"github.com/Cloud-Foundations/Dominator/lib/log"
)

var timeFormat string = "02 Jan 2006 15:04:05.99 MST"

type unreferencedObject struct {
	Hash   hash.Hash
	Length uint64
	Age    time.Time
}

type unreferencedObjectsEntry struct {
	object unreferencedObject
	prev   *unreferencedObjectsEntry
	next   *unreferencedObjectsEntry
}

type unreferencedObjectsList struct {
	totalBytes          uint64
	oldest              *unreferencedObjectsEntry
	newest              *unreferencedObjectsEntry
	hashToEntry         map[hash.Hash]*unreferencedObjectsEntry
	lastRegeneratedTime time.Time
}

func loadUnreferencedObjects(fName string) (*unreferencedObjectsList, error) {
	file, err := os.Open(fName)
	if err != nil {
		if !os.IsNotExist(err) {
			return nil, err
		}
		return &unreferencedObjectsList{
			hashToEntry: make(map[hash.Hash]*unreferencedObjectsEntry),
		}, nil
	}
	defer file.Close()
	reader := fsutil.NewChecksumReader(bufio.NewReader(file))
	decoder := gob.NewDecoder(reader)
	var length uint64
	if err := decoder.Decode(&length); err != nil {
		return nil, errors.New("error decoding list length: " + err.Error())
	}
	list := &unreferencedObjectsList{
		hashToEntry: make(map[hash.Hash]*unreferencedObjectsEntry, length),
	}
	for count := uint64(0); count < length; count++ {
		var object unreferencedObject
		if err := decoder.Decode(&object); err != nil {
			return nil, errors.New("error decoding object: " + err.Error())
		}
		entry := &unreferencedObjectsEntry{object: object}
		list.addEntry(entry)
	}
	if err := reader.VerifyChecksum(); err != nil {
		return nil, err
	}
	return list, nil
}

func (list *unreferencedObjectsList) write(w io.Writer,
	logger log.Logger) error {
	writer := fsutil.NewChecksumWriter(w)
	encoder := gob.NewEncoder(writer)
	if err := encoder.Encode(uint64(len(list.hashToEntry))); err != nil {
		return err
	}
	nWritten := 0
	for entry := list.oldest; entry != nil; entry = entry.next {
		if err := encoder.Encode(entry.object); err != nil {
			return err
		}
		nWritten++
	}
	if len(list.hashToEntry) != nWritten {
		logger.Panicf("unref objects list length: %d != num entries: %d\n",
			len(list.hashToEntry), nWritten)
	}
	return writer.WriteChecksum()
}

func (list *unreferencedObjectsList) addEntry(entry *unreferencedObjectsEntry) {
	entry.prev = list.newest
	if list.oldest == nil {
		list.oldest = entry
	} else {
		list.newest.next = entry
	}
	list.newest = entry
	list.hashToEntry[entry.object.Hash] = entry
	list.totalBytes += entry.object.Length
}

// Returns true if object was added, else false if object was already on list.
func (list *unreferencedObjectsList) addObject(hashVal hash.Hash,
	length uint64) bool {
	if _, ok := list.hashToEntry[hashVal]; !ok {
		object := unreferencedObject{hashVal, length, time.Now()}
		list.addEntry(&unreferencedObjectsEntry{object: object})
		return true
	}
	return false
}

func (list *unreferencedObjectsList) list() map[hash.Hash]uint64 {
	objectsMap := make(map[hash.Hash]uint64, len(list.hashToEntry))
	for entry := list.oldest; entry != nil; entry = entry.next {
		objectsMap[entry.object.Hash] = entry.object.Length
	}
	return objectsMap
}

// Returns true if object was removed, else false (if not on list).
func (list *unreferencedObjectsList) removeObject(hashVal hash.Hash) bool {
	entry := list.hashToEntry[hashVal]
	if entry == nil {
		return false
	}
	delete(list.hashToEntry, hashVal)
	if entry.prev == nil {
		list.oldest = entry.next
	} else {
		entry.prev.next = entry.next
	}
	if entry.next == nil {
		list.newest = entry.prev
	} else {
		entry.next.prev = entry.prev
	}
	list.totalBytes -= entry.object.Length
	return true
}

func (imdb *ImageDataBase) maybeAddToUnreferencedObjectsList(
	fs *filesystem.FileSystem) {
	// First get a list of objects in the image being deleted.
	objects := fs.GetObjects()
	// Scan all remaining images and remove their objects from the list.
	for _, image := range imdb.imageMap {
		image.ForEachObject(func(hashVal hash.Hash) error {
			delete(objects, hashVal)
			return nil
		})
	}
	changed := false
	for object, size := range objects {
		if imdb.unreferencedObjects.addObject(object, size) {
			changed = true
		}
	}
	// Run garbage collector and save new list in the background.
	unreferencedBytes := imdb.unreferencedObjects.totalBytes
	go func() {
		var bytesToDelete uint64
		maxUnrefData := uint64(*imageServerMaxUnrefData)
		if maxUnrefData > 0 && unreferencedBytes > maxUnrefData {
			bytesToDelete = unreferencedBytes - maxUnrefData
		}
		var maxAge time.Time
		if *imageServerMaxUnrefAge > 0 {
			maxAge = time.Now().Add(-*imageServerMaxUnrefAge)
		}
		if bytesToDelete > 0 || !maxAge.IsZero() {
			nDeleted, _ := imdb.collectGarbage(bytesToDelete, maxAge)
			if nDeleted > 0 {
				return // Garbage collector saved unreferenced objects list.
			}
		}
		if changed {
			imdb.saveUnreferencedObjectsList(true)
		}
	}()
}

func (imdb *ImageDataBase) removeFromUnreferencedObjectsListAndSave(
	img *image.Image) {
	if imdb.removeFromUnreferencedObjectsList(img) {
		imdb.saveUnreferencedObjectsList(false)
	}
}

func (imdb *ImageDataBase) removeFromUnreferencedObjectsList(
	img *image.Image) bool {
	changed := false
	img.ForEachObject(func(hashVal hash.Hash) error {
		if imdb.unreferencedObjects.removeObject(hashVal) {
			changed = true
		}
		return nil
	})
	return changed
}

func (imdb *ImageDataBase) saveUnreferencedObjectsList(grabLock bool) {
	if grabLock {
		imdb.RLock()
		defer imdb.RUnlock()
	}
	if err := imdb.writeUnreferencedObjectsList(); err != nil {
		imdb.logger.Printf("Error writing unreferenced objects list: %s\n",
			err)
	}
}

func (imdb *ImageDataBase) writeUnreferencedObjectsList() error {
	filename := path.Join(imdb.baseDir, unreferencedObjectsFile)
	file, err := fsutil.CreateRenamingWriter(filename, filePerms)
	if err != nil {
		return err
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	defer writer.Flush()
	return imdb.unreferencedObjects.write(writer, imdb.logger)
}

func (imdb *ImageDataBase) garbageCollector(bytesToDelete uint64) (
	uint64, error) {
	return imdb.collectGarbage(bytesToDelete, time.Time{})
}

// This grabs and releases the lock.
func (imdb *ImageDataBase) collectGarbage(bytesToDelete uint64,
	deleteBefore time.Time) (uint64, error) {
	if bytesToDelete < 1 && deleteBefore.IsZero() {
		return 0, nil
	}
	if deleteBefore.IsZero() {
		imdb.logger.Printf("Garbage collector deleting: %s\n",
			format.FormatBytes(bytesToDelete))
	} else {
		imdb.logger.Printf("Garbage collector deleting: %s or before: %s\n",
			format.FormatBytes(bytesToDelete), deleteBefore.Format(timeFormat))
	}
	imdb.Lock()
	var firstEntryToDelete *unreferencedObjectsEntry
	entry := imdb.unreferencedObjects.oldest
	var nObjectsDeleted uint64
	var nBytesDeleted uint64
	for ; entry != nil && (nBytesDeleted < bytesToDelete ||
		entry.object.Age.Before(deleteBefore)); entry = entry.next {
		firstEntryToDelete = imdb.unreferencedObjects.oldest
		delete(imdb.unreferencedObjects.hashToEntry, entry.object.Hash)
		nObjectsDeleted++
		nBytesDeleted += entry.object.Length
	}
	imdb.unreferencedObjects.totalBytes -= nBytesDeleted
	imdb.unreferencedObjects.oldest = entry
	if entry == nil {
		imdb.unreferencedObjects.newest = nil
	} else if entry.prev != nil {
		entry.prev.next = nil
		entry.prev = nil
	}
	imdb.Unlock()
	if firstEntryToDelete == nil {
		imdb.logger.Println("Garbage collector: nothing to delete")
		return 0, nil
	}
	nBytesDeleted = 0
	var err error
	for entry := firstEntryToDelete; entry != nil; entry = entry.next {
		if e := imdb.objectServer.DeleteObject(entry.object.Hash); e != nil {
			if err == nil {
				err = e
			}
		} else {
			nBytesDeleted += entry.object.Length
		}
	}
	imdb.saveUnreferencedObjectsList(true)
	imdb.logger.Printf("Garbage collector deleted: %s in: %d objects\n",
		format.FormatBytes(nBytesDeleted), nObjectsDeleted)
	return nBytesDeleted, err
}

// This grabs and releases the lock.
func (imdb *ImageDataBase) maybeRegenerateUnreferencedObjectsList() {
	imdb.RLock()
	lastRegeneratedTime := imdb.unreferencedObjects.lastRegeneratedTime
	imdb.RUnlock()
	lastMutationTime := imdb.objectServer.LastMutationTime()
	if lastMutationTime.After(lastRegeneratedTime) {
		imdb.regenerateUnreferencedObjectsList()
	}
}

// This grabs and releases the lock.
func (imdb *ImageDataBase) regenerateUnreferencedObjectsList() {
	scanTime := time.Now()
	// First generate list of currently unused objects.
	objectsMap := imdb.objectServer.ListObjectSizes()
	imdb.Lock()
	defer imdb.Unlock()
	for _, image := range imdb.imageMap {
		image.ForEachObject(func(hashVal hash.Hash) error {
			delete(objectsMap, hashVal)
			return nil
		})
	}
	changed := false
	// Now add unused objects to cached list.
	for hashVal, length := range objectsMap {
		if imdb.unreferencedObjects.addObject(hashVal, length) {
			changed = true
		}
	}
	// Finally remove objects from cached list which are no longer unreferenced.
	for entry := imdb.unreferencedObjects.oldest; entry != nil; {
		hashVal := entry.object.Hash
		entry = entry.next
		if _, ok := objectsMap[hashVal]; !ok {
			if imdb.unreferencedObjects.removeObject(hashVal) {
				changed = true
			}
		}
	}
	if changed {
		imdb.saveUnreferencedObjectsList(false)
	}
	imdb.unreferencedObjects.lastRegeneratedTime = scanTime
}

// This grabs and releases the lock.
func (imdb *ImageDataBase) garbageCollectorAddCallback(hashVal hash.Hash,
	length uint64, isNew bool) {
	imdb.Lock()
	defer imdb.Unlock()
	// Move added objects (whether new or old) to the back of the unreferenced
	// list if they are unreferenced, as they are likely to be referenced soon.
	if imdb.unreferencedObjects.removeObject(hashVal) {
		imdb.unreferencedObjects.addObject(hashVal, length)
	}
}

func (imdb *ImageDataBase) periodicGarbageCollector() {
	if *imageServerMaxUnrefData < 1 && *imageServerMaxUnrefAge < 1 {
		return
	}
	maxUnrefData := uint64(*imageServerMaxUnrefData)
	for ; ; time.Sleep(time.Minute) {
		var bytesToDelete uint64
		var maxAge time.Time
		imdb.RLock()
		unreferencedBytes := imdb.unreferencedObjects.totalBytes
		if maxUnrefData > 0 && unreferencedBytes > maxUnrefData {
			bytesToDelete = unreferencedBytes - maxUnrefData
		}
		if *imageServerMaxUnrefAge > 0 &&
			imdb.unreferencedObjects.oldest != nil {
			ageLimit := time.Now().Add(-*imageServerMaxUnrefAge)
			if imdb.unreferencedObjects.oldest.object.Age.Before(ageLimit) {
				maxAge = ageLimit
			}
		}
		imdb.RUnlock()
		if bytesToDelete > 0 || !maxAge.IsZero() {
			imdb.collectGarbage(bytesToDelete, maxAge)
		}
	}
}


text:
<?php

namespace PlatformBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Comments
 *
 * @ORM\Table(name="comments")
 * @ORM\Entity(repositoryClass="PlatformBundle\Repository\CommentRepository")
 */
class Comment
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="pseudo", type="string", length=255, nullable=true)
     */
    private $pseudo;

    /**
     * @var string
     *
     * @ORM\Column(name="email", type="string", length=255, nullable=true)
     */
    private $email;

    /**
     * @var string
     *
     * @ORM\Column(name="comment", type="text")
     */
    private $comment;

    /**
     * @var bool
     *
     * @ORM\Column(name="approved", type="boolean", nullable=true)
     */
    private $approved;

    /**
     * @var bool
     *
     * @ORM\Column(name="view", type="boolean")
     */
    private $view;

    /**
     * @var string
     *
     * @ORM\Column(name="ipaddress", type="string", length=255, nullable=true)
     */
    private $ipaddress;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=true)
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=true)
     */
    private $updatedAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="deleted_at", type="datetime", nullable=true)
     */
    private $deletedAt;

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set pseudo
     *
     * @param string $pseudo
     *
     * @return Comment
     */
    public function setPseudo($pseudo)
    {
        $this->pseudo = $pseudo;

        return $this;
    }

    /**
     * Get pseudo
     *
     * @return string
     */
    public function getPseudo()
    {
        return $this->pseudo;
    }

    /**
     * Set email
     *
     * @param string $email
     *
     * @return Comment
     */
    public function setEmail($email)
    {
        $this->email = $email;

        return $this;
    }

    /**
     * Get email
     *
     * @return string
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * Set comment
     *
     * @param string $comment
     *
     * @return Comment
     */
    public function setComment($comment)
    {
        $this->comment = $comment;

        return $this;
    }

    /**
     * Get comment
     *
     * @return string
     */
    public function getComment()
    {
        return $this->comment;
    }

    /**
     * Set approved
     *
     * @param boolean $approved
     *
     * @return Comment
     */
    public function setApproved($approved)
    {
        $this->approved = $approved;

        return $this;
    }

    /**
     * Get approved
     *
     * @return bool
     */
    public function getApproved()
    {
        return $this->approved;
    }

    /**
     * Set view
     *
     * @param boolean $view
     *
     * @return Comment
     */
    public function setView($view)
    {
        $this->view = $view;

        return $this;
    }

    /**
     * Get view
     *
     * @return bool
     */
    public function getView()
    {
        return $this->view;
    }

    /**
     * Set ipaddress
     *
     * @param string $ipaddress
     *
     * @return Comment
     */
    public function setIpaddress($ipaddress)
    {
        $this->ipaddress = $ipaddress;

        return $this;
    }

    /**
     * Get ipaddress
     *
     * @return string
     */
    public function getIpaddress()
    {
        return $this->ipaddress;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     *
     * @return Comment
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     *
     * @return Comment
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set deletedAt
     *
     * @param \DateTime $deletedAt
     *
     * @return Comment
     */
    public function setDeletedAt($deletedAt)
    {
        $this->deletedAt = $deletedAt;

        return $this;
    }

    /**
     * Get deletedAt
     *
     * @return \DateTime
     */
    public function getDeletedAt()
    {
        return $this->deletedAt;
    }
}


text:
(function($) {

  $.fn.date = function() {

    return this.each(function() {

      var input  = $(this).attr('type', 'text');
      var hidden = input.next();
      var format = input.data('format');
      var val    = input.val();
      var date   = val ? moment(val).format(format) : null;

      input.attr('placeholder', format);
      input.val(date);
      input.on('change', function() {
        hidden.val(moment(input.val()).format('YYYY-MM-DD'));
      });

      new Pikaday({
        field    : this,
        firstDay : 1,
        format   : format,
        i18n     : input.data('i18n'),
        onSelect : function(date) {
          hidden.val(moment(date).format('YYYY-MM-DD'));
        }
      });

    });

  };

})(jQuery);


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- From: file:/G:/uno-src/euamomeupet/android-app/app/src/main/res/values-v11/styles.xml -->
    <eat-comment/>
    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
        <!-- API 11 theme customizations can go here. -->
    </style>
</resources>


text:
package com.example.newbiechen.simpledependencedemo.model.net.api;

import com.example.newbiechen.simpledependencedemo.model.bean.ArticleBean;
import com.example.newbiechen.simpledependencedemo.model.bean.RecommendBean;
import com.example.newbiechen.simpledependencedemo.model.bean.ResponseBean;

import java.util.List;

import io.reactivex.Observable;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

/**
 * Created by newbiechen on 17-4-3.
 */

public interface ArticleApi {

    @GET("day/{year}/{month}/{day}")
    Observable<ResponseBean<RecommendBean>> getRecommendBean(@Path("year")String year, @Path("month")String month,
                                                             @Path("day")String day);

    @GET("data/{type}/10/{page}")
    Observable<ResponseBean<List<ArticleBean>>> getArticleList(@Path("type")String type,@Path("page") String page);
}


text:
using System;
using System.IO;
#if ! __UNIFIED__
using MonoTouch.UIKit;
using MonoTouch.Foundation;
#else
using UIKit;
using Foundation;
#endif
using System.Runtime.InteropServices;

namespace Xamarin.Social
{
	class NSDataStream : Stream
	{
		NSData data;
		uint pos;

		public NSDataStream (NSData data)
		{
			this.data = data;
		}

		protected override void Dispose (bool disposing)
		{
			if (data != null) {
				data.Dispose ();
				data = null;
			}
		}

		public override void Flush ()
		{
		}

		public override int Read (byte[] buffer, int offset, int count)
		{
			if (pos >= data.Length) {
				return 0;
			}
			else {
				#if ! __UNIFIED__
				var len = (int)Math.Min (count, data.Length - pos);
				#else
				var len = (int)Math.Min (count, (double)(data.Length - pos));
				#endif

				Marshal.Copy (new IntPtr (data.Bytes.ToInt64 () + pos), buffer, offset, len);
				pos += (uint)len;
				return len;
			}
		}

		public override long Seek (long offset, SeekOrigin origin)
		{
			throw new NotSupportedException ();
		}

		public override void SetLength (long value)
		{
			throw new NotSupportedException ();
		}

		public override void Write (byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException ();
		}

		public override bool CanRead {
			get {
				return true;
			}
		}

		public override bool CanSeek {
			get {
				return false;
			}
		}

		public override bool CanWrite {
			get {
				return false;
			}
		}

		public override long Length {
			get {
				// override does not allow nint
				#if ! __UNIFIED__
				return data.Length;
				#else
				return (long) data.Length;
				#endif
			}
		}

		public override long Position {
			get {
				return pos;
			}
			set {
			}
		}
	}
}


text:
Mikrotik API for swift running on ubuntu 16.10 or mac osx

https://wiki.mikrotik.com/wiki/Manual:API

BUILD ON MAC OSX

run sh generate-xcodeproj.sh

BUILD ON UBUNTU

thư viện yêu cầu
  clang , libmysqlclient-dev , openssl

run swift build


text:
package org.osgi.service.cm;

/**
 * An {@code Exception} class to inform the Configuration Admin service of
 * problems with configuration data.
 *
 * @author $Id: d4646fc2a8227d38ee0815407ee3578de0188541 $
 */
public class ConfigurationException extends Exception {
	static final long		serialVersionUID	= -1690090413441769377L;

	private final String	property;
	private final String	reason;

	/**
	 * Create a {@code ConfigurationException} object.
	 *
	 * @param property name of the property that caused the problem,
	 *        {@code null} if no specific property was the cause
	 * @param reason reason for failure
	 */
	public ConfigurationException(String property, String reason) {
		super(property + " : " + reason);
		this.property = property;
		this.reason = reason;
	}

	/**
	 * Create a {@code ConfigurationException} object.
	 *
	 * @param property name of the property that caused the problem,
	 *        {@code null} if no specific property was the cause
	 * @param reason reason for failure
	 * @param cause The cause of this exception.
	 * @since 1.2
	 */
	public ConfigurationException(String property, String reason, Throwable cause) {
		super(property + " : " + reason, cause);
		this.property = property;
		this.reason = reason;
	}

	/**
	 * Return the property name that caused the failure or null.
	 *
	 * @return name of property or null if no specific property caused the
	 *         problem
	 */
	public String getProperty() {
		return property;
	}

	/**
	 * Return the reason for this exception.
	 *
	 * @return reason of the failure
	 */
	public String getReason() {
		return reason;
	}

	/**
	 * Returns the cause of this exception or {@code null} if no cause was set.
	 *
	 * @return The cause of this exception or {@code null} if no cause was set.
	 * @since 1.2
	 */
	@Override
	public Throwable getCause() {
		return super.getCause();
	}

	/**
	 * Initializes the cause of this exception to the specified value.
	 *
	 * @param cause The cause of this exception.
	 * @return This exception.
	 * @throws IllegalArgumentException If the specified cause is this
	 *         exception.
	 * @throws IllegalStateException If the cause of this exception has already
	 *         been set.
	 * @since 1.2
	 */
	@Override
	public Throwable initCause(Throwable cause) {
		return super.initCause(cause);
	}
}


text:
var assert = require('assert')
  , fs = require('fs')

module.exports = function (_, dir, finish, gm) {

  var sub = gm.subClass({ subclassed: true });
  var s = sub('test').options({ setWithMethod: 2 });
  var g = gm('test').options({ hellowwww: 'there' });

  assert.equal(2, s._options.setWithMethod);
  assert.equal(true, s._options.subclassed);
  assert.equal('there', g._options.hellowwww);
  assert.equal(undefined, g._options.setWithMethod);
  assert.equal(undefined, s._options.hellowwww);
  assert.equal(undefined, g._options.subclassed);

  /// subclass options
  var s2 = sub('another');
  assert.equal(true, s2._options.subclassed);
  assert.equal(undefined, s2._options.setWithMethod);

  var writeFile = dir + '/IM-negative' + Math.random() + '.png';
  var imageMagick = gm.subClass({ imageMagick: true });

  imageMagick(dir + '/photo.JPG')
  .negative()
  .write(writeFile, function (err, _1, _2, cmd) {
    if (err) return finish(err);

    assert.ok(/^convert /.test(cmd));

    fs.stat(writeFile, function (err) {
      if (err) return finish(new Error('imagemagick did not write file'));
      try {
        fs.unlinkSync(writeFile);
      } catch (e) {}

      /// inline options
      gm(dir + '/photo.JPG')
      .negative()
      .options({ imageMagick: true })
      .write(writeFile, function (err, _1, _2, cmd) {
        if (err) return finish(err);

        assert.ok(/^convert /.test(cmd));

        fs.stat(writeFile, function (err) {
          if (err) return finish(new Error('imagemagick did not write file'));
          try {
            fs.unlinkSync(writeFile);
          } catch (e) {}
          finish();
        });
      });
    });
  });
}


text:
package edu.duke.cabig.c3pr.domain;

import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.Transient;

import com.semanticbits.coppa.domain.annotations.RemoteEntity;
import com.semanticbits.coppa.domain.annotations.RemoteProperty;
import com.semanticbits.coppa.domain.annotations.RemoteUniqueId;

import edu.duke.cabig.c3pr.infrastructure.RemoteStudyResolver;

/**
 * @author Vinay Gangoli
 */

@Entity
@DiscriminatorValue("Remote")
@RemoteEntity(entityResolver = RemoteStudyResolver.class)
public class RemoteStudy extends Study {

	private String externalId;

	public RemoteStudy(){
		super();
	}

	public RemoteStudy(boolean forSearchByExample){
		super(forSearchByExample);
	}

	@RemoteUniqueId
	@RemoteProperty
	public String getExternalId() {
		return externalId;
	}

	public void setExternalId(String externalId) {
		this.externalId = externalId;
	}

	@Transient
    public String getNciInstituteCode() {
		return externalId;
    }

    /*@Transient
     * public String getAssignedIdentifier() {
		for(OrganizationAssignedIdentifier oai: getOrganizationAssignedIdentifiers()){
			if(oai.getType().equals(OrganizationIdentifierTypeEnum.NCI)){
				return oai.getValue();
			}
		}
		return "";
    } */

}


text:
<head>
  <!-- Canonical link to help search engines -->
  <link rel="canonical" href="{{ site.baseurl }}{{ page.url }}">

  <!-- Basic meta elements -->
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <!--   Dublin Core metadata for Zotero -->
  <meta name="DC.title" content="{{ page.title }}" />
  <meta name="DC.creator" content="{{ page.author }}" />
  <meta name="DC.date" content="2016" />
  <meta name="DC.rights" content="{{ page.rights }}" />
  <meta name="DC.source" content="{{ site.title }}" />

  <title>
    {% if page.title == "Home" %}
      {{ site.title }}
    {% else %}
      {{ page.title }}
    {% endif %}
  </title>

  <!-- CSS links -->
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/poole.css">
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/syntax.css">
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/lanyon.css">
  <link rel="stylesheet" href="{{ site.baseurl }}/public/css/ed.css">

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="180x180" href="{{ site.baseurl }}/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="{{ site.baseurl }}/public/favicon.ico">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="org.ibase4j.mapper.SysMsgConfigMapper">
	<select id="selectIdPage" resultType="java.lang.Long">
		select id_ from sys_msg_config
		<where>
			<if test="cm.keyword != null and cm.keyword != ''">
				and (
					sms_plat_account like CONCAT('%',#{cm.keyword},'%')
					or sms_plat_password like CONCAT('%',#{cm.keyword},'%')
					or send_phone like CONCAT('%',#{cm.keyword},'%')
					or order_is_send like CONCAT('%',#{cm.keyword},'%')
					or pay_is_send like CONCAT('%',#{cm.keyword},'%')
					or send_goods_is_send like CONCAT('%',#{cm.keyword},'%')
					or regist_is_send like CONCAT('%',#{cm.keyword},'%')
					or advice_goods_is_send like CONCAT('%',#{cm.keyword},'%')
				)
			</if>
		</where>
	</select>
</mapper>


text:
<?php

namespace Doctrine\Tests\ODM\PHPCR\Query\Builder;

use Doctrine\ODM\PHPCR\Query\Builder\Where;
use PHPCR\Query\QOM\QueryObjectModelConstantsInterface as QOMConstants;

class OrderByTest extends NodeTestCase
{
    public function provideInterface()
    {
        return array(
            array('asc', 'Ordering', array(
                QOMConstants::JCR_ORDER_ASCENDING,
            )),
            array('desc', 'Ordering', array(
                QOMConstants::JCR_ORDER_DESCENDING,
            )),
        );
    }
}


text:
# Quantity queries

This guide allows to create quantity queries using only css.

Based in [Use Quantity Queries to Make Your CSS Quantity-Aware](http://www.hongkiat.com/blog/quantity-queries-css-quantity-aware/) article.

```css
/* At least 5 */
ul li:nth-last-child(n+5),
ul li:nth-last-child(n+5) ~ li {
    border: 2px dashed;
}

/* At most 5 */
ul li:nth-last-child(-n+5):first-child,
ul li:nth-last-child(-n+5):first-child ~ li {
    background-color: yellow;
}

/* Between 5 and 8 */
ul li:nth-last-child(n+5):nth-last-child(-n+8):first-child,
ul li:nth-last-child(n+5):nth-last-child(-n+8):first-child ~ li {
    font-weight: bold;
}

/* Exactly 5 */
ul li:nth-last-child(5):first-child,
ul li:nth-last-child(5):first-child ~ li {
    text-decoration: underline;
}
```

[Online demo](https://oscarotero.github.io/css-style-guide/cases/cuantity/)