text:
/**
 * Create a local storage parameter
 *
 == What makes it TOTAL Storage? ==

 * The browser doesn't support local storage it will fall-back to cookies! (Using the
   wonderful $.cookie plugin).
 * Send it strings, numbers even complex object arrays! TotalStorage does not care.
   Your efforts to defeat it will prove futile.
 * Simple as shit. jStorage and some other very well-written plugins provide a bevy of
   options for expiration, security and so forth. Frequently this is more power than you
   need and vulnerable to confusion if you're just want it to work (JWITW)

 * @desc Set the value of a key to a string
 * @example $.totalStorage('the_key', 'the_value');
 * @desc Set the value of a key to a number
 * @example $.totalStorage('the_key', 800.2);
 * @desc Set the value of a key to a complex Array
 * @example	var myArray = new Array();
 *			myArray.push({name:'Jared', company:'Upstatement', zip:63124});
			myArray.push({name:'McGruff', company:'Police', zip:60652};
			$.totalStorage('people', myArray);
			//to return:
			$.totalStorage('people');
 *
 * @name $.totalStorage
 * @cat Plugins/Cookie
 * @author Jared Novack/jared@upstatement.com
 * @version 1.1.2
 * @url http://upstatement.com/blog/2012/01/jquery-local-storage-done-right-and-easy/
 */

;(function($){

	/* Variables I'll need throghout */

	var ls = window.localStorage;
	var supported;
	if (typeof ls == 'undefined' || typeof window.JSON == 'undefined'){
		supported = false;
	} else {
		supported = true;
	}
	/* Make the methods public */

	$.totalStorage = function(key, value, options){
		return $.totalStorage.impl.init(key, value);
	}

	$.totalStorage.setItem = function(key, value){
		return $.totalStorage.impl.setItem(key, value);
	}

	$.totalStorage.getItem = function(key){
		return $.totalStorage.impl.getItem(key);
	}

	$.totalStorage.getAll = function(){
		return $.totalStorage.impl.getAll();
	}

	$.totalStorage.deleteItem = function(key){
		return $.totalStorage.impl.deleteItem(key);
	}

	/* Object to hold all methods: public and private */

	$.totalStorage.impl = {

		init: function(key, value){
			if (typeof value != 'undefined') {
				return this.setItem(key, value);
			} else {
				return this.getItem(key);
			}
		},

		setItem: function(key, value){
			if (!supported){
				try {
					$.cookie(key, value);
					return value;
				} catch(e){
					console.log('Local Storage not supported by this browser. Install the cookie plugin on your site to take advantage of the same functionality. You can get it at https://github.com/carhartl/jquery-cookie');
				}
			}
			var saver = JSON.stringify(value);
			ls.setItem(key, saver);
			return this.parseResult(saver);
		},

		getItem: function(key){
			if (!supported){
				try {
					return this.parseResult($.cookie(key));
				} catch(e){
					return null;
				}
 			}
			return this.parseResult(ls.getItem(key));
		},
		deleteItem: function(key){
			if (!supported){
				try {
					$.cookie(key, null);
					return true;
				} catch(e){
					return false;
				}
 			}
			ls.removeItem(key);
			return true;
		},
		getAll: function(){
			var items = new Array();
			if (!supported){
				try {
					var pairs = document.cookie.split(";");
					for (var i = 0; i<pairs.length; i++){
						var pair = pairs[i].split('=');
						var key = pair[0];
						items.push({key:key, value:this.parseResult($.cookie(key))});
					}
				} catch(e){
					return null;
				}
			} else {
				for (var i in ls){
					if (i.length){
						items.push({key:i, value:this.parseResult(ls.getItem(i))});
					}
				}
			}
			return items;
		},

		parseResult: function(res){
			var ret;
			try {
				ret = JSON.parse(res);
				if (ret == 'true'){
					ret = true;
				}
				if (ret == 'false'){
					ret = false;
				}
				if (parseFloat(ret) == ret && typeof ret != "object"){
					ret = parseFloat(ret);
				}
			} catch(e){}
			return ret;
		}
	}

})(jQuery);


text:
package com.google.cloud.spring.data.spanner.core.convert;

import com.google.cloud.ByteArray;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import org.springframework.util.Assert;

/**
 * Utility functions used in conversion operations.
 *
 * @since 1.1
 */
public final class ConversionUtils {

  private ConversionUtils() {}

  static Class boxIfNeeded(Class propertyType) {
    if (propertyType == null) {
      return null;
    }
    return propertyType.isPrimitive()
        ? Array.get(Array.newInstance(propertyType, 1), 0).getClass()
        : propertyType;
  }

  public static boolean isIterableNonByteArrayType(Class propType) {
    return Iterable.class.isAssignableFrom(propType) && !ByteArray.class.isAssignableFrom(propType);
  }

  static <T> Iterable<T> convertIterable(
      Iterable<Object> source, Class<T> targetType, SpannerCustomConverter converter) {
    List<T> result = new ArrayList<>();
    source.forEach(item -> result.add(converter.convert(item, targetType)));
    return result;
  }

  @SuppressWarnings("unchecked")
  public static <T> T wrapSimpleLazyProxy(Supplier<T> supplierFunc, Class<T> type) {
    return (T)
        Proxy.newProxyInstance(
            type.getClassLoader(),
            new Class[] {type},
            new SimpleLazyDynamicInvocationHandler<>(supplierFunc));
  }

  public static boolean ignoreForWriteLazyProxy(Object object) {
    if (Proxy.isProxyClass(object.getClass())
        && (Proxy.getInvocationHandler(object) instanceof SimpleLazyDynamicInvocationHandler)) {
      SimpleLazyDynamicInvocationHandler<?> handler =
          (SimpleLazyDynamicInvocationHandler<?>) Proxy.getInvocationHandler(object);
      return !handler.isEvaluated();
    }
    return false;
  }

  private static final class SimpleLazyDynamicInvocationHandler<T> implements InvocationHandler {

    private final Supplier<T> supplierFunc;

    private boolean isEvaluated = false;

    private T value;

    private SimpleLazyDynamicInvocationHandler(Supplier<T> supplierFunc) {
      Assert.notNull(supplierFunc, "A non-null supplier function is required for a lazy proxy.");
      this.supplierFunc = supplierFunc;
    }

