text:
<Record>
<Term>Neuromuscular Blocking Agents</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Neuromuscular Agents</ParentTerm>
<ClassificationPath>Chemical Actions and Uses/Pharmacologic Actions/Physiological Effects of Drugs/Peripheral Nervous System Agents/Neuromuscular Agents/Neuromuscular Blocking Agents</ClassificationPath>
<BroaderTerm>Neuromuscular Agents</BroaderTerm>
<BroaderTerm>Pharmacologic Actions</BroaderTerm>
<BroaderTerm>Peripheral Nervous System Agents</BroaderTerm>
<BroaderTerm>Chemical Actions and Uses</BroaderTerm>
<BroaderTerm>Neuromuscular Blocking Agents</BroaderTerm>
<BroaderTerm>Physiological Effects of Drugs</BroaderTerm>
<ChildTerm>Neuromuscular Nondepolarizing Agents</ChildTerm>
<ChildTerm>Neuromuscular Depolarizing Agents</ChildTerm>
<Synonym>Neuromuscular Blocking Agents</Synonym>
<Synonym>Neuromuscular Blockers</Synonym>
<Description>Drugs that interrupt transmission of nerve impulses at the skeletal neuromuscular junction. They can be of two types, competitive, stabilizing blockers (NEUROMUSCULAR NONDEPOLARIZING AGENTS) or noncompetitive, depolarizing agents (NEUROMUSCULAR DEPOLARIZING AGENTS). Both prevent acetylcholine from triggering the muscle contraction and they are used as anesthesia adjuvants, as relaxants during electroshock, in convulsive states, etc.</Description>
<Source>MeSH</Source>
</Record>


text:
package mutationoperators;

import java.io.File;
import java.util.HashMap;

public abstract class ConstructorTest extends InheritTest {

	/////////////////////////////////////////
	/// Constants
	/////////////////////////////////////////

	/**
	* The class name of the file where the method is contained in.
	*/
	protected static String CLASS_NAME = "Foo";

	/////////////////////////////////////////
	/// Fields
	/////////////////////////////////////////

	/////////////////////////////////////////
	/// Methods
	/////////////////////////////////////////

	@Override
	protected void initializeContextFiles() {
		// since we do not need external classes for most cases, we do not initialize any context
	}

	/**
	* Returns the other fields and methods of the main file under test. Will be used in {@link #createFieldMethodSourceCode(String)}.
	* @return The fields and methods of the file under test.
	*/
	protected abstract String getOtherClassContent();

	/**
	* Embed methodbody into method and class, creates files for prefix and postfix version
	* 	and calls {@link BasicTest#compareMatches(File, File, String) compareMatches(File, File)} in {@link BasicTest}.
	* @param prefixMethodBody The prefix method body.
	* @param postfixMethodBody The postfix method body.
	* @return The number of applications of the {@link MutationOperator} under test.
	*/
	public HashMap<String, Integer> compareMatches(String arguments, String prefixMethodBody, String postfixMethodBody) {
		File preFix = this.createPrefixSourceFile(this.createFieldConstructorSourceCode(arguments, prefixMethodBody));
		File postFix = this.createPostfixSourceFile(this.createFieldConstructorSourceCode(arguments, postfixMethodBody));

	return compareMatches(preFix, postFix, CLASS_NAME);
	}

	/**
	* Creates and returns a file at the prefix default path.
	* @param sourceCode The file's source code.
	* @return The temporary file for the prefix version.
	*/
	protected File createPrefixSourceFile(String sourceCode) {
		return this.createSourceFile(CLASS_NAME, sourceCode, PATH_FOR_PREFIX_FILES);
	}

	/**
	* Creates and returns a file at the postfix default path.
	* @param sourceCode The file's source code.
	* @return The temporary file for the postfix version.
	*/
	protected File createPostfixSourceFile(String sourceCode) {
		return this.createSourceFile(CLASS_NAME, sourceCode, PATH_FOR_POSTFIX_FILES);
	}

	/**
	* Adds class stuff around the snippet.
	* @param snippet
	* @return The complete file content.
	*/
	protected String surroundWithClass(String classname, String snippet){
		return "public class " + classname + " { \n" + snippet + " \n};";
	}

	/**
	* Adds class stuff with extends and implements around the snippet.
	* @param classname
	* @param extendName
	* @param implementNames
	* @param snippet
	* @return The complete file content.
	*/
	protected String surroundWithClass(String classname, String extendName, String implementNames, String snippet){
		String strResult = "public class " + classname + " ";
		if(extendName != ""){
			strResult = strResult + "extends " + extendName + " ";
		}
		if(implementNames != ""){
			strResult = strResult + "implements " + implementNames + " ";
		}
		strResult = strResult + "{ \n" + snippet + " \n};";
		return strResult;
	}

	/**
	* Embed the method's body into a method and the method into a class.<p>
	* Furthermore adds class fields and other methods from {@link #getOtherClassContent()}.
	* @param methodBody The method's body.
	* @return Returns the whole code of a .java class.
	*/
	protected String createFieldConstructorSourceCode(String arguments, String methodBody){
		StringBuilder methodSource = new StringBuilder();
		methodSource.append("public ");
		methodSource.append(CLASS_NAME);
		methodSource.append("(");
		methodSource.append(arguments);
		methodSource.append(") { ");
		methodSource.append(methodBody);
		methodSource.append(" }");
		return surroundWithClass(CLASS_NAME, getExtends(), getImplements(), getOtherClassContent() + "\n" + methodSource.toString());
	}

}

redpajama_set_name: RedPajamaGithub


text:
<?php
session_start();
?>

<!DOCTYPE html>

<title>My Space</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="lib/css/bootstrap.css" rel="stylesheet">
<link href="my_css/mycss_myspace.css" rel="stylesheet" type="text/css">
<link href="my_css/titlebar.css" rel="stylesheet" type="text/css">
<link href="my_css/categorylist.css" rel="stylesheet" type="text/css">

Categories

    Home
 Upload
    <button id="myspace_orders_btn"> Orders </button>
    <button id="myspace_setting_btn"> Setting </button>
        <button id="myspace_upload_btn"> Upload </button>

  <button id="shopping_cart_btn" onclick="goto_cart()"> Cart </button>

  <?php include("include/categorylist.php"); ?>

Books You Bought

              Diary of a Wimpy Kid
            Processing
            11/5, 2013
            $8.00
            2

              Diary
            Processing
            11/5, 2013
            $8.00
            2

Your Might Also Like

 Ender's Game

            Orson Scott Card

 Ender's Game

            Orson Scott Card

Your Basic Info

        Current Account Picture:
                  Edit

        User Name:
        <input class="myspace_input_text" type="text" value="Call Of Duty">

        Login Mail:
        <input class="myspace_input_text" type="text" value="ykdacd@qq.com">

        Phone Number:
        <input class="myspace_input_text" type="text" value="18591974748">

Manage Your Address

        District:
        <input class="myspace_input_text" type="text" value="Redwood City, California, US">

        Address:
        <input class="myspace_input_text" type="text" value="209 Redwood Shores Pkwy">

        Zipcode:
        <input class="myspace_input_text" type="text" value="90043">

Secure Service

 Edit your passward

        Strong password makes your account more secure. We recommend that you change your password regularly and contains a set of numbers and letters, and the length of more than six or more passwords

        Bind your phone number

        Bind your phone, you can enjoy the rich Scatter phone services, such as phone login, phone retrieving your password, opening mobile dynamic password, etc.

        Security question

        One way to find your passward. We recommend that you set up an question which is easy to remember but most diffcult by others answering to more effectively protect your passwords secure.

Internship opportunity

 ©2013 Scatter Inc. Site Terms of Service Privacy Policy Developers About Us


text:
<title>Fixed-size Arrays in C - FFTW 3.3.4</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="FFTW 3.3.4">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Multi_002ddimensional-Array-Format.html#Multi_002ddimensional-Array-Format" title="Multi-dimensional Array Format">
<link rel="prev" href="Column_002dmajor-Format.html#Column_002dmajor-Format" title="Column-major Format">
<link rel="next" href="Dynamic-Arrays-in-C.html#Dynamic-Arrays-in-C" title="Dynamic Arrays in C">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Dynamic Arrays in C,
Previous: Column-major Format,
Up: Multi-dimensional Array Format

3.2.3 Fixed-size Arrays in C

A multi-dimensional array whose size is declared at compile time in C
is already in row-major order.  You don't have to do anything
special to transform it.  For example:

     {
          fftw_complex data[N0][N1][N2];
          fftw_plan plan;
          ...
          plan = fftw_plan_dft_3d(N0, N1, N2, &data[0][0][0], &data[0][0][0],
                                  FFTW_FORWARD, FFTW_ESTIMATE);
          ...
     }

This will plan a 3d in-place transform of size N0 x N1 x N2.
Notice how we took the address of the zero-th element to pass to the
planner (we could also have used a typecast).

However, we tend to discourage users from declaring their
arrays in this way, for two reasons.  First, this allocates the array
on the stack (“automatic” storage), which has a very limited size on
most operating systems (declaring an array with more than a few
thousand elements will often cause a crash).  (You can get around this
limitation on many systems by declaring the array as
static and/or global, but that has its own drawbacks.)
Second, it may not optimally align the array for use with a SIMD
FFTW (see SIMD alignment and fftw_malloc).  Instead, we recommend
using fftw_malloc, as described below.


text:
// Copyright (c) Microsoft, All rights reserved. See License.txt in the project root for license information.

