text:
Connect | Code | Career

![Nigma.io](https://image.ibb.co/hwQFo6/nigmaio.png)

## Who are we?
A developer community for students studying computing related courses, entry level developers wanting to broaden their horizons and senior developers that want to help others that were once in the position they were in. Nigma was created through the frustration of one Computer Science student that had always wanted to learn, but didn't know exactly what to learn.

## What is our aim?
The main aim of Nigma is to try and bridge this gap between what software development students learn in education and what is being demanded in the workplace. With NI employers in high demand for top developers, we want to help empower students to help them reach their full potential through keeping them up to date on the latest technology stacks, tech meetups and career prospects. Our target audience is for senior students and graduates that are, either about to, or have just entered NI's software development industry.

> Check out our Official Website : http://nigma.io

> Join our [facebook community group](https://www.facebook.com/groups/nigmaio).

> Also take a look at our latest [Nigma Meetups](https://www.meetup.com/nigmaio/)

## Getting Setup

* [First time Git setup](https://git-scm.com/book/en/v2/Getting-Started-First-Time-Git-Setup)
* [Getting help](https://git-scm.com/book/en/v2/Getting-Started-Getting-Help)
* [Getting a repository](https://git-scm.com/book/en/v2/Git-Basics-Getting-a-Git-Repository)
* [Record changes to the repository](https://git-scm.com/book/en/v2/Git-Basics-Recording-Changes-to-the-Repository)
  * Tracking new files
  * Staging modified files
  * Ignoring files
  * Viewing staged and unstaged changes
  * Committing your changes
  * Removing files
  * Moving files
* [View commit history](https://git-scm.com/book/en/v2/Git-Basics-Viewing-the-Commit-History)
* [Undoing things](https://git-scm.com/book/en/v2/Git-Basics-Undoing-Things)

## Contributing to open source in general
- [Up For Grabs](http://up-for-grabs.net/#/) - a list of projects with beginner-friendly issues.
- [Issuehub.io](http://issuehub.io/) - a tool for searching GitHub issues by label and language.
- [Code Triage](https://www.codetriage.com/) - another, really nice, tool for finding popular repositories and issues filtered by language.
- [First Timers Only](http://www.firsttimersonly.com/) - a list of bugs that are labelled "first-timers-only".
- [YourFirstPR](https://twitter.com/yourfirstpr) - starter issues on GitHub that can be easily tackled by new contributors.
- [Awesome-for-beginners](https://github.com/MunGell/awesome-for-beginners) - a GitHub repo that amasses projects with good bugs for new contributors, and applies labels to describe them.
- [Openhatch](https://openhatch.org/) - a non-profit organization that helps lower barriers of entry into open source. You can find bugs and projects here, as well.
- [Open Source Guides](https://opensource.guide/) - Collection of resources for individuals, communities, and companies who want to learn how to run and contribute to an open source project.
- [45 Github Issues Dos and Don'ts](https://hackernoon.com/45-github-issues-dos-and-donts-dfec9ab4b612)- Do's and Don'ts on GitHub.
- [GitHub Guides](https://guides.github.com/) - basic guides on how to use GitHub effectively.
- [First Contributions](https://roshanjossey.github.io/first-contributions) - Make your first open source contribution in 5 minutes. A tool and tutorial to help beginners get started with contributions.

## Contributing workflow

Here's how we suggest you go about proposing a change to this project:

1. [Fork this project][fork] to your account.
2. [Create a branch][branch] for the change you intend to make.
3. Make your changes to your fork.
4. [Send a pull request][pr] from your fork's branch to our `master` branch.

Using the web-based interface to make changes is fine too, and will help you
by automatically forking the project and prompting to send a pull request too.

[fork]: https://help.github.com/articles/fork-a-repo/
[branch]: https://help.github.com/articles/creating-and-deleting-branches-within-your-repository
[pr]: https://help.github.com/articles/using-pull-requests/


text:
module RedminePluginSupport
  class StatsTask < GeneralTask

    STATS_DIRECTORIES = [
                         %w(Controllers        app/controllers),
                         %w(Helpers            app/helpers),
                         %w(Models             app/models),
                         %w(Libraries          lib/),
                         %w(APIs               app/apis),
                         %w(Integration\ tests test/integration),
                         %w(Functional\ tests  test/functional),
                         %w(Unit\ tests        test/unit)
                        ]

    def stats_directories
      STATS_DIRECTORIES.collect { |name, dir| [ name, "#{RedmineHelper.plugin_root}/#{dir}" ] }.select { |name, dir| File.directory?(dir) }
    end

    def define
      # TODO: Need to get rspec stats to work

      namespace :spec do
        task :statsetup do
          require 'code_statistics'
          STATS_DIRECTORIES << %w(Model\ specs spec/models) if File.exist?("#{RedmineHelper.plugin_root}/spec/models")
          STATS_DIRECTORIES << %w(View\ specs spec/views) if File.exist?("#{RedmineHelper.plugin_root}/spec/views")
          STATS_DIRECTORIES << %w(Controller\ specs spec/controllers) if File.exist?("#{RedmineHelper.plugin_root}/spec/controllers")
          STATS_DIRECTORIES << %w(Helper\ specs spec/helpers) if File.exist?("#{RedmineHelper.plugin_root}/spec/helpers")
          STATS_DIRECTORIES << %w(Library\ specs spec/lib) if File.exist?("#{RedmineHelper.plugin_root}/spec/lib")
          STATS_DIRECTORIES << %w(Routing\ specs spec/routing) if File.exist?("#{RedmineHelper.plugin_root}/spec/routing")
          STATS_DIRECTORIES << %w(Integration\ specs spec/integration) if File.exist?("#{RedmineHelper.plugin_root}/spec/integration")
          ::CodeStatistics::TEST_TYPES << "Model specs" if File.exist?("#{RedmineHelper.plugin_root}/spec/models")
          ::CodeStatistics::TEST_TYPES << "View specs" if File.exist?("#{RedmineHelper.plugin_root}/spec/views")
          ::CodeStatistics::TEST_TYPES << "Controller specs" if File.exist?("#{RedmineHelper.plugin_root}/spec/controllers")
          ::CodeStatistics::TEST_TYPES << "Helper specs" if File.exist?("#{RedmineHelper.plugin_root}/spec/helpers")
          ::CodeStatistics::TEST_TYPES << "Library specs" if File.exist?("#{RedmineHelper.plugin_root}/spec/lib")
          ::CodeStatistics::TEST_TYPES << "Routing specs" if File.exist?("#{RedmineHelper.plugin_root}/spec/routing")
          ::CodeStatistics::TEST_TYPES << "Integration specs" if File.exist?("#{RedmineHelper.plugin_root}/spec/integration")
        end
      end

      desc "Report code statistics (KLOCs, etc) from the application"
      task :stats do
        require 'code_statistics'
        CodeStatistics.new(*stats_directories).to_s
      end

      self
    end

  end
end

redpajama_set_name: RedPajamaGithub


text:
package goga

import (
	"log"
)

var (
	scenes      []Scene
	activeScene Scene
)

// A scene used to switch between game states.
// The Cleanup() method is called when a scene is removed
// or the program is stopped. It can be used to cleanup open resources
// (like GL objects).
// On switch, Pause() and Resume() are called.
// The name returned by GetName() must be unique. A scene must only be
// registered once.
type Scene interface {
	Pause()
	Resume()
	Cleanup()
	Resize(int, int)
	GetName() string
}

// Adds a scene to game.
// Returns false if the scene exists already.
// The first scene added will be set active.
func AddScene(scene Scene) bool {
	for _, s := range scenes {
		if s == scene {
			return false
		}
	}

	scenes = append(scenes, scene)
	log.Print("Added scene: " + scene.GetName())

	if activeScene == nil {
		activeScene = scene
		log.Print("Active scene: " + scene.GetName())
	}

	return true
}

// Removes a given scene.
// Returns false if it could not be found.
func RemoveScene(scene Scene) bool {
	for i, s := range scenes {
		if s == scene {
			s.Cleanup()
			scenes = append(scenes[:i], scenes[i+1:]...)
			log.Print("Removed scene: " + scene.GetName())
			return true
		}
	}

	return false
}

// Removes all scenes.
func RemoveAllScenes() {
	for _, s := range scenes {
		s.Cleanup()
	}

	scenes = make([]Scene, 0)
	log.Print("Cleared scenes")
}

// Finds and returns a scene by name, or nil if not found.
func GetSceneByName(name string) Scene {
	for _, s := range scenes {
		if s.GetName() == name {
			return s
		}
	}

	return nil
}

// Switches to given scene.
// This will pause the currently active scene.
func SwitchScene(scene Scene) {
	if activeScene != nil {
		activeScene.Pause()
	}

	activeScene = scene
	log.Print("Active scene: " + scene.GetName())

	for _, s := range scenes {
		if s == activeScene {
			activeScene.Resume()
			break
		}
	}
}

// Switches to given existing scene by name.
// Returns false if the scene does not exist.
func SwitchSceneByName(name string) bool {
	scene := GetSceneByName(name)

	if scene == nil {
		return false
	}

	SwitchScene(scene)

	return true
}

// Returns the currently active scene.
// Can be nil if no scene was set.
func GetActiveScene() Scene {
	return activeScene
}


text:
//
//  CAAnimationViewController.m
//  Demo_CoreAnimation
//
//  Created by 薛迎波 on 15/12/20.
//  Copyright © 2015年 XueYingbo. All rights reserved.
//

#import "CAAnimationViewController.h"

@interface CAAnimationViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end

@implementation CAAnimationViewController

- (void)viewDidLoad {
    [super viewDidLoad];

}
- (IBAction)animation:(UIButton *)sender {
    CAKeyframeAnimation *keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path addArcWithCenter:CGPointMake(200, 400) radius:50 startAngle:M_PI_2 * 3 endAngle:M_PI_2 * 3 + M_PI * 2 clockwise:YES];
    keyAnimation.path = path.CGPath;
    keyAnimation.duration  = 2.f;
    keyAnimation.fillMode = kCAFillModeForwards;
    keyAnimation.removedOnCompletion = NO;
    [self.imageView.layer addAnimation:keyAnimation forKey:nil];

    CABasicAnimation *basicAnimation = [CABasicAnimation animationWithKeyPath:@"transform"];
    basicAnimation.duration = 2.f;
    basicAnimation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    basicAnimation.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, .1, .1)];
    basicAnimation.fillMode = kCAFillModeForwards;
    basicAnimation.removedOnCompletion = NO;
    [self.imageView.layer addAnimation:basicAnimation forKey:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<link rel="stylesheet" type="text/css" href="style.css">

?Diciembre
2003

1604610

Legend -
 Level of confidence that token is an accurately-transcribed word

    extremely low
    very low
    low
    undetermined
    medium
    high
    very high


text:
package com.intel.analytics.bigdl.dllib.feature.common

import com.intel.analytics.bigdl.dllib.tensor.Tensor
import com.intel.analytics.bigdl.dllib.tensor.TensorNumericMath.TensorNumeric
import com.intel.analytics.bigdl.dllib.utils.Log4Error

import scala.reflect.ClassTag

/**
 * a Preprocessing that converts Array[Float], Array[Double] or MLlib Vector to multiple tensors
 * for multi-input models
 * @param multiSizes dimensions of target Tensors.
 */
class SeqToMultipleTensors[T: ClassTag](multiSizes: Array[Array[Int]])
    (implicit ev: TensorNumeric[T]) extends Preprocessing[Any, Array[Tensor[T]]] {

  override def apply(prev: Iterator[Any]): Iterator[Array[Tensor[T]]] = {
    prev.map { f =>
      val tensors = f match {
        case sd: Seq[Any] => matchSeq(sd)
        case _ =>
          Log4Error.invalidInputError(false, "SeqToTensor only supports Float, Double, " +
            s"Array[Float], Array[Double] or MLlib Vector but got $f")
          null
      }
      tensors
    }
  }

  def matchSeq(list: Seq[Any]): Array[Tensor[T]] = {
    val rawData = list.head match {
      case dd: Double => list.asInstanceOf[Seq[Double]].map(ev.fromType(_)).toArray
      case ff: Float => list.asInstanceOf[Seq[Float]].map(ev.fromType(_)).toArray
      case ii: Int => list.asInstanceOf[Seq[Int]].map(ev.fromType(_)).toArray
      case _ =>
        Log4Error.invalidInputError(false, s"SeqToTensor only supports Array[Int], " +
          s"Array[Float] and Array[Double] for ArrayType, but got $list")
        null
    }

    Log4Error.unKnowExceptionError(multiSizes.map(s => s.product).sum == rawData.length,
      s"feature columns length ${rawData.length} does not match with the sum of tensors" +
      s" ${multiSizes.map(a => a.mkString(",")).mkString("\n")}")

    var cur = 0
    val tensors = multiSizes.map { size =>
      val rawLength = size.product
      val t = Tensor(rawData.slice(cur, cur + rawLength), size)
      cur += rawLength
      t
    }
    tensors
  }
}

object SeqToMultipleTensors {
  def apply[T: ClassTag](
      multiSizes: Array[Array[Int]]
    )(implicit ev: TensorNumeric[T]): SeqToMultipleTensors[T] =
    new SeqToMultipleTensors[T](multiSizes)
}


text:
var test = require('tape')

var CHR = require('../../src/index')

test('chr.Rules.Add()', function (t) {
  t.test('chr.Rules.Add() is a function', function (t) {
    var chr = new CHR()
    var rules = chr.Rules

    t.equal(typeof rules.Add, 'function', 'chr.Rules.Add() is a function')

    t.end()
  })

  t.test('chr.Rules.Add() gives rule name if not specified', function (t) {
    var chr = new CHR()

    chr('a ==> b')

    t.equal(chr.Rules.Order.length, 1)

    var ruleName = chr.Rules.Order[0]
    t.ok(ruleName)
    t.ok(chr.Rules[ruleName])
    t.equal(ruleName, chr.Rules[ruleName].Name)

    t.end()
  })

  t.test('chr.Rules.Add() throws for identical rule name', function (t) {
    var chr = new CHR()

    chr('first @ a ==> b')

    t.throws(function () {
      chr('first @ c ==> d')
    }, 'chr.Rules.Add() throws for identical rule name')

    t.end()
  })

  t.end()
})

test('chr.Rules.Order', function (t) {
  var chr = new CHR()
  var rules = chr.Rules

  t.equal(typeof rules.Order, 'object', 'chr.Rules.Order is defined')
  t.ok(rules.Order instanceof Array, 'chr.Rules.Order is an Array')

  t.end()
})

test('chr.Rules.ForEach()', function (t) {
  t.test('chr.Rules.ForEach() is a function', function (t) {
    var chr = new CHR()
    var rules = chr.Rules

    t.equal(typeof rules.ForEach, 'function', 'chr.Rules.ForEach() is a function')

    t.end()
  })

  t.test('chr.Rules.ForEach() loops through all rules', function (t) {
    var chr = new CHR()

    chr('first  @ a ==> b')
    chr('second @ c ==> d')
    chr('third  @ e ==> f')

    var rules = chr.Rules
    var found = {}
    var order = []
    rules.ForEach(function (rule) {
      found[rule.Name] = 1
      order.push(rule.Name)
    })

    var expected = {
      first: 1,
      second: 1,
      third: 1
    }

    t.deepEqual(found, expected, 'all rules examined')
    t.deepEqual(order, ['first', 'second', 'third'], 'examined in order as defined')

    t.end()
  })

  t.test('chr.Rules.ForEach() loops in order', function (t) {
    var chr = new CHR()

    chr('first  @ a ==> b')
    chr('second @ c ==> d')
    chr('third  @ e ==> f')

    var rules = chr.Rules
    var order = [
      'third',
      'first',
      'second'
    ]
    rules.Order = order

    var found = []
    rules.ForEach(function (rule) {
      found.push(rule.Name)
    })

    t.deepEqual(found, order, 'examined in specified order')

    t.end()
  })

  t.end()
})

test('chr.Rules.Reset()', function (t) {
  t.test('chr.Rules.Reset() is a function', function (t) {
    var chr = new CHR()
    var rules = chr.Rules

    t.equal(typeof rules.Reset, 'function', 'chr.Rules.Reset() is a function')

    t.end()
  })

  t.test('chr.Rules.Reset() deletes existing rules', function (t) {
    var chr = new CHR()
    var rules = chr.Rules

    chr('first @ a ==> b')
    chr('second @ c ==> d')

    t.ok(rules.first)
    t.ok(rules.second)
    t.ok(chr.a)
    t.ok(chr.b)
    t.ok(chr.c)
    t.ok(chr.d)

    rules.Reset()

    t.notOk(rules.first)
    t.notOk(rules.second)
    t.notOk(chr.a)
    t.notOk(chr.b)
    t.notOk(chr.c)
    t.notOk(chr.d)

    t.deepEqual(chr.Constraints, {})

    t.end()
  })

  t.end()
})


text:
from abc import ABCMeta, abstractmethod
from . import client as riq
from requests import HTTPError
import math

class RIQBase(object, metaclass=ABCMeta):
    _cache = []
    _cache_index = 0
    _page_index = 0
    _page_length = 200
    _fetch_options = {}
    _batch_size = 50

    @classmethod
    @abstractmethod
    def node(cls) :
        pass

    @classmethod
    def endpoint(cls) :
        return cls.node()

    @classmethod
    def fetchBatch(cls,param,values,maxSize=_page_length) :
        chunks = [values[x:x+maxSize] for x in range(0, len(values), maxSize)]
        objects = []
        for i, chunk in enumerate(chunks):
            try:
                cls.setFetchOptions({param:','.join(chunk)})
                # TODO : set += is not consistent with the rest of the code base
                objects += cls.fetchPage()
            except HTTPError as e:
                if (e.response.status_code == 414 or e.response.status_code == 413) and maxSize > 1: #max url length is 8192 (2^13). If longer, will give a 414 error.
                    objects += cls.fetchBatch(param, chunk, int(math.ceil(maxSize/2)))
                else:
                    raise
        return objects

    @classmethod
    def fetchPage(cls,index=0,limit=None) :
        if limit == None :
            limit = cls._page_length
        cls._fetch_options['_start'] = str(index)
        cls._fetch_options['_limit'] =  str(limit)
        data = riq.get(cls.endpoint(),cls._fetch_options)
        objects = []
        for obj in data.get('objects',[]) :
            objects.append(cls(data=obj))
        return objects

    @classmethod
    def next(cls) :
        if cls._cache_index == 0 :
            cls._cache = []
            cls._cache_index = 0
            cls._page_index = 0
        if cls._cache_index == len(cls._cache) :
            if len(cls._cache) not in [0,cls._page_length] :
                return None
            del cls._cache[:]
            cls._cache.extend(cls.fetchPage(cls._page_index,cls._page_length))
            cls._page_index += len(cls._cache)
            cls._cache_index = 0
        if cls._cache_index < len(cls._cache) :
            obj = cls._cache[cls._cache_index]
            cls._cache_index += 1
            return obj
        else :
            return None

    @classmethod
    def resetCache(cls) :
        cls._fetch_options = {}
        cls._cache = []
        cls._cache_index = 0
        cls._page_index = 0
        cls._last_modified_date = None

    @classmethod
    def setPageSize(cls,limit) :
        cls._page_length = limit

    @classmethod
    def setFetchOptions(cls, options = {}):
        cls.resetCache()
        cls._fetch_options = options

    @classmethod
    def createBatch(cls,objs):
        return_objs = {}
        while len(objs) > 0:
            chunk_size = cls._batch_size if len(objs) > cls._batch_size else len(objs)
            chunk = objs[0:chunk_size]
            objs = objs[chunk_size:] if chunk_size < len(objs) else []
            batch_objs = cls.createBatchHelper('/createBatch',chunk)
            return_objs['successObjects'] = return_objs.setdefault('successObjects',[]) + batch_objs['successObjects']
            return_objs['errorObjects'] =   return_objs.setdefault('errorObjects', [])  + batch_objs['errorObjects']
        return return_objs

    @classmethod
    def updateBatch(cls,objs):
        return_objs = {}
        while len(objs) > 0:
            chunk_size = cls._batch_size if len(objs) > cls._batch_size else len(objs)
            chunk = objs[0:chunk_size]
            objs = objs[chunk_size:] if chunk_size < len(objs) else []
            batch_objs = cls.updateBatchHelper('/updateBatch',chunk)
            return_objs['successObjects'] = return_objs.setdefault('successObjects',[]) + batch_objs['successObjects']
            return_objs['errorObjects'] =   return_objs.setdefault('errorObjects', [])  + batch_objs['errorObjects']
        return return_objs

    @classmethod
    def updateBatchHelper(cls, endpoint, objs):
        batch_results = riq.put(cls.endpoint()+endpoint, {"objects":[obj.payload() for obj in objs]})
        batch_results['successObjects'] = [cls(data=obj) for obj in batch_results['successObjects']]
        for errorObj in batch_results['errorObjects']:
            errorObj['object'] = cls(data=errorObj['object'])
        return batch_results

    @classmethod
    def createBatchHelper(cls, endpoint, objs):
        batch_results = riq.post(cls.endpoint()+endpoint, {"objects":[obj.payload() for obj in objs]})
        batch_results['successObjects'] = [cls(data=obj) for obj in batch_results['successObjects']]
        for errorObj in batch_results['errorObjects']:
            errorObj['object'] = cls(data=errorObj['object'])
        return batch_results

    @classmethod
    def dummyClassMethod(cls):
        print()


text:
package sample;

import org.wisdom.api.Controller;
import org.wisdom.api.router.Route;

import java.util.Collections;
import java.util.List;

/**
 * A simple controller implementing Controller
 */
public class MyController implements Controller {
    /**
     * Returns an empty list.
     */
    @Override
    public List<Route> routes() {
        return Collections.emptyList();
    }
}


text:
package org.pi.litepost.html;

public class InputFactory {
	Validator validator;

	public InputFactory(Validator validator) {
		this.validator = validator;
	}

	public Select getSelect() {
		return new Select(validator);
	}

	public Textarea getTextarea() {
		return new Textarea(validator);
	}

	public Input getSubmit() {
		Input input = new Input("submit", validator);
		input.class_("button");
		return input;
	}

	public Input get(String type) {
		return new Input(type, validator);
	}

	public String getCsrfToken() {
		if(validator != null) {
			return validator.csrfToken().toString();
		} else {
			return "";
		}
	}

	public boolean error(String name) {
		if(validator != null) {
			return !validator.valid(name);
		} else {
			return false;
		}
	}

	public String value(String name) {
		if(validator != null) {
			return validator.value(name);
		} else {
			return "";
		}
	}
}


text:
package com.itellity.sys.util.xml;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Item {

	private String name;
	private String value;

	public Item() {
		super();
	}

	public Item(String name, String value) {
		super();
		this.name = name;
		this.value = value;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}

}


text:
package com.platzerworld.dao;

import com.platzerworld.entities.Adresse;
import com.platzerworld.entities.Biergarten;

import javax.ejb.Stateless;
import java.util.List;

/**
 * Created by platzerworld on 02.07.16.
 */
@Stateless
public class BiergartenDAO extends DAO {

    public Biergarten create(String name, String pwd, String mail) {
        Biergarten biergarten = new Biergarten();

        biergarten.setName("platzerworld");
        Adresse adresse = new Adresse();
        adresse.setStrasse("Gyßlingstraße");
        adresse.setPlz("80805");
        adresse.setOrt("München");
        biergarten.setAdresse(adresse);

        biergarten.setTelefon("089 / 36100880");//
        biergarten.setEmail("aumeister@aumeister.de");
        biergarten.setUrl("minihofbraeuhaus.de/");//
        biergarten.setLatitude("48,167011");
        biergarten.setLongitude("11,607648");
        biergarten.setMass("Mass");
        biergarten.setApfelschorle("AS");
        biergarten.setRiesenbreze("RB");
        biergarten.setObazda("Obazda");
        biergarten.setBiermarke("BM");
        biergarten.setLieblingsgericht("LG");
        biergarten.setSpeisekommentar("Speisekommentar");
        biergarten.setDescShort("DESC LONG");
        biergarten.setDescLong("Übers ganze Jahr süddeutsche Kost und Biere im gemütlichen und hundefreundlichen Gastgarten oder im Zelt.");
        biergarten.setFavorit(false);//
        return this.create(biergarten);
    }

    public Biergarten update(int id, String name) {
        Biergarten biergarten = this.find(Biergarten.class, id);
        if (biergarten == null) {
            throw new IllegalArgumentException("comment with id " + id + " not found");
        }
        biergarten.setName(name);

        return this.update(biergarten);
    }

    public void delete(int id) {
        this.delete(Biergarten.class, id);
    }

    public Biergarten getBiergartenById(int biergartenId) {
        Biergarten biergrten = this.find(Biergarten.class, biergartenId);
        if (biergrten == null) {
            throw new IllegalArgumentException("Biergarten with id " + biergartenId + " not found");
        }
        return biergrten;
    }

    public List<Biergarten> list(int first, int max) {
        return this.namedFind(Biergarten.class, "biergarten.list", first, max);
    }
}


text:
'use strict';

/*!
 * Module dependencies.
 */

var StorageError = require('../error.js');
var errorMessages = StorageError.messages;

/**
 * Schema validator error
 *
 * @param {String} path
 * @param {String} msg
 * @param {String} type
 * @param {String|Number|*} val
 * @inherits StorageError
 * @api private
 */

function ValidatorError (path, msg, type, val) {
  if ( !msg ) {
    msg = errorMessages.general.default;
  }

  var message = this.formatMessage(msg, path, type, val);
  StorageError.call(this, message);

  this.name = 'ValidatorError';
  this.path = path;
  this.type = type;
  this.value = val;
}

/*!
 * toString helper
 */

ValidatorError.prototype.toString = function () {
  return this.message;
};

/*!
 * Inherits from StorageError
 */
ValidatorError.prototype = Object.create( StorageError.prototype );
ValidatorError.prototype.constructor = ValidatorError;

/*!
 * exports
 */

module.exports = ValidatorError;


text:
package com.smile.spider.xml;

import javax.xml.bind.annotation.*;

/**
 * Created by zhutao on 15/7/30.
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "source")
public class TaskSource {

    @XmlAttribute(name = "db")
    private String db;

    @XmlAttribute(name = "field")
    private String field;

    @XmlElement(name = "parser")
    private TaskSourceParser parser;

    public String getDb() {
        return db;
    }

    public void setDb(String db) {
        this.db = db;
    }

    public String getField() {
        return field;
    }

    public void setField(String field) {
        this.field = field;
    }

    public TaskSourceParser getParser() {
        return parser;
    }

    public void setParser(TaskSourceParser parser) {
        this.parser = parser;
    }
}


text:
criterion: 5
category: Security, privacy, tools and standards
phase: live
---

#### Prompts

* How did you choose technology for the live service?
* What tools are you using for the live service?
* What options were considered and what factors led to the decision?
* How are you avoiding lock-in?
* Are the contracts in place suitably flexible and delivering value for money?
* What procurement vehicles have you used and why?
* What changes are you planning to make after the service is live?
* What metrics are you collecting from the running system ?
* How will you monitor and manage capacity after the service is live?
* How will you respond to increases in demand after the service is live?
* Do the operational team know what to do in the event of an incident on the service and have you tested this?

#### Evidence

Service Manager able to:

* Explain what technology and tools the service has bought, built and will use for the live service and why they have chosen them
* Explain how they are avoiding lock in, how their contracts are suitably flexible and how they are delivering value for money
* Explain what procurement vehicles they have used and why
* Explain what changes they are planning to make after the service is live
* Explain what metrics they are collecting from the running system
* Explain how they will monitor and manage capacity after the service is live, and how they will respond to increases in demand
* Explain the process in the event of an incident on the service and how this has been tested


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Immutable;

namespace Microsoft.CodeAnalysis
{
    internal sealed class CustomModifiersTuple
    {
        private readonly ImmutableArray<CustomModifier> _typeCustomModifiers;
        private readonly ImmutableArray<CustomModifier> _refCustomModifiers;
        public static readonly CustomModifiersTuple Empty = new CustomModifiersTuple(ImmutableArray<CustomModifier>.Empty, ImmutableArray<CustomModifier>.Empty);

        private CustomModifiersTuple(ImmutableArray<CustomModifier> typeCustomModifiers, ImmutableArray<CustomModifier> refCustomModifiers)
        {
            _typeCustomModifiers = typeCustomModifiers.NullToEmpty();
            _refCustomModifiers = refCustomModifiers.NullToEmpty();
        }

        public static CustomModifiersTuple Create(ImmutableArray<CustomModifier> typeCustomModifiers, ImmutableArray<CustomModifier> refCustomModifiers)
        {
            if (typeCustomModifiers.IsDefaultOrEmpty && refCustomModifiers.IsDefaultOrEmpty)
            {
                return Empty;
            }

            return new CustomModifiersTuple(typeCustomModifiers, refCustomModifiers);
        }

        public ImmutableArray<CustomModifier> TypeCustomModifiers { get { return _typeCustomModifiers; } }
        public ImmutableArray<CustomModifier> RefCustomModifiers { get { return _refCustomModifiers; } }
    }
}


text:
setup

%% MODEL 1
model1runme('gridApprox')
model1plot('tempModel1run_gridApprox')

model1runme('mcmcCustom')
model1plot('tempModel1run_mcmcCustom')

model1runme('mcmcJAGS')
model1plot('tempModel1run_mcmcJAGS')

% model 1 JAGS
model1MCMCconvergence	% check chain convergence

% accuracy of MCMC chain derived MAP estimates of sigma^2
model1MCMCse('calculate')
model1MCMCse('plot')

%% MODEL 2
model2runme				% parameter estimation + model prediction
model2plot

%% MODEL 3
model3runme				% parameter estimation + model prediction
model3plot

% calculate psychometric functions
model3psychometric('calculate')
model3psychometric('plot')


text:
subject: Coisas boas acontecem a quem abre esse e-mail
---

<container class="header">
  <row class="collapse">
    <columns>

    </columns>
  </row>
</container>

<spacer size="16"></spacer>

<container class="body-drip">

    <spacer size="0"></spacer>

    <row>

    </row>

    <spacer size="16"></spacer>

    <row>
      <columns>

Oi, tudo bem?

Vi que você abandonou a sua assinatura da PlayKids...

Não sei qual pode ter sido o motivo, mas pensei nas seguintes situações:

      </columns>
    </row>

    <row>
      <columns>

1. Você tem interesse na plataforma, mas algo te fez mudar de ideia.

          <spacer size="10"></spacer>

 2. Você tem interesse, mas a campainha tocou e você teve que sair correndo...

          <spacer size="10"></spacer>

 3.  Seu filho gritou dizendo que viu um dinossauro cantando Galinha Pintadinha e você precisa da minha ajuda para domar o animalzinho.

      </columns>
    </row>
    <spacer size="16"></spacer>
    <row>
      <columns>

      </columns>
    </row>

    <spacer size="30"></spacer>

    <row>
      <columns>

Responda esse e-mail me dizendo qual das alternativas acima é a correta e farei o máximo para te ajudar.

        <spacer size="20"></spacer>

Se a opção for a 2 você pode terminar a sua assinatura clicando aqui.

      </columns>
    </row>

    <spacer size="20"></spacer>

    <row class="collapsed footer">
      <columns>

Aguardo sua resposta, ok?

            <spacer size="10"></spacer>

Mari Lacerda

Atendimento ao cliente

suporte@playkids.com

      </columns>
    </row>

    <row>

    </row>

</container>

<spacer size="20"></spacer>

  <row>
    <columns>

Copyright © 2017 PlayKids. Todos os direitos reservados.

        <menu>
          <item></item>
          <item></item>
          <item></item>
          <item></item>
        </menu>

    </columns>
  </row>

<spacer size="50"></spacer>


text:
package org.designpattern.core.factories;

import org.junit.Test;

/**
 * {@link SpecialBusFactory} 的测试类
 *
 * @author kay
 * @version 1.0
 */
public class TestSpecialBusFactory extends SpecialBusFactory {

    @Test
    public void test(){
        System.out.println(FACTORY_CLASSNAME);
    }

    @Test
    public void testAbstractCreate(){
        System.out.println(this.create(this.FACTORY_CLASSNAME));
    }
}


text:
package org.apache.nifi.record.sink.lookup;

import org.apache.nifi.reporting.InitializationException;
import org.apache.nifi.serialization.SimpleRecordSchema;
import org.apache.nifi.serialization.WriteResult;
import org.apache.nifi.serialization.record.MapRecord;
import org.apache.nifi.serialization.record.Record;
import org.apache.nifi.serialization.record.RecordField;
import org.apache.nifi.serialization.record.RecordFieldType;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.RecordSet;
import org.apache.nifi.util.TestRunner;
import org.apache.nifi.util.TestRunners;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

public class TestRecordSinkServiceLookup {

    private MockRecordSinkServiceLookup sinkLookup;
    private TestRunner runner;
    private MockRecordSinkService sinkA, sinkB;
    private RecordSet recordSet;

    @Before
    public void setup() throws InitializationException {
        sinkA = new MockRecordSinkService("a");
        sinkB = new MockRecordSinkService("b");
        sinkLookup = new MockRecordSinkServiceLookup();

        runner = TestRunners.newTestRunner(TestProcessor.class);

        final String sinkServiceAIdentifier = "a";
        runner.addControllerService(sinkServiceAIdentifier, sinkA);

        final String sinkServiceBIdentifier = "b";
        runner.addControllerService(sinkServiceBIdentifier, sinkB);

        runner.addControllerService("sink-lookup", sinkLookup);
        runner.setProperty(sinkLookup, "a", sinkServiceAIdentifier);
        runner.setProperty(sinkLookup, "b", sinkServiceBIdentifier);

        runner.enableControllerService(sinkA);
        runner.enableControllerService(sinkB);
        runner.enableControllerService(sinkLookup);

        final List<RecordField> fields = new ArrayList<>();
        fields.add(new RecordField("a", RecordFieldType.STRING.getDataType()));
        fields.add(new RecordField("b", RecordFieldType.BOOLEAN.getDataType()));

        final RecordSchema schema = new SimpleRecordSchema(fields);

        final Map<String, Object> valueMap1 = new HashMap<>();
        valueMap1.put("a", "Hello");
        valueMap1.put("b", true);
        final Record record1 = new MapRecord(schema, valueMap1);

        final Map<String, Object> valueMap2 = new HashMap<>();
        valueMap2.put("a", "World");
        valueMap2.put("b", false);
        final Record record2 = new MapRecord(schema, valueMap2);

        recordSet = RecordSet.of(schema, record1, record2);
    }

    @Test
    public void testLookupServiceA() {
        final Map<String, String> attributes = new HashMap<>();
        attributes.put(RecordSinkServiceLookup.RECORD_SINK_NAME_ATTRIBUTE, "a");

        try {
            final WriteResult writeResult = sinkLookup.sendData(recordSet, attributes, false);
            assertNotNull(writeResult);
            assertEquals(2, writeResult.getRecordCount());
            String returnedName = writeResult.getAttributes().get("my.name");
            assertEquals("a", returnedName);
        } catch (IOException ioe) {
            fail("Should have completed successfully");
        }
    }

    @Test
    public void testLookupServiceB() {
        final Map<String, String> attributes = new HashMap<>();
        attributes.put(RecordSinkServiceLookup.RECORD_SINK_NAME_ATTRIBUTE, "b");

        try {
            final WriteResult writeResult = sinkLookup.sendData(recordSet, attributes, false);
            assertNotNull(writeResult);
            assertEquals(2, writeResult.getRecordCount());
            String returnedName = writeResult.getAttributes().get("my.name");
            assertEquals("b", returnedName);
        } catch (IOException ioe) {
            fail("Should have completed successfully");
        }
    }

    @Test
    public void testLookupServiceAThenB() {
        final Map<String, String> attributes = new HashMap<>();
        attributes.put(RecordSinkServiceLookup.RECORD_SINK_NAME_ATTRIBUTE, "a");

        try {
            final WriteResult writeResult = sinkLookup.sendData(recordSet, attributes, false);
            String returnedName = writeResult.getAttributes().get("my.name");
            assertEquals("a", returnedName);
            assertEquals(1, sinkA.getResetCount());
        } catch (IOException ioe) {
            fail("Should have completed successfully");
        }

        attributes.put(RecordSinkServiceLookup.RECORD_SINK_NAME_ATTRIBUTE, "b");

        try {
            final WriteResult writeResult = sinkLookup.sendData(recordSet, attributes, false);
            String returnedName = writeResult.getAttributes().get("my.name");
            assertEquals("b", returnedName);
            assertEquals(1, sinkB.getResetCount());
        } catch (IOException ioe) {
            fail("Should have completed successfully");
        }
        // reset() was called on the retrieved sinks (not the lookup itself) in sendData() when the sink changed
        assertEquals(0, sinkLookup.getResetCount());
        sinkLookup.reset();
        assertEquals(1, sinkLookup.getResetCount());
    }

    @Test
    public void testLookupServiceAThenA() {
        final Map<String, String> attributes = new HashMap<>();
        attributes.put(RecordSinkServiceLookup.RECORD_SINK_NAME_ATTRIBUTE, "a");

        try {
            WriteResult writeResult = sinkLookup.sendData(recordSet, attributes, false);
            String returnedName = writeResult.getAttributes().get("my.name");
            assertEquals("a", returnedName);
            assertEquals(1, sinkA.getResetCount());
            writeResult = sinkLookup.sendData(recordSet, attributes, false);
            returnedName = writeResult.getAttributes().get("my.name");
            assertEquals("a", returnedName);
            assertEquals(1, sinkA.getResetCount());

        } catch (IOException ioe) {
            fail("Should have completed successfully");
        }

        // reset() was called on the retrieved sinks (not the lookup itself) in sendData() when the sink changed
        assertEquals(0, sinkLookup.getResetCount());
        sinkLookup.reset();
        assertEquals(1, sinkLookup.getResetCount());
    }

    @Test(expected = IOException.class)
    public void testLookupWithoutAttributes() throws IOException {
        sinkLookup.sendData(recordSet, Collections.emptyMap(), false);
    }

    @Test(expected = IOException.class)
    public void testLookupMissingRecordSinkNameAttribute() throws IOException {
        sinkLookup.sendData(recordSet, Collections.emptyMap(), false);
    }

    @Test(expected = IOException.class)
    public void testLookupWithDatabaseNameThatDoesNotExist() throws IOException {
        final Map<String, String> attributes = new HashMap<>();
        attributes.put(RecordSinkServiceLookup.RECORD_SINK_NAME_ATTRIBUTE, "DOES-NOT-EXIST");
        sinkLookup.sendData(recordSet, attributes, false);
    }

    public static class MockRecordSinkServiceLookup extends RecordSinkServiceLookup {
        private int resetCount = 0;

        @Override
        public void reset() {
            resetCount++;
        }

        public int getResetCount() {
            return resetCount;
        }
    }
}


text: db.createCollection('loginAttempts');


text:
module Awspec::Generator
  module Spec
    class Lambda
      include Awspec::Helper::Finder
      def generate_all
        lambda_functions = select_all_lambda_functions
        raise 'Not Found lambda' if lambda_functions.empty?
        ERB.new(lambda_spec_template, nil, '-').result(binding).chomp
      end

      def lambda_spec_template
        template = <<-'EOF'
<% lambda_functions.each do |function| %>
describe lambda('<%= function.function_name %>') do
  it { should exist }
  its(:description) { should eq '<%= function.description %>' }
  its(:runtime) { should eq '<%= function.runtime %>' }
  its(:handler) { should eq '<%= function.handler %>' }
  its(:code_size) { should eq <%= function.code_size %> }
  its(:timeout) { should eq <%= function.timeout %> }
  its(:memory_size) { should eq <%= function.memory_size %> }
end
<% end %>
EOF
        template
      end
    end
  end
end


text:
package edu.anagen.cs.ssuet.ocr.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.PopupMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.pixplicity.easyprefs.library.Prefs;

import java.util.ArrayList;
import java.util.List;

import edu.anagen.cs.ssuet.ocr.R;
import edu.anagen.cs.ssuet.ocr.activities.SplashActivity;
import edu.anagen.cs.ssuet.ocr.model.Paper;
import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;

/**
 * Created by hp on 10/14/2017.
 */

public class questionsAdapter extends BaseAdapter {

    private Context context; //context
    private LayoutInflater inflater = null;
    private Realm realm;
    private List<Paper> paperList;

    public questionsAdapter(Context context, List<Paper> _paper) {

        this.context = context;
        this.paperList = _paper;
        inflater = LayoutInflater.from(context);

    }
    @Override
    public int getCount() {
        return paperList.size();
    }

    @Override
    public Object getItem(int i) {
        return paperList.size();
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View convertview, ViewGroup viewGroup) {

        Paper singlePaper = paperList.get(i);

        ViewHolder holder;
        if(convertview == null) {

            convertview =inflater.inflate(R.layout.questions_list_item,null);
            holder = new ViewHolder();

            holder._scanText = convertview.findViewById(R.id.scan_text);
            holder._complexity = convertview.findViewById(R.id.tv_complexity);
            holder._weightage = convertview.findViewById(R.id.tv_weightage);

            convertview.setTag(holder);

        } else {
            holder = (ViewHolder) convertview.getTag();
        }

        holder._scanText.setText(singlePaper.getText().toString());
        holder._complexity.setText("Complexity " +String.valueOf(singlePaper.getComplexity()));
        holder._weightage.setText("Weightage " +String.valueOf(singlePaper.getWeightage()));

        return convertview;
    }

    public class ViewHolder {

        TextView _scanText;
        TextView _complexity;
        TextView _weightage;
    }
}


text:
import Component from '../../../../src/component/Component.js';
import c from '../../../../src/dom/create.js';
import Fetch from '../../../../src/xhr/Fetch.js';
import AsyncAction from '../../../../src/action/AsyncAction.js';

export default class Profile extends Component {
    create() {
        /**
         * Statefull elements
         */
        const a = c('a')
            .h('javascript:void(0);')
            .txt('FETCH');

        const asyncAction = new AsyncAction('http://localhost/SFM/public_html/api/transactionodometadata.json?key=MeanName&partition=Week&dataLevels%5B%5D=Week&dataLevels%5B%5D=MeanName&dataTypes%5B%5D=Odo&dataTypes%5B%5D=Volume&startDate=2015-09-03&endDate=2015-12-03');
        asyncAction
            .before(asyncAction.do((asyncAction, state, Component) => {
                console.log('BEFORE');
                return true;
            }));

        this.on(a, 'click', asyncAction.when((e, asyncAction, state, Component) => {
            e.preventDefault();

            asyncAction.promise()
                .then(asyncAction.do((asyncAction, state) => {
                    console.log('SUCCESS');
                    console.log(state);
                    console.log(asyncAction.jsonResponse());
                    return true;
                }))
                .catch(asyncAction.do((asyncAction) => {
                    console.log('FAILURE');
                    return true;
                }))
                .then(asyncAction.do((asyncAction) => {
                    console.log('FINALLY');
                    return true;
                }));

            console.log('ACTION');
            return true; // Always send
        }));

        //this.on(a, 'click', (e, state, C) => {
        //    e.preventDefault();
        //    new Fetch(
        //        //'http://localhost/SFM/public_html/api/transactionlist.json?%00%00%00=&startDate=2015-09-01&endDate=2015-12-30&columns%5BId%5D=Id&columns%5BDate%5D=Date&columns%5BTime%5D=Time&columns%5BProduct%5D=ProductName&columns%5BPrice%5D=Price&columns%5BPPU%5D=PricePerVolume&columns%5BVolume%5D=Volume&columns%5BGroup%5D=DepartmentName&columns%5BDevice%5D=DeviceName&columns%5BOdo%5D=Odo&columns%5BPreviousOdo%5D=PreviousOdo&columns%5BDriver%5D=DriverName&columns%5BStation%5D=StationName&page=1'
        //        'http://localhost/SFM/public_html/api/transactionodometadat.json?key=MeanName&partition=Week&dataLevels%5B%5D=Week&dataLevels%5B%5D=MeanName&dataTypes%5B%5D=Odo&dataTypes%5B%5D=Volume&startDate=2015-09-03&endDate=2015-12-03'
        //        ).before((Fetch)=>{
        //            console.log('BEFORE');
        //        })
        //        .send()
        //        .then((Fetch) => {
        //            console.log('SUCCESS');
        //            console.log(Fetch.jsonResponse());
        //        })
        //        .catch((Fetch) => {
        //            console.log('FAILURE');
        //        })
        //        .then((Fetch) => {
        //            console.log('FINALLY');
        //        });
        //});
        /**
         * Structure elements
         */
        // Create root of component
        const fragment = c(),
            heading = c('h2').txt('Profile'),
            content = c('div');
        content.classList.add('content');

        // Append children
        fragment
            .append(heading, false)
            .append(a)
            .append(content);

        // Return root
        return fragment;
    }
}


text:
#include "common.h"
#include <vector>
extern "C" {
#include <unistd.h>
#include <limits.h>
#include <libgen.h>
#include <sys/types.h>
}

namespace afCommon{

std::string get_executable_dir(){
    char exePath[PATH_MAX];
    ssize_t exePathSize = readlink("/proc/self/exe", exePath, PATH_MAX);
    if(exePathSize == -1) throw AfSystemException("Cannot determine executable path");
    exePath[exePathSize] = '\0';
    return std::string(dirname(exePath)) + file_delim;
}

std::string cpp_realpath(const std::string& raw_path){
    char *pathCand = realpath(raw_path.c_str(), NULL);
    if(pathCand == NULL) throw AfSystemException("Cannot canonicalize path");
    return std::string(pathCand) + file_delim;
}

void erase_file(const std::string& filename){
    // TODO: for now this just rm's a file, later add an option to shred it
    if(std::remove(filename.c_str()) == -1){
	throw AfSystemException("Error removing " + filename);
    }
}

const int kB_remainder_mask = 1024 - 1;
const int kB_shift = 10;
const std::vector<std::string> binary_units = {" B", " kB", " MB", " GB"};

std::string humanize_byte_count(const off_t& byte_count){
    /* converts a raw byte count into the units of B, kB, MB, etc.. The
    prefixes k, M, G, etc., are binary, i.e., 1 kB = 2^10 B = 1024 B. The
    following format has been decided upon: the amount is expressed in terms of
    the largest possible binary prefix such that the integer part is non-zero.
    Given the expected use of the utility, the available prefixes go up to G.
    If the resulting integer part has one or two digits, the entire amount is
    rounded to one decimal place. If the rounded fractional part equals zero,
    the ".0" suffix is not shown. This is also not shown if the integer part
    has three or more digits. */
    // this attempts to do some fun bitwise computations
    off_t currValue_t = byte_count, nextQuotient;
    int prevRemainder = 0;
    int i;
    for(i = 0; i < 3 && (nextQuotient = currValue_t >> kB_shift) != 0; ++i){
	prevRemainder = currValue_t & kB_remainder_mask;
	currValue_t = nextQuotient;
    }
    int currValue = (int) currValue_t;
    int twoDecimalDigits = (100 * prevRemainder) / 1024;
    if(currValue / 100 != 0) {
	if (twoDecimalDigits < 50)
	    return std::to_string(currValue) + binary_units[i];
	return std::to_string(currValue + 1) + binary_units[i];
    }
    if(twoDecimalDigits < 5) return std::to_string(currValue) + binary_units[i];
    if(twoDecimalDigits >= 95) return std::to_string(currValue + 1) + binary_units[i];
    return std::to_string(currValue) + "." + std::to_string((twoDecimalDigits + 5) / 10) + binary_units[i];
}

}


text:
<!DOCTYPE HTML>

100% width


text:
package org.elasticsearch.search.aggregations.bucket.terms;

import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.aggregations.Aggregator;
import org.elasticsearch.search.aggregations.AggregatorFactories;
import org.elasticsearch.search.aggregations.BucketOrder;
import org.elasticsearch.search.aggregations.bucket.terms.heuristic.SignificanceHeuristic;
import org.elasticsearch.search.aggregations.support.AggregationContext;

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

import static java.util.Collections.emptyList;

abstract class AbstractStringTermsAggregator extends TermsAggregator {

    protected final boolean showTermDocCountError;

    AbstractStringTermsAggregator(String name, AggregatorFactories factories, AggregationContext context, Aggregator parent,
            BucketOrder order, DocValueFormat format, BucketCountThresholds bucketCountThresholds, SubAggCollectionMode subAggCollectMode,
            boolean showTermDocCountError, Map<String, Object> metadata) throws IOException {
        super(name, factories, context, parent, bucketCountThresholds, order, format, subAggCollectMode, metadata);
        this.showTermDocCountError = showTermDocCountError;
    }

    protected StringTerms buildEmptyTermsAggregation() {
        return new StringTerms(name, order, order, bucketCountThresholds.getRequiredSize(), bucketCountThresholds.getMinDocCount(),
                metadata(), format, bucketCountThresholds.getShardSize(), showTermDocCountError, 0, emptyList(), 0);
    }

    protected SignificantStringTerms buildEmptySignificantTermsAggregation(long subsetSize, SignificanceHeuristic significanceHeuristic) {
        // We need to account for the significance of a miss in our global stats - provide corpus size as context
        int supersetSize = searcher().getIndexReader().numDocs();
        return new SignificantStringTerms(name, bucketCountThresholds.getRequiredSize(), bucketCountThresholds.getMinDocCount(),
                metadata(), format, subsetSize, supersetSize, significanceHeuristic, emptyList());
    }
}


text:
<?php

use Twig\Extension\CoreExtension;

class_exists('Twig\Extension\CoreExtension');

if (\false) {
    class Twig_Extension_Core extends CoreExtension
    {
    }
}


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

<TITLE>
gov.nasa.worldwind.tracks (NASA World Wind)
</TITLE>

<META NAME="date" CONTENT="2010-01-14">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Index
      Help

NASA World Wind

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package gov.nasa.worldwind.tracks

Interface Summary

Track

TrackPoint

TrackPointIterator

TrackSegment

Class Summary

TrackPointImpl

TrackPointIteratorImpl

      Overview
    Package
      Class
      Use
      Tree
      Index
      Help

NASA World Wind

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes


text:
namespace chromeos {

class InputServiceProxy;
class TestObserver;

typedef device::InputServiceLinux::InputDeviceInfo InputDeviceInfo;

class InputServiceTestHelper {
 public:
  static const char kKeyboardId[];
  static const char kMouseId[];

  // This class must be instantiated BEFORE any InputServiceProxy. Otherwise, a
  // default InputServiceLinux will be created and become the proxy observer,
  // instead of the FakeInputServiceLinux from the .cc file.
  InputServiceTestHelper();
  ~InputServiceTestHelper();

  void SetProxy(InputServiceProxy* proxy);
  void ClearProxy();
  void AddDeviceToService(bool is_mouse, InputDeviceInfo::Type type);
  void RemoveDeviceFromService(bool is_mouse);

 private:
  std::unique_ptr<TestObserver> observer_;
  InputServiceProxy* proxy_;

  DISALLOW_COPY_AND_ASSIGN(InputServiceTestHelper);
};

}  // namespace chromeos

#endif  // CHROME_BROWSER_CHROMEOS_DEVICE_INPUT_SERVICE_TEST_HELPER_H_


text:
Ghabriel Nunes

on 2012-02-12 20:51:47

I found some errors in the function above.
The above function does not handle negative limits, and, according to the PHP documentation, if limit is 0, it's treated as 1. The above function treats limit as "not set" if it's 0, which is wrong. Also, if the limit is bigger than the split length, it adds white spaces to the array, which is also wrong. I re-created this function, fixing all the mistakes  I found:

Note: sorry for any english mistakes, english is not my first language.

function explode( delimiter, string, limit ){
	if ( arguments.length < 2 || typeof delimiter == 'undefined' || typeof string == 'undefined' ) return null;
	if ( delimiter === '' || delimiter === false || delimiter === null) return false;
	if ( typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object'){
		return { 0: '' };
	}
	if ( delimiter === true ) delimiter = '1';

	// Here we go...
	delimiter += '';
	string += '';

	var s = string.split( delimiter );

	if ( typeof limit === 'undefined' ) return s;

	// Support for limit
	if ( limit === 0 ) limit = 1;

	// Positive limit
	if ( limit > 0 ){
		if ( limit >= s.length ) return s;
		return s.slice( 0, limit - 1 ).concat( [ s.slice( limit - 1 ).join( delimiter ) ] );
	}

	// Negative limit
	if ( -limit >= s.length ) return [];

	s.splice( s.length + limit );
	return s;
}

raj

on 2011-03-07 06:52:47

ghghggh

a

on 2010-06-14 16:08:09

ser

IVI-R3za.M

on 2010-02-27 07:35:43

its so great! thanks

Brett Zamir

on 2010-02-15 07:00:28

It's working for me...

explode('-+-', 'abc-+-def-+-ghi') // abc,def,ghi

What are you trying to do that's different?

nowotny

on 2010-02-14 17:05:13

PHP explode function allows you to split by a string, not only one character, which this JS function does not allow...

Onno Marsman

on 2008-12-09 18:25:49

@valulgi: You'll need to look a bit closer. This function is really built around the split function from js.

valulgi

on 2008-12-08 13:49:34

why not use the split function from js?

Kevin van Zonneveld

on 2008-05-17 15:16:24

@ d3x: Thanks! I've updated the function. I changed the

arguments.length != 3

part, for it to allow 2 arguments. Other than that, great contribution!!

d3x

on 2008-05-17 09:40:35

Same function with the limit attribute:

function explode( delimiter, string, limit ) {
	// http://kevin.vanzonneveld.net
	// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   improved by: kenneth
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// *	 example 1: explode(' ', 'Kevin van Zonneveld');
	// *	 returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
	// +   further improved by: d3x
	// *     example 1: explode('=', 'a=bc=d', 2);
	// *     returns : ['a', 'bc=d']

	var emptyArray = { 0: '' };

	if ( arguments.length != 3
		|| typeof arguments[0] == 'undefined'
		|| typeof arguments[1] == 'undefined'
		|| typeof arguments[2] == 'undefined' )
	{
		return null;
	}

	if ( delimiter === ''
		|| delimiter === false
		|| delimiter === null )
	{
		return false;
	}

	if ( typeof delimiter == 'function'
		|| typeof delimiter == 'object'
		|| typeof string == 'function'
		|| typeof string == 'object' )
	{
		return emptyArray;
	}

	if ( delimiter === true ) {
		delimiter = '1';
	}
	if(!limit){
 		return string.toString().split ( delimiter.toString() );
	} else {
		var splitted = string.toString().split(delimiter.toString());
		var partA = splitted.splice(0, limit - 1);
		var partB = splitted.join(delimiter.toString());
		partA.push(partB);
		return partA;
	}
}

u24

on 2008-02-06 11:00:20

great project.

this one doesn't replicate the optional third $limit parameter which php has though. If I get a spare second I'll add another comment with amended code.

Kevin van Zonneveld

on 2008-02-01 07:57:52

@ kenneth: That was pretty ugly indeed, thanks for contributing, I've updated the source and added your name.

kenneth

on 2008-02-01 06:40:58

This function is wrong. Params are reversed, and return values are not what they would be in PHP.

The &quot;description&quot; above is actually correct, but both the actual source code given and the example given have the params reversed.

As for return values....I might as well just right it out at this point:

function explode( /* delimiter, string */ ) {

	var emptyArray = { 0: '' };

	if ( arguments.length != 2
			|| typeof arguments[0] == 'undefined'
			|| typeof arguments[1] == 'undefined' )
	{
		return null;
	}

	var delimiter = arguments[0];
	var string = arguments[1];

	if ( delimiter === ''
			|| delimiter === false
			|| delimiter === null )
	{
		return false;
	}

	if ( typeof delimiter == 'function'
			|| typeof delimiter == 'object'
			|| typeof string == 'function'
			|| typeof string == 'object' )
	{
		return emptyArray;
	}

	if ( delimiter === true ) {
		delimiter = '1';
	}

	return string.toString().split ( delimiter.toString() );

}


text:
import router from "kinesis-router";
import pipeline from "./pipeline/";

export var handler = router()
    .on("element inserted in collection pod-readings", pipeline);


text:
package hu.webhejj.commons;

/**
 * Like Eclipse's progress monitor, but without that dependency
 */
public interface ProgressMonitor {

	void begin(String name, int max);

	void progress(int amount);

	void done();

	void cancel();

	boolean isCanceled();
}


text:
package dk.bayes.clustergraph.factor

import org.junit._
import org.junit.Assert._
import dk.bayes.clustergraph.testutil.AssertUtil._
import dk.bayes.clustergraph.factor.SingleFactor
import dk.bayes.clustergraph.factor.Var

class SingleFactorTest {

  val factor = new SingleFactor(Var(1, 3), Array(0.3, 0.5, 0.2))

  /**
   * Tests for constructor
   */

  @Test(expected = classOf[IllegalArgumentException]) def create_values_inconsistent_with_dim_size:Unit = {
    SingleFactor(Var(1, 2), Array(0.3, 0.5, 0.2))
  }

  /**
   * Tests for getVariable() and getVariables() methods.
   */

  @Test def getVariable = assertEquals(Var(1, 3), factor.getVariable)

  @Test def getVariables = assertEquals(Array(Var(1, 3)).toList, factor.getVariables.toList)

  /**
   * Tests for getValue() and getValues() methods.
   */

  @Test(expected = classOf[IllegalArgumentException]) def getValue_empty_assignment:Unit = {
    factor.getValue(Array())
  }

  @Test(expected = classOf[IllegalArgumentException]) def getValue_multiple_assignments:Unit = {
    factor.getValue(Array(1, 2))
  }

  @Test(expected = classOf[ArrayIndexOutOfBoundsException]) def getValue_assignment_value_out_of_range:Unit = {
    factor.getValue(Array(3))
  }

  @Test def getValue = assertEquals(0.2, factor.getValue(Array(2)), 0)

  @Test def getValues = assertEquals(Array(0.3, 0.5, 0.2).toList, factor.getValues.toList)

  /**
   * Tests for product() method.
   */
  @Test(expected = classOf[IllegalArgumentException]) def product_factor_variable_ids_not_consistent:Unit = {
    val thatFactor = SingleFactor(Var(2, 3), Array(0.3, 0.5, 0.2))
    factor.product(thatFactor)
  }

  @Test(expected = classOf[IllegalArgumentException]) def product_factor_variable_dimensions_not_consistent:Unit = {
    val thatFactor = SingleFactor(Var(1, 2), Array(0.3, 0.5))
    factor.product(thatFactor)
  }

  @Test def product:Unit = {
    val thatFactor = new SingleFactor(Var(1, 3), Array(0.4, 0.1, 0.5))
    val factorProduct = factor.product(thatFactor)

    assertFactor(SingleFactor(Var(1, 3), Array(0.12, 0.05, 0.1)), factorProduct)
  }

  /**
   * Tests for withEvidence() method.
   */
  @Test(expected = classOf[IllegalArgumentException]) def withEvidence_variable_not_found:Unit = {
    factor.withEvidence(5, 1)
  }

  @Test(expected = classOf[ArrayIndexOutOfBoundsException]) def withEvidence_variable_value_index_out_of_range:Unit = {
    factor.withEvidence(1, 3)
  }

  @Test def withEvidence:Unit = {

    val factorWithEvidence = factor.withEvidence(1, 2)

    assertFactor(SingleFactor(Var(1, 3), Array(0, 0, 0.2)), factorWithEvidence)
  }

  /**
   * Tests for marginal() method.
   */

  @Test(expected = classOf[IllegalArgumentException]) def marginal_variable_not_found:Unit = {
    factor.marginal(5)
  }

  @Test def marginal = assertFactor(factor, factor.marginal(1))

  /**
   * Tests for normalise() method.
   */

  @Test def normalise_already_normalised:Unit = {

    val factor = SingleFactor(Var(1, 3), Array(0.3, 0.5, 0.2))
    val normalisedFactor = factor.normalise()

    assertFactor(factor, normalisedFactor)
  }

  @Test def normalise:Unit = {

    val factor = SingleFactor(Var(1, 3), Array(0.3, 0, 0.2))
    val normalisedFactor = factor.normalise()

    assertFactor(SingleFactor(Var(1, 3), Array(0.6, 0, 0.4)), normalisedFactor)
  }

  /**
   * Tests for mapAssignments
   */

  @Test def mapAssignments:Unit = {
    val factor = SingleFactor(Var(1, 3), Array(0.3, 0.5, 0.2))

    val assignments = factor.mapAssignments(a => a(0) + 5)

    assertEquals(List(5, 6, 7), assignments.toList)
  }
}


text:
@import UIKit;
@import ListerKit;

@interface AAPLCheckBoxCell : UITableViewCell

@property (weak) IBOutlet UILabel *label;
@property (weak) IBOutlet AAPLCheckBox *checkBox;

@end


text:
package sless

import ast._

// TODO: Mixin
// TODO: LessAST
object LessCSSParser extends sless.CSSParser {

  def constantName = "@[a-zA-Z_][a-zA-Z0-9_-]*".r
  def constantDef: Parser[Constant] = constantName ~ (":" ~> term <~ ";") ^^ { case name ~ term => Constant(name, term) }

  def lessStylesheet = opt(charset_rule) ~ rep(import_rule) ~
    rep( media | page | font_face | ruleset | constantDef) ^^ {
    case charset ~ imports ~ rules => LessStylesheet(charset, imports.map(Import(_)), rules)
  }

}


text: sudo -u ca openssl ca -config CA.cnf -revoke $1


text:
package com.blazebit.persistence.view.processor.convert;

import com.blazebit.persistence.view.processor.Context;

import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import java.util.Map;

/**
 * A contract for a converter to convert between an entity view model type and an underlying type.
 *
 * @author Christian Beikov
 * @since 1.6.0
 */
public interface TypeConverter {

    /**
     * Add the converter registrations for this converter.
     *
     * @param converters The map to register to
     */
    public void addRegistrations(Map<String, Map<String, TypeConverter>> converters);

    /**
     * Extract the underlying type from the declared type.
     * The owning class is the concrete entity view class which contains a field or method of the declared type.
     *
     * @param owningClass The class owning the declared type
     * @param declaredType The declared type as present in the entity view model
     * @param context The annotation processor context
     * @return The actual underlying type
     */
    public String getUnderlyingType(DeclaredType owningClass, TypeMirror declaredType, Context context);
}


text:
from sklearn.externals import joblib
import glob
import re
import matplotlib.pyplot as plt
import numpy as np

def plot_cm(cm, acc, targets, title="Confusion Matrix", cmap=plt.cm.Blues, norm=True):
    if(norm):
        cm = cm.astype(float)/cm.sum(axis=1)[:, np.newaxis]
    fig = plt.figure()
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title + ' Acc: ' + str(round(acc,2)))
    plt.colorbar()

    tick_marks = np.arange(len(targets))
    plt.xticks(tick_marks, targets, rotation=45)
    plt.yticks(tick_marks, targets)

    plt.ylabel('True Label')
    plt.xlabel('Predicted Label')

    # plt.show()

    fig.savefig(title + '.png')

    plt.close()

for f in glob.glob('result*.pkl'):
   res = joblib.load(f)
   clf_name = re.search('(?<=result)\w+(?=.pkl)', f).group(0)
   print clf_name
   plot_cm(res['tot_cm'], res['result']['overall_accuracy'], res['result']['class_wise_accuracy'].keys(), title='Clf: '+clf_name)


text:
export class ErrorResponse {

  errorCode: String;
  errorMessage:String;
  devErrorMessage:String;
  validationErrors:Array<ValidationError>;
}

export class ValidationError {
  field:String;
  message:String;
}


text:
#ifndef QPID_CLIENT_MESSAGEIMPL_H
#define QPID_CLIENT_MESSAGEIMPL_H

#include "qpid/client/Message.h"
#include "qpid/client/Session.h"
#include "qpid/framing/MessageTransferBody.h"
#include "qpid/framing/TransferContent.h"
#include <string>

namespace qpid {
namespace client {

class MessageImpl : public framing::TransferContent
{
public:
    /** Create a Message.
     *@param data Data for the message body.
     *@param routingKey Passed to the exchange that routes the message.
     */
    MessageImpl(const std::string& data=std::string(),
            const std::string& routingKey=std::string());

    /** The destination of messages sent to the broker is the exchange
     * name.  The destination of messages received from the broker is
     * the delivery tag identifyig the local subscription (often this
     * is the name of the subscribed queue.)
     */
    std::string getDestination() const;

    /** Check the redelivered flag. */
    bool isRedelivered() const;
    /** Set the redelivered flag. */
    void setRedelivered(bool redelivered);

    /** Get a modifyable reference to the message headers. */
    framing::FieldTable& getHeaders();

    /** Get a non-modifyable reference to the message headers. */
    const framing::FieldTable& getHeaders() const;

    ///@internal
    const framing::MessageTransferBody& getMethod() const;
    ///@internal
    const framing::SequenceNumber& getId() const;

    /**@internal for incoming messages */
    MessageImpl(const framing::FrameSet& frameset);

    static MessageImpl* get(Message& m) { return m.impl; }
    static const MessageImpl* get(const Message& m) { return m.impl; }

private:
    //method and id are only set for received messages:
    framing::MessageTransferBody method;
    framing::SequenceNumber id;
};

}}

#endif  /*!QPID_CLIENT_MESSAGEIMPL_H*/


text:
from __future__ import print_function
import os
import numpy as np
import json
import math
import sys
from scipy.spatial import distance
from scipy import spatial
import cv2
import argparse
import utils
from bounding_box import BoundingBox
import pyximport
pyximport.install()
import cv_wrap_module
datadir, imgdir, workdir, outdir = os.getcwd(), os.getcwd(), os.getcwd(), os.getcwd()

def get_image_top_left(ts, tile_index):
    xloc = ts[tile_index]["bbox"][0]
    yloc = ts[tile_index]["bbox"][2]
    return [xloc, yloc]

def get_mfov_centers_from_json(indexed_ts):
    mfov_centers = {}
    for mfov in indexed_ts.keys():
        tile_bboxes = []
        mfov_tiles = indexed_ts[mfov].values()
        tile_bboxes = zip(*[tile["bbox"] for tile in mfov_tiles])
        min_x = min(tile_bboxes[0])
        max_x = max(tile_bboxes[1])
        min_y = min(tile_bboxes[2])
        max_y = max(tile_bboxes[3])
        # center = [(min_x + min_y) / 2.0, (min_y + max_y) / 2.0], but w/o overflow
        mfov_centers[mfov] = np.array([(min_x / 2.0 + max_x / 2.0, min_y / 2.0 + max_y / 2.0)])
    return mfov_centers

def get_best_transformations(pre_mfov_matches):
    """Returns a dictionary that maps an mfov number to a matrix that best describes the transformation to the other section.
       As not all mfov's may be matched, some mfovs will be missing from the dictionary"""
    transforms = {}
    for m in pre_mfov_matches["matches"]:
        transforms[m["mfov1"]] = m["transformation"]["matrix"]
    return transforms

def find_best_mfov_transformation(mfov, best_transformations, mfov_centers):
    """Returns a matrix that represnets the best transformation for a given mfov to the other section"""
    if mfov in best_transformations.keys():
        return best_transformations[mfov]
    # Need to find a more intelligent way to do this, but this suffices for now
    # Uses transformation of another mfov (should be changed to the closest, unvisited mfov)
    mfov_center = mfov_centers[mfov]
    trans_keys = best_transformations.keys()
    closest_mfov_index = np.argmin([distance.euclidean(mfov_center, mfov_centers[mfovk]) for mfovk in trans_keys])
    # ** Should we add this transformation? maybe not, because we don't want to get a different result when a few
    # ** missing mfov matches occur and the "best transformation" can change when the centers are updated
    return best_transformations[trans_keys[closest_mfov_index]]

def get_tile_centers_from_json(ts):
    tiles_centers = []
    for tile in ts:
        center_x = (tile["bbox"][0] + tile["bbox"][1]) / 2.0
        center_y = (tile["bbox"][2] + tile["bbox"][3]) / 2.0
        tiles_centers.append(np.array([center_x, center_y]))
    return tiles_centers

def get_closest_index_to_point(point, centerstree):
    distanc, closest_index = centerstree.query(point)
    return closest_index

def get_img_matches(ts1, tile_centers1, ts2, tile_centers2, best_transformations, mfov_centers1):
    """For each tile in section1 find the closest 10 tiles in the second image (after applying the preliminary transformation)"""
    img_matches = []

    # TODO - Build a kd-tree of section2 centers

    # Iterate over the first section tiles, and get the approximated location on section 2 (after transformation)
    # and then get the closest 10 tiles (according to their centers) to that location
    for ind1, tile1 in enumerate(ts1):
        center1 = tile_centers1[ind1]
        trans_matrix = find_best_mfov_transformation(tile1["mfov"], best_transformations, mfov_centers1)
        expected_new_center = np.array(np.dot(trans_matrix, np.append(center1, [1]))[0:2])
        distances_to_sec2_mfovs = [np.linalg.norm(expected_new_center - tile_center) for tile_center in tile_centers2]
        closest_indices = np.array(distances_to_sec2_mfovs).argsort()[0:10]
        img_matches.append(closest_indices)

    return img_matches

def is_point_in_img(tile_ts, point):
    """Returns True if the given point lies inside the image as denoted by the given tile_tilespec"""
    # TODO - instead of checking inside the bbox, need to check inside the polygon after transformation
    img_bbox = tile_ts["bbox"]

    if point[0] > img_bbox[0] and point[1] > img_bbox[2] and \
       point[0] < img_bbox[1] and point[1] < img_bbox[3]:
        return True
    return False

def get_images_from_indices_and_point(ts, img_indices, point):
    """Returns all the images at the given img_indices that are overlapping with the given point"""
    img_arr = []
    for img_ind in img_indices:
        if is_point_in_img(ts[img_ind], point):
            img_url = ts[img_ind]["mipmapLevels"]["0"]["imageUrl"]
            img_url = img_url.replace("file://", "")
            img = cv2.imread(img_url, 0)
            img_arr.append((img, img_ind))
    return img_arr

def get_images_indices_from_indices_and_point(ts, img_indices, point):
    """Returns all the images at the given img_indices that are overlapping with the given point"""
    img_arr = []
    for img_ind in img_indices:
        if is_point_in_img(ts[img_ind], point):
            img_arr.append(img_ind)
    return img_arr

def get_template_from_img_and_point(img1resized, template_size, centerpoint):
    imgheight = img1resized.shape[1]
    imgwidth = img1resized.shape[0]
    notonmesh = False

    xstart = centerpoint[0] - template_size / 2
    ystart = centerpoint[1] - template_size / 2
    xend = centerpoint[0] + template_size / 2
    yend = centerpoint[1] + template_size / 2

    if (xstart < 0):
        xend = 1 + xstart
        xstart = 1
        notonmesh = True
    if (ystart < 0):
        yend = 1 + ystart
        ystart = 1
        notonmesh = True
    if (xend >= imgwidth):
        diff = xend - imgwidth
        xstart -= diff + 1
        xend -= diff + 1
        notonmesh = True
    if (yend >= imgwidth):
        diff = yend - imgwidth
        ystart -= diff + 1
        yend -= diff + 1
        notonmesh = True

    if (xstart < 0) or (ystart < 0) or (xend >= imgwidth) or (yend >= imgheight):
        return None
    return (img1resized[xstart:(xstart + template_size), ystart:(ystart + template_size)].copy(), xstart, ystart, notonmesh)

def get_blank_template_from_img_and_point(imgwidth, imgheight, template_size, centerpoint):
    notonmesh = False

    xstart = centerpoint[0] - template_size / 2
    ystart = centerpoint[1] - template_size / 2
    xend = centerpoint[0] + template_size / 2
    yend = centerpoint[1] + template_size / 2

    if (xstart < 0):
        xend = 1 + xstart
        xstart = 1
        notonmesh = True
    if (ystart < 0):
        yend = 1 + ystart
        ystart = 1
        notonmesh = True
    if (xend >= imgwidth):
        diff = xend - imgwidth
        xstart -= diff + 1
        xend -= diff + 1
        notonmesh = True
    if (yend >= imgwidth):
        diff = yend - imgwidth
        ystart -= diff + 1
        yend -= diff + 1
        notonmesh = True

    if (xstart < 0) or (ystart < 0) or (xend >= imgwidth) or (yend >= imgheight):
        return None
    return (xstart, ystart, template_size, template_size, notonmesh)

def generatehexagonalgrid(boundingbox, spacing):
    hexheight = spacing
    hexwidth = math.sqrt(3) * spacing / 2
    vertspacing = 0.75 * hexheight
    horizspacing = hexwidth
    sizex = int((boundingbox[1] - boundingbox[0]) / horizspacing) + 2
    sizey = int((boundingbox[3] - boundingbox[2]) / vertspacing) + 2
    if sizey % 2 == 0:
        sizey += 1
    pointsret = []
    for i in range(-2, sizex):
        for j in range(-2, sizey):
            xpos = i * spacing
            ypos = j * spacing
            if j % 2 == 1:
                xpos += spacing * 0.5
            if (j % 2 == 1) and (i == sizex - 1):
                continue
            pointsret.append([int(xpos), int(ypos)])
    return pointsret

def match_layers_pmcc_matching(tiles_fname1, tiles_fname2, pre_matches_fname, out_fname, conf_fname=None):
    params = utils.conf_from_file(conf_fname, 'MatchLayersBlockMatching')
    if params is None:
        params = {}
    cv_wrap_module.setNumThreads(1)

    # Parameters for the matching
    hex_spacing = params.get("hexspacing", 500)
    scaling = params.get("scaling", 0.2)
    template_size = params.get("template_size", 200)
    template_size *= scaling

    # Read the tilespecs
    ts1 = utils.load_tilespecs(tiles_fname1)
    ts2 = utils.load_tilespecs(tiles_fname2)
    indexed_ts1 = utils.index_tilespec(ts1)

    # Get the tiles centers for each section
    tile_centers1 = get_tile_centers_from_json(ts1)
    tile_centers1tree = spatial.KDTree(tile_centers1)
    tile_centers2 = get_tile_centers_from_json(ts2)
    mfov_centers1 = get_mfov_centers_from_json(indexed_ts1)

    # Load the preliminary matches
    with open(pre_matches_fname, 'r') as data_matches:
        mfov_pre_matches = json.load(data_matches)

    # Generate an hexagonal grid according to the first section's bounding box
    bb = BoundingBox.read_bbox(tiles_fname1)
    hexgr = generatehexagonalgrid(bb, hex_spacing)

    if len(mfov_pre_matches["matches"]) == 0:
        print("No matches were found in pre-matching")
        return

    best_transformations = get_best_transformations(mfov_pre_matches)
    img_matches = get_img_matches(ts1, tile_centers1, ts2, tile_centers2, best_transformations, mfov_centers1)

    img1_url = ts1[50]["mipmapLevels"]["0"]["imageUrl"]
    img1_url = img1_url.replace("file://", "")
    img1 = cv2.imread(img1_url, 0)
    img1_resized = cv2.resize(img1, (0, 0), fx=scaling, fy=scaling)
    img1width = img1_resized.shape[0]
    img1height = img1_resized.shape[1]

    # Iterate over the hexagonal points and find a match in the second section
    thedictionary = {}
    for i in range(len(hexgr)):
        if i % 1000 == 0 and i > 0:
            print(i)

        # Find the tile image where the point from the hexagonal is in the first section
        img1_ind = get_closest_index_to_point(hexgr[i], tile_centers1tree)
        if img1_ind is None:
            continue
        if not is_point_in_img(ts1[img1_ind], hexgr[i]):
            continue

        # Get expected point of hexgr[i] in the second section
        img1_offset = get_image_top_left(ts1, img1_ind)
        expected_transform = find_best_mfov_transformation(ts1[img1_ind]["mfov"], best_transformations, mfov_centers1)
        img1_template = get_blank_template_from_img_and_point(img1width, img1height, template_size, (np.array(hexgr[i]) - img1_offset) * scaling)
        if img1_template is None:
            continue
        startx, starty, w, h, not_on_mesh = img1_template
        center_point1 = np.array([startx + w / 2, starty + h / 2]) / scaling + img1_offset
        expected_new_center = np.dot(expected_transform, np.append(center_point1, [1]))[0:2]

        img2_inds = img_matches[img1_ind]
        img2s = get_images_indices_from_indices_and_point(ts2, img2_inds, expected_new_center)

        for img2_ind in img2s:
            # Build dictionary here
            if img1_ind in thedictionary:
                newdi = thedictionary[img1_ind]
                if img2_ind in newdi:
                    newdi[img2_ind].append(hexgr[i])
                else:
                    newdi[img2_ind] = []
                    newdi[img2_ind].append(hexgr[i])
            else:
                newdi = {}
                newdi[img2_ind] = []
                newdi[img2_ind].append(hexgr[i])
                thedictionary[img1_ind] = newdi

    with open(out_fname, 'w') as out:
        json.dump(thedictionary, out, indent=4)

    print("Done.")

def main():

    print(sys.argv)
    # Command line parser
    parser = argparse.ArgumentParser(description='Given two tilespecs of two sections, and a preliminary matches list, generates a grid the image, and performs block matching (with PMCC filtering).')
    parser.add_argument('tiles_file1', metavar='tiles_file1', type=str,
                        help='the first layer json file containing tilespecs')
    parser.add_argument('tiles_file2', metavar='tiles_file2', type=str,
                        help='the second layer json file containing tilespecs')
    parser.add_argument('pre_matches_file', metavar='pre_matches_file', type=str,
                        help='a json file that contains the preliminary matches')
    parser.add_argument('-o', '--output_file', type=str,
                        help='an output correspondent_spec file, that will include the matches between the sections (default: ./matches.json)',
                        default='./matches.json')
    parser.add_argument('-c', '--conf_file_name', type=str,
                        help='the configuration file with the parameters for each step of the alignment process in json format (uses default parameters, if not supplied)',
                        default=None)

    args = parser.parse_args()

    match_layers_pmcc_matching(args.tiles_file1, args.tiles_file2,
        args.pre_matches_file, args.output_file,
        conf_fname=args.conf_file_name)

if __name__ == '__main__':
    main()


text:
It's available at [censusindia.gov.in](http://censusindia.gov.in/2011-Documents/PCA_HL_2011_Release.xls). You can pre-download the dataset and place it in the `data` folder, or you can download it from the URL in real-time.

### Overview
The first 4 columns refer to the location for which the data is tabulated. The 5th column is called TRU; it stands for Total, Urban, or Rural. From Column 6 - 85, we have values tabulated. The column header is the variable. For example, the 6th column header is `No_HH_Head`, which has the values for `Number of Household Heads`. A list of all such variables and their definition can be found in the CSV  `india_census/common/primary_abstract_data_variables.csv`

 - State - Two-digit state code
 - District - Three-digit district code inside the specific state
 - Level - If the actual location is India (country), STATE, DISTRICT, SUB-DISTRICT, TOWN, VILLAGE or EB
 - Name - Official Name of the place
 - TRU - Stands for Total, Urban or Rural
 - 6-84 - Data value columns

 #### Raw Data Snippet

|State|District|Level   |Name           |TRU  |No_HH |TOT_HL_P|TOT_HL_M|
|-----|--------|--------|---------------|-----|------|--------|--------|
|00   |000     |India   |India          |Total|449787|1773040 |1046871 |
|00   |000     |India   |India          |Rural|192891|834692  |444450  |
|00   |000     |India   |India          |Urban|256896|938348  |602421  |
|01   |000     |STATE   |JAMMU & KASHMIR|Total|3064  |19047   |10524   |
|01   |000     |STATE   |JAMMU & KASHMIR|Rural|1441  |8199    |4465    |
|01   |000     |STATE   |JAMMU & KASHMIR|Urban|1623  |10848   |6059    |
|01   |001     |DISTRICT|Kupwara        |Total|75    |495     |288     |
|01   |001     |DISTRICT|Kupwara        |Rural|65    |424     |239     |

#### Cleaned Data
As part of the cleaning process, we remove the unwanted columns and then convert the columns into rows. Then add the `StatisticalVariable` column corresponding to census variable and TRU.

Cleaned data [IndiaCensus2011_Primary_Abstract_HouselessPopulation.csv](IndiaCensus2011_Primary_Abstract_HouselessPopulation.csv) will have the following columns.

- census_location_id - indianCensusAreaCode2011
- TRU - TRU
- columnName - census variable name
- StatisticalVariable - statistical variable
- Value - Value for the attribute
- Year - Census year

#### Cleaned Data Snippet

|census_location_id|TRU|columnName|Value          |StatisticalVariable|Year  |
|------------------|---|----------|---------------|-------------------|------|
|0                 |Total|No_HH     |449787         |Count_Household_Houseless|2011  |
|0                 |Rural|No_HH     |192891         |Count_Household_Houseless_Rural|2011  |
|0                 |Urban|No_HH     |256896         |Count_Household_Houseless_Urban|2011  |
|01                |Total|No_HH     |3064           |Count_Household_Houseless|2011  |
|01                |Rural|No_HH     |1441           |Count_Household_Houseless_Rural|2011  |
|01                |Urban|No_HH     |1623           |Count_Household_Houseless_Urban|2011  |
|001               |Total|No_HH     |75             |Count_Household_Houseless|2011  |
|001               |Rural|No_HH     |65             |Count_Household_Houseless_Rural|2011  |

#### MCFs and Template MCFs

- [IndiaCensus2011_Primary_Abstract_HouselessPopulation.mcf](IndiaCensus2011_Primary_Abstract_HouselessPopulation.mcf)
- [IndiaCensus2011_Primary_Abstract_HouselessPopulation.tmcf](IndiaCensus2011_Primary_Abstract_HouselessPopulation.tmcf)

### Import Procedure

The below script will generate; mcf, tmcf and csv files.

`python -m india_census.primary_census_abstract_houseless_population.preprocess`