text:
/**
 * Obscura Photos component.
 * Contains:
 * 		- photo-feed directive
 * 		- PhotoService, API service
 */
angular.module('ob.photos', [
	'ngResource',
	'ob.transclude'
])

/**
 * Photo feed directive.
 * Used to fetch photos via Obscura API, providing a few options along the way.
 *
 * @param {string} set Set name to fetch photos from. Can only be one. Setting this also changes photo URLs to include set names.
 * @param {string} authors Comma-delimited list of authors
 * @param {integer} perpage Number of photos per page
 *
 * @return {*}
 */
.directive('photoFeed', function() {
	return {
		scope: {
			set: "@",
			authors: "@",
			perpage: "@",
			onLoaded: "&onload"
		},
		transclude: true,
		template: '<ul ob-transclude></ul>',
		controller: ['$scope', '$element', '$timeout', '$q', 'PhotoService', function($scope, $element, $timeout, $q, PhotoService)
		{
			/* Fetch photos */
			this.items = PhotoService.get({
				set: $scope.set,
				authors: $scope.authors,
				perpage: $scope.perpage
			});

			this.onload = $scope.onLoaded;
		}],
		controllerAs: 'feed'
	};
})

/**
 * Photos REST service
 *
 * @return {*}
 */
.factory('PhotoService', ['$resource', function($resource)
{
	return $resource('/api/photos/:photoId/:action',
	{
		action:  '@action',
		photoId: '@photoId'
	},
	{
		all:
		{
			method: 'GET',
			isArray: true,
			action:  '',
			cache: true
		},
		get:
		{
			cache: true,
			action:  '',
			isArray: true
		},
		find:
		{
			cache: true,
			action: '',
			isArray: false
		},
		update:
		{
			method: 'POST',
			action: 'edit',
			isArray: false
		},
		save:
		{
			method: 'POST'
		}
	});
}])

;

redpajama_set_name: RedPajamaGithub


