text:
extern "stdcall" {
    fn printf(_: *const u8, ...); //~ ERROR: variadic function must have C calling convention
}

extern {
    fn foo(f: int, x: u8, ...);
}

extern "C" fn bar(f: int, x: u8) {}

fn main() {
    unsafe {
        foo(); //~ ERROR: this function takes at least 2 parameters but 0 parameters were supplied
        foo(1); //~ ERROR: this function takes at least 2 parameters but 1 parameter was supplied

        let x: unsafe extern "C" fn(f: int, x: u8) = foo;
        //~^ ERROR: mismatched types: expected `unsafe extern "C" fn(int, u8)`
        //          but found `unsafe extern "C" fn(int, u8, ...)`
        //          (expected non-variadic fn but found variadic function)

        let y: unsafe extern "C" fn(f: int, x: u8, ...) = bar;
        //~^ ERROR: mismatched types: expected `unsafe extern "C" fn(int, u8, ...)`
        //          but found `extern "C" extern fn(int, u8)`
        //          (expected variadic fn but found non-variadic function)

        foo(1, 2, 3f32); //~ ERROR: can't pass an f32 to variadic function, cast to c_double
        foo(1, 2, true); //~ ERROR: can't pass bool to variadic function, cast to c_int
        foo(1, 2, 1i8); //~ ERROR: can't pass i8 to variadic function, cast to c_int
        foo(1, 2, 1u8); //~ ERROR: can't pass u8 to variadic function, cast to c_uint
        foo(1, 2, 1i16); //~ ERROR: can't pass i16 to variadic function, cast to c_int
        foo(1, 2, 1u16); //~ ERROR: can't pass u16 to variadic function, cast to c_uint
    }
}


text:
#include "regint.h"

/*
 * Name: UTF8-DoCoMo, SJIS-DoCoMo
 * Link: http://www.nttdocomo.co.jp/english/service/imode/make/content/pictograph/basic/index.html
 * Link: http://www.nttdocomo.co.jp/english/service/imode/make/content/pictograph/extention/index.html
 */
ENC_REPLICATE("UTF8-DoCoMo", "UTF-8")
ENC_REPLICATE("SJIS-DoCoMo", "Windows-31J")

/*
 * Name: UTF8-KDDI, SJIS-KDDI, ISO-2022-JP-KDDI
 * Link: http://www.au.kddi.com/ezfactory/tec/spec/img/typeD.pdf
 */
ENC_REPLICATE("UTF8-KDDI", "UTF-8")
ENC_REPLICATE("SJIS-KDDI", "Windows-31J")
ENC_REPLICATE("ISO-2022-JP-KDDI", "ISO-2022-JP")
ENC_REPLICATE("stateless-ISO-2022-JP-KDDI", "stateless-ISO-2022-JP")

/*
 * Name: UTF8-SoftBank, SJIS-SoftBank
 * Link: http://creation.mb.softbank.jp/web/web_pic_about.html
 * Link: http://www2.developers.softbankmobile.co.jp/dp/tool_dl/download.php?docid=120&companyid=
 */
ENC_REPLICATE("UTF8-SoftBank", "UTF-8")
ENC_REPLICATE("SJIS-SoftBank", "Windows-31J")

redpajama_set_name: RedPajamaGithub


text:
package com.orientechnologies.orient.server.distributed.asynch;

import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseType;
import com.orientechnologies.orient.core.db.OrientDB;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.OElement;
import com.orientechnologies.orient.core.record.OVertex;
import org.junit.Ignore;

@Ignore
public class AsyncReplMode2ServersAddEdgeIT extends BareBoneBase2ServerTest {

  private static final int NUM_OF_LOOP_ITERATIONS = 100;

  private Object parentV1Id;

  @Override
  protected String getDatabaseName() {
    return "AsyncReplMode2ServersAddEdgeIT";
  }

  protected void dbClient1(BareBonesServer[] servers) {
    OGlobalConfiguration.LOG_CONSOLE_LEVEL.setValue("FINEST");

    synchronized (LOCK) {
      OrientDB orientdb = servers[0].getServer().getContext();
      orientdb.createIfNotExists(getDatabaseName(), ODatabaseType.PLOCAL);
      ODatabaseDocument graph = orientdb.open(getDatabaseName(), "admin", "admin");
      if (!graph.getMetadata().getSchema().existsClass("vertextype"))
        graph.createClass("vertextype", "V");
      if (!graph.getMetadata().getSchema().existsClass("edgetype"))
        graph.createClass("edgetype", "E");

      graph.begin();
      try {
        OVertex parentV1 = graph.newVertex("vertextype");
        parentV1.save();
        graph.commit();
        graph.begin();
        assertEquals(1, parentV1.getRecord().getVersion());
        parentV1Id = parentV1.getIdentity();

        for (int i = 0; i < NUM_OF_LOOP_ITERATIONS; i++) {
          OVertex childV = graph.newVertex("vertextype");
          childV.save();
          graph.commit();
          graph.begin();
          assertEquals(1, childV.getVersion());

          parentV1.addEdge(childV, "edgetype").save();

          graph.commit();
          graph.begin();

          OLogManager.instance()
              .error(
                  this,
                  "parentV1 %s v%d should be v%d",
                  null,
                  parentV1.getIdentity(),
                  parentV1.getRecord().getVersion(),
                  i + 2);

          assertEquals(i + 2, parentV1.getVersion());
          assertEquals(2, childV.getVersion());
        }

        pause();
      } catch (Throwable e) {
        OLogManager.instance().error(this, "Exception", e);
        if (exceptionInThread == null) {
          exceptionInThread = e;
        }
      } finally {
        System.out.println("Shutting down");
        graph.close();
        LOCK.notifyAll();
      }
    }
  }

  protected void dbClient2(BareBonesServer[] servers) {
    sleep(500);

    synchronized (LOCK) {
      OrientDB orientdb = servers[2].getServer().getContext();
      orientdb.createIfNotExists(getDatabaseName(), ODatabaseType.PLOCAL);
      ODatabaseDocument graph = orientdb.open(getDatabaseName(), "admin", "admin");

      try {
        sleep(500);
        OElement parentV1 = graph.load((ORID) parentV1Id);
        assertEquals(NUM_OF_LOOP_ITERATIONS + 1, parentV1.getRecord().getVersion());
      } catch (Throwable e) {
        if (exceptionInThread == null) {
          exceptionInThread = e;
        }
      } finally {
        System.out.println("Shutting down");
        graph.close();
        LOCK.notifyAll();
      }
    }
  }
}


text:
import { shallowMount } from "@vue/test-utils";
import App from "./App.vue";

