text:
using System;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudioTools.Project;
using Microsoft.Windows.Design.Host;

namespace PowerShellTools.Project
{
    class PowerShellNonCodeFileNode : CommonNonCodeFileNode
    {
        private DesignerContext _designerContext;
	    private PowerShellFileNode _child;

        public PowerShellNonCodeFileNode(CommonProjectNode root, ProjectElement e)
            : base(root, e)
        {
        }

        protected internal object DesignerContext
        {
            get
            {
                if (_designerContext == null)
                {
                    _designerContext = new DesignerContext();
                    var child = ProjectMgr.FindNodeByFullPath(Url + PowerShellConstants.PS1File) as DependentFileNode;
	                if (child == null) return _designerContext;
	                _child = new PowerShellFileNode(ProjectMgr, child.ItemNode);
					var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
	                var x = componentModel.DefaultExportProvider.GetExports<Func<Func<IWpfTextView>, Func<IWpfTextView>, EventBindingProvider>>("WpfEventProviderFactory").FirstOrDefault();

	                _designerContext.EventBindingProvider = x.Value(GetTextView, _child.GetTextView);
                }
                return _designerContext;
            }
        }

		public override int QueryService(ref Guid guidService, out object result)
        {
	        //
	        // If you have a code dom provider you'd provide it here.
	        if (guidService == typeof(SVSMDCodeDomProvider).GUID)
	        {
		        result = new PowerShellCodeDomProvider();
		        return VSConstants.S_OK;
	        }

			if (guidService == typeof(DesignerContext).GUID && Path.GetExtension(Url)?.Equals(".xaml", StringComparison.OrdinalIgnoreCase) == true)
            {
				// Create a DesignerContext for the XAML designer for this file
				result = DesignerContext;
                return VSConstants.S_OK;
            }

            return base.QueryService(ref guidService, out result);
        }
    }
    }


text:
<?php
namespace Chamilo\Libraries\Format\Form;

use Chamilo\Libraries\Platform\Translation;
use Chamilo\Libraries\Utilities\StringUtilities;

/**
 * This class parsers xml files which describe a dynamic form and builds the elements
 *
 * @package \libraries
 * @author Sven Vanpoucke - Hogeschool Gent
 */
class XmlFormParser
{

    /**
     * **************************************************************************************************************
     * Properties *
     * **************************************************************************************************************
     */

    /**
     * The Formvalidator object which builds the form elements
     *
     * @var FormValidator
     */
    private $form_builder;

    /**
     * The Xml Form Parser Result object that stores the result of this parsed form
     *
     * @var XmlFormParserResult
     */
    private $xml_form_parser_result;

    /**
     * The XPath object to search in the xml structure
     *
     * @var \DOMXPath
     */
    private $dom_xpath;

    /**
     * The connector class to retrieve the form element options
     *
     * @var Object
     */
    private $connector_class;

    /**
     * The context of the form elements, used for translations
     *
     * @param String
     */
    private $context;

    /**
     * The prefix for the elements
     *
     * @var String
     */
    private $prefix;

    /**
     * **************************************************************************************************************
     * Form Element Types *
     * **************************************************************************************************************
     */
    const ELEMENT_TYPE_TEXT = 'text';
    const ELEMENT_TYPE_SELECT = 'select';
    const ELEMENT_TYPE_CHECKBOX = 'checkbox';
    const ELEMENT_TYPE_TOGGLE = 'toggle';
    const ELEMENT_TYPE_RADIO = 'radio';
    const ELEMENT_TYPE_STATIC = 'static';
    const ELEMENT_TYPE_HTML_EDITOR = 'html_editor';
    const ELEMENT_TYPE_GROUP = 'group';
    const ELEMENT_TYPE_HTML = 'html';

    /**
     * **************************************************************************************************************
     * Main functionality *
     * **************************************************************************************************************
     */

    /**
     * Constructor Initializes the form builder
     */
    public function __construct()
    {
        $this->form_builder = new FormValidator();
    }

    /**
     * Parses an xml file to an array of form elements
     *
     * @param String $file_path - The path to the xml file
     * @param String $context - [OPTIONAL] The context - Default common\libraries
     * @param Object $connector_class - [OPTIONAL] The connector class to retrieve the dynamic options
     * @param String $prefix - [OPTIONAL] The prefix for the elements
     * @return XmlFormParserResult
     */
    public function build_elements($file_path, $context = null, $connector_class = null, $prefix = null)
    {
        if (! file_exists($file_path))
        {
            throw new \Exception(Translation::get('PathToXmlFileDoesNotExist'));
        }

        if (! $context)
        {
            $context = __NAMESPACE__;
        }

        $this->set_context($context);
        $this->set_connector_class($connector_class);
        $this->set_prefix($prefix);

        $dom_document = new \DOMDocument();
        $dom_document->load($file_path);

        $this->set_dom_xpath(new \DOMXPath($dom_document));

        $this->parse_categories();

        return $this->get_xml_form_parser_result();
    }

    /**
     * **************************************************************************************************************
     * Parser functionality *
     * **************************************************************************************************************
     */

    /**
     * Parses the categories in the xml file
     */
    protected function parse_categories()
    {
        $category_nodes = $this->get_dom_xpath()->query('//category');
        foreach ($category_nodes as $category_node)
        {
            $this->parse_category_node($category_node);
        }
    }

    /**
     * Handles a single category node
     *
     * @param \DOMElement $category_node
     */
    protected function parse_category_node(\DOMElement $category_node)
    {
        $category_name = $category_node->getAttribute('name');
        $category_name = $this->translate($category_name);

        $this->create_and_add_element('category', $category_name);

        $this->parse_elements_for_category($category_node);

        $this->create_and_add_element('category');
    }

    /**
     * Parses the elements in the xml file for a given category
     *
     * @param \DOMElement $category_node
     */
    protected function parse_elements_for_category(\DOMElement $category_node)
    {
        $element_nodes = $this->get_dom_xpath()->query('element', $category_node);
        foreach ($element_nodes as $element_node)
        {
            $this->parse_element_node($element_node);
        }
    }

    /**
     * Parses a single element node
     *
     * @param \DOMElement $element_node
     */
    protected function parse_element_node(\DOMElement $element_node)
    {
        $element_name = $element_node->getAttribute('name');
        $element_title = $this->translate($element_name);
        $element_type = $element_node->getAttribute('field');
        $default_value = $element_node->getAttribute('default');

        $prefix = $this->get_prefix();

        if ($prefix)
        {
            $element_name = $this->get_prefix() . '[' . $element_name . ']';
        }

        switch ($element_type)
        {
            case self::ELEMENT_TYPE_SELECT :
                $this->create_select_element($element_node, $element_name, $element_title);
                break;
            case self::ELEMENT_TYPE_RADIO :
                $this->create_radio_element($element_node, $element_name, $element_title);
                break;
            case self::ELEMENT_TYPE_CHECKBOX :
                $this->create_checkbox_element($element_node, $element_name, $element_title);
                break;
            case self::ELEMENT_TYPE_TOGGLE :
                $this->create_toggle_element($element_node, $element_name, $element_title);
                break;
            case self::ELEMENT_TYPE_TEXT :
                $this->create_text_element($element_node, $element_name, $element_title);
                break;
            default :
                $this->create_and_add_element($element_type, $element_name, $element_title);
                break;
        }

        $this->get_xml_form_parser_result()->add_default_value($element_name, $default_value);

        $this->parse_validation_rules($element_node, $element_name);
    }

    /**
     * Creates a text element on the form
     *
     * @param \DOMElement $element_node
     * @param String $element_name
     * @param Strings $element_title
     */
    protected function create_text_element($element_node, $element_name, $element_title)
    {
        $element_size = $element_node->getAttribute('size');
        if (! $element_size)
        {
            $element_size = 50;
        }

        $attributes = array('size' => $element_size);

        $this->create_and_add_element(self::ELEMENT_TYPE_TEXT, $element_name, $element_title, $attributes);
    }

    /**
     * Creates a select element on the form
     *
     * @param \DOMElement $element_node
     * @param String $element_name
     * @param String $element_title
     */
    protected function create_select_element($element_node, $element_name, $element_title)
    {
        $element_options = $this->parse_element_options($element_node);
        $this->create_and_add_element(self::ELEMENT_TYPE_SELECT, $element_name, $element_title, $element_options);
    }

    /**
     * Creates a radio buttons element on the form
     *
     * @param \DOMElement $element_node
     * @param String $element_name
     * @param String $element_title
     */
    protected function create_radio_element($element_node, $element_name, $element_title)
    {
        $element_options = $this->parse_element_options($element_node);

        $group_elements = array();

        foreach ($element_options as $option_value => $option_name)
        {
            $group_elements[] = $this->form_builder->createElement(
                self::ELEMENT_TYPE_RADIO,
                $element_name,
                null,
                $option_name,
                $option_value);
        }

        $this->create_and_add_element(
            self::ELEMENT_TYPE_GROUP,
            $element_name,
            $element_title,
            $group_elements,
            '',
            false);
    }

