text:
package io.github.resilience4j.bulkhead.operator;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.IOException;

import io.github.resilience4j.bulkhead.Bulkhead;
import io.github.resilience4j.bulkhead.BulkheadConfig;
import io.github.resilience4j.bulkhead.BulkheadFullException;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import org.junit.Test;

/**
 * Unit test for {@link BulkheadObserver} using {@link BulkheadOperator}.
 */
@SuppressWarnings("unchecked")
public class BulkheadObserverTest {
    private Bulkhead bulkhead = Bulkhead.of("test", BulkheadConfig.custom().maxConcurrentCalls(1).maxWaitTime(0).build());

    @Test
    public void shouldEmitAllEvents() {
        Observable.fromArray("Event 1", "Event 2")
            .lift(BulkheadOperator.of(bulkhead))
            .test()
            .assertResult("Event 1", "Event 2");

        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    }

    @Test
    public void shouldPropagateError() {
        Observable.error(new IOException("BAM!"))
            .lift(BulkheadOperator.of(bulkhead))
            .test()
            .assertSubscribed()
            .assertError(IOException.class)
            .assertNotComplete();

        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    }

    @Test
    public void shouldEmitErrorWithBulkheadFullException() {
        bulkhead.isCallPermitted();

        Observable.fromArray("Event 1", "Event 2")
            .lift(BulkheadOperator.of(bulkhead))
            .test()
            .assertSubscribed()
            .assertError(BulkheadFullException.class)
            .assertNotComplete();

        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(0);
    }

    @Test
    public void shouldHonorDisposedWhenCallingOnNext() throws Exception {
        // Given
        Disposable disposable = mock(Disposable.class);
        Observer childObserver = mock(Observer.class);
        Observer decoratedObserver = BulkheadOperator.of(bulkhead).apply(childObserver);
        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
        decoratedObserver.onSubscribe(disposable);

        // When
        decoratedObserver.onNext("one");
        ((Disposable) decoratedObserver).dispose();
        decoratedObserver.onNext("two");

        // Then
        verify(childObserver, times(1)).onNext(any());
        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    }

    @Test
    public void shouldHonorDisposedWhenCallingOnError() throws Exception {
        // Given
        Disposable disposable = mock(Disposable.class);
        Observer childObserver = mock(Observer.class);
        Observer decoratedObserver = BulkheadOperator.of(bulkhead).apply(childObserver);
        decoratedObserver.onSubscribe(disposable);

        // When
        ((Disposable) decoratedObserver).dispose();
        decoratedObserver.onError(new IllegalStateException());

        // Then
        verify(childObserver, never()).onError(any());
        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    }

    @Test
    public void shouldHonorDisposedWhenCallingOnComplete() throws Exception {
        // Given
        Disposable disposable = mock(Disposable.class);
        Observer childObserver = mock(Observer.class);
        Observer decoratedObserver = BulkheadOperator.of(bulkhead).apply(childObserver);
        decoratedObserver.onSubscribe(disposable);

        // When
        ((Disposable) decoratedObserver).dispose();
        decoratedObserver.onComplete();

        // Then
        verify(childObserver, never()).onComplete();
        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1);
    }

    @Test
    public void shouldNotReleaseBulkheadWhenWasDisposedAfterNotPermittedSubscribe() throws Exception {
        // Given
        Disposable disposable = mock(Disposable.class);
        Observer childObserver = mock(Observer.class);
        Observer decoratedObserver = BulkheadOperator.of(bulkhead).apply(childObserver);
        bulkhead.isCallPermitted();
        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(0);
        decoratedObserver.onSubscribe(disposable);

        // When
        ((Disposable) decoratedObserver).dispose();

        // Then
        assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(0);
    }
}


text:
package test.dataprovider;

import org.testng.annotations.Test;

public class InheritanceBTest extends InheritanceATest {

  @Test(dataProvider = "dp")
  public void f(String s) {
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
  include('data/includes/less_compiler.php');

?>


text:
static CGFloat const MUDefaultCheckMarkAccessoryWidth = 38.5;

@interface MUFormOptionCell ()

@property (weak, nonatomic) IBOutlet UILabel *staticLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *staticLabelTrailingSpaceConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *messageLabelTrailingSpaceConstraint;

@property (assign, nonatomic, getter=isAnimating) BOOL animating;
@property (copy, nonatomic) void(^selectedAnimationCompletion)();
@end

@implementation MUFormOptionCell

#pragma mark - Properties -

- (void)setFont:(UIFont *)font {
    _font = font;
    self.staticLabel.font = font;
}

#pragma mark - Overrides -

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    if (!selected && animated) {
        self.animating = YES;

        // This block will be run at the end of the selected animation.
        [CATransaction setCompletionBlock:^{
            self.animating = NO;
            if (self.selectedAnimationCompletion) {
                self.selectedAnimationCompletion();
                self.selectedAnimationCompletion = NULL;
            }
        }];
    }

    [super setSelected:selected animated:animated];
}

- (void)setEnabled:(BOOL)enabled {
    [super setEnabled:enabled];

    __weak __typeof__(self) weakSelf = self;
    void (^setStyle)() = ^{
        weakSelf.selectionStyle = enabled ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
    };

    if (self.isAnimating) {
        self.selectedAnimationCompletion = setStyle;
    }
    else {
        setStyle();
    }
}

- (void)configureWithValue:(id)value info:(NSDictionary *)info
{
    [super configureWithValue:value info:info];

    BOOL isValueEqualToDefault = [value isEqual:info[MUFormDefaultValueKey]];
    if (isValueEqualToDefault && self.accessoryType != UITableViewCellAccessoryCheckmark) {
        self.accessoryType = UITableViewCellAccessoryCheckmark;
        self.staticLabelTrailingSpaceConstraint.constant = 0;
        self.messageLabelTrailingSpaceConstraint.constant = 0.;
        [self setNeedsUpdateConstraints];
    }
    else if (!isValueEqualToDefault && self.accessoryType == UITableViewCellAccessoryCheckmark)
    {
        self.accessoryType = UITableViewCellAccessoryNone;
        self.staticLabelTrailingSpaceConstraint.constant = MUDefaultCheckMarkAccessoryWidth;
        self.messageLabelTrailingSpaceConstraint.constant = MUDefaultCheckMarkAccessoryWidth;
        [self setNeedsUpdateConstraints];
    }

    NSString *localizedStaticTextKey = info[MUFormLocalizedStaticTextKey];
    self.staticLabel.text = [[NSBundle mainBundle] localizedStringForKey:localizedStaticTextKey value:localizedStaticTextKey table:MUFormKitStringTable];

    NSString *localizedCellMessageKey = info[MUFormLocalizedCellMessageKey];
    self.messageLabel.text = [[NSBundle mainBundle] localizedStringForKey:localizedCellMessageKey value:localizedCellMessageKey table:MUFormKitStringTable];

    self.enabled = ![info[MUFormCellIsDisabledKey] boolValue];
}

@end


text:
public class Tesla : Car, IElectricCar
{
    private int batteries;

    public Tesla(string model, string color, int batteries)
        : base(model, color)
    {
        this.Batterries = batteries;
    }

    public int Batterries
    {
        get { return this.batteries; }
        private set { this.batteries = value; }
    }

    protected override string GetCarInfo()
    {
        return base.GetCarInfo() + $" with {this.Batterries} Batteries";
    }
}


text:
import pytest
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

def pytest_addoption(parser):
    parser.addoption(
        '--sqlalchemy_url',
        action='store',
        default='sqlite:///:memory:',
        help='SQLAlchemy connection url to database under test.'
    )

@pytest.fixture()
def engine(request):
    engine = create_engine(
        request.config.getoption('--sqlalchemy_url'),
        echo=True
    )

    return engine

@pytest.fixture()
def session_maker(request, engine):
    _session_maker = sessionmaker(
        bind=engine
    )

    return _session_maker

def create_data(session):
    from skosprovider_sqlalchemy.models import (
        Concept,
        ConceptScheme,
        Collection,
        Label,
        Note,
        Match,
        Language
    )
    en = session.query(Language).get('en')
    nl = session.query(Language).get('nl')
    cs = ConceptScheme(
        id=1,
        uri='urn:x-skosprovider:test',
        languages=[en, nl]
    )
    session.add(cs)
    con = Concept(
        id=10,
        uri='urn:x-skosprovider:test:1',
        concept_id=1,
        conceptscheme=cs
    )
    session.add(con)
    l = Label('Churches', 'prefLabel', 'en')
    con.labels.append(l)
    l = Label('Kerken', 'prefLabel', 'nl')
    con.labels.append(l)
    col = Collection(
        id=20,
        uri='urn:x-skosprovider:test:2',
        concept_id=2,
        conceptscheme=cs
    )
    col.broader_concepts.add(con)
    n = Note(
        'Churches organised by function, as opposed to by shape or religion.',
        'scopeNote',
        'en'
    )
    col.notes.append(n)
    l = Label('Churches by function', 'prefLabel', 'en')
    col.labels.append(l)
    l = Label('111sortmefirst', 'sortLabel', 'en')
    col.labels.append(l)
    session.add(col)
    chap = Concept(
        id=30,
        uri='urn:x-skosprovider:test:3',
        concept_id=3,
        conceptscheme=cs
    )
    l = Label('Chapels', 'prefLabel', 'en')
    chap.labels.append(l)
    session.add(chap)
    chap.related_concepts.add(con)
    tchap = Concept(
        id=50,
        uri='urn:x-skosprovider:test:5',
        concept_id=5,
        conceptscheme=cs
    )
    tchap.labels.append(Label('Boomkapellen', 'prefLabel', 'nl'))
    session.add(tchap)
    tchap.broader_concepts.add(chap)
    cath = Concept(
        id=40,
        uri='urn:x-skosprovider:test:4',
        concept_id=4,
        conceptscheme=cs
    )
    l = Label('Cathedrals', 'prefLabel', 'en')
    cath.labels.append(l)
    n = Note(
        'A cathedral is a church which contains the seat of a bishop.',
        'definition',
        'en'
    )
    cath.notes.append(n)
    match = Match(
        matchtype_id = 'closeMatch',
        uri = 'http://vocab.getty.edu/aat/300007501'
    )
    cath.matches.append(match)
    session.add(cath)
    cath.member_of.add(col)
    pchurch = Concept(
        id=60,
        uri='urn:x-skosprovider:test:6',
        concept_id=6,
        conceptscheme=cs
    )
    l = Label('Parochiekerken', 'prefLabel', 'nl')
    pchurch.labels.append(l)
    session.add(pchurch)
    pchurch.member_of.add(col)
    hkerk = Concept(
        id=70,
        uri='urn:x-skosprovider:test:7',
        concept_id=7,
        conceptscheme=cs
    )
    l = Label('Hulpkerken', 'prefLabel', 'nl')
    hkerk.labels.append(l)
    session.add(hkerk)
    hkerk.broader_concepts.add(pchurch)
    chparts = Collection(
        id=80,
        uri='urn:x-skosprovider:test:8',
        concept_id=8,
        conceptscheme=cs,
        infer_concept_relations=False
    )
    l = Label('Parts of churches', 'prefLabel', 'en')
    chparts.labels.append(l)
    session.add(chparts)
    chparts.broader_concepts.add(con)
    chtow = Concept(
        id=90,
        uri='urn:x-skosprovider:test:9',
        concept_id=9,
        conceptscheme=cs,
    )
    l = Label('Churchtowers', 'prefLabel', 'en')
    chtow.labels.append(l)
    match = Match(
        matchtype_id = 'exactMatch',
        uri = 'http://vocab.getty.edu/aat/300003625'
    )
    chtow.matches.append(match)
    session.add(chtow)
    chtow.member_of.add(chparts)
    session.commit()

def create_visitation(session):
    from skosprovider_sqlalchemy.utils import (
        VisitationCalculator
    )
    from skosprovider_sqlalchemy.models import (
        Visitation,
        ConceptScheme
    )
    vc = VisitationCalculator(session)
    conceptschemes = session.query(ConceptScheme).all()
    for cs in conceptschemes:
        visit = vc.visit(cs)
        for v in visit:
            vrow = Visitation(
                conceptscheme=cs,
                concept_id=v['id'],
                lft=v['lft'],
                rght=v['rght'],
                depth=v['depth']
            )
            session.add(vrow)
    session.commit()


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->
<eventReceiver name="worndetector-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
    <from eventAdapterType="oauth-mqtt">
        <property name="topic">carbon.super/alertme/+/worndetector</property>
		<property name="username">admin</property>
		<property name="password">admin</property>
		<property name="contentValidator">org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTContentValidator</property>
		<property name="cleanSession">true</property>
    </from>
    <mapping customMapping="disable" type="json"/>
    <to streamName="org.wso2.iot.devices.worndetector" version="1.0.0"/>
</eventReceiver>


text:
<?php
namespace Octo\Utilities;

use Twitter;
use Octo\System\Model\Setting;
use Octo\Twitter\Model\Tweet;
use Octo\Store;

class TwitterUtilities
{