    private boolean isEvaluated() {
      return this.isEvaluated;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      if (!this.isEvaluated) {
        this.value = this.supplierFunc.get();
        this.isEvaluated = true;
      }
      return method.invoke(this.value, args);
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
var gulp = require('gulp'),
    browserSync = require('browser-sync'),

    $ = require('gulp-load-plugins')(),

    jsFiles = ['lib/**/*.js'],
    lintFiles = ['gulpfile.js', 'lib/**/*.js'],
    testFiles = ['test/**/*.js'];

/**
 * Linting
 *
 * Tests for code quality and source standards.
 */
gulp.task('jshint', function() {
    return gulp.src(lintFiles)
        .pipe(browserSync.reload({
            stream : true,
            once   : true
        }))
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish'))
        .pipe($.if(!browserSync.active, $.jshint.reporter('fail')));
});

/**
 * Code Style
 *
 * Tests for code style accuracy.
 */
gulp.task('eslint', function() {
    return gulp.src(lintFiles)
        .pipe($.eslint())
        .pipe($.eslint.format())
        .pipe($.eslint.failOnError());
});

/**
 * Test
 *
 * Tests the application.
 */
gulp.task('test', ['jshint', 'eslint'], function() {
    return gulp.src(testFiles)
        .pipe($.mocha());
});

/**
 * Setup-Coverage
 *
 * Sets up istanbul for watching tests.
 */
gulp.task('setup-coverage', function() {
    return gulp.src(jsFiles)
        .pipe($.istanbul({
            includeUntested : true
        }))
        .pipe($.istanbul.hookRequire())
        .pipe(gulp.dest('coverage/'));
});

/**
 * Coverage
 *
 * Runs a coverage report for the tests.
 */
gulp.task('coverage', ['setup-coverage'], function() {
    return gulp.src(testFiles)
        .pipe($.mocha())
        .pipe($.istanbul.writeReports());
});

/**
 * Changelog
 *
 * Outputs a markdown version of the changelog between the previous two tags.
 */
gulp.task('changelog', function() {
    var tagString;

    function printChangeLog(err, stdout) {
        if (err) {
            throw err;
        }

        process.stdout.write('\nChangelog between tags ' + tagString + ':\n\n');
        process.stdout.write(stdout + '\n');
    }

    function getPrevTag(err, stdout) {
        if (!err) {
            tagString = stdout.trim() + '..' + tagString;
        }

        $.git.exec({args : 'log ' + tagString + ' --no-merges --reverse --pretty=format:\'- [view](https://github.com/slackrpg/slack-orm/commit/%H) • %s\''}, printChangeLog);
    }

    function getLatestTag(err, stdout) {
        if (err) {
            throw err;
        }

        tagString = stdout.trim();

        $.git.exec({args : 'describe --abbrev=0 --tags ' + tagString + '~1'}, getPrevTag);
    }

    // Fire off our chain
    $.git.exec({args : 'describe --abbrev=0 --tags'}, getLatestTag);

});


text:
package org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.regex;

import com.intellij.lang.PsiBuilder;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.plugins.groovy.GroovyBundle;
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
import org.jetbrains.plugins.groovy.lang.parser.GroovyParser;
import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.BinaryExpression;
import org.jetbrains.plugins.groovy.lang.parser.parsing.util.ParserUtils;

/**
 * @author ilyas
 */
public class RegexExpression implements GroovyElementTypes {

  private static final TokenSet REGEX_DO = TokenSet.create(
      mREGEX_FIND,
      mREGEX_MATCH
  );

  public static boolean parse(PsiBuilder builder, GroovyParser parser) {

    PsiBuilder.Marker marker = builder.mark();
    if (BinaryExpression.EQUALITY.parseBinary(builder, parser)) {
      IElementType type = builder.getTokenType();
      if (ParserUtils.getToken(builder, REGEX_DO)) {
        ParserUtils.getToken(builder, mNLS);
        if (!BinaryExpression.EQUALITY.parseBinary(builder, parser)) {
          builder.error(GroovyBundle.message("expression.expected"));
        }
        PsiBuilder.Marker newMarker = marker.precede();
        marker.done(type == mREGEX_FIND ? REGEX_FIND_EXPRESSION : REGEX_MATCH_EXPRESSION);
        if (REGEX_DO.contains(builder.getTokenType())) {
          subParse(builder, newMarker, parser);
        } else {
          newMarker.drop();
        }
      } else {
        marker.drop();
      }
      return true;
    } else {
      marker.drop();
      return false;
    }
  }

  private static void subParse(PsiBuilder builder, PsiBuilder.Marker marker, GroovyParser parser) {
    IElementType type = builder.getTokenType();
    ParserUtils.getToken(builder, REGEX_DO);
    ParserUtils.getToken(builder, mNLS);
    if (!BinaryExpression.EQUALITY.parseBinary(builder, parser)) {
      builder.error(GroovyBundle.message("expression.expected"));
    }
    PsiBuilder.Marker newMarker = marker.precede();
    marker.done(type == mREGEX_FIND ? REGEX_FIND_EXPRESSION : REGEX_MATCH_EXPRESSION);
    if (REGEX_DO.contains(builder.getTokenType())) {
      subParse(builder, newMarker, parser);
    } else {
      newMarker.drop();
    }
  }

}


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>The nova.api.openstack.compute.contrib.disk_config Module — nova 2012.2.1 documentation</title>

    <link rel="stylesheet" href="../_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/tweaks.css" type="text/css" />

    <link rel="top" title="nova 2012.2.1 documentation" href="../index.html" />
    <link rel="up" title="<no title>" href="autoindex.html" />
    <link rel="next" title="The nova.api.openstack.compute.contrib.extended_server_attributes Module" href="nova.api.openstack.compute.contrib.extended_server_attributes.html" />
    <link rel="prev" title="The nova.api.openstack.compute.contrib.deferred_delete Module" href="nova.api.openstack.compute.contrib.deferred_delete.html" />

OpenStack

Home

Projects

User Stories

Community

Blog

Wiki

Documentation

The <tt class="xref py py-mod docutils literal">nova.api.openstack.compute.contrib.disk_config</tt> Module¶

Disk Config extension.

class <tt class="descname">Disk_config</tt><big>(</big>ext_mgr<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">nova.api.openstack.extensions.ExtensionDescriptor</tt>

Disk Management Extension

<tt class="descname">alias</tt> = 'OS-DCF'¶

<tt class="descname">get_controller_extensions</tt><big>(</big><big>)</big>¶

<tt class="descname">name</tt> = 'DiskConfig'¶

<tt class="descname">namespace</tt> = 'http://docs.openstack.org/compute/ext/disk_config/api/v1.1'¶

<tt class="descname">updated</tt> = '2011-09-27T00:00:00+00:00'¶

class <tt class="descname">ImageDiskConfigController</tt><big>(</big>view_builder=None<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">nova.api.openstack.wsgi.Controller</tt>

<tt class="descname">detail</tt><big>(</big>req, resp_obj<big>)</big>¶

<tt class="descname">show</tt><big>(</big>req, resp_obj, id<big>)</big>¶

<tt class="descname">wsgi_actions</tt> = {}¶

<tt class="descname">wsgi_extensions</tt> = [('detail', None), ('show', None)]¶

class <tt class="descname">ImageDiskConfigTemplate</tt>¶

Bases: <tt class="xref py py-class docutils literal">nova.api.openstack.xmlutil.TemplateBuilder</tt>

<tt class="descname">construct</tt><big>(</big><big>)</big>¶

class <tt class="descname">ImagesDiskConfigTemplate</tt>¶

Bases: <tt class="xref py py-class docutils literal">nova.api.openstack.xmlutil.TemplateBuilder</tt>

<tt class="descname">construct</tt><big>(</big><big>)</big>¶

class <tt class="descname">ServerDiskConfigController</tt><big>(</big>view_builder=None<big>)</big>¶

Bases: <tt class="xref py py-class docutils literal">nova.api.openstack.wsgi.Controller</tt>

<tt class="descname">create</tt><big>(</big>req, body<big>)</big>¶

<tt class="descname">detail</tt><big>(</big>req, resp_obj<big>)</big>¶

<tt class="descname">show</tt><big>(</big>req, resp_obj, id<big>)</big>¶

<tt class="descname">update</tt><big>(</big>req, id, body<big>)</big>¶

<tt class="descname">wsgi_actions</tt> = {}¶

<tt class="descname">wsgi_extensions</tt> = [('show', None), ('create', None), ('detail', None), ('update', None), ('_action_rebuild', 'rebuild'), ('_action_resize', 'resize')]¶

class <tt class="descname">ServerDiskConfigTemplate</tt>¶

Bases: <tt class="xref py py-class docutils literal">nova.api.openstack.xmlutil.TemplateBuilder</tt>

<tt class="descname">construct</tt><big>(</big><big>)</big>¶

class <tt class="descname">ServersDiskConfigTemplate</tt>¶

Bases: <tt class="xref py py-class docutils literal">nova.api.openstack.xmlutil.TemplateBuilder</tt>

<tt class="descname">construct</tt><big>(</big><big>)</big>¶

<tt class="descname">disk_config_from_api</tt><big>(</big>value<big>)</big>¶

<tt class="descname">disk_config_to_api</tt><big>(</big>value<big>)</big>¶

Previous topic

The <tt class="docutils literal docutils literal docutils literal">nova.api.openstack.compute.contrib.deferred_delete</tt> Module

Next topic

The <tt class="docutils literal">nova.api.openstack.compute.contrib.extended_server_attributes</tt> Module

This Page

Show Source

Quick search

              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>

              Enter search terms or a module, class or function name.

Navigation

          index

          modules |

          next |

          previous |

nova 2012.2.1 documentation »

Developer Guide »

<no title> »

        © Copyright 2010-present, OpenStack, LLC.
      Last updated on Thu Nov 1 16:11:51 2012, commit 4ed8d3e.
      Created using Sphinx 1.1.3.


text:
<?php

/**
 * Class AutoLoader
 * @Todo Actually not very flexible, will improved later!
 */
class AutoLoader
{
	/**
	 * @var array Registered classes are stored in this array.
	 */
	private static $classes = array();

	private static $scannedDirectories = array();

	/**
	 * Register the directory for the Autoloader.
	 * Scan all files inside the directory recursively and buffer them in the classes property.
	 *
	 * @param string $directory Absolute or relative path to directory that should scanned.
	 * @param bool   $first
	 */
	public static function register($directory, $first = true)
	{
		if($first)
		{
			self::$scannedDirectories[] = $directory;
		}
		$directory = trim($directory, '/');
		$dir       = dir(trim($directory));
		while(false !== $file = $dir->read())
		{
			if($file !== '.' && $file !== '..')
			{
				if(is_dir($directory . DIRECTORY_SEPARATOR . $file))
				{
					self::register($directory . DIRECTORY_SEPARATOR . $file, false);
				}
				elseif(is_file($directory . DIRECTORY_SEPARATOR . $file))
				{
					self::_asd($directory, $file);
				}
			}
		}
		$dir->close();
	}

	/**
	 * This method will call when the system try to instantiate a not included class or interface.
	 * The parsed class name should exist as key. If this is the case, the class will required.
	 *
	 * @param $class
	 */
	public static function load($class)
	{
		//		var_dump('Alcys\\' . $class);
		if(array_key_exists($class, self::$classes) && is_file(self::$classes[$class]))
		{
			require_once self::$classes[$class];
		}
		elseif(array_key_exists('Alcys\\' . $class, self::$classes) && is_file(self::$classes[$class]))
		{
			require_once self::$classes['Alcys\\' . $class];
		}
	}

	private static function _asd($directory, $file)
	{
		$path = $directory . DIRECTORY_SEPARATOR . $file;

		// Cut the .php extension.
		$className = strstr($path, '.php', true);

		// Replace scanned directories with the Alcys - namespace prefix.
		foreach(self::$scannedDirectories as $registeredDir)
		{
			$className = str_replace(trim($registeredDir, '/'), 'Alcys', $className);
		}

		// Replace slashes with backslashes
		$className = str_replace('/', '\\', $className);

		self::$classes[$className] = $path;
	}
}


text:
package org.apache.camel.component.aws.ec2;

/**
 * Constants used in Camel AWS EC2 module
 *
 */
public interface EC2Constants {

    String IMAGE_ID                 = "CamelAwsEC2ImageId";
    String INSTANCE_TYPE            = "CamelAwsEC2InstanceType";
    String OPERATION                = "CamelAwsEC2Operation";
    String INSTANCE_MIN_COUNT       = "CamelAwsEC2InstanceMinCount";
    String INSTANCE_MAX_COUNT       = "CamelAwsEC2InstanceMaxCount";
    String INSTANCE_MONITORING      = "CamelAwsEC2InstanceMonitoring";
    String INSTANCE_KERNEL_ID       = "CamelAwsEC2InstanceKernelId";
    String INSTANCE_EBS_OPTIMIZED   = "CamelAwsEC2InstanceEbsOptimized";
    String INSTANCE_SECURITY_GROUPS = "CamelAwsEC2InstanceSecurityGroups";
    String INSTANCES_IDS            = "CamelAwsEC2InstancesIds";
}


text:
import Ember from 'ember';
import sendEvent from '../utils/send-event';

export default {

  // ---------------------------------- メソッド

  // アクションをトリガーする関数
  actionTrigger: function(actionName) {
    return Ember.computed(function() {
      return this.sendAction.bind(this, actionName);
    }).readOnly();
  },

  // イベントをトリガする関数
  eventTrigger: function(eventName) {
    return Ember.computed(function() {
      return sendEvent.bind(this, this, eventName);
    }).readOnly();
  }
};


text:
package co.cask.cdap.proto;

/**
 * Class containing a program status.
 */
public class ProgramStatus {
  private String applicationId;
  private String programId;
  private String status;

  public ProgramStatus(String applicationId, String programId, String status) {
    this.applicationId = applicationId;
    this.programId = programId;
    this.status = status;
  }

  public String getStatus() {
    return this.status;
  }
}


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

-->

<set xmlns:android="http://schemas.android.com/apk/res/android"
        android:shareInterpolator="false">
    <scale android:fromXScale="1.0" android:toXScale="1.1111111111111"
            android:fromYScale="1.0" android:toYScale="1.1111111111111"
            android:pivotX="50%" android:pivotY="50%"
            android:interpolator="@android:interpolator/accelerate_decelerate"
            android:fillEnabled="true"
            android:fillBefore="true" android:fillAfter="true"
            android:duration="@android:integer/config_shortAnimTime"/>
    <scale android:fromXScale="100%p" android:toXScale="100%"
            android:fromYScale="100%p" android:toYScale="100%"
            android:pivotX="50%" android:pivotY="50%"
            android:interpolator="@android:interpolator/decelerate_quint"
            android:fillEnabled="true"
            android:fillBefore="true" android:fillAfter="true"
            android:duration="@android:integer/config_mediumAnimTime" />
</set>


text:
// Type: Highsoft.Web.Mvc.Stocks.PlotOptionsScatterDataLabelsOverflow

namespace Highsoft.Web.Mvc.Stocks
{
    public enum PlotOptionsScatterDataLabelsOverflow
    {
        Justify,
        None,
    }
}


text:
namespace IronFoundry.Dea.JsonConverters
{
    using System;
    using System.Globalization;
    using Newtonsoft.Json;

    public class VcapDateTimeConverter : JsonConverter
    {
        private const string dateFormat = "yyyy-MM-dd HH:mm:ss zzz";
        private static readonly Type convertableType = typeof(DateTime);

        public override bool CanConvert(Type objectType)
        {
            return (null != objectType && convertableType == objectType);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (null == value)
            {
                throw new Exception("Attempt to convert null DateTime value.");
            }
            else
            {
                DateTime dateTimeValue = (DateTime)value;
                writer.WriteValue(dateTimeValue.ToString(dateFormat, CultureInfo.InvariantCulture));
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                throw new Exception(String.Format(CultureInfo.InvariantCulture, "Cannot convert null value to {0}.", objectType));
            }

            return DateTime.ParseExact(reader.Value.ToString(), dateFormat, CultureInfo.InvariantCulture);
        }
    }
}


text:
#ifndef MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_H264_H_
#define MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_H264_H_

#include <stddef.h>
#include <stdint.h>

#include <deque>
#include <memory>
#include <queue>

#include "api/array_view.h"
#include "modules/include/module_common_types.h"
#include "modules/rtp_rtcp/source/rtp_format.h"
#include "modules/rtp_rtcp/source/rtp_packet_to_send.h"
#include "modules/video_coding/codecs/h264/include/h264_globals.h"
#include "rtc_base/buffer.h"
#include "rtc_base/constructor_magic.h"

namespace webrtc {

class RtpPacketizerH264 : public RtpPacketizer {
 public:
  // Initialize with payload from encoder.
  // The payload_data must be exactly one encoded H264 frame.
  RtpPacketizerH264(rtc::ArrayView<const uint8_t> payload,
                    PayloadSizeLimits limits,
                    H264PacketizationMode packetization_mode,
                    const RTPFragmentationHeader& fragmentation);

  ~RtpPacketizerH264() override;

  size_t NumPackets() const override;

  // Get the next payload with H264 payload header.
  // Write payload and set marker bit of the |packet|.
  // Returns true on success, false otherwise.
  bool NextPacket(RtpPacketToSend* rtp_packet) override;

 private:
  // A packet unit (H264 packet), to be put into an RTP packet:
  // If a NAL unit is too large for an RTP packet, this packet unit will
  // represent a FU-A packet of a single fragment of the NAL unit.
  // If a NAL unit is small enough to fit within a single RTP packet, this
  // packet unit may represent a single NAL unit or a STAP-A packet, of which
  // there may be multiple in a single RTP packet (if so, aggregated = true).
  struct PacketUnit {
    PacketUnit(rtc::ArrayView<const uint8_t> source_fragment,
               bool first_fragment,
               bool last_fragment,
               bool aggregated,
               uint8_t header)
        : source_fragment(source_fragment),
          first_fragment(first_fragment),
          last_fragment(last_fragment),
          aggregated(aggregated),
          header(header) {}

    rtc::ArrayView<const uint8_t> source_fragment;
    bool first_fragment;
    bool last_fragment;
    bool aggregated;
    uint8_t header;
  };

  bool GeneratePackets(H264PacketizationMode packetization_mode);
  bool PacketizeFuA(size_t fragment_index);
  size_t PacketizeStapA(size_t fragment_index);
  bool PacketizeSingleNalu(size_t fragment_index);

  void NextAggregatePacket(RtpPacketToSend* rtp_packet);
  void NextFragmentPacket(RtpPacketToSend* rtp_packet);

  const PayloadSizeLimits limits_;
  size_t num_packets_left_;
  std::deque<rtc::ArrayView<const uint8_t>> input_fragments_;
  std::queue<PacketUnit> packets_;

  RTC_DISALLOW_COPY_AND_ASSIGN(RtpPacketizerH264);
};
}  // namespace webrtc
#endif  // MODULES_RTP_RTCP_SOURCE_RTP_FORMAT_H264_H_


text:
#ifndef _PSYNC_API_H
#define _PSYNC_API_H

#include "pcompat.h"
#include "pcompiler.h"
#include <string.h>
#include <stdint.h>

#define PARAM_STR   0
#define PARAM_NUM   1
#define PARAM_BOOL  2

#define PARAM_ARRAY 3
#define PARAM_HASH  4
#define PARAM_DATA  5

#define PARAM_END 255

#define PTR_OK ((binresult *)1)

#define ASYNC_RES_NEEDMORE 0
#define ASYNC_RES_READY    1

typedef struct {
  uint16_t paramtype;
  uint16_t paramnamelen;
  uint32_t opts;
  const char *paramname;
  union {
    uint64_t num;
    const char *str;
  };
} binparam;

struct _binresult;

typedef struct _hashpair {
  const char *key;
  struct _binresult *value;
} hashpair;

typedef struct _binresult{
  uint32_t type;
  uint32_t length;
  union {
    uint64_t num;
    const char str[8];
    struct _binresult **array;
    struct _hashpair *hash;
  };
} binresult;

typedef struct {
  binresult *result;
  uint32_t state;
  uint32_t bytesread;
  uint32_t bytestoread;
  uint32_t respsize;
  unsigned char *data;
} async_result_reader;

#define P_STR(name, val) {PARAM_STR, strlen(name), strlen(val), (name), {(uint64_t)((uintptr_t)(val))}}
#define P_LSTR(name, val, len) {PARAM_STR, strlen(name), (len), (name), {(uint64_t)((uintptr_t)(val))}}
#define P_NUM(name, val) {PARAM_NUM, strlen(name), 0, (name), {(val)}}
#define P_BOOL(name, val) {PARAM_BOOL, strlen(name), 0, (name), {(val)?1:0}}

#define send_command(sock, cmd, params) do_send_command(sock, cmd, strlen(cmd), params, sizeof(params)/sizeof(binparam), -1, 1)
#define send_command_no_res(sock, cmd, params) do_send_command(sock, cmd, strlen(cmd), params, sizeof(params)/sizeof(binparam), -1, 0)

#define send_command_thread(sock, cmd, params) do_send_command(sock, cmd, strlen(cmd), params, sizeof(params)/sizeof(binparam), -1, 1|2)
#define send_command_no_res_thread(sock, cmd, params) do_send_command(sock, cmd, strlen(cmd), params, sizeof(params)/sizeof(binparam), -1, 2)

#define prepare_command_data_alloc(cmd, params, datalen, alloclen, retlen) \
  do_prepare_command(cmd, strlen(cmd), params, sizeof(params)/sizeof(binparam), datalen, alloclen, retlen)

#define psync_find_result(res, name, type) psync_do_find_result(res, name, type, __FILE__, __FUNCTION__, __LINE__)
#define psync_check_result(res, name, type) psync_do_check_result(res, name, type, __FILE__, __FUNCTION__, __LINE__)

psync_socket *psync_api_connect(int usessl);
void psync_api_conn_fail_inc();
void psync_api_conn_fail_reset();

binresult *get_result(psync_socket *sock) PSYNC_NONNULL(1);
binresult *get_result_thread(psync_socket *sock) PSYNC_NONNULL(1);
void async_result_reader_init(async_result_reader *reader) PSYNC_NONNULL(1);
void async_result_reader_destroy(async_result_reader *reader) PSYNC_NONNULL(1);
int get_result_async(psync_socket *sock, async_result_reader *reader) PSYNC_NONNULL(1, 2);
unsigned char *do_prepare_command(const char *command, size_t cmdlen, const binparam *params, size_t paramcnt, int64_t datalen, size_t additionalalloc, size_t *retlen);
binresult *do_send_command(psync_socket *sock, const char *command, size_t cmdlen, const binparam *params, size_t paramcnt, int64_t datalen, int readres) PSYNC_NONNULL(1, 2);
const binresult *psync_do_find_result(const binresult *res, const char *name, uint32_t type, const char *file, const char *function, int unsigned line) PSYNC_NONNULL(2) PSYNC_PURE;
const binresult *psync_do_check_result(const binresult *res, const char *name, uint32_t type, const char *file, const char *function, int unsigned line)  PSYNC_NONNULL(2) PSYNC_PURE;

#endif


text:
package org.apache.nutch.parse.html;

import java.net.URL;
import java.net.MalformedURLException;
import java.util.Collection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

import org.apache.nutch.parse.Outlink;
import org.apache.nutch.util.NodeWalker;
import org.apache.nutch.util.URLUtil;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.MapWritable;
import org.apache.hadoop.io.Text;

/**
 * A collection of methods for extracting content from DOM trees.
 *
 * This class holds a few utility methods for pulling content out of DOM nodes,
 * such as getOutlinks, getText, etc.
 *
 */
public class DOMContentUtils {

  private String srcTagMetaName;
  private boolean keepNodenames;
  private Set<String> blockNodes;

  public static class LinkParams {
    public String elName;
    public String attrName;
    public int childLen;

    public LinkParams(String elName, String attrName, int childLen) {
      this.elName = elName;
      this.attrName = attrName;
      this.childLen = childLen;
    }

    public String toString() {
      return "LP[el=" + elName + ",attr=" + attrName + ",len=" + childLen + "]";
    }
  }

  private HashMap<String, LinkParams> linkParams = new HashMap<String, LinkParams>();
  private Configuration conf;

  public DOMContentUtils(Configuration conf) {
    setConf(conf);
  }

  public void setConf(Configuration conf) {
    // forceTags is used to override configurable tag ignoring, later on
    Collection<String> forceTags = new ArrayList<String>(1);

    this.conf = conf;
    linkParams.clear();
    linkParams.put("a", new LinkParams("a", "href", 1));
    linkParams.put("area", new LinkParams("area", "href", 0));
    if (conf.getBoolean("parser.html.form.use_action", true)) {
      linkParams.put("form", new LinkParams("form", "action", 1));
      if (conf.get("parser.html.form.use_action") != null)
        forceTags.add("form");
    }
    linkParams.put("frame", new LinkParams("frame", "src", 0));
    linkParams.put("iframe", new LinkParams("iframe", "src", 0));
    linkParams.put("script", new LinkParams("script", "src", 0));
    linkParams.put("link", new LinkParams("link", "href", 0));
    linkParams.put("img", new LinkParams("img", "src", 0));
    linkParams.put("source", new LinkParams("source", "src", 0));

    // remove unwanted link tags from the linkParams map
    String[] ignoreTags = conf.getStrings("parser.html.outlinks.ignore_tags");
    for (int i = 0; ignoreTags != null && i < ignoreTags.length; i++) {
      if (!forceTags.contains(ignoreTags[i]))
        linkParams.remove(ignoreTags[i]);
    }

    //NUTCH-2433 - Should we keep the html node where the outlinks are found?
    srcTagMetaName = this.conf
        .get("parser.html.outlinks.htmlnode_metadata_name");
    keepNodenames = (srcTagMetaName != null && srcTagMetaName.length() > 0);
    blockNodes = new HashSet<>(conf.getTrimmedStringCollection("parser.html.line.separators"));
  }

  /**
   * This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
   * append all the content text found beneath the DOM node to the
   * StringBuffer.
   *
   *

   *
   * If abortOnNestedAnchors is true, DOM traversal will be aborted
   * and the StringBuffer will not contain any text encountered
   * after a nested anchor is found.
   *
   *

   *
   * @param sb a {@link StringBuffer} used to store content text
   * found beneath the DOM node... if any exists
   * @param node a DOM {@link Node} to check for content text
   * @param abortOnNestedAnchors true to abort if nested anchors
   * are encountered, false otherwise
   * @return true if nested anchors were found
   */
  public boolean getText(StringBuffer sb, Node node,
      boolean abortOnNestedAnchors) {
    if (getTextHelper(sb, node, abortOnNestedAnchors, 0)) {
      return true;
    }
    return false;
  }

  /**
   * This is a convinience method, equivalent to
   * {@link #getText(StringBuffer,Node,boolean) getText(sb, node, false)}.
   * @param sb a {@link StringBuffer} used to store content text
   * found beneath the DOM node... if any exists
   * @param node a DOM {@link Node} to check for content text
   */
  public void getText(StringBuffer sb, Node node) {
    getText(sb, node, false);
  }

  // returns true if abortOnNestedAnchors is true and we find nested
  // anchors
  private boolean getTextHelper(StringBuffer sb, Node node,
      boolean abortOnNestedAnchors, int anchorDepth) {
    boolean abort = false;
    NodeWalker walker = new NodeWalker(node);

    while (walker.hasNext()) {

      Node currentNode = walker.nextNode();
      String nodeName = currentNode.getNodeName();
      short nodeType = currentNode.getNodeType();
      Node previousSibling = currentNode.getPreviousSibling();
      if (previousSibling != null
          && blockNodes.contains(previousSibling.getNodeName().toLowerCase())) {
        appendParagraphSeparator(sb);
      } else if (blockNodes.contains(nodeName.toLowerCase())) {
        appendParagraphSeparator(sb);
      }

      if ("script".equalsIgnoreCase(nodeName)) {
        walker.skipChildren();
      }
      if ("style".equalsIgnoreCase(nodeName)) {
        walker.skipChildren();
      }
      if (abortOnNestedAnchors && "a".equalsIgnoreCase(nodeName)) {
        anchorDepth++;
        if (anchorDepth > 1) {
          abort = true;
          break;
        }
      }
      if (nodeType == Node.COMMENT_NODE) {
        walker.skipChildren();
      }
      if (nodeType == Node.TEXT_NODE) {
        // cleanup and trim the value
        String text = currentNode.getNodeValue();
        text = text.replaceAll("\\s+", " ");
        text = text.trim();
        if (text.length() > 0) {
          appendSpace(sb);
          sb.append(text);
        } else {
          appendParagraphSeparator(sb);
        }
      }
    }

    return abort;
  }

  /**
   * Conditionally append a paragraph/line break to StringBuffer unless last
   * character a already indicates a paragraph break. Also remove trailing space
   * before paragraph break.
   *
   * @param buffer
   *          StringBuffer to append paragraph break
   */
  private void appendParagraphSeparator(StringBuffer buffer) {
    if (buffer.length() == 0) {
      return;
    }
    char lastChar = buffer.charAt(buffer.length() - 1);
    if ('\n' != lastChar) {
      // remove white space before paragraph break
      while (lastChar == ' ') {
        buffer.deleteCharAt(buffer.length() - 1);
        lastChar = buffer.charAt(buffer.length() - 1);
      }
      if ('\n' != lastChar) {
        buffer.append('\n');
      }
    }
  }

  /**
   * Conditionally append a space to StringBuffer unless last character is a
   * space or line/paragraph break.
   *
   * @param buffer
   *          StringBuffer to append space
   */
  private void appendSpace(StringBuffer buffer) {
    if (buffer.length() == 0) {
      return;
    }
    char lastChar = buffer.charAt(buffer.length() - 1);
    if (' ' != lastChar && '\n' != lastChar) {
      buffer.append(' ');
    }
  }

  /**
   * This method takes a {@link StringBuffer} and a DOM {@link Node}, and will
   * append the content text found beneath the first title node to
   * the StringBuffer.
   * @param sb a {@link StringBuffer} used to store content text
   * found beneath the DOM node... if any exists
   * @param node a DOM {@link Node} to check for content text
   * @return true if a title node was found, false otherwise
   */
  public boolean getTitle(StringBuffer sb, Node node) {

    NodeWalker walker = new NodeWalker(node);

    while (walker.hasNext()) {

      Node currentNode = walker.nextNode();
      String nodeName = currentNode.getNodeName();
      short nodeType = currentNode.getNodeType();

      if ("body".equalsIgnoreCase(nodeName)) { // stop after HEAD
        return false;
      }

      if (nodeType == Node.ELEMENT_NODE) {
        if ("title".equalsIgnoreCase(nodeName)) {
          getText(sb, currentNode);
          return true;
        }
      }
    }

    return false;
  }

  /**
   * If Node contains a BASE tag then it's HREF is returned.
   * @param node a DOM {@link Node} to check for a BASE tag
   * @return HREF if one exists
   */
  public String getBase(Node node) {

    NodeWalker walker = new NodeWalker(node);

    while (walker.hasNext()) {

      Node currentNode = walker.nextNode();
      String nodeName = currentNode.getNodeName();
      short nodeType = currentNode.getNodeType();

      // is this node a BASE tag?
      if (nodeType == Node.ELEMENT_NODE) {

        if ("body".equalsIgnoreCase(nodeName)) { // stop after HEAD
          return null;
        }

        if ("base".equalsIgnoreCase(nodeName)) {
          NamedNodeMap attrs = currentNode.getAttributes();
          for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            if ("href".equalsIgnoreCase(attr.getNodeName())) {
              return attr.getNodeValue();
            }
          }
        }
      }
    }

    // no.
    return null;
  }

  private boolean hasOnlyWhiteSpace(Node node) {
    String val = node.getNodeValue();
    for (int i = 0; i < val.length(); i++) {
      if (!Character.isWhitespace(val.charAt(i)))
        return false;
    }
    return true;
  }

  // this only covers a few cases of empty links that are symptomatic
  // of nekohtml's DOM-fixup process...
  private boolean shouldThrowAwayLink(Node node, NodeList children,
      int childLen, LinkParams params) {
    if (childLen == 0) {
      // this has no inner structure
      if (params.childLen == 0)
        return false;
      else
        return true;
    } else if ((childLen == 1)
        && (children.item(0).getNodeType() == Node.ELEMENT_NODE)
        && (params.elName.equalsIgnoreCase(children.item(0).getNodeName()))) {
      // single nested link
      return true;

    } else if (childLen == 2) {

      Node c0 = children.item(0);
      Node c1 = children.item(1);

      if ((c0.getNodeType() == Node.ELEMENT_NODE)
          && (params.elName.equalsIgnoreCase(c0.getNodeName()))
          && (c1.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c1)) {
        // single link followed by whitespace node
        return true;
      }

      if ((c1.getNodeType() == Node.ELEMENT_NODE)
          && (params.elName.equalsIgnoreCase(c1.getNodeName()))
          && (c0.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c0)) {
        // whitespace node followed by single link
        return true;
      }

    } else if (childLen == 3) {
      Node c0 = children.item(0);
      Node c1 = children.item(1);
      Node c2 = children.item(2);

      if ((c1.getNodeType() == Node.ELEMENT_NODE)
          && (params.elName.equalsIgnoreCase(c1.getNodeName()))
          && (c0.getNodeType() == Node.TEXT_NODE)
          && (c2.getNodeType() == Node.TEXT_NODE) && hasOnlyWhiteSpace(c0)
          && hasOnlyWhiteSpace(c2)) {
        // single link surrounded by whitespace nodes
        return true;
      }
    }

    return false;
  }

  /**
   * This method finds all anchors below the supplied DOM node, and
   * creates appropriate {@link Outlink} records for each (relative to the
   * supplied base URL), and adds them to the outlinks
   * {@link ArrayList}.
   *
   *

   *
   * Links without inner structure (tags, text, etc) are discarded, as are links
   * which contain only single nested links and empty text nodes (this is a
   * common DOM-fixup artifact, at least with nekohtml).
   *
   * @param base the canonical {@link URL}
   * @param outlinks the {@link ArrayList} of {@link Outlink}'s associated
   * with the base URL
   * @param node a {@link Node} under which to discover anchors
   */
  public void getOutlinks(URL base, ArrayList<Outlink> outlinks, Node node) {

    NodeWalker walker = new NodeWalker(node);
    while (walker.hasNext()) {

      Node currentNode = walker.nextNode();
      String nodeName = currentNode.getNodeName();
      short nodeType = currentNode.getNodeType();
      NodeList children = currentNode.getChildNodes();
      int childLen = (children != null) ? children.getLength() : 0;

      if (nodeType == Node.ELEMENT_NODE) {

        nodeName = nodeName.toLowerCase();
        LinkParams params = (LinkParams) linkParams.get(nodeName);
        if (params != null) {
          if (!shouldThrowAwayLink(currentNode, children, childLen, params)) {

            StringBuffer linkText = new StringBuffer();
            getText(linkText, currentNode, true);
            if (linkText.toString().trim().length() == 0) {
              // try harder - use img alt if present
              NodeWalker subWalker = new NodeWalker(currentNode);
              while (subWalker.hasNext()) {
                Node subNode = subWalker.nextNode();
                if (subNode.getNodeType() == Node.ELEMENT_NODE) {
                  if (subNode.getNodeName().toLowerCase().equals("img")) {
                    NamedNodeMap subAttrs = subNode.getAttributes();
                    Node alt = subAttrs.getNamedItem("alt");
                    if (alt != null) {
                      String altTxt = alt.getTextContent();
                      if (altTxt != null && altTxt.trim().length() > 0) {
                        if (linkText.length() > 0)
                          linkText.append(' ');
                        linkText.append(altTxt);
                      }
                    }
                  } else {
                    // ignore other types of elements

                  }
                } else if (subNode.getNodeType() == Node.TEXT_NODE) {
                  String txt = subNode.getTextContent();
                  if (txt != null && txt.length() > 0) {
                    if (linkText.length() > 0)
                      linkText.append(' ');
                    linkText.append(txt);
                  }
                }
              }
            }

            NamedNodeMap attrs = currentNode.getAttributes();
            String target = null;
            boolean noFollow = false;
            boolean post = false;
            for (int i = 0; i < attrs.getLength(); i++) {
              Node attr = attrs.item(i);
              String attrName = attr.getNodeName();
              if (params.attrName.equalsIgnoreCase(attrName)) {
                target = attr.getNodeValue();
              } else if ("rel".equalsIgnoreCase(attrName)
                  && "nofollow".equalsIgnoreCase(attr.getNodeValue())) {
                noFollow = true;
              } else if ("method".equalsIgnoreCase(attrName)
                  && "post".equalsIgnoreCase(attr.getNodeValue())) {
                post = true;
              }
            }
            if (target != null && !noFollow && !post)
              try {

                URL url = URLUtil.resolveURL(base, target);
                Outlink outlink = new Outlink(url.toString(), linkText
                    .toString().trim());
                outlinks.add(outlink);

                // NUTCH-2433 - Keep the node name where the URL was found into
                // the outlink metadata
                if (keepNodenames) {
                  MapWritable metadata = new MapWritable();
                  metadata.put(new Text(srcTagMetaName), new Text(nodeName));
                  outlink.setMetadata(metadata);
                }

              } catch (MalformedURLException e) {
                // don't care
              }
          }
          // this should not have any children, skip them
          if (params.childLen == 0)
            continue;
        }
      }
    }
  }

}


text:
High-Level API
==============

.. currentmodule:: nbgrader.apps.api

.. versionadded:: 0.5.0

This API is a high-level api that provides access to nbgrader's core
functionality, for example assigning, releasing, collecting, and autograding
assignments. For example:

.. code:: python

    from nbgrader.apps import NbGraderAPI
    from traitlets.config import Config

    # create a custom config object to specify options for nbgrader
    config = Config()
    config.CourseDirectory.course_id = "course101"

    api = NbGraderAPI(config=config)

    # assuming source/ps1 exists
    api.generate_assignment("ps1")

For details on how to configure the API, see :doc:`/configuration/config_options`.

.. autoclass:: NbGraderAPI

    .. automethod:: __init__

    .. autoattribute:: gradebook

    .. automethod:: get_source_assignments

    .. automethod:: get_released_assignments

    .. automethod:: get_submitted_students

    .. automethod:: get_submitted_timestamp

    .. automethod:: get_autograded_students

    .. automethod:: get_assignment

    .. automethod:: get_assignments

    .. automethod:: get_notebooks

    .. automethod:: get_submission

    .. automethod:: get_submissions

    .. automethod:: get_notebook_submission_indices

    .. automethod:: get_notebook_submissions

    .. automethod:: get_student

    .. automethod:: get_students

    .. automethod:: get_student_submissions

    .. automethod:: get_student_notebook_submissions

    .. automethod:: assign

    .. automethod:: release

    .. automethod:: unrelease

    .. automethod:: collect

    .. automethod:: autograde

    .. automethod:: generate_feedback

    .. automethod:: release_feedback

    .. automethod:: fetch_feedback


text:
#include    "pch.h"
#include    "GetChatCondition.h"
#include    "TrainingMission.h"

namespace Training
{
    //------------------------------------------------------------------------------
    // global variabes
    //------------------------------------------------------------------------------
    extern TrainingMission*    g_pMission;

    //------------------------------------------------------------------------------
    // class methods
    //------------------------------------------------------------------------------
    /* void */  GetChatCondition::GetChatCondition (ChatTarget expectedRecipient) :
    m_expectedRecipient (expectedRecipient),
    m_bGotExpectedChat (false)
    {
    }

    //------------------------------------------------------------------------------
    /* void */  GetChatCondition::~GetChatCondition (void)
    {
    }

    //------------------------------------------------------------------------------
    bool        GetChatCondition::Start (void)
    {
        g_pMission->SetChatCondition (this);
        m_bGotExpectedChat = false;
        return false;
    }

    //------------------------------------------------------------------------------
    bool        GetChatCondition::Evaluate (void)
    {
        bool    result = m_bGotExpectedChat;
        m_bGotExpectedChat = false;
        return result;
    }

    //------------------------------------------------------------------------------
    void        GetChatCondition::RecordChat (ChatTarget recipient)
    {
        if (recipient == m_expectedRecipient)
            m_bGotExpectedChat = true;
    }

    //------------------------------------------------------------------------------
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2014. All Rights Reserved.                             */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

#pragma once

#include "HAL/HAL.hpp"
#include "SensorBase.h"
#include "LiveWindow/LiveWindowSendable.h"

/**
 * MXP analog output class.
 */
class AnalogOutput : public SensorBase, public LiveWindowSendable
{
public:
    explicit AnalogOutput(uint32_t channel);
    virtual ~AnalogOutput();

    void SetVoltage(float voltage);
    float GetVoltage();

    void UpdateTable();
    void StartLiveWindowMode();
    void StopLiveWindowMode();
    std::string GetSmartDashboardType();
    void InitTable(ITable *subTable);
    ITable *GetTable();

protected:
    void InitAnalogOutput(uint32_t channel);
    uint32_t m_channel;
    void* m_port;

    ITable *m_table;
};


text:
using System.IO;
using System;
using Aspose.Pdf;
using Aspose.Pdf.Devices;

namespace Aspose.Pdf.Examples.CSharp.AsposePDF.Images
{
    public class AllPagesToTIFF
    {
        public static void Run()
        {
            // ExStart:AllPagesToTIFF
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir_AsposePdf_Images();

            // Open document
            Document pdfDocument = new Document(dataDir+ "PageToTIFF.pdf");

            // Create Resolution object
            Resolution resolution = new Resolution(300);

            // Create TiffSettings object
            TiffSettings tiffSettings = new TiffSettings();
            tiffSettings.Compression = CompressionType.None;
            tiffSettings.Depth = ColorDepth.Default;
            tiffSettings.Shape = ShapeType.Landscape;
            tiffSettings.SkipBlankPages = false;

            // Create TIFF device
            TiffDevice tiffDevice = new TiffDevice(resolution, tiffSettings);

            // Convert a particular page and save the image to stream
            tiffDevice.Process(pdfDocument, dataDir + "AllPagesToTIFF_out.tif");

            // ExEnd:AllPagesToTIFF
            System.Console.WriteLine("PDF all pages converted to one tiff file successfully!");
        }
    }
}


text:
// ==UserScript==
// @name         taobaoDaigou
// @version      0.1.1
// @description  淘宝代购,保留一切版权。
// @author       Wanghsinche
// @include      http://www.amazon.co.uk/*
// @include      http://www.amazon.co.jp/*
// @include      http://www.amazon.com/*
// @include      http://daigou.taobao.com
// @require http://libs.useso.com/js/jquery/1.9.0/jquery.min.js
// @grant       GM_xmlhttpRequest
// @grant       GM_openInTab
// @run-at document-body

// ==/UserScript==
//Event is a simple class for implementing the Observer pattern:
function Event(sender) {
    this._sender = sender;
    this._listeners = [];
}

Event.prototype = {
    attach : function (listener) {//push the callback function into _listeners[];
        this._listeners.push(listener);
    },
    notify : function (args) {//pop all the callback functions and execute the functions with same args?
        var index;

        for (index = 0; index < this._listeners.length; index += 1) {
            this._listeners[index](this._sender, args);//auto pass sender and args into callback function, so the default form of callback function is function(sender,args){}
        }
    }
};
//////////////////////////////////
//page router settings
var route={
	defaultRoute:'',
	currentHash:'',
	routeLst:[
    	{hash:'#1', vc:function(appModel){
    		requirejs(['app/selectApp/vcForView1'],function(app){
				var appViewer=new app.Viewer(appModel,{
					selectItemClass:'.item',
					templateID:'t:view_select',
					viewID:'#view_select',
				});
				var appController=new app.Controller(appModel,appViewer);
				appController.initial();
   			});
    	}},
    	{hash:'#2', vc:function(appModel){
    		requirejs(['app/selectApp/vcForView2'],function(app){
				var appViewer=new app.Viewer(appModel,{
					selectItemClass:'.problem-item',
					templateID:'t:view_problem',
					viewID:'#view_select',
					textAreaID:'#textPro',
				});
				var appController=new app.Controller(appModel,appViewer);
				appController.initial();
   			});
    	}},
    	{hash:'#4', vc:function(appModel){
    		requirejs(['app/selectApp/vcForView4'],function(app){
				var appViewer=new app.Viewer(appModel,{
					selectItemClass:'.serve-item',
					templateID:'t:view_serve',
					viewID:'#view_select',
				});
				var appController=new app.Controller(appModel,appViewer);
				appController.initial();
   			});
    	}},
	],
	hashCheck:function(model){
        if (window.location.hash != this.currentHash){
        	for(var i=0,currentRoute;i<this.routeLst.length;i++){
            	currentRoute = this.routeLst[i];
                if (window.location.hash == currentRoute.hash){
            		this.currentHash = window.location.hash;
                    currentRoute.vc(model);
                    this.refleshView(model);
                	break;
                }
        	}
        }
    },
	refleshView:function(model){
		var self=this;
		$('.process-item').removeClass('active');
		$.each($('.process-item>a'),function(index,val){
			$(val).parent().addClass('active');
			if($(val).attr('href').toString()===self.currentHash)
				return false;
		});
    },
    startRoute:function(defaultRoute,model){
        window.location.hash = window.location.hash || defaultRoute;
        this.defaultRoute=defaultRoute;
        this.currentHash="";
        var self=this;
        setInterval(function(){self.hashCheck(model);}, 200);
	    },
};
//////////////////////////////////
var afterLoaded=function(response){
	var existParttern="商品已经存在";
	var successParttern="itemPublish.htm";
	var hasPostedParttern="已经存在该商品";
	if (response.finalUrl.match(existParttern)===null) {
		//商品不存在,继续
		if (response.finalUrl.match(successParttern)===null){
			//未知类型,退出
			alert('未知类型');
			// console.log('1');
		}else{
			//已知类型
			if (response.responseText.match(hasPostedParttern)===null) {
				//可以提交
				GM_openInTab(response.finalUrl,false);
			}else{
				//已经提交
				alert(hasPostedParttern);
							// console.log('2');

			}

		}
	}
	else{
		//商品存在
		alert(existParttern);
					// console.log('3');

	}

};
//////////////////////////////////
var getURL=function(){
	var url=location.href;
	var host=location.host;//url.match(/http:\/\/[\w|\.]*/);
	var code=url.match(/B00\w{7}/);
	var suburl='';
	suburl='http://'+host+'/dp/'+code;
	return suburl;
};
//////////////////////////////////
var fetchLogin=function(i){
	var loginEvent= new Event(this);
	var loginURL='http://daigou.taobao.com/buyer/index.htm';
	var suburl=getURL();
	var text=["action="+encodeURIComponent('/buyer/submit_url_action'),"event_submit_do_submit_url="+encodeURIComponent('anything'),"_tb_token_="+encodeURIComponent('LUHLJE8DqGtdw64'),"itemUrl="+encodeURIComponent(suburl)];
	var senddata=text.join('&');
	var _this=this;
	console.log(suburl);
	GM_xmlhttpRequest({
		method:"POST",
		url:loginURL,
		headers: {
		    "User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used.
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		data:senddata,
		onload:function(response){
			afterLoaded(response);
		},
		onerror:function(response){
				// globalFetchDoneEvent.notify();//skip and next account
				// console.log("username :" + tempuser+'login failed');
				// return false;
				alert('未知错误');
		}
	});
};

////////////////////
$('#productTitle').append('<button id="wxzBtn" class="">check</button>');
$('#wxzBtn').click(function(){
	fetchLogin();
});


text:
.class Lcom/android/gallery3d/ui/TileImageView$TileQueue;
.super Ljava/lang/Object;
.source "TileImageView.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/gallery3d/ui/TileImageView;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "TileQueue"
.end annotation

# instance fields
.field private mHead:Lcom/android/gallery3d/ui/TileImageView$Tile;

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 770
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Lcom/android/gallery3d/ui/TileImageView$1;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 770
    invoke-direct {p0}, Lcom/android/gallery3d/ui/TileImageView$TileQueue;-><init>()V

    return-void
.end method

# virtual methods
.method public clean()V
    .locals 1

    .prologue
    .line 787
    const/4 v0, 0x0

    iput-object v0, p0, Lcom/android/gallery3d/ui/TileImageView$TileQueue;->mHead:Lcom/android/gallery3d/ui/TileImageView$Tile;

    .line 788
    return-void
.end method

.method public pop()Lcom/android/gallery3d/ui/TileImageView$Tile;
    .locals 2

    .prologue
    .line 774
    iget-object v0, p0, Lcom/android/gallery3d/ui/TileImageView$TileQueue;->mHead:Lcom/android/gallery3d/ui/TileImageView$Tile;

    .line 775
    .local v0, tile:Lcom/android/gallery3d/ui/TileImageView$Tile;
    if-eqz v0, :cond_0

    iget-object v1, v0, Lcom/android/gallery3d/ui/TileImageView$Tile;->mNext:Lcom/android/gallery3d/ui/TileImageView$Tile;

    iput-object v1, p0, Lcom/android/gallery3d/ui/TileImageView$TileQueue;->mHead:Lcom/android/gallery3d/ui/TileImageView$Tile;

    .line 776
    :cond_0
    return-object v0
.end method

.method public push(Lcom/android/gallery3d/ui/TileImageView$Tile;)Z
    .locals 2
    .parameter "tile"

    .prologue
    .line 780
    iget-object v1, p0, Lcom/android/gallery3d/ui/TileImageView$TileQueue;->mHead:Lcom/android/gallery3d/ui/TileImageView$Tile;

    if-nez v1, :cond_0

    const/4 v0, 0x1

    .line 781
    .local v0, wasEmpty:Z
    :goto_0
    iget-object v1, p0, Lcom/android/gallery3d/ui/TileImageView$TileQueue;->mHead:Lcom/android/gallery3d/ui/TileImageView$Tile;

    iput-object v1, p1, Lcom/android/gallery3d/ui/TileImageView$Tile;->mNext:Lcom/android/gallery3d/ui/TileImageView$Tile;

    .line 782
    iput-object p1, p0, Lcom/android/gallery3d/ui/TileImageView$TileQueue;->mHead:Lcom/android/gallery3d/ui/TileImageView$Tile;

    .line 783
    return v0

    .line 780
    .end local v0           #wasEmpty:Z
    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method


text:
[![travis](https://img.shields.io/travis/adrai/node-viewmodel.svg)](https://travis-ci.org/adrai/node-viewmodel) [![npm](https://img.shields.io/npm/v/viewmodel.svg)](https://npmjs.org/package/viewmodel)

Node-viewmodel is a node.js module for multiple databases.
It can be very useful if you work with (d)ddd, cqrs, eventdenormalizer, host, etc.

# Installation

    $ npm install viewmodel

# Usage

## Connecting to an in-memory repository in read mode

	var viewmodel = require('viewmodel');

	viewmodel.read(function(err, repository) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }
    });

## Connecting to any repository (mongodb in the example / mode=write)
Make shure you have installed the required driver, in this example run: 'npm install mongodb'.

    var viewmodel = require('viewmodel');

    viewmodel.write(
        {
            type: 'mongodb',
            host: 'localhost',      // optional
            port: 27017,            // optional
            dbName: 'viewmodel',    // optional
            timeout: 10000          // optional
        },
        function(err, repository) {
            if(err) {
                console.log('ohhh :-(');
                return;
            }
        }
    );

## Catch connect ad disconnect events

    var repository = viewmodel.write({ type: 'mongodb' });
    repository.on('connect', function() {
        console.log('hello from event');
    });
    repository.on('disconnect', function() {
        console.log('bye');
    });
    repository.connect();

## Define a collection...

    var dummyRepo = repository.extend({
        collectionName: 'dummy'
    });

## Create a new viewmodel (only in write mode)

    dummyRepo.get(function(err, vm) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }

        vm.set('myProp', 'myValue');
        vm.set('myProp.deep', 'myValueDeep');

        console.log(vm.toJSON());

        console.log(vm.has('myProp.deep'));

        dummyRepo.commit(vm, function(err) {
        });
        // or you can call commit directly on vm...
        vm.commit(function(err) {
        });
    });

## Find...

    // the query object ist like in mongoDb...
    dummyRepo.find({ color: 'green' }, function(err, vms) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }

        // vms is an array of all what is in the repository
        var firstItem = vms[0];
        console.log('the id: ' + firstItem.id);
        console.log('the saved value: ' + firstItem.get('color'));
    });

## Find with query options