    /**
     * Creates a checkbox element on the form
     *
     * @param \DOMElement $element_node
     * @param string $element_name
     * @param string $element_title
     */
    protected function create_checkbox_element($element_node, $element_name, $element_title)
    {
        $this->create_and_add_element(self::ELEMENT_TYPE_CHECKBOX, $element_name, $element_title, '', null, '1', '0');
    }

    /**
     * Creates a toggle element on the form
     *
     * @param \DOMElement $element_node
     * @param string $element_name
     * @param string $element_title
     */
    protected function create_toggle_element($element_node, $element_name, $element_title)
    {
        $this->create_and_add_element(self::ELEMENT_TYPE_TOGGLE, $element_name, $element_title, '', null, '1', '0');
    }

    /**
     * Parses the options for a given element node
     *
     * @param \DOMElement $element_node
     *
     * @return String[String] - The options
     */
    protected function parse_element_options(\DOMElement $element_node)
    {
        $options_node_list = $this->get_dom_xpath()->query('options', $element_node);
        if ($options_node_list->length == 0)
        {
            return;
        }

        $options_node = $options_node_list->item(0);
        $options_type = $options_node->getAttribute('type');

        if ($options_type == 'dynamic')
        {
            $source = $options_node->getAttribute('source');
            $options = call_user_func(array($this->get_connector_class(), $source));
        }
        else
        {
            $options = array();

            $option_node_list = $this->get_dom_xpath()->query('option', $options_node);
            foreach ($option_node_list as $option_node)
            {
                $option_name = $option_node->getAttribute('name');
                $option_value = $option_node->getAttribute('value');

                $options[$option_value] = $this->translate($option_name);
            }
        }

        return $options;
    }

    /**
     * Parses the validation rules for an element node
     *
     * @param \DOMElement $element_node
     * @param String $element_name
     */
    protected function parse_validation_rules(\DOMElement $element_node, $element_name)
    {
        $required_attribute = $element_node->getAttribute('required');
        if ($required_attribute)
        {
            $this->create_and_add_validation_rule($element_name, Translation::get('ThisFieldIsRequired'), 'required');
        }

        $validation_node_list = $this->get_dom_xpath()->query('validations/validation', $element_node);
        foreach ($validation_node_list as $validation_node)
        {
            $type = $validation_node->getAttribute('rule');
            $message = $validation_node->getAttribute('message');

            $this->create_and_add_validation_rule($element_name, $message, $type);
        }
    }

    /**
     * **************************************************************************************************************
     * Helper functionality *
     * **************************************************************************************************************
     */

    /**
     * Creates an element and adds it to the elements list
     *
     * @param Dynamic Arguments List - Same arguments as in createElement for quickform
     * @return HTML_QuickForm_element
     */
    protected function create_and_add_element()
    {
        $element = call_user_func_array(array($this->form_builder, 'createElement'), func_get_args());

        $this->get_xml_form_parser_result()->add_element($element);

        return $element;
    }

    /**
     * Creates a validation rule with the given parameters and adds it to the result
     *
     * @param String $element - The form element name
     * @param String $message - The message to display
     * @param String $type - The validation rule type
     * @param String $format - [OPTIONAL] The format - Required for extra rule data
     * @param String $validation - [OPTIONAL] The place to execute the validation Server - Client
     * @param boolean $reset - [OPTIONAL] Whether or not to reset the elements on client validation error
     * @param boolean $force - [OPTIONAL] Forces the rule to be applied, even if the element does not exist yet
     */
    protected function create_and_add_validation_rule($element, $message, $type, $format = null, $validation = 'server',
        $reset = false, $force = false)
    {
        $validation_rule = new XmlFormParserValidationRule(
            $element,
            $message,
            $type,
            $format,
            $validation,
            $reset,
            $force);
        $this->get_xml_form_parser_result()->add_validation_rule($validation_rule);
    }

    /**
     * Translates a variable with the global context variable
     *
     * @param String $translation_variable
     * @param String[] $parameters
     *
     * @return String
     */
    protected function translate($translation_variable, $parameters)
    {
        $translation_variable = (string) StringUtilities::getInstance()->createString($translation_variable)->upperCamelize();
        return Translation::get($translation_variable, $parameters, $this->get_context());
    }

    /**
     * Returns a new result object
     *
     * @return XmlFormParserResult
     */
    protected function create_new_xml_form_parser_result()
    {
        return new XmlFormParserResult();
    }

    /**
     * **************************************************************************************************************
     * Getters and setters *
     * **************************************************************************************************************
     */

    /**
     * Returns the xml_form_parser_result object
     *
     * @return XmlFormParserResult
     */
    public function get_xml_form_parser_result()
    {
        if (! isset($this->xml_form_parser_result))
        {
            $this->xml_form_parser_result = $this->create_new_xml_form_parser_result();
        }
        return $this->xml_form_parser_result;
    }

    /**
     * Sets the xml_form_parser_result object
     *
     * @param XmlFormParserResult $xml_form_parser_result
     */
    public function set_xml_form_parser_result(XmlFormParserResult $xml_form_parser_result)
    {
        $this->xml_form_parser_result = $xml_form_parser_result;
    }

    /**
     * Returns the form_builder object
     *
     * @return FormValidator
     */
    public function get_form_builder()
    {
        return $this->form_builder;
    }

    /**
     * Sets the form_builder object
     *
     * @param FormValidator $form_builder
     */
    public function set_form_builder(FormValidator $form_builder)
    {
        $this->form_builder = $form_builder;
    }

    /**
     * Returns the dom_xpath object
     *
     * @return \DOM_XPath
     */
    public function get_dom_xpath()
    {
        return $this->dom_xpath;
    }

    /**
     * Sets the dom_xpath object
     *
     * @param \DOM_XPath $dom_xpath
     */
    public function set_dom_xpath($dom_xpath)
    {
        $this->dom_xpath = $dom_xpath;
    }

    /**
     * Returns the connector_class object
     *
     * @return Object
     */
    public function get_connector_class()
    {
        return $this->connector_class;
    }

    /**
     * Sets the connector_class object
     *
     * @param Object $connector_class
     */
    public function set_connector_class($connector_class)
    {
        $this->connector_class = $connector_class;
    }

    /**
     * Returns the context
     *
     * @return String
     */
    public function get_context()
    {
        return $this->context;
    }

    /**
     * Sets the context
     *
     * @param Strings $context
     */
    public function set_context($context)
    {
        $this->context = $context;
    }

    /**
     * Returns the prefix
     *
     * @return String
     */
    public function get_prefix()
    {
        return $this->prefix;
    }

    /**
     * Sets the prefix
     *
     * @param Strings $prefix
     */
    public function set_prefix($prefix)
    {
        $this->prefix = $prefix;
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * Created by dfsj16111702 on 2017/2/23.
 */
import {Component, Input, ElementRef, Output, EventEmitter} from '@angular/core';
var eCharts = require('echarts/lib/echarts');
var $ = require('jquery');
require('echarts/lib/chart/line');
require('echarts/lib/chart/pie');
// 引入提示框和标题组件
//require('echarts/lib/component');
require('echarts/lib/component/graphic');
require('echarts/lib/component/grid');
require('echarts/lib/component/legend');
require('echarts/lib/component/tooltip');
require('echarts/lib/component/polar');
require('echarts/lib/component/geo');
require('echarts/lib/component/parallel');
require('echarts/lib/component/singleAxis');
require('echarts/lib/component/brush');
require('echarts/lib/component/title');
require('echarts/lib/component/dataZoom');
require('echarts/lib/component/visualMap');
require('echarts/lib/component/markPoint');
require('echarts/lib/component/markLine');
require('echarts/lib/component/markArea');
require('echarts/lib/component/timeline');
require('echarts/lib/component/toolbox');
require('zrender/lib/vml/vml');
@Component({
    selector: 'e-chart',
    templateUrl: './eChart.html'
})

export class eChartComponent {
    @Input('option') options:any = {};
    @Input('type') type:any = '';
    @Input('title') title:any = '';
    @Input('xAxisData') xAxisData:any = [];
    eChart:any;
    //timer:any;
    constructor(private div:ElementRef) {
        //console.log(this.div.nativeElement.childNodes);
        //console.log($(this.div.nativeElement).find('div#eChart'));

    }

    ngAfterViewInit() {
        this.eChart = eCharts.init(this.div.nativeElement.children[0].children[0]);
        let timer = setTimeout(data => {
            this.dataChange();
            //noinspection TypeScriptUnresolvedFunction
            clearTimeout(timer);
        }, 200);

    }

    dataChange() {
        if (this.type == 'pie') {
            let data = [];
            let dataName = [];
            this.options.forEach(function (item) {
                data.push({name: item.name, value: item.value});
                dataName.push(item.name);
            });
            this.getPie(data, dataName);
        } else if (this.type == 'line') {
            let data = [];
            let dataName = [];
            let type = this.type;
            this.options.forEach(function (item) {
                data.push({name: item.name, type: type, data: item.data});
                dataName.push(item.name);
            });
            this.getLine(dataName, data);

        }
    }

    ngOnChanges(a) {
        let timer = setTimeout(data => {
            this.dataChange();
            //noinspection TypeScriptUnresolvedVariable
            clearTimeout(timer);
        }, 200);
    }

    getPie(data, dataName) {
        this.eChart.setOption(<echarts.Option>{
            title: {
                text: this.title,
                x: 'center',
                textStyle: {
                    fontSize: 16,
                    fontWeight: 500,
                    color: '#000',
                    fontFamily: 'Microsoft Yahei',
                }
            },
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b} : {c} ({d}%)",
                confine: true,
            },
            legend: {
                orient: 'vertical',
                left: 'left',
                data: dataName
            },
            series: [
                {
                    name: this.title,
                    type: 'pie',
                    radius: '50%',
                    center: ['50%', '60%'],
                    data: data,
                    hoverAnimation: true,
                    animationType: 'expansion',
                    animation: true,
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    },
                    color: ['#4285f4', '#ea4335', '#fbbc05']
                }
            ]
        });
    }

    getLine(dataName, seriesData) {
        this.eChart.setOption(<echarts.Option>{
            title: {
                text: this.title
            },
            tooltip: {
                trigger: 'axis',
                confine: true
            },
            legend: {
                data: dataName,
                bottom: "-5"
            },
            grid: {
                left: '5%',
                right: '4%',
                bottom: '8%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: this.xAxisData,
                axisLabel: {
                    margin: -20,
                    inside: true
                }
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    margin: -45,
                    inside: true
                }
            },
            series: seriesData
        })
    }

}