text:
<TITLE>Review for Eye of the Beholder (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Eye of the Beholder (1999)

reviewed by
Harvey S. Karten

EYE OF THE BEHOLDER

 Reviewed by Harvey Karten
 Destination Films
 Director: Stephan Elliott
 Writer: Marc Behm (Novel), Stephan Elliott
 Cast: Ewan McGregor, Ashley Judd, Patrick Bergin, k.d.
lang, Jason Priestley, Genevieve Bujold

   Here's why we need lots and lots of critics.  One guy says
this about "Eye of the Beholder"..."As it slithers under the
skin and behind the brain, 'Eye of the Beholder' works a
brand of guileful magic rarely seen in movies
today--courageously blurring the line between its characters'
inner conflicts and outer lives to create a disturbingly hypnotic
odyssey not unlike Alfred Hitchcock's 'Vertigo' or Brian
De Palma's 'Obsession.'"  Another fellow says this: "I was
absolutely dumbfounded.  I thought this movie was totally
incomprehensible, and the ending seemed arbitrary and
pointless.  It's shocking how poorly pieced together it is."
Other reviews have come through in various shades between
these two extremes.

   The diversity of opinion could be explained as a conflict
between those who want a story to be clear almost from the
start and those who prefer movies to be more challenging.
Granted: "Eye of the Beholder," based on Marc Behm's 1980
noir novel, is the sort of tale that starts off in a manner so
baffling that you'd be tempted to wonder whether two or three
movies were spliced together.  In fact, if you go into this film
realizing that its director, Stephan Elliot, is known principally
for two far-out comedies, "Welcome to Woop Woop" and
"Priscilla: Queen of the Desert," you can't be blamed for
concluding that the man is putting one over on us.

   Ah but wait.  As we get into the story, the truth begins to
unfold.  "Eye of the Beholder" is a psychological thriller not
unlike Brian De Palma's most intriguing creation,
"Obsession," which is itself a rehash of Alfred Hitchcock's
"Vertigo" (with elements of "Rear Window").  This time the
Cliff Robertson role is taken by the strikingly handsome Ewan
McGregor, who exhibits the same personal traits as did
Robertson's character, with a fine side role by Genevieve
Bujold--who was the object of the man's obsession in the De
Palma movie but now takes on the role of an ultra-liberal,
bleeding-heart parole officer.

   McGregor performs in the role of The Eye, a surveillance
man with the British Secret Service who has been assigned
to spy on the son of his employer and who communicates
regularly by modem with a sharply cynical woman named
Hilary (k.d. lang).  A loner, depressed since his wife walked
out on him eight years earlier taking their daughter with her,
The Eye has lost it.  He's still good at his job, still maintaining
the preoccupation with work that led to the breakup of his
family.  That he frequently hallucinates his daughter's
presence--skipping rope, making noise, asking questions,
getting in the way of his spying--does not greatly interfere
with his tasks.  But when he inadvertently witnesses the cold-
blooded murder of a man in the midst of a tryst with the
beautiful Joanna (Ashley Judd), he becomes strangely
captivated by the killer and determined to protect her at all
costs.  Stalking Joanna in New York, Boston, Chicago, San
Francisco and even Alaska, he seems to recognize that
despite her affinity for serial killing, the two are somehow
made for each other.  And in a way--considering how both of
these tormented individuals went nuts for similar reasons--
they are.  Writer/director Elliot appears to invite us to
consider why we each choose the person we do, suggesting
that some extrasensory insight makes us see into our
partner's deepest recesses.  It's no wonder that much of the
conversation between Joanna and her unlucky male friends
turns upon astrology and numerology.

   Rarely has anyone in the cinema so successfully stalked
another through so many cities--The Eye's accomplishment
particularly odd considering the bright red jacket he wears
and the smashing good looks that he displays.  McGregor
turns in a performance that is exceptional for the very reason
that he is able to hide his outer feelings from the audience so
well.  He is a tabula rasa, a poker-faced isolate who lives
almost entirely within his own mind, dedicating himself to the
protection of this criminally insane woman even at the cost of
his own job.  Ashley Judd looks equally smashing through
most of her disguises, not so hot when she wears a page-boy
wig but devastating in a succession of long-hair rugs, both
blond and brunette, which she acquires with the money she
lifts from her victims. Judd and McGregor are rarely together
on screen, giving their one extended dialogue a climactic
impact.

  If Cliff Robertson and Genevieve's Bujold's connection in
"Obsession" never left your mind--and you prayed for a
chance to see a rekindling of the subject with equally
matched performers--"Eye of the Beholder" is the movie
you're looking for. This one might turn off the MTV generation
eager for a succession of slam-bang episodes, but will fulfill
the hopes of those who believe that vigorous inner action is
of more dramatic note than plot-driven, exterior movement.

Rated R.  Running Time: 102 minutes.  (C) 2000
Harvey Karten, film_critic@compuserve.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
package org.apache.flink.table.plan.rules

import org.apache.calcite.rel.core.RelFactories
import org.apache.calcite.rel.rules._
import org.apache.calcite.tools.{RuleSet, RuleSets}
import org.apache.flink.table.plan.nodes.logical
import org.apache.flink.table.plan.rules.common._
import org.apache.flink.table.plan.rules.logical._
import org.apache.flink.table.plan.rules.dataSet._
import org.apache.flink.table.plan.rules.datastream._
import org.apache.flink.table.plan.nodes.logical._

object FlinkRuleSets {

  /**
    * Convert sub-queries before query decorrelation.
    */
  val TABLE_SUBQUERY_RULES: RuleSet = RuleSets.ofList(
    SubQueryRemoveRule.FILTER,
    SubQueryRemoveRule.PROJECT,
    SubQueryRemoveRule.JOIN)

  /**
    * Expand plan by replacing references to tables into a proper plan sub trees. Those rules
    * can create new plan nodes.
    */
  val EXPAND_PLAN_RULES: RuleSet = RuleSets.ofList(
    LogicalCorrelateToTemporalTableJoinRule.INSTANCE,
    TableScanRule.INSTANCE)

  val POST_EXPAND_CLEAN_UP_RULES: RuleSet = RuleSets.ofList(
    EnumerableToLogicalTableScan.INSTANCE)

  val LOGICAL_OPT_RULES: RuleSet = RuleSets.ofList(

    // push a filter into a join
    FilterJoinRule.FILTER_ON_JOIN,
    // push filter into the children of a join
    FilterJoinRule.JOIN,
    // push filter through an aggregation
    FilterAggregateTransposeRule.INSTANCE,
    // push filter through set operation
    FilterSetOpTransposeRule.INSTANCE,
    // push project through set operation
    ProjectSetOpTransposeRule.INSTANCE,

    // aggregation and projection rules
    AggregateProjectMergeRule.INSTANCE,
    AggregateProjectPullUpConstantsRule.INSTANCE,
    // push a projection past a filter or vice versa
    ProjectFilterTransposeRule.INSTANCE,
    FilterProjectTransposeRule.INSTANCE,
    // push a projection to the children of a join
    // push all expressions to handle the time indicator correctly
    new ProjectJoinTransposeRule(PushProjector.ExprCondition.FALSE, RelFactories.LOGICAL_BUILDER),
    // merge projections
    ProjectMergeRule.INSTANCE,
    // remove identity project
    ProjectRemoveRule.INSTANCE,
    // reorder sort and projection
    SortProjectTransposeRule.INSTANCE,
    ProjectSortTransposeRule.INSTANCE,

    // join rules
    JoinPushExpressionsRule.INSTANCE,

    // remove union with only a single child
    UnionEliminatorRule.INSTANCE,
    // convert non-all union into all-union + distinct
    UnionToDistinctRule.INSTANCE,

    // remove aggregation if it does not aggregate and input is already distinct
    AggregateRemoveRule.INSTANCE,
    // push aggregate through join
    AggregateJoinTransposeRule.EXTENDED,
    // aggregate union rule
    AggregateUnionAggregateRule.INSTANCE,

    // reduce aggregate functions like AVG, STDDEV_POP etc.
    AggregateReduceFunctionsRule.INSTANCE,
    WindowAggregateReduceFunctionsRule.INSTANCE,

    // remove unnecessary sort rule
    SortRemoveRule.INSTANCE,

    // prune empty results rules
    PruneEmptyRules.AGGREGATE_INSTANCE,
    PruneEmptyRules.FILTER_INSTANCE,
    PruneEmptyRules.JOIN_LEFT_INSTANCE,
    PruneEmptyRules.JOIN_RIGHT_INSTANCE,
    PruneEmptyRules.PROJECT_INSTANCE,
    PruneEmptyRules.SORT_INSTANCE,
    PruneEmptyRules.UNION_INSTANCE,

    // calc rules
    FilterCalcMergeRule.INSTANCE,
    ProjectCalcMergeRule.INSTANCE,
    FilterToCalcRule.INSTANCE,
    ProjectToCalcRule.INSTANCE,
    CalcMergeRule.INSTANCE,

    // scan optimization
    PushProjectIntoTableSourceScanRule.INSTANCE,
    PushFilterIntoTableSourceScanRule.INSTANCE,

    // unnest rule
    LogicalUnnestRule.INSTANCE,

    // translate to flink logical rel nodes
    FlinkLogicalAggregate.CONVERTER,
    FlinkLogicalWindowAggregate.CONVERTER,
    FlinkLogicalOverWindow.CONVERTER,
    FlinkLogicalCalc.CONVERTER,
    FlinkLogicalCorrelate.CONVERTER,
    FlinkLogicalIntersect.CONVERTER,
    FlinkLogicalJoin.CONVERTER,
    FlinkLogicalTemporalTableJoin.CONVERTER,
    FlinkLogicalMinus.CONVERTER,
    FlinkLogicalSort.CONVERTER,
    FlinkLogicalUnion.CONVERTER,
    FlinkLogicalValues.CONVERTER,
    FlinkLogicalTableSourceScan.CONVERTER,
    FlinkLogicalTableFunctionScan.CONVERTER,
    FlinkLogicalNativeTableScan.CONVERTER,
    FlinkLogicalMatch.CONVERTER
  )

  /**
    * RuleSet to normalize plans for batch / DataSet execution
    */
  val DATASET_NORM_RULES: RuleSet = RuleSets.ofList(
    // simplify expressions rules
    ReduceExpressionsRule.FILTER_INSTANCE,
    ReduceExpressionsRule.PROJECT_INSTANCE,
    ReduceExpressionsRule.CALC_INSTANCE,
    ReduceExpressionsRule.JOIN_INSTANCE,
    ProjectToWindowRule.PROJECT,

    // Transform grouping sets
    DecomposeGroupingSetRule.INSTANCE,
    // Transform window to LogicalWindowAggregate
    DataSetLogicalWindowAggregateRule.INSTANCE,
    WindowPropertiesRule.INSTANCE,
    WindowPropertiesHavingRule.INSTANCE,

    // expand distinct aggregate to normal aggregate with groupby
    AggregateExpandDistinctAggregatesRule.JOIN,

    // merge a cascade of predicates to IN or NOT_IN
    ConvertToNotInOrInRule.IN_INSTANCE,
    ConvertToNotInOrInRule.NOT_IN_INSTANCE
  )

  /**
    * RuleSet to optimize plans for batch / DataSet execution
    */
  val DATASET_OPT_RULES: RuleSet = RuleSets.ofList(
    // translate to Flink DataSet nodes
    DataSetWindowAggregateRule.INSTANCE,
    DataSetAggregateRule.INSTANCE,
    DataSetDistinctRule.INSTANCE,
    DataSetCalcRule.INSTANCE,
    DataSetJoinRule.INSTANCE,
    DataSetSingleRowJoinRule.INSTANCE,
    DataSetScanRule.INSTANCE,
    DataSetUnionRule.INSTANCE,
    DataSetIntersectRule.INSTANCE,
    DataSetMinusRule.INSTANCE,
    DataSetSortRule.INSTANCE,
    DataSetValuesRule.INSTANCE,
    DataSetCorrelateRule.INSTANCE,
    BatchTableSourceScanRule.INSTANCE
  )

  /**
    * RuleSet to normalize plans for stream / DataStream execution
    */
  val DATASTREAM_NORM_RULES: RuleSet = RuleSets.ofList(
    // Transform window to LogicalWindowAggregate
    DataStreamLogicalWindowAggregateRule.INSTANCE,
    WindowPropertiesRule.INSTANCE,
    WindowPropertiesHavingRule.INSTANCE,

    // simplify expressions rules
    ReduceExpressionsRule.FILTER_INSTANCE,
    ReduceExpressionsRule.PROJECT_INSTANCE,
    ReduceExpressionsRule.CALC_INSTANCE,
    ProjectToWindowRule.PROJECT,

    // merge a cascade of predicates to IN or NOT_IN
    ConvertToNotInOrInRule.IN_INSTANCE,
    ConvertToNotInOrInRule.NOT_IN_INSTANCE
  )

  /**
    * RuleSet to optimize plans for stream / DataStream execution
    */
  val DATASTREAM_OPT_RULES: RuleSet = RuleSets.ofList(
    // translate to DataStream nodes
    DataStreamSortRule.INSTANCE,
    DataStreamGroupAggregateRule.INSTANCE,
    DataStreamOverAggregateRule.INSTANCE,
    DataStreamGroupWindowAggregateRule.INSTANCE,
    DataStreamCalcRule.INSTANCE,
    DataStreamScanRule.INSTANCE,
    DataStreamUnionRule.INSTANCE,
    DataStreamValuesRule.INSTANCE,
    DataStreamCorrelateRule.INSTANCE,
    DataStreamWindowJoinRule.INSTANCE,
    DataStreamJoinRule.INSTANCE,
    DataStreamTemporalTableJoinRule.INSTANCE,
    StreamTableSourceScanRule.INSTANCE,
    DataStreamMatchRule.INSTANCE
  )

  /**
    * RuleSet to decorate plans for stream / DataStream execution
    */
  val DATASTREAM_DECO_RULES: RuleSet = RuleSets.ofList(
    // retraction rules
    DataStreamRetractionRules.DEFAULT_RETRACTION_INSTANCE,
    DataStreamRetractionRules.UPDATES_AS_RETRACTION_INSTANCE,
    DataStreamRetractionRules.ACCMODE_INSTANCE
  )

}


text:
using System;

namespace _3.CirclePerimeterAndArea
{
    class CirclePerimeterAndArea
    {
        static void Main()
        {
            Console.Write("Enter the radius r = ");
            double radius = double.Parse(Console.ReadLine());

            Console.WriteLine("The perimeter of the Circle is: {0: 0.00}", 2 * (Math.PI) * radius);
            Console.WriteLine("The area of the Circle is: {0: 0.00}", (Math.PI) * radius * radius);
        }
    }
}


text:
package jp.fieldnotes.hatunatu.dao.impl;

import jp.fieldnotes.hatunatu.dao.annotation.tiger.Bean;
import jp.fieldnotes.hatunatu.dao.unit.HatunatuTest;
import org.junit.Rule;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class CharBindTest {

    @Rule
    public HatunatuTest test = new HatunatuTest(this,"CharBindTest.xml" );

    private CharTableDao charTableDao;

    @Test
    public void testCharBindTx() throws Exception {
        // ## Arrange ##
        {
            CharTable bean = new CharTable();
            bean.setId(31);
            bean.setAaa('Z');
            charTableDao.insert(bean);
        }

        // ## Act ##
        final CharTable bean = charTableDao.findById(31);

        // ## Assert ##
        assertEquals('Z', bean.getAaa());
    }

    public static interface CharTableDao {

        public CharTable findById(int id);

        public void insert(CharTable charTable);

        public void update(CharTable charTable);

    }

    @Bean(table="CHAR_TABLE")
    public static class CharTable {

        private int id;

        private char aaa;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public char getAaa() {
            return aaa;
        }

        public void setAaa(char aaa) {
            this.aaa = aaa;
        }

    }

}


text:
#include <limits.h>
#include <math.h>

#include "vp9/encoder/vp9_aq_cyclicrefresh.h"

#include "vp9/common/vp9_seg_common.h"

#include "vp9/encoder/vp9_ratectrl.h"
#include "vp9/encoder/vp9_segmentation.h"

struct CYCLIC_REFRESH {
  // Percentage of blocks per frame that are targeted as candidates
  // for cyclic refresh.
  int percent_refresh;
  // Maximum q-delta as percentage of base q.
  int max_qdelta_perc;
  // Superblock starting index for cycling through the frame.
  int sb_index;
  // Controls how long block will need to wait to be refreshed again, in
  // excess of the cycle time, i.e., in the case of all zero motion, block
  // will be refreshed every (100/percent_refresh + time_for_refresh) frames.
  int time_for_refresh;
  // Target number of (8x8) blocks that are set for delta-q.
  int target_num_seg_blocks;
  // Actual number of (8x8) blocks that were applied delta-q.
  int actual_num_seg1_blocks;
  int actual_num_seg2_blocks;
  // RD mult. parameters for segment 1.
  int rdmult;
  // Cyclic refresh map.
  signed char *map;
  // Thresholds applied to the projected rate/distortion of the coding block,
  // when deciding whether block should be refreshed.
  int64_t thresh_rate_sb;
  int64_t thresh_dist_sb;
  // Threshold applied to the motion vector (in units of 1/8 pel) of the
  // coding block, when deciding whether block should be refreshed.
  int16_t motion_thresh;
  // Rate target ratio to set q delta.
  double rate_ratio_qdelta;
  double low_content_avg;
  int qindex_delta_seg1;
  int qindex_delta_seg2;
};

CYCLIC_REFRESH *vp9_cyclic_refresh_alloc(int mi_rows, int mi_cols) {
  CYCLIC_REFRESH *const cr = vpx_calloc(1, sizeof(*cr));
  if (cr == NULL)
    return NULL;

  cr->map = vpx_calloc(mi_rows * mi_cols, sizeof(*cr->map));
  if (cr->map == NULL) {
    vpx_free(cr);
    return NULL;
  }

  return cr;
}

void vp9_cyclic_refresh_free(CYCLIC_REFRESH *cr) {
  vpx_free(cr->map);
  vpx_free(cr);
}

// Check if we should turn off cyclic refresh based on bitrate condition.
static int apply_cyclic_refresh_bitrate(const VP9_COMMON *cm,
                                        const RATE_CONTROL *rc) {
  // Turn off cyclic refresh if bits available per frame is not sufficiently
  // larger than bit cost of segmentation. Segment map bit cost should scale
  // with number of seg blocks, so compare available bits to number of blocks.
  // Average bits available per frame = avg_frame_bandwidth
  // Number of (8x8) blocks in frame = mi_rows * mi_cols;
  const float factor = 0.25;
  const int number_blocks = cm->mi_rows  * cm->mi_cols;
  // The condition below corresponds to turning off at target bitrates:
  // (at 30fps), ~12kbps for CIF, 36kbps for VGA, 100kps for HD/720p.
  // Also turn off at very small frame sizes, to avoid too large fraction of
  // superblocks to be refreshed per frame. Threshold below is less than QCIF.
  if (rc->avg_frame_bandwidth < factor * number_blocks ||
      number_blocks / 64 < 5)
    return 0;
  else
    return 1;
}

// Check if this coding block, of size bsize, should be considered for refresh
// (lower-qp coding). Decision can be based on various factors, such as
// size of the coding block (i.e., below min_block size rejected), coding
// mode, and rate/distortion.
static int candidate_refresh_aq(const CYCLIC_REFRESH *cr,
                                const MB_MODE_INFO *mbmi,
                                int64_t rate,
                                int64_t dist,
                                int bsize) {
  MV mv = mbmi->mv[0].as_mv;
  // Reject the block for lower-qp coding if projected distortion
  // is above the threshold, and any of the following is true:
  // 1) mode uses large mv
  // 2) mode is an intra-mode
  // Otherwise accept for refresh.
  if (dist > cr->thresh_dist_sb &&
      (mv.row > cr->motion_thresh || mv.row < -cr->motion_thresh ||
       mv.col > cr->motion_thresh || mv.col < -cr->motion_thresh ||
       !is_inter_block(mbmi)))
    return CR_SEGMENT_ID_BASE;
  else  if (bsize >= BLOCK_16X16 &&
            rate < cr->thresh_rate_sb &&
            is_inter_block(mbmi) &&
            mbmi->mv[0].as_int == 0)
    // More aggressive delta-q for bigger blocks with zero motion.
    return CR_SEGMENT_ID_BOOST2;
  else
    return CR_SEGMENT_ID_BOOST1;
}

// Compute delta-q for the segment.
static int compute_deltaq(const VP9_COMP *cpi, int q, double rate_factor) {
  const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  const RATE_CONTROL *const rc = &cpi->rc;
  int deltaq = vp9_compute_qdelta_by_rate(rc, cpi->common.frame_type,
                                          q, rate_factor,
                                          cpi->common.bit_depth);
  if ((-deltaq) > cr->max_qdelta_perc * q / 100) {
    deltaq = -cr->max_qdelta_perc * q / 100;
  }
  return deltaq;
}

// For the just encoded frame, estimate the bits, incorporating the delta-q
// from non-base segment. For now ignore effect of multiple segments
// (with different delta-q). Note this function is called in the postencode
// (called from rc_update_rate_correction_factors()).
int vp9_cyclic_refresh_estimate_bits_at_q(const VP9_COMP *cpi,
                                          double correction_factor) {
  const VP9_COMMON *const cm = &cpi->common;
  const CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  int estimated_bits;
  int mbs = cm->MBs;
  int num8x8bl = mbs << 2;
  // Weight for non-base segments: use actual number of blocks refreshed in
  // previous/just encoded frame. Note number of blocks here is in 8x8 units.
  double weight_segment1 = (double)cr->actual_num_seg1_blocks / num8x8bl;
  double weight_segment2 = (double)cr->actual_num_seg2_blocks / num8x8bl;
  // Take segment weighted average for estimated bits.
  estimated_bits = (int)((1.0 - weight_segment1 - weight_segment2) *
      vp9_estimate_bits_at_q(cm->frame_type, cm->base_qindex, mbs,
                             correction_factor, cm->bit_depth) +
                             weight_segment1 *
      vp9_estimate_bits_at_q(cm->frame_type,
                             cm->base_qindex + cr->qindex_delta_seg1, mbs,
                             correction_factor, cm->bit_depth) +
                             weight_segment2 *
      vp9_estimate_bits_at_q(cm->frame_type,
                             cm->base_qindex + cr->qindex_delta_seg2, mbs,
                             correction_factor, cm->bit_depth));
  return estimated_bits;
}

// Prior to encoding the frame, estimate the bits per mb, for a given q = i and
// a corresponding delta-q (for segment 1). This function is called in the
// rc_regulate_q() to set the base qp index.
// Note: the segment map is set to either 0/CR_SEGMENT_ID_BASE (no refresh) or
// to 1/CR_SEGMENT_ID_BOOST1 (refresh) for each superblock, prior to encoding.
int vp9_cyclic_refresh_rc_bits_per_mb(const VP9_COMP *cpi, int i,
                                      double correction_factor) {
  const VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  int bits_per_mb;
  int num8x8bl = cm->MBs << 2;
  // Weight for segment prior to encoding: take the average of the target
  // number for the frame to be encoded and the actual from the previous frame.
  double weight_segment = (double)((cr->target_num_seg_blocks +
      cr->actual_num_seg1_blocks + cr->actual_num_seg2_blocks) >> 1) /
      num8x8bl;
  // Compute delta-q corresponding to qindex i.
  int deltaq = compute_deltaq(cpi, i, cr->rate_ratio_qdelta);
  // Take segment weighted average for bits per mb.
  bits_per_mb = (int)((1.0 - weight_segment) *
      vp9_rc_bits_per_mb(cm->frame_type, i, correction_factor, cm->bit_depth) +
      weight_segment *
      vp9_rc_bits_per_mb(cm->frame_type, i + deltaq, correction_factor,
                         cm->bit_depth));
  return bits_per_mb;
}

// Prior to coding a given prediction block, of size bsize at (mi_row, mi_col),
// check if we should reset the segment_id, and update the cyclic_refresh map
// and segmentation map.
void vp9_cyclic_refresh_update_segment(VP9_COMP *const cpi,
                                       MB_MODE_INFO *const mbmi,
                                       int mi_row, int mi_col,
                                       BLOCK_SIZE bsize,
                                       int64_t rate,
                                       int64_t dist,
                                       int skip) {
  const VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  const int bw = num_8x8_blocks_wide_lookup[bsize];
  const int bh = num_8x8_blocks_high_lookup[bsize];
  const int xmis = MIN(cm->mi_cols - mi_col, bw);
  const int ymis = MIN(cm->mi_rows - mi_row, bh);
  const int block_index = mi_row * cm->mi_cols + mi_col;
  const int refresh_this_block = candidate_refresh_aq(cr, mbmi, rate, dist,
                                                      bsize);
  // Default is to not update the refresh map.
  int new_map_value = cr->map[block_index];
  int x = 0; int y = 0;

  // If this block is labeled for refresh, check if we should reset the
  // segment_id.
  if (cyclic_refresh_segment_id_boosted(mbmi->segment_id)) {
    mbmi->segment_id = refresh_this_block;
    // Reset segment_id if will be skipped.
    if (skip)
      mbmi->segment_id = CR_SEGMENT_ID_BASE;
  }

  // Update the cyclic refresh map, to be used for setting segmentation map
  // for the next frame. If the block  will be refreshed this frame, mark it
  // as clean. The magnitude of the -ve influences how long before we consider
  // it for refresh again.
  if (cyclic_refresh_segment_id_boosted(mbmi->segment_id)) {
    new_map_value = -cr->time_for_refresh;
  } else if (refresh_this_block) {
    // Else if it is accepted as candidate for refresh, and has not already
    // been refreshed (marked as 1) then mark it as a candidate for cleanup
    // for future time (marked as 0), otherwise don't update it.
    if (cr->map[block_index] == 1)
      new_map_value = 0;
  } else {
    // Leave it marked as block that is not candidate for refresh.
    new_map_value = 1;
  }

  // Update entries in the cyclic refresh map with new_map_value, and
  // copy mbmi->segment_id into global segmentation map.
  for (y = 0; y < ymis; y++)
    for (x = 0; x < xmis; x++) {
      cr->map[block_index + y * cm->mi_cols + x] = new_map_value;
      cpi->segmentation_map[block_index + y * cm->mi_cols + x] =
          mbmi->segment_id;
    }
}

// Update the actual number of blocks that were applied the segment delta q.
void vp9_cyclic_refresh_postencode(VP9_COMP *const cpi) {
  VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  unsigned char *const seg_map = cpi->segmentation_map;
  int mi_row, mi_col;
  cr->actual_num_seg1_blocks = 0;
  cr->actual_num_seg2_blocks = 0;
  for (mi_row = 0; mi_row < cm->mi_rows; mi_row++)
    for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
      if (cyclic_refresh_segment_id(
          seg_map[mi_row * cm->mi_cols + mi_col]) == CR_SEGMENT_ID_BOOST1)
        cr->actual_num_seg1_blocks++;
      else if (cyclic_refresh_segment_id(
          seg_map[mi_row * cm->mi_cols + mi_col]) == CR_SEGMENT_ID_BOOST2)
        cr->actual_num_seg2_blocks++;
    }
}