;(function (factory) {
  var objectTypes = {
    'function': true,
    'object': true
  };

  function checkGlobal(value) {
    return (value && value.Object === Object) ? value : null;
  }

  var freeExports = (objectTypes[typeof exports] && exports && !exports.nodeType) ? exports : null;
  var freeModule = (objectTypes[typeof module] && module && !module.nodeType) ? module : null;
  var freeGlobal = checkGlobal(freeExports && freeModule && typeof global === 'object' && global);
  var freeSelf = checkGlobal(objectTypes[typeof self] && self);
  var freeWindow = checkGlobal(objectTypes[typeof window] && window);
  var moduleExports = (freeModule && freeModule.exports === freeExports) ? freeExports : null;
  var thisGlobal = checkGlobal(objectTypes[typeof this] && this);
  var root = freeGlobal || ((freeWindow !== (thisGlobal && thisGlobal.window)) && freeWindow) || freeSelf || thisGlobal || Function('return this')();

  // Because of build optimizers
  if (typeof define === 'function' && define.amd) {
    define(['./rx.lite'], function (Rx, exports) {
      return factory(root, exports, Rx);
    });
  } else if (typeof module === 'object' && module && module.exports === freeExports) {
    module.exports = factory(root, module.exports, require('rx-lite'));
  } else {
    root.Rx = factory(root, {}, root.Rx);
  }
}.call(this, function (root, exp, Rx, undefined) {

  // Aliases
  var Observable = Rx.Observable,
    observableFromPromise = Observable.fromPromise,
    observableThrow = Observable.throwError,
    AnonymousObservable = Rx.AnonymousObservable,
    ObservableBase = Rx.ObservableBase,
    AsyncSubject = Rx.AsyncSubject,
    disposableCreate = Rx.Disposable.create,
    CompositeDisposable = Rx.CompositeDisposable,
    immediateScheduler = Rx.Scheduler.immediate,
    defaultScheduler = Rx.Scheduler['default'],
    inherits = Rx.internals.inherits,
    isScheduler = Rx.Scheduler.isScheduler,
    isPromise = Rx.helpers.isPromise,
    isFunction = Rx.helpers.isFunction,
    isIterable = Rx.helpers.isIterable,
    isArrayLike = Rx.helpers.isArrayLike;

  Observable.wrap = function (fn) {
    function createObservable() {
      return Observable.spawn.call(this, fn.apply(this, arguments));
    }

    createObservable.__generatorFunction__ = fn;
    return createObservable;
  };

  var spawn = Observable.spawn = function () {
    var gen = arguments[0], self = this, args = [];
    for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }

    return new AnonymousObservable(function (o) {
      var g = new CompositeDisposable();

      if (isFunction(gen)) { gen = gen.apply(self, args); }
      if (!gen || !isFunction(gen.next)) {
        o.onNext(gen);
        return o.onCompleted();
      }

      function processGenerator(res) {
        var ret = tryCatch(gen.next).call(gen, res);
        if (ret === errorObj) { return o.onError(ret.e); }
        next(ret);
      }

      processGenerator();

      function onError(err) {
        var ret = tryCatch(gen.next).call(gen, err);
        if (ret === errorObj) { return o.onError(ret.e); }
        next(ret);
      }

      function next(ret) {
        if (ret.done) {
          o.onNext(ret.value);
          o.onCompleted();
          return;
        }
        var obs = toObservable.call(self, ret.value);
        var value = null;
        var hasValue = false;
        if (Observable.isObservable(obs)) {
          g.add(obs.subscribe(function(val) {
            hasValue = true;
            value = val;
          }, onError, function() {
            hasValue && processGenerator(value);
          }));
        } else {
          onError(new TypeError('type not supported'));
        }
      }

      return g;
    });
  };

  function toObservable(obj) {
    if (!obj) { return obj; }
    if (Observable.isObservable(obj)) { return obj; }
    if (isPromise(obj)) { return Observable.fromPromise(obj); }
    if (isGeneratorFunction(obj) || isGenerator(obj)) { return spawn.call(this, obj); }
    if (isFunction(obj)) { return thunkToObservable.call(this, obj); }
    if (isArrayLike(obj) || isIterable(obj)) { return arrayToObservable.call(this, obj); }
    if (isObject(obj)) {return objectToObservable.call(this, obj);}
    return obj;
  }

  function arrayToObservable (obj) {
    return Observable.from(obj).concatMap(function(o) {
      if(Observable.isObservable(o) || isObject(o)) {
        return toObservable.call(null, o);
      } else {
        return Rx.Observable.just(o);
      }
    }).toArray();
  }

  function objectToObservable (obj) {
    var results = new obj.constructor(), keys = Object.keys(obj), observables = [];
    for (var i = 0, len = keys.length; i < len; i++) {
      var key = keys[i];
      var observable = toObservable.call(this, obj[key]);

      if(observable && Observable.isObservable(observable)) {
        defer(observable, key);
      } else {
        results[key] = obj[key];
      }
    }

    return Observable.forkJoin.apply(Observable, observables).map(function() {
      return results;
    });

    function defer (observable, key) {
      results[key] = undefined;
      observables.push(observable.map(function (next) {
        results[key] = next;
      }));
    }
  }

  function thunkToObservable(fn) {
    var self = this;
    return new AnonymousObservable(function (o) {
      fn.call(self, function () {
        var err = arguments[0], res = arguments[1];
        if (err) { return o.onError(err); }
        if (arguments.length > 2) {
          var args = [];
          for (var i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
          res = args;
        }
        o.onNext(res);
        o.onCompleted();
      });
    });
  }

  function isGenerator(obj) {
    return isFunction (obj.next) && isFunction (obj['throw']);
  }

  function isGeneratorFunction(obj) {
    var ctor = obj.constructor;
    if (!ctor) { return false; }
    if (ctor.name === 'GeneratorFunction' || ctor.displayName === 'GeneratorFunction') { return true; }
    return isGenerator(ctor.prototype);
  }

  function isObject(val) {
    return Object == val.constructor;
  }

  /**
   * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
   *
   * @example
   * var res = Rx.Observable.start(function () { console.log('hello'); });
   * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
   * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
   *
   * @param {Function} func Function to run asynchronously.
   * @param {Scheduler} [scheduler]  Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
   * @param [context]  The context for the func parameter to be executed.  If not specified, defaults to undefined.
   * @returns {Observable} An observable sequence exposing the function's result value, or an exception.
   *
   * Remarks
   * * The function is called immediately, not during the subscription of the resulting sequence.
   * * Multiple subscriptions to the resulting sequence can observe the function's result.
   */
  Observable.start = function (func, context, scheduler) {
    return observableToAsync(func, context, scheduler)();
  };

  /**
   * Invokes the asynchronous function, surfacing the result through an observable sequence.
   * @param {Function} functionAsync Asynchronous function which returns a Promise to run.
   * @returns {Observable} An observable sequence exposing the function's result value, or an exception.
   */
  Observable.startAsync = function (functionAsync) {
    var promise = tryCatch(functionAsync)();
    if (promise === errorObj) { return observableThrow(promise.e); }
    return observableFromPromise(promise);
  };

  return Rx;
}));


text:
package de.isse.JaCoP;

import org.jacop.constraints.PrimitiveConstraint;
import org.jacop.core.BooleanVar;

import ua.cr2csop.constraints.Constraint;

/**
 * Adds a weight to a primitive constraints
 * @author alexander
 *
 */
public class WrappedPrimitiveConstraint {
	private PrimitiveConstraint pc;
	private int weight;
	private BooleanVar violationIndicator;
	private Constraint associatedConstraint;

	public WrappedPrimitiveConstraint(PrimitiveConstraint pc, int weight) {
		super();
		this.pc = pc;
		this.weight = weight;
	}

	public int getWeight() {
		return weight;
	}

	public void setWeight(int weight) {
		this.weight = weight;
	}

	public PrimitiveConstraint getPrimitiveConstraint() {
		return pc;
	}

	public void setPrimitiveConstraint(PrimitiveConstraint pc) {
		this.pc = pc;
	}

	public BooleanVar getViolationIndicator() {
		return violationIndicator;
	}

	public void setViolationIndicator(BooleanVar violationIndicator) {
		this.violationIndicator = violationIndicator;
	}

	public Constraint getAssociatedConstraint() {
		return associatedConstraint;
	}

	public void setAssociatedConstraint(Constraint associatedConstraint) {
		this.associatedConstraint = associatedConstraint;
	}

}


text:
package com.stratio.provider

import com.stratio.provider.Config.Property

import scala.reflect.ClassTag

/**
 * Abstract config builder, used to set a bunch of properties a build
 * a config object from them.
 *
 * @param properties Map of any-type properties.
 * @tparam Builder Current Builder implementation type.
 */
abstract class ConfigBuilder[Builder<:ConfigBuilder[Builder] ](
  val properties: Map[Property,Any] = Map()) extends Serializable { builder =>

  /**
   * Required properties to build a Deep config object.
   * At build time, if these properties are not set, an assert
   * exception will be thrown.
   */
  val requiredProperties: List[Property]

  /**
   * Instantiate a brand new Builder from given properties map
   *
   * @param props Map of any-type properties.
   * @return The new builder
   */
  def apply(props: Map[Property,Any]): Builder

  /**
   * Set (override if exists) a single property value given a new one.
   *
   * @param property Property to be set
   * @param value New value for given property
   * @tparam T Property type
   * @return A new builder that includes new value of the specified property
   */
  def set[T](property: Property,value: T): Builder =
    apply(properties + (property -> value))

  /**
   * Build the config object from current builder properties.
   *
   * @return The Deep configuration object.
   */
  def build(): Config = new Config {

    val properties = builder.properties

    require(
      requiredProperties.forall(properties.isDefinedAt),
      s"Not all properties are defined! : ${
        requiredProperties.diff(
          properties.keys.toList.intersect(requiredProperties))
      }")

  }

}

/**
 * Deep standard configuration object
 */
trait Config extends Serializable {

  /**
   * Contained properties in configuration object
   */
  val properties: Map[Property, Any]

  /**
   * Gets specified property from current configuration object
   * @param property Desired property
   * @tparam T Property expected value type.
   * @return An optional value of expected type
   */
  def get[T: ClassTag](property: Property): Option[T] =
    properties.get(property).map(_.asInstanceOf[T])

  /**
   * Gets specified property from current configuration object.
   * It will fail if property is not previously set.
   * @param property Desired property
   * @tparam T Property expected value type
   * @return Expected type value
   */
  def apply[T: ClassTag](property: Property): T = {
    get[T](property).get
  }
}

object Config {

  type Property = String

  /**
   * Defines how to act in case any parameter is not set
   * @param key Key that couldn't be obtained
   * @tparam T Expected type (used to fit in 'getOrElse' cases).
   * @return Throws an IllegalStateException.
   */
  def notFound[T](key: String): T =
    throw new IllegalStateException(s"Parameter $key not specified")

}


text:
#include <string.h>
#include "ruby.h"
#if HAVE_RUBY_ST_H
#include "ruby/st.h"
#endif
#if HAVE_ST_H
#include "st.h"
#endif
#include "unicode.h"
#include <math.h>

#ifndef RHASH_TBL
#define RHASH_TBL(hsh) (RHASH(hsh)->tbl)
#endif

#ifndef RHASH_SIZE
#define RHASH_SIZE(hsh) (RHASH(hsh)->tbl->num_entries)
#endif

#ifndef RFLOAT_VALUE
#define RFLOAT_VALUE(val) (RFLOAT(val)->value)
#endif

#ifdef HAVE_RUBY_ENCODING_H
#include "ruby/encoding.h"
#define FORCE_UTF8(obj) rb_enc_associate((obj), rb_utf8_encoding())
#else
#define FORCE_UTF8(obj)
#endif

#define check_max_nesting(state, depth) do {                                   \
    long current_nesting = 1 + depth;                                          \
    if (state->max_nesting != 0 && current_nesting > state->max_nesting)       \
        rb_raise(eNestingError, "nesting of %ld is too deep", current_nesting); \
} while (0);

static VALUE mJSON, mExt, mGenerator, cState, mGeneratorMethods, mObject,
             mHash, mArray, mInteger, mFloat, mString, mString_Extend,
             mTrueClass, mFalseClass, mNilClass, eGeneratorError,
             eCircularDatastructure, eNestingError;

static ID i_to_s, i_to_json, i_new, i_indent, i_space, i_space_before,
          i_object_nl, i_array_nl, i_check_circular, i_max_nesting,
          i_allow_nan, i_pack, i_unpack, i_create_id, i_extend;

typedef struct JSON_Generator_StateStruct {
    VALUE indent;
    VALUE space;
    VALUE space_before;
    VALUE object_nl;
    VALUE array_nl;
    int check_circular;
    VALUE seen;
    VALUE memo;
    VALUE depth;
    long max_nesting;
    int flag;
    int allow_nan;
} JSON_Generator_State;

#define GET_STATE(self)                       \
    JSON_Generator_State *state;              \
    Data_Get_Struct(self, JSON_Generator_State, state);

/*
 * Document-module: JSON::Ext::Generator
 *
 * This is the JSON generator implemented as a C extension. It can be
 * configured to be used by setting
 *
 *  JSON.generator = JSON::Ext::Generator
 *
 * with the method generator= in JSON.
 *
 */