text:
DELIMITER /

ALTER TABLE WATERMARK ADD GROUP_NAME VARCHAR(20)
/

ALTER TABLE WATERMARK DROP INDEX WATERMARK_UK1
/

DELIMITER ;


text:
/* multiple classes */

class mainclass
{
   public static void main( String[] trash )
   {
      System.out.println( 43110 );
   }
}

class secondClass
{
   int field;

   public int plus( int a, int b )
   {
      return a + b;
   }
}

class thirdClass
{
   public int three()
   {
      return 3;
   }
}


text:
<!doctype html>

        <meta charset="utf-8">
        <title>NYT React App</title>
        <meta name="description" content="Desctiption of 4 thousand footer project">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/initialize.css">
        <link rel="stylesheet" type="text/css" href="css/grid.css">
        <link rel="stylesheet" href="css/main.css">

        <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
        <link href='https://fonts.googleapis.com/css?family=Lora' rel='stylesheet' type='text/css'>

New York Times React App

            Github Link

Skills: ReactJs

A basic React app that uses the NYT API to get stories from the past 7 days. Then it infinitely scrolls through stories calling for the next 10 when you get near the bottom of the list.

Also includes a search functionality. Minimal styles for the time being. Full working site hosted in the near future, for now just the github code.


text:
<!doctype html>

  <meta charset="UTF-8" />
  <link rel="stylesheet" type="text/css" href="/public/stylesheets/projects.css">
  <link rel="stylesheet" type="text/css" href="/public/stylesheets/default.css">
  <title>LeeAnne Hawley</title>

LeeAnne Hawley

Projects

About Me

Resume

Professional Portfolio

Side Projects

LeeAnne Hawley |

        hawleyleeanne@gmail.com

| 603-845-6849


text:
* Leonhard Campo
*
* 2017
* not determined yet


text:
package dbr

import (
	"bytes"
	"database/sql"
	"encoding/json"
	"time"

	"github.com/go-sql-driver/mysql"
)

//
// Your app can use these Null types instead of the defaults. The sole benefit you get is a MarshalJSON method that is not retarded.
//

// NullString is a type that can be null or a string
type NullString struct {
	sql.NullString
}

// NullFloat64 is a type that can be null or a float64
type NullFloat64 struct {
	sql.NullFloat64
}

// NullInt64 is a type that can be null or an int
type NullInt64 struct {
	sql.NullInt64
}

// NullTime is a type that can be null or a time
type NullTime struct {
	mysql.NullTime
}

// NullBool is a type that can be null or a bool
type NullBool struct {
	sql.NullBool
}

var nullString = []byte("null")

// MarshalJSON correctly serializes a NullString to JSON
func (n *NullString) MarshalJSON() ([]byte, error) {
	if n.Valid {
		j, e := json.Marshal(n.String)
		return j, e
	}
	return nullString, nil
}

// MarshalJSON correctly serializes a NullInt64 to JSON
func (n *NullInt64) MarshalJSON() ([]byte, error) {
	if n.Valid {
		j, e := json.Marshal(n.Int64)
		return j, e
	}
	return nullString, nil
}

// MarshalJSON correctly serializes a NullFloat64 to JSON
func (n *NullFloat64) MarshalJSON() ([]byte, error) {
	if n.Valid {
		j, e := json.Marshal(n.Float64)
		return j, e
	}
	return nullString, nil
}

// MarshalJSON correctly serializes a NullTime to JSON
func (n *NullTime) MarshalJSON() ([]byte, error) {
	if n.Valid {
		j, e := json.Marshal(n.Time)
		return j, e
	}
	return nullString, nil
}

// MarshalJSON correctly serializes a NullBool to JSON
func (n *NullBool) MarshalJSON() ([]byte, error) {
	if n.Valid {
		j, e := json.Marshal(n.Bool)
		return j, e
	}
	return nullString, nil
}

// UnmarshalJSON correctly deserializes a NullString from JSON
func (n *NullString) UnmarshalJSON(b []byte) error {
	var s interface{}
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	return n.Scan(s)
}

// UnmarshalJSON correctly deserializes a NullInt64 from JSON
func (n *NullInt64) UnmarshalJSON(b []byte) error {
	var s int64
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	return n.Scan(s)
}

// UnmarshalJSON correctly deserializes a NullFloat64 from JSON
func (n *NullFloat64) UnmarshalJSON(b []byte) error {
	var s interface{}
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	return n.Scan(s)
}

// UnmarshalJSON correctly deserializes a NullTime from JSON
func (n *NullTime) UnmarshalJSON(b []byte) error {
	// scan for null
	if bytes.Equal(b, nullString) {
		return n.Scan(nil)
	}
	// scan for JSON timestamp
	var t time.Time
	if err := json.Unmarshal(b, &t); err != nil {
		return err
	}
	return n.Scan(t)
}

// UnmarshalJSON correctly deserializes a NullBool from JSON
func (n *NullBool) UnmarshalJSON(b []byte) error {
	var s interface{}
	if err := json.Unmarshal(b, &s); err != nil {
		return err
	}
	return n.Scan(s)
}


text:
package io.myweb.camera;

import android.app.Activity;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.TextureView;
import android.view.View;
import android.view.Window;

import com.android.grafika.AspectFrameLayout;
import com.android.grafika.CameraUtils;

import java.io.IOException;

import io.myweb.LocalService;

public class CaptureCameraActivity extends Activity implements LocalService.ConnectionListener<Streaming> {
	private static final String LOG_TAG = CaptureCameraActivity.class.getName();

	private Camera mCamera;
	private TextureView mTextureView;
	private int mCameraPreviewWidth;
	private int mCameraPreviewHeight;
	private volatile boolean portraitMode = false;
	private LocalService.Connection<Streaming> streamingConnection;
	private SurfaceTexture mSurfaceTexture;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_capture_camera);

		mTextureView = (TextureView) findViewById(R.id.textureView);
		mTextureView.setSurfaceTextureListener(createSurfaceTextureListener());
		mTextureView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});

		streamingConnection = StreamingService.connection(this).withListener(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		streamingConnection.close();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if(streamingConnection.getService()!=null) {
			streamingConnection.getService().startStreaming(mCamera);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if(streamingConnection.getService()!=null) {
			streamingConnection.getService().stopStreaming();
		}
	}

	private TextureView.SurfaceTextureListener createSurfaceTextureListener() {
		return new TextureView.SurfaceTextureListener() {

			@Override
			public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) {
				portraitMode = (width < height);
				onCameraSurfaceTextureAvailable(surfaceTexture, 640, 480);
			}

			@Override
			public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int width, int height) {
			}

			@Override
			public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
				return onCameraSurfaceTextureDestroyed(surfaceTexture);
			}

			@Override
			public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
			}

		};
	};

	private void onCameraSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
		mSurfaceTexture = surface;
		openCamera(width, height);

		// Set the preview aspect ratio.
		AspectFrameLayout layout = (AspectFrameLayout) findViewById(R.id.cameraPreview_afl);
		layout.setAspectRatio((double) mCameraPreviewWidth / mCameraPreviewHeight);

		try {
			mCamera.setPreviewTexture(surface);
			mCamera.startPreview();
		} catch (IOException ex) {
			Log.e(LOG_TAG, ex.getMessage(), ex);
		}
		new Handler(Looper.getMainLooper()).post(new Runnable() {
			@Override
			public void run() {
				streamingConnection.getService().startStreaming(mCamera);
			}
		});
	}

	private boolean onCameraSurfaceTextureDestroyed(SurfaceTexture surface) {
		mSurfaceTexture = null;
		releaseCamera();
		return true;
	}

	/**
	 * This is basicly copied as-is from grafika example
	 *
	 * Opens a camera, and attempts to establish preview mode at the specified width and height.
	 * <p>
	 * Sets mCameraPreviewWidth and mCameraPreviewHeight to the actual width/height of the preview.
	 */
	private void openCamera(int desiredWidth, int desiredHeight) {
		if (mCamera != null) {
			throw new RuntimeException("Camera already initialized");
		}
		Camera.CameraInfo info = new Camera.CameraInfo();
// Try to find a front-facing camera (e.g. for videoconferencing).
		int numCameras = Camera.getNumberOfCameras();
		for (int i = 0; i < numCameras; i++) {
			Camera.getCameraInfo(i, info);
			if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
				mCamera = Camera.open(i);
				if(portraitMode) mCamera.setDisplayOrientation(90);
				break;
			}
		}
		if (mCamera == null) {
			Log.d(LOG_TAG, "No front-facing camera found; opening default");
			mCamera = Camera.open(); // opens first back-facing camera
		}
		if (mCamera == null) {
			throw new RuntimeException("Unable to open camera");
		}
		Camera.Parameters parms = mCamera.getParameters();
		CameraUtils.choosePreviewSize(parms, desiredWidth, desiredHeight);