// Set golden frame update interval, for non-svc 1 pass CBR mode.
void vp9_cyclic_refresh_set_golden_update(VP9_COMP *const cpi) {
  RATE_CONTROL *const rc = &cpi->rc;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  // Set minimum gf_interval for GF update to a multiple (== 2) of refresh
  // period. Depending on past encoding stats, GF flag may be reset and update
  // may not occur until next baseline_gf_interval.
  if (cr->percent_refresh > 0)
    rc->baseline_gf_interval = 2 * (100 / cr->percent_refresh);
  else
    rc->baseline_gf_interval = 20;
}

// Update some encoding stats (from the just encoded frame), and if the golden
// reference is to be updated check if we should NOT update the golden ref.
void vp9_cyclic_refresh_check_golden_update(VP9_COMP *const cpi) {
  VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  int mi_row, mi_col;
  double fraction_low = 0.0;
  int low_content_frame = 0;
  for (mi_row = 0; mi_row < cm->mi_rows; mi_row++)
    for (mi_col = 0; mi_col < cm->mi_cols; mi_col++) {
      if (cr->map[mi_row * cm->mi_cols + mi_col] < 1)
        low_content_frame++;
    }
  fraction_low =
      (double)low_content_frame / (cm->mi_rows * cm->mi_cols);
  // Update average.
  cr->low_content_avg = (fraction_low + 3 * cr->low_content_avg) / 4;
  if (cpi->refresh_golden_frame == 1) {
    // Don't update golden reference if the amount of low_content for the
    // current encoded frame is small, or if the recursive average of the
    // low_content over the update interval window falls below threshold.
    if (fraction_low < 0.8 || cr->low_content_avg < 0.7)
      cpi->refresh_golden_frame = 0;
    // Reset for next internal.
    cr->low_content_avg = fraction_low;
  }
}