static int hash_to_json_state_i(VALUE key, VALUE value, VALUE Vstate)
{
    VALUE json, buf, Vdepth;
    GET_STATE(Vstate);
    buf = state->memo;
    Vdepth = state->depth;

    if (key == Qundef) return ST_CONTINUE;
    if (state->flag) {
        state->flag = 0;
        rb_str_buf_cat2(buf, ",");
        if (RSTRING_LEN(state->object_nl)) rb_str_buf_append(buf, state->object_nl);
    }
    if (RSTRING_LEN(state->object_nl)) {
        rb_str_buf_append(buf, rb_str_times(state->indent, Vdepth));
    }
    json = rb_funcall(rb_funcall(key, i_to_s, 0), i_to_json, 2, Vstate, Vdepth);
    Check_Type(json, T_STRING);
    rb_str_buf_append(buf, json);
    OBJ_INFECT(buf, json);
    if (RSTRING_LEN(state->space_before)) {
        rb_str_buf_append(buf, state->space_before);
    }
    rb_str_buf_cat2(buf, ":");
    if (RSTRING_LEN(state->space)) rb_str_buf_append(buf, state->space);
    json = rb_funcall(value, i_to_json, 2, Vstate, Vdepth);
    Check_Type(json, T_STRING);
    state->flag = 1;
    rb_str_buf_append(buf, json);
    OBJ_INFECT(buf, json);
    state->depth = Vdepth;
    state->memo = buf;
    return ST_CONTINUE;
}

inline static VALUE mHash_json_transfrom(VALUE self, VALUE Vstate, VALUE Vdepth) {
    long depth, len = RHASH_SIZE(self);
    VALUE result;
    GET_STATE(Vstate);

    depth = 1 + FIX2LONG(Vdepth);
    result = rb_str_buf_new(len);
    state->memo = result;
    state->depth = LONG2FIX(depth);
    state->flag = 0;
    rb_str_buf_cat2(result, "{");
    if (RSTRING_LEN(state->object_nl)) rb_str_buf_append(result, state->object_nl);
    rb_hash_foreach(self, hash_to_json_state_i, Vstate);
    if (RSTRING_LEN(state->object_nl)) rb_str_buf_append(result, state->object_nl);
    if (RSTRING_LEN(state->object_nl)) {
        rb_str_buf_append(result, rb_str_times(state->indent, Vdepth));
    }
    rb_str_buf_cat2(result, "}");
    return result;
}

static int hash_to_json_i(VALUE key, VALUE value, VALUE buf)
{
    VALUE tmp;

    if (key == Qundef) return ST_CONTINUE;
    if (RSTRING_LEN(buf) > 1) rb_str_buf_cat2(buf, ",");
    tmp = rb_funcall(rb_funcall(key, i_to_s, 0), i_to_json, 0);
    Check_Type(tmp, T_STRING);
    rb_str_buf_append(buf, tmp);
    OBJ_INFECT(buf, tmp);
    rb_str_buf_cat2(buf, ":");
    tmp = rb_funcall(value, i_to_json, 0);
    Check_Type(tmp, T_STRING);
    rb_str_buf_append(buf, tmp);
    OBJ_INFECT(buf, tmp);

    return ST_CONTINUE;
}

/*
 * call-seq: to_json(state = nil, depth = 0)
 *
 * Returns a JSON string containing a JSON object, that is unparsed from
 * this Hash instance.
 * _state_ is a JSON::State object, that can also be used to configure the
 * produced JSON string output further.
 * _depth_ is used to find out nesting depth, to indent accordingly.
 */
static VALUE mHash_to_json(int argc, VALUE *argv, VALUE self)
{
    VALUE Vstate, Vdepth, result;
    long depth;

    rb_scan_args(argc, argv, "02", &Vstate, &Vdepth);
    depth = NIL_P(Vdepth) ? 0 : FIX2LONG(Vdepth);
    if (NIL_P(Vstate)) {
        long len = RHASH_SIZE(self);
        result = rb_str_buf_new(len);
        rb_str_buf_cat2(result, "{");
        rb_hash_foreach(self, hash_to_json_i, result);
        rb_str_buf_cat2(result, "}");
    } else {
        GET_STATE(Vstate);
        check_max_nesting(state, depth);
        if (state->check_circular) {
            VALUE self_id = rb_obj_id(self);
            if (RTEST(rb_hash_aref(state->seen, self_id))) {
                rb_raise(eCircularDatastructure,
                        "circular data structures not supported!");
            }
            rb_hash_aset(state->seen, self_id, Qtrue);
            result = mHash_json_transfrom(self, Vstate, LONG2FIX(depth));
            rb_hash_delete(state->seen, self_id);
        } else {
            result = mHash_json_transfrom(self, Vstate, LONG2FIX(depth));
        }
    }
    OBJ_INFECT(result, self);
    FORCE_UTF8(result);
    return result;
}

inline static VALUE mArray_json_transfrom(VALUE self, VALUE Vstate, VALUE Vdepth) {
    long i, len = RARRAY_LEN(self);
    VALUE shift, result;
    long depth = NIL_P(Vdepth) ? 0 : FIX2LONG(Vdepth);
    VALUE delim = rb_str_new2(",");
    GET_STATE(Vstate);

    check_max_nesting(state, depth);
    if (state->check_circular) {
        VALUE self_id = rb_obj_id(self);
        rb_hash_aset(state->seen, self_id, Qtrue);
        result = rb_str_buf_new(len);
        if (RSTRING_LEN(state->array_nl)) rb_str_append(delim, state->array_nl);
        shift = rb_str_times(state->indent, LONG2FIX(depth + 1));

        rb_str_buf_cat2(result, "[");
        OBJ_INFECT(result, self);
        rb_str_buf_append(result, state->array_nl);
        for (i = 0;  i < len; i++) {
            VALUE element = RARRAY_PTR(self)[i];
            if (RTEST(rb_hash_aref(state->seen, rb_obj_id(element)))) {
                rb_raise(eCircularDatastructure,
                        "circular data structures not supported!");
            }
            OBJ_INFECT(result, element);
            if (i > 0) rb_str_buf_append(result, delim);
            rb_str_buf_append(result, shift);
            element = rb_funcall(element, i_to_json, 2, Vstate, LONG2FIX(depth + 1));
            Check_Type(element, T_STRING);
            rb_str_buf_append(result, element);
        }
        if (RSTRING_LEN(state->array_nl)) {
            rb_str_buf_append(result, state->array_nl);
            rb_str_buf_append(result, rb_str_times(state->indent, LONG2FIX(depth)));
        }
        rb_str_buf_cat2(result, "]");
        rb_hash_delete(state->seen, self_id);
    } else {
        result = rb_str_buf_new(len);
        OBJ_INFECT(result, self);
        if (RSTRING_LEN(state->array_nl)) rb_str_append(delim, state->array_nl);
        shift = rb_str_times(state->indent, LONG2FIX(depth + 1));

        rb_str_buf_cat2(result, "[");
        rb_str_buf_append(result, state->array_nl);
        for (i = 0;  i < len; i++) {
            VALUE element = RARRAY_PTR(self)[i];
            OBJ_INFECT(result, element);
            if (i > 0) rb_str_buf_append(result, delim);
            rb_str_buf_append(result, shift);
            element = rb_funcall(element, i_to_json, 2, Vstate, LONG2FIX(depth + 1));
            Check_Type(element, T_STRING);
            rb_str_buf_append(result, element);
        }
        rb_str_buf_append(result, state->array_nl);
        if (RSTRING_LEN(state->array_nl)) {
            rb_str_buf_append(result, rb_str_times(state->indent, LONG2FIX(depth)));
        }
        rb_str_buf_cat2(result, "]");
    }
    return result;
}

/*
 * call-seq: to_json(state = nil, depth = 0)
 *
 * Returns a JSON string containing a JSON array, that is unparsed from
 * this Array instance.
 * _state_ is a JSON::State object, that can also be used to configure the
 * produced JSON string output further.
 * _depth_ is used to find out nesting depth, to indent accordingly.
 */