// Give the camera a hint that we're recording video. This can have a big
// impact on frame rate.
		parms.setRecordingHint(true);
// leave the frame rate set to default
		mCamera.setParameters(parms);
		int[] fpsRange = new int[2];
		Camera.Size mCameraPreviewSize = parms.getPreviewSize();
		parms.getPreviewFpsRange(fpsRange);
		String previewFacts = mCameraPreviewSize.width + "x" + mCameraPreviewSize.height;
		if (fpsRange[0] == fpsRange[1]) {
			previewFacts += " @" + (fpsRange[0] / 1000.0) + "fps";
		} else {
			previewFacts += " @[" + (fpsRange[0] / 1000.0) +
					" - " + (fpsRange[1] / 1000.0) + "] fps";
		}
		Log.d(LOG_TAG, previewFacts);
//		TextView text = (TextView) findViewById(R.id.cameraParams_text);
//		text.setText(previewFacts);
		if(portraitMode) {
			mCameraPreviewWidth = mCameraPreviewSize.height;
			mCameraPreviewHeight = mCameraPreviewSize.width;
		} else {
			mCameraPreviewWidth = mCameraPreviewSize.width;
			mCameraPreviewHeight = mCameraPreviewSize.height;
		}
		Log.d(LOG_TAG, "openCamera -- done");
	}

	/**
	 * Stops camera preview, and releases the camera to the system.
	 */
	private void releaseCamera() {
		if (mCamera != null) {
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
			Log.d(LOG_TAG, "releaseCamera -- done");
		}
	}

	@Override
	public void onServiceConnected(Streaming service) {
		Log.d(LOG_TAG, "Streaming service connected");
	}

	@Override
	public void onServiceDisconnected(Streaming service) {
		Log.d(LOG_TAG, "Streaming service disconnected");
	}

}