    // the query object ist like in mongoDb...
    dummyRepo.find({ color: 'green' }, { limit: 2, skip: 1 }, function(err, vms) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }

        // vms is an array of all what is in the repository
        var firstItem = vms[0];
        console.log('the id: ' + firstItem.id);
        console.log('the saved value: ' + firstItem.get('color'));
    });

## FindOne

    // the query object ist like in mongoDb...
    dummyRepo.findOne({ color: 'green' }, function(err, vm) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }

        console.log('the id: ' + vm.id);
        if (vm.has('color')) {
            console.log('the saved value: ' + vm.get('color'));
        }
    });

## Find by id...

    // the query object ist like in mongoDb...
    dummyRepo.get('myId', function(err, vm) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }

        console.log('the id: ' + vm.id);
        console.log('the saved value: ' + vm.get('color'));
    });

## Delete a viewmodel (only in write mode)

    dummyRepo.get('myId', function(err, vm) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }

        vm.destroy();

        dummyRepo.commit(vm, function(err) {
        });
        // or you can call commit directly on vm...
        vm.commit(function(err) {
        });
    });

## Obtain a new id

    myQueue.getNewId(function(err, newId) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }

        console.log('the new id is: ' + newId);
    });

## Clear a "collection" (only in write mode)

    dummyRepo.clear(function(err) {
        if(err) {
            console.log('ohhh :-(');
            return;
        }
    });