static VALUE mArray_to_json(int argc, VALUE *argv, VALUE self) {
    VALUE Vstate, Vdepth, result;

    rb_scan_args(argc, argv, "02", &Vstate, &Vdepth);
    if (NIL_P(Vstate)) {
        long i, len = RARRAY_LEN(self);
        result = rb_str_buf_new(2 + 2 * len);
        rb_str_buf_cat2(result, "[");
        OBJ_INFECT(result, self);
        for (i = 0;  i < len; i++) {
            VALUE element = RARRAY_PTR(self)[i];
            OBJ_INFECT(result, element);
            if (i > 0) rb_str_buf_cat2(result, ",");
            element = rb_funcall(element, i_to_json, 0);
            Check_Type(element, T_STRING);
            rb_str_buf_append(result, element);
        }
        rb_str_buf_cat2(result, "]");
    } else {
        result = mArray_json_transfrom(self, Vstate, Vdepth);
    }
    OBJ_INFECT(result, self);
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: to_json(*)
 *
 * Returns a JSON string representation for this Integer number.
 */
static VALUE mInteger_to_json(int argc, VALUE *argv, VALUE self)
{
    VALUE result = rb_funcall(self, i_to_s, 0);
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: to_json(*)
 *
 * Returns a JSON string representation for this Float number.
 */
static VALUE mFloat_to_json(int argc, VALUE *argv, VALUE self)
{
    JSON_Generator_State *state = NULL;
    VALUE Vstate, rest, tmp, result;
    double value = RFLOAT_VALUE(self);
    rb_scan_args(argc, argv, "01*", &Vstate, &rest);
    if (!NIL_P(Vstate)) Data_Get_Struct(Vstate, JSON_Generator_State, state);
    if (isinf(value)) {
        if (!state || state->allow_nan) {
            result = rb_funcall(self, i_to_s, 0);
        } else {
            tmp = rb_funcall(self, i_to_s, 0);
            rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp));
        }
    } else if (isnan(value)) {
        if (!state || state->allow_nan) {
            result = rb_funcall(self, i_to_s, 0);
        } else {
            tmp = rb_funcall(self, i_to_s, 0);
            rb_raise(eGeneratorError, "%u: %s not allowed in JSON", __LINE__, StringValueCStr(tmp));
        }
    } else {
        result = rb_funcall(self, i_to_s, 0);
    }
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: String.included(modul)
 *
 * Extends _modul_ with the String::Extend module.
 */
static VALUE mString_included_s(VALUE self, VALUE modul) {
    VALUE result = rb_funcall(modul, i_extend, 1, mString_Extend);
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: to_json(*)
 *
 * This string should be encoded with UTF-8 A call to this method
 * returns a JSON string encoded with UTF16 big endian characters as
 * \u????.
 */
static VALUE mString_to_json(int argc, VALUE *argv, VALUE self)
{
    VALUE result = rb_str_buf_new(RSTRING_LEN(self));
    rb_str_buf_cat2(result, "\"");
    JSON_convert_UTF8_to_JSON(result, self, strictConversion);
    rb_str_buf_cat2(result, "\"");
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: to_json_raw_object()
 *
 * This method creates a raw object hash, that can be nested into
 * other data structures and will be unparsed as a raw string. This
 * method should be used, if you want to convert raw strings to JSON
 * instead of UTF-8 strings, e. g. binary data.
 */
static VALUE mString_to_json_raw_object(VALUE self) {
    VALUE ary;
    VALUE result = rb_hash_new();
    rb_hash_aset(result, rb_funcall(mJSON, i_create_id, 0), rb_class_name(rb_obj_class(self)));
    ary = rb_funcall(self, i_unpack, 1, rb_str_new2("C*"));
    rb_hash_aset(result, rb_str_new2("raw"), ary);
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: to_json_raw(*args)
 *
 * This method creates a JSON text from the result of a call to
 * to_json_raw_object of this String.
 */
static VALUE mString_to_json_raw(int argc, VALUE *argv, VALUE self) {
    VALUE result, obj = mString_to_json_raw_object(self);
    Check_Type(obj, T_HASH);
    result = mHash_to_json(argc, argv, obj);
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: json_create(o)
 *
 * Raw Strings are JSON Objects (the raw bytes are stored in an array for the
 * key "raw"). The Ruby String can be created by this module method.
 */
static VALUE mString_Extend_json_create(VALUE self, VALUE o) {
    VALUE ary;
    Check_Type(o, T_HASH);
    ary = rb_hash_aref(o, rb_str_new2("raw"));
    return rb_funcall(ary, i_pack, 1, rb_str_new2("C*"));
}

/*
 * call-seq: to_json(state = nil, depth = 0)
 *
 * Returns a JSON string for true: 'true'.
 */
static VALUE mTrueClass_to_json(int argc, VALUE *argv, VALUE self)
{
    VALUE result = rb_str_new2("true");
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: to_json(state = nil, depth = 0)
 *
 * Returns a JSON string for false: 'false'.
 */
static VALUE mFalseClass_to_json(int argc, VALUE *argv, VALUE self)
{
    VALUE result = rb_str_new2("false");
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: to_json(state = nil, depth = 0)
 *
 */
static VALUE mNilClass_to_json(int argc, VALUE *argv, VALUE self)
{
    VALUE result = rb_str_new2("null");
    FORCE_UTF8(result);
    return result;
}

/*
 * call-seq: to_json(*)
 *
 * Converts this object to a string (calling #to_s), converts
 * it to a JSON string, and returns the result. This is a fallback, if no
 * special method #to_json was defined for some object.
 */
static VALUE mObject_to_json(int argc, VALUE *argv, VALUE self)
{
    VALUE result, string = rb_funcall(self, i_to_s, 0);
    Check_Type(string, T_STRING);
    result = mString_to_json(argc, argv, string);
    FORCE_UTF8(result);
    return result;
}

/*
 * Document-class: JSON::Ext::Generator::State
 *
 * This class is used to create State instances, that are use to hold data
 * while generating a JSON text from a a Ruby data structure.
 */

static void State_mark(JSON_Generator_State *state)
{
    rb_gc_mark_maybe(state->indent);
    rb_gc_mark_maybe(state->space);
    rb_gc_mark_maybe(state->space_before);
    rb_gc_mark_maybe(state->object_nl);
    rb_gc_mark_maybe(state->array_nl);
    rb_gc_mark_maybe(state->seen);
    rb_gc_mark_maybe(state->memo);
    rb_gc_mark_maybe(state->depth);
}

static JSON_Generator_State *State_allocate()
{
    JSON_Generator_State *state = ALLOC(JSON_Generator_State);
    return state;
}

static VALUE cState_s_allocate(VALUE klass)
{
    JSON_Generator_State *state = State_allocate();
    return Data_Wrap_Struct(klass, State_mark, -1, state);
}

/*
 * call-seq: configure(opts)
 *
 * Configure this State instance with the Hash _opts_, and return
 * itself.
 */
static VALUE cState_configure(VALUE self, VALUE opts)
{
    VALUE tmp;
    GET_STATE(self);
    tmp = rb_convert_type(opts, T_HASH, "Hash", "to_hash");
    if (NIL_P(tmp)) tmp = rb_convert_type(opts, T_HASH, "Hash", "to_h");
    if (NIL_P(tmp)) {
        rb_raise(rb_eArgError, "opts has to be hash like or convertable into a hash");
    }
    opts = tmp;
    tmp = rb_hash_aref(opts, ID2SYM(i_indent));
    if (RTEST(tmp)) {
        Check_Type(tmp, T_STRING);
        state->indent = tmp;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_space));
    if (RTEST(tmp)) {
        Check_Type(tmp, T_STRING);
        state->space = tmp;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_space_before));
    if (RTEST(tmp)) {
        Check_Type(tmp, T_STRING);
        state->space_before = tmp;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_array_nl));
    if (RTEST(tmp)) {
        Check_Type(tmp, T_STRING);
        state->array_nl = tmp;
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_object_nl));
    if (RTEST(tmp)) {
        Check_Type(tmp, T_STRING);
        state->object_nl = tmp;
    }
    tmp = ID2SYM(i_check_circular);
    if (st_lookup(RHASH_TBL(opts), tmp, 0)) {
        tmp = rb_hash_aref(opts, ID2SYM(i_check_circular));
        state->check_circular = RTEST(tmp);
    } else {
        state->check_circular = 1;
    }
    tmp = ID2SYM(i_max_nesting);
    state->max_nesting = 19;
    if (st_lookup(RHASH_TBL(opts), tmp, 0)) {
        VALUE max_nesting = rb_hash_aref(opts, tmp);
        if (RTEST(max_nesting)) {
            Check_Type(max_nesting, T_FIXNUM);
            state->max_nesting = FIX2LONG(max_nesting);
        } else {
            state->max_nesting = 0;
        }
    }
    tmp = rb_hash_aref(opts, ID2SYM(i_allow_nan));
    state->allow_nan = RTEST(tmp);
    return self;
}

/*
 * call-seq: to_h
 *
 * Returns the configuration instance variables as a hash, that can be
 * passed to the configure method.
 */
static VALUE cState_to_h(VALUE self)
{
    VALUE result = rb_hash_new();
    GET_STATE(self);
    rb_hash_aset(result, ID2SYM(i_indent), state->indent);
    rb_hash_aset(result, ID2SYM(i_space), state->space);
    rb_hash_aset(result, ID2SYM(i_space_before), state->space_before);
    rb_hash_aset(result, ID2SYM(i_object_nl), state->object_nl);
    rb_hash_aset(result, ID2SYM(i_array_nl), state->array_nl);
    rb_hash_aset(result, ID2SYM(i_check_circular), state->check_circular ? Qtrue : Qfalse);
    rb_hash_aset(result, ID2SYM(i_allow_nan), state->allow_nan ? Qtrue : Qfalse);
    rb_hash_aset(result, ID2SYM(i_max_nesting), LONG2FIX(state->max_nesting));
    return result;
}

/*
 * call-seq: new(opts = {})
 *
 * Instantiates a new State object, configured by _opts_.
 *
 * _opts_ can have the following keys:
 *
 * * *indent*: a string used to indent levels (default: ''),
 * * *space*: a string that is put after, a : or , delimiter (default: ''),
 * * *space_before*: a string that is put before a : pair delimiter (default: ''),
 * * *object_nl*: a string that is put at the end of a JSON object (default: ''),
 * * *array_nl*: a string that is put at the end of a JSON array (default: ''),
 * * *check_circular*: true if checking for circular data structures
 *   should be done, false (the default) otherwise.
 * * *allow_nan*: true if NaN, Infinity, and -Infinity should be
 *   generated, otherwise an exception is thrown, if these values are
 *   encountered. This options defaults to false.
 */
static VALUE cState_initialize(int argc, VALUE *argv, VALUE self)
{
    VALUE opts;
    GET_STATE(self);

    rb_scan_args(argc, argv, "01", &opts);
    state->indent = rb_str_new2("");
    state->space = rb_str_new2("");
    state->space_before = rb_str_new2("");
    state->array_nl = rb_str_new2("");
    state->object_nl = rb_str_new2("");
    if (NIL_P(opts)) {
        state->check_circular = 1;
        state->allow_nan = 0;
        state->max_nesting = 19;
    } else {
        cState_configure(self, opts);
    }
    state->seen = rb_hash_new();
    state->memo = Qnil;
    state->depth = INT2FIX(0);
    return self;
}

/*
 * call-seq: from_state(opts)
 *
 * Creates a State object from _opts_, which ought to be Hash to create a
 * new State instance configured by _opts_, something else to create an
 * unconfigured instance. If _opts_ is a State object, it is just returned.
 */
static VALUE cState_from_state_s(VALUE self, VALUE opts)
{
    if (rb_obj_is_kind_of(opts, self)) {
        return opts;
    } else if (rb_obj_is_kind_of(opts, rb_cHash)) {
        return rb_funcall(self, i_new, 1, opts);
    } else {
        return rb_funcall(self, i_new, 0);
    }
}

/*
 * call-seq: indent()
 *
 * This string is used to indent levels in the JSON text.
 */
static VALUE cState_indent(VALUE self)
{
    GET_STATE(self);
    return state->indent;
}

/*
 * call-seq: indent=(indent)
 *
 * This string is used to indent levels in the JSON text.
 */
static VALUE cState_indent_set(VALUE self, VALUE indent)
{
    GET_STATE(self);
    Check_Type(indent, T_STRING);
    return state->indent = indent;
}

/*
 * call-seq: space()
 *
 * This string is used to insert a space between the tokens in a JSON
 * string.
 */
static VALUE cState_space(VALUE self)
{
    GET_STATE(self);
    return state->space;
}

/*
 * call-seq: space=(space)
 *
 * This string is used to insert a space between the tokens in a JSON
 * string.
 */
static VALUE cState_space_set(VALUE self, VALUE space)
{
    GET_STATE(self);
    Check_Type(space, T_STRING);
    return state->space = space;
}

/*
 * call-seq: space_before()
 *
 * This string is used to insert a space before the ':' in JSON objects.
 */
static VALUE cState_space_before(VALUE self)
{
    GET_STATE(self);
    return state->space_before;
}

/*
 * call-seq: space_before=(space_before)
 *
 * This string is used to insert a space before the ':' in JSON objects.
 */
static VALUE cState_space_before_set(VALUE self, VALUE space_before)
{
    GET_STATE(self);
    Check_Type(space_before, T_STRING);
    return state->space_before = space_before;
}

/*
 * call-seq: object_nl()
 *
 * This string is put at the end of a line that holds a JSON object (or
 * Hash).
 */
static VALUE cState_object_nl(VALUE self)
{
    GET_STATE(self);
    return state->object_nl;
}

/*
 * call-seq: object_nl=(object_nl)
 *
 * This string is put at the end of a line that holds a JSON object (or
 * Hash).
 */
static VALUE cState_object_nl_set(VALUE self, VALUE object_nl)
{
    GET_STATE(self);
    Check_Type(object_nl, T_STRING);
    return state->object_nl = object_nl;
}

/*
 * call-seq: array_nl()
 *
 * This string is put at the end of a line that holds a JSON array.
 */
static VALUE cState_array_nl(VALUE self)
{
    GET_STATE(self);
    return state->array_nl;
}

/*
 * call-seq: array_nl=(array_nl)
 *
 * This string is put at the end of a line that holds a JSON array.
 */
static VALUE cState_array_nl_set(VALUE self, VALUE array_nl)
{
    GET_STATE(self);
    Check_Type(array_nl, T_STRING);
    return state->array_nl = array_nl;
}

/*
 * call-seq: check_circular?
 *
 * Returns true, if circular data structures should be checked,
 * otherwise returns false.
 */
static VALUE cState_check_circular_p(VALUE self)
{
    GET_STATE(self);
    return state->check_circular ? Qtrue : Qfalse;
}

/*
 * call-seq: max_nesting
 *
 * This integer returns the maximum level of data structure nesting in
 * the generated JSON, max_nesting = 0 if no maximum is checked.
 */
static VALUE cState_max_nesting(VALUE self)
{
    GET_STATE(self);
    return LONG2FIX(state->max_nesting);
}

/*
 * call-seq: max_nesting=(depth)
 *
 * This sets the maximum level of data structure nesting in the generated JSON
 * to the integer depth, max_nesting = 0 if no maximum should be checked.
 */
static VALUE cState_max_nesting_set(VALUE self, VALUE depth)
{
    GET_STATE(self);
    Check_Type(depth, T_FIXNUM);
    state->max_nesting = FIX2LONG(depth);
    return Qnil;
}

/*
 * call-seq: allow_nan?
 *
 * Returns true, if NaN, Infinity, and -Infinity should be generated, otherwise
 * returns false.
 */
static VALUE cState_allow_nan_p(VALUE self)
{
    GET_STATE(self);
    return state->allow_nan ? Qtrue : Qfalse;
}

/*
 * call-seq: seen?(object)
 *
 * Returns _true_, if _object_ was already seen during this generating run.
 */
static VALUE cState_seen_p(VALUE self, VALUE object)
{
    GET_STATE(self);
    return rb_hash_aref(state->seen, rb_obj_id(object));
}

/*
 * call-seq: remember(object)
 *
 * Remember _object_, to find out if it was already encountered (if a cyclic
 * data structure is rendered).
 */
static VALUE cState_remember(VALUE self, VALUE object)
{
    GET_STATE(self);
    return rb_hash_aset(state->seen, rb_obj_id(object), Qtrue);
}

/*
 * call-seq: forget(object)
 *
 * Forget _object_ for this generating run.
 */
static VALUE cState_forget(VALUE self, VALUE object)
{
    GET_STATE(self);
    return rb_hash_delete(state->seen, rb_obj_id(object));
}

/*
 *
 */
void Init_generator()
{
    rb_require("json/common");
    mJSON = rb_define_module("JSON");
    mExt = rb_define_module_under(mJSON, "Ext");
    mGenerator = rb_define_module_under(mExt, "Generator");
    eGeneratorError = rb_path2class("JSON::GeneratorError");
    eCircularDatastructure = rb_path2class("JSON::CircularDatastructure");
    eNestingError = rb_path2class("JSON::NestingError");
    cState = rb_define_class_under(mGenerator, "State", rb_cObject);
    rb_define_alloc_func(cState, cState_s_allocate);
    rb_define_singleton_method(cState, "from_state", cState_from_state_s, 1);
    rb_define_method(cState, "initialize", cState_initialize, -1);

    rb_define_method(cState, "indent", cState_indent, 0);
    rb_define_method(cState, "indent=", cState_indent_set, 1);
    rb_define_method(cState, "space", cState_space, 0);
    rb_define_method(cState, "space=", cState_space_set, 1);
    rb_define_method(cState, "space_before", cState_space_before, 0);
    rb_define_method(cState, "space_before=", cState_space_before_set, 1);
    rb_define_method(cState, "object_nl", cState_object_nl, 0);
    rb_define_method(cState, "object_nl=", cState_object_nl_set, 1);
    rb_define_method(cState, "array_nl", cState_array_nl, 0);
    rb_define_method(cState, "array_nl=", cState_array_nl_set, 1);
    rb_define_method(cState, "check_circular?", cState_check_circular_p, 0);
    rb_define_method(cState, "max_nesting", cState_max_nesting, 0);
    rb_define_method(cState, "max_nesting=", cState_max_nesting_set, 1);
    rb_define_method(cState, "allow_nan?", cState_allow_nan_p, 0);
    rb_define_method(cState, "seen?", cState_seen_p, 1);
    rb_define_method(cState, "remember", cState_remember, 1);
    rb_define_method(cState, "forget", cState_forget, 1);
    rb_define_method(cState, "configure", cState_configure, 1);
    rb_define_method(cState, "to_h", cState_to_h, 0);

    mGeneratorMethods = rb_define_module_under(mGenerator, "GeneratorMethods");
    mObject = rb_define_module_under(mGeneratorMethods, "Object");
    rb_define_method(mObject, "to_json", mObject_to_json, -1);
    mHash = rb_define_module_under(mGeneratorMethods, "Hash");
    rb_define_method(mHash, "to_json", mHash_to_json, -1);
    mArray = rb_define_module_under(mGeneratorMethods, "Array");
    rb_define_method(mArray, "to_json", mArray_to_json, -1);
    mInteger = rb_define_module_under(mGeneratorMethods, "Integer");
    rb_define_method(mInteger, "to_json", mInteger_to_json, -1);
    mFloat = rb_define_module_under(mGeneratorMethods, "Float");
    rb_define_method(mFloat, "to_json", mFloat_to_json, -1);
    mString = rb_define_module_under(mGeneratorMethods, "String");
    rb_define_singleton_method(mString, "included", mString_included_s, 1);
    rb_define_method(mString, "to_json", mString_to_json, -1);
    rb_define_method(mString, "to_json_raw", mString_to_json_raw, -1);
    rb_define_method(mString, "to_json_raw_object", mString_to_json_raw_object, 0);
    mString_Extend = rb_define_module_under(mString, "Extend");
    rb_define_method(mString_Extend, "json_create", mString_Extend_json_create, 1);
    mTrueClass = rb_define_module_under(mGeneratorMethods, "TrueClass");
    rb_define_method(mTrueClass, "to_json", mTrueClass_to_json, -1);
    mFalseClass = rb_define_module_under(mGeneratorMethods, "FalseClass");
    rb_define_method(mFalseClass, "to_json", mFalseClass_to_json, -1);
    mNilClass = rb_define_module_under(mGeneratorMethods, "NilClass");
    rb_define_method(mNilClass, "to_json", mNilClass_to_json, -1);

    i_to_s = rb_intern("to_s");
    i_to_json = rb_intern("to_json");
    i_new = rb_intern("new");
    i_indent = rb_intern("indent");
    i_space = rb_intern("space");
    i_space_before = rb_intern("space_before");
    i_object_nl = rb_intern("object_nl");
    i_array_nl = rb_intern("array_nl");
    i_check_circular = rb_intern("check_circular");
    i_max_nesting = rb_intern("max_nesting");
    i_allow_nan = rb_intern("allow_nan");
    i_pack = rb_intern("pack");
    i_unpack = rb_intern("unpack");
    i_create_id = rb_intern("create_id");
    i_extend = rb_intern("extend");
}


text:
package store

import (
	"crypto/sha256"
	"encoding/hex"
	"strings"
)

// Predicate for filtering returned instances
type Predicate func(si *ServiceInstance) bool

// Catalog for managing instances within a registry namespace
type Catalog interface {
	Register(si *ServiceInstance) (*ServiceInstance, error)
	Deregister(instanceID string) (*ServiceInstance, error)
	Renew(instanceID string) (*ServiceInstance, error)
	SetStatus(instanceID, status string) (*ServiceInstance, error)

	Instance(instanceID string) (*ServiceInstance, error)
	List(serviceName string, predicate Predicate) ([]*ServiceInstance, error)
	ListServices(predicate Predicate) []*Service
}

const (
	// ServiceNameMaxLength is the maximum length of a service instance name, specified in bytes
	ServiceNameMaxLength int = 64

	// EndpointValueMaxLength is the maximum length of a service instance endpoint value, specified in bytes
	EndpointValueMaxLength int = 128

	// StatusMaxLength is the maximum length of a service instance status field, specified in bytes
	StatusMaxLength int = 32

	// MetadataMaxLength is the maximum length of a service instance metadata, specifie in bytes
	MetadataMaxLength int = 1024
)

// Metric objects names
const (
	instancesMetricName  = "store.instances.count"
	expirationMetricName = "store.instances.expiration"
	lifetimeMetricName   = "store.instances.lifetime"

	metadataLengthMetricName    = "store.metadata.length"
	metadataInstancesMetricName = "store.metadata.instances"
	tagsLengthMetricName        = "store.tags.length"
	tagsInstancesMetricName     = "store.tags.instances"
)

func computeInstanceID(si *ServiceInstance) string {
	// The ID is deterministically computed for each catalog,
	// This is necessary to support replication, and duplicate registration request accross nodes in the sd cluster
	hash := sha256.New()
	hash.Write([]byte(strings.Join([]string{si.ServiceName, si.Endpoint.Type, si.Endpoint.Value}, "/")))
	//hash.Write([]byte(time.Now().String()))
	md := hash.Sum(nil)
	mdStr := hex.EncodeToString(md)
	return mdStr[:16]
}


text:
package http

import (
	bm "go-common/library/net/http/blademaster"
)

// ping check server ok.
func ping(c *bm.Context) {
}


text:
package org.apache.camel.component.jira;

public interface JiraConstants {

    String JIRA = "jira";
    String ACCESS_TOKEN = "accessToken";
    String VERIFICATION_CODE = "verificationCode";
    String JIRA_URL = "jiraUrl";
    String PRIVATE_KEY = "privateKey";
    String CONSUMER_KEY = "consumerKey";
    String ISSUE_ASSIGNEE = "IssueAssignee";
    String ISSUE_COMPONENTS = "IssueComponents";
    String ISSUE_COMMENT = "IssueComment";
    String ISSUE_KEY = "IssueKey";
    String ISSUE_PRIORITY_ID = "IssuePriorityId";
    String ISSUE_PRIORITY_NAME = "IssuePriorityName";
    String ISSUE_PROJECT_KEY = "ProjectKey";
    String ISSUE_SUMMARY = "IssueSummary";
    String ISSUE_TRANSITION_ID = "IssueTransitionId";
    String ISSUE_TYPE_ID = "IssueTypeId";
    String ISSUE_TYPE_NAME = "IssueTypeName";
    String ISSUE_WATCHERS_ADD = "IssueWatchersAdd";
    String ISSUE_WATCHERS_REMOVE = "IssueWatchersRemove";
    String JIRA_REST_CLIENT_FACTORY = "JiraRestClientFactory";

}


text:
#ifndef LINEARJITTERFORCE_H
#define LINEARJITTERFORCE_H

#include "linearRandomForce.h"

/**
 * Completely random noise force vector.  Not repeatable, reliable, or
 * predictable.
 */
class EXPCL_PANDAPHYSICS LinearJitterForce : public LinearRandomForce {
PUBLISHED:
  LinearJitterForce(PN_stdfloat a = 1.0f, bool m = false);
  LinearJitterForce(const LinearJitterForce &copy);
  virtual ~LinearJitterForce();

  virtual void output(ostream &out) const;
  virtual void write(ostream &out, unsigned int indent=0) const;

private:
  virtual LVector3 get_child_vector(const PhysicsObject *po);
  virtual LinearForce *make_copy();

public:
  static TypeHandle get_class_type() {
    return _type_handle;
  }
  static void init_type() {
    LinearRandomForce::init_type();
    register_type(_type_handle, "LinearJitterForce",
                  LinearRandomForce::get_class_type());
  }
  virtual TypeHandle get_type() const {
    return get_class_type();
  }
  virtual TypeHandle force_init_type() {init_type(); return get_class_type();}

private:
  static TypeHandle _type_handle;
};

#endif // LINEARJITTERFORCE_H


text:
package com.swfarm.biz.ebay.job;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.csvreader.CsvReader;
import com.swfarm.biz.chain.bo.CustomerOrder;
import com.swfarm.biz.chain.bo.CustomerOrderItem;
import com.swfarm.biz.chain.srv.ChainManagementService;
import com.swfarm.pub.utils.DateUtils;
import com.swfarm.pub.utils.HttpUtils;

public class SynchronizeDeTransactionsTask {
	Logger logger = Logger.getLogger(SynchronizeDeTransactionsTask.class);

	private static final String IMPORT_URL = "http://tinxi.de/export/login.asp?UserName=shenzhen&UserPassword=D600$&date=${0}";

	private int userIdPos;

	private int buyerFullnamePos;

	private int buyerPhoneNumberPos;

	private int buyerAddress1Pos;

	private int buyerAddress2Pos;

	private int buyerCityPos;

	private int buyerStatePos;

	private int buyerZipPos;

	private int buyerCountryPos;

	private int itemTitlePos;

	private int quantityPos;

	private int customerOrderNoPos;

	private int stockLocationPos;

	private int itemNamePos;

	private int shippingMethodPos;

	private int pricePos;

	private int currencyPos;

	private ChainManagementService chainManagementService;

	public void setChainManagementService(ChainManagementService chainManagementService) {
		this.chainManagementService = chainManagementService;
	}

	public synchronized void pullTransactions(Date importDate) {
		logger.warn("*********start to synchronize ebay transactions*********");
		if (importDate == null) {
			importDate = DateUtils.stringToDate(DateUtils.dateToString(new Date(), "yyyy/MM/dd"), "yyyy/MM/dd");
		}
		try {

		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		}
		this.chainManagementService.refreshStockAvailability();
		logger.warn("**********finish synchronize ebay transactions**********");
	}

	public void importCustomerOrders(Date importDate) {
		String importDateStr = DateUtils.dateToString(importDate, "dd.MM.yyyy");
		String importUrl = MessageFormat.format(IMPORT_URL, new Object[] { importDateStr });
		HttpClient client = new HttpClient();
		GetMethod method = new GetMethod(importUrl);
		Reader fileReader = null;
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
		try {
			int statusCode = client.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + method.getStatusLine());
			}
			Header[] headers = method.getResponseHeaders();
			for (int i = 0; i < headers.length; i++) {
				System.err.println(headers[i].getName() + " : " + headers[i].getValue());
			}
			InputStream is = method.getResponseBodyAsStream();
			fileReader = new InputStreamReader(is, "ISO-8859-1");
			CsvReader reader = new CsvReader(fileReader, ',');
			reader.setUseTextQualifier(true);
			reader.setTextQualifier('"');
			reader.setEscapeMode(CsvReader.ESCAPE_MODE_BACKSLASH);
			List<String[]> customerOrderInfoList = new ArrayList<String[]>();
			while (reader.readRecord()) {
				String[] customerOrderInfo = reader.getValues();
				if (customerOrderInfo != null && customerOrderInfo.length > 10
						&& StringUtils.isNotEmpty(customerOrderInfo[0])) {
					if (customerOrderInfo[0].equals("User ID")) {
						setFieldPositions(customerOrderInfo);
					} else if (!customerOrderInfo[0].equals("User ID")) {
						customerOrderInfoList.add(customerOrderInfo);
					}
				}
			}
			Object[] returns = importCustomerOrders(customerOrderInfoList);
		} catch (HttpException e) {
			System.err.println("Fatal protocol violation: " + e.getMessage());
			logger.warn(e.getMessage(), e);
		} catch (IOException e) {
			System.err.println("Fatal transport error: " + e.getMessage());
			logger.warn(e.getMessage(), e);
		} finally {
			if (fileReader != null) {
				try {
					fileReader.close();
				} catch (Exception e) {
					logger.warn(e.getMessage(), e);
				}
			}
			HttpUtils.close(client, method);
		}
	}

	private Object[] importCustomerOrders(List<String[]> customerOrderInfoList) {
		Object[] returns = new Object[4];
		CustomerOrder customerOrder = null;
		CustomerOrderItem customerOrderItem = null;
		int importedCustomerOrder = 0;
		int importedCustomerOrderItem = 0;
		if (CollectionUtils.isNotEmpty(customerOrderInfoList)) {
			for (Iterator<String[]> iter = customerOrderInfoList.iterator(); iter.hasNext();) {
				String[] customerOrderInfo = iter.next();
				String userId = customerOrderInfo[this.userIdPos];
				String buyerFullname = customerOrderInfo[this.buyerFullnamePos];
				String buyerPhoneNumber = customerOrderInfo[this.buyerPhoneNumberPos];
				String buyerAddress1 = customerOrderInfo[this.buyerAddress1Pos];
				String buyerAddress2 = customerOrderInfo[this.buyerAddress2Pos];
				String buyerCity = customerOrderInfo[this.buyerCityPos];
				String buyerState = customerOrderInfo[this.buyerStatePos];
				String buyerZip = customerOrderInfo[this.buyerZipPos];
				String buyerCountry = customerOrderInfo[this.buyerCountryPos];
				String itemTitle = customerOrderInfo[this.itemTitlePos];
				String quantity = customerOrderInfo[this.quantityPos];
				String customerOrderNo = customerOrderInfo[this.customerOrderNoPos];
				String stockLocation = customerOrderInfo[this.stockLocationPos];
				String itemName = customerOrderInfo[this.itemNamePos];
				String shippingMethod = customerOrderInfo[this.shippingMethodPos];
				String price = customerOrderInfo[this.pricePos];
				String currency = customerOrderInfo[this.currencyPos];
				customerOrderItem = new CustomerOrderItem();
				if (StringUtils.isNotEmpty(itemTitle)) {
					customerOrderItem.setCustomLabel(itemTitle);
					customerOrderItem.setArticleNumber(itemTitle);
				}
				if (StringUtils.isNotEmpty(quantity)) {
					customerOrderItem.setQuantity(new Double(quantity));
					customerOrderItem.setCustomLabelQuantity(new Double(quantity));
				}

			}
		}
		return returns;
	}

	private void setFieldPositions(String[] customerOrderInfo) {
		for (int i = 0; i < customerOrderInfo.length; i++) {
			if ("User ID".equals(customerOrderInfo[i])) {
				this.userIdPos = i;
			} else if ("Buyer Fullname".equals(customerOrderInfo[i])) {
				this.buyerFullnamePos = i;
			} else if ("Buyer Phone Number".equals(customerOrderInfo[i])) {
				this.buyerPhoneNumberPos = i;
			} else if ("Buyer Address 1".equals(customerOrderInfo[i])) {
				this.buyerAddress1Pos = i;
			} else if ("Buyer Address 2".equals(customerOrderInfo[i])) {
				this.buyerAddress2Pos = i;
			} else if ("Buyer City".equals(customerOrderInfo[i])) {
				this.buyerCityPos = i;
			} else if ("Buyer State".equals(customerOrderInfo[i])) {
				this.buyerStatePos = i;
			} else if ("Buyer Postcode".equals(customerOrderInfo[i])) {
				this.buyerZipPos = i;
			} else if ("Buyer Country".equals(customerOrderInfo[i])) {
				this.buyerCountryPos = i;
			} else if ("Item Title".equals(customerOrderInfo[i])) {
				this.itemTitlePos = i;
			} else if ("Quantity".equals(customerOrderInfo[i])) {
				this.quantityPos = i;
			} else if ("Lieferschein-Nr".equals(customerOrderInfo[i])) {
				this.customerOrderNoPos = i;
			} else if ("Lagerplatz".equals(customerOrderInfo[i])) {
				this.stockLocationPos = i;
			} else if ("Itemname".equals(customerOrderInfo[i])) {
				this.itemNamePos = i;
			} else if ("shippingMethod".equals(customerOrderInfo[i])) {
				this.shippingMethodPos = i;
			} else if ("price".equals(customerOrderInfo[i])) {
				this.pricePos = i;
			} else if ("currency".equals(customerOrderInfo[i])) {
				this.currencyPos = i;
			}
		}
	}

}


text:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.gis.gdal import DataSource, GDALException
from geotrek.zoning.models import RestrictedArea, RestrictedAreaType
from django.contrib.gis.geos.polygon import Polygon
from django.contrib.gis.geos.collections import MultiPolygon
from django.conf import settings

class Command(BaseCommand):
    help = 'Load Restricted Area from a file within the spatial extent\n'

    def add_arguments(self, parser):
        parser.add_argument('file_path', help="File's path of the restricted area")
        parser.add_argument('area_type', action='store',
                            help="Type of restricted areas in the file")
        parser.add_argument('--name-attribute', '-n', action='store', dest='name', default='nom',
                            help="Name of the name's attribute inside the file")
        parser.add_argument('--encoding', '-e', action='store', dest='encoding', default='utf-8',
                            help='File encoding, default utf-8')
        parser.add_argument('--srid', '-s', action='store', dest='srid', default=4326, type=int,
                            help="File's SRID")
        parser.add_argument('--intersect', '-i', action='store_true', dest='intersect', default=False,
                            help="Check features intersect spatial extent and not only within")

    def handle(self, *args, **options):
        verbosity = options.get('verbosity')
        file_path = options.get('file_path')
        area_type_name = options.get('area_type')
        name_column = options.get('name')
        encoding = options.get('encoding')
        srid = options.get('srid')
        do_intersect = options.get('intersect')
        bbox = Polygon.from_bbox(settings.SPATIAL_EXTENT)
        bbox.srid = settings.SRID
        ds = DataSource(file_path, encoding=encoding)
        count_error = 0
        area_type, created = RestrictedAreaType.objects.get_or_create(name=area_type_name)
        if verbosity > 0:
            self.stdout.write("RestrictedArea Type's %s created" % area_type_name if created else "Get %s" % area_type_name)

        for layer in ds:
            for feat in layer:
                try:
                    geom = feat.geom.geos
                    if not isinstance(geom, Polygon) and not isinstance(geom, MultiPolygon):
                        if verbosity > 0:
                            self.stdout.write("%s's geometry is not a polygon" % feat.get(name_column))
                        break
                    elif isinstance(geom, Polygon):
                        geom = MultiPolygon(geom)
                    self.check_srid(srid, geom)
                    geom.dim = 2
                    if geom.valid:
                        if do_intersect and bbox.intersects(geom) or not do_intersect and geom.within(bbox):
                            instance, created = RestrictedArea.objects.update_or_create(name=feat.get(name_column),
                                                                                area_type=area_type,
                                                                                defaults={
                                                                                'geom': geom})
                            if verbosity > 0:
                                self.stdout.write("%s %s" % ('Created' if created else 'Updated', feat.get(name_column)))
                    else:
                        if verbosity > 0:
                            self.stdout.write("%s's geometry is not valid" % feat.get(name_column))
                except IndexError:
                    if count_error == 0:
                        self.stdout.write(
                            "Name's attribute do not correspond with options\n"
                            "Please, use --name to fix it.\n"
                            "Fields in your file are : %s" % ', '.join(layer.fields))
                    count_error += 1

    def check_srid(self, srid, geom):
        if not geom.srid:
            geom.srid = int(srid)

        if geom.srid != settings.SRID:
            try:
                geom.transform(settings.SRID)
            except GDALException:
                raise CommandError("SRID is not well configurate, change/add option srid")


text:
![Build Status](https://github.com/zooniverse/Panoptes-Front-End/actions/workflows/ci-tests.yml/badge.svg?branch=master)

[![Coverage Status](https://coveralls.io/repos/github/zooniverse/Panoptes-Front-End/badge.svg)](https://coveralls.io/github/zooniverse/Panoptes-Front-End)

## Getting started

We are no longer actively developing features for this app. PRs will be accepted for bug fixes, translations, and content updates. Active feature development is happening at [https://github.com/zooniverse/front-end-monorepo/](https://github.com/zooniverse/front-end-monorepo/)

### With Docker

To avoid having to install Node.js or any other dependencies, you can run
everything with Docker and Docker Compose.

- `docker-compose build` will build a local Docker image and run `npm ci`. Run this whenever you
change dependencies in `package.json`.

- `docker-compose up` starts a development web server that listens on port 3735.

- `docker-compose down` stops the development server.

- `docker-compose run --rm shell` starts a container running a shell eg. for running tests.

### With Node.js

Make sure you have Node 8 and `npm` 5 or greater. It's recommended you manage your Node installations with **nvm**.

- `npm ci` installs dependencies.

- `npm start` builds and runs the site locally.

Note 1: _[npm ci](https://docs.npmjs.com/cli/v8/commands/npm-ci)_ (clean install) is preferred over _npm install,_ as it doesn't modify the package lock.

⚠ **Note 2:** as of Node 16.15, running _npm ci_ results in errors such as _npm ERR! ERESOLVE could not resolve_ and _Conflicting peer dependency: foobar@x.y.z_ You can bypass this problem by instead running `npm ci --legacy-peer-deps`. Please see [issue 6155](https://github.com/zooniverse/Panoptes-Front-End/issues/6155) for more details.

### Viewing the Website

Open your web browser of choice and go to `https://localhost:3735/`

If you want to _login_ via the Panoptes API and _view authenticated pages,_ then you'll need to set up and use `https://local.zooniverse.org:3735` instead of using localhost:3735. Otherwise, you'll run into CORS errors. (You need to add the hostname to your hosts file, pointing to local. Instructions are on [our Stackoverflow](https://stackoverflow.com/c/zooniverse/questions/109).)

**Troubleshooting: web browser blocks local website**

The problem: when attempting to view _localhost:3735_ or _local.zooniverse.org:3735,_ my web browser stops me and shows a warning screen.

Example errors: "Your connection is not private / NET::ERR_CERT_AUTHORITY_INVALID" on Chrome 104; "Warning: Potential Security Risk Ahead" on Firefox 103; "This connection is not private" on Safari 15.4.

The cause: the local web server is running HTTPS, and it's using a self-signed certificate. Modern web browsers consider these certificates very untrustworthy, and a possible indicator of a man-in-the-middle attack.

The solution(s):
- For Firefox or Safari, open the _advanced options_ on the warning page, and then click whatever's the equivalent of _"accept risk and continue"._
- For Chrome, type in the _interstitial bypass keyword_ (`thisisunsafe`) anywhere on the window to temporarily bypass the warning; or ⚠ manually add the SSL cert to your computer's list of trusted certificates. [See Stackoverflow for additional details.](https://stackoverflow.com/questions/7580508/getting-chrome-to-accept-self-signed-localhost-certificate)

⚠ Warning: please be careful if you do change your web browser's or computer's security settings.

### Configuration

The app can be configured using the following environment variables:

- `NODE_ENV` - sets the environment of the code, and determines whether to apply any production optimizations to the bundled code, and which set of defaults to apply for e.g. API host url, Talk host url etc.
- `PANOPTES_API_APPLICATION` - sets the application ID to use when making authentication requests to the Panoptes API. Defaults to that set by `NODE_ENV`.
- `PANOPTES_API_HOST` - sets the URL of the instance of the Panoptes API. Defaults to that set by `NODE_ENV`.
- `STAT_HOST` - sets the URL of the instance of the Stats API. Defaults to that set by `NODE_ENV`.
- `SUGAR_HOST` - sets the URL of the instance of the Sugar API. Defaults to that set by `NODE_ENV`.
- `TALK_HOST` - sets the URL of the instance of the Talk API. Defaults to that set by `NODE_ENV`.

#### Configuration notes

- Some of these environment variables are set by commands in the `package.json` `scripts` block; in order to override them, you'll need to modify `package.json`.
- To see the defaults set by the `NODE_ENV` environment variable, see [`config.js`](https://github.com/zooniverse/panoptes-javascript-client/blob/master/lib/config.js) in [panoptes-javascript-client](https://github.com/zooniverse/panoptes-javascript-client).

### Development

New GitHub PRs from within the Zooniverse organisation will be staged by Jenkins as part of the CI process. Once CI finishes, your changes should be staged at https://pr-{PR-Number}.pfe-preview.zooniverse.org. Jenkins sometimes times out before finishing the build. If a PR build fails, use the link to Jenkins (from your PR) to log in and try restarting the build.

For testing with production data, you can add `env=production` to your development url, e.g. `localhost:3735/projects?env=production`. Note that it is removed on every page refresh.

All the good stuff is in **./app**. Start at **./app/main.cjsx**

We lint our JavaScript code against a modified version of the [AirBnB style guide](https://github.com/airbnb/javascript). Please lint your changes with eslint, using the .eslintrc file at the root of this repo. If you have any questions, do feel free to ask us on GitHub.

While editing, do your best to follow style and architecture conventions already used by the project. The codebase is large, and styles have evolved during its development. Take a look at [zooniverse/front-end-monorepo](https://github.com/zooniverse/front-end-monorepo) to get an idea of our conventions for organising components.

### What to do if it doesn't run

Try `npm ci` to freshen up your dependencies. And read the warnings, they should tell you if you're using the wrong version of Node or npm or if you're missing any dependencies. If you use `docker-compose` to build and test the site, you shouldn't run into any problems with the Node version, but `docker-compose build` will build a new image with a fresh `npm ci`.

## Testing

If you write a new component, write a test. Each component should have its own `.spec.js` file. The test runner is [Mocha](https://mochajs.org/) and [Enzyme](http://airbnb.io/enzyme/) is available for testing React components.
Mocha throws an error (`Illegal import declaration`) when compiling coffeescript files that contain ES6 import statements with template strings. Convert these imports to `require` statements.
You can run the tests with `npm test`.

## Deployment

Deployment is handled by Github Action.

### Staging

On opening of pull requests, a Github Action is triggered to deploy to a branch staging location. The blob storage location depends on the pull request number, e.g. `https://pr-5926.pfe-preview.zooniverse.org`.

On push to master, a Github Action is triggered to deploy to master staging found at `https://master.pfe-preview.zooniverse.org`.

### Production

Production deployments are triggered by an update to which commit the `production-release` tag is pointed to. This tag should be updated via chat ops and then a Github Action will run that builds and uploads the files to our cloud provider found at `https://www.zooniverse.org`. The production deployment can be run ad hoc in the actions tab as needed if you have the appropriate permissions on the repository, but only do this in an emergency.

## Directory structure

- #### ./app/classifier/

  All things classifier-related.

- #### ./app/collections/

  Collections-related components.

- #### ./app/components/

  Misc generic, reusable components.

- #### ./app/layout/

  App-level layout stuff goes here. If it affects the main site header, the main site footer, or the layout of the main site content, this is where it lives.

- #### ./app/lib/

  Individual functions and data that are reused across components.

- #### ./app/pages/

  This is where the bulk of the app lives. Ideally, each route points to a page component responsible for fetching data and handling any actions the user can perform on that data. That page component uses that data to render the UI with dumb components, passing actions down as necessary.

- #### ./app/partials/

  Originally intended to hold isolated components that wouldn't actually be reused anywhere. These probably belong closer to where they're actually used.

- #### ./app/subjects/

  Subject views (TODOC: How's this related to Talk/collections?)

- #### ./app/talk/

  Talk-related components.

- #### ./public

  Files here will get copied to the output directory during build.

### Classifier tasks

Each task component class should have a couple static components:

- `Summary`: Shows the post-classification summary of the tasks's annotation.

- `Editor`: The component used to edit the workflow task in the project builder.

There are also a few hooks into the rest of the classification interface available, if the task needs to render outside the task area.

- `BeforeSubject`: HTML Content to appear before the subject image during the task.

- `InsideSubject`: SVG Content to appear over the subject image during the task.

- `AfterSubject` HTML Content to appear after the subject image during the task.

These hooks can be prefixed with `Persist`, which will cause them to appear with the task and persist even after the user has moved on to the next task.

`Persist{Before,After}Task` work the same way, but for the task area. Non-persistent hooks are unnecessary for the task area.

Each component also needs a few static methods:

- `getDefaultTask`: Returns the task description to be used as the default when a user adds the task to a workflow in the project builder.

- `getTaskText`: Given a task, this returns a basic text description of the task (e.g. the question in a question task, the instruction in a drawing task, etc.)

- `getDefaultAnnotation`: The annotation to be generated when the classifier begins the task

- `isAnnotationComplete`: Given a task and an annotation, this determines whether or not the classifier will allow the user to move on to the next task.

- `testAnnotationQuality`: Given the user's annotation and a known-good "gold standard" annotation for the same task, this returns a number between 0 (totally wrong) and 1 (totally correct) indicating how close the user's annotation is to the standard.

#### Task editors

Make sure you call `this.props.onChange` with the updated task when it changes.

### Drawing task tools

Some static methods, called from the `MarkInitializer` component, which controls the mark's values during the user's first mark-creating action:

- `defaultValues`: Just some defaults for the mark.

- `initStart`: For every mousedown/touchstart until `isComplete` returns true, return the values for the mark.

- `initMove`" For every mousemove/touchmove, return new values for the mark.

- `initRelease`: For every mouseup/touchend, return new values for the mark.

- `isComplete`: Is the mark complete? Some marks require multiple interactions before the initializer gives up control.

- `initValid`: If a mark is invalid (e.g. a rectangle with zero width or height), it'll be destroyed automatically.

A couple helper components are the `DrawingToolRoot` which handles selected/disabled states and renders sub-task popups, and the `DeleteButton` and `DragHandle`, which render consistent controls for drawing tools. There's also a `deleteIfOutOfBounds` function that should be called after any whole-mark drags.

### Conventions

React requires each component in an array to have a sibling-unique `key`. When rendering arrays of things that do not have IDs (annotations, answers), provide a random `_key` property if it doesn't exist. Ensure underscore-prefixed properties aren't persisted. That's automatic with the `JSONAPIClient.Model` class.

```cjsx
<ul>
  {for item in things
    item._key ?= Math.random()
    <li key={item._key}>{item.label}</li>}
</ul>
```

### Async helper components

There are some ~~nice~~ **unfortunate** (in hindsight) components to help with async values. They take a function as `@props.children`, which looks a little horsey but works rather nicely. Most requested data is cached locally, so these are usually safe, but if you notice the same request being made multiple times in a row, these are a good place to start looking for the redundant calls. Here's an example of re-rendering when a project changes, which results in checking the projects owners.

```cjsx
<ChangeListener target={@props.project}>{=>
  <PromiseRenderer promise={@props.project.get('owners')}>{([owner]) =>
    if owner is @props.user
      <p>This project is yours.</p>
    else
      <p>This project belongs to {owner.display_name}.</p>
  }</PromiseRenderer>
}</ChangeListener>
```

**Do not write new code using `ChangeListener` or `PromiseRenderer`.**

**If it's reasonable, replace `ChangeListener` and `PromiseRenderer` instances with component state in code you work on.** It's more verbose, but it's more readable, and it'll get us closer to rendering on the server in the future.

### CSS conventions

Include any CSS **required for a component's functionality** inline in with component, otherwise keep it in a separate file, one per component. For a given component, pick a unique top-level class name for that component and nest child classes under it. Keep common base styles and variables in **common.styl**. Stylus formatting: Yes colons, no semicolons, no braces. `@extends` up top, then properties (alphabetically), then descendant selectors. Prefer use of `display: flex` and `flex-wrap: wrap` to explicit media queries wherever possible.

Our CSS has gotten really huge, so we're trying out [BEM](http://getbem.com/introduction/) for organization.

```styl
// <special-button.styl>
.special-button
  background: red
  color: white

.special-button__icon
  width: 1em;

// <special-container.styl>
.special-container
  margin: 1em 1vw

  .special-container__button
    border: 1px solid
```

### Writing components in ES6/ES2015

We're migrating from coffeescript to ES6. This can be done incrementally by writing a new component or rewriting an existing component in ES6. A few gotchas should be mentioned:

- The existential operator does not exist in ES6. Either compare explicitly to `null` or use `!!thing` if it just needs to be truthy.

- Native ES6 classes are preferred since `React.createClass()` is deprecated, however, if the existing component is relying on mixins, then consider using `createReactClass()`.

- Mixins are being deprecated and not supported with native classes, so do not use them in new components.

- Use backticks to import ES6 components into coffeescript components:

```
`import NewComponent from './new-component'`
```

An ESLint configuration file is setup in the root of the repository for you to use with your text editor to lint both ES6 and use Airbnb's React style guide.

A [guide](https://reactjs.org/docs/react-without-es6.html) on writing native classes versus using `createReactClass()`

## Custom projects

See the **panoptes-client** library: <https://www.npmjs.com/package/panoptes-client>.

## Format of annotation values

The format of an annotation's value depends on the task used to generate it.

- **single:** The index of the chosen answer.

- **multiple:** An array of the indices of the chosen answers (in the order they were chosen).

- **drawing:** An array of drawing tool marks (descriptions of which follow below).

- **survey:** An array of identifications as objects. Each identification a `choice` (the ID of the identified animal) and `answers`, an object. Each key in `answers` is the ID of a question. If that question allows multiple answers, the value will be an array of answer IDs, otherwise just a single answer ID.

- **crop:** An object containing the `x`, `y`, `width`, and `height` of the cropped region.

- **text:** A string.

- **combo:** A sub-array of annotations.

- **dropdown:** An array of objects where the string `value` refers to the answer to the corresponding question and the boolean `option` indicates that the answer was in the list of options.

### Drawing tool marks

All coordinates are relative to the top-left of the image.

All marks have a `tool`, which is the index of the tool (e.g. `workflow.tasks.T0.tools[0]`) used to make the mark.

All marks contain a `frame`, which is the index of the subject frame (e.g. `subject.locations[0]`) the mark was made on.

If `details` tasks are defined for a tool, its marks will have a `details` array of sub-classifications (each with a `value`, following the descriptions above).

Drawing annotation value are as follows:

- **point:** The `x` and `y` coordinates.

- **line:** The start (`x1`, `y1`) and end (`x2`, `y2`) coordinates.

- **polygon:** An array of objects, each containing the `x` and `y` coordinate of a vertex. If the mark was not explicitly closed by the user, `auto_closed` is `true`.

- **rectangle:** The `x`, `y` coordinate of the top-left point of the rectangle along with its `width` and `height`.

- **circle:** The `x` and `y` coordinate of the center of the circle and its radius `r`.

- **ellipse:** The `x` and `y` coordinate of the center of the ellipse, its radii `rx` and `ry`, and the `angle` of `rx` relative to the x axis in degrees (counterclockwise from 3:00).

- **bezier:** The same as polygon, but every odd-indexed point is the coordinate of the control point of a quadratic bezier curve.

- **column:** The left-most `x` pixel and the `width` of the column selection.

## Acknowledgements

Thanks to [BrowserStack](https://www.browserstack.com) for supporting open
source and allowing us to test this project on multiple platforms.

[![BrowserStack logo](https://static.zooniverse.org/browserstack-logo-300x158.png)](https://www.browserstack.com)

[![pullreminders](https://pullreminders.com/badge.svg)](https://pullreminders.com?ref=badge)


text:
/*
 *@test
 *@bug 6442006
 *@summary Test case for verifying timezone display name for Asia/Taipei
 */

import java.util.Locale;
import java.util.TimeZone;

public class Bug6442006 {

    public static void main(String[] args) {

        TimeZone tz = TimeZone.getTimeZone("Asia/Taipei");
        Locale tzLocale = new Locale("ja");
        String jaStdName = "\u4e2d\u56fd\u6a19\u6e96\u6642";
        String jaDstName = "\u4e2d\u56fd\u590f\u6642\u9593";

        if (!tz.getDisplayName(false, TimeZone.LONG, tzLocale).equals
           (jaStdName))
             throw new RuntimeException("\n" + tzLocale + ": LONG, " +
                                        "non-daylight saving name for " +
                                        tz.getID() +
                                        " should be " +
                                        jaStdName);
        if (!tz.getDisplayName(true, TimeZone.LONG, tzLocale).equals
           (jaDstName))
             throw new RuntimeException("\n" + tzLocale + ": LONG, " +
                                        "daylight saving name for " +
                                        tz.getID() +
                                        " should be " +
                                        jaDstName);
    }
}


text:
package io.strimzi.systemtest.utils.kubeUtils.objects;

import io.strimzi.operator.common.model.Labels;
import io.strimzi.systemtest.Constants;
import io.strimzi.systemtest.resources.ResourceOperation;
import io.strimzi.test.TestUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Map;

import static io.strimzi.test.k8s.KubeClusterResource.kubeClient;

public class ServiceUtils {

    private static final Logger LOGGER = LogManager.getLogger(ServiceUtils.class);
    private static final long DELETION_TIMEOUT = ResourceOperation.getTimeoutForResourceDeletion();

    private ServiceUtils() { }

    public static void waitForServiceLabelsChange(String namespaceName, String serviceName, Map<String, String> labels) {
        for (Map.Entry<String, String> entry : labels.entrySet()) {
            boolean isK8sTag = entry.getKey().equals("controller-revision-hash") || entry.getKey().equals("statefulset.kubernetes.io/pod-name");
            boolean isStrimziTag = entry.getKey().startsWith(Labels.STRIMZI_DOMAIN);
            // ignoring strimzi.io and k8s labels
            if (!(isStrimziTag || isK8sTag)) {
                LOGGER.info("Waiting for Service label change {} -> {}", entry.getKey(), entry.getValue());
                TestUtils.waitFor("Service label change " + entry.getKey() + " -> " + entry.getValue(), Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS,
                    Constants.GLOBAL_TIMEOUT, () ->
                        kubeClient(namespaceName).getService(namespaceName, serviceName).getMetadata().getLabels().get(entry.getKey()).equals(entry.getValue())
                );
            }
        }
    }

    public static void waitForServiceLabelsDeletion(String namespaceName, String serviceName, String... labelKeys) {
        for (final String labelKey : labelKeys) {
            LOGGER.info("Service label {} change to {}", labelKey, null);
            TestUtils.waitFor("Service label" + labelKey + " change to " + null, Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS,
                DELETION_TIMEOUT, () ->
                    kubeClient(namespaceName).getService(namespaceName, serviceName).getMetadata().getLabels().get(labelKey) == null
            );
        }
    }

    /**
     * Wait until Service of the given name will be recovered.
     * @param serviceName service name
     * @param serviceUid service original uid
     */
    public static void waitForServiceRecovery(String serviceName, String serviceUid) {
        LOGGER.info("Waiting when Service {}-{} in namespace {} will be recovered", serviceName, serviceUid, kubeClient().getNamespace());

        TestUtils.waitFor("Service " + serviceName + " to be recovered", Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, Constants.TIMEOUT_FOR_RESOURCE_RECOVERY,
            () -> !kubeClient().getServiceUid(serviceName).equals(serviceUid));
        LOGGER.info("{} in namespace {} is recovered", serviceName, kubeClient().getNamespace());
    }

    public static void waitUntilAddressIsReachable(String address) {
        LOGGER.info("Wait until address {} is reachable", address);
        TestUtils.waitFor("", Constants.GLOBAL_POLL_INTERVAL, Constants.GLOBAL_STATUS_TIMEOUT,
            () -> {
                try {
                    InetAddress.getByName(address);
                    return true;
                } catch (IOException e) {
                    return false;
                }
            });
        LOGGER.info("Address {} is reachable", address);
    }
}


text:
/* @LICENSE(MUSLC_MIT) */

#include <sys/mman.h>
#include "internal/syscall.h"
#include "libc.h"

int __madvise(void *addr, size_t len, int advice)
{
	return syscall(SYS_madvise, addr, len, advice);
}

weak_alias(__madvise, madvise);


text:
using System.Collections.Generic;

namespace ModelGraphSTD
{
    internal class ErrorOneAux : ErrorOne
    {
        internal Item Aux;

        #region Constructor  ==================================================
        internal ErrorOneAux(StoreOf<Error> owner, Item item, Item aux, Trait trait, string text = null) : base(owner,item,trait, text)
        {
            Aux = aux;
        }
        #endregion
    }
}


text:
package dev.knative.eventing.kafka.broker.dispatcher.impl.filter.subscriptionsapi;

import io.cloudevents.CloudEvent;
import io.cloudevents.core.builder.CloudEventBuilder;
import java.net.URI;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

import static org.assertj.core.api.Assertions.assertThat;

public class CeSqlFilterTest {

  final static CloudEvent event = CloudEventBuilder.v1()
    .withId("123-42")
    .withDataContentType("application/cloudevents+json")
    .withDataSchema(URI.create("/api/schema"))
    .withSource(URI.create("/api/some-source"))
    .withSubject("a-subject-42")
    .withType("type")
    .withTime(OffsetDateTime.of(
      1985, 4, 12,
      23, 20, 50, 0,
      ZoneOffset.UTC
    ))
    .build();

  @ParameterizedTest
  @MethodSource(value = {"testCases"})
  public void match(CloudEvent event, String expression, boolean shouldMatch) {
    var filter = new CeSqlFilter(expression);
    assertThat(filter.test(event))
      .isEqualTo(shouldMatch);
  }

  static Stream<Arguments> testCases() {
    return Stream.of(
      Arguments.of(event, "'TRUE'", true),
      Arguments.of(event, "'FALSE'", false),
      Arguments.of(event, "0", false),
      Arguments.of(event, "1", false),
      Arguments.of(event, "id LIKE '123%'", true),
      Arguments.of(event, "NOT(id LIKE '123%')", false)
    );
  }

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cat_66b.c
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_dest.label.xml
Template File: sources-sink-66b.tmpl.c
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using malloc() and set data pointer to a small buffer
 * GoodSource: Allocate using malloc() and set data pointer to a large buffer
 * Sinks: cat
 *    BadSink : Copy string to data using strcat
 * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifndef OMITBAD

void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cat_66b_badSink(char * dataArray[])
{
    /* copy data out of dataArray */
    char * data = dataArray[2];
    {
        char source[100];
        memset(source, 'C', 100-1); /* fill with 'C's */
        source[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if source is larger than sizeof(data)-strlen(data) */
        strcat(data, source);
        printLine(data);
        free(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void CWE122_Heap_Based_Buffer_Overflow__c_dest_char_cat_66b_goodG2BSink(char * dataArray[])
{
    char * data = dataArray[2];
    {
        char source[100];
        memset(source, 'C', 100-1); /* fill with 'C's */
        source[100-1] = '\0'; /* null terminate */
        /* POTENTIAL FLAW: Possible buffer overflow if source is larger than sizeof(data)-strlen(data) */
        strcat(data, source);
        printLine(data);
        free(data);
    }
}

#endif /* OMITGOOD */


text:
var SortOrder = Class.create({
  initialize: function(string) {
    this.sortIds = string.toArray().inGroupsOf(8).map(function(key){return key.join("")})
  },

  getSortNumberFor: function(id) {
    var sortNumber = 0

    this.sortIds.each(function(sortId, index) {
      if(sortId == id) {
        sortNumber = index
        throw $break
      }
    })

    return sortNumber
  }
})


text:
<?php

namespace PHPExiftool\Driver\Tag\DICOM;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class LargestImagePixelValueInPlane extends AbstractTag
{

    protected $Id = '0028,0111';

    protected $Name = 'LargestImagePixelValueInPlane';

    protected $FullName = 'DICOM::Main';

    protected $GroupName = 'DICOM';

    protected $g0 = 'DICOM';

    protected $g1 = 'DICOM';

    protected $g2 = 'Image';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Largest Image Pixel Value In Plane';
}