    /**
     * Get the stream of tweets for the search term and cache to the database
     */
    public static function getStream()
    {
        $tweetStore = Store::get('Tweet');

        $consumerKey = Setting::getSetting('twitter', 'consumer_key');
        $consumerSecret = Setting::getSetting('twitter', 'consumer_secret');
        $accessToken = Setting::getSetting('twitter', 'access_token');
        $accessTokenSecret = Setting::getSetting('twitter', 'access_token_secret');
        $streamSearch = Setting::getSetting('twitter', 'stream_search');

        $twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

        if (self::canCallAPI()) {
            self::updateLastAPICall();

            $stream = $twitter->search($streamSearch);

            foreach ($stream as $s) {
                if (!$tweetStore->getByTwitterIdForScope($s->id, 'stream')) {
                    $t = new Tweet;
                    $t->setTwitterId($s->id);
                    $t->setText($s->text);
                    $t->setHtmlText(Twitter::clickable($s));
                    $t->setScreenname($s->user->screen_name);
                    $t->setPosted($s->created_at);
                    $t->setCreatedDate(new \DateTime());
                    $t->setScope('stream');
                    $tweetStore->insert($t);
                }
            }
        }
    }

    /**
     * Get tweets for the currently authenticated twitter user
     */
    public static function getUser()
    {
        $tweetStore = Store::get('Tweet');

        $consumerKey = Setting::getSetting('twitter', 'consumer_key');
        $consumerSecret = Setting::getSetting('twitter', 'consumer_secret');
        $accessToken = Setting::getSetting('twitter', 'access_token');
        $accessTokenSecret = Setting::getSetting('twitter', 'access_token_secret');

        $twitter = new Twitter($consumerKey, $consumerSecret, $accessToken, $accessTokenSecret);

        if (self::canCallAPI()) {
            self::updateLastAPICall();

            $statuses = $twitter->load(Twitter::ME);
            foreach ($statuses as $s) {
                if (!$tweetStore->getByTwitterIdForScope($s->id, 'user')) {
                    $t = new Tweet;
                    $t->setTwitterId($s->id);
                    $t->setText($s->text);
                    $t->setHtmlText(Twitter::clickable($s));
                    $t->setScreenname($s->user->screen_name);
                    $t->setPosted($s->created_at);
                    $t->setCreatedDate(new \DateTime());
                    $t->setScope('user');
                    $tweetStore->saveByInsert($t);
                }
            }
        }
    }

    /**
     * Update the last Twitter API call to now
     */
    public static function updateLastAPICall()
    {
        $now = new \DateTime();
        Setting::set('twitter', 'last_api_call', $now->format('Y-m-d H:i:s'));
    }

    /**
     * Checks whether the API can be called
     *
     * Returns false if the API was called less than a minute ago (which gets over 15 requests in
     * 15 minute on Twitter API rate limiting)
     *
     * @return bool
     */
    public static function canCallAPI()
    {
        $lastCall = Setting::getSetting('twitter', 'last_api_call');

        if ($lastCall == null) {
            return true;
        } else {
            $lastCall = new \DateTime($lastCall);
        }

        $now = new \DateTime();
        $interval = $lastCall->diff($now);

        // Are we at least one minute ago?
        if ($interval->i >= 1) {
            return true;
        } else {
            return false;
        }
    }
}


text:
<!doctype html>

<meta charset="utf-8">
<link href="layout.css" charset="utf-8" type="text/css" rel="stylesheet"></link>
<title>SDL_title</title>

Title


text:
package scala
package reflect
package internal

import util._

/** Handling range positions
 *  atPos, the main method in this trait, will add positions to a tree,
 *  and will ensure the following properties:
 *
 *    1. All nodes between the root of the tree and nodes that already have positions
 *       will be assigned positions.
 *    2. No node which already has a position will be assigned a different range; however
 *       a RangePosition might become a TransparentPosition.
 *    3. The position of each assigned node includes the positions of each of its children.
 *    4. The positions of all solid descendants of children of an assigned node
 *       are mutually non-overlapping.
 *
 * Here, the solid descendant of a node are:
 *
 *   If the node has a TransparentPosition, the solid descendants of all its children
 *   Otherwise, the singleton consisting of the node itself.
 */
trait Positions extends api.Positions { self: SymbolTable =>
  type Position = scala.reflect.internal.util.Position
  val NoPosition = scala.reflect.internal.util.NoPosition
  implicit val PositionTag = ClassTag[Position](classOf[Position])

  def useOffsetPositions: Boolean = true

  /** A position that wraps a set of trees.
   *  The point of the wrapping position is the point of the default position.
   *  If some of the trees are ranges, returns a range position enclosing all ranges
   *  Otherwise returns default position that is either focused or not.
   */
  def wrappingPos(default: Position, trees: List[Tree]): Position = wrappingPos(default, trees, focus = true)
  def wrappingPos(default: Position, trees: List[Tree], focus: Boolean): Position = {
    if (useOffsetPositions) default else {
      var rest = trees
      var min = Int.MaxValue
      var max = Int.MinValue
      while (rest ne Nil) {
        val head = rest.head
        rest = rest.tail

        // TODO: a tree's range position should cover the positions of all trees it "includes"
        // (inclusion mostly refers to subtrees, but also other attributes reached through the tree, such as its annotations/modifiers);
        // concretely, a MemberDef's position should cover its annotations (scala/bug#11060)
        // Workaround, which explicitly includes annotations of traversed trees, can be removed when TODO above is resolved:
        head match { case md: MemberDef => rest = md.mods.annotations ::: rest  case _ => }

        val pos = head.pos
        if (pos.isRange) {
          min = Math.min(min, pos.start)
          max = Math.max(max, pos.end)
        }
      }
      if (min > max)
      //there are no ranges
        if (focus) default.focus else default
      else Position.range(default.source, min, default.point, max)
    }
  }

  /** A position that wraps the non-empty set of trees.
   *  The point of the wrapping position is the point of the first trees' position.
   *  If some of the trees are non-synthetic, returns a range position enclosing the non-synthetic trees
   *  Otherwise returns a synthetic offset position to point.
   */
  def wrappingPos(trees: List[Tree]): Position = {
    val headpos = trees.head.pos
    if (useOffsetPositions || !headpos.isDefined) headpos
    else wrappingPos(headpos, trees)
  }

  /** Ensure that given tree has no positions that overlap with
   *  any of the positions of `others`. This is done by
   *  shortening the range, assigning TransparentPositions
   *  to some of the nodes in `tree` or focusing on the position.
   */
  def ensureNonOverlapping(tree: Tree, others: List[Tree]): Unit ={ ensureNonOverlapping(tree, others, focus = true) }
  def ensureNonOverlapping(tree: Tree, others: List[Tree], focus: Boolean): Unit = {
    if (useOffsetPositions) return

    def isOverlapping(pos: Position) =
      pos.isRange && (others exists (pos overlaps _.pos))

    val treePos = tree.pos
    if (isOverlapping(treePos)) {
      val children = tree.children
      children foreach (ensureNonOverlapping(_, others, focus))
      if (treePos.isOpaqueRange) {
        val wpos = wrappingPos(treePos, children, focus)
        tree setPos (if (isOverlapping(wpos)) treePos.makeTransparent else wpos)
      }
    }
  }

  def rangePos(source: SourceFile, start: Int, point: Int, end: Int): Position =
    if (useOffsetPositions) Position.offset(source, point)
    else Position.range(source, start, point, end)

  abstract class ChildSolidDescendantsCollector extends Traverser {
    // don't traverse annotations
    override def traverseModifiers(mods: Modifiers): Unit = ()

    override def traverse(tree: Tree): Unit =
      if (tree ne EmptyTree) {
        if (tree.pos.isTransparent) super.traverse(tree)
        else {
          traverseSolidChild(tree)
        }
      }
    def traverseSolidChild(t: Tree): Unit
    def apply(t: Tree): Unit = super.traverse(t)
  }

  private[this] def reportTree(prefix: String, tree: Tree): Unit = {
    val source = if (tree.pos.isDefined) tree.pos.source else ""
    inform("== " + prefix + " tree [" + tree.id + "] of type " + tree.productPrefix + " at " + tree.pos.show + source)
    inform("")
    inform(treeStatus(tree))
    inform("")
  }

  private[this] def positionError(topTree: Tree, msg: String)(body: => Unit): Unit = {
    inform("======= Position error\n" + msg)
    body
    inform("\nWhile validating #" + topTree.id)
    inform(treeStatus(topTree))
    inform("\nChildren:")
    topTree.children foreach (t => inform("  " + treeStatus(t, topTree)))
    inform("=======")
    throw new ValidateException(msg)
  }