test("links are a list of url, label objects", () => {
  const wrapper = shallowMount(App);
  const links = wrapper.vm.links;
  for (const link of links) {
    expect(link).toEqual({
      url: expect.stringMatching(/^https?:\/\//),
      label: expect.any(String)
    });
  }
});


text:
FOUNDATION_EXPORT double NSMPlayerVersionNumber;
FOUNDATION_EXPORT const unsigned char NSMPlayerVersionString[];


text:
create table t1 (i1 integer shared 0, i2 integer) ;
insert into t1 set i2=1;
insert into t1 set i2=2;
update t1 set t1.i1=-1;

select t1.i1, i2 from t1 order by 2;
show columns in t1;

alter table t1 change i1 i1 integer NOT NULL;

insert into t1 set i2=3;

select t1.i1, i2 from t1 order by 2;

show columns in t1;

drop table t1;

-- NOT NULL with type change
create table t1  (i1 integer shared 0, i2 integer) ;
insert into t1 set i2=1;
insert into t1 set i2=2;
update t1 set t1.i1=-1;

select t1.i1, i2 from t1 order by 2;
show columns in t1;

alter table t1 change i1 i1 bigint NOT NULL;

insert into t1 set i2=3;

select t1.i1, i2 from t1 order by 2;

show columns in t1;

drop table t1;

-- adding NOT NULL with type change initial SHARED value is NULL
create table t1  (i1 integer shared NULL, i2 integer) ;
insert into t1 set i2=1;
insert into t1 set i2=2;

select t1.i1, i2 from t1 order by 2;
show columns in t1;

alter table t1 change i1 i1 bigint NOT NULL;

insert into t1 set i2=3;

select t1.i1, i2 from t1 order by 2;

show columns in t1;

drop table t1;

-- STRICT MODE applies for SHARED ATTRIBUTE
set system parameters 'alter_table_change_type_strict=yes';
set system parameters 'error_log_level=warning';
set system parameters 'error_log_warning=yes';
create table t1  (i1 integer shared NULL, i2 integer) ;
insert into t1 set i2=1;
insert into t1 set i2=2;

select t1.i1, i2 from t1 order by 2;
show columns in t1;

alter table t1 change i1 i1 bigint NOT NULL;

insert into t1 set i2=3;

select t1.i1, i2 from t1 order by 2;

show columns in t1;

drop table t1;
set system parameters 'alter_table_change_type_strict=no';

-- UNIQUE
create table t1 (i1 integer shared 0, i2 integer) ;
insert into t1 set i2=1;
insert into t1 set i2=2;
update t1 set t1.i1=-1;

select t1.i1, i2 from t1 order by 2;
show columns in t1;

alter table t1 change i1 i1 integer UNIQUE;

insert into t1 set i2=3;

select t1.i1, i2 from t1 order by 2;

show columns in t1;

drop table t1;

-- PRIMARY KEY
create table t1 (i1 integer shared 0, i2 integer) ;
insert into t1 set i2=1;
insert into t1 set i2=2;
update t1 set t1.i1=-1;

select t1.i1, i2 from t1 order by 2;
show columns in t1;

alter table t1 change i1 i1 integer primary key;

insert into t1 set i2=3;

select t1.i1, i2 from t1 order by 2;

show columns in t1;

drop table t1;

-- auto_increment
create table t1 (i1 integer shared 0, i2 integer) ;
insert into t1 set i2=1;
insert into t1 set i2=2;
update t1 set t1.i1=-1;

select t1.i1, i2 from t1 order by 2;
show columns in t1;

alter table t1 change i1 i1 integer auto_increment;

insert into t1 set i2=3;

select t1.i1, i2 from t1 order by 2;

show columns in t1;

drop table t1;
commit;
--+ holdcas off;


text:
namespace app {
    'use strict';

    /**
     *
     *
     * @export
     * @interface IRightsService
     */
    export interface IRightsService {
        /**
         *
         *
         * @param {Club} club
         * @param {AppUser} user
         * @returns {angular.IPromise<void>}
         */
        giveRights(club: Club, user: AppUser): angular.IPromise<void>;
    }

    /**
     *
     *
     * @class RightsService
     * @implements {IRightsService}
     */
    class RightsService implements IRightsService {
        /**
         *
         *
         * @private
         * @type {*}
         */
        private firebaseRolesRef: any;
        /**
         *
         *
         * @private
         * @type {*}
         */
        private firebaseUserRolesRef: any;

        // @ngInject
        /**
         * Creates an instance of RightsService.
         *
         * @param {angular.IRootScopeService} $rootScope
         * @param {angular.IQService} $q
         * @param {angular.ILogService} $log
         */
        constructor(
            private $rootScope: angular.IRootScopeService,
            private $q: angular.IQService,
            private $log: angular.ILogService
        ) {
            let me: RightsService = this;
            me.firebaseRolesRef = firebase.database().ref('/roles');
            me.firebaseUserRolesRef = firebase.database().ref('/userroles');

        }

        /**
         *
         *
         * @param {Club} club
         * @param {AppUser} user
         * @returns {angular.IPromise<void>}
         */
        public giveRights(club: Club, user: AppUser): angular.IPromise<void> {
            let me: RightsService = this;
            let def: angular.IDeferred<any> = me.$q.defer();

            return def.promise;
        }

        /**
         *
         *
         * @param {AppUser} user
         * @param {(Club | Event | Post)} item
         * @returns {angular.IPromise<boolean>}
         */
        public hasRights(user: AppUser, item: Club | Event | Post): angular.IPromise<boolean> {
            let me: RightsService = this;
            let def: angular.IDeferred<boolean> = me.$q.defer();

            return def.promise;
        }

    }
    angular.module('app').service('rightsService', RightsService);
}


text:
<?php

class tx_Traversal_Hook
{
	/**
	 * hook after all database operations
	 *
	 * @param	string	$status		(new|update)
	 * @param	string	$table
	 * @param	int		$id
	 * @param	array	&$fieldArray
	 * @param	object	&$object
	 * @return	void
	 */
	public function processDatamap_afterDatabaseOperations($status, $table, $id, &$fieldArray, t3lib_TCEmain &$object)
	{
		if ($table === "pages") {
			Tx_Traversal_PageTree::recalculate();
		}
	}

	/**
	 * hook after BE db command
	 *
	 * @param string $command
	 * @param string $table
	 * @param string $id
	 * @param string $value
	 * @param t3lib_TCEmain $tcemain
	 * @return void
	 */
	public function processCmdmap_postProcess($command, $table, $id, $value, t3lib_TCEmain $tcemain)
	{
		if ($table == 'pages' && in_array($command, array('move', 'delete', 'undelete'))) {
			Tx_Traversal_PageTree::recalculate();
		}
	}
}


text: Assignment 2 and 3 of UCI's INF225 Information Retrieval course: Search Engine


text:
package com.sensoranalytics.inspectionmanager.facade;

import com.sensoranalytics.inspectionmanager.entity.BaseEntity;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Root;

/**
 *
 * @author Joel Bondurant
 */
public abstract class AbstractFacade<T> {

	private Class<T> entityClass;

	public AbstractFacade(Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	protected abstract EntityManager getEntityManager();

	public void create(T entity) {
		getEntityManager().persist(entity);
	}

	public void update(T entity) {
		getEntityManager().merge(entity);
	}

	public void delete(T entity) {
		getEntityManager().remove(getEntityManager().merge(entity));
	}

	public void bulkCreate(Collection<T> entityList) {
		for (T entity : entityList) {
			if (((BaseEntity) entity).getId() == null) {
				getEntityManager().persist(entity);
			}
		}
	}

	public void bulkUpdate(Collection<T> entityList) {
		for (T entity : entityList) {
			if (((BaseEntity) entity).getId() != null) {
				getEntityManager().merge(entity);
			}
		}
	}

	public void bulkDelete(Collection<T> entityList) {
		for (T entity : entityList) {
			getEntityManager().remove(getEntityManager().merge(entity));
		}
	}

	public T find(Object id) {
		return getEntityManager().find(entityClass, id);
	}

	public List<T> findAll() {
		CriteriaQuery<T> cq = getEntityManager().getCriteriaBuilder().createQuery(entityClass);
		cq.select(cq.from(entityClass));
		return getEntityManager().createQuery(cq).getResultList();
	}

	public int count() {
		CriteriaQuery<Long> cq = getEntityManager().getCriteriaBuilder().createQuery(Long.class);
		Root<T> rt = cq.from(entityClass);
		Expression<Long> count = getEntityManager().getCriteriaBuilder().count(rt);
		cq.select(count);
		TypedQuery<Long> tq = getEntityManager().createQuery(cq);
		return (tq.getSingleResult()).intValue();
	}

	public void bulkSync(Collection<T> entityList) {
		this.bulkCreate(entityList);
		this.bulkUpdate(entityList);
	}
}


text:
var sharedSchema = new SimpleSchema({
  description: { type: String },
});

Template.optionsAndSubmit.helpers({
  mutationSchema: function () {
    return new SimpleSchema([
      sharedSchema,
      Mutations.simpleSchema().pick([
        "biological_source",
        "mutation_impact_assessor",
        "mutation_caller",
      ]),
    ]);
  },
  sharedSchema: function () {
    return sharedSchema;
  },
  onlyDescription: function () {
    return sharedSchema;
  },

  // superpathwaySchema: function () {
  //   return new SimpleSchema([
  //     sharedSchema,
  //     {
  //       "update_or_create": {
  //         type: String,
  //         label: "Update or create",
  //         allowedValues: ["update", "create"],
  //       },
  //     },
  //     Superpathways.simpleSchema().pick(['name']),
  //   ]);
  // },
});

var maxErrorsToDisplay = 5;
Template.submissionStatus.helpers({
  hasErrors: function () {
    return this.errors && this.errors.length > 0;
  },
  firstCoupleErrors: function () {
    return this.errors.slice(0, maxErrorsToDisplay);
  },
  tooManyErrors: function () {
    return this.errors.length > maxErrorsToDisplay;
  },
});

Template.submissionOptions.helpers({
  currentOptions: function () {
    // wrap in nonreactive so that it doesn't delete filled-in
    // stuff when the submission object is updated in an
    // unrelated way
    return Tracker.nonreactive(function () {
      return Template.instance().parent().data.options;
    });
  },
  readonlyIfNotEditing: function () {
    if (Template.instance().parent().data.status !== "editing") {
      return "readonly";
    }
  },
});

Template.sharedFields.helpers({
  collaborationOptions: function () {
    return Collaborations.find().map(function (collaboration) {
      return {
        label: collaboration.description,
        value: collaboration.name,
      };
    });
  },
});

Template.validateAndSubmit.events({
  "click .save-for-later": function (event, instance) {
    event.preventDefault();
    WranglerSubmissions.update(instance.parent(2).data._id, {
      $set: {
        "options": AutoForm.getFormValues("submission-options").insertDoc
      }
    });
  },
  "click .reset-options": function (event, instance) {
    event.preventDefault();
    WranglerSubmissions.update(instance.parent(2).data._id, {
      $set: {
        "options": {}
      }
    });
    AutoForm.resetForm("submission-options");
  },
  "click .validate-and-submit": function (event, instance) {
    event.preventDefault();

    if (AutoForm.validateForm("submission-options")) {
      var submission_id = instance.parent(2).data._id;
      WranglerSubmissions.update(submission_id, {
        $set: {
          "options": AutoForm.getFormValues("submission-options").insertDoc
        }
      });

      Meteor.call("submitSubmission", submission_id);
    }
  },
});

// function getUpdateOrCreate() {
//   return AutoForm.getFieldValue("update_or_create", "submission-options");
// }
//
// Template.superpathwayFields.helpers({
//   updateCreateSelected: function () {
//     return getUpdateOrCreate() !== undefined;
//   },
//   selectOrText: function () {
//     if (getUpdateOrCreate() === "update") {
//       return "select";
//     } else {
//       return "text";
//     }
//   },
//   superpathwayOptions: function () {
//     var sortedNames = _.pluck(Superpathways.find({}).fetch(), "name").sort();
//
//     var uniqueNames = [];
//     _.each(sortedNames, function (value, index) {
//       if (index === 0 || sortedNames[index - 1] !== value) {
//         uniqueNames.push(value);
//       }
//     });
//
//     return _.map(uniqueNames, function (value) {
//       return {
//         "label": value,
//         "value": value,
//       };
//     });
//   },
// });


text:
namespace uc
{
    namespace pso
    {
        namespace parser
        {

            template <typename iterator, typename error_handler>
            struct depth_stencil_desc : public qi::grammar< iterator, ast::depth_stencil_desc(), ascii::space_type  >
            {
                using base = qi::grammar< iterator, ast::depth_stencil_desc(), ascii::space_type >;

                depth_stencil_desc(error_handler& e) : base(m_start, "depth_stencil_desc")
                , m_depth_enable(".DepthEnable")
                , m_stencil_enable(".StencilEnable")
                , m_front_face(e)
                , m_back_face(e)
                , m_stencil_read_mask(".StencilReadMask")
                , m_stencil_write_mask(".StencilWriteMask")
                {
                    using qi::lit;
                    //qi::raw_type    raw;
                    //qi::lexeme_type lexeme;
                    //qi::alpha_type  alpha;
                    //qi::alnum_type  alnum;
                    //qi::uint_type   uint_;

                    m_identifier = raw[lexeme[(alpha | '_') > *(alnum | '_')]];
                    m_start = lit("DepthStencilDescription") > m_identifier > '=' > '{'
                    > m_depth_enable
                    > m_depth_write_mask
                    > m_depth_function
                    > m_stencil_enable
                    > m_stencil_read_mask
                    > m_stencil_write_mask
                    > m_front_face
                    > m_back_face
                    > '}';

                    m_identifier.name("identifier");

                    {

                        using boost::phoenix::function;
                        using error_handler_function = function < error_handler >;
                        using annotation_function = function < annotation<iterator> >;

                        qi::_1_type     _1;
                        //qi::_3_type     _3;
                        qi::_val_type   _val;

                        using qi::on_error;
                        using qi::on_success;
                        using qi::fail;

                        //on_error<fail>(m_start, error_handler_function(e)(_3));
                        auto success = annotation_function(annotation<iterator>(e.m_iters, e.m_first));
                        on_success(m_start, success(_val, _1));
                    }
                }

                named_value_bool<iterator>                                         m_depth_enable;
                named_value_bool<iterator>                                         m_stencil_enable;
                depth_write_mask<iterator>                                         m_depth_write_mask;
                depth_function<iterator>                                           m_depth_function;
                front_face<iterator, error_handler>                                m_front_face;
                back_face<iterator, error_handler>                                 m_back_face;
                named_value_uint32<iterator>                                       m_stencil_read_mask;
                named_value_uint32<iterator>                                       m_stencil_write_mask;

                qi::rule<iterator, std::string(), ascii::space_type >              m_identifier;
                qi::rule<iterator, ast::depth_stencil_desc(), ascii::space_type >  m_start;
            };
        }
    }
}


text:
@class ClassADependsOnB;

@interface ClassBDependsOnA : NSObject

- (ClassADependsOnB *)dependencyOnA;
- (void)setDependencyOnA:(ClassADependsOnB *)dependencyOnA;

@end


text:
local io, string, os, table = io, string, os, table
local type, pcall, load, setmetatable, ipairs, next = type, pcall, load, setmetatable, ipairs, next
local ENV = {}
_ENV = ENV

--- Output formatted string to the current output.
-- @function printf
-- @param str C-like string (STRING)
-- @param ... Variable number of arguments to interpolate str (VARARGS)
local printf = function (str, ...)
  return io.write(string.format(str, ...))
end

--- Output formatted string to a specified output.
-- @function fprintf
-- @param fd stream/descriptor
-- @param str C-like string (STRING)
-- @param ... Variable number of arguments to interpolate str (VARARGS)
local fprintf = function (fd, str, ...)
  local o = io.output()
  io.output(fd)
  local ret, err = printf(str, ...)
  io.output(o)
  return ret, err
end

--- Output formatted string to STDERR.
-- @function warn
-- @param str C-like string (STRING)
-- @param ... Variable number of arguments to interpolate str (VARARGS)
local warn = function (str, ...)
  return fprintf(io.stderr, str, ...)
end

--- Output formatted string to STDERR and return 1 as the exit status.
-- @function errorf
-- @param str C-like string (STRING)
-- @param ... Variable number of arguments to interpolate str (VARARGS)
local errorf = function (str, ...)
  warn(str, ...)
  os.exit(1)
end

--- Call cimicida.errorf if the first argument is false (i.e. nil or false).
-- @function assertf
-- @param v value to evaluate
-- @param str C-like string (STRING)
-- @param ... Variable number of arguments to interpolate str (VARARGS)
local assertf = function (v, str, ...)
  if v then
    return true
  else
    errorf(str, ...)
  end
end

-- Append a line break and string to an input string.
-- @function append
-- @param str Input string (STRING)
-- @param a String to append to str (STRING)
-- @return new string (STRING)
local append = function (str, a)
  return string.format("%s\n%s", str, a)
end

--- Time in the strftime(3) format %H:%M.
-- @function timehm
-- @return the time as a string (STRING)
local timehm = function ()
  return os.date("%H:%M")
end

--- Date in the strftime(3) format %Y-%m-%d.
-- @function dateymd
-- @return the date as a string (STRING)
local dateymd = function ()
  return os.date("%Y-%m-%d")
end

--- Timestamp in the strftime(3) format %Y-%m-%d %H:%M:%S %Z%z.
-- @function timestamp
-- @return the timestamp as a string (STRING)
local timestamp = function ()
  return os.date("%Y-%m-%d %H:%M:%S %Z%z")
end

--- Check if a table has an specified string.
-- @function find_string
-- @param tbl table to search (TABLE)
-- @param string value to look for in tbl (STRING)
-- @return a boolean value, true if v is found, nil otherwise (BOOLEAN)
local find_string = function (tbl, value)
  for _, tval in next, tbl do
    tval = string.gsub(tval, '[%c]', '')
    if tval == value then return true end
  end
end

--- Convert an array to a record.
-- Array values are converted into field names
-- @function arr_to_rec
-- @warning Does not check if input table is a sequence.
-- @param tbl the properly sequenced table to convert (TABLE)
-- @param def default value for each field in the record (VALUE)
-- @return the converted table (TABLE)
local arr_to_rec = function (tbl, def)
  local t = {}
  for n = 1, #tbl do t[tbl[n]] = def end
  return t
end

--- Convert string to table.
-- Each line is a table value
-- @function ln_to_tbl
-- @param str string to convert (STRING)
-- @return the table (TABLE)
local ln_to_tbl = function (str)
  local tbl = {}
  if not str then
    return tbl
  end
  for ln in string.gmatch(str, "([^\n]*)\n") do
    tbl[#tbl + 1] = ln
  end
  return tbl
end

--- Split alphanumeric matches of a string into table values.
-- @function word_to_tbl
-- @param str string to convert (STRING)
-- @return the table (TABLE)
local word_to_tbl = function (str)
  local t = {}
  for s in string.gmatch(str, "%w+") do
    t[#t + 1] = s
  end
  return t
end

--- Split non-space character matches of a string into table values.
-- @function str_to_tbl
-- @param str string to convert (STRING)
-- @return the table (TABLE)
local str_to_tbl = function (str)
  local t = {}
  for s in string.gmatch(str, "%S+") do
    t[#t + 1] = s
  end
  return t
end

--- Escape a string for pattern usage
-- From lua-nucleo.
-- @function escape_pattern
-- @param str string to escape (STRING)
-- @return a new string (STRING)
local escape_pattern = function (str)
  local matches =
  {
    ["^"] = "%^",
    ["$"] = "%$",
    ["("] = "%(",
    [")"] = "%)",
    ["%"] = "%%",
    ["."] = "%.",
    ["["] = "%[",
    ["]"] = "%]",
    ["*"] = "%*",
    ["+"] = "%+",
    ["-"] = "%-",
    ["?"] = "%?",
    ["\0"] = "%z"
  }
  return string.gsub(str, ".", matches)
end

--- Filter table values.
-- Adapted from <http://stackoverflow.com/questions/12394841/safely-remove-items-from-an-array-table-while-iterating>
-- @function filter_tbl_value
-- @param tbl table to operate on (TABLE)
-- @param patt pattern to filter (STRING)
-- @param plain set to true if doing plain matching (BOOLEAN)
-- @return modified table (TABLE)
local filter_tbl_value = function (tbl, patt, plain)
  plain = plain or nil
  local s, c = #tbl, 0
  for n = 1, s do
    if string.find(tbl[n], patt, 1, plain) then
      tbl[n] = nil
    end
  end
  for n = 1, s do
    if tbl[n] ~= nil then
      c = c + 1
      tbl[c] = tbl[n]
    end
  end
  for n = c + 1, s do
    tbl[n] = nil
  end
  return tbl
end

--- Convert file into a table.
-- Each line is a table value
-- @function file_to_tbl
-- @param file file to convert (STRING)
-- @return a table (TABLE)
local file_to_tbl = function (file)
  local ok ,fd =  pcall(io.open, file, "re")
  if not ok then
    fd = io.open(file, "r")
  end
  if fd then
    local default = io.input()
    io.input(fd)
    local tbl = {}
    for ln in io.lines() do
      tbl[#tbl + 1] = ln
    end
    io.close(fd)
    io.input(default)
    return tbl
  end
end

--- Find a string in a table value.
-- string is a plain string not a pattern
-- @function find_in_tbl
-- @param tbl properly sequenced table to traverse (TABLE)
-- @param str string to find (STRING)
-- @param patt boolean setting for plain strings (BOOLEAN)
-- @return the matching index if string is found, nil otherwise (NUMBER)
local find_in_tbl = function (tbl, str, patt)
  patt = patt or nil
  local ok, found
  for n = 1, #tbl do
    ok, found = pcall(string.find, tbl[n], str, 1, patt)
    if ok and found then
      return n
    end
  end
end

--- Do a shallow copy of a table.
-- An empty table is created in the copy when a table is encountered
-- @function shallow_cp
-- @param tbl table to be copied (TABLE)
-- @return the copy as a table (TABLE)
local shallow_cp = function (tbl)
  local copy = {}
  for f, v in next, tbl do
    if type(v) == "table" then
      copy[f] = {} -- first level only
    else
      copy[f] = v
    end
  end
  return copy
end

--- Split a path into its immediate location and file/directory components.
-- @function split_path
-- @param path path to split (STRING)
-- @return location (STRING)
-- @return file/directory (STRING)
local split_path = function (path)
  local l = string.len(path)
  local c = string.sub(path, l, l)
  while l > 0 and c ~= "/" do
    l = l - 1
    c = string.sub(path, l, l)
  end
  if l == 0 then
    return '', path
  else
    return string.sub(path, 1, l - 1), string.sub(path, l + 1)
  end
end

--- Check if a path is a file or not.
-- @function test_open
-- @param file path to the file (STRING)
-- @return true if path is a file, nil otherwise (BOOLEAN)
local test_open = function (file)
  local fd = io.open(file, "rb")
  if fd then
    io.close(fd)
    return true
  end
end

--- Read a file/path.
-- @function fopen
-- @param file path to the file (STRING)
-- @return the contents of the file, nil if the file cannot be read or opened (STRING or NIL)
local fopen = function (file)
  local str
  for s in io.lines(file, 2^12) do
    str = string.format("%s%s", str or "", s)
  end
  if string.len(str) ~= 0 then
    return str
  end
end

--- Write a string to a file/path.
-- @function fwrite
-- @param path path to the file (STRING)
-- @param str string to write (STRING)
-- @param mode io.open mode (STRING)
-- @return true if the write succeeded, nil and the error message otherwise (BOOLEAN)
local fwrite = function (path, str, mode)
  local setvbuf, write = io.setvbuf, io.write
  mode = mode or "w+"
  local fd = io.open(path, mode)
  if fd then
    fd:setvbuf("no")
    local _, err = fd:write(str)
    io.flush(fd)
    io.close(fd)
    if err then
      return nil, err
    end
    return true
  end
end

--- Get line.
-- Given a line number return the line as a string.
-- @function getln
-- @param ln line number (NUMBER)
-- @param file (STRING)
-- @return the line (STRING)
local getln = function (ln, file)
  local str = fopen(file)
  local i = 0
  for line in string.gmatch(str, "([^\n]*)\n") do
    i = i + 1
    if i == ln then return line end
  end
end

--- Simple string interpolation.
-- Given a record, interpolate by replacing field names with the respective value
-- Example:
-- tbl = { "field" = "value" }
-- str = [[ this is the {{ field }} ]]
-- If passed with these arguments 'this is the {{ field }}' becomes 'this is the value'
-- @function sub
-- @param str string to interpolate (STRING)
-- @param tbl table (record) to deduce values from (TABLE)
-- @return processed string (STRING)
local sub = function (str, tbl)
  local t, _ = {}, nil
  _, str = pcall(string.gsub, str, "{{[%s]-([%g]+)[%s]-}}",
    function (s)
      t.type = type
      local code = [[
        V=%s
        if type(V) == "function" then
          V=V()
        end
      ]]
      local lua = string.format(code, s)
      local chunk, err = load(lua, lua, "t", setmetatable(t, {__index=tbl}))
      if chunk then
        chunk()
        return t.V
      else
        return s
      end
    end) -- pcall
  return str
end

--- Generate a string based on the values returned by os.execute or px.exec.
-- @function exit_string
-- @param proc process name (STRING)
-- @param status exit status (STRING)
-- @param code exit code (NUMBER)
-- @return a formatted string (STRING)
local exit_string = function (proc, status, code)
  if status == "exit" or status == "exited" then
    return string.format("%s: Exited with code %s", proc, code)
  end
  if status == "signal" or status == "killed" then
    return string.format("%s: Caught signal %s", proc, code)
  end
end

--- Check if "yes" or a "true" was passed.
-- @function truthy
-- @param s string (STRING)
-- @return the boolean true if the string matches, nil otherwise (BOOLEAN)
local truthy = function (s)
  if s == "yes" or
     s == "YES" or
     s == "true" or
     s == "True" or
     s == "TRUE" then
     return true
  end
end

--- Convert a "no" or a "false" was passed.
-- @function falsy
-- @param s string (STRING)
-- @return the boolean true if the string matches, nil otherwise (BOOLEAN)
local falsy = function (s)
  if s == "no" or
     s == "NO" or
     s == "false" or
     s == "False" or
     s == "FALSE" then
     return true
  end
end

--- Wrap io.popen also known as popen(3)
-- The command has a script preamble.
-- 1. Exit immediately if a command exits with a non-zero status
-- 2. Pathname expansion is disabled.
-- 3. STDIN is closed
-- 4. Copy STDERR to STDOUT
-- 5. Finally replace the shell with the command
-- @function popen
-- @param str command to popen(3) (STRING)
-- @param cwd current working directory (STRING)
-- @param ignore_error boolean setting to ignore errors (BOOLEAN)
-- @param return_code boolean setting to return exit code (BOOLEAN)
-- @return the output as a string if the command exits with a non-zero status, nil otherwise (STRING or BOOLEAN)
-- @return a status output from cimicida.exitstr as a string (STRING)
local popen = function (str, cwd, _ignore_error, _return_code)
  local result = {}
  local header = [[  set -ef
  export LC_ALL=C
  exec 0>&- 2>&1
  ]]
  if cwd then
    str = string.format("%scd %s\n%s", header, cwd, str)
  else
    str = string.format("%s%s", header, str)
  end
  local pipe = io.popen(str, "re")
  io.flush(pipe)
  local tbl = {}
  for ln in pipe:lines() do
    tbl[#tbl + 1] = ln
  end
  local _
  _, result.status, result.code = io.close(pipe)
  result.bin = "io.popen"
  if _return_code then
    return result.code, result
  elseif _ignore_error or result.code == 0 then
    return tbl, result
  else
    return nil, result
  end
end

--- Wrap io.popen also known as popen(3)
-- Unlike cimicida.popen this writes to the pipe
-- The command has a script preamble.
-- 1. Exit immediately if a command exits with a non-zero status
-- 2. Pathname expansion is disabled.
-- 3. STDOUT is closed
-- 4. STDERR is closed
-- 5. Finally replace the shell with the command
-- @function pwrite
-- @param str command to popen(3) (STRING)
-- @param data string to feed to the pipe (STRING)
-- @return the true if the command exits with a non-zero status, nil otherwise (BOOLEAN)
-- @return a status output from cimicida.exitstr as a string (STRING)
local pwrite = function (str, data)
  local result = {}
  local write = io.write
  str = [[  set -ef
  export LC_ALL=C
  exec ]] .. str
  local pipe = io.popen(str, "we")
  io.flush(pipe)
  pipe:write(data)
  local _
  _, result.status, result.code = io.close(pipe)
  if result.code == 0 then
    return true, result
  else
    return nil, result
  end
end

--- Wrap os.execute also known as system(3).
-- The command has a script preamble.
-- 1. Exit immediately if a command exits with a non-zero status
-- 2. Pathname expansion is disabled.
-- 3. STDERR and STDIN are closed
-- 4. STDOUT is piped to /dev/null
-- 5. Finally replace the shell with the command
-- @function system
-- @param str command to pass to system(3) (STRING)
-- @return true if exit code is equal to zero, nil otherwise (BOOLEAN)
-- @return a status output from cimicida.exitstr as a string (STRING)
local system = function (str)
  local result = {}
  local set = [[  set -ef
  export LC_ALL=C
  exec 0>&- 2>&- 1>/dev/null
  exec ]]
  local redir = [[ 0>&- 2>&- 1>/dev/null ]]
  local _
  _, result.status, result.code = os.execute(set .. str .. redir)
  result.bin = "os.execute"
  if result.code == 0 then
    return true, result
  else
    return nil, result
  end
end

--- Wrap os.execute also known as system(3).
-- Similar to cimicida.system but it does not replace the shell.
-- Suitable for scripts.
-- @function execute
-- @param str string to pass to system(3) (STRING)
-- @return true if exit code is equal to zero, nil otherwise (BOOLEAN)
-- @return a status output from cimicida.exitstr as a string (STRING)
local execute = function (str)
  local result = {}
  local set = [[  set -ef
  exec 0>&- 2>&- 1>/dev/null
  ]]
  local _
  _, result.status, result.code = os.execute(set .. str)
  if result.code == 0 then
    return true, result
  else
    return nil, result
  end
end

--- Run a shell pipe.
-- @function pipeline
-- @param ... a vararg containing the command pipe. The first argument should be popen or execute
-- @return the output from cimicida.popen or cimicida.execute, nil if popen or execute was not passed (STRING or BOOLEAN)
local pipeline = function (...)
  local pipe = {}
  local cmds = {...}
  for n = 2, #cmds do
    pipe[#pipe + 1] = table.concat(cmds[n], " ")
    if n ~= #cmds then pipe[#pipe + 1] = " | " end
  end
  if cmds[1] == "popen" then
    return popen(table.concat(pipe))
  elseif cmds[1] == "execute" then
    return execute(table.concat(pipe))
  else
    return
  end
end

--- Time a function run.
-- @function time
-- @param f the function (FUNCTION)
-- @param ... a vararg containing the arguments for the function (VARARGS)
-- @return the return values of the function (VALUE)
-- @return the seconds elapsed as a number (NUMBER)
local time = function (f, ...)
  local t1 = os.time()
  local fn = {f(...)}
  return table.unpack(fn), os.difftime(os.time() , t1)
end

--- Escape quotes ",'.
-- @function escape_quotes
-- @param str string to quote (STRING)
-- @return quoted string (STRING)
local escape_quotes = function (str)
  str = string.gsub(str, [["]], [[\"]])
  str = string.gsub(str, [[']], [[\']])
  return str
end

--- Log to a file.
-- @function flog
-- @param file path name of the file (STRING)
-- @param ident identification (STRING)
-- @param msg string to log (STRING)
-- @return a boolean value, true if not errors, nil otherwise (BOOLEAN)
local flog = function (file, ident, msg)
  local setvbuf = io.setvbuf
  local openlog = function (f)
    local fd = io.open(f, "ae+")
    if fd then
      return fd
    end
  end
  local fd = openlog(file)
  local log = "%s %s: %s\n"
  local timestamp = os.date("%a %b %d %T")
  fd:setvbuf("line")
  local _, err = fprintf(fd, log, timestamp, ident, msg)
  io.flush(fd)
  io.close(fd)
  if err then
    return nil, err
  end
  return true
end

--- Insert a value to a table position if the first argument is not nil or not false.
-- Wraps table.insert().
-- @function insert_if
-- @param bool value to evaluate (VALUE)
-- @param list table to insert to (TABLE)
-- @param pos position in the table (NUMBER)
-- @param value value to insert (VALUE)
-- @return the result of table.insert() (VALUE)
local insert_if = function (bool, list, pos, value)
  if bool then
    if type(value) == "table" then
      for n, i in ipairs(value) do
        local p = n - 1
        table.insert(list, pos + p, i)
      end
    else
      table.insert(list, pos, value)
    end
  end
end

--- Return the second argument if the first argument is not nil or not false.
-- For value functions there should be no evaluation in the arguments.
-- @function return_if
-- @param bool value to evaluate (VALUE)
-- @param value to return (VALUE)
-- @return the value if bool is not nil or not false
local return_if = function (bool, value)
  if bool then
    return (value)
  end
end

--- Return the second argument if the first argument is nil or false.
-- @function return_if_not
-- @param bool value to evaluate (VALUE)
-- @param value to return (VALUE)
-- @return the value if bool is nil or false
local return_if_not = function (bool, value)
  if bool == false or bool == nil then
    return value
  end
end

--- A function for testing and condition and returning an error in case.
-- Returns a function for testing a parameter and if the parameter is false or nil, logs to a file and output to stderr.
-- @function try
-- @param file file to log to (STRING)
-- @param ident string to identify as when logging (STRING)
-- @return a function
local try = function (file, ident)
  return function (condition, error_string)
    if condition then return true end
    error_string = string.format("%s\n", error_string)
    flog(file, ident, error_string)
    errorf(error_string)
  end
end

--- Truncate a file.
-- @function truncate
-- @param file file to truncate (STRING)
-- @return true if successful, or nil otherwise (BOOLEAN)
local truncate = function (file)
  local fd = io.open(file, "w+")
  if fd then
    local o = io.output()
    io.output(fd)
    io.write("")
    io.close()
    io.output(o)
    return true
  end
end

--- Read file then assign to a string.
-- @function read_all
-- @param file to read (STRING)
-- @return contents of file as a new string, nil otherwise (STRING)
local read_all = function (file)
  local str
  local fd = io.open(file)
  if fd then
    local o = io.input()
    io.input(fd)
    str = io.read("*a")
    io.close()
    io.input(o)
    return str
  end
end

return {
  printf = printf,
  fprintf = fprintf,
  errorf = errorf,
  assertf = assertf,
  warn = warn,
  append = append,
  timehm = timehm,
  dateymd = dateymd,
  timestamp = timestamp,
  find_string = find_string,
  arr_to_rec = arr_to_rec,
  ln_to_tbl = ln_to_tbl,
  word_to_tbl = word_to_tbl,
  str_to_tbl = str_to_tbl,
  escape_pattern = escape_pattern,
  filter_tbl_value = filter_tbl_value,
  file_to_tbl = file_to_tbl,
  find_in_tbl = find_in_tbl,
  shallow_cp = shallow_cp,
  split_path = split_path,
  test_open = test_open,
  fopen = fopen,
  fwrite = fwrite,
  getln = getln,
  sub = sub,
  exit_string = exit_string,
  truthy = truthy,
  falsy = falsy,
  popen = popen,
  pwrite = pwrite,
  system = system,
  execute = execute,
  pipeline = pipeline,
  time = time,
  escape_quotes = escape_quotes,
  flog = flog,
  insert_if = insert_if,
  return_if = return_if,
  return_if_not = return_if_not,
  try = try,
  truncate = truncate,
  read_all = read_all
}


text: atom-package-install


text:
using System;
using System.Collections;

namespace NUnit.Framework.Constraints
{
    /// <summary>
    /// AllItemsConstraint applies another constraint to each
    /// item in a collection, succeeding if they all succeed.
    /// </summary>
    public class AllItemsConstraint : PrefixConstraint
    {
        /// <summary>
        /// Construct an AllItemsConstraint on top of an existing constraint
        /// </summary>
        /// <param name="itemConstraint"></param>
        public AllItemsConstraint(IConstraint itemConstraint)
            : base(itemConstraint)
        {
            DescriptionPrefix = "all items";
        }

        /// <summary>
        /// The display name of this Constraint for use by ToString().
        /// The default value is the name of the constraint with
        /// trailing "Constraint" removed. Derived classes may set
        /// this to another name in their constructors.
        /// </summary>
        public override string DisplayName { get { return "All"; } }

        /// <summary>
        /// Apply the item constraint to each item in the collection,
        /// failing if any item fails.
        /// </summary>
        /// <param name="actual"></param>
        /// <returns></returns>
        public override ConstraintResult ApplyTo<TActual>(TActual actual)
        {
            if (!(actual is IEnumerable))
                throw new ArgumentException("The actual value must be an IEnumerable", "actual");

            foreach (object item in (IEnumerable)actual)
                if (!BaseConstraint.ApplyTo(item).IsSuccess)
                    return new ConstraintResult(this, actual, ConstraintStatus.Failure);

            return new ConstraintResult(this, actual, ConstraintStatus.Success);
        }
    }
}


text:
require 'linguist/file_blob'

module Linguist
  # A Repository is an abstraction of a Grit::Repo or a basic file
  # system tree. It holds a list of paths pointing to Blobish objects.
  #
  # Its primary purpose is for gathering language statistics across
  # the entire project.
  class Repository
    # Public: Initialize a new Repository from a File directory
    #
    # base_path - A path String
    #
    # Returns a Repository
    def self.from_directory(base_path)
      new Dir["#{base_path}/**/*"].
        select { |f| File.file?(f) }.
        map { |path| FileBlob.new(path, base_path) }
    end

    # Public: Initialize a new Repository
    #
    # enum - Enumerator that responds to `each` and
    #        yields Blob objects
    #
    # Returns a Repository
    def initialize(enum)
      @enum = enum
      @computed_stats = false
      @language = @size = nil
      @sizes = Hash.new { 0 }
    end

    # Public: Returns a breakdown of language stats.
    #
    # Examples
    #
    #   # => { Language['Ruby'] => 46319,
    #          Language['JavaScript'] => 258 }
    #
    # Returns a Hash of Language keys and Integer size values.
    def languages
      compute_stats
      @sizes
    end

    # Public: Get primary Language of repository.
    #
    # Returns a Language
    def language
      compute_stats
      @language
    end

    # Public: Get the total size of the repository.
    #
    # Returns a byte size Integer
    def size
      compute_stats
      @size
    end

    # Internal: Compute language breakdown for each blob in the Repository.
    #
    # Returns nothing
    def compute_stats
      return if @computed_stats

      @enum.each do |blob|
        # Skip binary file extensions
        next if blob.binary_mime_type?

        # Skip vendored or generated blobs
        next if blob.vendored? || blob.generated? || blob.language.nil?

        # Only include programming languages
        if blob.language.type == :programming
          @sizes[blob.language.group] += blob.size
        end
      end

      # Compute total size
      @size = @sizes.inject(0) { |s,(k,v)| s + v }

      # Get primary language
      if primary = @sizes.max_by { |(_, size)| size }
        @language = primary[0]
      end

      @computed_stats = true

      nil
    end
  end
end


text: Recién estoy empezando con esto del control de versiones, Git y Github. Así que paciencia :)


text:
[![NuGet](https://img.shields.io/nuget/v/Obvs.NetMQ.svg)](https://www.nuget.org/packages/Obvs.NetMQ/)

NetMQ transport support for [Obvs](https://github.com/christopherread/Obvs).

Obvs is a [Reactive Extensions (RX)](https://rx.codeplex.com/) wrapper over many common transport protocols including ZeroMQ, RabbitMQ and ActiveMQ.

This solution is a standalone project that uses the Obvs API with the [ZeroMQ transport protocol](http://zeromq.org/). It uses the [NetMQ](https://github.com/zeromq/netmq) library which provides  native C# support for the [ZeroMQ protocol](http://zeromq.org/).

## Sample code

See the sample projects:
- Publisher: `Obvs.NetMQ.Tests.Console.Publisher`
- Subscriber:  `Obvs.NetMQ.Tests.Console.Subscriber`

There also lots of sample code in the UnitTest projects.

## NuGet Package

[![NuGet](https://img.shields.io/nuget/v/Obvs.NetMQ.svg)](https://www.nuget.org/packages/Obvs.NetMQ/)

See the [NuGet Package Obvs.NetMQ](https://www.nuget.org/packages/Obvs.NetMQ/).


text:
package service;

public enum AccountRangeEntitlementTypeEnum {
	FIRST("61400000", "61409999"),
	SECOND("85155000", "85159999"),
	THIRD("89600000", "89699999"),
	FOURTH("91525000", "91539999");

	private String fromAccount;
	private String toAccount;

	private AccountRangeEntitlementTypeEnum(String fromAccount, String toAccount) {
		this.fromAccount = fromAccount;
		this.toAccount = toAccount;
	}

	public String getFromAccount() {
		return fromAccount;
	}

	public String getToAccount() {
		return toAccount;
	}

}


text:
package com.aucguy.lateore.generate;

import java.util.Random;

import com.aucguy.lateore.util.NBTHelper;

import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraft.world.chunk.Chunk;

public class OreGenerator extends Generator {
	public int veinsPerChunk;
	public int blocksPerVein;
	public int maximumHeight;
	public Block blockToGenerate;
	public int blockMetadata = 0;

	@Override
	public void generate(Chunk chunk, Random random) {
		// thanks to aidancbrady for this code in his mekanism mod
		for(int i = 0; i < this.veinsPerChunk; i++) {
			int randPosX = random.nextInt(16);
			int randPosY = random.nextInt(this.maximumHeight);
			int randPosZ = random.nextInt(16);
			this.generate(chunk.worldObj, random, randPosX, randPosY, randPosZ, chunk);
		}
	}

	public boolean generate(World world, Random rand, int veinX, int veinY, int veinZ, Chunk chunk) {
		float angle = rand.nextFloat() * (float) Math.PI; // the angle the vein will be parrelel to
		// the start and ends determines the 'box' the vein is in
		double startX = veinX + 8 + MathHelper.sin(angle) * this.blocksPerVein / 8.0F;
		double endX = veinX + 8 - MathHelper.sin(angle) * this.blocksPerVein / 8.0F;
		double startZ = ((veinZ + 8) + MathHelper.cos(angle) * this.blocksPerVein / 8.0F);
		double endZ = ((veinZ + 8) - MathHelper.cos(angle) * this.blocksPerVein / 8.0F);
		double startY = (veinY + rand.nextInt(3) - 2); // veinY + randint(-2, 1)
		double endY = (veinY + rand.nextInt(3) - 2); // same as d5, but a different random

		for(int blockCount = 0; blockCount <= this.blocksPerVein; ++blockCount) {
			// blockCount / this.blocksPerVein = completion percentage
			// d0 = start value
			// (d1 - d0) = end - start
			// centerX/Y/Z = the propable place for the ore to go
			double centerX = startX + (endX - startX) * blockCount / this.blocksPerVein;
			double centerY = startY + (endY - startY) * blockCount / this.blocksPerVein;
			double centerZ = startZ + (endZ - startZ) * blockCount / this.blocksPerVein;
			double d9 = rand.nextDouble() * this.blocksPerVein / 16.0D; // some random number
			// the sin is slowly rotating through the vein. I.E the first block is pointing one direction
			// and it eventually goes the other way
			double hypotenuse = (MathHelper.sin(blockCount * (float) Math.PI / this.blocksPerVein) + 1.0F) * d9 + 1.0D;
			double hypotenuse2 = (MathHelper.sin(blockCount * (float) Math.PI / this.blocksPerVein) + 1.0F) * d9 + 1.0D; // same
																															// as
			// d10
			int minX = MathHelper.floor_double(centerX - hypotenuse / 2.0D);
			int minY = Math.max(0, MathHelper.floor_double(centerY - hypotenuse2 / 2.0D));
			int minZ = MathHelper.floor_double(centerZ - hypotenuse / 2.0D);
			int maxX = MathHelper.floor_double(centerX + hypotenuse / 2.0D);
			int maxY = Math.min(255, MathHelper.floor_double(centerY + hypotenuse2 / 2.0D));
			int maxZ = MathHelper.floor_double(centerZ + hypotenuse / 2.0D);

			for(int blockX = minX; blockX <= maxX; ++blockX) {
				double distX = (blockX + 0.5D - centerX) / (hypotenuse / 2.0D);

				if(distX * distX < 1.0D) {
					for(int blockY = minY; blockY <= maxY; ++blockY) {
						double distY = (blockY + 0.5D - centerY) / (hypotenuse2 / 2.0D);

						if(distX * distX + distY * distY < 1.0D) {
							for(int blockZ = minZ; blockZ <= maxZ; ++blockZ) {
								double distZ = (blockZ + 0.5D - centerZ) / (hypotenuse / 2.0D);
								if(distX * distX + distY * distY + distZ * distZ < 1.0D) {
									int realX = blockX & 15;
									int realZ = blockZ & 15;

									if(chunk.getBlock(realX, blockY, realZ).isReplaceableOreGen(world, blockX, blockY,
											blockZ, Blocks.stone)) {
										chunk.func_150807_a(realX, blockY, realZ, this.blockToGenerate,
												this.blockMetadata);
									}
								}
							}
						}
					}
				}
			}
		}

		return true;
	}

	@Override
	public boolean hasBeenApplied(Chunk chunk) {
		return NBTHelper.isBlockInChunk(chunk, this.blockToGenerate);
	}
}


text:
Clash
=====

## Things to Integrate

- Self Doubt
- Credability
    - Persuation
- Believability
- Willingness to Lie
    - Corruption


text:
require('colors');
var chai = require("chai");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
chai.should();

var wd;
try {
  wd = require('wd');
} catch( err ) {
  wd = require('../../lib/main');
}

// enables chai assertion chaining
chaiAsPromised.transferPromiseness = wd.transferPromiseness;

wd.addAsyncMethod(
  'elementByCssSelectorWhenReady',
  function(selector, timeout/*, cb*/) {
    // 'wd.findCallback' is a small helper which looks for the callback in a safe way, and avoids
    // hanging when the number of arguments passed is wrong.
    // There is also a 'wd.varargs' for methods with variable argument number.
    var cb = wd.findCallback(arguments);

    var _this = this;
    this.waitForElementByCssSelector(selector, timeout, function() {
      _this.elementByCssSelector(selector, cb);
    });
  }
);

var browser = wd.promiseChainRemote();

// optional extra logging
browser.on('status', function(info) {
  console.log(info.cyan);
});
browser.on('command', function(eventType, command, response) {
  console.log(' > ' + eventType.cyan, command, (response || '').grey);
});
browser.on('http', function(meth, path, data) {
  console.log(' > ' + meth.magenta, path, (data || '').grey);
});

browser
  .init({browserName:'chrome'})
  .get("http://admc.io/wd/test-pages/guinea-pig.html")
  .title()
  .should.become('WD Tests')
  .elementByCssSelector('#comments').getTagName().should.become('textarea')
  .elementByCssSelectorWhenReady('#comments', 2000)
  //   .should.eventually.exist
  // .elementByCssSelectorWhenReady('#comments', 2000)
  //   .type('Bonjour!').getValue().should.become('Bonjour!')
  .fin(function() { return browser.quit(); })
  .done();


text:
/* sJSON is based on cJSON written by Dave Gamble */

#ifndef sJSON__h
#define sJSON__h

#include <stdint.h>

/* sJSON Types: */
#define sJSON_False 0
#define sJSON_True 1
#define sJSON_NULL 2
#define sJSON_Number 3
#define sJSON_String 4
#define sJSON_Array 5
#define sJSON_Object 6

#define sJSON_IsReference 256

#include "murmurhash.h"

/* The sJSON structure: */
typedef struct sJSON {
   struct sJSON *next,*prev;	/* next/prev allow you to walk array/object chains. Alternatively,
                                 use GetArraySize/GetArrayItem/GetObjectItem */
   struct sJSON *child;       /* An array or object item will have a child pointer pointing to
                                 a chain of the items in the array/object. */
	int type;					/* The type of the item, as above. */

   char *valueString;		/* The item's string, if type==sJSON_String */
   int valueInt;				/* The item's number, if type==sJSON_Number */
   double valueDouble;		/* The item's number, if type==sJSON_Number */

   char *nameString;			/* The item's name string, if this item is the child of, or is
                              in the list of subitems of an object. */
   uint32_t nameHash;
} sJSON;

typedef struct sJSON_Hooks {
      void *(*malloc_fn)(size_t sz);
      void (*free_fn)(void *ptr);
} sJSON_Hooks;

/* Supply malloc, realloc and free functions to sJSON */
extern void sJSONinitHooks(sJSON_Hooks* hooks);

/* Supply a block of JSON, and this returns a sJSON object you can interrogate. Call sJSON_Delete when finished. */
extern sJSON *sJSONparse(const char *value);

/* Render a sJSON entity to text for transfer/storage. Free the char* when finished. */
extern char  *sJSONprint(sJSON *item);
/* Render a sJSON entity to text for transfer/storage without any formatting. Free the char* when finished. */
extern char  *sJSONprintUnformatted(sJSON *item);
/* Delete a sJSON entity and all subentities. */
extern void   sJSONdelete(sJSON *c);

/* Returns the number of items in an array (or object). */
extern uint32_t sJSONgetArraySize(sJSON *array);
/* Retrieve item number "item" from array "array". Returns NULL if unsuccessful. */
extern sJSON *sJSONgetArrayItem(sJSON *array,int item);
/* Get item "string" from object. Case SENSITIVE! */
extern sJSON *sJSONgetObjectItem(sJSON *object, eastl::FixedMurmurHash stringHash);
extern sJSON *sJSONgetObjectItem(sJSON *object, uint32_t stringHash);

/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a
   few chars back to make sense of it. Defined when sJSON_Parse() returns 0. 0 when sJSON_Parse() succeeds. */
extern const char *sJSONgetErrorPtr();

/* These calls create a sJSON item of the appropriate type. */
extern sJSON *sJSONcreateNull();
extern sJSON *sJSONcreateTrue();
extern sJSON *sJSONcreateFalse();
extern sJSON *sJSONcreateBool(int b);
extern sJSON *sJSONcreateNumber(double num);
extern sJSON *sJSONcreateString(const char *string);
extern sJSON *sJSONcreateArray();
extern sJSON *sJSONcreateObject();

/* These utilities create an Array of count items. */
extern sJSON *sJSONcreateIntArray(int *numbers,int count);
extern sJSON *sJSONcreateFloatArray(float *numbers,int count);
extern sJSON *sJSONcreateDoubleArray(double *numbers,int count);
extern sJSON *sJSONcreateStringArray(const char **strings,int count);

/* Append item to the specified array/object. */
extern void sJSONaddItemToArray(sJSON *array, sJSON *item);
extern void	sJSONaddItemToObject(sJSON *object,const char *string,sJSON *item);
/* Append reference to item to the specified array/object. Use this when you want to add an existing #
   sJSON to a new sJSON, but don't want to corrupt your existing sJSON. */
extern void sJSONaddItemReferenceToArray(sJSON *array, sJSON *item);
extern void	sJSONaddItemReferenceToObject(sJSON *object,const char *string,sJSON *item);

/* Remove/Detatch items from Arrays/Objects. */
extern sJSON *sJSONdetachItemFromArray(sJSON *array,int which);
extern void   sJSONdeleteItemFromArray(sJSON *array,int which);
extern sJSON *sJSONdetachItemFromObject(sJSON *object,const char *string);
extern void   sJSONdeleteItemFromObject(sJSON *object,const char *string);

/* Update array items. */
extern void sJSONreplaceItemInArray(sJSON *array,int which,sJSON *newitem);
extern void sJSONreplaceItemInObject(sJSON *object,const char *string,sJSON *newitem);

#define sJSONaddNullToObject(object,name)       sJSONaddItemToObject(object, name, sJSONcreateNull())
#define sJSONaddTrueToObject(object,name)       sJSONaddItemToObject(object, name, sJSONcreateTrue())
#define sJSONaddFalseToObject(object,name)		sJSONaddItemToObject(object, name, sJSONcreateFalse())
#define sJSONaddNumberToObject(object,name,n)	sJSONaddItemToObject(object, name, sJSONcreateNumber(n))
#define sJSONaddStringToObject(object,name,s)	sJSONaddItemToObject(object, name, sJSONcreateString(s))

#endif


text:
class TextureCacheTest : public Layer
{
public:
    TextureCacheTest();
    void addSprite();
    void loadingCallBack(cocos2d::Texture2D *texture);

private:
    cocos2d::Label *_labelLoading;
    cocos2d::Label *_labelPercent;
    int _numberOfSprites;
    int _numberOfLoadedSprites;
};

class TextureCacheTestScene : public TestScene
{
public:
    virtual void runThisTest();
};

#endif // _TEXTURECACHE_TEST_H_


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class LoginForm
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Me.Label1 = New System.Windows.Forms.Label()
        Me.txUsername = New System.Windows.Forms.TextBox()
        Me.txPassword = New System.Windows.Forms.TextBox()
        Me.Label2 = New System.Windows.Forms.Label()
        Me.Button1 = New System.Windows.Forms.Button()
        Me.Button2 = New System.Windows.Forms.Button()
        Me.SuspendLayout()
        '
        'Label1
        '
        Me.Label1.AutoSize = True
        Me.Label1.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label1.Location = New System.Drawing.Point(17, 14)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(110, 25)
        Me.Label1.TabIndex = 0
        Me.Label1.Text = "Username"
        '
        'txUsername
        '
        Me.txUsername.Font = New System.Drawing.Font("Modern No. 20", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txUsername.Location = New System.Drawing.Point(133, 12)
        Me.txUsername.Name = "txUsername"
        Me.txUsername.Size = New System.Drawing.Size(207, 30)
        Me.txUsername.TabIndex = 0
        '
        'txPassword
        '
        Me.txPassword.Font = New System.Drawing.Font("Modern No. 20", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.txPassword.Location = New System.Drawing.Point(133, 60)
        Me.txPassword.Name = "txPassword"
        Me.txPassword.PasswordChar = Global.Microsoft.VisualBasic.ChrW(42)
        Me.txPassword.Size = New System.Drawing.Size(207, 30)
        Me.txPassword.TabIndex = 1
        '
        'Label2
        '
        Me.Label2.AutoSize = True
        Me.Label2.Font = New System.Drawing.Font("Microsoft Sans Serif", 15.75!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Label2.Location = New System.Drawing.Point(17, 62)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(106, 25)
        Me.Label2.TabIndex = 2
        Me.Label2.Text = "Password"
        '
        'Button1
        '
        Me.Button1.Location = New System.Drawing.Point(265, 96)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(75, 23)
        Me.Button1.TabIndex = 4
        Me.Button1.Text = "Exit"
        Me.Button1.UseVisualStyleBackColor = True
        '
        'Button2
        '
        Me.Button2.BackColor = System.Drawing.SystemColors.ButtonHighlight
        Me.Button2.Location = New System.Drawing.Point(7, 131)
        Me.Button2.Name = "Button2"
        Me.Button2.Size = New System.Drawing.Size(116, 23)
        Me.Button2.TabIndex = 5
        Me.Button2.Text = "Server Settings"
        Me.Button2.UseVisualStyleBackColor = False
        '
        'LoginForm
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackColor = System.Drawing.SystemColors.ButtonHighlight
        Me.ClientSize = New System.Drawing.Size(346, 158)
        Me.ControlBox = False
        Me.Controls.Add(Me.Button2)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.txPassword)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.txUsername)
        Me.Controls.Add(Me.Label1)
        Me.Name = "LoginForm"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "Login"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents txUsername As System.Windows.Forms.TextBox
    Friend WithEvents txPassword As System.Windows.Forms.TextBox
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button2 As System.Windows.Forms.Button
End Class


text:
require 'test_helper'

class Admin::ResponsesControllerTest < ActionController::TestCase
  should_be_an_admin_controller

  setup do
    login_as :writer
    @consultation = create(:draft_consultation, opening_at: 2.days.ago, closing_at: 1.day.ago)
  end

  test 'Actions are unavailable if consultation is unmodifiable' do
    edition = create(:published_consultation)

    get :show, consultation_id: edition, type: 'ConsultationOutcome'
    assert_response :redirect
  end

  test 'Access is forbidden to users who do not have access to the consultation' do
    login_as :world_editor
    get :show, consultation_id: @consultation, type: 'ConsultationOutcome'
    assert_response :forbidden
  end

  view_test "GET :show renders a form for outcome when one does not exist" do
    get :show, consultation_id: @consultation, type: 'ConsultationOutcome'

    assert_response :success
    assert_select "textarea[name='consultation_outcome[summary]']"
  end

  view_test "GET :show renders a form for feedback when one does not exist" do
    get :show, consultation_id: @consultation, type: 'ConsultationPublicFeedback'

    assert_response :success
    assert_select "textarea[name='consultation_public_feedback[summary]']"
  end

  view_test "GET :show when consultation has an outcome shows the outcome details and includes an edit link" do
    outcome = create_outcome
    get :show, consultation_id: @consultation, type: 'ConsultationOutcome'

    assert_response :success
    assert_select 'p', text: 'A summary of the outcome'
    assert_select 'a', text: 'Edit outcome'
  end

  view_test "GET :show when consultation has public feedback shows the feedback details and includes an edit link" do
    feedback = create_feedback
    get :show, consultation_id: @consultation, type: 'ConsultationPublicFeedback'

    assert_response :success
    assert_select 'p', text: 'A summary of the public feedback'
    assert_select 'a', text: 'Edit public feedback'
  end

  test "POST :create with valid outcome params saves the outcome and redirects" do
    post :create, consultation_id: @consultation, consultation_outcome: { summary: 'Outcome summary', published_on: Date.today }, type: 'ConsultationOutcome'

    assert_response :redirect
    assert outcome = @consultation.outcome
    assert_equal 'Outcome summary', outcome.summary
  end

  test "POST :create with valid feedback params saves the feedback and redirects" do
    post :create, consultation_id: @consultation, consultation_public_feedback: { summary: 'Feedback summary', published_on: Date.today }, type: 'ConsultationPublicFeedback'

    assert_response :redirect
    assert public_feedback = @consultation.public_feedback
    assert_equal 'Feedback summary', public_feedback.summary
  end

  view_test "POST :create with invalid params re-renders the form" do
    post :create, consultation_id: @consultation, consultation_outcome: { summary: '', published_on: Date.today }, type: 'ConsultationOutcome'

    assert_response :success
    assert_select "textarea[name='consultation_outcome[summary]']"
  end

  view_test "GET :edit renders the edit form for an outcome" do
    outcome = create_outcome
    get :edit, consultation_id: @consultation, type: 'ConsultationOutcome'
    assert_select "textarea[name='consultation_outcome[summary]']", text: outcome.summary
  end

  view_test "GET :edit renders the edit form for public feedback" do
    feedback = create_feedback
    get :edit, consultation_id: @consultation, type: 'ConsultationPublicFeedback'
    assert_select "textarea[name='consultation_public_feedback[summary]']", text: feedback.summary
  end

  test "PUT :update with valid outcome params saves the changes to the outcome" do
    outcome = create_outcome
    put :update, consultation_id: @consultation, consultation_outcome: { summary: 'New summary', published_on: Date.today }, type: 'ConsultationOutcome'
    assert_response :redirect
    assert_equal 'New summary', outcome.reload.summary
  end

  test "PUT :update with valid feedback params saves the changes to the feedback" do
    feedback = create_feedback
    put :update, consultation_id: @consultation, consultation_public_feedback: { summary: 'New summary', published_on: Date.today }, type: 'ConsultationPublicFeedback'
    assert_response :redirect
    assert_equal 'New summary', feedback.reload.summary
  end

  private

  def create_outcome
    create(:consultation_outcome, summary: 'A summary of the outcome', consultation: @consultation)
  end

  def create_feedback
    create(:consultation_public_feedback, summary: 'A summary of the public feedback', consultation: @consultation)
  end
end


text:
#include "staticruleaiplayer.h"
#include "../player/rules/greedyrule.h"
#include "../player/rules/openingrule.h"
#include "../player/rules/endgamerule.h"
#include "../player/rules/cornerrule.h"
#include "../player/rules/minimiseopponentmovementrule.h"
#include "../player/rules/maximiseownmovementrule.h"
#include "../player/rules/fewerfrontierdiscsrule.h"
#include <QDebug>

StaticRuleAIPlayer::StaticRuleAIPlayer(QObject *parent) :
    Player(parent)
{
    _rulelist.append(new CornerRule(this));
    _rulelist.append(new OpeningRule(this));
    _rulelist.append(new EndgameRule(this));
    _rulelist.append(new MinimiseOpponentMovementRule(this));
    _rulelist.append(new MaximiseOwnMovementRule(this));
    _rulelist.append(new FewerFrontierDiscsRule(this));

    QList<Rule *> ::const_iterator iterator;
    for(iterator=_rulelist.begin(); iterator != _rulelist.end();++iterator)
    {
        QObject::connect((*iterator),SIGNAL(turn(int,int)),this,SLOT(getTurn(int,int)));
    }
}

StaticRuleAIPlayer::~StaticRuleAIPlayer()
{
    QList<Rule *> ::const_iterator iterator;
    for(iterator=_rulelist.begin(); iterator != _rulelist.end();++iterator)
    {
        delete (*iterator);
    }
}

bool StaticRuleAIPlayer::isHuman()
{
    return false;
}

void StaticRuleAIPlayer::doTurn(Gameboard board, int player)
{
    QList<Rule *> ::const_iterator iterator;
    for(iterator=_rulelist.begin(); iterator != _rulelist.end();++iterator)
    {
        if((*iterator)->applicable(board,player))
        {
            emit sendMessage(QString(tr("Now using rule \"%1\"")).arg((*iterator)->name()));
            (*iterator)->doTurn(board,player);
            return;
        }
    }

    // If everything fails do a greedy rule
    qWarning() << "ERROR: Did not find any rule, using default \"Greedy Rule\"";
    GreedyRule rule;
    if(!rule.applicable(board,player))
    {
        emit sendMessage(tr("Static Rule AI hasn't any rules to apply..."));
        qCritical() << "CRITICAL ERROR in " __FILE__ << " " << __LINE__ << ": Static Rule AI has no rule to apply";
        return;
    }
    QObject::connect(&rule,SIGNAL(turn(int,int)),this,SLOT(getTurn(int,int)));
    emit sendMessage(tr("Using fallback \"Greedy Rule\""));
    rule.doTurn(board,player);
    QObject::disconnect(&rule,SIGNAL(turn(int,int)),this,SLOT(getTurn(int,int)));
}

void StaticRuleAIPlayer::humanInput(int x, int y)
{
}

void StaticRuleAIPlayer::getTurn(int x, int y)
{
    emit turn(x,y);
}


text:
iPhone 6/6s

            <button type="button" class=" resultsRefine btn btn-default " ng-click="openFilterModal()">Refine</button>

 Item added to cart successfully !

Price :
                    ${{items.CoreProperties.ExtendedPrice}}

                {{items.FeatureOptions[0].DisplayName}}

{{items.DisplayName}}

                        <button class="form-button orange primary "
                                style="height: 40px !important;background-color: #06bef0;" ng-click="display()">

                    Add to Cart

                        </button>

                        <button class="wide-button" style="height: 40px !important;color:#661121" disabled="true">

                    Out Of Stock

                        </button>

Back to Top


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace Store.Models
{
    public class Order
    {
        [Key]
        public int Id { get; set; }

        [Required]
        public DateTime Date { get; set; }

        [Required]
        public int CustomerId { get; set; }

        [Required]
        public int Product_Id { get; set; }
    }
}


text:
using System;
using System.Linq;
using System.Data.Entity;
using Cluster.Accounts.Impl;
using Cluster.Accounts.Api;
using NakedObjects;
using NakedObjects.Core.Context;

namespace Cluster.Accounts.Test
{
    public class AccountsFixture
    {
        #region Injected Services
        public IDomainObjectContainer Container { set; protected get; }

        public AccountsService AccountsService { set; protected get; }

        public CustomerAccountsService CustomerAccountsService { set; protected get; }

        public Cluster.System.Api.IClock Clock { set; protected get; }
        #endregion

        public void Install()
        {
            TestAccounts();
            TestPeriods();

            AllMockAccountHoldersAndTheirAccounts();
            AllMockSalesItems();
            AllMockPayments();
            //DemoAccounts();

            TestTransactions();

        }

        private static Account Receivables;
        private static Account Bank;
        private static Account Sales;

        public void DemoAccounts()
        {
            Receivables = NewAccount("REC", "Receivables", AccountTypes.Asset);
            Bank = NewAccount("BANK", "Bank", AccountTypes.Asset);
            Sales = NewAccount("SALES", "Sales", AccountTypes.Income);
            NewAccount("SAL", "Salaries", AccountTypes.Expense);

        }

        private Account NewAccount(string code, string name, AccountTypes type, string currency = "USD", DateTime? date = null)
        {
            DateTime startDate = date != null ? date.Value : Clock.Today().AddYears(-1);
            return AccountsService.CreateNewAccount(code, name, type, currency, new decimal(0), startDate);
        }

        public void DemoPeriods()
        {
            AccountsService.NewPeriod("Jun 13", new DateTime(2013, 6, 1), new DateTime(2013, 6, 30));
            AccountsService.NewPeriod("Jul 13", new DateTime(2013, 7, 1), new DateTime(2013, 7, 31));
            AccountsService.NewPeriod("Aug 13", new DateTime(2013, 8, 1), new DateTime(2013, 8, 31));
            AccountsService.NewPeriod("Sep 13", new DateTime(2013, 9, 1), new DateTime(2013, 9, 30));
            AccountsService.NewPeriod("Oct 13", new DateTime(2013, 10, 1), new DateTime(2013, 10, 31));
        }

        public void DemoTransactions()
        {
            AccountsService.PostTransaction(new DateTime(2013, 6, 4), "Service  - Regsitration", "USD", 150, Receivables, Sales);
            AccountsService.PostTransaction(new DateTime(2013, 6, 5), "Service  - Regsitration", "USD", 250, Receivables, Sales);
            AccountsService.PostTransaction(new DateTime(2013, 6, 7), "Service  - Regsitration", "USD", 600, Receivables, Sales);

            AccountsService.PostTransaction(new DateTime(2013, 6, 10), "Cheque Payment", "USD", 200, Bank, Receivables);
            AccountsService.PostTransaction(new DateTime(2013, 6, 11), "Cash Payment", "USD", 100, Bank, Receivables);

            AccountsService.PostTransaction(new DateTime(2013, 6, 11), "Cash Payment", "USD", 100, Bank, Receivables);
        }
        public void TestAccounts()
        {
            NewAccount("F1", "Foo 1", AccountTypes.Income);
            NewAccount("F2", "Foo 2", AccountTypes.Income);
            NewAccount("A1", "Account 1", AccountTypes.Income);
            NewAccount("A2", "Account 2", AccountTypes.Income);
            NewAccount("A3", "Account 3", AccountTypes.Income);
            NewAccount("A4", "Account 4", AccountTypes.Income);
            NewAccount("A5", "Account 5", AccountTypes.Income);
            NewAccount("A6", "Account 6", AccountTypes.Income);
            NewAccount("A7", "Account 7", AccountTypes.Income, "EUR");

            DateTime yearOld = Clock.Today().AddYears(-1);
            Receivables = NewAccount("REC", "Receivables", AccountTypes.Asset, "USD", yearOld);
            Bank = NewAccount("BANK", "Bank", AccountTypes.Asset, "USD", yearOld);
            Sales = NewAccount("SALES", "Sales", AccountTypes.Income, "USD", yearOld);
        }

        public void TestTransactions()
        {
            //For Matching tests
            AccountsService.PostTransaction(new DateTime(1999, 12, 11), "Invoice1", "USD", 100, Receivables, Sales);
            AccountsService.PostTransaction(new DateTime(1999, 12, 2), "Invoice1", "USD", 90, Receivables, Sales);
            AccountsService.PostTransaction(new DateTime(1999, 12, 2), "Payment1", "USD", 80, Bank, Receivables);
            AccountsService.PostTransaction(new DateTime(1999, 12, 2), "Payment2", "USD", 30, Receivables, Sales);
            AccountsService.PostTransaction(new DateTime(1999, 12, 2), "Payment3", "USD", 60, Receivables, Sales);
        }

        public void TestPeriods()
        {
            AccountsService.NewPeriod("Nov 99", new DateTime(1999, 11, 1), new DateTime(1999, 11, 30), true);
            AccountsService.NewPeriod("Dec 99", new DateTime(1999, 12, 1), new DateTime(1999, 12, 31));
            AccountsService.NewPeriod("Jan 00", new DateTime(2000, 1, 1), new DateTime(2000, 1, 31));
            AccountsService.NewPeriod("Feb 00", new DateTime(2000, 2, 1), new DateTime(2000, 2, 28));
            AccountsService.NewPeriod("Mar 00", new DateTime(2000, 3, 1), new DateTime(2000, 3, 31));
            AccountsService.NewPeriod("Apr 00", new DateTime(2000, 4, 1), new DateTime(2000, 4, 30));
        }

        public  void AllMockAccountHoldersAndTheirAccounts()
        {
            var mock1 = NewMockAccountHolder( "Mock1");
            var mock2 = NewMockAccountHolder( "Mock2");
            NewMockAccountHolder( "Mock3");
            NewMockAccountHolder( "Mock4");

            NakedObjectsContext.ObjectPersistor.EndTransaction();
            NakedObjectsContext.ObjectPersistor.StartTransaction();

            CustomerAccountsService.CreateNewAccount(mock1, "USD", new decimal(0), Clock.Today(), null);
            CustomerAccountsService.CreateNewAccount(mock2, "USD", new decimal(0), Clock.Today(), null);
        }

        public  MockAccountHolder NewMockAccountHolder(string name)
        {
            var mah = Container.NewTransientInstance<MockAccountHolder>();
            mah.Name = name;
            Container.Persist(ref mah);
            return mah;
        }

          public void AllMockSalesItems()
        {
            NewMockSalesItem( new decimal(1.00), "Item1", "AB001");
            NewMockSalesItem( new decimal(2.00), "Item2");
            NewMockSalesItem( new decimal(3.00), "Item3");

            NewMockSalesItem( new decimal(4.00), "Item4");
            NewMockSalesItem( new decimal(5.00), "Item5");
        }

        public  MockSalesItem NewMockSalesItem(
            decimal amount,
            string description,
            string analysisCodes = null)
        {
            var mci = Container.NewTransientInstance<MockSalesItem>();

                // CurrencyCode = currencyCode,
                mci.Amount = amount;
                mci.Description = description;
                mci.Description = description;
                mci.AnalysisCodes = analysisCodes;
                Container.Persist(ref mci);
            return mci;
        }

        public  void AllMockPayments()
        {
            NewMockPayment(new decimal(10), "Payment1");
            NewMockPayment( new decimal(20), "Payment2");
        }

        public  MockPayment NewMockPayment(
            decimal amount,
            string description,
            string analysisCodes = null
            )
        {
            var pay = Container.NewTransientInstance<MockPayment>();

                // CurrencyCode = currencyCode,
                pay.Amount = amount;
                pay.Description = description;
                pay.AnalysisCodes = analysisCodes;
                Container.Persist(ref pay);
            return pay;
        }
    }
}


text:
var http = require('http');
var twitter = exports.twitter = require('./twitter').twitter;

twitter.fetchUrl = function(url, callback) {
	var host = url.match(/^https?:\/\/search\.twitter\.com/) ? 'search.twitter.com' : 'twitter.com';
	var connection = http.createClient(80, host);
	var params = { host: host, 'User-Agent': 'twitter.js node client' };
	var request = connection.get(url, params).finish(function(response) {
		var responseBody = '';
		response.setBodyEncoding('utf8');
		response.addListener('body', function(chunk) { responseBody += chunk});
        response.addListener('complete', function() {
			callback(JSON.parse(responseBody));
		})
	})
}

// twitter.getMentions('marcuswestin', function(response) {
// 	var tweets = response.results;
// 	var tweet = tweets[0];
// 	sys.puts(tweet.text);
// })


text:
require "spec_helper"
require "hiera/version"
require 'pathname'

describe "Hiera.version Public API" do
  subject() { Hiera }

  before :each do
    Hiera.instance_eval do
      if @hiera_version
        @hiera_version = nil
      end
    end
  end

  context "without a VERSION file" do
    before :each do
      subject.stubs(:read_version_file).returns(nil)
    end

    it "is Hiera::VERSION" do
      subject.version.should == Hiera::VERSION
    end
    it "respects the version= setter" do
      subject.version = '1.2.3'
      subject.version.should == '1.2.3'
    end
  end

  context "with a VERSION file" do
    it "is the content of the file" do
      subject.expects(:read_version_file).with() do |path|
        pathname = Pathname.new(path)
        pathname.basename.to_s == "VERSION"
      end.returns('1.2.1-9-g9fda440')

      subject.version.should == '1.2.1-9-g9fda440'
    end
    it "respects the version= setter" do
      subject.version = '1.2.3'
      subject.version.should == '1.2.3'
    end
  end
end


text:
FamilyFinances
==============

Family finances


text:
#ifndef __UM_NET_KERN_H
#define __UM_NET_KERN_H

#include <linux/netdevice.h>
#include <linux/platform_device.h>
#include <linux/skbuff.h>
#include <linux/socket.h>
#include <linux/list.h>
#include <linux/workqueue.h>

struct uml_net {
	struct list_head list;
	struct net_device *dev;
	struct platform_device pdev;
	int index;
	unsigned char mac[ETH_ALEN];
};

struct uml_net_private {
	struct list_head list;
	spinlock_t lock;
	struct net_device *dev;
	struct timer_list tl;
	struct net_device_stats stats;
	struct work_struct work;
	int fd;
	unsigned char mac[ETH_ALEN];
	unsigned short (*protocol)(struct sk_buff *);
	int (*open)(void *);
	void (*close)(int, void *);
	void (*remove)(void *);
	int (*read)(int, struct sk_buff **skb, struct uml_net_private *);
	int (*write)(int, struct sk_buff **skb, struct uml_net_private *);

	void (*add_address)(unsigned char *, unsigned char *, void *);
	void (*delete_address)(unsigned char *, unsigned char *, void *);
	int (*set_mtu)(int mtu, void *);
	int user[1];
};

struct net_kern_info {
	void (*init)(struct net_device *, void *);
	unsigned short (*protocol)(struct sk_buff *);
	int (*read)(int, struct sk_buff **skb, struct uml_net_private *);
	int (*write)(int, struct sk_buff **skb, struct uml_net_private *);
};

struct transport {
	struct list_head list;
	const char *name;
	int (* const setup)(char *, char **, void *);
	const struct net_user_info *user;
	const struct net_kern_info *kern;
	const int private_size;
	const int setup_size;
};

extern struct net_device *ether_init(int);
extern unsigned short ether_protocol(struct sk_buff *);
extern struct sk_buff *ether_adjust_skb(struct sk_buff *skb, int extra);
extern int tap_setup_common(char *str, char *type, char **dev_name,
			    char **mac_out, char **gate_addr);
extern void register_transport(struct transport *new);
extern unsigned short eth_protocol(struct sk_buff *skb);

#endif


text:
layout: page
title: Duncan Summit Limited Show
date: 2016-05-24
author: Tyler Higgins
tags: weekly links, java
status: published
summary: Suspendisse eget nunc odio. Proin.
banner: images/banner/wedding.jpg
booking:
  startDate: 03/09/2018
  endDate: 03/14/2018
  ctyhocn: PAHMYHX
  groupCode: DSLS
published: true
---
Aliquam non volutpat lorem. Maecenas ultricies dignissim hendrerit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur et massa dictum, posuere neque ut, mollis erat. Cras rutrum eleifend ipsum, eget luctus augue luctus eu. Sed non auctor erat. Curabitur ex felis, gravida mollis enim tristique, tempus gravida ligula. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut sed ante vitae orci vulputate tincidunt volutpat vitae metus. Vestibulum pellentesque dolor lacus, non lacinia velit hendrerit ut. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Suspendisse potenti. Donec lectus risus, faucibus eget arcu eget, tristique finibus lacus. Suspendisse cursus diam a euismod accumsan. Pellentesque aliquam tellus sed ex sollicitudin eleifend.
Donec imperdiet leo et iaculis faucibus. Sed eget mi gravida justo semper mollis. Praesent sit amet sagittis magna. Cras vel venenatis lorem, at aliquam leo. Morbi ac imperdiet odio. Phasellus tempus augue sapien, in tincidunt elit luctus at. Vestibulum id lorem ac est gravida elementum. Suspendisse leo massa, suscipit ut lacinia a, maximus id orci. Nullam id ex ut felis semper cursus. Fusce luctus vitae magna eu tincidunt.

* Praesent rhoncus magna non elit pharetra, sit amet tempus diam porta
* Duis eget sapien sed turpis sollicitudin eleifend
* Sed feugiat nisl non diam condimentum eleifend nec vel magna
* Pellentesque suscipit sem id accumsan condimentum
* Curabitur et libero nec erat faucibus fringilla nec in nisl.

Nunc eleifend, dolor sit amet tincidunt cursus, ligula nibh pretium risus, sit amet pharetra dui elit eu eros. Praesent urna risus, convallis eget pretium vel, ultricies vitae odio. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur felis mi, consectetur ut pretium ut, condimentum in justo. Etiam quis urna sodales, feugiat ligula sed, consectetur nisi. Praesent sed iaculis magna. Quisque ornare mollis placerat. Aenean efficitur posuere ante, nec porta mauris vulputate vel.


text:
class Employee:
	def __init__(self, name, salary=0):
		self.name = name
		self.salary = salary
	def giveRaise(self, percent):
		self.salary = self.salary + (self.salary * percent)
	def work(self):
		print(self.name, "does stuff")
	def __repr__(self):
		return "<Employee: name=%s, salary=%s>" % (self.name, self.salary)

class Chef(Employee):
	def __init__(self, name):
		Employee.__init__(self, name, 50000)
	def work(self):
		print(self.name, "makes food")

class Server(Employee):
	def __init__(self, name):
		Employee.__init__(self, name, 40000)
	def work(self):
		print(self.name, "interfaces with customer")

class PizzaRobot(Chef):
	def __init__(self, name):
		Chef.__init__(self, name)
	def work(self):
		print(self.name, "makes pizza")

if __name__ == "__main__":
	bob = PizzaRobot('bob')	# Создать робота с именем bob
	print(bob)				# Вызвать унаследованный метод __repr__
	bob.work()				# Выполнить действие, зависящее от типа
	bob.giveRaise(0.20)		# Увеличить роботу зарплату на 20%
	print(bob); print()

	for klass in Employee, Chef, Server, PizzaRobot:
		obj = klass(klass.__name__)
		obj.work()


text:
<?php

namespace Topxia\Api\Resource\Course;

use Silex\Application;
use Topxia\Api\Resource\BaseResource;
use Symfony\Component\HttpFoundation\Request;

class Member extends BaseResource
{

    public function filter($res)
    {
        unset($res['userId']);
        $res['user'] = $this->callSimplify('User', $res['user']);
        $res['course'] = $this->callSimplify('Course', $res['course']);
        $res['noteLastUpdateTime'] = date('c', $res['noteLastUpdateTime']);
        $res['createdTime'] = date('c', $res['createdTime']);
        return $res;
    }
}


text:
title: "Best Practice For Producer"
permalink: /docs/best-practice-producer/
modified: 2016-12-24T15:01:43-04:00
---

Some useful tips for users.

{% include toc %}

## SendStatus
When sending a message, you will get SendResult and it will contain the SendStatus. Firstly, we assume that Message's isWaitStoreMsgOK=true(default is true). If not, we will always get SEND_OK if no exception is thrown.
Follow are the descriptions about each status.
### FLUSH_DISK_TIMEOUT
If the Broker set MessageStoreConfig's FlushDiskType=SYNC_FLUSH(default is ASYNC_FLUSH), and the Broker dose not finish flushing disk within MessageStoreConfig's syncFlushTimeout(default is 5 secs), you will get such status.
### FLUSH_SLAVE_TIMEOUT
If the Broker's role is SYNC_MASTER(default is ASYNC_MASTER), and the slave Broker dose not finish synchronizing with the master within the MessageStoreConfig's syncFlushTimeout(default is 5 secs), you will get such status.
### SLAVE_NOT_AVAILABLE
If the Broker's role is SYNC_MASTER(default is ASYNC_MASTER), but no slave Broker is configured, you will get such status.
### SEND_OK
You should be aware that SEND_OK does not mean it is reliable. If you cannot tolerate message missing, you should also enable SYNC_MASTER or SYNC_FLUSH.
### Duplication or Missing
If you get FLUSH_DISK_TIMEOUT, FLUSH_SLAVE_TIMEOUT and the Broker happens to shutdown right the moment, you may get your message missing.
At this time, you have two choices, one is letting it go, which may get message missing; another is resending, which may get message duplication.
Often we suggest resend and make a way to handle the duplication removal when consuming. Unless you feel it does not matter when some messages are missed.
But be ware that resending has no use when you get SLAVE_NOT_AVAILABLE, you'd better keep the scene and send some alerts to the Cluster Manager.
## Timeout
The Client send requests to Broker, and wait the responses, but if the max wait time is elapsed and no response is return, the Client will throw a RemotingTimeoutException.
The default wait time is 3 seconds.You can also pass timeout argument using send(msg, timeout) instead of send(msg).
Note that we do not suggest the value to be too small, for the Broker need some time to flush disk or synchronize with slave. Also the value may have little effect if it is too bigger than syncFlushTimeout for Broker may return a response with FLUSH_SLAVE_TIMEOUT or FLUSH_SLAVE_TIMEOUT before the timeout.
## Message Size
We suggest the message should be no more than 512K.
## Async Sending
Default send(msg) will block until the response is return. So if you care about performance, we suggest you use send(msg, callback) which will act in a async way.
## Producer Group
Normally, the producer group has no effects. But if you are involved in  transaction, you should pay attention to it.
In default, you can only create only one producer with the same producer group in the same JVM. Usually, this is enough.
## Thread Safety
The producer is thread-safe, you can just use it in your business logic.
## Performance
If you want more than one producer in one JVM, maybe for big data processing, we suggest you:
* use async sending with a few producers(3~5 is enough)
* setInstanceName for each producer


text:
(function() {
    function linkCodeBlocks(linkable=true) {
        codeworldKeywords = {};
        registerStandardHints( function(){
        var pres = document.getElementsByTagName('pre');
            for (var i = 0; i < pres.length; ++i) {
                (function() {
                    var pre = pres[i];
                    var text = pre.textContent;
                    pre.innerHTML = '';
                    CodeMirror.runMode(text, { name: 'codeworld', overrideKeywords: codeworldKeywords }, pre);
                    pre.classList.add('cm-s-default');

                    if (text.indexOf("main ") != -1 && linkable) {
                        pre.classList.add('clickable');
                        pre.onclick = function() {
                            if (parent && parent.loadSample) {
                                parent.loadSample(text);
                            }
                        }
                    }
                })();
            }
        });
    }

    function linkFunBlocks() {
        var pres = document.getElementsByTagName('xml');
        var i = 0;

        while(pres != null && pres.length > 0){
          (function() {
          var pre = pres[0];

          var text = pre.outerHTML;

          pre.outerHTML = '<iframe frameborder="0" scrolling="no" id="frame' + i + '"></iframe>';

          var myIframe = document.getElementById('frame' + i);
          var thisDocument = document;
          myIframe.addEventListener("load", function() {
              this.contentWindow.setParent(parent);
              this.contentWindow.setId(myIframe);
              this.contentWindow.loadXml.call(myIframe.contentWindow,text);
          });

          myIframe.src = 'help/blockframe.html';
          myIframe.classList.add('clickable');

          pres = document.getElementsByTagName('xml');
          i++;
          })();
        }
    }

    function addTableOfContents() {
        var contents = document.createElement('div');
        contents.id = 'helpcontents';
        contents.classList.add('contents');

        var elems = document.getElementsByTagName('*');

        var currentLevel = 0;
        var currentElem = contents;
        var n = 0;
        for (var i = 0; i < elems.length; ++i) {
            var header = elems[i];
            var match = (/h([1-3])/i).exec(header.tagName);
            if (match == null) continue;
            var level = parseInt(match[1]);

            while (currentLevel < level) {
                var sub = document.createElement('ul');
                currentElem.appendChild(sub);
                ++currentLevel;
                currentElem = sub;
            }

            while (currentLevel > level) {
                currentElem = currentElem.parentNode;
                --currentLevel;
            }

            ++n;

            var anchor = document.createElement('a');
            anchor.setAttribute('name', n);
            anchor.innerHTML = header.innerHTML;
            header.innerHTML = '';
            header.appendChild(anchor);

            var li = document.createElement('li');
            var link = document.createElement('a');
            link.setAttribute('href', '#' + n);
            link.textContent = header.textContent;
            li.appendChild(link);
            currentElem.appendChild(li);
        }
        if (contents.childNodes.length > 0) {
            document.body.insertBefore(contents, document.body.firstChild);
        }
    }
    var path = window.location.search.slice(1);
    var request = new XMLHttpRequest();
    request.open('GET', path, true);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {

          var text = request.responseText;
          var converter = new Markdown.Converter();
          var html = converter.makeHtml(text);
          document.getElementById('help').innerHTML = html;

          if(path.includes('blocks')){
            linkFunBlocks();
            linkCodeBlocks(false);
          }
          else{
            linkCodeBlocks();
          }

          addTableOfContents();
        }
    };
    request.send(null);
})();


text:
<!doctype html>

    <meta charset="utf-8">
    <title>Two Segment Reach</title>
    <link rel="stylesheet" href="../include/style.css">

    <canvas id="canvas" width="400" height="400"></canvas>
    Move mouse on canvas element.

      Return to Animation Menu


text:
无搜索内容

返回上一页