# Implementation differences

## mongodb
For mongodb you can define indexes for performance boosts in find function.

    var dummyRepo = repository.extend({
        collectionName: 'dummy',
        indexes: [
            'profileId',
            // or:
            { profileId: 1 },
            // or:
            { index: {profileId: 1}, options: {} }
        ]
    });

## redis
The find function does ignore the query argument and always fetches all items in the collection.

#[Release notes](https://github.com/adrai/node-viewmodel/blob/master/releasenotes.md)

# Database Support
Currently these databases are supported:

1. inmemory
2. mongodb ([node-mongodb-native] (https://github.com/mongodb/node-mongodb-native))
3. couchdb ([cradle] (https://github.com/cloudhead/cradle))
4. tingodb ([tingodb] (https://github.com/sergeyksv/tingodb))
5. redis ([redis] (https://github.com/mranney/node_redis))
6. azuretable ([azure-storage](https://github.com/Azure/azure-storage-node))
7. documentdb ([documentdb](https://github.com/Azure/azure-documentdb-node), [doqmentdb](https://github.com/a8m/doqmentdb))
8. elasticsearch ([elasticsearch] (https://github.com/elastic/elasticsearch-js))

## own db implementation
You can use your own db implementation by extending this...

    var Repository = require('viewmodel').Repository,
    util = require('util'),
        _ = require('lodash');

    function MyDB(options) {
      Repository.call(this, options);
    }

    util.inherits(MyDB, Repository);

    _.extend(MyDB.prototype, {

      ...

    });

    module.exports = MyDB;

# License

Copyright (c) 2015 Adriano Raiano

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.


text:
<?php

namespace vpourvalek\FactionBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class vpourvalekFactionBundle extends Bundle
{
}


text:
package com.researchspace.api.clientmodel;

public enum ActivityDomain {
RECORD,NOTEBOOK,FOLDER,WORKSPACE
}


text:
function parseJSON(str) {
	try {
		return JSON.parse(str);
	}
	catch(e) {
		return undefined;
	}
}

function getQS(obj) {
	var arr = Object.keys(obj);
	for(var i = 0; i < arr.length; i++) {
		arr[i] = escape(arr[i]) + "=" + escape(obj[arr[i]]);
	}
	return arr.join("&");
}
function parseQS(str) {
	var arr = str.split("&");
	var obj = {};
	for(var i = 0; i < arr.length; i++) {
		var pair = arr[i].split("=");
		obj[unescape(pair[0])] = unescape(pair[1] || "");
	}
	return obj;
}
function ajax(url, get, post, cb, err) {
	var qs = getQS(get);
	if(qs != "") {
		url += "?" + qs;
	}
	var xhr = new XMLHttpRequest() || new XDomainRequest();
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {
			if(cb && xhr.status >= 200 && xhr.status < 400) {
				cb(parseQS(xhr.responseText));
			}
			else if(err) {
				err();
			}
		}
	};
	xhr.open("POST", url, true);
	xhr.send(getQS(post));
}
function sync(){
	ajax("http://" + localStorage.ip + ":" + localStorage.port + "/sync", {}, {
		"user": localStorage.user || sessionStorage.user,
		"token": localStorage.token || sessionStorage.token,
		"data": localStorage.unSynced || "[]",
		"feedback" : localStorage.feedback || "[]",
		"deleted" : localStorage.deleted || "[]"
	}, function(result){
		if(result.code == 0){
			localStorage.data = result.data;
			localStorage.matches = result.matches;
			localStorage.teams = result.teams;
			localStorage.userTeam = result.team;
			localStorage.unSynced = "[]";
			localStorage.feedback = "[]";
			localStorage.deleted = "[]";
			$('#loadingSync').html("Done!");
			console.log("synced");
			localStorage.hasSynced = true;
		}else if(result.code == 1){
			$('#loadingSync').html('Log in first!');
			setTimeout(function() {
				$(':mobile-pagecontainer').pagecontainer('change', 'login.html', {transition: "none"});
			}, 1000);
		}else{
			$('#loadingSync').html('Internal Error');
		}
	}, function() {
		$('#loading').html('Error connecting to server');
	});
}
function autoSync(){
	ajax("http://" + localStorage.ip + ":" + localStorage.port + "/sync", {}, {
		"user": localStorage.user || sessionStorage.user,
		"token": localStorage.token || sessionStorage.token,
		"data": localStorage.unSynced || "[]",
		"feedback" : localStorage.feedback || "[]",
		"deleted" : localStorage.deleted || "[]"
	}, function(result){
		if(result.code == 0){
			localStorage.data = result.data;
			localStorage.matches = result.matches;
			localStorage.teams = result.teams;
			localStorage.userTeam = result.team;
			localStorage.unSynced = "[]";
			localStorage.feedback = "[]";
			localStorage.deleted = "[]";
			console.log("synced");
			localStorage.hasSynced = true;
		}else if(result.code == 1){
			console.log("cant sync -> not logged in")
		}else{
			console.log("cant sync -> internal error")
		}
	}, function() {
		$('#loadingSync').html('Error connecting to server');
	});
}

Array.prototype.last = function() {
	return this[this.length - 1];
};

$(document).ready(function() {

	if(navigator.onLine){
		autoSync();
	}

	$('.panelLink').click(function(){
		$("[data-role=panel]").panel("close");
	});

	if(localStorage.user !== undefined){

		var userD = document.createTextNode(" " + localStorage.user);
		//document.getElementById("UserDropdown").innerHTML = '

View Profile

Log Out

'
		$('.nameDisplay').html(userD);
		$('.loginLink').html('Log Out');;
		$('.loginLink').attr('id', "logout");
		$('.loginLink').attr('href', "#" );
		document.getElementById("logout").onclick = function() {
			ajax("http://" + localStorage.ip + ":" + localStorage.port + "/logout", {}, {"user" : localStorage.user, "token" : localStorage.token}, function(result) {
				if(result.code == 0) {
					localStorage.removeItem('user');
					localStorage.removeItem('token');
					$('.loginLink').html('Log In');;
	                $('.loginLink').removeAttr('id');
	                $('.loginLink').attr('href', "login.html" );
	                $('.nameDisplay').html("");
	                location = "index.html";
				}
				else if(result.code == 1) {
					alert("invalid token");
				}
				else {
					alert("oops");
				}
			});
			return false;
		}
		document.getElementById("view_prof").onclick = function() {
			alert("Hello and have a good day, " + localStorage.user + "\nToken: " + localStorage.token + "\nLogged in indefinitely.\nIP: " + localStorage.ip+":"+localStorage.port);
		}
	} else if (sessionStorage.user !== undefined) {

		var userD = document.createTextNode(" " + sessionStorage.user);
		//document.getElementById("loginDiv").innerHTML = 'Log Out'
		// document.getElementById('nameD').appendChild(userD);
		$('.nameDisplay').html(userD);
		$('.loginLink').html('Log Out');;
		$('.loginLink').attr('id', "logout");
		$('.loginLink').attr('href', "#" );
		document.getElementById("logout").onclick = function() {

			ajax("http://" + localStorage.ip + ":" + localStorage.port + "/logout", {}, {"user" : sessionStorage.user, "token" : sessionStorage.token}, function(result) {
				if(result.code == 0) {
					sessionStorage.removeItem('user');
					sessionStorage.removeItem('token');
					$('.loginLink').html('Log In');;
		            $('.loginLink').removeAttr('id');
		            $('.loginLink').attr('href', "login.html" );
		            $('.nameDisplay').html("");
		            location = "index.html";
				}
				else if(result.code == 1) {
					alert("invalid token");
				}
				else {
					alert("oops");
				}
			});
			return false;

		}
	} else {
	}
		$('.button').hover(function(){
			$(this).toggleClass('button_hovered')
		});
		$('.button').bind('touchstart',function(){
			$(this).addClass('button_hovered')
		});
		$('.button').bind('touchend',function(){
			$(this).removeClass('button_hovered')
		});

});


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mémoires de la Société Royale de Botanique de Belgique 29: 222 (1890)

#### Original name
Belonidium imperspicuum Sacc., E. Bommer & M. Rousseau

### Remarks
null


text:
TRANSACTION

STOCK OPNAME

					SEARCH BY :

						<select name="forecast_param" class="form-control filter1">
							<option value="aw.warehouse_name">WAREHOUSE</option>
							<option value="ae.employee_name">CREATED BY</option>
							<option value="3">DATE</option>
						</select>
						<input type="text" class="form-control value1" id="ddd" name="forecast_param1_value" placeholder="value">
						<button type="submit" name="submit_param" class="btn btn-default" onclick="excecuteSearch()"></button>

                <a href="<?=base_url('asset/stockopname/insert')?>"><button class="btn btn-primary btn-atas">NEW</button>

								No
								Stock Opname Code
								Warehouse
                                Created By
                                Date
                                Status
                                Action


text:
describe Dymos::Model do
  describe "不正なfield" do
    it "末尾に?は使えない" do
      expect { Class.new(Dymos::Model) do
        field "hoge?", :string
      end }.to raise_error
    end
    it "type:boolには初期値が必須" do
      expect { Class.new(Dymos::Model) do
        field "hoge", :boolean
      end }.to raise_error
    end
  end
  class DummyUser < Dymos::Model
    table :dummy
    field :id, :string, desc: 'hoge'
    field :name, :string, desc: '名前'
    field :email, :string
    field :list, :string_set
    field :count, :integer
    field :enable, :boolean, default: false

    field :created_at, :time
    field :updated_at, :time

    validates :id, :presence => true
    validates :name, :presence => true, length: {maximum: 8}
    validates :email, :presence => true, format: {with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i}
  end

  class DummyPost < Dymos::Model
    table :post
    field :id, :number
    field :body, :string
    validates :id, :presence => true
    validates :body, :presence => true, length: {maximum: 256}
  end

  def sample_user_hash
    {id: 'hoge', name: '太郎', email: 'hoge@example.net', count: 10, list: Set['a', 'b', 'c']}
  end

  before :all do
    @client.delete_table(table_name: 'dummy') if @client.list_tables[:table_names].include?('dummy')
    @client.create_table(
      table_name: 'dummy',
      attribute_definitions: [
        {attribute_name: 'id', attribute_type: 'S'}
      ],
      key_schema: [
        {attribute_name: 'id', key_type: 'HASH'}
      ],
      provisioned_throughput: {
        read_capacity_units: 1,
        write_capacity_units: 1,
      })
    @client.put_item(table_name: 'dummy', item: {id: 'hoge', name: '太郎', list: Set['a', 'b', 'c']})
    @client.put_item(table_name: 'dummy', item: {id: 'fuga', name: '次郎'})
    @client.put_item(table_name: 'dummy', item: {id: 'piyo', name: '三郎'})
    @client.put_item(table_name: 'dummy', item: {id: 'musashi', name: '巴'}) #削除用
    @client.put_item(table_name: 'dummy', item: {id: 'enable_id', name: 'enable', enable: true})
    @client.put_item(table_name: 'dummy', item: {id: 'disable_id', name: 'disable', enable: false})

    @client.delete_table(table_name: 'post') if @client.list_tables[:table_names].include?('post')
    @client.create_table(
      table_name: 'post',
      attribute_definitions: [
        {attribute_name: 'id', attribute_type: 'S'},
        {attribute_name: 'timestamp', attribute_type: 'N'},
      ],
      key_schema: [
        {attribute_name: 'id', key_type: 'HASH'},
        {attribute_name: 'timestamp', key_type: 'RANGE'},
      ],
      provisioned_throughput: {
        read_capacity_units: 1,
        write_capacity_units: 1,
      })
  end

#  let(:model) { Dummy.new }

  describe :fields do
    it do
      expect(DummyUser.fields.keys).to eq([:id, :name, :email, :list, :count, :enable, :created_at, :updated_at])
    end
  end
  describe "クラスマクロのデフォルト値" do
    it "設定されていなければnilを返す" do
      expect(DummyPost.new.id).to eq(nil)
    end

    class DummyModel < Dymos::Model
      field :id, :number, default: 0
      field :body, :string, default: "none"
    end

    it "idは0を返す" do
      expect(DummyModel.new.id).to eq(0)
    end

    it "bodyは'none'を返す" do
      expect(DummyModel.new.body).to eq('none')
    end
    it "enable?はfalseを返す" do
      model = DummyUser.new
      expect(model.enable?).to eq(false)
      model.enable = true
      expect(model.enable?).to eq(true)
    end
    it "上書きすることができる" do
      model = DummyModel.new
      model.id=1
      expect(model.id).to eq(1)
    end
  end

  describe :new do

    describe :field do
      it 'fieldで名前と型を定義' do
        model = DummyUser.new
        expect(model.methods).to include(:id, :id=, :id?, :id_type, :name, :name=, :name?, :name_type)
        model.id = 123
        expect(model.id).to eq(123)
        model.name = '太郎'
        expect(model.name).to eq('太郎')
        expect(model.name?).to eq(true)
        expect(model.name_desc).to eq('名前')
        expect(model.name_type).to eq(:string)

        model = DummyPost.new
        expect(model.id).to eq(nil)
        expect(model.methods).to include(:id, :id=, :id?, :id_type, :body, :body, :body?, :body_type)
        expect(model.methods).not_to include(:name)

      end
    end

    it 'コンストラクタで定義' do
      model = DummyUser.new(sample_user_hash)
      expect(model.id).to eq('hoge')
      expect(model.name).to eq('太郎')
      expect(model.email).to eq('hoge@example.net')
      expect(model.list).to eq(Set['a', 'b', 'c'])
    end

  end

  describe :validate do
    it 'バリデート' do
      model = DummyUser.new(id: 'hoge', name: '', email: 'hoge')
      expect(model.valid?).to eq(false)
      model.name='太郎'
      expect(model.valid?).to eq(false)
      model.email='hoge@example.net'
      expect(model.valid?).to eq(true)
    end
  end

  describe :attributes= do
    it 'まとめて代入' do
      model = DummyUser.new
      model.attributes = sample_user_hash
      expect(model.id).to eq('hoge')
      expect(model.name).to eq('太郎')
      expect(model.email).to eq('hoge@example.net')
      expect(model.count).to eq(10)
      expect(model.list).to eq(Set['a', 'b', 'c'])
    end
  end

  describe :attributes do
    it 'まとめて取得' do
      model = DummyUser.new(sample_user_hash)
      expect(model.attributes).to eq(
                                    id:'hoge',
                                    name:'太郎',
                                    email:'hoge@example.net',
                                    list:Set['a', 'b', 'c'],
                                    count:10,
                                    enable:false,
                                    created_at:nil,
                                    updated_at:nil
                                  )
    end
  end

  describe :dynamo, :order => :defined do

    describe :describe do
      it "table情報を得る" do
        describe=DummyUser.describe
        expect(describe[:table][:table_name]).to eq('dummy')
        expect(describe[:table][:key_schema].first[:attribute_name]).to eq('id')
        expect(describe[:table][:key_schema].first[:key_type]).to eq('HASH')
      end
    end

    describe :key_scheme do
      it "キー情報" do
        expect(DummyUser.key_scheme.first[:attribute_name]).to eq('id')
        expect(DummyUser.key_scheme.first[:key_type]).to eq('HASH')

        expect(DummyPost.key_scheme.first[:attribute_name]).to eq('id')
        expect(DummyPost.key_scheme.first[:key_type]).to eq('HASH')
        expect(DummyPost.key_scheme.last[:attribute_name]).to eq('timestamp')
        expect(DummyPost.key_scheme.last[:key_type]).to eq('RANGE')
      end
    end

    describe :find do
      it "ユーザを抽出" do
        user = DummyUser.find('hoge')
        expect(user.id).to eq('hoge')
        expect(user.name).to eq('太郎')
      end
    end

    describe :save, :order => :defined do
      it '書き込み' do
        user = DummyUser.new
        user.id = 'aiueo'
        user.name = '四郎'
        user.email = 'hoge@sample.net'
        user.enable = true
        expect(user.created_at).to eq(nil)
        now = Time.now
        Timecop.freeze(now)
        result = user.save!
        expect(result).to eq(true)
        expect(user.created_at.to_s).to eq(now.to_s)
        expect(user.updated_at.to_s).to eq(now.to_s)
      end

      it '更新' do
        user = DummyUser.new
        user.id = 'aiueo'
        user.name = '四郎'
        user.email = 'hoge@sample.net'
        now = Time.now
        Timecop.freeze(now)
        user.save!
        user.email = 'hoge@sample.net'
        Timecop.freeze(now+1)
        user.update!
        expect(user.created_at.to_s).to eq(now.to_s)
        expect(user.updated_at.to_s).not_to eq(now.to_s)
      end
    end

    describe :all do
      it "すべてのユーザを抽出" do
        users = DummyUser.all
        expect(users.size).to eq(7)
      end
      it :limit do
        users = DummyUser.limit(2).all
        expect(users.size).to eq(2)
      end
    end

    describe :find do
      it "ユーザを抽出" do
        user = DummyUser.find('hoge')
        expect(user.id).to eq('hoge')
        expect(user.name).to eq('太郎')
      end
    end
  end

  describe "変更検知" do
    class DummyModel < Dymos::Model
      field :id, :number, default: 0
      field :body, :string, default: "none"
    end

    it "新規モデル" do
      user = DummyModel.new
      expect(user.changes).to eq({})
      expect(user.changed?).to eq(false)
      user.id = 1
      expect(user.changed?).to eq(true)
      expect(user.changes).to eq({"id" => [0, 1]})
      user.body = "hoge"
      expect(user.changes).to eq({"id" => [0, 1], "body" => ['none', 'hoge']})
    end

    describe "DBから引いたモデル" do
      it "" do
        user = DummyUser.find('hoge')
        expect(user.changes).to eq({})
        expect(user.changed?).to eq(false)
        user.id = 1
        expect(user.changed?).to eq(true)
        expect(user.id_changed?).to eq(true)
        expect(user.changes).to eq({"id" => ["hoge", 1]})
      end
    end
  end

  describe :persistence do
    describe "新規モデル" do
      it do
        user = DummyUser.new
        expect(user.new_record?).to eq(true)
        expect(user.destroyed?).to eq(false)
        expect(user.persisted?).to eq(false)
      end

      describe "DBから引いたモデル" do
        it do
          user = DummyUser.find('musashi')
          expect(user.new_record?).to eq(false)
          expect(user.destroyed?).to eq(false)
          expect(user.persisted?).to eq(true)
          user.delete
          expect(user.destroyed?).to eq(true)
          expect(DummyUser.find('musashi')).to eq(nil)
        end
        it 'enableはBoolとして扱われる' do
          user = DummyUser.find('enable_id')
          expect(user.enable).to eq(true)
          expect(user.enable?).to eq(true)
          user = DummyUser.find('disable_id')
          expect(user.enable).to eq(false)
          expect(user.enable?).to eq(false)
        end
      end
    end
  end

  describe :callbacks do
    class DummyArticle < Dymos::Model
      table :dummy
      field :id, :integer
      field :title, :string
      field :updated_at, :time

      after_set_title do
        self.updated_at = Time.now
      end
    end
    it 'タイトルが挿入されるとタイトルを2回繰り返して更新時間が自動的に挿入される' do
      article = DummyArticle.new
      expect(article.title).to eq(nil)
      expect(article.updated_at).to eq(nil)
      article.title="hoge"*2
      expect(article.title).to eq("hogehoge")
      expect(article.updated_at.class).to eq(Time)
    end
    class DummyTable < Dymos::Model
      table :dummy
      before_save do
        fail StandardError
      end
    end
    it "DummyTableをsaveするとfalseを返す" do
      d = DummyTable.new
      result=d.save
      expect(result).to eq(false)
    end
    it "DummyTableをsave!すると例外を返す" do
      expect { DummyTable.new.save! }.to raise_error
    end
  end
end