text:
"""Sub class Bunch to represent an IDF object.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import copy
import itertools

from munch import Munch as Bunch

from eppy.bunchhelpers import matchfieldnames, scientificnotation, makefieldname
import eppy.function_helpers as fh
import eppy.ext_field_functions as extff

class BadEPFieldError(AttributeError):
    """An Exception"""

    pass

class RangeError(ValueError):
    """An Exception"""

    pass

def almostequal(first, second, places=7, printit=True):
    """
    Test if two values are equal to a given number of places.
    This is based on python's unittest so may be covered by Python's
    license.

    """
    if first == second:
        return True

    if round(abs(second - first), places) != 0:
        if printit:
            print(round(abs(second - first), places))
            print("notalmost: %s != %s to %i places" % (first, second, places))
        return False
    else:
        return True

def somevalues(ddtt):
    """returns some values"""
    return ddtt.Name, ddtt.Construction_Name, ddtt.obj

def extendlist(lst, i, value=""):
    """extend the list so that you have i-th value"""
    if i < len(lst):
        pass
    else:
        lst.extend([value] * (i - len(lst) + 1))

def return42(self, *args, **kwargs):
    # proof of concept - to be removed
    return 42

def addfunctions(abunch):
    """add functions to epbunch"""

    key = abunch.obj[0].upper()

    # -----------------
    # TODO : alternate strategy to avoid listing the objkeys in snames
    # check if epbunch has field "Zone_Name" or "Building_Surface_Name"
    # and is in group u'Thermal Zones and Surfaces'
    # then it is likely to be a surface.
    # of course we need to recode for surfaces that do not have coordinates :-(
    # or we can filter those out since they do not have
    # the field "Number_of_Vertices"
    snames = [
        "BuildingSurface:Detailed",
        "Wall:Detailed",
        "RoofCeiling:Detailed",
        "Floor:Detailed",
        "FenestrationSurface:Detailed",
        "Shading:Site:Detailed",
        "Shading:Building:Detailed",
        "Shading:Zone:Detailed",
    ]
    snames = [sname.upper() for sname in snames]
    if key in snames:
        func_dict = {
            "area": fh.area,
            "height": fh.height,  # not working correctly
            "width": fh.width,  # not working correctly
            "azimuth": fh.azimuth,
            "true_azimuth": fh.true_azimuth,
            "tilt": fh.tilt,
            "coords": fh.getcoords,  # needed for debugging
        }
        abunch.__functions.update(func_dict)

    # -----------------
    # print(abunch.getfieldidd )
    names = [
        "CONSTRUCTION",
        "MATERIAL",
        "MATERIAL:AIRGAP",
        "MATERIAL:INFRAREDTRANSPARENT",
        "MATERIAL:NOMASS",
        "MATERIAL:ROOFVEGETATION",
        "WINDOWMATERIAL:BLIND",
        "WINDOWMATERIAL:GLAZING",
        "WINDOWMATERIAL:GLAZING:REFRACTIONEXTINCTIONMETHOD",
        "WINDOWMATERIAL:GAP",
        "WINDOWMATERIAL:GAS",
        "WINDOWMATERIAL:GASMIXTURE",
        "WINDOWMATERIAL:GLAZINGGROUP:THERMOCHROMIC",
        "WINDOWMATERIAL:SCREEN",
        "WINDOWMATERIAL:SHADE",
        "WINDOWMATERIAL:SIMPLEGLAZINGSYSTEM",
    ]
    if key in names:
        func_dict = {
            "rvalue": fh.rvalue,
            "ufactor": fh.ufactor,
            "rvalue_ip": fh.rvalue_ip,  # quick fix for Santosh. Needs to thought thru
            "ufactor_ip": fh.ufactor_ip,  # quick fix for Santosh. Needs to thought thru
            "heatcapacity": fh.heatcapacity,
        }
        abunch.__functions.update(func_dict)

    names = [
        "FAN:CONSTANTVOLUME",
        "FAN:VARIABLEVOLUME",
        "FAN:ONOFF",
        "FAN:ZONEEXHAUST",
        "FANPERFORMANCE:NIGHTVENTILATION",
    ]
    if key in names:
        func_dict = {
            "f_fanpower_bhp": fh.fanpower_bhp,
            "f_fanpower_watts": fh.fanpower_watts,
            "f_fan_maxcfm": fh.fan_maxcfm,
        }
        abunch.__functions.update(func_dict)
    # =====
    # code for references
    # -----------------
    # add function zonesurfaces
    if key == "ZONE":
        func_dict = {"zonesurfaces": fh.zonesurfaces}
        abunch.__functions.update(func_dict)

    # -----------------
    # add function subsurfaces
    # going to cheat here a bit
    # check if epbunch has field "Zone_Name"
    # and is in group u'Thermal Zones and Surfaces'
    # then it is likely to be a surface attached to a zone
    fields = abunch.fieldnames
    try:
        group = abunch.getfieldidd("key")["group"]
    except KeyError as e:  # some pytests don't have group
        group = None
    if group == "Thermal Zones and Surfaces":
        if "Zone_Name" in fields:
            func_dict = {"subsurfaces": fh.subsurfaces}
            abunch.__functions.update(func_dict)

    return abunch

class EpBunch(Bunch):
    """
    Fields, values, and descriptions of fields in an EnergyPlus IDF object
    stored in a `bunch` which is a `dict` extended to allow access to dict
    fields as attributes as well as by keys.

    """

    def __init__(self, obj, objls, objidd, *args, **kwargs):
        super(EpBunch, self).__init__(*args, **kwargs)
        self.obj = obj  # field names
        self.objls = objls  # field values
        self.objidd = objidd  # field metadata (minimum, maximum, type, etc.)
        self.theidf = None  # pointer to the idf this epbunch belongs to
        # This is None if there is no idf - a standalone epbunch
        # This will be set by Idf_MSequence
        self["__functions"] = {}  # initialize the functions
        addfunctions(self)

    @property
    def fieldnames(self):
        """Friendly name for objls."""
        return self.objls

    @property
    def fieldvalues(self):
        """Friendly name for obj."""
        return self.obj

    def checkrange(self, fieldname):
        """Check if the value for a field is within the allowed range."""
        return checkrange(self, fieldname)

    def getrange(self, fieldname):
        """Get the allowed range of values for a field."""
        return getrange(self, fieldname)

    def getfieldidd(self, fieldname):
        """get the idd dict for this field
        Will return {} if the fieldname does not exist"""
        return getfieldidd(self, fieldname)

    def getfieldidd_item(self, fieldname, iddkey):
        """return an item from the fieldidd, given the iddkey
        will return and empty list if it does not have the iddkey
        or if the fieldname does not exist"""
        return getfieldidd_item(self, fieldname, iddkey)

    def get_retaincase(self, fieldname):
        """check if the field should retain case"""
        return get_retaincase(self, fieldname)

    def isequal(self, fieldname, value, places=7):
        """return True if the field == value
        Will retain case if get_retaincase == True
        for real value will compare to decimal 'places'
        """
        return isequal(self, fieldname, value, places=places)

    def getreferingobjs(self, iddgroups=None, fields=None):
        """Get a list of objects that refer to this object"""
        return getreferingobjs(self, iddgroups=iddgroups, fields=fields)

    def get_referenced_object(self, fieldname):
        """
        Get an object referred to by a field in another object.

        For example an object of type Construction has fields for each layer, each
        of which refers to a Material. This functions allows the object
        representing a Material to be fetched using the name of the layer.

        Returns the first item found since if there is more than one matching item,
        it is a malformed IDF.

        Parameters
        ----------
        referring_object : EpBunch
            The object which contains a reference to another object,
        fieldname : str
            The name of the field in the referring object which contains the
            reference to another object.

        Returns
        -------
        EpBunch

        """
        return get_referenced_object(self, fieldname)

    def __setattr__(self, name, value):
        try:
            origname = self["__functions"][name]
            # TODO: unit test never hits here so what is it for?
            self[origname] = value
        except KeyError:
            pass

        try:
            name = self["__aliases"][name]  # get original name of the alias
        except KeyError:
            pass

        if name in ("__functions", "__aliases"):  # just set the new value
            self[name] = value
            return None
        elif name in ("obj", "objls", "objidd", "theidf"):  # let Bunch handle it
            super(EpBunch, self).__setattr__(name, value)
            return None
        elif name in self.fieldnames:  # set the value, extending if needed
            i = self.fieldnames.index(name)
            try:
                self.fieldvalues[i] = value
            except IndexError:
                extendlist(self.fieldvalues, i)
                self.fieldvalues[i] = value
        # elif name_is_extensible(name):
        #     # do one field at a time - mto start with
        #     extendinIDD
        #     do the previous elif
        elif extff.getextensible(self.objidd):  # idfobject has extensible fields
            if extff.islegalextensiblefield(
                self.objidd, name
            ):  # is the field a legal extensible field
                # What is the integer on that field
                name_int = extff.extfieldint(name)
                # get the int in the last extensible field
                last_extfield = self.objidd[-1]["field"][0]
                last_extfield_int = extff.extfieldint(last_extfield, sep=" ")
                # calculate the number of new field sets to be generated
                newextensibles = name_int - last_extfield_int
                # generate the new fileds in eppy's IDD
                key_i = self.theidf.model.dtls.index(self.key)
                mult = extff.getextensible(self.objidd)
                extff.increaseIDDfields(
                    self.theidf.block,
                    self.theidf.idd_info,
                    key_i,
                    self.key,
                    newextensibles * mult,
                )
                # need to update objls and objidd here
                self.objidd = self.theidf.idd_info[key_i]

                objfields = [comm.get("field") for comm in self.objidd]
                objfields[0] = ["key"]
                objfields = [field[0] for field in objfields]
                obj_fields = [makefieldname(field) for field in objfields]
                self.objls = obj_fields
                if name in self.fieldnames:  # set the value, extending if needed
                    i = self.fieldnames.index(name)
                    try:
                        self.fieldvalues[i] = value
                    except IndexError:
                        extendlist(self.fieldvalues, i)
                        self.fieldvalues[i] = value
                else:
                    pass
            else:
                astr = "unable to find field %s" % (name,)
                raise BadEPFieldError(astr)  # TODO: could raise AttributeError
        else:
            astr = "unable to find field %s" % (name,)
            raise BadEPFieldError(astr)  # TODO: could raise AttributeError

    def __getattr__(self, name):
        try:
            func = self["__functions"][name]
            return func(self)
        except KeyError:
            pass

        try:
            name = self["__aliases"][name]
        except KeyError:
            pass

        if name == "__functions":
            return self["__functions"]
        elif name in ("__aliases", "obj", "objls", "objidd", "theidf"):
            # unit test
            return super(EpBunch, self).__getattr__(name)
        elif name in self.fieldnames:
            i = self.fieldnames.index(name)
            try:
                return self.fieldvalues[i]
            except IndexError:
                return ""
        elif extff.getextensible(self.objidd):  # idfobject has extensible fields
            if extff.islegalextensiblefield(
                self.objidd, name
            ):  # is the field a legal extensible field
                # no point creating a field
                return ""
            else:
                astr = "unable to find field %s" % (name,)
                raise BadEPFieldError(astr)  # TODO: could raise AttributeError
                astr = "unable to find field %s" % (name,)
                raise BadEPFieldError(astr)
        else:
            astr = "unable to find field %s" % (name,)
            raise BadEPFieldError(astr)

    def __getitem__(self, key):
        if key in ("obj", "objls", "objidd", "__functions", "__aliases", "theidf"):
            return super(EpBunch, self).__getitem__(key)
        elif key in self.fieldnames:
            i = self.fieldnames.index(key)
            try:
                return self.fieldvalues[i]
            except IndexError:
                return ""
        elif extff.getextensible(self.objidd):  # idfobject has extensible fields
            if extff.islegalextensiblefield(
                self.objidd, key
            ):  # is the field a legal extensible field
                # no point creating a field
                return ""
            else:
                astr = "unable to find field %s" % (key,)
                raise BadEPFieldError(astr)
        else:
            # TODO: Do similar strategy as in __getattr__
            astr = "unknown field %s" % (key,)
            raise BadEPFieldError(astr)

    def __setitem__(self, key, value):
        if key in ("obj", "objls", "objidd", "__functions", "__aliases", "theidf"):
            super(EpBunch, self).__setitem__(key, value)
            return None
        elif key in self.fieldnames:
            i = self.fieldnames.index(key)
            try:
                self.fieldvalues[i] = value
            except IndexError:
                extendlist(self.fieldvalues, i)
                self.fieldvalues[i] = value
        elif extff.getextensible(self.objidd):  # idfobject has extensible fields
            if extff.islegalextensiblefield(
                self.objidd, key
            ):  # is the field a legal extensible field
                # What is the integer on that field
                name_int = extff.extfieldint(key)
                # get the int in the last extensible field
                last_extfield = self.objidd[-1]["field"][0]
                last_extfield_int = extff.extfieldint(last_extfield, sep=" ")
                # calculate the number of new fields to be generated
                newextensibles = name_int - last_extfield_int
                # generate the new fileds in eppy's IDD
                key_i = self.theidf.model.dtls.index(self.key)
                mult = extff.getextensible(self.objidd)
                extff.increaseIDDfields(
                    self.theidf.block,
                    self.theidf.idd_info,
                    key_i,
                    self.key,
                    newextensibles * mult,
                )
                # need to update objls and objidd here
                self.objidd = self.theidf.idd_info[key_i]

                objfields = [comm.get("field") for comm in self.objidd]
                objfields[0] = ["key"]
                objfields = [field[0] for field in objfields]
                obj_fields = [makefieldname(field) for field in objfields]
                self.objls = obj_fields
                if key in self.fieldnames:  # set the value, extending if needed
                    i = self.fieldnames.index(key)
                    try:
                        self.fieldvalues[i] = value
                    except IndexError:
                        extendlist(self.fieldvalues, i)
                        self.fieldvalues[i] = value
                else:
                    pass
            else:
                astr = "unknown field %s" % (key,)
                raise BadEPFieldError(astr)
        else:
            astr = "unknown field %s" % (key,)
            raise BadEPFieldError(astr)

    def __repr__(self):
        """print this as an idf snippet"""
        # lines = [str(val) for val in self.obj]
        # replace the above line with code that will print an integer without decimals
        lines = []
        for val in self.obj:
            try:
                value = int(val)
                if value != val:
                    value = val
            except ValueError as e:
                value = val
            lines.append(value)
        # ------------
        comments = [comm.replace("_", " ") for comm in self.objls]
        lines[0] = "%s," % (lines[0],)  # comma after first line
        for i, line in enumerate(lines[1:-1]):
            line = scientificnotation(
                line, width=18
            )  # E+ cannot read wide numbers, convert to 1e+3
            lines[i + 1] = "    %s," % (line,)  # indent and comma
        lines[-1] = "    %s;" % (lines[-1],)  # ';' after last line
        lines = lines[:1] + [line.ljust(26) for line in lines[1:]]  # ljsut the lines
        filler = "%s    !- %s"
        nlines = [
            filler % (line, comm) for line, comm in zip(lines[1:], comments[1:])
        ]  # adds comments to line
        nlines.insert(0, lines[0])  # first line without comment
        astr = "\n".join(nlines)
        return "\n%s\n" % (astr,)

    def __str__(self):
        """same as __repr__"""
        # needed if YAML is installed. See issue 67
        # unit test
        return self.__repr__()

    def __dir__(self):
        fnames = self.fieldnames
        func_names = list(self["__functions"].keys())
        return super(EpBunch, self).__dir__() + fnames + func_names

def getrange(bch, fieldname):
    """get the ranges for this field"""
    keys = ["maximum", "minimum", "maximum<", "minimum>", "type"]
    index = bch.objls.index(fieldname)
    fielddct_orig = bch.objidd[index]
    fielddct = copy.deepcopy(fielddct_orig)
    therange = {}
    for key in keys:
        therange[key] = fielddct.setdefault(key, None)
    if therange["type"]:
        therange["type"] = therange["type"][0]
    if therange["type"] == "real":
        for key in keys[:-1]:
            if therange[key]:
                therange[key] = float(therange[key][0])
    if therange["type"] == "integer":
        for key in keys[:-1]:
            if therange[key]:
                therange[key] = int(therange[key][0])
    return therange

def checkrange(bch, fieldname):
    """throw exception if the out of range"""
    fieldvalue = bch[fieldname]
    therange = bch.getrange(fieldname)
    if therange["maximum"] != None:
        if fieldvalue > therange["maximum"]:
            astr = "Value %s is not less or equal to the 'maximum' of %s"
            astr = astr % (fieldvalue, therange["maximum"])
            raise RangeError(astr)
    if therange["minimum"] != None:
        if fieldvalue < therange["minimum"]:
            astr = "Value %s is not greater or equal to the 'minimum' of %s"
            astr = astr % (fieldvalue, therange["minimum"])
            raise RangeError(astr)
    if therange["maximum<"] != None:
        if fieldvalue >= therange["maximum<"]:
            astr = "Value %s is not less than the 'maximum<' of %s"
            astr = astr % (fieldvalue, therange["maximum<"])
            raise RangeError(astr)
    if therange["minimum>"] != None:
        if fieldvalue <= therange["minimum>"]:
            astr = "Value %s is not greater than the 'minimum>' of %s"
            astr = astr % (fieldvalue, therange["minimum>"])
            raise RangeError(astr)
    return fieldvalue
    """get the idd dict for this field
    Will return {} if the fieldname does not exist"""

def getfieldidd(bch, fieldname):
    """get the idd dict for this field
    Will return {} if the fieldname does not exist"""
    # print(bch)
    try:
        fieldindex = bch.objls.index(fieldname)
    except ValueError as e:
        return {}  # the fieldname does not exist
        # so there is no idd
    fieldidd = bch.objidd[fieldindex]
    return fieldidd

def getfieldidd_item(bch, fieldname, iddkey):
    """return an item from the fieldidd, given the iddkey
    will return and empty list if it does not have the iddkey
    or if the fieldname does not exist"""
    fieldidd = getfieldidd(bch, fieldname)
    try:
        return fieldidd[iddkey]
    except KeyError as e:
        return []

def get_retaincase(bch, fieldname):
    """Check if the field should retain case"""
    fieldidd = bch.getfieldidd(fieldname)
    return "retaincase" in fieldidd

def isequal(bch, fieldname, value, places=7):
    """return True if the field is equal to value"""

    def equalalphanumeric(bch, fieldname, value):
        if bch.get_retaincase(fieldname):
            return bch[fieldname] == value
        else:
            return bch[fieldname].upper() == value.upper()

    fieldidd = bch.getfieldidd(fieldname)
    try:
        ftype = fieldidd["type"][0]
        if ftype in ["real", "integer"]:
            return almostequal(bch[fieldname], float(value), places=places)
        else:
            return equalalphanumeric(bch, fieldname, value)
    except KeyError as e:
        return equalalphanumeric(bch, fieldname, value)

def getreferingobjs(referedobj, iddgroups=None, fields=None):
    """Get a list of objects that refer to this object"""
    # pseudocode for code below
    # referringobjs = []
    # referedobj has: -> Name
    #                 -> reference
    # for each obj in idf:
    # [optional filter -> objects in iddgroup]
    #     each field of obj:
    #     [optional filter -> field in fields]
    #         has object-list [refname]:
    #             if refname in reference:
    #                 if Name = field value:
    #                     referringobjs.append()
    referringobjs = []
    idf = referedobj.theidf
    referedidd = referedobj.getfieldidd("Name")
    try:
        references = referedidd["reference"]
    except KeyError as e:
        return referringobjs
    idfobjs = idf.idfobjects.values()
    idfobjs = list(itertools.chain.from_iterable(idfobjs))  # flatten list
    if iddgroups:  # optional filter
        idfobjs = [
            anobj for anobj in idfobjs if anobj.getfieldidd("key")["group"] in iddgroups
        ]
    for anobj in idfobjs:
        if not fields:
            thefields = anobj.objls
        else:
            thefields = fields
        for field in thefields:
            try:
                itsidd = anobj.getfieldidd(field)
            except ValueError as e:
                continue
            if "object-list" in itsidd:
                refname = itsidd["object-list"][0]
                if refname in references:
                    if referedobj.isequal("Name", anobj[field]):
                        referringobjs.append(anobj)
    return referringobjs

def get_referenced_object(referring_object, fieldname):
    """
    Get an object referred to by a field in another object.

    For example an object of type Construction has fields for each layer, each
    of which refers to a Material. This functions allows the object
    representing a Material to be fetched using the name of the layer.

    Returns the first item found since if there is more than one matching item,
    it is a malformed IDF.

    Parameters
    ----------
    referring_object : EpBunch
        The object which contains a reference to another object,
    fieldname : str
        The name of the field in the referring object which contains the
        reference to another object.

    Returns
    -------
    EpBunch

    """
    idf = referring_object.theidf
    object_list = referring_object.getfieldidd_item(fieldname, "object-list")
    for obj_type in idf.idfobjects:
        for obj in idf.idfobjects[obj_type]:
            valid_object_lists = obj.getfieldidd_item("Name", "reference")
            if set(object_list).intersection(set(valid_object_lists)):
                referenced_obj_name = referring_object[fieldname]
                if obj.Name == referenced_obj_name:
                    return obj


text:
/*
 * INET		An implementation of the TCP/IP protocol suite for the LINUX
 *		operating system.  INET is implemented using the  BSD Socket
 *		interface as the means of communication with the user level.
 *
 *		Definitions for the Interfaces handler.
 *
 * Version:	@(#)dev.h	1.0.10	08/12/93
 *
 * Authors:	Ross Biro
 *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
 *		Corey Minyard <wf-rch!minyard@relay.EU.net>
 *		Donald J. Becker, <becker@cesdis.gsfc.nasa.gov>
 *		Alan Cox, <alan@lxorguk.ukuu.org.uk>
 *		Bjorn Ekwall. <bj0rn@blox.se>
 *              Pekka Riikonen <priikone@poseidon.pspt.fi>
 *
 *		This program is free software; you can redistribute it and/or
 *		modify it under the terms of the GNU General Public License
 *		as published by the Free Software Foundation; either version
 *		2 of the License, or (at your option) any later version.
 *
 *		Moved to /usr/include/linux for NET3
 */
#ifndef _LINUX_NETDEVICE_H
#define _LINUX_NETDEVICE_H

#include <linux/if.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>

#define MAX_ADDR_LEN	32		/* Largest hardware address length */

/*
 *	Network device statistics. Akin to the 2.0 ether stats but
 *	with byte counters.
 */

struct net_device_stats
{
	unsigned long	rx_packets;		/* total packets received	*/
	unsigned long	tx_packets;		/* total packets transmitted	*/
	unsigned long	rx_bytes;		/* total bytes received 	*/
	unsigned long	tx_bytes;		/* total bytes transmitted	*/
	unsigned long	rx_errors;		/* bad packets received		*/
	unsigned long	tx_errors;		/* packet transmit problems	*/
	unsigned long	rx_dropped;		/* no space in linux buffers	*/
	unsigned long	tx_dropped;		/* no space available in linux	*/
	unsigned long	multicast;		/* multicast packets received	*/
	unsigned long	collisions;

	/* detailed rx_errors: */
	unsigned long	rx_length_errors;
	unsigned long	rx_over_errors;		/* receiver ring buff overflow	*/
	unsigned long	rx_crc_errors;		/* recved pkt with crc error	*/
	unsigned long	rx_frame_errors;	/* recv'd frame alignment error */
	unsigned long	rx_fifo_errors;		/* recv'r fifo overrun		*/
	unsigned long	rx_missed_errors;	/* receiver missed packet	*/

	/* detailed tx_errors */
	unsigned long	tx_aborted_errors;
	unsigned long	tx_carrier_errors;
	unsigned long	tx_fifo_errors;
	unsigned long	tx_heartbeat_errors;
	unsigned long	tx_window_errors;

	/* for cslip etc */
	unsigned long	rx_compressed;
	unsigned long	tx_compressed;
};

/* Media selection options. */
enum {
        IF_PORT_UNKNOWN = 0,
        IF_PORT_10BASE2,
        IF_PORT_10BASET,
        IF_PORT_AUI,
        IF_PORT_100BASET,
        IF_PORT_100BASETX,
        IF_PORT_100BASEFX
};

#endif	/* _LINUX_NETDEVICE_H */


text:
{% extends "base.html" %}

{% load i18n %}
{% load staticfiles %}

{% block title %}{% trans "Set a Password" %}{% endblock title %}

{% block page_header %}

{% trans "Set a Password" %}

{% endblock page_header %}

{% block content %}

Please set a password to login to your account in the future.

                    <form role="form" method="post" action="{% url 'password_upsell' %}">
                        {% load crispy_forms_tags %}
                        {{ form|crispy }}
                        {% csrf_token %}

                            <button type="submit" class="btn btn-primary btn-lg btn-block">{% trans "Set Password" %}
                            </button>

                    </form>

{% endblock content %}


text:
using ZyGames.Framework.Model;

namespace ZyGames.Framework.Net
{
    ///
    /// 转发器接收参数
    ///
    public class TransReceiveParam
    {
        ///
        ///
        ///<param name="redisKey"></param>
        public TransReceiveParam(string redisKey)
        {
            RedisKey = redisKey;
        }

        ///
        ///
        ///<param name="redisKey"></param>
        ///<param name="schema"></param>
        ///<param name="capacity"></param>
        ///<param name="dbFilter"></param>
        public TransReceiveParam(string redisKey, SchemaTable schema, int capacity, DbDataFilter dbFilter)
            : this(redisKey)
        {
            Schema = schema;
            Capacity = capacity;
            DbFilter = dbFilter;
        }

        ///
        ///
        public string RedisKey { get; set; }

        ///
        ///
        public SchemaTable Schema { get; set; }

        ///
        ///
        public int Capacity { get; set; }

        ///
        ///
        public DbDataFilter DbFilter { get; set; }
    }
}


text:
struct PolyInfo {
    struct image *img;
    struct FlatImage *img_to_draw;
    struct FloatImage *normal_map;
};

void draw_poly(
        struct PolyInfo* info,
        const int voxes[9],
        const int uv[6]);

void draw_sprite(
        struct image *img,
        struct FlatImage *img_to_draw,
        const int vox[3],
        const double normal[3]);

void draw_sprites_in_random_position_in_poly(
        struct image *img,
        struct FlatImage *img_to_draw,
        const int voxes[3],
        const int density);

void poly_info_clear(struct PolyInfo* info);


text:
package org.kie.internal.builder.fluent;

import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.rule.RuleRuntime;
import org.kie.api.runtime.rule.StatefulRuleSession;

/**
 * See {@link RuleRuntime} and {@link StatefulRuleSession}
 */
public interface RuleFluent<T, U> {

    T fireAllRules();

    T setGlobal( String identifier, Object object );

    T getGlobal(String identifier);

    T insert(Object object);

    T update( FactHandle handle, Object object );

    T delete(FactHandle handle);

    T setActiveRuleFlowGroup(String ruleFlowGroup);

    T setActiveAgendaGroup(String agendaGroup);

    U dispose();

}


text:
<?php

use \Bandama\Foundation\Translation\Translator;
use \Bandama\Foundation\Translation\TranslationException;

describe(Translator::class, function() {

    context('Initialization', function() {
        describe('::_construct', function() {
            it('exptects translations should be null when we call constructor without arguments', function() {
                $translator = new Translator();
                expect($translator->translate('hello', 'en'))->toBeNull();
                expect($translator->getTranslations())->toBeEmpty();
            });

            it('exptects translations should not be null when we call constructor with arguments', function() {
                $translator = new Translator(__DIR__.'/translations/messages.fr.php', __DIR__.'/translations/messages.en.php');
                expect($translator->getTranslations())->not->toBeEmpty();
                expect(count($translator->getTranslations()))->toBe(2);
                expect($translator->getTranslations()['fr'])->not->toBeNull();
                expect($translator->getTranslations()['en'])->not->toBeNull();
            });
        });

        describe('::addFile', function() {
            it('expects files content added to translations', function() {
                $translator = new Translator();
                $translator->addFile(__DIR__.'/translations/messages.fr.php');
                expect($translator->getTranslations())->not->toBeEmpty();
                expect(count($translator->getTranslations()))->toBe(1);
                expect($translator->getTranslations()['fr'])->not->toBeNull();

                $translator->addFile(__DIR__.'/translations/messages.en.php');
                expect(count($translator->getTranslations()))->toBe(2);
                expect($translator->getTranslations()['fr'])->not->toBeNull();
                expect($translator->getTranslations()['en'])->not->toBeNull();
            });
        });

        describe('::addData', function() {
            it('expects data to be added to translations', function() {
                $translator = new Translator();
                $fr = require(__DIR__.'/translations/messages.fr.php');
                $translator->addData($fr, 'fr');
                expect($translator->getTranslations())->not->toBeEmpty();
                expect(count($translator->getTranslations()))->toBe(1);
                expect($translator->getTranslations()['fr'])->not->toBeNull();

                $en = require(__DIR__.'/translations/messages.en.php');
                $translator->addData($en, 'en');
                expect(count($translator->getTranslations()))->toBe(2);
                expect($translator->getTranslations()['fr'])->not->toBeNull();
                expect($translator->getTranslations()['en'])->not->toBeNull();

                $enUS = require(__DIR__.'/translations/messages.en-US.php');
                $translator->addData($enUS, 'en-US');
                expect(count($translator->getTranslations()))->toBe(2);
                expect($translator->getTranslations()['en'])->toContainKey('US');
            });

            it('should throw TranslationException', function() {
                $closure = function() {
                    $translator = new Translator();
                    $en = require(__DIR__.'/translations/messages.en.php');
                    $translator->addData($en, 'en-US-ZZ');
                };

                expect($closure)->toThrow(new TranslationException('Invalid language'));
            });
        });
    });

    context('Translation', function() {
        given('translator', function() {
            return new Translator(__DIR__.'/translations/messages.fr.php', __DIR__.'/translations/messages.en.php');
        });

        describe('::translate', function() {
            it('should throw TranslationException', function() {
                $closure = function() {
                    $this->translator->translate('hello', 'en-US-ZZ');
                };

                expect($closure)->toThrow(new TranslationException('Invalid language'));
            });

            it('should return null', function() {
                expect($this->translator->translate('hell.world', 'en'))->toBeNull();
            });

            it('expects translator return "Bonjour le monde!"', function() {
                expect($this->translator->translate('hello', 'fr'))->toBe('Bonjour le monde!');
            });

            it('expects translator return "Hello world!"', function() {
                expect($this->translator->translate('hello', 'en'))->toBe('Hello world!');
            });

            it('expects translator return "Hi world!"', function() {
                $this->translator->addFile(__DIR__.'/translations/messages.en-US.php');
                expect($this->translator->translate('hello', 'en-US'))->toBe('Hi world!');
            });
        });
    });
});


text:
import pytest
import mock

from discogstagger.discogsalbum import DiscogsAlbum
from discogstagger.discogswrapper import DiscogsWrapper

@pytest.fixture(scope='module')
def discogs_album():

    with open('responses/40522.json', 'rb') as fh:
        b = fh.read()

    with mock.patch('discogstagger.discogswrapper.DiscogsWrapper.is_authenticated', new_callable=mock.PropertyMock) as mock_authenticated:
        mock_authenticated.return_value = False

        with mock.patch('discogstagger.discogswrapper.DiscogsWrapper._get_request_token') as mock_token:
            mock_token.return_value = True
            with mock.patch('discogs_client.fetchers.RequestsFetcher') as mock_discogs_request_fetcher:

                dw = DiscogsWrapper()
                mock_discogs_request_fetcher.return_value = b, 200
                da = DiscogsAlbum(dw.discogs, 40522, '&', '&')
    return da

def test_discogs_release_properties(discogs_album):
    assert discogs_album.releaseid == 40522
    assert discogs_album.url == 'http://www.discogs.com/release/40522'
    assert discogs_album.catno == '12DEF006'
    assert discogs_album.label == 'Definitive Recordings'
    assert discogs_album.title == 'House For All'
    assert discogs_album.year == '1993'
    assert discogs_album.master_id == 206510
    assert discogs_album.genre == 'Electronic'
    assert discogs_album.genres == 'Electronic'
    assert discogs_album.style == 'House'
    assert discogs_album.country == 'Canada'
    assert discogs_album.artist == 'Blunted Dummies'
    assert discogs_album.note == '"House For All (Original Mix)" was originally released on the [r=183558]  '
    assert discogs_album.disctotal == 1
    assert discogs_album.is_compilation is False

def test_discogs_release_tracks(discogs_album):
    track_one = discogs_album.tracks[0]
    assert len(discogs_album.tracks) == 5
    assert track_one.tracknumber == 1
    assert track_one.discsubtitle is None
    assert track_one.sortartist == track_one.artist
    assert track_one.title == 'House For All (Original Mix)'

def test_discogs_release_str(discogs_album):
    with open('responses/40522.txt') as fh:
        str_rep = fh.read()
    assert str(discogs_album) == str_rep
    assert discogs_album.album_info == str_rep

def test_discogsalbum_clean_name():
    assert DiscogsAlbum.clean_name('Aphex Twin, The') == 'The Aphex Twin'


text:
<?php

namespace Core;

class Error {

	public static function errorHandler($level, $message, $file, $line) {
		if (error_reporting() !== 0) {
			throw new \ErrorException($message, 0, $level, $file, $line);
		}
	}

	public static function exceptionHandler($exception) {

		$code = $exception->getCode();
		if ($code != 404) {
			$code = 500;
		}
		http_response_code($code);

		if (\App\Config::SHOW_ERRORS) {
			echo "
Fatal error
";
			echo "
Uncaught exception: '" . get_class($exception) . "'
";
			echo "
Message: '" . $exception->getMessage() . "'
";
			echo "
Stack trace:
" . $exception->getTraceAsString() . "

";
			echo "
Thrown in '" . $exception->getFile() . "' on line " . $exception->getLine() . "
";
		}
		else {
			$log = dirname(__DIR__) . '/logs/' . date('Y-m-d') . '.txt';
			ini_set('error_log', $log);

			$message = "Uncaught exception: '" . get_class($exception) . "'";
			$message.= " with message '" . $exception->getMessage() . "'";
			$message.= "\nStack trace: " . $exception->getTraceAsString();
			$message.= "\nThrown in '" . $exception->getFile() . "' on line " . $exception->getLine();

			error_log($message);

			View::renderTemplate("$code.twig");

		}

	}
}


text:
<!DOCTYPE html>

<html class="no-js" ng-app="LS"

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">

<base href="http://everaldoreis.github.io/iSM---Stock-Manager/" />

<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="vendor/font-awesome4/css/font-awesome.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/my.css">

<link rel="stylesheet" type="text/css"
	href="vendor/calculator/jquery.calculator.css">


text:
package net.tofweb;

import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author Lynn Owens
 *
 *         Setup the persistence framework
 */
// This class contains configuration info
@Configuration
// Permit the use of transactions for db connections
@EnableTransactionManagement
public class PersistenceConfig {

	@Resource
	private Environment env;

	/**
	 * Get a SessionFactory with which to build sessions to database
	 *
	 * @return LocalSessionFactoryBean
	 */
	@Bean
	public LocalSessionFactoryBean getSessionFactory() {
		LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
		sessionFactory.setDataSource(getDataSource());
		sessionFactory.setPackagesToScan(new String[] { "net.tofweb" });
		sessionFactory.setHibernateProperties(buildHibernateProperties());

		return sessionFactory;
	}

	/**
	 * Get a DataSource to the embedded H2 database
	 *
	 * @return EmbeddedDatabase
	 */
	@Bean
	public DataSource getDataSource() {
		EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
		EmbeddedDatabase db = builder.setType(EmbeddedDatabaseType.H2).addScript("db/sql/initDb.sql").build();
		return db;
	}

	/**
	 * Get a TransactionManager using the specified SessionFactory
	 *
	 * @param sessionFactory
	 * @return HibernateTransactionManager
	 */
	@Bean
	@Autowired
	public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
		HibernateTransactionManager txManager = new HibernateTransactionManager();
		txManager.setSessionFactory(sessionFactory);

		return txManager;
	}

	/**
	 * Get a translator to convert database driver exceptions into a common
	 * standard
	 *
	 * @return PersistenceExceptionTranslationPostProcessor
	 */
	@Bean
	public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
		return new PersistenceExceptionTranslationPostProcessor();
	}

	/*
	 * Build the Hibernate Properties. This configures Hibernate to talk to the
	 * H2 database.
	 */
	private Properties buildHibernateProperties() {
		return new Properties() {

			private static final long serialVersionUID = 1L;

			{
				setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
			}
		};
	}
}


text:
package com.gunshippenguin.openflood;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

/**
 * Class representing a game in progress.
 */
public class Game {
    private int board[][];
    private int boardSize;

    private int numColors;

    private int steps = 0;
    private int maxSteps;

    private String seed;
    private static final String SEED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";
    private static final int SEED_LENGTH_LOWER = 5;
    private static final int SEED_LENGTH_UPPER = 15;

    public Game(int boardSize, int numColors) {
        // Initialize board
        this.boardSize = boardSize;
        this.numColors = numColors;
        this.seed = generateRandomSeed();
        initBoard();
        initMaxSteps();
    }

    public Game(int boardSize, int numColors, String seed) {
        // Initialize board
        this.boardSize = boardSize;
        this.numColors = numColors;
        this.seed = seed;
        initBoard();
        initMaxSteps();
    }

    public Game(int[][] board, int boardSize, int numColors, int steps, String seed) {
        // Restore board
        this.board = board;
        this.boardSize = boardSize;
        this.numColors = numColors;
        this.steps = steps;
        this.seed = seed;
        initMaxSteps();
    }

    private String generateRandomSeed() {
        Random rand = new Random(System.currentTimeMillis());
        String currSeed = "";
        for(int i=0;i<rand.nextInt((SEED_LENGTH_UPPER-SEED_LENGTH_LOWER)+1)+SEED_LENGTH_LOWER;i++) {
            currSeed += SEED_CHARS.charAt(rand.nextInt(SEED_CHARS.length()));
        }
        return currSeed;
    }

    public int[][] getBoard() {
        return board;
    }

    public int getColor(int x, int y) {
        return board[y][x];
    }

    public int getBoardDimensions() {
        return boardSize;
    }

    public String getSeed() {
        return seed;
    }

    public int getSteps() {
        return steps;
    }

    public int getMaxSteps() {
        return maxSteps;
    }

    private void initBoard() {
        board = new int[boardSize][boardSize];
        Random r = new Random(seed.hashCode());
        for (int y = 0; y < boardSize; y++) {
            for (int x = 0; x < boardSize; x++) {
                board[y][x] = r.nextInt(numColors);
            }
        }
        return;
    }

    private void initMaxSteps() {
        maxSteps = (int) 30 * (boardSize * numColors) / (17 * 6);
    }

    public void flood(int replacementColor) {
        int targetColor = board[0][0];
        if (targetColor == replacementColor) {
            return;
        }

        Queue<BoardPoint> queue = new LinkedList<BoardPoint>();
        ArrayList<BoardPoint> processed = new ArrayList<BoardPoint>();

        queue.add(new BoardPoint(0, 0));

        BoardPoint currPoint;
        while (!queue.isEmpty()) {
            currPoint = queue.remove();
            if (board[currPoint.getY()][currPoint.getX()] == targetColor) {
                board[currPoint.getY()][currPoint.getX()] = replacementColor;
                if (currPoint.getX() != 0 &&
                        !processed.contains(new BoardPoint(currPoint.getX() - 1, currPoint.getY()))) {
                    queue.add(new BoardPoint(currPoint.getX() - 1, currPoint.getY()));
                }
                if (currPoint.getX() != boardSize - 1 &&
                        !processed.contains(new BoardPoint(currPoint.getX() + 1, currPoint.getY()))) {
                    queue.add(new BoardPoint(currPoint.getX() + 1, currPoint.getY()));
                }
                if (currPoint.getY() != 0 &&
                        !processed.contains(new BoardPoint(currPoint.getX(), currPoint.getY() - 1))) {
                    queue.add(new BoardPoint(currPoint.getX(), currPoint.getY() - 1));
                }
                if (currPoint.getY() != boardSize - 1 &&
                        !processed.contains(new BoardPoint(currPoint.getX(), currPoint.getY() + 1))) {
                    queue.add(new BoardPoint(currPoint.getX(), currPoint.getY() + 1));
                }
            }
        }
        steps++;
        return;
    }

    public boolean checkWin() {
        int lastColor = board[0][0];
        for (int y = 0; y < board.length; y++) {
            for (int x = 0; x < board.length; x++) {
                if (lastColor != board[y][x]) {
                    return false;
                }
                lastColor = board[y][x];
            }
        }
        return true;
    }

    private class BoardPoint {
        int x, y;

        public BoardPoint(int x, int y) {
            this.x = x;
            this.y = y;
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }

        @Override
        public boolean equals(Object obj) {
            if (!BoardPoint.class.isAssignableFrom(obj.getClass())) {
                return false;
            }
            BoardPoint bp = (BoardPoint) obj;
            return (this.x == bp.getX()) && (this.y == bp.getY());
        }
    }
}