  private[this] val posStartOrdering: Ordering[Tree] = new Ordering[Tree] {
    override def compare(x: Tree, y: Tree): Int = {
      @inline def posOf(t: Tree): Int = {
        val pos = t.pos
        if (pos eq NoPosition) Int.MinValue else pos.start
      }
      Integer.compare(posOf(x), posOf(y))
    }
  }
  def validatePositions(tree: Tree): Unit = if (!useOffsetPositions) {
    object worker {
      val trace = settings.Yposdebug && settings.verbose
      val topTree = tree

      object solidChildrenCollector extends ChildSolidDescendantsCollector {
        private[this] var size = 0
        private[this] var childSolidDescendants = new Array[Tree](32)
        private[this] val spares = new java.util.ArrayList[Array[Tree]]

        def borrowArray:  Array[Tree] = {
          val borrowed = childSolidDescendants
          childSolidDescendants = if (spares.isEmpty) new Array[Tree](32) else spares.remove(spares.size - 1)
          clear()
          borrowed
        }
        def spareArray(array: Array[Tree]): Unit = {
          spares.add(array)
        }

        def child(i:Int) = childSolidDescendants(i)
        def collectedSize = size
        def sortedArray: Array[Tree] = {
          if (size > 1)
            java.util.Arrays.sort(childSolidDescendants, 0, size, posStartOrdering)
          childSolidDescendants
        }

        //we dont care about zeroing the array
        def clear(): Unit = {size = 0}

        def traverseSolidChild(t: Tree): Unit = {
          if (size == childSolidDescendants.length) {
            spareArray(childSolidDescendants)
            childSolidDescendants = java.util.Arrays.copyOf(childSolidDescendants, size << 1)
          }
          childSolidDescendants(size) = t
          size += 1
        }
      }

      def loop(tree: Tree, encltree: Tree): Unit = {
        if (!tree.isEmpty && tree.canHaveAttrs) {
          val treePos = tree.pos
          if (trace)
            inform("[%10s] %s".format("validate", treeStatus(tree, encltree)))

          if (!treePos.isDefined)
            positionError(topTree, "Unpositioned tree #" + tree.id) {
              inform("%15s %s".format("unpositioned", treeStatus(tree, encltree)))
              inform("%15s %s".format("enclosing", treeStatus(encltree)))
              encltree.children foreach (t => inform("%15s %s".format("sibling", treeStatus(t, encltree))))
            }

          solidChildrenCollector(tree)
          val numChildren = solidChildrenCollector.collectedSize

          if (treePos.isRange) {
            val enclPos = encltree.pos
            if (!enclPos.isRange)
              positionError(topTree, "Synthetic tree [" + encltree.id + "] contains nonsynthetic tree [" + tree.id + "]") {
                reportTree("Enclosing", encltree)
                reportTree("Enclosed", tree)
              }
            if (!(enclPos includes treePos))
              positionError(topTree, "Enclosing tree [" + encltree.id + "] does not include tree [" + tree.id + "]") {
                reportTree("Enclosing", encltree)
                reportTree("Enclosed", tree)
              }

            if (numChildren > 1) {
              val childSolidDescendants = solidChildrenCollector.sortedArray
              var t1 = childSolidDescendants(0)
              var t1Pos = t1.pos
              var i = 1
              while (i < numChildren) {
                val t2 = childSolidDescendants(i)
                val t2Pos = t2.pos
                if (t1Pos.overlaps(t2Pos)) {
                  positionError(topTree, "Overlapping trees") {
                    reportTree("Ancestor", tree)
                    reportTree("First overlapping", t1)
                    reportTree("Second overlapping", t2)
                  }
                }
                //why only for range
                if (t2Pos.isRange) {
                  t1 = t2
                  t1Pos = t2Pos
                }
                i += 1
              }
            }
          }
          if (numChildren > 0) {
            if (numChildren == 1) {
              val first = solidChildrenCollector.child(0)
              solidChildrenCollector.clear()
              loop(first, tree)
            } else {
              val snap = solidChildrenCollector.borrowArray
              var i = 0
              while (i < numChildren) {
                loop(snap(i), tree)
                i += 1
              }
              solidChildrenCollector.spareArray(snap)
            }
          }
        }
      }
    }
    worker.loop(tree, tree)
  }

  /** Set position of all children of a node
   *  @param  pos   A target position.
   *                Uses the point of the position as the point of all positions it assigns.
   *                Uses the start of this position as an Offset position for unpositioned trees
   *                without children.
   *  @param  trees  The children to position. All children must be positionable.
   */
  private def setChildrenPos(pos: Position, trees: List[Tree]): Unit = try {
    for (tree <- trees) {
      if (!tree.isEmpty && tree.canHaveAttrs && tree.pos == NoPosition) {
        val children = tree.children
        if (children.isEmpty) {
          tree setPos pos.focus
        } else {
          setChildrenPos(pos, children)
          tree setPos wrappingPos(pos, children)
        }
      }
    }
  } catch {
    case ex: Exception =>
      inform("error while set children pos "+pos+" of "+trees)
      throw ex
  }

  class ValidateException(msg : String) extends Exception(msg)

  /** A locator for trees with given positions.
   *  Given a position `pos`, locator.apply returns
   *  the smallest tree that encloses `pos`.
   */
  class Locator(pos: Position) extends Traverser {
    var last: Tree = _
    def locateIn(root: Tree): Tree = {
      this.last = EmptyTree
      traverse(root)
      this.last
    }
    protected def isEligible(t: Tree) = !t.pos.isTransparent
    override def traverse(t: Tree): Unit = {
      t match {
        case tt : TypeTree if tt.original != null && (tt.pos includes tt.original.pos) =>
          traverse(tt.original)
        case _ =>
          if (t.pos includes pos) {
            if (isEligible(t)) last = t
            super.traverse(t)
          } else t match {
            case mdef: MemberDef =>
              val annTrees = mdef.mods.annotations match {
                case Nil if mdef.symbol != null =>
                  // After typechecking, annotations are moved from the modifiers
                  // to the annotation on the symbol of the annotatee.
                  mdef.symbol.annotations.map(_.original)
                case anns => anns
              }
              traverseTrees(annTrees)
            case _ =>
          }
      }
    }
  }

  class TypedLocator(pos: Position) extends Locator(pos) {
    override protected def isEligible(t: Tree) = super.isEligible(t) && t.tpe != null
  }

  trait PosAssigner extends InternalTraverser {
    var pos: Position
  }
  protected[this] lazy val posAssigner: PosAssigner = new DefaultPosAssigner

  protected class DefaultPosAssigner extends PosAssigner {
    var pos: Position = _
    override def traverse(t: Tree): Unit = {
      if (!t.canHaveAttrs) ()
      else if (t.pos == NoPosition) {
        t.setPos(pos)
        t.traverse(this)   // TODO: bug? shouldn't the traverse be outside of the if?
        // @PP: it's pruning whenever it encounters a node with a
        // position, which I interpret to mean that (in the author's
        // mind at least) either the children of a positioned node will
        // already be positioned, or the children of a positioned node
        // do not merit positioning.
        //
        // Whatever the author's rationale, it does seem like a bad idea
        // to press on through a positioned node to find unpositioned
        // children beneath it and then to assign whatever happens to
        // be in `pos` to such nodes. There are supposed to be some
        // position invariants which I can't imagine surviving that.
      }
    }
  }