// Update the segmentation map, and related quantities: cyclic refresh map,
// refresh sb_index, and target number of blocks to be refreshed.
// The map is set to either 0/CR_SEGMENT_ID_BASE (no refresh) or to
// 1/CR_SEGMENT_ID_BOOST1 (refresh) for each superblock.
// Blocks labeled as BOOST1 may later get set to BOOST2 (during the
// encoding of the superblock).
void vp9_cyclic_refresh_update_map(VP9_COMP *const cpi) {
  VP9_COMMON *const cm = &cpi->common;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  unsigned char *const seg_map = cpi->segmentation_map;
  int i, block_count, bl_index, sb_rows, sb_cols, sbs_in_frame;
  int xmis, ymis, x, y;
  vpx_memset(seg_map, CR_SEGMENT_ID_BASE, cm->mi_rows * cm->mi_cols);
  sb_cols = (cm->mi_cols + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
  sb_rows = (cm->mi_rows + MI_BLOCK_SIZE - 1) / MI_BLOCK_SIZE;
  sbs_in_frame = sb_cols * sb_rows;
  // Number of target blocks to get the q delta (segment 1).
  block_count = cr->percent_refresh * cm->mi_rows * cm->mi_cols / 100;
  // Set the segmentation map: cycle through the superblocks, starting at
  // cr->mb_index, and stopping when either block_count blocks have been found
  // to be refreshed, or we have passed through whole frame.
  assert(cr->sb_index < sbs_in_frame);
  i = cr->sb_index;
  cr->target_num_seg_blocks = 0;
  do {
    int sum_map = 0;
    // Get the mi_row/mi_col corresponding to superblock index i.
    int sb_row_index = (i / sb_cols);
    int sb_col_index = i - sb_row_index * sb_cols;
    int mi_row = sb_row_index * MI_BLOCK_SIZE;
    int mi_col = sb_col_index * MI_BLOCK_SIZE;
    assert(mi_row >= 0 && mi_row < cm->mi_rows);
    assert(mi_col >= 0 && mi_col < cm->mi_cols);
    bl_index = mi_row * cm->mi_cols + mi_col;
    // Loop through all 8x8 blocks in superblock and update map.
    xmis = MIN(cm->mi_cols - mi_col,
               num_8x8_blocks_wide_lookup[BLOCK_64X64]);
    ymis = MIN(cm->mi_rows - mi_row,
               num_8x8_blocks_high_lookup[BLOCK_64X64]);
    for (y = 0; y < ymis; y++) {
      for (x = 0; x < xmis; x++) {
        const int bl_index2 = bl_index + y * cm->mi_cols + x;
        // If the block is as a candidate for clean up then mark it
        // for possible boost/refresh (segment 1). The segment id may get
        // reset to 0 later if block gets coded anything other than ZEROMV.
        if (cr->map[bl_index2] == 0) {
          sum_map++;
        } else if (cr->map[bl_index2] < 0) {
          cr->map[bl_index2]++;
        }
      }
    }
    // Enforce constant segment over superblock.
    // If segment is at least half of superblock, set to 1.
    if (sum_map >= xmis * ymis / 2) {
      for (y = 0; y < ymis; y++)
        for (x = 0; x < xmis; x++) {
          seg_map[bl_index + y * cm->mi_cols + x] = CR_SEGMENT_ID_BOOST1;
        }
      cr->target_num_seg_blocks += xmis * ymis;
    }
    i++;
    if (i == sbs_in_frame) {
      i = 0;
    }
  } while (cr->target_num_seg_blocks < block_count && i != cr->sb_index);
  cr->sb_index = i;
}

// Set/update global/frame level cyclic refresh parameters.
void vp9_cyclic_refresh_update_parameters(VP9_COMP *const cpi) {
  const RATE_CONTROL *const rc = &cpi->rc;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  cr->percent_refresh = 10;
  // Use larger delta-qp (increase rate_ratio_qdelta) for first few (~4)
  // periods of the refresh cycle, after a key frame. This corresponds to ~40
  // frames with cr->percent_refresh = 10.
  if (rc->frames_since_key <  40)
    cr->rate_ratio_qdelta = 3.0;
  else
    cr->rate_ratio_qdelta = 2.0;
}

// Setup cyclic background refresh: set delta q and segmentation map.
void vp9_cyclic_refresh_setup(VP9_COMP *const cpi) {
  VP9_COMMON *const cm = &cpi->common;
  const RATE_CONTROL *const rc = &cpi->rc;
  CYCLIC_REFRESH *const cr = cpi->cyclic_refresh;
  struct segmentation *const seg = &cm->seg;
  const int apply_cyclic_refresh  = apply_cyclic_refresh_bitrate(cm, rc);
  if (cm->current_video_frame == 0)
    cr->low_content_avg = 0.0;
  // Don't apply refresh on key frame or enhancement layer frames.
  if (!apply_cyclic_refresh ||
      (cm->frame_type == KEY_FRAME) ||
      (cpi->svc.temporal_layer_id > 0) ||
      (cpi->svc.spatial_layer_id > 0)) {
    // Set segmentation map to 0 and disable.
    unsigned char *const seg_map = cpi->segmentation_map;
    vpx_memset(seg_map, 0, cm->mi_rows * cm->mi_cols);
    vp9_disable_segmentation(&cm->seg);
    if (cm->frame_type == KEY_FRAME)
      cr->sb_index = 0;
    return;
  } else {
    int qindex_delta = 0;
    int qindex2;
    const double q = vp9_convert_qindex_to_q(cm->base_qindex, cm->bit_depth);
    vp9_clear_system_state();
    cr->max_qdelta_perc = 50;
    cr->time_for_refresh = 0;
    // Set rate threshold to some multiple (set to 2 for now) of the target
    // rate (target is given by sb64_target_rate and scaled by 256).
    cr->thresh_rate_sb = ((int64_t)(rc->sb64_target_rate) << 8) << 2;
    // Distortion threshold, quadratic in Q, scale factor to be adjusted.
    // q will not exceed 457, so (q * q) is within 32bit; see:
    // vp9_convert_qindex_to_q(), vp9_ac_quant(), ac_qlookup*[].
    cr->thresh_dist_sb = ((int64_t)(q * q)) << 2;
    cr->motion_thresh = 32;
    // Set up segmentation.
    // Clear down the segment map.
    vp9_enable_segmentation(&cm->seg);
    vp9_clearall_segfeatures(seg);
    // Select delta coding method.
    seg->abs_delta = SEGMENT_DELTADATA;

    // Note: setting temporal_update has no effect, as the seg-map coding method
    // (temporal or spatial) is determined in vp9_choose_segmap_coding_method(),
    // based on the coding cost of each method. For error_resilient mode on the
    // last_frame_seg_map is set to 0, so if temporal coding is used, it is
    // relative to 0 previous map.
    // seg->temporal_update = 0;

    // Segment BASE "Q" feature is disabled so it defaults to the baseline Q.
    vp9_disable_segfeature(seg, CR_SEGMENT_ID_BASE, SEG_LVL_ALT_Q);
    // Use segment BOOST1 for in-frame Q adjustment.
    vp9_enable_segfeature(seg, CR_SEGMENT_ID_BOOST1, SEG_LVL_ALT_Q);
    // Use segment BOOST2 for more aggressive in-frame Q adjustment.
    vp9_enable_segfeature(seg, CR_SEGMENT_ID_BOOST2, SEG_LVL_ALT_Q);

    // Set the q delta for segment BOOST1.
    qindex_delta = compute_deltaq(cpi, cm->base_qindex, cr->rate_ratio_qdelta);
    cr->qindex_delta_seg1 = qindex_delta;

    // Compute rd-mult for segment BOOST1.
    qindex2 = clamp(cm->base_qindex + cm->y_dc_delta_q + qindex_delta, 0, MAXQ);

    cr->rdmult = vp9_compute_rd_mult(cpi, qindex2);

    vp9_set_segdata(seg, CR_SEGMENT_ID_BOOST1, SEG_LVL_ALT_Q, qindex_delta);

    // Set a more aggressive (higher) q delta for segment BOOST2.
    qindex_delta = compute_deltaq(cpi, cm->base_qindex,
                                  MIN(CR_MAX_RATE_TARGET_RATIO,
                                      CR_BOOST2_FAC * cr->rate_ratio_qdelta));
    cr->qindex_delta_seg2 = qindex_delta;
    vp9_set_segdata(seg, CR_SEGMENT_ID_BOOST2, SEG_LVL_ALT_Q, qindex_delta);

    // Update the segmentation and refresh map.
    vp9_cyclic_refresh_update_map(cpi);
  }
}

int vp9_cyclic_refresh_get_rdmult(const CYCLIC_REFRESH *cr) {
  return cr->rdmult;
}


text:
using Flurfunk.Data.Interface;
using Flurfunk.Data.Model;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Flurfunk.Data
{
    public class MessageService : IMessageService
    {
        private IDatabase db;

        public MessageService(IDatabase database)
        {
            db = database;
        }

        public Message Create(string text, string creator)
        {
            return Create(text, creator, ObjectId.Empty.ToString());
        }

        public Message Create(string text, string creator, string groupId)
        {
            Message newMessage = new Message() { CreatorId = creator, Text = text, GroupId = groupId, Created = DateTime.Now };
            newMessage.Validate();
            db.Messages.Insert(newMessage);
            return newMessage;
        }

        public void Delete(string messageId)
        {
            db.Messages.Remove(Query.EQ("_id", messageId));
        }

        public List<Message> GetNewerThan(DateTime time, string keyword = "", string groupId = "")
        {
            IQueryable<Message> data = string.IsNullOrWhiteSpace(keyword) ? db.Messages.AsQueryable() : Filter(keyword).AsQueryable();

            if (!string.IsNullOrWhiteSpace(groupId))
            {
                data = data.Where(x => x.GroupId == groupId);
            }
            else
            {
                data = data.Where(x => x.GroupId == ObjectId.Empty.ToString());
            }

            var messages = data.Where(x => x.Created > time).OrderByDescending(x => x.Created);

            return LoadUsers(messages.ToList());
        }
        public List<Message> GetOlderThan(int count, DateTime time, string keyword = "", string groupId = "")
        {
            IQueryable<Message> data = string.IsNullOrWhiteSpace(keyword) ? db.Messages.AsQueryable() : Filter(keyword).AsQueryable();

            if (!string.IsNullOrWhiteSpace(groupId))
            {
                data = data.Where(x => x.GroupId == groupId);
            }
            else
            {
                data = data.Where(x => x.GroupId == ObjectId.Empty.ToString());
            }

            var messages = data.Where(x => x.Created < time).OrderByDescending(x => x.Created).Take(count);

            return LoadUsers(messages.ToList());
        }

        [Obsolete]
        public List<Message> Get(int count, int startIndex)
        {
            return db.Messages.AsQueryable().OrderBy(x => x.Created).Skip(startIndex).Take(count).ToList();
        }

        [Obsolete]
        public List<Message> Get(int count, int startIndex, string keyword)
        {
            var textSearchCommand = new CommandDocument
                {
                    { "text", db.Messages.Name },
                    { "search", keyword }
                };
            var commandResult = db.MongoDatabase.RunCommand(textSearchCommand);
            var response = commandResult.Response["results"];

            List<Message> result = new List<Message>();

            foreach (var item in response.AsBsonArray)
            {
                result.Add(BsonSerializer.Deserialize<Message>(item["obj"].ToBsonDocument()));
            }

            return result.OrderBy(x => x.Created).Skip(startIndex).Take(count).ToList();
        }

        public List<Message> Filter(string keyword)
        {
            var textSearchCommand = new CommandDocument
                {
                    { "text", db.Messages.Name },
                    { "search", keyword }
                };
            var commandResult = db.MongoDatabase.RunCommand(textSearchCommand);
            var response = commandResult.Response["results"];

            List<Message> result = new List<Message>();

            foreach (var item in response.AsBsonArray)
            {
                result.Add(BsonSerializer.Deserialize<Message>(item["obj"].ToBsonDocument()));
            }

            return result;
        }

        private List<Message> LoadUsers(List<Message> messages)
        {
            var ids = messages.Select(x => x.CreatorId).Distinct();

            var users = db.Users.Find(Query<User>.In(x => x._id, ids));

            return messages.Join(users, message => message.CreatorId, user => user._id, (message, user) => { message.Creator = user; return message; }).ToList();
        }
    }
}


text:
echo 'creating folder axe-aggregator'
mkdir -p /opt/cloudiator/axe-aggregator

cd /opt/cloudiator/axe-aggregator
echo 'downloading latest binary'
wget  https://oss.sonatype.org/content/repositories/snapshots/io/github/cloudiator/axe/axe-aggregator-service/0.2.0-SNAPSHOT/axe-aggregator-service-0.2.0-20161026.111801-20-jar-with-dependencies.jar -O axe-aggregator-service-0.2.0-SNAPSHOT-jar-with-dependencies.jar

echo 'downloading upstart config'
wget https://raw.githubusercontent.com/cloudiator/installation/master/shell/ubuntu/14/axe-aggregator.conf -O /etc/init/axe-aggregator.conf

echo 'starting axe-aggregator'
start axe-aggregator

echo 'control axe-aggregator via COMMAND axe-aggregator'


text:
<!DOCTYPE html>

  <title>Lesson 5 / VVVV.js Workshop</title>

  <link rel="Stylesheet" href="../vvvv_js/vvvviewer/vvvv.css"/>

  <link rel="VVVV" href="mypatch.v4p"/>


text:
#define DT_DRV_COMPAT ti_bq274xx

#include <zephyr/drivers/i2c.h>
#include <zephyr/init.h>
#include <zephyr/drivers/sensor.h>
#include <zephyr/pm/device.h>
#include <zephyr/sys/__assert.h>
#include <string.h>
#include <zephyr/sys/byteorder.h>
#include <zephyr/drivers/gpio.h>
#include <zephyr/logging/log.h>

#include "bq274xx.h"

LOG_MODULE_REGISTER(bq274xx, CONFIG_SENSOR_LOG_LEVEL);

#define BQ274XX_SUBCLASS_DELAY 5 /* subclass 64 & 82 needs 5ms delay */
/* Time to set pin in order to exit shutdown mode */
#define PIN_DELAY_TIME 1U
/* Time it takes device to initialize before doing any configuration */
#define INIT_TIME 100U

static int bq274xx_gauge_configure(const struct device *dev);

static int bq274xx_command_reg_read(const struct device *dev, uint8_t reg_addr,
				    int16_t *val)
{
	const struct bq274xx_config *config = dev->config;
	uint8_t i2c_data[2];
	int status;

	status = i2c_burst_read_dt(&config->i2c, reg_addr,
				   i2c_data, 2);
	if (status < 0) {
		LOG_ERR("Unable to read register");
		return -EIO;
	}

	*val = (i2c_data[1] << 8) | i2c_data[0];

	return 0;
}

static int bq274xx_control_reg_write(const struct device *dev,
				     uint16_t subcommand)
{
	const struct bq274xx_config *config = dev->config;
	uint8_t i2c_data, reg_addr;
	int status = 0;

	reg_addr = BQ274XX_COMMAND_CONTROL_LOW;
	i2c_data = (uint8_t)((subcommand)&0x00FF);

	status = i2c_reg_write_byte_dt(&config->i2c, reg_addr,
				       i2c_data);
	if (status < 0) {
		LOG_ERR("Failed to write into control low register");
		return -EIO;
	}

	k_msleep(BQ274XX_SUBCLASS_DELAY);

	reg_addr = BQ274XX_COMMAND_CONTROL_HIGH;
	i2c_data = (uint8_t)((subcommand >> 8) & 0x00FF);

	status = i2c_reg_write_byte_dt(&config->i2c, reg_addr,
				       i2c_data);
	if (status < 0) {
		LOG_ERR("Failed to write into control high register");
		return -EIO;
	}

	return 0;
}

static int bq274xx_command_reg_write(const struct device *dev, uint8_t command,
				     uint8_t data)
{
	const struct bq274xx_config *config = dev->config;
	uint8_t i2c_data, reg_addr;
	int status = 0;

	reg_addr = command;
	i2c_data = data;

	status = i2c_reg_write_byte_dt(&config->i2c, reg_addr,
				       i2c_data);
	if (status < 0) {
		LOG_ERR("Failed to write into control register");
		return -EIO;
	}

	return 0;
}

static int bq274xx_read_data_block(const struct device *dev, uint8_t offset,
				   uint8_t *data, uint8_t bytes)
{
	const struct bq274xx_config *config = dev->config;
	uint8_t i2c_data;
	int status = 0;

	i2c_data = BQ274XX_EXTENDED_BLOCKDATA_START + offset;

	status = i2c_burst_read_dt(&config->i2c, i2c_data,
				   data, bytes);
	if (status < 0) {
		LOG_ERR("Failed to read block");
		return -EIO;
	}

	k_msleep(BQ274XX_SUBCLASS_DELAY);

	return 0;
}

static int bq274xx_get_device_type(const struct device *dev, uint16_t *val)
{
	int status;

	status =
		bq274xx_control_reg_write(dev, BQ274XX_CONTROL_DEVICE_TYPE);
	if (status < 0) {
		LOG_ERR("Unable to write control register");
		return -EIO;
	}

	status = bq274xx_command_reg_read(dev, BQ274XX_COMMAND_CONTROL_LOW,
					  val);

	if (status < 0) {
		LOG_ERR("Unable to read register");
		return -EIO;
	}

	return 0;
}

/**
 * @brief sensor value get
 *
 * @return -ENOTSUP for unsupported channels
 */
static int bq274xx_channel_get(const struct device *dev,
			       enum sensor_channel chan,
			       struct sensor_value *val)
{
	struct bq274xx_data *bq274xx = dev->data;
	float int_temp;

	switch (chan) {
	case SENSOR_CHAN_GAUGE_VOLTAGE:
		val->val1 = ((bq274xx->voltage / 1000));
		val->val2 = ((bq274xx->voltage % 1000) * 1000U);
		break;

	case SENSOR_CHAN_GAUGE_AVG_CURRENT:
		val->val1 = ((bq274xx->avg_current / 1000));
		val->val2 = ((bq274xx->avg_current % 1000) * 1000U);
		break;

	case SENSOR_CHAN_GAUGE_STDBY_CURRENT:
		val->val1 = ((bq274xx->stdby_current / 1000));
		val->val2 = ((bq274xx->stdby_current % 1000) * 1000U);
		break;

	case SENSOR_CHAN_GAUGE_MAX_LOAD_CURRENT:
		val->val1 = ((bq274xx->max_load_current / 1000));
		val->val2 = ((bq274xx->max_load_current % 1000) * 1000U);
		break;

	case SENSOR_CHAN_GAUGE_TEMP:
		int_temp = (bq274xx->internal_temperature * 0.1f);
		int_temp = int_temp - 273.15f;
		val->val1 = (int32_t)int_temp;
		val->val2 = (int_temp - (int32_t)int_temp) * 1000000;
		break;

	case SENSOR_CHAN_GAUGE_STATE_OF_CHARGE:
		val->val1 = bq274xx->state_of_charge;
		val->val2 = 0;
		break;

	case SENSOR_CHAN_GAUGE_STATE_OF_HEALTH:
		val->val1 = bq274xx->state_of_health;
		val->val2 = 0;
		break;

	case SENSOR_CHAN_GAUGE_FULL_CHARGE_CAPACITY:
		val->val1 = (bq274xx->full_charge_capacity / 1000);
		val->val2 = ((bq274xx->full_charge_capacity % 1000) * 1000U);
		break;

	case SENSOR_CHAN_GAUGE_REMAINING_CHARGE_CAPACITY:
		val->val1 = (bq274xx->remaining_charge_capacity / 1000);
		val->val2 =
			((bq274xx->remaining_charge_capacity % 1000) * 1000U);
		break;

	case SENSOR_CHAN_GAUGE_NOM_AVAIL_CAPACITY:
		val->val1 = (bq274xx->nom_avail_capacity / 1000);
		val->val2 = ((bq274xx->nom_avail_capacity % 1000) * 1000U);
		break;

	case SENSOR_CHAN_GAUGE_FULL_AVAIL_CAPACITY:
		val->val1 = (bq274xx->full_avail_capacity / 1000);
		val->val2 = ((bq274xx->full_avail_capacity % 1000) * 1000U);
		break;

	case SENSOR_CHAN_GAUGE_AVG_POWER:
		val->val1 = (bq274xx->avg_power / 1000);
		val->val2 = ((bq274xx->avg_power % 1000) * 1000U);
		break;

	default:
		return -ENOTSUP;
	}

	return 0;
}

static int bq274xx_sample_fetch(const struct device *dev,
				enum sensor_channel chan)
{
	struct bq274xx_data *bq274xx = dev->data;
	int status = 0;

	if (!bq274xx->configured) {
		status = bq274xx_gauge_configure(dev);

		if (status < 0) {
			return status;
		}
	}

	switch (chan) {
	case SENSOR_CHAN_GAUGE_VOLTAGE:
		status = bq274xx_command_reg_read(
			dev, BQ274XX_COMMAND_VOLTAGE, &bq274xx->voltage);
		if (status < 0) {
			LOG_ERR("Failed to read voltage");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_AVG_CURRENT:
		status = bq274xx_command_reg_read(dev,
						  BQ274XX_COMMAND_AVG_CURRENT,
						  &bq274xx->avg_current);
		if (status < 0) {
			LOG_ERR("Failed to read average current ");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_TEMP:
		status = bq274xx_command_reg_read(
			dev, BQ274XX_COMMAND_INT_TEMP,
			&bq274xx->internal_temperature);
		if (status < 0) {
			LOG_ERR("Failed to read internal temperature");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_STDBY_CURRENT:
		status = bq274xx_command_reg_read(dev,
						  BQ274XX_COMMAND_STDBY_CURRENT,
						  &bq274xx->stdby_current);
		if (status < 0) {
			LOG_ERR("Failed to read standby current");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_MAX_LOAD_CURRENT:
		status = bq274xx_command_reg_read(dev,
						  BQ274XX_COMMAND_MAX_CURRENT,
						  &bq274xx->max_load_current);
		if (status < 0) {
			LOG_ERR("Failed to read maximum current");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_STATE_OF_CHARGE:
		status = bq274xx_command_reg_read(dev, BQ274XX_COMMAND_SOC,
						  &bq274xx->state_of_charge);
		if (status < 0) {
			LOG_ERR("Failed to read state of charge");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_FULL_CHARGE_CAPACITY:
		status = bq274xx_command_reg_read(
			dev, BQ274XX_COMMAND_FULL_CAPACITY,
			&bq274xx->full_charge_capacity);
		if (status < 0) {
			LOG_ERR("Failed to read full charge capacity");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_REMAINING_CHARGE_CAPACITY:
		status = bq274xx_command_reg_read(
			dev, BQ274XX_COMMAND_REM_CAPACITY,
			&bq274xx->remaining_charge_capacity);
		if (status < 0) {
			LOG_ERR("Failed to read remaining charge capacity");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_NOM_AVAIL_CAPACITY:
		status = bq274xx_command_reg_read(dev,
						  BQ274XX_COMMAND_NOM_CAPACITY,
						  &bq274xx->nom_avail_capacity);
		if (status < 0) {
			LOG_ERR("Failed to read nominal available capacity");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_FULL_AVAIL_CAPACITY:
		status =
			bq274xx_command_reg_read(dev,
						 BQ274XX_COMMAND_AVAIL_CAPACITY,
						 &bq274xx->full_avail_capacity);
		if (status < 0) {
			LOG_ERR("Failed to read full available capacity");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_AVG_POWER:
		status = bq274xx_command_reg_read(dev,
						  BQ274XX_COMMAND_AVG_POWER,
						  &bq274xx->avg_power);
		if (status < 0) {
			LOG_ERR("Failed to read battery average power");
			return -EIO;
		}
		break;

	case SENSOR_CHAN_GAUGE_STATE_OF_HEALTH:
		status = bq274xx_command_reg_read(dev, BQ274XX_COMMAND_SOH,
						  &bq274xx->state_of_health);

		bq274xx->state_of_health = (bq274xx->state_of_health) & 0x00FF;

		if (status < 0) {
			LOG_ERR("Failed to read state of health");
			return -EIO;
		}
		break;

	default:
		return -ENOTSUP;
	}

	return 0;
}

/**
 * @brief initialise the fuel gauge
 *
 * @return 0 for success
 */
static int bq274xx_gauge_init(const struct device *dev)
{
	const struct bq274xx_config *const config = dev->config;
	int status = 0;
	uint16_t id;

	if (!device_is_ready(config->i2c.bus)) {
		LOG_ERR("I2C bus device not ready");
		return -ENODEV;
	}

#if defined(CONFIG_PM_DEVICE) || defined(CONFIG_BQ274XX_TRIGGER)
	if (!device_is_ready(config->int_gpios.port)) {
		LOG_ERR("GPIO device pointer is not ready to be used");
		return -ENODEV;
	}
#endif

	status = bq274xx_get_device_type(dev, &id);
	if (status < 0) {
		LOG_ERR("Unable to get device ID");
		return -EIO;
	}

	if (id != BQ274XX_DEVICE_ID) {
		LOG_ERR("Invalid Device");
		return -EINVAL;
	}

#ifdef CONFIG_BQ274XX_TRIGGER
	status = bq274xx_trigger_mode_init(dev);
	if (status < 0) {
		LOG_ERR("Unable set up trigger mode.");
		return status;
	}
#endif

	if (!config->lazy_loading) {
		status = bq274xx_gauge_configure(dev);
	}

	return status;
}

static int bq274xx_gauge_configure(const struct device *dev)
{
	const struct bq274xx_config *const config = dev->config;
	struct bq274xx_data *data = dev->data;

	int status = 0;
	uint8_t tmp_checksum = 0, checksum_old = 0, checksum_new = 0;
	uint16_t flags = 0, designenergy_mwh = 0, taperrate = 0;
	uint8_t designcap_msb, designcap_lsb, designenergy_msb, designenergy_lsb,
		terminatevolt_msb, terminatevolt_lsb, taperrate_msb,
		taperrate_lsb;
	uint8_t block[32];

	designenergy_mwh = (uint16_t)3.7 * config->design_capacity;
	taperrate =
		(uint16_t)config->design_capacity / (0.1 * config->taper_current);

	/** Unseal the battery control register **/
	status = bq274xx_control_reg_write(dev, BQ274XX_UNSEAL_KEY);
	if (status < 0) {
		LOG_ERR("Unable to unseal the battery");
		return -EIO;
	}

	status = bq274xx_control_reg_write(dev, BQ274XX_UNSEAL_KEY);
	if (status < 0) {
		LOG_ERR("Unable to unseal the battery");
		return -EIO;
	}

	/* Send CFG_UPDATE */
	status = bq274xx_control_reg_write(dev,
					   BQ274XX_CONTROL_SET_CFGUPDATE);
	if (status < 0) {
		LOG_ERR("Unable to set CFGUpdate");
		return -EIO;
	}

	/** Step to place the Gauge into CONFIG UPDATE Mode **/
	do {
		status = bq274xx_command_reg_read(
			dev, BQ274XX_COMMAND_FLAGS, &flags);
		if (status < 0) {
			LOG_ERR("Unable to read flags");
			return -EIO;
		}

		if (!(flags & 0x0010)) {
			k_msleep(BQ274XX_SUBCLASS_DELAY * 10);
		}

	} while (!(flags & 0x0010));

	status = bq274xx_command_reg_write(dev,
					   BQ274XX_EXTENDED_DATA_CONTROL, 0x00);
	if (status < 0) {
		LOG_ERR("Failed to enable block data memory");
		return -EIO;
	}

	/* Access State subclass */
	status = bq274xx_command_reg_write(dev, BQ274XX_EXTENDED_DATA_CLASS,
					   0x52);
	if (status < 0) {
		LOG_ERR("Failed to update state subclass");
		return -EIO;
	}

	/* Write the block offset */
	status = bq274xx_command_reg_write(dev, BQ274XX_EXTENDED_DATA_BLOCK,
					   0x00);
	if (status < 0) {
		LOG_ERR("Failed to update block offset");
		return -EIO;
	}

	for (uint8_t i = 0; i < 32; i++) {
		block[i] = 0;
	}

	status = bq274xx_read_data_block(dev, 0x00, block, 32);
	if (status < 0) {
		LOG_ERR("Unable to read block data");
		return -EIO;
	}

	tmp_checksum = 0;
	for (uint8_t i = 0; i < 32; i++) {
		tmp_checksum += block[i];
	}
	tmp_checksum = 255 - tmp_checksum;

	/* Read the block checksum */
	status = i2c_reg_read_byte_dt(&config->i2c,
				      BQ274XX_EXTENDED_CHECKSUM, &checksum_old);
	if (status < 0) {
		LOG_ERR("Unable to read block checksum");
		return -EIO;
	}

	designcap_msb = config->design_capacity >> 8;
	designcap_lsb = config->design_capacity & 0x00FF;
	designenergy_msb = designenergy_mwh >> 8;
	designenergy_lsb = designenergy_mwh & 0x00FF;
	terminatevolt_msb = config->terminate_voltage >> 8;
	terminatevolt_lsb = config->terminate_voltage & 0x00FF;
	taperrate_msb = taperrate >> 8;
	taperrate_lsb = taperrate & 0x00FF;

	status = i2c_reg_write_byte_dt(&config->i2c,
				       BQ274XX_EXTENDED_BLOCKDATA_DESIGN_CAP_HIGH,
				       designcap_msb);
	if (status < 0) {
		LOG_ERR("Failed to write designCAP MSB");
		return -EIO;
	}

	status = i2c_reg_write_byte_dt(&config->i2c,
				       BQ274XX_EXTENDED_BLOCKDATA_DESIGN_CAP_LOW,
				       designcap_lsb);
	if (status < 0) {
		LOG_ERR("Failed to write designCAP LSB");
		return -EIO;
	}

	status = i2c_reg_write_byte_dt(&config->i2c,
				       BQ274XX_EXTENDED_BLOCKDATA_DESIGN_ENR_HIGH,
				       designenergy_msb);
	if (status < 0) {
		LOG_ERR("Failed to write designEnergy MSB");
		return -EIO;
	}

	status = i2c_reg_write_byte_dt(&config->i2c,
				       BQ274XX_EXTENDED_BLOCKDATA_DESIGN_ENR_LOW,
				       designenergy_lsb);
	if (status < 0) {
		LOG_ERR("Failed to write designEnergy LSB");
		return -EIO;
	}

	status = i2c_reg_write_byte_dt(&config->i2c,
				       BQ274XX_EXTENDED_BLOCKDATA_TERMINATE_VOLT_HIGH,
				       terminatevolt_msb);
	if (status < 0) {
		LOG_ERR("Failed to write terminateVolt MSB");
		return -EIO;
	}

	status = i2c_reg_write_byte_dt(&config->i2c, BQ274XX_EXTENDED_BLOCKDATA_TERMINATE_VOLT_LOW,
				       terminatevolt_lsb);
	if (status < 0) {
		LOG_ERR("Failed to write terminateVolt LSB");
		return -EIO;
	}

	status = i2c_reg_write_byte_dt(&config->i2c,
				       BQ274XX_EXTENDED_BLOCKDATA_TAPERRATE_HIGH,
				       taperrate_msb);
	if (status < 0) {
		LOG_ERR("Failed to write taperRate MSB");
		return -EIO;
	}

	status = i2c_reg_write_byte_dt(&config->i2c,
				       BQ274XX_EXTENDED_BLOCKDATA_TAPERRATE_LOW,
				       taperrate_lsb);
	if (status < 0) {
		LOG_ERR("Failed to write taperRate LSB");
		return -EIO;
	}

	for (uint8_t i = 0; i < 32; i++) {
		block[i] = 0;
	}

	status = bq274xx_read_data_block(dev, 0x00, block, 32);
	if (status < 0) {
		LOG_ERR("Unable to read block data");
		return -EIO;
	}

	checksum_new = 0;
	for (uint8_t i = 0; i < 32; i++) {
		checksum_new += block[i];
	}
	checksum_new = 255 - checksum_new;

	status = bq274xx_command_reg_write(dev, BQ274XX_EXTENDED_CHECKSUM,
					   checksum_new);
	if (status < 0) {
		LOG_ERR("Failed to update new checksum");
		return -EIO;
	}

	tmp_checksum = 0;
	status = i2c_reg_read_byte_dt(&config->i2c,
				      BQ274XX_EXTENDED_CHECKSUM, &tmp_checksum);
	if (status < 0) {
		LOG_ERR("Failed to read checksum");
		return -EIO;
	}

	status = bq274xx_control_reg_write(dev, BQ274XX_CONTROL_BAT_INSERT);
	if (status < 0) {
		LOG_ERR("Unable to configure BAT Detect");
		return -EIO;
	}

	status = bq274xx_control_reg_write(dev, BQ274XX_CONTROL_SOFT_RESET);
	if (status < 0) {
		LOG_ERR("Failed to soft reset the gauge");
		return -EIO;
	}

	flags = 0;
	/* Poll Flags   */
	do {
		status = bq274xx_command_reg_read(
			dev, BQ274XX_COMMAND_FLAGS, &flags);
		if (status < 0) {
			LOG_ERR("Unable to read flags");
			return -EIO;
		}

		if (flags & 0x0010) {
			k_msleep(BQ274XX_SUBCLASS_DELAY * 10);
		}
	} while (flags & 0x0010);

	/* Seal the gauge */
	status = bq274xx_control_reg_write(dev, BQ274XX_CONTROL_SEALED);
	if (status < 0) {
		LOG_ERR("Failed to seal the gauge");
		return -EIO;
	}

	data->configured = true;

	return 0;
}

#ifdef CONFIG_PM_DEVICE
static int bq274xx_enter_shutdown_mode(const struct device *dev)
{
	int status;

	status = bq274xx_control_reg_write(dev, BQ274XX_UNSEAL_KEY);
	if (status < 0) {
		LOG_ERR("Unable to unseal the battery");
		return status;
	}

	status = bq274xx_control_reg_write(dev, BQ274XX_UNSEAL_KEY);
	if (status < 0) {
		LOG_ERR("Unable to unseal the battery");
		return status;
	}

	status = bq274xx_control_reg_write(dev,
					   BQ274XX_CONTROL_SHUTDOWN_ENABLE);
	if (status < 0) {
		LOG_ERR("Unable to enable shutdown mode");
		return status;
	}

	status = bq274xx_control_reg_write(dev, BQ274XX_CONTROL_SHUTDOWN);
	if (status < 0) {
		LOG_ERR("Unable to enter shutdown mode");
		return status;
	}

	status = bq274xx_control_reg_write(dev, BQ274XX_CONTROL_SEALED);
	if (status < 0) {
		LOG_ERR("Failed to seal the gauge");
		return status;
	}

	return 0;
}

static int bq274xx_exit_shutdown_mode(const struct device *dev)
{
	const struct bq274xx_config *const config = dev->config;
	int status = 0;

	status = gpio_pin_configure_dt(&config->int_gpios,
			   GPIO_OUTPUT | GPIO_OPEN_DRAIN);
	if (status < 0) {
		LOG_ERR("Unable to configure interrupt pin to output and open drain");
		return status;
	}

	status = gpio_pin_set_dt(&config->int_gpios, 0);
	if (status < 0) {
		LOG_ERR("Unable to set interrupt pin to low");
		return status;
	}

	k_msleep(PIN_DELAY_TIME);

	status = gpio_pin_configure_dt(&config->int_gpios, GPIO_INPUT);
	if (status < 0) {
		LOG_ERR("Unable to configure interrupt pin to input");
		return status;
	}

	if (!config->lazy_loading) {
		k_msleep(INIT_TIME);

		status = bq274xx_gauge_configure(dev);
		if (status < 0) {
			LOG_ERR("Unable to configure bq274xx gauge");
			return status;
		}
	}

	return 0;
}

static int bq274xx_pm_action(const struct device *dev,
			     enum pm_device_action action)
{
	int ret;

	switch (action) {
	case PM_DEVICE_ACTION_TURN_OFF:
		ret = bq274xx_enter_shutdown_mode(dev);
		break;
	case PM_DEVICE_ACTION_RESUME:
		ret = bq274xx_exit_shutdown_mode(dev);
		break;
	default:
		ret = -ENOTSUP;
		break;
	}

	return ret;
}
#endif /* CONFIG_PM_DEVICE */

static const struct sensor_driver_api bq274xx_battery_driver_api = {
	.sample_fetch = bq274xx_sample_fetch,
	.channel_get = bq274xx_channel_get,
#ifdef CONFIG_BQ274XX_TRIGGER
	.trigger_set = bq274xx_trigger_set,
#endif
};

#if defined(CONFIG_PM_DEVICE) || defined(CONFIG_BQ274XX_TRIGGER)
#define BQ274XX_INT_CFG(index)						      \
	.int_gpios = GPIO_DT_SPEC_INST_GET(index, int_gpios),
#else
#define BQ274XX_INT_CFG(index)
#endif

#define BQ274XX_INIT(index)							\
	static struct bq274xx_data bq274xx_driver_##index;			\
										\
	static const struct bq274xx_config bq274xx_config_##index = {		\
		.i2c = I2C_DT_SPEC_INST_GET(index),				\
		BQ274XX_INT_CFG(index)						\
		.design_voltage = DT_INST_PROP(index, design_voltage),		\
		.design_capacity = DT_INST_PROP(index, design_capacity),	\
		.taper_current = DT_INST_PROP(index, taper_current),		\
		.terminate_voltage = DT_INST_PROP(index, terminate_voltage),	\
		.lazy_loading = DT_INST_PROP(index, zephyr_lazy_load),		\
	};									\
										\
	PM_DEVICE_DT_INST_DEFINE(index, bq274xx_pm_action);			\
										\
	SENSOR_DEVICE_DT_INST_DEFINE(index, &bq274xx_gauge_init,		\
			    PM_DEVICE_DT_INST_GET(index),			\
			    &bq274xx_driver_##index,				\
			    &bq274xx_config_##index, POST_KERNEL,		\
			    CONFIG_SENSOR_INIT_PRIORITY,			\
			    &bq274xx_battery_driver_api);

DT_INST_FOREACH_STATUS_OKAY(BQ274XX_INIT)


text:
import Ember from 'ember';
import $ from 'jquery';

const { computed, uuid } = Ember;

export default Ember.Component.extend({
  classNames: ['resize-handle'],

  column: null,

  eventNamespace: computed({
    get() {
      return `.rc${uuid()}`;
    }
  }),

  didInsertElement() {
    const eventNamespace = this.get('eventNamespace');
    const eventString = combineEventsWithNamespace(['mousedown', 'touchstart'], eventNamespace);

    this.$().on(eventString, this._onPointerDown.bind(this));
  },

  willDestroyElement() {
    const eventNamespace = this.get('eventNamespace');

    this.$().off(eventNamespace);
  },

  _onPointerDown(event) {
    // Ignore everything except left-click dragging
    if (event.which !== 1) {
      return;
    }

    this.startX = getPointerX(event);
    this.startWidth = this.get('column.width');

    const ownerDocument = $(this.element.ownerDocument);
    const eventNamespace = this.get('eventNamespace');

    const moveEventString = combineEventsWithNamespace(['mousemove', 'touchmove'], eventNamespace);
    const upEventString = combineEventsWithNamespace(['mouseup', 'touchend'], eventNamespace);

    ownerDocument.on(moveEventString, this._onPointerMove.bind(this));
    ownerDocument.on(upEventString, this._onPointerUp.bind(this));
  },

  _onPointerMove(event) {
    const minWidth = this.get('column.minWidth');
    let diff = getPointerX(event) - this.startX;
    let newWidth = this.startWidth + diff;
    if (newWidth < minWidth) {
      newWidth = minWidth;
    }

    this.get('column').set('width', newWidth);
    this.attrs.onColumnWidthChange();
  },

  _onPointerUp(/* event */) {
    const ownerDocument = $(this.element.ownerDocument);
    const eventNamespace = this.get('eventNamespace');
    const events = ['mouseup', 'touchend', 'mousemove', 'touchmove'];

    ownerDocument.off(combineEventsWithNamespace(events, eventNamespace));
  }
});

function getPointerX(event) {
  if (event.type.indexOf('touch') === 0) {
    return (event.originalEvent.touches[0] || event.originalEvent.changedTouches[0]).pageX;
  }

  return event.pageX;
}

function combineEventsWithNamespace(events, namespace) {
  let eventString = events.join(`${namespace} `);
  return `${eventString}${namespace}`;
}


text:
$: << File.dirname(__FILE__) + '/../config'
require 'environment'

class FogMachine
  class << self
    def sdb_servers
      Util.sdb_items(Config["worker_domain"]).inject({}) do |_, item|
        _[item.keys.first] = item.values.first

        _
      end
    end

    def clean_sdb
      usable_instance_ids = usable_servers.collect { |i| i[:aws_instance_id] }
      sdb_servers.keys.reject do |id|
        usable_instance_ids.include? id
      end.each do |inactive_id|
        sdb.delete_attributes Config["worker_domain"], inactive_id
      end
    end

    def servers
      server_metadata = sdb_servers

      servers = active_servers.collect do |data|
        Instance.new data, server_metadata[data[:aws_instance_id]]
      end

      InstanceArray.new(servers)
    end

    def active_servers
      ec2.describe_instances
    end

    def usable_servers
      active_servers.select { |i| i[:aws_state] == "running" || i[:aws_state] == "pending" }
    end

    def running_servers
      active_servers.select { |i| i[:aws_state] == "running" }
    end

    def recipe(name)
      rcp = Recipe.get(name)
      servers.active.with_profile(rcp.get_profile).run_command rcp.get_command
    end

    def recipes(*names)
      names.each { |name| recipe name }
    end

    def ec2
      RightAws::Ec2.new Config["access_key_id"],
        Config["secret_access_key"],
        :logger => logger
    end

    def sdb
      RightAws::SdbInterface.new Config["access_key_id"],
        Config["secret_access_key"],
        :multi_thread => true,
        :logger => logger
    end

    def logger
      Logger.new("/dev/null")
    end

    def launch(options = {})
      print "Cleaning out inactive instances... "
      clean_sdb
      puts "Done"

      options = {:count => 1}.merge options

      tag = options.delete :profile

      profile = Profile.get(tag).inject({}) do |_, (key, value)|
        _[key.to_sym] = value.first

        _
      end

      count = options.delete :count

      ami = profile.delete :ami

      user_data_filename = profile.delete(:user_data_filename)
      user_data = File.read(user_data_filename) if user_data_filename && !user_data_filename.empty?

      launch_options = profile.merge({:min_count => count, :max_count => count, :user_data => user_data})

      launch_options = launch_options.merge options

      response = ec2.launch_instances ami, launch_options

      response.each do |server|
        sdb.put_attributes Config["worker_domain"], server[:aws_instance_id], {'profile' => tag, 'started_at' => Time.now.to_i}
      end
    end
  end

  class InstanceArray < Array
    def active
      select &:active?
    end

    def with_profile(profile)
      select { |i| i.from_profile == profile }
    end

    def select
      self.class.new(super)
    end

    def run(command, concurrent = true)
      concurrent ? run_concurrently(command) : run_serially(command)
    end
    alias_method :run_command, :run

    def run_serially(command)
      map { |i| send_to_instance(i, command)}
    end

    def run_concurrently(command)
      map do |i|
        Thread.new do
          Thread.current[:result] = send_to_instance(i, command)
        end
      end.map{|t| t.join; t[:result] }
    end

    def silence_output
      @silence_output = true
    end

    def unsilence_output
      @silence_output = false
    end

    def silence_output?
      !!@silence_output
    end

    private
    def send_to_instance instance, command
      r = instance.run_command(command)
      puts r unless silence_output?
      r
    end
  end

  class Instance
    def initialize(data, metadata)
      @data, @metadata = data, metadata
    end

    def active?
      state == "running"
    end

    def metadata
      @metadata || {}
    end

    def method_missing(method, *args)
      @data[method] or @data[:"aws_#{method}"] or super
    end

    def id
      @data[:aws_instance_id]
    end

    def from_profile
      self['profile']
    end

    def run_command(command)
      puts "#{id} >> Running: #{command}"
      result = nil
      Net::SSH.start(dns_name, "root",
                     :keys => [keyfile],
                     :auth_methods => ['publickey']) do |ssh|
        result = ssh.exec!(command)
      end

      result = result.strip if result.respond_to?(:strip)
    end

    def keyfile
      file = File.join(Config['ssh_key_directory'], ssh_key_name + '.pem')
      raise "No keyfile exists at #{file.inspect}" unless File.exists? file
      file
    end

    def inspect
      "<FogMachine::Instance #{id}>"
    end

    def []=(key, val)
      FogMachine.sdb.put_attributes Config["worker_domain"], id, {key => val}
    end

    def [](key)
      (metadata[key] || []).first
    end

    def ssh_command
      "ssh -i #{keyfile} root@#{dns_name}"
    end

    def ssh!
      %x{osascript -e 'tell app "System Events" to set termOn to (exists process "Terminal")' -e 'set cmd to "#{ssh_command}"' -e 'if (termOn) then' -e 'tell app "Terminal" to do script cmd' -e 'else' -e 'tell app "Terminal" to do script cmd in front window' -e 'end if' -e 'tell app "Terminal" to activate'}
    end

    def shutdown
      FM::ec2.terminate_instances [id]
    end
  end

  class Profile < Hash
    attr_accessor :name

    def initialize(name, attrs = {})
      @name = name
      merge! attrs
    end

    def save
      self.class.save name, self
    end

    class << self
      def get(name)
        attrs = sdb.get_attributes(Config["profile_domain"], name)[:attributes]
        new name, attrs
      end

      def all
        Util.sdb_items(Config["profile_domain"]).map do |data|
          new data.keys.first, data.values.first
        end
      end

      def save(name, attrs)
        sdb.put_attributes Config["profile_domain"], name, attrs, true
      end

      def sdb
        FogMachine.sdb
      end
    end
  end
end

FM = FogMachine unless defined? FM


text:
package main

import (
	"bytes"
	"database/sql"
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"text/template"

	"github.com/bgentry/speakeasy"
	_ "github.com/go-sql-driver/mysql"
	"github.com/ttacon/chalk"
	"github.com/ttacon/pouch/pouch/defs"
	"golang.org/x/tools/imports"
)

var (
	// where to put the generated code
	targetPkg = flag.String("pkg", "", "package to inspect to")
	pkgName   = flag.String("pName", "", "pkg name for the generated files")

	// TODO(ttacon): dsn or individual parts?
	// for DB mode
	host     = flag.String("h", "", "db host to connect to")
	user     = flag.String("u", "", "user to connect to db as")
	password = flag.Bool("p", false, "use a password to authenticate user with")
	database = flag.String("db", "", "database to read tables from")
	fullDsn  = flag.String("dsn", "", "the uri to use to connect to the database")

	// modes
	// TODO(ttacon): more detailed, yet still succinct, usage message
	dbDiff       = flag.Bool("db-diff", false, "identify differences between db/code")
	codeMode     = flag.Bool("ff", false, "only use files as source")
	onlyCodeMode = flag.Bool("ff-dry-run", false, "dry run of created tables from structs")
	beastMode    = flag.Bool("beast-mode", false, "force create tables and code")

	// Prompts
	prompt     = chalk.Green.NewStyle().Style
	warning    = chalk.Yellow.NewStyle().Style
	errorP     = chalk.Red.NewStyle().Style
	dbgenPrmpt = chalk.Magenta.Color("[pouch]")

	// Other things we need...
	gopath = os.Getenv("GOPATH")
)

var (
	errorX  = errorP("✗")
	checkY2 = prompt("✔")
	checkY  = chalk.Green.Color("✔")
	// checkY2 does not give same output as checkY
)

func main() {
	flag.Parse()
	if len(os.Args) == 1 {
		flag.Usage()
		return
	}

	// a little varialble overriding
	*codeMode = *codeMode || *onlyCodeMode

	err := loadTemplates()
	if err != nil {
		fmt.Println(dbgenPrmpt, "failed to load templates: "+err.Error())
		return
	}

	if len(*targetPkg) == 0 {
		cwd, err := os.Getwd()
		if err != nil {
			fmt.Println(
				dbgenPrmpt,
				errorP("no target pkg provided + "+
					"failed to retrieve current directory"))
			return
		}
		*targetPkg = cwd
	} else {
		*targetPkg = filepath.Join(gopath, "src", *targetPkg)
	}

	var dirPkg = filepath.Base(*targetPkg)
	if len(*pkgName) > 0 {
		dirPkg = *pkgName
	}

	if *dbDiff {
		dbConn, err := getDBConn(*host, *user, *database, *password)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to connect to database: "+err.Error())
			return
		}
		dbEntities, err := generateStructsFrom(dbConn)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to generate structs from db: "+err.Error())
			os.Exit(1)
		}

		fileEntities, err := StructsFromFile(*targetPkg)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to retrieve structs: "+err.Error())
			os.Exit(1)
		}

		diffAndReport(dbEntities, fileEntities)
		return
	}

	var (
		structFileNeeded = false
		createTables     = true
		entities         []*defs.StructInfo
	)

	if dbInfoProvided(*host, *user, *database) && !*codeMode {
		fmt.Println(dbgenPrmpt, "running in db mode")
		// TODO(ttacon): add option for specific table(s) to be generated for
		dbConn, err := getDBConn(*host, *user, *database, *password)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to connect to database: "+err.Error())
			return
		}
		entities, err = generateStructsFrom(dbConn)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to generate structs: "+err.Error())
			os.Exit(1)
		}
		dbConn.Close()
		structFileNeeded = true
	} else {
		// we're reading from the file system
		entities, err = StructsFromFile(*targetPkg)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to retrieve structs: "+err.Error())
			os.Exit(1)
		}
		createTables = true
	}

	// check structs for field conflicts
	err = nameConflicts(entities)
	if err != nil {
		fmt.Println(dbgenPrmpt, errorP("name conflicts: "+err.Error()))
		os.Exit(1)
	}

	// file generation
	if structFileNeeded {
		fBytes, err := generateStructCode(entities)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to generate struct file, err:", err)
			return
		}

		fBuf := bytes.NewBufferString("package " + dirPkg + "\n\n")
		fBuf.WriteString(`
// THIS FILE IS GENERATED BY pouch.
// EDIT AT YOUR OWN PERIL.
`)
		fBuf.Write(fBytes)
		fBuf.WriteString("\n\n")

		fmt.Println(fBuf.String())
		process, err := imports.Process("", fBuf.Bytes(), nil)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to process imports for struct file:", err)
			return
		}

		fmt.Print(dbgenPrmpt, " writing file structs.pch.go: ")
		err = ioutil.WriteFile(
			filepath.Join(*targetPkg, "structs.pch.go"),
			process,
			os.FileMode(0744))
		if err != nil {
			fmt.Println(errorX)
			fmt.Println("err: ", err)
			return
		}
		fmt.Println(checkY)
	}

	// prompt user to create tables on db
	if createTables && dbInfoProvided(*user, *host, *database) {
		if len(entities) == 0 {
			fmt.Println(dbgenPrmpt, "no entities to create tables for")
			return
		}

		dbConn, err := getDBConn(*host, *user, *database, *password)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to connect to database: "+err.Error())
			return
		}

		dbEntities, err := generateStructsFrom(dbConn)
		if err != nil {
			fmt.Println(dbgenPrmpt, "failed to generate structs: "+err.Error())
			os.Exit(1)
		}

		woTable := diffContained(dbEntities, entities)
		if len(woTable) == 0 {
			fmt.Println(dbgenPrmpt, "all annotated structs have associated tables")
			if *onlyCodeMode {
				return
			}
		} else {
			if *onlyCodeMode {
				fmt.Println(dbgenPrmpt, "there are structs unknown to the db:")
				for i, wo := range woTable {
					fmt.Printf("\t[%d] %s\n", i+1, wo.Name)
				}
				fmt.Println(dbgenPrmpt, "(to force create, run in -beast-mode)")
				return
			}

			// TODO(ttacon): create tables from structs
			err = createTablesFn(dbConn, woTable)
			if err != nil {
				fmt.Println(dbgenPrmpt, errorP("failed to create tables"))
				os.Exit(1)
			}
		}
	}

	fmt.Print(dbgenPrmpt, " generating functions (functions.pch.go): ")
	funcCode, err := generateFunctions(entities)
	if err != nil {
		fmt.Println(errorX)
		fmt.Println("err: ", err)
		return
	}

	fBuf := bytes.NewBufferString("package " + dirPkg + "\n\n")
	fBuf.WriteString(`
// THIS FILE IS GENERATED BY pouch.
// EDIT AT YOUR OWN PERIL.
`)
	fBuf.Write(funcCode)
	fBuf.WriteString("\n\n")

	funcCode, err = imports.Process("", fBuf.Bytes(), nil)
	if err != nil {
		fmt.Println(errorX)
		fmt.Println("err: ", err)
		return
	}

	err = ioutil.WriteFile(
		filepath.Join(*targetPkg, "functions.pch.go"),
		funcCode,
		os.FileMode(0644))
	if err != nil {
		fmt.Println(errorX)
		fmt.Println("err: ", err)
		return
	}

	fmt.Println(checkY)
}

func dbInfoProvided(ss ...string) bool {
	for _, s := range ss {
		if len(s) > 0 {
			return true
		}
	}
	return false
}

func getDBConn(host, username, database string, passwordPrompt bool) (*sql.DB, error) {
	var (
		password string
		err      error
	)
	if passwordPrompt {
		password, err = speakeasy.Ask("Password: ")
		if err != nil {
			return nil, err
		}
	}

	return sql.Open("mysql",
		fmt.Sprintf("%s:%s@%s/%s?parseTime=true", username, password, host, database))
}

// templates
var (
	structTmplt                                  *template.Template
	identifiableT                                *template.Template
	insertableT, tableablT, findableT, gettableT *template.Template
)

func loadTemplates() error {
	var err error
	structTmplt, err = template.New("struct").Parse(structTemplate)
	if err != nil {
		return err
	}

	identifiableT, err = template.New("identifiable").Parse(identifiableTemplate)
	if err != nil {
		return err
	}

	insertableT, err = template.New("insertable").Parse(insertableTemplate)
	if err != nil {
		return err
	}

	tableablT, err = template.New("tableable").Parse(tableableTemplate)
	if err != nil {
		return err
	}

	findableT, err = template.New("findable").Parse(findableTemplate)
	if err != nil {
		return err
	}

	gettableT, err = template.New("gettable").Parse(gettableTemplate)
	if err != nil {
		return err
	}

	return nil
}

func nameConflicts(es []*defs.StructInfo) error {
	for _, e := range es {
		for _, field := range e.Fields {
			if _, ok := functionNames[field.Name]; ok {
				return errors.New(e.Name + "." + field.Name)
			}
		}
	}
	return nil
}

var functionNames = map[string]struct{}{
	"Table":              struct{}{},
	"FindableCopy":       struct{}{},
	"FieldsFor":          struct{}{},
	"InsertableFields":   struct{}{},
	"SetIdentifier":      struct{}{},
	"IdentifiableFields": struct{}{},
	"GetFieldsFor":       struct{}{},
	"GetAllFields":       struct{}{},
}

////////// templates for function generation //////////
////////// these will go in own file after we test them //////////
var structTemplate = `
type {{.Name}} struct { {{range $i, $v := .Fields}}
    {{$v.Name}} {{if $v.IsPointer}}*{{end}}{{$v.Type}}{{end}}
}
`

// Identifiable
var identifiableTemplate = `
func (i *{{.Name}}) IdentifiableFields() ([]string, []interface{}) {
    var (
        cols []string
        fields []interface{}
    ){{range $i, $v := .Fields}}{{if $v.IsPrimaryKey}}
    // adding primary key column/field pair {{$v.Name}}
    cols = append(cols, "{{$v.Column}}")
    fields = append(fields, i.{{$v.Name}}){{end}}{{end}}
    return cols, fields
}
`

// TODO(ttacon): do we need insertable fields??
// as in, do we need to differentiate "empty" or not?
// it seems like added complexity that isn't entirely necessary
// Insertable
var insertableTemplate = `
func (i *{{.Name}}) FieldsFor(fs []string) []interface{} {
    var fields = make([]interface{}, len(fs))

    for ii, f := range fs {
        switch f { {{range $i, $v := .Fields}}
        case "{{$v.Column}}":
            fields[ii] = &i.{{$v.Name}}{{end}}
        }
    }
    return fields
}

func (i *{{.Name}}) InsertableFields() ([]string, []interface{}) {
    return []string{ {{range $i, $v := .Fields}}
        "{{$v.Column}}",{{end}}
    }, []interface{}{ {{range $i, $v := .Fields}}
        i.{{$v.Name}},{{end}}
    }
}

func (i *{{.Name}}) SetIdentifier(d interface{}) error { {{if not .HasAutoGenIDField}}
    return nil
    {{else}}
    id, _ := d.(int64)
    i.{{.IDField}} = int(id)
    return nil
{{end}}}
`

// Tableable
var tableableTemplate = `
func (t *{{.Name}}) Table() string {
    return "{{.Table}}"
}
`

// Findable:FindableCopy
var findableTemplate = `
func (f *{{.Name}}) FindableCopy() pouch.Findable {
    return &{{.Name}}{}
}
`

// Gettable
var gettableTemplate = `
func (g *{{.Name}}) GetFieldsFor(fs []string) []interface{} {
    var fields = make([]interface{}, len(fs))

    for i, f := range fs {
        switch f { {{range $i, $v := .Fields}}
        case "{{$v.Column}}":
            fields[i] = &g.{{$v.Name}}{{end}}
        }
    }
    return fields
}

func (g *{{.Name}}) GetAllFields() ([]string, []interface{}) {
    var cols  = []string{ {{range $i, $v := .Fields}}
        "{{$v.Column}}",{{end}}
    }
    var fields = []interface{}{ {{range $i, $v := .Fields}}
        &g.{{$v.Name}},{{end}}
    }
    return cols, fields
}
`


text:
<?php
$queue = new SplPriorityQueue();
$queue->insert('foo', 1);
$queue->insert('bar', 3);
$queue->insert('baz', 0);

foreach ($queue as $value) {
  echo $value . PHP_EOL;
}
?>


text:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const releaseSchema = new Schema({
  master: {
    type: Schema.Types.ObjectId,
    ref: "Master"
  },
  releaseCountry: {
    type: String
  },
  releaseYear: {
    type: Number
  },
  reference: {
    type: String
  },
  ISBN: {
    type: String
  },
  releaseLanguage: {
    type: String
  },
  isTranslation: {
    type: Boolean
  },
  translator: {
    type: Schema.Types.ObjectId,
    ref: "Artist"
  },
  format: {
    type: String
  },
  coverType: {
    type: String
  },
  isFirstIssue: {
    type: Boolean,
    default: false
  },
  isCountryFirstIssue: {
    type: Boolean,
    default: false
  },
  image: {
    type: String
  },
  notes: {
    type: String
  },
  addedBy: {
    type: Schema.Types.ObjectId,
    ref: "User"
  },
  releasePublisher: {
    type: Schema.Types.ObjectId,
    ref: "Publisher"
  }
});

releaseSchema.set("timestamps", true);

module.exports = mongoose.model("Release", releaseSchema);


text:
from __future__ import absolute_import
from collections import namedtuple

__all__ = ['NamedRecord']

class NamedRecord(object):
    """
    namedtuple的封装, 增加字段类型的转换
    >>> Point = NamedRecord('Point', 'x y', {'x': float})
    >>> Point(x='1', y=1.0)
    Point(x=1.0, y=1.0)
    """
    def __init__(self, typename, field_names,
                 field_trans_func_d=None):
        self.record = namedtuple(typename, field_names)
        if field_trans_func_d is not None and \
                not isinstance(field_trans_func_d, dict):
            raise TypeError('{} is not a dict'.format(field_trans_func_d))
        self.field_trans_func_d = field_trans_func_d

    def __call__(self, *args, **kwargs):
        as_dict = kwargs.pop('as_dict', False)

        rd = self.record(*args, **kwargs)
        if self.field_trans_func_d is not None:
            _field_d = rd.__dict__.copy()
            for field, trans_func in self.field_trans_func_d.items():
                if callable(trans_func):
                    _field_d[field] = trans_func(_field_d[field])
            rd = self.record(**_field_d)
        return rd.__dict__.copy() if as_dict else rd

    def __repr__(self):
        return repr(self.record)


text:
package uk.ac.ucl.chime.tests;

import junit.framework.Test;
import junit.framework.TestSuite;

public class AllTests {

	public static Test suite() {
		TestSuite suite = new TestSuite("Test for uk.ac.ucl.chime.tests");
		//$JUnit-BEGIN$
		suite.addTestSuite(ObservationArchetypeWrapperTest.class);
		suite.addTestSuite(ObservationWrapperTest.class);
		suite.addTestSuite(CodedTextValueConstraintBindingWrapperTest.class);
		//$JUnit-END$
		return suite;
	}

}


text:
layout: organization
category: local

title: Autism Speaks L.I.
impact_area: Health
keywords:
location_services:
location_offices:
website: http://www.walknowforautismspeaks.org/longisland

description:
mission: |
  At Autism Speaks, our goal is to change the future for all who struggle with autism spectrum disorders.  We are dedicated to funding global biomedical research into the causes, prevention, treatments, and cure for autism; to raising public awareness about autism and its effects on individuals, families, and society; and to bringing hope to all who deal with the hardships of this disorder. We are committed to raising the funds necessary to support these goals.

cash_grants:
grants:
service_opp:
services:

learn:
cont_relationship:

salutation:
first_name:
last_name:
title_contact_person:

city: Huningston Station
state: NY
address: |
  380 Oakwood Drive
  Huningston Station NY 11746
lat: 40.815715
lng: -73.364729
phone: 631-521-7853
ext:
fax:
email:
preferred_contact:
contact_person_intro:
---


text:
<Nested />

<script>
  import Nested from './nested';

  export default {
    components: {
      Nested
    }
  };
</script>


text:
namespace ceres {
namespace internal {

LinearSolver::~LinearSolver() {
}

LinearSolverType LinearSolver::LinearSolverForZeroEBlocks(
    LinearSolverType linear_solver_type) {
  if (!IsSchurType(linear_solver_type)) {
    return linear_solver_type;
  }

  if (linear_solver_type == SPARSE_SCHUR) {
    return SPARSE_NORMAL_CHOLESKY;
  }

  if (linear_solver_type == DENSE_SCHUR) {
    // TODO(sameeragarwal): This is probably not a great choice.
    // Ideally, we should have a DENSE_NORMAL_CHOLESKY, that can take
    // a BlockSparseMatrix as input.
    return DENSE_QR;
  }

  if (linear_solver_type == ITERATIVE_SCHUR) {
    return CGNR;
  }

  return linear_solver_type;
}

LinearSolver* LinearSolver::Create(const LinearSolver::Options& options) {
  switch (options.type) {
    case CGNR:
      return new CgnrSolver(options);

    case SPARSE_NORMAL_CHOLESKY:
#if defined(CERES_NO_SUITESPARSE) &&              \
    defined(CERES_NO_CXSPARSE) &&                 \
   !defined(CERES_USE_EIGEN_SPARSE)
      return NULL;
#else
      return new SparseNormalCholeskySolver(options);
#endif

    case SPARSE_SCHUR:
#if defined(CERES_NO_SUITESPARSE) &&                 \
    defined(CERES_NO_CXSPARSE) &&                    \
   !defined(CERES_USE_EIGEN_SPARSE)
      return NULL;
#else
      return new SparseSchurComplementSolver(options);
#endif

    case DENSE_SCHUR:
      return new DenseSchurComplementSolver(options);

    case ITERATIVE_SCHUR:
      if (options.use_explicit_schur_complement) {
        return new SparseSchurComplementSolver(options);
      } else {
        return new IterativeSchurComplementSolver(options);
      }

    case DENSE_QR:
      return new DenseQRSolver(options);

    case DENSE_NORMAL_CHOLESKY:
      return new DenseNormalCholeskySolver(options);

    default:
      LOG(FATAL) << "Unknown linear solver type :"
                 << options.type;
      return NULL;  // MSVC doesn't understand that LOG(FATAL) never returns.
  }
}

}  // namespace internal
}  // namespace ceres


text:
package cz.metacentrum.perun.webgui.model;

import com.google.gwt.core.client.JavaScriptObject;

/**
 * Overlay type for registrar: ApplicationForm
 *
 * @author Vaclav Mach <374430@mail.muni.cz>
 */

public class ApplicationForm extends JavaScriptObject {

	protected ApplicationForm() {}

	/**
	 * Get ID
	 * @return id
	 */
	public final native int getId() /*-{
		return this.id;
	}-*/;

		/**
		 * Get {@link VirtualOrganization}
		 * @return VO
		 */
		public final native VirtualOrganization getVo() /*-{
			return this.vo;
		}-*/;

		/**
		 * Get {@link Group}
		 * @return VO
		 */
		public final native Group getGroup() /*-{
			return this.group;
		}-*/;

		/**
		 * Get automaticApproval for INITIAL app
		 * @return automaticApproval
		 */
		public final native boolean getAutomaticApproval() /*-{
			if (!this.automaticApproval) return false;
			return this.automaticApproval;
		}-*/;

		public final native String getModuleClassName() /*-{
			if (!this.moduleClassName) return "";
			return this.moduleClassName;
		}-*/;

		/**
		 * Get automaticApproval for EXTENSION
		 * @return automaticApproval
		 */
		public final native boolean getAutomaticApprovalExtension() /*-{
			if (!this.automaticApprovalExtension) return false;
			return this.automaticApprovalExtension;
		}-*/;

		/**
		 * Get automaticApproval for EMBEDDED
		 * @return automaticApproval
		 */
		public final native boolean getAutomaticApprovalEmbedded() /*-{
			if (!this.automaticApprovalEmbedded) return false;
			return this.automaticApprovalEmbedded;
		}-*/;

		/**
		 * Set automaticApproval
		 * @param automatic (true=automatic / false=manual)
		 */
		public final native void setAutomaticApproval(boolean automatic) /*-{
			this.automaticApproval = automatic;
		}-*/;

		/**
		 * Set automaticApprovalExtension
		 * @param automatic (true=automatic / false=manual)
		 */
		public final native void setAutomaticApprovalExtension(boolean automatic) /*-{
			this.automaticApprovalExtension = automatic;
		}-*/;

		/**
		 * Set automaticApprovalEmbedded
		 * @param automatic (true=automatic / false=manual)
		 */
		public final native void setAutomaticApprovalEmbedded(boolean automatic) /*-{
			this.automaticApprovalEmbedded = automatic;
		}-*/;

		public final native void setModuleClassName(String name) /*-{
			this.moduleClassName = name;
		}-*/;

		/**
		 * Returns Perun specific type of object
		 *
		 * @return type of object
		 */
		public final native String getObjectType() /*-{
			if (!this.beanName) {
			return "JavaScriptObject"
			}
			return this.beanName;
		}-*/;

		/**
		 * Sets Perun specific type of object
		 *
		 * @param type type of object
		 */
		public final native void setObjectType(String type) /*-{
			this.beanName = type;
		}-*/;

		/**
		 * Returns the status of this item in Perun system as String
		 * VALID, INVALID, EXPIRED, DISABLED
		 *
		 * @return string which defines item status
		 */
		public final native String getStatus() /*-{
			return this.status;
		}-*/;

		/**
		 * Compares to another object
		 * @param o  Object to compare
		 * @return true, if they are the same
		 */
		public final boolean equals(ApplicationForm o)
		{
			return o.getId() == this.getId();
		}
}


text:
import * as _ from 'lodash';
import * as L from './libs/leaflet';
import WorldmapCtrl from './worldmap_ctrl';

const tileServers = {
  'CartoDB Positron': {
    url: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png',
    attribution:
      '© OpenStreetMap ' +
      '© CartoDB',
    subdomains: 'abcd',
  },
  'CartoDB Dark': {
    url: 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png',
    attribution:
      '© OpenStreetMap ' +
      '© CartoDB',
    subdomains: 'abcd',
  },
};

export default class WorldMap {
  ctrl: WorldmapCtrl;
  mapContainer: any;
  circles: any[];
  map: any;
  legend: any;
  circlesLayer: any;

  constructor(ctrl, mapContainer) {
    this.ctrl = ctrl;
    this.mapContainer = mapContainer;
    this.circles = [];
  }

  createMap() {
    const mapCenter = (<any>window).L.latLng(
      parseFloat(this.ctrl.panel.mapCenterLatitude),
      parseFloat(this.ctrl.panel.mapCenterLongitude)
    );
    this.map = L.map(this.mapContainer, {
      worldCopyJump: true,
      preferCanvas: true,
      center: mapCenter,
      zoom: parseInt(this.ctrl.panel.initialZoom, 10) || 1,
    });
    this.setMouseWheelZoom();

    const selectedTileServer = tileServers[this.ctrl.tileServer];
    (<any>window).L.tileLayer(selectedTileServer.url, {
      maxZoom: 18,
      subdomains: selectedTileServer.subdomains,
      reuseTiles: true,
      detectRetina: true,
      attribution: selectedTileServer.attribution,
    }).addTo(this.map);
  }

  createLegend() {
    this.legend = (<any>window).L.control({ position: 'bottomleft' });
    this.legend.onAdd = () => {
      this.legend._div = (<any>window).L.DomUtil.create('div', 'info legend');
      this.legend.update();
      return this.legend._div;
    };

    this.legend.update = () => {
      const thresholds = this.ctrl.data.thresholds;
      let legendHtml = '';
      legendHtml +=
        '
 ' +
        '< ' +
        thresholds[0] +
        '
';
      for (let index = 0; index < thresholds.length; index += 1) {
        legendHtml +=
          '
 ' +
          thresholds[index] +
          (thresholds[index + 1] ? '–' + thresholds[index + 1] + '
' : '+');
      }
      this.legend._div.innerHTML = legendHtml;
    };
    this.legend.addTo(this.map);
  }

  needToRedrawCircles(data) {
    if (this.circles.length === 0 && data.length > 0) {
      return true;
    }

    if (this.circles.length !== data.length) {
      return true;
    }

    const locations = _.map(_.map(this.circles, 'options'), 'location').sort();
    const dataPoints = _.map(data, 'key').sort();
    return !_.isEqual(locations, dataPoints);
  }

  filterEmptyAndZeroValues(data) {
    return _.filter(data, o => {
      return !(this.ctrl.panel.hideEmpty && _.isNil(o.value)) && !(this.ctrl.panel.hideZero && o.value === 0);
    });
  }

  clearCircles() {
    if (this.circlesLayer) {
      this.circlesLayer.clearLayers();
      this.removeCircles();
      this.circles = [];
    }
  }

  drawCircles() {
    const data = this.filterEmptyAndZeroValues(this.ctrl.data);
    if (this.needToRedrawCircles(data)) {
      this.clearCircles();
      this.createCircles(data);
    } else {
      this.updateCircles(data);
    }
  }

  createCircles(data) {
    const circles: any[] = [];
    data.forEach(dataPoint => {
      if (!dataPoint.locationName) {
        return;
      }
      circles.push(this.createCircle(dataPoint));
    });
    this.circlesLayer = this.addCircles(circles);
    this.circles = circles;
  }

  updateCircles(data) {
    data.forEach(dataPoint => {
      if (!dataPoint.locationName) {
        return;
      }

      const circle = _.find(this.circles, cir => {
        return cir.options.location === dataPoint.key;
      });

      if (circle) {
        circle.setRadius(this.calcCircleSize(dataPoint.value || 0));
        circle.setStyle({
          color: this.getColor(dataPoint.value),
          fillColor: this.getColor(dataPoint.value),
          fillOpacity: 0.5,
          location: dataPoint.key,
        });
        circle.unbindPopup();
        this.createPopup(circle, dataPoint.locationName, dataPoint.valueRounded);
      }
    });
  }

  createCircle(dataPoint) {
    const circle = (<any>window).L.circleMarker([dataPoint.locationLatitude, dataPoint.locationLongitude], {
      radius: this.calcCircleSize(dataPoint.value || 0),
      color: this.getColor(dataPoint.value),
      fillColor: this.getColor(dataPoint.value),
      fillOpacity: 0.5,
      location: dataPoint.key,
    });

    this.createPopup(circle, dataPoint.locationName, dataPoint.valueRounded);
    return circle;
  }

  calcCircleSize(dataPointValue) {
    const circleMinSize = parseInt(this.ctrl.panel.circleMinSize, 10) || 2;
    const circleMaxSize = parseInt(this.ctrl.panel.circleMaxSize, 10) || 30;

    if (this.ctrl.data.valueRange === 0) {
      return circleMaxSize;
    }

    const dataFactor = (dataPointValue - this.ctrl.data.lowestValue) / this.ctrl.data.valueRange;
    const circleSizeRange = circleMaxSize - circleMinSize;

    return circleSizeRange * dataFactor + circleMinSize;
  }

  createPopup(circle, locationName, value) {
    const unit = value && value === 1 ? this.ctrl.panel.unitSingular : this.ctrl.panel.unitPlural;
    const label = (locationName + ': ' + value + ' ' + (unit || '')).trim();
    circle.bindPopup(label, {
      offset: (<any>window).L.point(0, -2),
      className: 'worldmap-popup',
      closeButton: this.ctrl.panel.stickyLabels,
    });

    circle.on('mouseover', function onMouseOver(evt) {
      const layer = evt.target;
      layer.bringToFront();
      this.openPopup();
    });

    if (!this.ctrl.panel.stickyLabels) {
      circle.on('mouseout', function onMouseOut() {
        circle.closePopup();
      });
    }
  }

  getColor(value) {
    for (let index = this.ctrl.data.thresholds.length; index > 0; index -= 1) {
      if (value >= this.ctrl.data.thresholds[index - 1]) {
        return this.ctrl.panel.colors[index];
      }
    }
    return _.first(this.ctrl.panel.colors);
  }

  resize() {
    this.map.invalidateSize();
  }

  panToMapCenter() {
    this.map.panTo([parseFloat(this.ctrl.panel.mapCenterLatitude), parseFloat(this.ctrl.panel.mapCenterLongitude)]);
    this.ctrl.mapCenterMoved = false;
  }

  removeLegend() {
    this.legend.remove(this.map);
    this.legend = null;
  }

  setMouseWheelZoom() {
    if (!this.ctrl.panel.mouseWheelZoom) {
      this.map.scrollWheelZoom.disable();
    } else {
      this.map.scrollWheelZoom.enable();
    }
  }

  addCircles(circles) {
    return (<any>window).L.layerGroup(circles).addTo(this.map);
  }

  removeCircles() {
    this.map.removeLayer(this.circlesLayer);
  }

  setZoom(zoomFactor) {
    this.map.setZoom(parseInt(zoomFactor, 10));
  }

  remove() {
    this.circles = [];
    if (this.circlesLayer) {
      this.removeCircles();
    }
    if (this.legend) {
      this.removeLegend();
    }
    this.map.remove();
  }
}