  /** Position a tree.
   *  This means: Set position of a node and position all its unpositioned children.
   */
  def atPos[T <: Tree](pos: Position)(tree: T): T = {
    if (useOffsetPositions || !pos.isOpaqueRange) {
      posAssigner.pos = pos
      posAssigner.traverse(tree)
      tree
    }
    else {
      if (!tree.isEmpty && tree.canHaveAttrs && tree.pos == NoPosition) {
        tree.setPos(pos)
        val children = tree.children
        if (children.nonEmpty) {
          if (children.tail.isEmpty) atPos(pos)(children.head)
          else setChildrenPos(pos, children)
        }
      }
      tree
    }
  }
}


text:
define(['jimu/shared/BaseVersionManager'],
function(BaseVersionManager) {
  function VersionManager(){
    this.versions = [{
      version: '1.0',
      upgrader: function(oldConfig){
        return oldConfig;
      }
    }, {
      version: '1.1',
      upgrader: function(oldConfig){
        return oldConfig;
      }
    }, {
      version: '1.2',
      upgrader: function(oldConfig){
        return oldConfig;
      }
    }, {
      version: '1.3',
      upgrader: function(oldConfig){
        return oldConfig;
      }
    }, {
      version: '1.4',
      upgrader: function(oldConfig){
        return oldConfig;
      }
    }, {
      version: '2.0Beta',
      upgrader: function(oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.0',
      upgrader: function(oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.0.1',
      upgrader: function(oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.1',
      upgrader: function(oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.2',
      upgrader: function (oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.3',
      upgrader: function (oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.4',
      upgrader: function (oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.5',
      upgrader: function (oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.6',
      upgrader: function (oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.7',
      upgrader: function (oldConfig) {
        var newConfig = oldConfig;
        if (newConfig) {
          newConfig.layerState = null;
          newConfig.isZoom = false;
        }
        return newConfig;
      }
    }, {
      version: '2.8',
      upgrader: function (oldConfig) {
        var newConfig = oldConfig;
        if (newConfig) {
          newConfig.handleColor = "";
        }
        return newConfig;
      }
    }, {
      version: '2.9',
      upgrader: function (oldConfig) {
        var newConfig = oldConfig;
        if (newConfig) {
          newConfig.layerMode = "single";
          newConfig.defaultLayers = [];
        }
        return newConfig;
      }
    }, {
      version: '2.10',
      upgrader: function (oldConfig) {
        return oldConfig;
      }
    }, {
      version: '2.11',
      upgrader: function (oldConfig) {
        var newConfig = oldConfig;
        if (newConfig) {
          newConfig.invertPlacement = false;
        }
        return newConfig;
      }
    }, {
      version: '2.12',
      upgrader: function (oldConfig) {
        var newConfig = oldConfig;
        if (newConfig) {
          newConfig.isHidePanel = false;
        }
        return newConfig;
      }
    }];
  }

  VersionManager.prototype = new BaseVersionManager();
  VersionManager.prototype.constructor = VersionManager;
  return VersionManager;
});


text:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;

namespace CloudRoboticsDefTool
{
    class DeviceRoutingProcessor
    {
        private string sqlConnectionString;
        private ApplicationException ae = null;

        public DeviceRoutingProcessor(string sqlConnectionString)
        {
            this.sqlConnectionString = sqlConnectionString;
        }

        public List<DeviceRoutingEntity> GetDeviceRoutings(string deviceId)
        {
            deviceId = deviceId.Replace("*", "%");

            string sqltext = "SELECT DeviceId,RoutingKeyword,TargetType,TargetDeviceGroupId,TargetDeviceId,"
                           + "Status,Description,Registered_DateTime "
                           + "FROM RBFX.DeviceRouting "
                           + "WHERE DeviceId LIKE @p1 ORDER BY DeviceId,RoutingKeyword";

            List<DeviceRoutingEntity> listOfDeviceRoutings = new List<DeviceRoutingEntity>();

            SqlConnection conn = new SqlConnection(this.sqlConnectionString);
            try
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand(sqltext, conn);
                AddSqlParameter(ref cmd, "@p1", SqlDbType.NVarChar, deviceId);
                SqlDataReader reader = cmd.ExecuteReader();

                if (!reader.HasRows)
                {
                    ae = new ApplicationException("No record was found in RBFX.DeviceRouting");
                    throw ae;
                }

                while (reader.Read())
                {
                    DeviceRoutingEntity devRoutingEntity = new DeviceRoutingEntity();
                    devRoutingEntity.DeviceId = reader.GetString(0);
                    devRoutingEntity.RoutingKeyword = reader.GetString(1);
                    devRoutingEntity.TargetType = reader.GetString(2);
                    if (!reader.IsDBNull(3))
                    {
                        devRoutingEntity.TargetDeviceGroupId = reader.GetString(3);
                    }
                    else
                    {
                        devRoutingEntity.TargetDeviceGroupId = string.Empty;
                    }

                    if (!reader.IsDBNull(4))
                    {
                        devRoutingEntity.TargetDeviceId = reader.GetString(4);
                    }
                    else
                    {
                        devRoutingEntity.TargetDeviceId = string.Empty;
                    }

                    devRoutingEntity.Status = reader.GetString(5);

                    if (!reader.IsDBNull(6))
                    {
                        devRoutingEntity.Description = reader.GetString(6);
                    }
                    else
                    {
                        devRoutingEntity.Description = string.Empty;
                    }

                    if (!reader.IsDBNull(7))
                    {
                        devRoutingEntity.Registered_DateTime = reader.GetDateTime(7);
                    }

                    listOfDeviceRoutings.Add(devRoutingEntity);
                }

                reader.Close();
                conn.Close();
            }
            catch (Exception ex)
            {
                if (ex.GetType().Equals(ae))
                    conn.Close();
                throw (ex);
            }

            return listOfDeviceRoutings;

        }

        public void insertDeviceRouting(DeviceRoutingEntity devRoutingEntity)
        {
            validateTargetId(devRoutingEntity);

            string sqltext = "INSERT INTO RBFX.DeviceRouting ("
                + "DeviceId,RoutingKeyword,TargetType,TargetDeviceGroupId,TargetDeviceId,"
                + "Status,Description,Registered_DateTime"
                + ") VALUES "
                + "(@p1,@p2,@p3,@p4,@p5,@p6,@p7,@p8)";

            SqlConnection conn = new SqlConnection(this.sqlConnectionString);
            try
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand(sqltext, conn);
                AddSqlParameter(ref cmd, "@p1", SqlDbType.NVarChar, devRoutingEntity.DeviceId);
                AddSqlParameter(ref cmd, "@p2", SqlDbType.NVarChar, devRoutingEntity.RoutingKeyword);
                AddSqlParameter(ref cmd, "@p3", SqlDbType.NVarChar, devRoutingEntity.TargetType);
                AddSqlParameter(ref cmd, "@p4", SqlDbType.NVarChar, devRoutingEntity.TargetDeviceGroupId);
                AddSqlParameter(ref cmd, "@p5", SqlDbType.NVarChar, devRoutingEntity.TargetDeviceId);
                AddSqlParameter(ref cmd, "@p6", SqlDbType.NVarChar, devRoutingEntity.Status);
                AddSqlParameter(ref cmd, "@p7", SqlDbType.NVarChar, devRoutingEntity.Description);
                AddSqlParameter(ref cmd, "@p8", SqlDbType.DateTime, devRoutingEntity.Registered_DateTime);
                cmd.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                conn.Close();
                throw ex;
            }
        }

        public void updateDeviceRouting(DeviceRoutingEntity devRoutingEntity)
        {
            validateTargetId(devRoutingEntity);

            string sqltext = "UPDATE RBFX.DeviceRouting SET "
                + "TargetType = @p3,"
                + "TargetDeviceGroupId = @p4,"
                + "TargetDeviceId = @p5,"
                + "Status = @p6,"
                + "Description = @p7,"
                + "Registered_DateTime = @p8 "
                + "WHERE DeviceId = @p1 AND RoutingKeyword = @p2";

            SqlConnection conn = new SqlConnection(this.sqlConnectionString);
            try
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand(sqltext, conn);
                AddSqlParameter(ref cmd, "@p1", SqlDbType.NVarChar, devRoutingEntity.DeviceId);
                AddSqlParameter(ref cmd, "@p2", SqlDbType.NVarChar, devRoutingEntity.RoutingKeyword);
                AddSqlParameter(ref cmd, "@p3", SqlDbType.NVarChar, devRoutingEntity.TargetType);
                AddSqlParameter(ref cmd, "@p4", SqlDbType.NVarChar, devRoutingEntity.TargetDeviceGroupId);
                AddSqlParameter(ref cmd, "@p5", SqlDbType.NVarChar, devRoutingEntity.TargetDeviceId);
                AddSqlParameter(ref cmd, "@p6", SqlDbType.NVarChar, devRoutingEntity.Status);
                AddSqlParameter(ref cmd, "@p7", SqlDbType.NVarChar, devRoutingEntity.Description);
                AddSqlParameter(ref cmd, "@p8", SqlDbType.DateTime, devRoutingEntity.Registered_DateTime);
                cmd.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                conn.Close();
                throw ex;
            }
        }

        public void deleteDeviceRouting(string deviceId, string routingKeyword)
        {
            string sqltext = "DELETE FROM RBFX.DeviceRouting WHERE DeviceId = @p1 AND RoutingKeyword = @p2";

            SqlConnection conn = new SqlConnection(this.sqlConnectionString);
            try
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand(sqltext, conn);
                AddSqlParameter(ref cmd, "@p1", SqlDbType.NVarChar, deviceId);
                AddSqlParameter(ref cmd, "@p2", SqlDbType.NVarChar, routingKeyword);
                cmd.ExecuteNonQuery();

                conn.Close();
            }
            catch (Exception ex)
            {
                conn.Close();
                throw ex;
            }
        }

        private void validateTargetId(DeviceRoutingEntity devRoutingEntity)
        {
            if (devRoutingEntity.TargetType == CRoboticsConst.TypeDeviceGroup)
            {
                if (!existDeviceGroupId(devRoutingEntity.TargetDeviceGroupId))
                {
                    ae = new ApplicationException("Input Device Group ID not exist in RBFX.DeviceGroup");
                    throw ae;
                }
            }
            else if (devRoutingEntity.TargetType == CRoboticsConst.TypeDevice)
            {
                if (!existDeviceId(devRoutingEntity.TargetDeviceId))
                {
                    ae = new ApplicationException("Input Device ID not exist in RBFX.DeviceMaster");
                    throw ae;
                }
            }
            else
            {
                ae = new ApplicationException($"Input Target Type must be \"{CRoboticsConst.TypeDeviceGroup}\" or \"{CRoboticsConst.TypeDevice}\"");
                throw ae;
            }
        }

        private bool existDeviceGroupId(string deviceGroupId)
        {
            string sqltext = "SELECT DeviceGroupId FROM RBFX.DeviceGroup WHERE DeviceGroupId = @p1";

            SqlConnection conn = new SqlConnection(this.sqlConnectionString);
            try
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand(sqltext, conn);
                AddSqlParameter(ref cmd, "@p1", SqlDbType.NVarChar, deviceGroupId);
                SqlDataReader reader = cmd.ExecuteReader();

                if (!reader.HasRows)
                {
                    return false;
                }

                reader.Close();
                conn.Close();
            }
            catch (Exception ex)
            {
                conn.Close();
                throw ex;
            }

            return true;
        }

        private bool existDeviceId(string deviceId)
        {
            string sqltext = "SELECT DeviceId FROM RBFX.DeviceMaster WHERE DeviceId = @p1";

            SqlConnection conn = new SqlConnection(this.sqlConnectionString);
            try
            {
                conn.Open();

                SqlCommand cmd = new SqlCommand(sqltext, conn);
                AddSqlParameter(ref cmd, "@p1", SqlDbType.NVarChar, deviceId);
                SqlDataReader reader = cmd.ExecuteReader();

                if (!reader.HasRows)
                {
                    return false;
                }

                reader.Close();
                conn.Close();
            }
            catch (Exception ex)
            {
                conn.Close();
                throw ex;
            }

            return true;
        }

        private void AddSqlParameter(ref SqlCommand cmd, string ParameterName, SqlDbType type, Object value)
        {
            SqlParameter param = cmd.CreateParameter();
            param.ParameterName = ParameterName;
            param.SqlDbType = type;
            param.Direction = ParameterDirection.Input;
            param.Value = value;
            cmd.Parameters.Add(param);
        }

    }
}


text:
module.exports = function bridge(nativeWindow, win, unwrapEphemeral){
  function isObject(o){
    if (o == null) return o !== null && o !== undefined;
    return typeof o === 'object' || typeof o === 'function';
  }

  function encode(msg){
    if (msg == null)
      return '{}';
    else if (typeof msg === 'object')
      return JSON.stringify(msg);
    else if (typeof msg === 'string')
      return msg;
    else
      throw new TypeError("Tried to encode invalid type");
  }

  function decode(msg){
    try {
      return JSON.parse(msg);
    } catch (e) {
      return { error: e };
    }
  }

  var _call   = Function.prototype.call,
      _apply  = Function.prototype.apply,
      _bind   = Function.prototype.bind,
      _slice  = Array.prototype.slice,
      _hasOwn = Object.prototype.hasOwnProperty,
      char    = String.fromCharCode;

  var foreignObjects = new WeakMap,
      foreignIDs = new WeakMap,
      localObjects = new WeakMap,
      localIDs = new WeakMap,
      localCanonicals = [],
      foreignCanonicals = Object.create(null);

  var TOKEN       = char(1),
      LITERAL     = char(2),
      TRUE        = [TOKEN, 1],
      FALSE       = [TOKEN, 2],
      UNDEFINED   = [TOKEN, 3],
      NULL        = [TOKEN, 4],
      NAN         = [TOKEN, 5],
      INFINITY    = [TOKEN, 6],
      NEGINFINITY = [TOKEN, 7],
      NEGZERO     = [TOKEN, 8],
      ZERO        = [TOKEN, 9];

  var tokens = [, true, false, undefined, null, NaN, Infinity, -Infinity, -0, 0];

  var pipe = function(source, listeners){
    source.onmessage = function onmessage(msg){
      var res = {};
      msg = decode(msg);
      listeners[msg.type] && listeners[msg.type](msg.msg, res);
      return encode(res.result === undefined ? {} : res.result);
    };

    return {
      send: function send(type, msg){
        msg = { type: type, msg: msg };
        return decode(source.send(encode(msg)));
      },
      listen: function listen(type, handler){
        listeners[type] = handler;
      }
    };
  }(nativeWindow || appjs, {});

  if (!nativeWindow) {
    var LOCAL = char(15), FOREIGN = char(16);
    var logger = function logger(type, error){
      if (typeof node !== 'undefined') {
        logger = function logger(type, error){
          node.process.emit('appjs-log', type, 'browser', error);
        };
        logger(type, context, error);
      }
    }
  } else {
    var LOCAL = char(16), FOREIGN = char(15);
    var logger = function logger(type, error){
      process.emit('appjs-log', type, 'node', error);
    };
    nativeWindow.once('context-released', function released(){
      mirror = {
        type      : function(){ return ['object'] },
        keys      : function(){ return [] },
        enumerate : function(){ return [] },
        props     : function(){ return [] },
        get       : function(){ return UNDEFINED },
        set       : function(){ return TRUE },
        proto     : function(){ return NULL },
        has       : function(){ return FALSE },
        hasOwn    : function(){ return FALSE },
        delete    : function(){ return TRUE },
        define    : function(){ return TRUE },
        describe  : function(){ return UNDEFINED },
        construct : function(){ return UNDEFINED },
        apply     : function(){ return UNDEFINED }
      };
      unwrap = wrap = pipe.send = pipe.listen = function(){ return {} };
      nativeWindow.onmessage = function(){ return ''; }
      nativeWindow = null;
      foreignObjects = foreignIDs = foreignCanonicals = null;
      localObjects = localIDs = localCanonicals = null;
    });
  }

  wrap(nativeWindow ? global : window);

  function initForeign(obj, proxy){
    foreignObjects.set(proxy, obj);
    foreignIDs.set(obj, proxy);
    foreignCanonicals[obj[1]] = obj;
    return proxy;
  }

  function unwrap(obj){
    if (!isObject(obj)) {
      return obj;
    } else if (obj[0] === TOKEN) {
      return tokens[obj[1]];
    } else if (obj[0] === LITERAL) {
      return obj[1];
    } else if (obj[0] === FOREIGN) {
      if (obj[1] in foreignCanonicals) {
        return foreignIDs.get(foreignCanonicals[obj[1]]);
      } else {
        return initForeign(obj, new Mirror(obj));
      }
    } else if (obj[0] === LOCAL && localCanonicals[obj[1]]) {
      return localObjects.get(localCanonicals[obj[1]]);
    } else {
      return obj;
    }
  }

  function wrap(obj){
    if (!isObject(obj)) {
      switch (typeof obj) {
        case 'boolean':      return obj ? TRUE : FALSE;
        case 'undefined':    return UNDEFINED;
        case 'object':       return NULL;
        case 'string':       return [LITERAL, obj];
        case 'number':
          switch (obj) {
            case Infinity:   return INFINITY;
            case -Infinity:  return NEGINFINITY;
            case NaN:        return NAN;
            case 0:          return 1 / obj === -Infinity ? NEGZERO : ZERO;
            default:         return obj !== obj ? NAN : [LITERAL, obj];
          }
      }
    } else if (foreignObjects.has(obj)) {
      return foreignObjects.get(obj);
    } else if (localIDs.has(obj)) {
      return localIDs.get(obj);
    } else {
      var id = [LOCAL, localCanonicals.length];
      localObjects.set(id, obj);
      localIDs.set(obj, id);
      localCanonicals[id[1]] = id;
      return id;
    }
  }

  var mirror = {
    type: function type(obj){
      return [typeof obj];
    },
    keys: function keys(obj){
      return Object.keys(obj);
    },
    enumerate: function enumerate(obj){
      var i=0, k=[];
      for (k[i++] in obj);
      return k;
    },
    props: function props(obj){
      return Object.getOwnPropertyNames(obj);
    },
    get: function get(obj, key){
      return wrap(obj[key]);
    },
    proto: function proto(obj){
      return wrap(obj.__proto__);
    },
    has: function has(obj, key){
      return wrap(key in obj);
    },
    hasOwn: function hasOwn(obj, key){
      return wrap(_hasOwn.call(obj, key));
    },
    delete: function delete_(obj, key){
      delete obj[key];
      return TRUE;
    },
    define: function define(obj, key, desc){
      if ('value' in desc) {
        desc.value = unwrap(desc.value);
      } else {
        if (desc.get) desc.get = unwrap(desc.get);
        if (desc.set) desc.set = unwrap(desc.set);
      }
      Object.defineProperty(obj, key, desc);
      return TRUE;
    },
    describe: function describe(obj, key){
      var desc = Object.getOwnPropertyDescriptor(obj, key);
      if (desc) {
        desc.configurable = true;
        if ('value' in desc) {
          if (desc.value === undefined) desc.value = obj[key];
          desc.value = wrap(desc.value);
        } else {
          if (desc.get) desc.get = wrap(desc.get);
          if (desc.set) desc.set = wrap(desc.set);
        }
        return desc;
      } else if (desc === undefined && _hasOwn.call(obj, key)) {
        return { configurable: true,
                 enumerable: true,
                 writable: true,
                 value: wrap(obj[key]) };
      } else {
        return UNDEFINED;
      }
    },
    construct: function construct(obj, args){
      try {
        return wrap(new (_bind.apply(obj, [null].concat(args.map(unwrap)))));
      } catch (e) {
        logger('Constructor throw', e);
        return wrap(e);
      }
    },
  };

  if (nativeWindow) {
    mirror.apply = function apply(obj, receiver, args){
      try {
        return wrap(_apply.call(obj, unwrap(receiver), args.map(unwrap)));
      } catch (e) {
        logger('Apply throw', e);
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      obj[key] = unwrap(value);
      return TRUE;
    };
  } else {
    var proxyForProxy = function proxyForProxy(fn){
      return function(){ return _apply.call(fn, this, arguments) };
    };
    mirror.apply = function apply(obj, receiver, args){
      // workaround for bug where proxy functions are not valid DOM event handlers
      args = args.map(unwrap);
      if (obj.name === 'addEventListener' && typeof args[1] === 'function') {
        args[1] = proxyForProxy(args[1]);
      }
      try {
        return wrap(_apply.call(obj, unwrap(receiver), args));
      } catch (e) {
        logger('Apply throw', e);
        return wrap(e);
      }
    };
    mirror.set = function set(obj, key, value){
      value = unwrap(value);
      obj[key] = value;
      if (obj[key] === null && typeof value === 'function') {
        // workaround for bug where proxy functions are not valid DOM event handlers
        obj[key] = proxyForProxy(value);
      }
      return TRUE;
    };
  }

  function Mirror(obj){
    var self = this;
    var type = pipe.send('Δtype', obj)[0];
    this.id = obj;
    this.id2 = obj.concat(null);
    this.id3 = obj.concat(null, null);
    if (type === 'function') {
      return Proxy.createFunction(this,
        function(){ return self.apply(this, _slice.call(arguments)) },
        function(){ return self.construct(_slice.call(arguments)) }
      );
    } else {
      return Proxy.create(this, unwrap(pipe.send('Δproto', this.id)));
    }
  }

  Mirror.prototype = {
    keys: function keys(){
      return pipe.send('Δkeys', this.id);
    },
    enumerate: function enumerate(){
      return pipe.send('Δenumerate', this.id);
    },
    getOwnPropertyNames: function getOwnPropertyNames(){
      return pipe.send('Δprops', this.id);
    },
    get: function get(rcvr, key){
      this.id2[2] = key;
      return unwrap(pipe.send('Δget', this.id2));
    },
    set: function set(rcvr, key, value){
      this.id3[2] = key;
      this.id3[3] = wrap(value);
      pipe.send('Δset', this.id3);
      return true;
    },
    getOwnPropertyDescriptor: function getOwnPropertyDescriptor(key){
      this.id2[2] = key;
      var desc = pipe.send('Δdescribe', this.id2);
      if (desc) {
        desc.configurable = true;
        if ('value' in desc) {
          desc.value = unwrap(desc.value);
        } else {
          if (desc.get) desc.get = unwrap(desc.get);
          if (desc.set) desc.set = unwrap(desc.set);
        }
      }
      return desc;
    },
    has: function has(key){
      this.id2[2] = key;
      return pipe.send('Δhas', this.id2);
    },
    hasOwn: function hasOwn(key){
      this.id2[2] = key;
      return pipe.send('ΔhasOwn', this.id2);
    },
    delete: function delete_(key){
      this.id2[2] = key;
      pipe.send('Δdelete', this.id2);
      return true;
    },
    defineProperty: function defineProperty(key, desc){
      this.id3[2] = key;
      this.id3[3] = desc;
      if ('value' in desc) {
        desc.value = wrap(desc.value);
      } else {
        if (desc.get) desc.get = wrap(desc.get);
        if (desc.set) desc.set = wrap(desc.set);
      }
      pipe.send('Δdefine', this.id3);
      return true;
    },
    apply: function apply(receiver, args){
      this.id3[2] = wrap(receiver);
      this.id3[3] = args.map(wrap);
      return unwrap(pipe.send('Δapply', this.id3));
    },
    construct: function construct(args){
      this.id2[2] = args.map(wrap);
      return unwrap(pipe.send('Δconstruct', this.id2));
    }
  };

  Object.keys(mirror).forEach(function(key){
    pipe.listen('Δ'+key, function(val, res){
      res.result = mirror[key](unwrap(val), val[2], val[3]);
    });
  });

  if (nativeWindow) {
    void function(){
      var id = [FOREIGN, 0];
      unwrapEphemeral(win).morph(Mirror.prototype, {
        id:  id,
        id2: [FOREIGN, 0, null],
        id3: [FOREIGN, 0, null, null]
      });
      initForeign(id, win);
    }();
  } else {
    window.node = unwrap([FOREIGN, 0]);
  }
}


text:
// Make sure the compiler doesn't complain about missing Xml comments and CLS compliance
// 0108: suppress "Foo hides inherited member Foo. Use the new keyword if hiding was intended." when a controller and its abstract parent are both processed
// 0114: suppress "Foo.BarController.Baz()' hides inherited member 'Qux.BarController.Baz()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword." when an action (with an argument) overrides an action in a parent controller
#pragma warning disable 1591, 3008, 3009, 0108, 0114
#region T4MVC

using System;
using System.Diagnostics;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Mvc.Html;
using System.Web.Routing;
using T4MVC;
namespace WebExtras.DemoApp.Areas.JQueryUI.Controllers
{
    public partial class MvcController
    {
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public MvcController() { }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected MvcController(Dummy d) { }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(ActionResult result)
        {
            var callInfo = result.GetT4MVCResult();
            return RedirectToRoute(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToAction(Task<ActionResult> taskResult)
        {
            return RedirectToAction(taskResult.Result);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(ActionResult result)
        {
            var callInfo = result.GetT4MVCResult();
            return RedirectToRoutePermanent(callInfo.RouteValueDictionary);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        protected RedirectToRouteResult RedirectToActionPermanent(Task<ActionResult> taskResult)
        {
            return RedirectToActionPermanent(taskResult.Result);
        }

        [NonAction]
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public virtual System.Web.Mvc.ActionResult JQueryUIHtml()
        {
            return new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.JQueryUIHtml);
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public MvcController Actions { get { return MVC.JQueryUI.Mvc; } }
        [GeneratedCode("T4MVC", "2.0")]
        public readonly string Area = "JQueryUI";
        [GeneratedCode("T4MVC", "2.0")]
        public readonly string Name = "Mvc";
        [GeneratedCode("T4MVC", "2.0")]
        public const string NameConst = "Mvc";
        [GeneratedCode("T4MVC", "2.0")]
        static readonly ActionNamesClass s_actions = new ActionNamesClass();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ActionNamesClass ActionNames { get { return s_actions; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionNamesClass
        {
            public readonly string Index = "Index";
            public readonly string CoreHtml = "CoreHtml";
            public readonly string CoreForm = "CoreForm";
            public readonly string JQueryUIHtml = "JQueryUIHtml";
            public readonly string JQueryUIForm = "JQueryUIForm";
            public readonly string ActionMessageDemo = "ActionMessageDemo";
            public readonly string ActionResults = "ActionResults";
        }

        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionNameConstants
        {
            public const string Index = "Index";
            public const string CoreHtml = "CoreHtml";
            public const string CoreForm = "CoreForm";
            public const string JQueryUIHtml = "JQueryUIHtml";
            public const string JQueryUIForm = "JQueryUIForm";
            public const string ActionMessageDemo = "ActionMessageDemo";
            public const string ActionResults = "ActionResults";
        }

        static readonly ActionParamsClass_JQueryUIHtml s_params_JQueryUIHtml = new ActionParamsClass_JQueryUIHtml();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ActionParamsClass_JQueryUIHtml JQueryUIHtmlParams { get { return s_params_JQueryUIHtml; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ActionParamsClass_JQueryUIHtml
        {
            public readonly string msg = "msg";
        }
        static readonly ViewsClass s_views = new ViewsClass();
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public ViewsClass Views { get { return s_views; } }
        [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
        public class ViewsClass
        {
            static readonly _ViewNamesClass s_ViewNames = new _ViewNamesClass();
            public _ViewNamesClass ViewNames { get { return s_ViewNames; } }
            public class _ViewNamesClass
            {
                public readonly string ActionResults = "ActionResults";
                public readonly string CoreForm = "CoreForm";
                public readonly string CoreHtml = "CoreHtml";
                public readonly string JQueryUIForm = "JQueryUIForm";
                public readonly string JQueryUIHtml = "JQueryUIHtml";
            }
            public readonly string ActionResults = "~/Areas/JQueryUI/Views/Mvc/ActionResults.cshtml";
            public readonly string CoreForm = "~/Areas/JQueryUI/Views/Mvc/CoreForm.cshtml";
            public readonly string CoreHtml = "~/Areas/JQueryUI/Views/Mvc/CoreHtml.cshtml";
            public readonly string JQueryUIForm = "~/Areas/JQueryUI/Views/Mvc/JQueryUIForm.cshtml";
            public readonly string JQueryUIHtml = "~/Areas/JQueryUI/Views/Mvc/JQueryUIHtml.cshtml";
        }
    }

    [GeneratedCode("T4MVC", "2.0"), DebuggerNonUserCode]
    public partial class T4MVC_MvcController : WebExtras.DemoApp.Areas.JQueryUI.Controllers.MvcController
    {
        public T4MVC_MvcController() : base(Dummy.Instance) { }

        [NonAction]
        partial void IndexOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult Index()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.Index);
            IndexOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void CoreHtmlOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult CoreHtml()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.CoreHtml);
            CoreHtmlOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void CoreFormOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult CoreForm()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.CoreForm);
            CoreFormOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void JQueryUIHtmlOverride(T4MVC_System_Web_Mvc_ActionResult callInfo, bool? msg);

        [NonAction]
        public override System.Web.Mvc.ActionResult JQueryUIHtml(bool? msg)
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.JQueryUIHtml);
            ModelUnbinderHelpers.AddRouteValues(callInfo.RouteValueDictionary, "msg", msg);
            JQueryUIHtmlOverride(callInfo, msg);
            return callInfo;
        }

        [NonAction]
        partial void JQueryUIFormOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult JQueryUIForm()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.JQueryUIForm);
            JQueryUIFormOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void ActionMessageDemoOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult ActionMessageDemo()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.ActionMessageDemo);
            ActionMessageDemoOverride(callInfo);
            return callInfo;
        }

        [NonAction]
        partial void ActionResultsOverride(T4MVC_System_Web_Mvc_ActionResult callInfo);

        [NonAction]
        public override System.Web.Mvc.ActionResult ActionResults()
        {
            var callInfo = new T4MVC_System_Web_Mvc_ActionResult(Area, Name, ActionNames.ActionResults);
            ActionResultsOverride(callInfo);
            return callInfo;
        }

    }
}

#endregion T4MVC
#pragma warning restore 1591, 3008, 3009, 0108, 0114


text:
layout: post
title: "Bloom Filter in HBase"
excerpt: "Bloom Filter intro"
categories: knownotes
tags: [hbase]
comments: true
share: true
author: chungyu
---

> [Julian Dontcheff's Database Blog](https://juliandontcheff.wordpress.com/2012/08/28/bloom-filters-for-dbas/)

A Bloom filter is a probabilistic algorithm for doing **existence tests** in less memory than a full list of keys would require. In other words, a Bloom filter is a method for representing a set of n elements (also called keys) to support membership queries.

> [Commiter's response in quora](https://www.quora.com/How-are-bloom-filters-used-in-HBase)

* When a HFile is opened, typically when a region is deployed to a RegionServer, the bloom filter is loaded into memory and used to determine if a given key is in that store file. They can be scoped on a row key or column key level, where the latter needs more space as it has to store many more keys compared to just using the row keys
* Keep in mind that HBase only has a block index per file, which is rather coarse grained and tells the reader that a key *may* be in the file because it falls into a start and end key range in the block index. But if the key is actually present can only be determined by loading that block and scanning it.
*  If you are doing Row scans, then Row+Col doesn't buy you anything.  **A row bloom can filter on a Row+Col get, but not the other way around.**  However, the problem with Row blooms is that you may have a ton of column-level puts and end up with a scenario where a Row is present in every StoreFile.  Then the bloom filter is wasteful because it's always positive.
* Since the reads are in parallel, you don't see much perf gain on an individual get, which is dominated by disk read latency.  If later, we allow a serial get option (beneficial for data that is overwritten), then you'll see bloom filters have immediate benefit on read latency.

> [hbase scan and bloom filter](http://xitong.iteye.com/blog/1797420)

* scan是一个范围,如果是row的bloomfilter不命中只能说明该rowkey不在此storefile中,但next rowkey可能在。而rowcol的bloomfilter就不一样了,如果rowcol的bloomfilter没有命中表明该qualifiy不在这个storefile中,因此这次scan就不需要scan此storefile了!


text:
package org.llaith.toolkit.core.status.impl;

import org.llaith.toolkit.core.memo.Memo;
import org.llaith.toolkit.core.status.ExceptionToken;
import org.llaith.toolkit.core.status.StatusLevel;

/**
 *
 */
public class ExceptionTokenImpl implements ExceptionToken {

    private final StatusLogger logger;
    private final Context context;
    private final Object id;
    private final StatusLevel level;

    public ExceptionTokenImpl(final StatusLogger logger, final Context context, final Object id, final StatusLevel level) {
        this.logger = logger;
        this.context = context;
        this.id = id;
        this.level = level;
    }

    @Override
    public ExceptionToken update(final Memo memo, final Exception exception) {

        if (memo != null) {
            this.logger.reportMessage(
                    new ElapsedContext(this.context),
                    this.id,
                    this.level,
                    memo);
        }

        if (exception != null) {
            this.logger.reportException(
                    new ElapsedContext(this.context),
                    this.id,
                    this.level,
                    exception);
        }

        return this;

    }

}


text:
package May2021GoogLeetcode;

import java.util.List;

public class _0093RestoreIPAddress {

	public static void main(String[] args) {
		System.out.println(restoreIpAddresses("25525511135"));
		System.out.println(restoreIpAddresses("0000"));
		System.out.println(restoreIpAddresses("1111"));
		System.out.println(restoreIpAddresses("010010"));
		System.out.println(restoreIpAddresses("101023"));
	}

	public static List<String> restoreIpAddresses(String s) {

	}
}


text:
package com.intellij.refactoring.ui;

import org.jetbrains.annotations.NonNls;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

/**
 * @author dsl
 */
public abstract class EnableDisableAction extends AbstractAction {
  public void actionPerformed(ActionEvent e) {
    if (getTable().isEditing()) return;
    int[] rows = getTable().getSelectedRows();
    if (rows.length > 0) {
      boolean valueToBeSet = false;
      for (final int row : rows) {
        if (!isRowChecked(row)) {
          valueToBeSet = true;
          break;
        }
      }
      applyValue(rows, valueToBeSet);
//          myMyTableModel.fireTableRowsUpdated(rows[0], rows[rows.length - 1]);
    }
    getTable().requestFocus();
  }

  protected abstract JTable getTable();

  protected abstract void applyValue(int[] rows, boolean valueToBeSet);

  protected abstract boolean isRowChecked(int row);

  public void register() {// make SPACE check/uncheck selected rows
    JTable table = getTable();
    @NonNls InputMap inputMap = table.getInputMap();
    inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "enable_disable");
    @NonNls final ActionMap actionMap = table.getActionMap();
    actionMap.put("enable_disable", this);
  }
}


text:
package com.vmware.spring.workshop.facade.beans;

import com.vmware.spring.workshop.dto.banking.BankDTO;
import com.vmware.spring.workshop.dto.banking.BranchDTO;

/**
 * @author lgoldstein
 */
public class BranchBean extends AbstractDTOBean<BranchDTO> {
    private BankDTO    _bankValue;
    public BranchBean() {
        super();
    }

    public BranchBean(BranchDTO dtoValue) {
        super(dtoValue);
    }

    public BranchBean(BankDTO bank, BranchDTO dtoValue) {
        this(dtoValue);
        _bankValue = bank;
    }

    public BankDTO getBankValue() {
        return _bankValue;
    }

    public void setBankValue(BankDTO bankValue) {
        _bankValue = bankValue;
    }
}


text:
pain.howMuchMorphine

                 pain.administrationType

                <select ng-change="vm.updateRegistration()"
                        ng-model="vm.registration.morphineType">
                    <option value='pain.oral' translate>pain.oral</option>
                    <option value='pain.intravenous' translate>pain.intravenous</option>
                </select>

            pain.dose
                <input type="number"
                       min="0"
                       style="direction: rtl;"
                       ng-change="vm.updateRegistration()"
                       ng-model="vm.registration.morphineDose">

                <select class="item item-input item-select"
                        ng-change="vm.updateRegistration()"
                        ng-model="vm.registration.morphineMeasureUnit">
                    <option value='pain.mg' translate>pain.mg</option>
                    <option value='pain.mgHour' translate>pain.mgHour</option>
                    <option value='pain.mgDay' translate>pain.mgDay</option>
                </select>


text:
'''
Plotting tools relevant for illustrating and comparing clustering results
can be found in this module.
'''
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

def scatter_plot_two_dim_group_data(
        two_dim_data,
        labels,
        markers=None,
        colors=None,
        figsize=(10, 6),
        xlim=None,
        ylim=None,
        alpha=0.8,
        bbox_to_anchor=(1.01, 1),
        loc=2,
        grid=True,
        show=True,
        filepath=None,
        **kwargs
        ):
    '''
    Plot the distribution of a two dimensional data against clustering groups
    in a scatter plot.

    A point represents an instance in the dataset. Points in a same cluster
    are painted with a same colour.

    This tool is useful to check the clustering impact in this two-dimensional
    sub-space.

    Parameters
    ----------

    two_dim_data: Pandas DataFrame
        A dataframe with two columns. The first column goes to the x-axis,
        and the second column goes to the y-axis.
    labels: list, Pandas Series, Numpy Array, or any iterable
        The segment label for each sample in ``two_dim_data``.
    markers: list
        Marker names for each group.
    bbox_to_anchor: tuple
        Instruction to placing the legend box relative to the axes. Details
        refer to ``Matplotlib`` document.
    colors: list, default None
        Colours for each group. Use equally distanced colours on colour map
        if not supplied.
    figsize: tuple
        Figure size (width, height).
    xlim: tuple
        X-axis limits.
    ylim: tuple
        Y-axis limits.
    alpha: float, between 0 and 1
        Marker transparency. From 0 to 1: from transparent to opaque.
    loc: int
        The corner of the legend box to anchor. Details refer to ``Matplotlib``
        document.
    grid: boolean, default True
        Show grid.
    show: boolean, default True
        Show figure in pop-up windows if true. Save to files if False.
    filepath: str
        File name to saving the plot. Must be assigned a valid filepath if
        ``show`` is False.
    **kwargs: keyword arguments
        Other keyword arguemnts passed on to ``matplotlib.pyplot.scatter``.

    Note
    ----

    Instances in a same cluster does not necessarily assemble together in
    all two dimensional sub-spaces. There can be possibly no clustering
    capaility for certain features. Additionally certain features play a
    secondary role in clustering as having less importance in
    ``field_importance`` in ``clusteror`` module.
    '''
    assert isinstance(two_dim_data, pd.core.frame.DataFrame)
    assert two_dim_data.shape[1] == 2, 'Two_dim_data must have two columns!'
    if isinstance(labels, pd.core.series.Series):
        labels = labels.values
    grouped = two_dim_data.groupby(labels)
    n_groups = grouped.ngroups
    # there should be enough markers
    if markers is not None:
        error_msg = 'There should be one marker for each group!'
        assert len(markers) == n_groups, error_msg
    # get color for each group from the spectrum
    if colors is None:
        colors = plt.cm.Spectral(np.linspace(0, 1, n_groups))
    plt.figure(figsize=figsize)
    ax = plt.subplot(111)
    if markers is None:
        # do a for loop to plot one by one
        # if markers not given, default circles
        for (name, group), color in zip(grouped, colors):
            ax.scatter(
                x=group.values[:, 0],
                y=group.values[:, 1],
                color=color,
                label=str(name),
                alpha=alpha,
                **kwargs)
    else:
        for (name, group), color, marker in zip(grouped, colors, markers):
            ax.scatter(
                x=group.values[:, 0],
                y=group.values[:, 1],
                color=color,
                marker=marker,
                label=str(name),
                alpha=alpha,
                ax=ax,
                **kwargs)
    # place the legend at the right hand side of the chart
    plt.legend(bbox_to_anchor=bbox_to_anchor, loc=loc)
    # get the axes names
    x_label, y_label = tuple(two_dim_data.columns)
    plt.xlabel(x_label, size=17)
    plt.ylabel(y_label, size=17)
    # get lim for x and y axes
    if xlim is None:
        xlim = (two_dim_data.iloc[:, 0].min(), two_dim_data.iloc[:, 0].max())
    if ylim is None:
        ylim = (two_dim_data.iloc[:, 1].min(), two_dim_data.iloc[:, 1].max())
    plt.xlim(xlim)
    plt.ylim(ylim)
    if grid:
        plt.grid()
    if show:
        plt.show()
    else:
        assert filepath
        plt.savefig(filepath)

def hist_plot_one_dim_group_data(
        one_dim_data,
        labels,
        bins=11,
        colors=None,
        figsize=(10, 6),
        xlabel='Dimension Reduced Data',
        ylabel='Occurance',
        bbox_to_anchor=(1.01, 1),
        loc=2,
        grid=True,
        show=True,
        filepath=None,
        **kwargs):
    '''
    Plot the distribution of a one dimensional numerical data in a histogram.
    This tool is useful to check the clustering impact in this one-dimensional
    sub-space.

    Parameters
    ----------

    one_dim_data: list, Pandas Series, Numpy Array, or any iterable
        A sequence of data. Each element if for an instance.
    labels: list, Pandas Series, Numpy Array, or any iterable
        The segment label for each sample in ``one_dim_data``.
    bins: int or iterable
        If an integer, bins - 1 bins created or a list of the delimiters.
    colors: list, default None
        Colours for each group. Use equally distanced colours on colour map
        if not supplied.
    figsize: tuple
        Figure size (width, height).
    xlabel: str
        Plot xlabel.
    ylabel: str
        Plot ylabel.
    bbox_to_anchor: tuple
        Instruction to placing the legend box relative to the axes. Details
        refer to ``Matplotlib`` document.
    loc: int
        The corner of the legend box to anchor. Details refer to ``Matplotlib``
        document.
    grid: boolean, default True
        Show grid.
    show: boolean, default True
        Show figure in pop-up windows if true. Save to files if False.
    filepath: str
        File name to saving the plot. Must be assigned a valid filepath if
        ``show`` is False.
    **kwargs: keyword arguments
        Other keyword arguemnts passed on to ``matplotlib.pyplot.scatter``.

    Note
    ----

    Instances in a same cluster does not necessarily assemble together in
    all one dimensional sub-spaces. There can be possibly no clustering
    capaility for certain features. Additionally certain features play a
    secondary role in clustering as having less importance in
    ``field_importance`` in ``clusteror`` module.
    '''
    if not isinstance(one_dim_data, pd.core.series.Series):
        one_dim_data = pd.Series(one_dim_data)
    if isinstance(labels, pd.core.series.Series):
        labels = labels.values
    grouped = one_dim_data.groupby(labels)
    n_groups = grouped.ngroups
    # get color for each group from the spectrum
    if colors is None:
        colors = plt.cm.Spectral(np.linspace(0, 1, n_groups))
    plt.figure(figsize=figsize)
    ax = plt.subplot(111)
    # do a for loop to plot one by one
    for (name, group), color in zip(grouped, colors):
        ax.hist(
            group.values,
            bins=bins,
            color=color,
            label=str(name),
            alpha=0.5,
            **kwargs
        )
    # place the legend at the right hand side of the chart
    plt.legend(bbox_to_anchor=bbox_to_anchor, loc=loc)
    plt.xlabel(xlabel, size=17)
    plt.ylabel(ylabel, size=17)
    if grid:
        plt.grid()
    if show:
        plt.show()
    else:
        assert filepath
        plt.savefig(filepath)

def group_occurance_plot(
        one_dim_data,
        cat_label,
        labels,
        group_label,
        colors=None,
        figsize=(10, 6),
        bbox_to_anchor=(1.01, 1),
        loc=2,
        grid=True,
        show=True,
        filepath=None,
        **kwargs):
    '''
    Plot the distribution of a one dimensional **ordinal or categorical** data
    in a bar chart. This tool is useful to check the clustering impact in this
    one-dimensional sub-space.

    Parameters
    ----------

    one_dim_data: list, Pandas Series, Numpy Array, or any iterable
        A sequence of data. Each element if for an instance.
    cat_label: str
        Field name will be used for the one dimensional data.
    labels: list, Pandas Series, Numpy Array, or any iterable
        The segment label for each sample in one_dim_data.
    group_label: str
        Field name will be used for the cluster ID.
    colors: list, default None
        Colours for each category existing in this one dimensional data.
        Default colour scheme used if not supplied.
    figsize: tuple
        Figure size (width, height).
    bbox_to_anchor: tuple
        Instruction to placing the legend box relative to the axes. Details
        refer to ``Matplotlib`` document.
    loc: int
        The corner of the legend box to anchor. Details refer to ``Matplotlib``
        document.
    grid: boolean, default True
        Show grid.
    show: boolean, default True
        Show figure in pop-up windows if true. Save to files if False.
    filepath: str
        File name to saving the plot. Must be assigned a valid filepath if
        ``show`` is False.
    **kwargs: keyword arguments
        Other keyword arguemnts passed on to ``matplotlib.pyplot.scatter``.

    Note
    ----

    Instances in a same cluster does not necessarily assemble together in
    all one dimensional sub-spaces. There can be possibly no clustering
    capaility for certain features. Additionally certain features play a
    secondary role in clustering as having less importance in
    ``field_importance`` in ``clusteror`` module.
    '''
    if not isinstance(one_dim_data, pd.core.series.Series):
        one_dim_data = pd.Series(one_dim_data)
    df = pd.DataFrame({cat_label: one_dim_data, group_label: labels})
    df_to_plot = df.pivot_table(
        index=group_label,
        columns=cat_label,
        aggfunc=len
    )
    plt.figure(figsize=figsize)
    ax = plt.subplot(111)
    df_to_plot.plot.bar(color=colors, ax=ax, **kwargs)
    plt.legend(bbox_to_anchor=bbox_to_anchor, loc=loc)
    if grid:
        plt.grid()
    if show:
        plt.show()
    else:
        assert filepath
        plt.savefig(filepath)


text:
namespace hecl {
class CVar;
} // namespace hecl

namespace DataSpec::DNAMP1 {

#define DEFINE_CVAR_GLOBAL(name)                                                                                \
  extern hecl::CVar* tw_##name;

DEFINE_CVAR_GLOBAL(WorldPrefix);
DEFINE_CVAR_GLOBAL(FieldOfView);
DEFINE_CVAR_GLOBAL(SplashScreensDisabled);
DEFINE_CVAR_GLOBAL(PressStartDelay);
DEFINE_CVAR_GLOBAL(WavecapIntensityNormal);
DEFINE_CVAR_GLOBAL(WavecapIntensityPoison);
DEFINE_CVAR_GLOBAL(WavecapIntensityLava);
DEFINE_CVAR_GLOBAL(RippleIntensityNormal);
DEFINE_CVAR_GLOBAL(RippleIntensityPoison);
DEFINE_CVAR_GLOBAL(RippleIntensityLava);
DEFINE_CVAR_GLOBAL(FluidEnvBumpScale);
DEFINE_CVAR_GLOBAL(WaterFogDistanceBase);
DEFINE_CVAR_GLOBAL(WaterFogDistanceRange);
DEFINE_CVAR_GLOBAL(GravityWaterFogDistanceBase);
DEFINE_CVAR_GLOBAL(GravityWaterFogDistanceRange);
DEFINE_CVAR_GLOBAL(HardModeDamageMult);
DEFINE_CVAR_GLOBAL(HardModeWeaponMult);

#undef DEFINE_CVAR_GLOBAL

struct CTweakGame final : ITweakGame {
  AT_DECL_DNA_YAML
  String<-1> x4_worldPrefix;
  String<-1> x14_defaultRoom;
  Value<float> x24_fov;
  Value<bool> x28_unknown1;
  Value<bool> x29_unknown2;
  Value<bool> x2a_unknown3;
  Value<bool> x2b_splashScreensDisabled;
  Value<float> x2c_unknown5;
  Value<float> x30_pressStartDelay;
  Value<float> x34_wavecapIntensityNormal;
  Value<float> x38_wavecapIntensityPoison;
  Value<float> x3c_wavecapIntensityLava;
  Value<float> x40_rippleIntensityNormal;
  Value<float> x44_rippleIntensityPoison;
  Value<float> x48_rippleIntensityLava;
  Value<float> x4c_fluidEnvBumpScale;
  Value<float> x50_waterFogDistanceBase;
  Value<float> x54_waterFogDistanceRange;
  Value<float> x58_gravityWaterFogDistanceBase;
  Value<float> x5c_gravityWaterFogDistanceRange;
  Value<float> x60_hardmodeDamageMult;
  Value<float> x64_hardmodeWeaponMult;

  std::string_view GetWorldPrefix() const override { return x4_worldPrefix; }
  std::string_view GetDefaultRoom() const { return x14_defaultRoom; }
  bool GetSplashScreensDisabled() const override { return x2b_splashScreensDisabled; }
  float GetFirstPersonFOV() const override { return x24_fov; }
  float GetPressStartDelay() const override { return x30_pressStartDelay; }
  float GetWavecapIntensityNormal() const override { return x34_wavecapIntensityNormal; }
  float GetWavecapIntensityPoison() const override { return x38_wavecapIntensityPoison; }
  float GetWavecapIntensityLava() const override { return x3c_wavecapIntensityLava; }
  float GetRippleIntensityNormal() const override { return x40_rippleIntensityNormal; }
  float GetRippleIntensityPoison() const override { return x44_rippleIntensityPoison; }
  float GetRippleIntensityLava() const override { return x48_rippleIntensityLava; }
  float GetFluidEnvBumpScale() const override { return x4c_fluidEnvBumpScale; }
  float GetWaterFogDistanceBase() const override { return x50_waterFogDistanceBase; }
  float GetWaterFogDistanceRange() const override { return x54_waterFogDistanceRange; }
  float GetGravityWaterFogDistanceBase() const override { return x58_gravityWaterFogDistanceBase; }
  float GetGravityWaterFogDistanceRange() const override { return x5c_gravityWaterFogDistanceRange; }
  float GetHardModeDamageMultiplier() const override { return x60_hardmodeDamageMult; }
  float GetHardModeWeaponMultiplier() const override { return x64_hardmodeWeaponMult; }
  CTweakGame() = default;
  CTweakGame(athena::io::IStreamReader& in) {
    this->read(in);
#ifdef NDEBUG
    x2b_splashScreensDisabled = false;
#endif
  }

  void initCVars(hecl::CVarManager* mgr) override;

private:
  void _tweakListener(hecl::CVar* cv);
};
} // namespace DataSpec::DNAMP1


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
The MIT License (MIT)

Copyright (c) 2015 FetLife-OSS Contributors
https://bitbucket.org/malachid/fetlife-oss/src/default/Contributors.md?at=default

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

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

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable name="data" type="net.goldenspiral.fetlifeoss.rest.model.GroupRef"/>
    </data>
    <!-- @TODO bind this textview onclick to in-app version of data.url. -->
    <TextView
        style="@style/ListItems"
        android:text="@{data.name}"
        android:drawableLeft="@drawable/new_posts"
        app:count="@{data.newPosts}"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</layout>


text:
package replay

import (
	"testing"

	"github.com/google/gapid/core/log"
	"github.com/google/gapid/gapis/api/gles"
	"github.com/google/gapid/gapis/memory"
	"github.com/google/gapid/test/integration/gles/snippets"
)

func TestClearFramebuffer(t *testing.T) {
	ctx, d := setup(log.Testing(t))

	b := snippets.NewBuilder(ctx, d)
	b.CreateContext(64, 64, false, false)

	tex := gles.TextureId(10)
	fbo := gles.FramebufferId(20)

	texR := b.Data(ctx, tex)
	fboR := b.Data(ctx, fbo)

	b.Add(
		b.CB.GlGenTextures(1, texR.Ptr()).AddRead(texR.Data()),
		b.CB.GlBindTexture(gles.GLenum_GL_TEXTURE_2D, tex),
		b.CB.GlTexParameteri(gles.GLenum_GL_TEXTURE_2D, gles.GLenum_GL_TEXTURE_WRAP_S, gles.GLint(gles.GLenum_GL_CLAMP_TO_EDGE)),
		b.CB.GlTexParameteri(gles.GLenum_GL_TEXTURE_2D, gles.GLenum_GL_TEXTURE_WRAP_T, gles.GLint(gles.GLenum_GL_CLAMP_TO_EDGE)),
		b.CB.GlTexParameteri(gles.GLenum_GL_TEXTURE_2D, gles.GLenum_GL_TEXTURE_MAG_FILTER, gles.GLint(gles.GLenum_GL_LINEAR)),
		b.CB.GlTexParameteri(gles.GLenum_GL_TEXTURE_2D, gles.GLenum_GL_TEXTURE_MIN_FILTER, gles.GLint(gles.GLenum_GL_LINEAR)),
		b.CB.GlTexImage2D(
			gles.GLenum_GL_TEXTURE_2D,
			0,
			gles.GLint(gles.GLenum_GL_RGBA),
			64, 64, 0,
			gles.GLenum_GL_RGBA,
			gles.GLenum_GL_UNSIGNED_BYTE,
			memory.Nullptr),

		b.CB.GlGenFramebuffers(1, fboR.Ptr()).AddRead(fboR.Data()),
		b.CB.GlBindFramebuffer(gles.GLenum_GL_FRAMEBUFFER, fbo),
		b.CB.GlFramebufferTexture2D(
			gles.GLenum_GL_FRAMEBUFFER,
			gles.GLenum_GL_COLOR_ATTACHMENT0,
			gles.GLenum_GL_TEXTURE_2D,
			tex,
			0),

		b.CB.GlBindFramebuffer(gles.GLenum_GL_FRAMEBUFFER, fbo),
	)
	clear := b.ClearColor(1, 0, 0, 1)

	c := b.Capture(ctx, "clear-framebuffer")

	checkReplay(ctx, c, d, 1, func() { // expect a single replay batch.
		checkColorBuffer(ctx, c, d, 64, 64, 0, "solid-red", clear, nil)
	})

	checkReplay(ctx, c, d, 1, func() { // expect a single replay batch.
		checkTextureBuffer(ctx, c, d, 64, 64, 0, "solid-red", clear, tex, nil)
	})
}


text: /* Put local CSS rules in this file; it won't be modified by the project */


text:
<?php
	if ($_SESSION['customer_id'] == 0 ){
		unset($_SESSION['customer_id']);
		session_destroy();
		echo "";
	}
    ?>

You Can Update Your Information

				<?php
					$sql_cusinfo = "SELECT * FROM customer WHERE id = '".$_SESSION['customer_id']."'";
					$result_cusinfo = $mysql->query($sql_cusinfo);
					$cusinfo = $mysql->fetch($result_cusinfo);
					if (isset ($_POST['fname'])){
						$fname = $_POST['fname'];
						$lname = $_POST['lname'];
						$phone = $_POST['phone'];
                        $sex = $_POST['sex'];
                        $address = $_POST['address'];
						if($lname==""||  $fname=="" || $phone=="" || $address=="") {
				    echo"";
					} else {
				    $sql_updatecus = "UPDATE customer SET FirstName = '$fname', LastName = '$lname', tel = '$phone', address = '$address', sex = '$sex' WHERE id = '".$_SESSION['customer_id']."'";
					$result_updatecus = $mysql->query($sql_updatecus);
					echo"";
				}
			}
				?>
				<form method='post'>

				    	First Name:
						<input type="text" maxlength="20" class="form-control" name="fname" id="fname" value="<?php echo $cusinfo['FirstName']; ?>">

				    	Last Name:
						<input type="text" maxlength="20" class="form-control" name="lname" id="lname" value="<?php echo $cusinfo['LastName']; ?>">

				    	Username:
						<input type="text" class="form-control" name="username" id='username' value="<?php echo $cusinfo['username']; ?>" disabled>

				    	Phone Number:
						<input type="text" maxlength="13" class="form-control" name="phone" id='phone' value="<?php echo $cusinfo['tel']; ?>">

				    	Address:
						<input type="text" maxlength="40" class="form-control" name="address" id='address' value="<?php echo $cusinfo['address']; ?>">

				    	Gender:

				            Unknown<input type='radio' name='sex' value=0 checked/>
				            Male<input type='radio' name='sex' value=1/>
				            Female<input type='radio' name='sex' value=2/>

				    	<input type="submit" value="Submit" class="btn btn-danger">

				</form>

Update Password

				<?php
				if (isset ($_POST['password'])){
					$oldpwd = inputCheck($_POST['password']);
					$res_pwd = $mysql->fetch($mysql->query("SELECT pwdhash,salt FROM customer WHERE id = '{$_SESSION['customer_id']}'"));
					$oldpwdhash = MD5($oldpwd.$res_pwd['salt']);
					if($oldpwdhash == $res_pwd['pwdhash']){
						if($_POST['newpassword']==$_POST['newpasswordagain']){
							$newpwdhash = MD5($_POST['newpassword'].$res_pwd['salt']);
							if($newpwdhash==$oldpwdhash){
								echo "";
							}else{
								$sql_newPwd = "UPDATE customer SET pwdhash = '$newpwdhash' WHERE id = '{$_SESSION['customer_id']}'";
								$mysql->query($sql_newPwd);
								unset($_SESSION['customer_name']);
								unset($_SESSION['customer_id']);
								redirect('login.php','Change Password Successfully!\\nPlease Log in again!');
							}
						}else{
							echo "";
						}
					}else{
						echo "";
					}
				}
				?>
				<form method="post">

			   		 	Password:
						<input type="text" class="form-control" name="password" id='password' placeholder="Your Old Password" required>

			   		 	New Password:
						<input type="text" class="form-control" name="newpassword" id='newpassword' placeholder="New Password" required>

			   		 	New Password Again:
						<input type="text" class="form-control" name="newpasswordagain" id='newpasswordagain' placeholder="New Password Again" required>

				    	<input type="submit" value="Submit" class="btn btn-danger">

				</form>

Update Car Information

				<?php
				$sql_cuscarid = "SELECT * FROM car WHERE cus_id ='".$_SESSION['customer_id']."'";
				$result_cuscarid = $mysql->query($sql_cuscarid);
				$rows = mysqli_num_rows($result_cuscarid);
				$num = 0;
				while ($row_carinfo = $mysql->fetch($result_cuscarid)) {
					$num ++;
				?>
					<form method="post">

Car Information<?php echo $num;?>

				   			 	Plate Number:
								<input type="text" class="form-control" name="plate<?php echo $num;?>" id='plate' value="<?php echo $row_carinfo['plate']; ?>">
								<input type="hidden" name="id<?php echo $num;?>" value="<?php echo $row_carinfo['id']; ?>">

				   			 	Color:
								<input type="text" class="form-control" name="color<?php echo $num;?>" id='color' value="<?php echo $row_carinfo['color']; ?>">
								<input type="hidden" name="id<?php echo $num;?>" value="<?php echo $row_carinfo['id']; ?>">

				   			 	Type:
								<input type="text" class="form-control" name="type<?php echo $num;?>" id='type' value="<?php echo $row_carinfo['brand']; ?>">
								<input type="hidden" name="id<?php echo $num;?>" value="<?php echo $row_carinfo['id']; ?>">

					<?php
				}
				if (isset ($_POST['plate1'])){
						$plate1 = $_POST['plate1'];
						$plate2 = $_POST['plate2'];
						$plate3 = $_POST['plate3'];
						$color1 = $_POST['color1'];
						$color2 = $_POST['color2'];
						$color3 = $_POST['color3'];
						$type1 = $_POST['type1'];
						$type2 = $_POST['type2'];
						$type3 = $_POST['type3'];
						$id1 = $_POST['id1'];
						$id2 = $_POST['id2'];
						$id3 = $_POST['id3'];
						$sql_updatecar1 = "UPDATE car SET plate = '$plate1', brand = '$type1', color = '$color1' WHERE id = '$id1'";
						$result_updatecar1 = $mysql->query($sql_updatecar1);
						$sql_updatecar2 = "UPDATE car SET plate = '$plate2', brand = '$type2', color = '$color2' WHERE id = '$id2'";
						$result_updatecar2 = $mysql->query($sql_updatecar2);
						$sql_updatecar3 = "UPDATE car SET plate = '$plate3', brand = '$type3', color = '$color3' WHERE id = '$id3'";
						$result_updatecar3 = $mysql->query($sql_updatecar3);

						echo"";
				}
					?>

				    		<input type="submit" value="Submit" class="btn btn-danger">

				  </form>


text:
<?php

chdir(dirname(__FILE__).'/../');

include_once("./config.php");
include_once("./lib/loader.php");
include_once("./lib/threads.php");

set_time_limit(0);

// connecting to database
$db = new mysql(DB_HOST, '', DB_USER, DB_PASSWORD, DB_NAME);

include_once("./load_settings.php");
include_once(DIR_MODULES."control_modules/control_modules.class.php");

$ctl = new control_modules();

if (defined('ONEWIRE_SERVER'))
{
   include_once(DIR_MODULES.'onewire/onewire.class.php');
   $onw=new onewire();
}
else
{
   exit;
}

echo date("H:i:s") . " running " . basename(__FILE__) . "\n";

while(1)
{
   setGlobal((str_replace('.php', '', basename(__FILE__))).'Run', time(), 1);

   // check all 1wire devices
   $onw->updateDevices();
   $onw->updateDisplays();

   if (file_exists('./reboot') || $_GET['onetime'])
   {
      $db->Disconnect();
      exit;
   }

   sleep(1);
}

DebMes("Unexpected close of cycle: " . basename(__FILE__));

?>


text:
"use strict"

module.exports = function(sequelize, DataTypes) {
  var region = sequelize.define('region', {
    RegionID: {
      type: DataTypes.INTEGER,
      field: 'RegionID',
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    RegionDescription: {
      type: DataTypes.TEXT,
      allowNull: false
    }
  }, {

    classMethods: {
      associate: function (models) {
        region.belongsTo(models.territories, {foreignKey: 'RegionID'})
      }
    }
  });
  return region;
};