text:
package com.dytech.gui.filter;

import com.dytech.gui.TableLayout;
import com.tle.common.gui.models.GenericListModel;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;

public class FilteredShuffleList<T> extends JComponent implements ActionListener {
  private FilterModel<T> filterModel;
  private String title;

  private JButton search;
  private JButton remove;
  private JList list;
  private GenericListModel<T> model;
  private JScrollPane scroller;
  private Comparator<? super T> sorter;

  public FilteredShuffleList(String title, FilterModel<T> filterModel) {
    this(title, filterModel, null);
  }

  public FilteredShuffleList(
      String title, FilterModel<T> filterModel, Comparator<? super T> sorter) {
    this.title = title;
    this.filterModel = filterModel;
    this.sorter = sorter;

    createGUI();
  }

  public GenericListModel<T> getModel() {
    return model;
  }

  public void setListCellRenderer(ListCellRenderer lcr) {
    list.setCellRenderer(lcr);
  }

  @Override
  public void setEnabled(boolean b) {
    search.setEnabled(b);
    remove.setEnabled(b);
    list.setEnabled(b);
    scroller.setEnabled(b);
  }

  public void addItem(T item) {
    model.add(item);
    ensureSort();
  }

  public void addItems(T[] items) {
    for (T item : items) {
      model.add(item);
    }
    ensureSort();
  }

  public void addItems(Collection<T> items) {
    model.addAll(items);
    ensureSort();
  }

  public boolean removeItem(T item) {
    return model.remove(item);
  }

  public void removeItemAt(int index) {
    model.remove(index);
  }

  public void removeAllItems() {
    model.clear();
  }

  public int getItemCount() {
    return model.getSize();
  }

  public Object getItemAt(int index) {
    return model.get(index);
  }

  public java.util.List<T> getItems() {
    return model;
  }

  private void createGUI() {
    search = new JButton("Search...");
    remove = new JButton("Remove");

    remove.addActionListener(this);
    search.addActionListener(this);

    model = new GenericListModel<T>();
    list = new JList(model);
    scroller = new JScrollPane(list);

    final int width = search.getPreferredSize().width;
    final int height = search.getPreferredSize().height;
    final int[] rows = new int[] {height, height, TableLayout.FILL};
    final int[] cols = new int[] {width, TableLayout.FILL};

    setLayout(new TableLayout(rows, cols, 5, 5));

    add(search, new Rectangle(0, 0, 1, 1));
    add(remove, new Rectangle(0, 1, 1, 1));
    add(scroller, new Rectangle(1, 0, 1, 3));
  }

  public void setSearchText(String text) {
    search.setText(text);
  }

  public void setRemoveText(String text) {
    remove.setText(text);
  }

  /*
   * (non-Javadoc)
   * @see
   * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
   */
  @Override
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == search) {
      filterModel.setExclusion(getItems());

      FilterDialog<T> dialog = new FilterDialog<T>(title, filterModel);
      dialog.setListCellRenderer(list.getCellRenderer());
      List<T> results = dialog.showDialog(this);
      if (results != null) {
        addItems(results);
      }
    } else if (e.getSource() == remove) {
      if (!list.isSelectionEmpty()) {
        final int[] indices = list.getSelectedIndices();
        for (int i = indices.length - 1; i >= 0; i--) {
          removeItemAt(indices[i]);
        }
        list.updateUI();
      }
    }
  }

  private void ensureSort() {
    if (sorter != null) {
      Collections.sort(model, sorter);
    }
  }
}


text:
React Trigger Component

[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![gemnasium deps][gemnasium-image]][gemnasium-url]
[![npm download][download-image]][download-url]

[npm-image]: http://img.shields.io/npm/v/rc-trigger.svg?style=flat-square
[npm-url]: http://npmjs.org/package/rc-trigger
[travis-image]: https://img.shields.io/travis/react-component/trigger.svg?style=flat-square
[travis-url]: https://travis-ci.org/react-component/trigger
[coveralls-image]: https://img.shields.io/coveralls/react-component/trigger.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/react-component/trigger?branch=master
[gemnasium-image]: http://img.shields.io/gemnasium/react-component/trigger.svg?style=flat-square
[gemnasium-url]: https://gemnasium.com/react-component/trigger
[node-image]: https://img.shields.io/badge/node.js-%3E=_0.10-green.svg?style=flat-square
[node-url]: http://nodejs.org/download/
[download-image]: https://img.shields.io/npm/dm/rc-trigger.svg?style=flat-square
[download-url]: https://npmjs.org/package/rc-trigger

## Browser Support

|![IE](https://raw.github.com/alrra/browser-logos/master/internet-explorer/internet-explorer_48x48.png) | ![Chrome](https://raw.github.com/alrra/browser-logos/master/chrome/chrome_48x48.png) | ![Firefox](https://raw.github.com/alrra/browser-logos/master/firefox/firefox_48x48.png) | ![Opera](https://raw.github.com/alrra/browser-logos/master/opera/opera_48x48.png) | ![Safari](https://raw.github.com/alrra/browser-logos/master/safari/safari_48x48.png)|
| --- | --- | --- | --- | --- |
| IE 8+ ✔ | Chrome 31.0+ ✔ | Firefox 31.0+ ✔ | Opera 30.0+ ✔ | Safari 7.0+ ✔ |

## Development

```
npm install
npm start
```

## Example

http://localhost:8200/examples/

online example: http://react-component.github.io/trigger/examples/

## Feature

* support ie8,ie8+,chrome,firefox,safari

## install

[![rc-trigger](https://nodei.co/npm/rc-trigger.png)](https://npmjs.org/package/rc-trigger)

## Usage

```js
import React from 'react';
import ReactDOM from 'react-dom';
import Trigger from 'rc-trigger';

ReactDOM.render((
  <Trigger
    action={['click']}
    popup={<span>popup</span>}
    popupAlign={{
      points: ['tl', 'bl'],
      offset: [0, 3]
    }}
  >
    <a href='#'>hover</a>
  </Trigger>
), container);
```

## API

### props

        name
        type
        default
        description

          popupClassName
          string

          additional className added to popup

          destroyPopupOnHide
          boolean
          false
          whether destroy popup when hide

          getPopupClassNameFromAlign
          getPopupClassNameFromAlign(align: Object):String

          additional className added to popup according to align

          action
          string[]
          ['hover']
          which actions cause popup shown. enum of 'hover','click','focus'

          mouseEnterDelay
          number
          0
          delay time to show when mouse enter. unit: s.

          mouseLeaveDelay
          number
          0.1
          delay time to hide when mouse leave. unit: s.

          popupStyle
          Object

          additional style of popup

          prefixCls
          String
          rc-trigger-popup
          prefix class name

          popupTransitionName
          String

          https://github.com/react-component/animate

          maskTransitionName
          String

          https://github.com/react-component/animate

          onPopupVisibleChange
          Function

          call when popup visible is changed

          mask
          boolean
          false
          whether to support mask

          maskClosable
          boolean
          true
          whether to support click mask to hide

          popupVisible
          boolean

          whether popup is visible

          zIndex
          number

          popup's zIndex

          defaultPopupVisible
          boolean

          whether popup is visible initially

          popupAlign
          Object: alignConfig of [dom-align](https://github.com/yiminghe/dom-align)

          popup 's align config

          onPopupAlign
          function(popupDomNode, align)

          callback when popup node is aligned

          popup
          React.Element | function() => React.Element

          popup content

          getPopupContainer
          getPopupContainer(): HTMLElement

          function returning html node which will act as popup container

          popupPlacement
          string

          use preset popup align config from builtinPlacements, can be merged by popupAlign prop

          builtinPlacements
          object

          builtin placement align map. used by placement prop

## Test Case

```
npm test
npm run chrome-test
```

## Coverage

```
npm run coverage
```

open coverage/ dir

## License

rc-trigger is released under the MIT license.

redpajama_set_name: RedPajamaGithub


text:
{% extends "nexus/admin/base_site.html" %}
{% load url from future %}
{% load i18n admin_modify adminmedia %}
{% load nexus_admin %}

{% block head %}
    {{ block.super }}
    {% url 'admin:jsi18n' as jsi18nurl %}

    <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/widgets.css" />
    {{ media }}
{% endblock %}

{% if not is_popup %}
    {% block breadcrumb_bits %}

{% trans "Model Admin" %}

{{ app_label|capfirst|escape }}

            {% if has_change_permission %}
                {{ opts.verbose_name_plural|capfirst }}
            {% else %}
                {{ opts.verbose_name_plural|capfirst }}
            {% endif %}

            {% if add %}
                {% trans "Add" %} {{ opts.verbose_name }}
            {% else %}
                {{ original|truncatewords:"18" }}
            {% endif %}

    {% endblock %}
{% endif %}

{% block content %}
    {% block object-tools %}
    {% if change and not is_popup %}

{% trans "History" %}

            {% if has_absolute_url %}

{% trans "View on site" %}

            {% endif%}

    {% endif %}
    {% endblock %}
    <form {% if has_file_field %}enctype="multipart/form-data" {% endif %}action="{{ form_url }}" method="post" id="{{ opts.module_name }}_form">{% csrf_token %}{% block form_top %}{% endblock %}

    {% if is_popup %}<input type="hidden" name="_popup" value="1" />{% endif %}
    {% if save_on_top %}{% submit_row %}{% endif %}
    {% if errors %}

        {% blocktrans count errors|length as counter %}Please correct the error below.{% plural %}Please correct the errors below.{% endblocktrans %}

        {{ adminform.form.non_field_errors }}
    {% endif %}

    {% for fieldset in adminform %}
      {% include "admin/includes/fieldset.html" %}
    {% endfor %}

    {% block after_field_sets %}{% endblock %}

    {% for inline_admin_formset in inline_admin_formsets %}
        {% include inline_admin_formset.opts.template %}
    {% endfor %}

    {% block after_related_objects %}{% endblock %}

    {% submit_row %}

    {% if adminform and add %}

    {% endif %}

    {# JavaScript for prepopulated fields #}
    {% prepopulated_fields_js %}

    </form>
{% endblock %}


text:
QImageLuminanceSource::QImageLuminanceSource(QImage& _image) : LuminanceSource(_image.width(), _image.height())
{
    image = _image.copy();
}

ArrayRef<char> QImageLuminanceSource::getRow(int y, ArrayRef<char> _row) const
{
    for (int x = 0; x < this->getWidth(); x++)
        _row[x] = qGray(image.pixel(x, y));
    return _row;
}

ArrayRef<char> QImageLuminanceSource::getMatrix() const
{
    ArrayRef<char> mymatrix(width*height);
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++) {
            mymatrix[y*width+x] = qGray(image.pixel(x, y));
        }
    }
    return mymatrix;
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Kay
 * Date: 18.10.2015
 * Time: 11:00
 */

namespace AppBundle\BattleCalculator;

use AppBundle\BattleCalculator\Unit\AirUnit;
use AppBundle\BattleCalculator\Unit\Destroyer;
use AppBundle\BattleCalculator\Unit\Submarine;
use Symfony\Bridge\Monolog\Logger;

use AppBundle\BattleCalculator\Unit\Unit;

class Defender extends Side
{

    /**
     * @param Unit[] $units
     * @param Battle $battle
     * @param Logger $logger
     */
    function __construct($units, Battle $battle, Logger $logger = null)
    {
        $this->logger = $logger;
        $this->battle = $battle;
        $this->units = $units;
        foreach($this->units as $unit)
            $unit->setSide($this);

        $this->createUnitsByTypeAndTag();
    }

    /**
     *
     */
    public function removeCasualties()
    {
        if($this->logger)
            $this->logger->info('cleaning up defenders casualties', ['casualties' => count($this->casualties)]);

        if(count($this->casualties) > 0) {
            foreach($this->casualties as $casualty) {
                $this->removeUnit($casualty);
                $this->addLostUnit($casualty);
                $this->removeCasualty($casualty);
            }
        }

        $this->createUnitsByTypeAndTag();
    }

    /**
     *
     */
    public function orderUnits() {
        $this->orderUnitsByDefense();

        if($this->battle->getCalculator()->getSettings()->getKeepDestroyers()) {
            if(count($this->battle->getAttacker()->getUnitsByType(Submarine::class)) > 0) {
                foreach($this->units as $i => $unit) {
                    if($unit instanceof Destroyer) {
                        unset($this->units[$i]);
                        $this->units[] = $unit;
                        break;
                    }
                }
            }
        }

        if($this->logger)
            $this->logger->info('ordering defender units', [array_map(function(Unit $unit) {
                return $unit->getName() . ' (' . $unit->getDefense() . ')';
            }, $this->units)]);
    }

    /**
     * @return mixed
     */
    private function orderUnitsByDefense() {
        usort( $this->units, function(Unit $a, Unit $b) {
            if($a->hasTag('chosen_last') === $b->hasTag('chosen_last')) {
                if ($a->getHitPoints() === $b->getHitPoints()) {
                    if ($a->getDefense() === $b->getDefense()) {
                        return $a->getCost() - $b->getCost();
                    }
                    return $a->getDefense() - $b->getDefense();
                }
                return $b->getHitPoints() - $a->getHitPoints();
            }
            return $a->hasTag('chosen_last')? +1 : -1;
        });
    }

    /**
     * @return number
     */
    public function getCombatPower()
    {
        return array_sum(
            array_map(
                function(Unit $unit) {
                    return $unit->getDefense();
                }, $this->units
            )
        );
    }
}


text:
package org.aika.network;

import org.aika.Input;
import org.aika.Model;
import org.aika.Neuron;
import org.aika.corpus.Document;
import org.aika.corpus.Range;
import org.aika.corpus.Range.Operator;
import org.aika.lattice.AndNode;
import org.junit.Assert;
import org.junit.Test;

/**
 *
 * @author Lukas Molzberger
 */
public class ConcurrencyTest {

    @Test
    public void testMultipleDocuments() {
        Model m = new Model(null, 8);
        AndNode.minFrequency = 1;

        Neuron inA = m.createNeuron("A");
        Neuron inB = m.createNeuron("B");

        Neuron pC = m.initNeuron(m.createNeuron("pC"),
                0.001,
                new Input()
                        .setNeuron(inA)
                        .setWeight(1.0f)
                        .setRelativeRid(0)
                        .setRecurrent(false)
                        .setBiasDelta(1.0)
                        .setStartRangeMatch(Operator.EQUALS)
                        .setStartRangeOutput(true),
                new Input()
                        .setNeuron(inB)
                        .setWeight(1.0f)
                        .setRelativeRid(0)
                        .setRecurrent(false)
                        .setBiasDelta(1.0)
                        .setEndRangeMatch(Operator.EQUALS)
                        .setEndRangeOutput(true)
        );

        Neuron inStart = m.createNeuron("START");
        Neuron inClock = m.createNeuron("CLOCK");

        Neuron ctn = m.initCounterNeuron(m.createNeuron("CTN"), inClock, false, inStart, true, false);

        Document doc0 = m.createDocument("aaaaaaaaaa", 0);
        Document doc1 = m.createDocument("bbbbbbbbbb", 1);
        Document doc2 = m.createDocument("cccccccccc", 2);
        Document doc3 = m.createDocument("dddddddddd", 3);
        Document doc4 = m.createDocument("eeeeeeeeee", 4);

        inA.addInput(doc2, 0, 4);
        inB.addInput(doc2, 2, 6);

        Assert.assertEquals(1, pC.get().node.get().getActivations(doc2).size());

        inA.addInput(doc4, 0, 6);

        Assert.assertEquals(0, pC.get().node.get().getActivations(doc4).size());

        inB.addInput(doc0, 4, 8);
        inB.addInput(doc4, 2, 8);

        Assert.assertEquals(1, pC.get().node.get().getActivations(doc4).size());

        inA.addInput(doc0, 0, 6);

        inStart.addInput(doc3, 0, 1);
        inClock.addInput(doc3, 4, 5);
        inClock.addInput(doc3, 6, 7);

        Assert.assertEquals(2, ctn.get().node.get().getThreadState(doc3.threadId, true).activations.size());

        inStart.addInput(doc1, 0, 1);
        inClock.addInput(doc1, 3, 4);
        inClock.addInput(doc1, 7, 8);

        Assert.assertEquals(2, ctn.get().node.get().getThreadState(doc1.threadId, true).activations.size());
        Assert.assertEquals(2, ctn.get().node.get().getActivations(doc1).size());

        Assert.assertEquals(1, pC.get().node.get().getActivations(doc2).size());

        inA.removeInput(doc2, 0, 4);

        Assert.assertEquals(0, pC.get().node.get().getActivations(doc2).size());

        Assert.assertEquals(2, ctn.get().node.get().getThreadState(doc3.threadId, true).activations.size());
    }

    @Test
    public void testMultithreading() {
        final Model m = new Model();
        AndNode.minFrequency = 1;

        final Neuron inA = m.createNeuron("A");
        final Neuron inB = m.createNeuron("B");

        final Neuron pC = m.initNeuron(m.createNeuron("pC"),
                0.001,
                new Input()
                        .setNeuron(inA)
                        .setWeight(1.0f)
                        .setRelativeRid(0)
                        .setRecurrent(false)
                        .setBiasDelta(1.0)
                        .setStartRangeMatch(Operator.EQUALS)
                        .setStartRangeOutput(true),
                new Input()
                        .setNeuron(inB)
                        .setWeight(1.0f)
                        .setRelativeRid(0)
                        .setRecurrent(false)
                        .setBiasDelta(1.0)
                        .setEndRangeMatch(Operator.EQUALS)
                        .setEndRangeOutput(true)
        );

        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int j = 0; j < 20; j++) {
                        Document doc = m.createDocument("          ", 0);

                        inA.addInput(doc, 0, 6);
                        inB.addInput(doc, 4, 10);

                        Assert.assertEquals(1, pC.get().node.get().getActivations(doc).size());
                        Assert.assertNotNull(TestHelper.get(doc, pC.get().node.get(), new Range(4, 6), null));

                        inB.removeInput(doc, 4, 10);
                        Assert.assertEquals(0, pC.get().node.get().getActivations(doc).size());

                        doc.clearActivations();

                        Assert.assertEquals(0, inA.get().node.get().getActivations(doc).size());
                    }
                }
            }).run();
        }
    }
}


text:
use tipb::FieldType;

use crate::interface::*;
use tidb_query_common::storage::IntervalRange;
use tidb_query_datatype::codec::batch::LazyBatchColumnVec;
use tidb_query_datatype::codec::data_type::VectorValue;
use tidb_query_datatype::expr::EvalWarnings;

/// A simple mock executor that will return batch data according to a fixture without any
/// modification.
///
/// Normally this should be only used in tests.
pub struct MockExecutor {
    schema: Vec<FieldType>,
    results: std::vec::IntoIter<BatchExecuteResult>,
}

impl MockExecutor {
    pub fn new(schema: Vec<FieldType>, results: Vec<BatchExecuteResult>) -> Self {
        assert!(!results.is_empty());
        Self {
            schema,
            results: results.into_iter(),
        }
    }
}

impl BatchExecutor for MockExecutor {
    type StorageStats = ();

    fn schema(&self) -> &[FieldType] {
        &self.schema
    }

    fn next_batch(&mut self, _scan_rows: usize) -> BatchExecuteResult {
        self.results.next().unwrap()
    }

    fn collect_exec_stats(&mut self, _dest: &mut ExecuteStats) {
        // Do nothing
    }

    fn collect_storage_stats(&mut self, _dest: &mut Self::StorageStats) {
        // Do nothing
    }

    fn take_scanned_range(&mut self) -> IntervalRange {
        // Do nothing
        unreachable!()
    }

    fn can_be_cached(&self) -> bool {
        false
    }
}

pub struct MockScanExecutor {
    pub rows: Vec<i64>,
    pub pos: usize,
    schema: Vec<FieldType>,
}

impl MockScanExecutor {
    pub fn new(rows: Vec<i64>, schema: Vec<FieldType>) -> Self {
        MockScanExecutor {
            rows,
            pos: 0,
            schema,
        }
    }
}

impl BatchExecutor for MockScanExecutor {
    type StorageStats = ();

    fn schema(&self) -> &[FieldType] {
        &self.schema
    }

    fn next_batch(&mut self, scan_rows: usize) -> BatchExecuteResult {
        let real_scan_rows = std::cmp::min(scan_rows, self.rows.len());
        // just one column
        let mut res_col = Vec::new();
        let mut res_logical_rows = Vec::new();
        let mut cur_row_idx = 0;
        while self.pos < self.rows.len() && cur_row_idx < real_scan_rows {
            res_col.push(Some(self.rows[self.pos]));
            res_logical_rows.push(cur_row_idx);
            self.pos += 1;
            cur_row_idx += 1;
        }
        let is_drained = self.pos >= self.rows.len();
        BatchExecuteResult {
            physical_columns: LazyBatchColumnVec::from(vec![VectorValue::Int(res_col.into())]),
            logical_rows: res_logical_rows,
            warnings: EvalWarnings::default(),
            is_drained: Ok(is_drained),
        }
    }

    fn collect_exec_stats(&mut self, _dest: &mut ExecuteStats) {
        // Do nothing
    }

    fn collect_storage_stats(&mut self, _dest: &mut Self::StorageStats) {
        // Do nothing
    }

    fn take_scanned_range(&mut self) -> IntervalRange {
        // Do nothing
        unreachable!()
    }

    fn can_be_cached(&self) -> bool {
        false
    }
}


text:
var path = require('path');
var os = require('os');
var fs = require('fs');
var qs = require('querystring');

process.stdout.on('error', function () {});

var argv = require('minimist')(process.argv.slice(2));
if (argv.h || argv.help || argv._[0] === 'help') return help();

var lport = argv.localport || argv.l || 41963;
var port = argv.port || argv.p || 4026;

var home = process.env.HOME || process.env.USERPROFILE;
var dbfile = argv.db || path.join(home, '.config', 'cypher-feed', 'data');

var mkdirp = require('mkdirp');
mkdirp.sync(dbfile);

var hyperquest = require('hyperquest');
var defined = require('defined');

var cmd = argv._[0];

if (cmd === 'start') {
    var level = require('level');
    var sublevel = require('level-sublevel');
    var db = sublevel(level(dbfile, { encoding: 'json' }));
    var feed = require('../')(db);
    //feed.join();

    var local = feed.createLocalServer();
    local.listen(lport, '127.0.0.1');
    console.log('local server listening on 127.0.0.1:' + lport);

    var server = feed.createServer();
    server.listen(port);
    console.log('public server listening on 0.0.0.0:' + port);
}
else if (cmd === 'publish') {
    var file = argv._[1];
    if (!file) {
        console.error('usage: cypher-feed publish FILE');
        return process.exit(1);
    }

    var encoding = argv.encoding || argv.e;
    if (argv.json) encoding = 'json';
    if (!encoding && /\.json/.test(file)) encoding = 'json';
    if (!encoding) encoding = 'utf8';

    var type = argv.type || argv.t || 'file';

    var u = 'http://localhost:' + lport + '/publish?';
    var hq = hyperquest.put(u + qs.stringify({
        encoding: encoding,
        raw: Boolean(argv.raw || argv.r),
        type: type,
        filename: defined(argv.filename, argv.f, path.basename(file))
    }));
    hq.pipe(process.stdout);

    fs.createReadStream(file).pipe(hq);
}
else if (cmd === 'list' || cmd === 'query') {
    var u = 'http://localhost:' + lport + '/query?';
    hyperquest(u + qs.stringify(argv)).pipe(process.stdout);
}
else if (cmd === 'connect') {
    var u = 'http://localhost:' + lport + '/connect?';
    var addr = argv._[1];
    var hq = hyperquest(u + qs.stringify({ addr: addr }));
    hq.pipe(process.stdout);
}
else help()

function help () {
    fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout);
}


text:
namespace Spect.Net.SpectrumEmu.Abstraction.Providers
{
    /// <summary>
    /// This interface represents a provider that emulates Kempston joystick
    /// </summary>
    public interface IKempstonProvider: IVmComponentProvider
    {
        /// <summary>
        /// Indicates if the Kempston device is present.
        /// </summary>
        bool IsPresent { get; }

        /// <summary>
        /// The flag that indicates if the left button is pressed.
        /// </summary>
        bool LeftPressed { get; }

        /// <summary>
        /// The flag that indicates if the right button is pressed.
        /// </summary>
        bool RightPressed { get; }

        /// <summary>
        /// The flag that indicates if the up button is pressed.
        /// </summary>
        bool UpPressed { get; }

        /// <summary>
        /// The flag that indicates if the down button is pressed.
        /// </summary>
        bool DownPressed { get; }

        /// <summary>
        /// The flag that indicates if the fire button is pressed.
        /// </summary>
        bool FirePressed { get; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Text;
using wojilu.Web.Mvc;
using wojilu.Web.Mvc.Attr;
using wojilu.Apps.Download.Domain;
using wojilu.Web.Controller.Common;

namespace wojilu.Web.Controller.Download {

    [App( typeof( DownloadApp ) )]
    public class DownloadController : ControllerBase {

        public void Index() {

            WebUtils.pageTitle( this, "资源下载" );

            load( "sidebar", sidebar );

            String key = strUtil.SqlClean( ctx.Get( "q" ), 10 );
            set( "key", key );

            DataPage<FileItem> list = FileItem.GetPage( ctx.app.Id, key );
            ctx.SetItem( "list", list );
            load( "list", new CategoryController().List );
        }

        [NonVisit]
        public void sidebar() {

            List<FileCategory> cats = FileCategory.GetRootList();
            bindCats( cats );

        }

        private void bindCats( List<FileCategory> cats ) {
            IBlock block = getBlock( "cat" );
            foreach (FileCategory cat in cats) {

                block.Set( "cat.Name", cat.Name );
                block.Set( "cat.Link", to( new CategoryController().Show, cat.Id ) );

                bindSubCats( block, cat );

                block.Next();
            }
        }

        private void bindSubCats( IBlock block, FileCategory cat ) {
            IBlock subBlock = block.GetBlock( "subcat" );
            List<FileCategory> subcats = FileCategory.GetByParentId( cat.Id );
            foreach (FileCategory subcat in subcats) {

                subBlock.Set( "subcat.Name", subcat.Name );
                subBlock.Set( "subcat.Link", to( new CategoryController().Show, subcat.Id ) );
                subBlock.Next();

            }
        }

    }

}


text:
cask "qiyimedia" do
  version "20201215,11.12.0"
  sha256 :no_check

  url "https://mbdapp.iqiyi.com/j/ot/iQIYIMedia_271.dmg"
  appcast "https://macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://mbdapp.iqiyi.com/j/ot/iQIYIMedia_271.dmg",
          must_contain: version.before_comma
  name "iQIYI"
  name "爱奇艺视频"
  desc "Interactive media player"
  homepage "https://app.iqiyi.com/mac/player/index.html"

  depends_on macos: ">= :catalina"

  app "爱奇艺.app"

  zap trash: [
    "~/Library/Application Scripts/com.iqiyi.player",
    "~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/com.iqiyi.player.sfl*",
    "~/Library/Containers/com.iqiyi.player",
  ]
end


text:
set -e

CROMWELL_DIR=$1
cd $CROMWELL_DIR
sbt 'set test in assembly := {}' notests:assembly
CROMWELL_JAR=$(find target | grep 'cromwell.*\.jar')
mv $CROMWELL_JAR ./cromwell.jar
sbt clean


text:
package org.apache.hadoop.hdfs.server.federation.router;

import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ROUTER_HEARTBEAT_INTERVAL_MS;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_ROUTER_HEARTBEAT_INTERVAL_MS_DEFAULT;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Map;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.ha.HAServiceProtocol;
import org.apache.hadoop.ha.HAServiceStatus;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.NameNodeProxies;
import org.apache.hadoop.hdfs.protocol.ClientProtocol;
import org.apache.hadoop.hdfs.protocol.HdfsConstants.SafeModeAction;
import org.apache.hadoop.hdfs.server.federation.resolver.ActiveNamenodeResolver;
import org.apache.hadoop.hdfs.server.federation.resolver.NamenodeStatusReport;
import org.apache.hadoop.hdfs.server.protocol.NamenodeProtocol;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
import org.apache.hadoop.hdfs.tools.NNHAServiceTarget;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The {@link Router} periodically checks the state of a Namenode (usually on
 * the same server) and reports their high availability (HA) state and
 * load/space status to the
 * {@link org.apache.hadoop.hdfs.server.federation.store.StateStoreService}
 * . Note that this is an optional role as a Router can be independent of any
 * subcluster.
 *

 * For performance with Namenode HA, the Router uses the high availability state
 * information in the State Store to forward the request to the Namenode that is
 * most likely to be active.
 *

 * Note that this service can be embedded into the Namenode itself to simplify
 * the operation.
 */
public class NamenodeHeartbeatService extends PeriodicService {

  private static final Logger LOG =
      LoggerFactory.getLogger(NamenodeHeartbeatService.class);

  /** Configuration for the heartbeat. */
  private Configuration conf;

  /** Router performing the heartbeating. */
  private final ActiveNamenodeResolver resolver;

  /** Interface to the tracked NN. */
  private final String nameserviceId;
  private final String namenodeId;

  /** Namenode HA target. */
  private NNHAServiceTarget localTarget;
  /** RPC address for the namenode. */
  private String rpcAddress;
  /** Service RPC address for the namenode. */
  private String serviceAddress;
  /** Service RPC address for the namenode. */
  private String lifelineAddress;
  /** HTTP address for the namenode. */
  private String webAddress;

  /**
   * Create a new Namenode status updater.
   * @param resolver Namenode resolver service to handle NN registration.
   * @param nameserviceId Identifier of the nameservice.
   * @param namenodeId Identifier of the namenode in HA.
   */
  public NamenodeHeartbeatService(
      ActiveNamenodeResolver resolver, String nsId, String nnId) {
    super(NamenodeHeartbeatService.class.getSimpleName() +
        (nsId == null ? "" : " " + nsId) +
        (nnId == null ? "" : " " + nnId));

    this.resolver = resolver;

    this.nameserviceId = nsId;
    this.namenodeId = nnId;

  }

  @Override
  protected void serviceInit(Configuration configuration) throws Exception {

    this.conf = configuration;

    String nnDesc = nameserviceId;
    if (this.namenodeId != null && !this.namenodeId.isEmpty()) {
      this.localTarget = new NNHAServiceTarget(
          conf, nameserviceId, namenodeId);
      nnDesc += "-" + namenodeId;
    } else {
      this.localTarget = null;
    }

    // Get the RPC address for the clients to connect
    this.rpcAddress = getRpcAddress(conf, nameserviceId, namenodeId);
    LOG.info("{} RPC address: {}", nnDesc, rpcAddress);

    // Get the Service RPC address for monitoring
    this.serviceAddress =
        DFSUtil.getNamenodeServiceAddr(conf, nameserviceId, namenodeId);
    if (this.serviceAddress == null) {
      LOG.error("Cannot locate RPC service address for NN {}, " +
          "using RPC address {}", nnDesc, this.rpcAddress);
      this.serviceAddress = this.rpcAddress;
    }
    LOG.info("{} Service RPC address: {}", nnDesc, serviceAddress);

    // Get the Lifeline RPC address for faster monitoring
    this.lifelineAddress =
        DFSUtil.getNamenodeLifelineAddr(conf, nameserviceId, namenodeId);
    if (this.lifelineAddress == null) {
      this.lifelineAddress = this.serviceAddress;
    }
    LOG.info("{} Lifeline RPC address: {}", nnDesc, lifelineAddress);

    // Get the Web address for UI
    this.webAddress =
        DFSUtil.getNamenodeWebAddr(conf, nameserviceId, namenodeId);
    LOG.info("{} Web address: {}", nnDesc, webAddress);

    this.setIntervalMs(conf.getLong(
        DFS_ROUTER_HEARTBEAT_INTERVAL_MS,
        DFS_ROUTER_HEARTBEAT_INTERVAL_MS_DEFAULT));

    super.serviceInit(configuration);
  }

  @Override
  public void periodicInvoke() {
    updateState();
  }

  /**
   * Get the RPC address for a Namenode.
   * @param conf Configuration.
   * @param nsId Name service identifier.
   * @param nnId Name node identifier.
   * @return RPC address in format hostname:1234.
   */
  private static String getRpcAddress(
      Configuration conf, String nsId, String nnId) {

    // Get it from the regular RPC setting
    String confKey = DFSConfigKeys.DFS_NAMENODE_RPC_ADDRESS_KEY;
    String ret = conf.get(confKey);

    if (nsId != null || nnId != null) {
      // Get if for the proper nameservice and namenode
      confKey = DFSUtil.addKeySuffixes(confKey, nsId, nnId);
      ret = conf.get(confKey);

      // If not available, get it from the map
      if (ret == null) {
        Map<String, InetSocketAddress> rpcAddresses =
            DFSUtil.getRpcAddressesForNameserviceId(conf, nsId, null);
        InetSocketAddress sockAddr = null;
        if (nnId != null) {
          sockAddr = rpcAddresses.get(nnId);
        } else if (rpcAddresses.size() == 1) {
          // Get the only namenode in the namespace
          sockAddr = rpcAddresses.values().iterator().next();
        }
        if (sockAddr != null) {
          InetAddress addr = sockAddr.getAddress();
          ret = addr.getHostName() + ":" + sockAddr.getPort();
        }
      }
    }
    return ret;
  }

  /**
   * Update the state of the Namenode.
   */
  private void updateState() {
    NamenodeStatusReport report = getNamenodeStatusReport();
    if (!report.registrationValid()) {
      // Not operational
      LOG.error("Namenode is not operational: {}", getNamenodeDesc());
    } else if (report.haStateValid()) {
      // block and HA status available
      LOG.debug("Received service state: {} from HA namenode: {}",
          report.getState(), getNamenodeDesc());
    } else if (localTarget == null) {
      // block info available, HA status not expected
      LOG.debug(
          "Reporting non-HA namenode as operational: " + getNamenodeDesc());
    } else {
      // block info available, HA status should be available, but was not
      // fetched do nothing and let the current state stand
      return;
    }
    try {
      if (!resolver.registerNamenode(report)) {
        LOG.warn("Cannot register namenode {}", report);
      }
    } catch (IOException e) {
      LOG.info("Cannot register namenode in the State Store");
    } catch (Exception ex) {
      LOG.error("Unhandled exception updating NN registration for {}",
          getNamenodeDesc(), ex);
    }
  }

  /**
   * Get the status report for the Namenode monitored by this heartbeater.
   * @return Namenode status report.
   */
  protected NamenodeStatusReport getNamenodeStatusReport() {
    NamenodeStatusReport report = new NamenodeStatusReport(nameserviceId,
        namenodeId, rpcAddress, serviceAddress, lifelineAddress, webAddress);

    try {
      LOG.debug("Probing NN at service address: {}", serviceAddress);

      URI serviceURI = new URI("hdfs://" + serviceAddress);
      // Read the filesystem info from RPC (required)
      NamenodeProtocol nn = NameNodeProxies
          .createProxy(this.conf, serviceURI, NamenodeProtocol.class)
          .getProxy();

      if (nn != null) {
        NamespaceInfo info = nn.versionRequest();
        if (info != null) {
          report.setNamespaceInfo(info);
        }
      }
      if (!report.registrationValid()) {
        return report;
      }

      // Check for safemode from the client protocol. Currently optional, but
      // should be required at some point for QoS
      try {
        ClientProtocol client = NameNodeProxies
            .createProxy(this.conf, serviceURI, ClientProtocol.class)
            .getProxy();
        if (client != null) {
          boolean isSafeMode = client.setSafeMode(
              SafeModeAction.SAFEMODE_GET, false);
          report.setSafeMode(isSafeMode);
        }
      } catch (Exception e) {
        LOG.error("Cannot fetch safemode state for {}", getNamenodeDesc(), e);
      }

      // Read the stats from JMX (optional)
      updateJMXParameters(webAddress, report);

      if (localTarget != null) {
        // Try to get the HA status
        try {
          // Determine if NN is active
          // TODO: dynamic timeout
          HAServiceProtocol haProtocol = localTarget.getProxy(conf, 30*1000);
          HAServiceStatus status = haProtocol.getServiceStatus();
          report.setHAServiceState(status.getState());
        } catch (Throwable e) {
          if (e.getMessage().startsWith("HA for namenode is not enabled")) {
            LOG.error("HA for {} is not enabled", getNamenodeDesc());
            localTarget = null;
          } else {
            // Failed to fetch HA status, ignoring failure
            LOG.error("Cannot fetch HA status for {}: {}",
                getNamenodeDesc(), e.getMessage(), e);
          }
        }
      }
    } catch(IOException e) {
      LOG.error("Cannot communicate with {}: {}",
          getNamenodeDesc(), e.getMessage());
    } catch(Throwable e) {
      // Generic error that we don't know about
      LOG.error("Unexpected exception while communicating with {}: {}",
          getNamenodeDesc(), e.getMessage(), e);
    }
    return report;
  }

  /**
   * Get the description of the Namenode to monitor.
   * @return Description of the Namenode to monitor.
   */
  public String getNamenodeDesc() {
    if (namenodeId != null && !namenodeId.isEmpty()) {
      return nameserviceId + "-" + namenodeId + ":" + serviceAddress;
    } else {
      return nameserviceId + ":" + serviceAddress;
    }
  }

  /**
   * Get the parameters for a Namenode from JMX and add them to the report.
   * @param webAddress Web interface of the Namenode to monitor.
   * @param report Namenode status report to update with JMX data.
   */
  private void updateJMXParameters(
      String address, NamenodeStatusReport report) {
    try {
      // TODO part of this should be moved to its own utility
      String query = "Hadoop:service=NameNode,name=FSNamesystem*";
      JSONArray aux = FederationUtil.getJmx(query, address);
      if (aux != null) {
        for (int i = 0; i < aux.length(); i++) {
          JSONObject jsonObject = aux.getJSONObject(i);
          String name = jsonObject.getString("name");
          if (name.equals("Hadoop:service=NameNode,name=FSNamesystemState")) {
            report.setDatanodeInfo(
                jsonObject.getInt("NumLiveDataNodes"),
                jsonObject.getInt("NumDeadDataNodes"),
                jsonObject.getInt("NumDecommissioningDataNodes"),
                jsonObject.getInt("NumDecomLiveDataNodes"),
                jsonObject.getInt("NumDecomDeadDataNodes"));
          } else if (name.equals(
              "Hadoop:service=NameNode,name=FSNamesystem")) {
            report.setNamesystemInfo(
                jsonObject.getLong("CapacityRemaining"),
                jsonObject.getLong("CapacityTotal"),
                jsonObject.getLong("FilesTotal"),
                jsonObject.getLong("BlocksTotal"),
                jsonObject.getLong("MissingBlocks"),
                jsonObject.getLong("PendingReplicationBlocks"),
                jsonObject.getLong("UnderReplicatedBlocks"),
                jsonObject.getLong("PendingDeletionBlocks"));
          }
        }
      }
    } catch (Exception e) {
      LOG.error("Cannot get stat from {} using JMX", getNamenodeDesc(), e);
    }
  }
}


text:
package wombat;

import javax.servlet.http.*;
import javax.servlet.*;

public class InitServlet extends HttpServlet {

  public void init() {
    //System.out.println("TATA wombat.InitServlet.init() called.");
  }

  public void doGet(HttpServletRequest req, HttpServletResponse res) {
    // nothing to do
  }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.analyticsreporting.v4.model;

/**
 * An Activity represents data for an activity of a user. Note that an Activity is different from a
 * hit. A hit might result in multiple Activity's. For example, if a hit includes a transaction and
 * a goal completion, there will be two Activity protos for this hit, one for ECOMMERCE and one for
 * GOAL. Conversely, multiple hits can also construct one Activity. In classic e-commerce, data for
 * one transaction might be sent through multiple hits. These hits will be merged into one ECOMMERCE
 * Activity.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Analytics Reporting API. For a detailed explanation
 * see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class Activity extends com.google.api.client.json.GenericJson {

  /**
   * Timestamp of the activity.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private String activityTime;

  /**
   * Type of this activity.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String activityType;

  /**
   * This will be set if `activity_type` equals `SCREEN_VIEW`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private ScreenviewData appview;

  /**
   * For manual campaign tracking, it is the value of the utm_campaign campaign tracking parameter.
   * For AdWords autotagging, it is the name(s) of the online ad campaign(s) you use for the
   * property. If you use neither, its value is (not set).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String campaign;

  /**
   * The Channel Group associated with an end user's session for this View (defined by the View's
   * Channel Groupings).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String channelGrouping;

  /**
   * A list of all custom dimensions associated with this activity.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<CustomDimension> customDimension;

  /**
   * This will be set if `activity_type` equals `ECOMMERCE`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private EcommerceData ecommerce;

  /**
   * This field contains all the details pertaining to an event and will be set if `activity_type`
   * equals `EVENT`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private EventData event;

  /**
   * This field contains a list of all the goals that were reached in this activity when
   * `activity_type` equals `GOAL`.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private GoalSetData goals;

  /**
   * The hostname from which the tracking request was made.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String hostname;

  /**
   * For manual campaign tracking, it is the value of the utm_term campaign tracking parameter. For
   * AdWords traffic, it contains the best matching targeting criteria. For the display network,
   * where multiple targeting criteria could have caused the ad to show up, it returns the best
   * matching targeting criteria as selected by Ads. This could be display_keyword, site placement,
   * boomuserlist, user_interest, age, or gender. Otherwise its value is (not set).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String keyword;

  /**
   * The first page in users' sessions, or the landing page.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String landingPagePath;

  /**
   * The type of referrals. For manual campaign tracking, it is the value of the utm_medium campaign
   * tracking parameter. For AdWords autotagging, it is cpc. If users came from a search engine
   * detected by Google Analytics, it is organic. If the referrer is not a search engine, it is
   * referral. If users came directly to the property and document.referrer is empty, its value is
   * (none).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String medium;

  /**
   * This will be set if `activity_type` equals `PAGEVIEW`. This field contains all the details
   * about the visitor and the page that was visited.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private PageviewData pageview;

  /**
   * The source of referrals. For manual campaign tracking, it is the value of the utm_source
   * campaign tracking parameter. For AdWords autotagging, it is google. If you use neither, it is
   * the domain of the source (e.g., document.referrer) referring the users. It may also contain a
   * port address. If users arrived without a referrer, its value is (direct).
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String source;

  /**
   * Timestamp of the activity.
   * @return value or {@code null} for none
   */
  public String getActivityTime() {
    return activityTime;
  }

  /**
   * Timestamp of the activity.
   * @param activityTime activityTime or {@code null} for none
   */
  public Activity setActivityTime(String activityTime) {
    this.activityTime = activityTime;
    return this;
  }

  /**
   * Type of this activity.
   * @return value or {@code null} for none
   */
  public java.lang.String getActivityType() {
    return activityType;
  }

  /**
   * Type of this activity.
   * @param activityType activityType or {@code null} for none
   */
  public Activity setActivityType(java.lang.String activityType) {
    this.activityType = activityType;
    return this;
  }

  /**
   * This will be set if `activity_type` equals `SCREEN_VIEW`.
   * @return value or {@code null} for none
   */
  public ScreenviewData getAppview() {
    return appview;
  }

  /**
   * This will be set if `activity_type` equals `SCREEN_VIEW`.
   * @param appview appview or {@code null} for none
   */
  public Activity setAppview(ScreenviewData appview) {
    this.appview = appview;
    return this;
  }

  /**
   * For manual campaign tracking, it is the value of the utm_campaign campaign tracking parameter.
   * For AdWords autotagging, it is the name(s) of the online ad campaign(s) you use for the
   * property. If you use neither, its value is (not set).
   * @return value or {@code null} for none
   */
  public java.lang.String getCampaign() {
    return campaign;
  }

  /**
   * For manual campaign tracking, it is the value of the utm_campaign campaign tracking parameter.
   * For AdWords autotagging, it is the name(s) of the online ad campaign(s) you use for the
   * property. If you use neither, its value is (not set).
   * @param campaign campaign or {@code null} for none
   */
  public Activity setCampaign(java.lang.String campaign) {
    this.campaign = campaign;
    return this;
  }

  /**
   * The Channel Group associated with an end user's session for this View (defined by the View's
   * Channel Groupings).
   * @return value or {@code null} for none
   */
  public java.lang.String getChannelGrouping() {
    return channelGrouping;
  }

  /**
   * The Channel Group associated with an end user's session for this View (defined by the View's
   * Channel Groupings).
   * @param channelGrouping channelGrouping or {@code null} for none
   */
  public Activity setChannelGrouping(java.lang.String channelGrouping) {
    this.channelGrouping = channelGrouping;
    return this;
  }

  /**
   * A list of all custom dimensions associated with this activity.
   * @return value or {@code null} for none
   */
  public java.util.List<CustomDimension> getCustomDimension() {
    return customDimension;
  }

  /**
   * A list of all custom dimensions associated with this activity.
   * @param customDimension customDimension or {@code null} for none
   */
  public Activity setCustomDimension(java.util.List<CustomDimension> customDimension) {
    this.customDimension = customDimension;
    return this;
  }

  /**
   * This will be set if `activity_type` equals `ECOMMERCE`.
   * @return value or {@code null} for none
   */
  public EcommerceData getEcommerce() {
    return ecommerce;
  }

  /**
   * This will be set if `activity_type` equals `ECOMMERCE`.
   * @param ecommerce ecommerce or {@code null} for none
   */
  public Activity setEcommerce(EcommerceData ecommerce) {
    this.ecommerce = ecommerce;
    return this;
  }

  /**
   * This field contains all the details pertaining to an event and will be set if `activity_type`
   * equals `EVENT`.
   * @return value or {@code null} for none
   */
  public EventData getEvent() {
    return event;
  }

  /**
   * This field contains all the details pertaining to an event and will be set if `activity_type`
   * equals `EVENT`.
   * @param event event or {@code null} for none
   */
  public Activity setEvent(EventData event) {
    this.event = event;
    return this;
  }

  /**
   * This field contains a list of all the goals that were reached in this activity when
   * `activity_type` equals `GOAL`.
   * @return value or {@code null} for none
   */
  public GoalSetData getGoals() {
    return goals;
  }

  /**
   * This field contains a list of all the goals that were reached in this activity when
   * `activity_type` equals `GOAL`.
   * @param goals goals or {@code null} for none
   */
  public Activity setGoals(GoalSetData goals) {
    this.goals = goals;
    return this;
  }

  /**
   * The hostname from which the tracking request was made.
   * @return value or {@code null} for none
   */
  public java.lang.String getHostname() {
    return hostname;
  }

  /**
   * The hostname from which the tracking request was made.
   * @param hostname hostname or {@code null} for none
   */
  public Activity setHostname(java.lang.String hostname) {
    this.hostname = hostname;
    return this;
  }

  /**
   * For manual campaign tracking, it is the value of the utm_term campaign tracking parameter. For
   * AdWords traffic, it contains the best matching targeting criteria. For the display network,
   * where multiple targeting criteria could have caused the ad to show up, it returns the best
   * matching targeting criteria as selected by Ads. This could be display_keyword, site placement,
   * boomuserlist, user_interest, age, or gender. Otherwise its value is (not set).
   * @return value or {@code null} for none
   */
  public java.lang.String getKeyword() {
    return keyword;
  }

  /**
   * For manual campaign tracking, it is the value of the utm_term campaign tracking parameter. For
   * AdWords traffic, it contains the best matching targeting criteria. For the display network,
   * where multiple targeting criteria could have caused the ad to show up, it returns the best
   * matching targeting criteria as selected by Ads. This could be display_keyword, site placement,
   * boomuserlist, user_interest, age, or gender. Otherwise its value is (not set).
   * @param keyword keyword or {@code null} for none
   */
  public Activity setKeyword(java.lang.String keyword) {
    this.keyword = keyword;
    return this;
  }

  /**
   * The first page in users' sessions, or the landing page.
   * @return value or {@code null} for none
   */
  public java.lang.String getLandingPagePath() {
    return landingPagePath;
  }

  /**
   * The first page in users' sessions, or the landing page.
   * @param landingPagePath landingPagePath or {@code null} for none
   */
  public Activity setLandingPagePath(java.lang.String landingPagePath) {
    this.landingPagePath = landingPagePath;
    return this;
  }

  /**
   * The type of referrals. For manual campaign tracking, it is the value of the utm_medium campaign
   * tracking parameter. For AdWords autotagging, it is cpc. If users came from a search engine
   * detected by Google Analytics, it is organic. If the referrer is not a search engine, it is
   * referral. If users came directly to the property and document.referrer is empty, its value is
   * (none).
   * @return value or {@code null} for none
   */
  public java.lang.String getMedium() {
    return medium;
  }

  /**
   * The type of referrals. For manual campaign tracking, it is the value of the utm_medium campaign
   * tracking parameter. For AdWords autotagging, it is cpc. If users came from a search engine
   * detected by Google Analytics, it is organic. If the referrer is not a search engine, it is
   * referral. If users came directly to the property and document.referrer is empty, its value is
   * (none).
   * @param medium medium or {@code null} for none
   */
  public Activity setMedium(java.lang.String medium) {
    this.medium = medium;
    return this;
  }

  /**
   * This will be set if `activity_type` equals `PAGEVIEW`. This field contains all the details
   * about the visitor and the page that was visited.
   * @return value or {@code null} for none
   */
  public PageviewData getPageview() {
    return pageview;
  }

  /**
   * This will be set if `activity_type` equals `PAGEVIEW`. This field contains all the details
   * about the visitor and the page that was visited.
   * @param pageview pageview or {@code null} for none
   */
  public Activity setPageview(PageviewData pageview) {
    this.pageview = pageview;
    return this;
  }

  /**
   * The source of referrals. For manual campaign tracking, it is the value of the utm_source
   * campaign tracking parameter. For AdWords autotagging, it is google. If you use neither, it is
   * the domain of the source (e.g., document.referrer) referring the users. It may also contain a
   * port address. If users arrived without a referrer, its value is (direct).
   * @return value or {@code null} for none
   */
  public java.lang.String getSource() {
    return source;
  }

  /**
   * The source of referrals. For manual campaign tracking, it is the value of the utm_source
   * campaign tracking parameter. For AdWords autotagging, it is google. If you use neither, it is
   * the domain of the source (e.g., document.referrer) referring the users. It may also contain a
   * port address. If users arrived without a referrer, its value is (direct).
   * @param source source or {@code null} for none
   */
  public Activity setSource(java.lang.String source) {
    this.source = source;
    return this;
  }

  @Override
  public Activity set(String fieldName, Object value) {
    return (Activity) super.set(fieldName, value);
  }

  @Override
  public Activity clone() {
    return (Activity) super.clone();
  }

}


text:
package com.kissthinker.collection.map;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * A "bi map" or "two way map".
 *
 * Get a value with a given key (as in a traditional map), but also get a key with a given value.
 * @author David Ainslie
 *
 */
public class BiMap<K, V> implements Map<K, V>
{
    /** */
    private final Map<K, V> keyValueMap = new HashMap<>();

    /** */
    private final Map<V, K> valueKeyMap = new HashMap<>();

    /** */
    public BiMap()
    {
        super();
    }

    /**
     *
     * @param key Key
     * @param value Value
     */
    @Override
    public V put(K key, V value)
    {
        valueKeyMap.put(value, key);
        return keyValueMap.put(key, value);
    }

    /**
     *
     * @param key Key
     * @return V or null
     */
    public V value(K key)
    {
        return keyValueMap.get(key);
    }

    /**
     *
     * @param value Value
     * @return true if contained
     */
    public boolean hasValue(V value)
    {
        return valueKeyMap.containsKey(value);
    }

    /**
     *
     * @param key Key
     * @return V or null
     */
    public V removeValue(K key)
    {
        V value = keyValueMap.remove(key);
        valueKeyMap.remove(value);

        return value;
    }

    /**
     *
     * @param value Value
     * @return K or null
     */
    public K key(V value)
    {
        return valueKeyMap.get(value);
    }

    /**
     *
     * @param key Key
     * @return true if contained
     */
    public boolean hasKey(K key)
    {
        return keyValueMap.containsKey(key);
    }

    /**
     *
     * @param value Value
     * @return K or null
     */
    public K removeKey(V value)
    {
        K key = valueKeyMap.remove(value);
        keyValueMap.remove(key);

        return key;
    }

    /** */
    @Override
    public int size()
    {
        return keyValueMap.size();
    }

    /** */
    @Override
    public boolean isEmpty()
    {
        return keyValueMap.isEmpty();
    }

    /**
     *
     * @param key Key
     * @return Value
     */
    @Override
    public V get(Object key)
    {
        return keyValueMap.get(key);
    }

    /**
     *
     * @param key Key
     * @return Value
     */
    @Override
    public V remove(Object key)
    {
        V value = keyValueMap.remove(key);
        valueKeyMap.remove(value);

        return value;
    }

    /**
     *
     * @param m Map
     */
    @Override
    public void putAll(Map<? extends K, ? extends V> m)
    {
        keyValueMap.putAll(m);
        // TODO need to update valueKeyMap
    }

    /** */
    @Override
    public void clear()
    {
        keyValueMap.clear();
        valueKeyMap.clear();
    }

    /** */
    @Override
    public Set<K> keySet()
    {
        return keyValueMap.keySet();
    }

    /** */
    @Override
    public Collection<V> values()
    {
        return keyValueMap.values();
    }

    /** */
    @Override
    public Set<java.util.Map.Entry<K, V>> entrySet()
    {
        return keyValueMap.entrySet();
    }

    /**
     *
     * @param key Key
     * @return True or false
     */
    @Override
    public boolean containsKey(Object key)
    {
        return keyValueMap.containsKey(key);
    }

    /**
     *
     * @param value Value
     * @return True or false
     */
    @Override
    public boolean containsValue(Object value)
    {
        return valueKeyMap.containsKey(value);
    }
}


text:
import logging
import inspect

import numpy as np

#from matplotlib import _cntr as cntr
#from contours.core import shapely_formatter as shapely_fmt
#from contours.quad import QuadContourGenerator
from astropy.coordinates import Angle
from astropy import constants as c
from astropy import wcs
from astropy.io import fits
from matplotlib.patheffects import withStroke

class Polygon:
    """
    Generic polygon class.

    Note: code based on:
    http://code.activestate.com/recipes/578381-a-point-in-polygon-program-sw-sloan-algorithm/

    Parameters
    ----------
    x : array
        A sequence of nodal x-coords.
    y : array
        A sequence of nodal y-coords.

    """
    def __init__(self, x, y):

        self.logger = logging.getLogger(__name__)
        self.logger.info("Creating Polygon")

        if len(x) != len(y):
            raise IndexError('x and y must be equally sized.')
        self.x = np.asfarray(x)
        self.y = np.asfarray(y)

        # Closes the polygon if were open
        x1, y1 = x[0], y[0]
        xn, yn = x[-1], y[-1]
        if x1 != xn or y1 != yn:
            self.x = np.concatenate((self.x, [x1]))
            self.y = np.concatenate((self.y, [y1]))

        # Anti-clockwise coordinates
        if _det(self.x, self.y) < 0:
            self.x = self.x[::-1]
            self.y = self.y[::-1]

    def get_vertices(self):
        """
        Returns the vertices of the polygon as a 2xNvert list.
        """

        return [[i,j] for i,j in zip(self.x, self.y)]

    def is_inside(self, xpoint, ypoint, smalld=1e-12):
        """
        Check if point is inside a general polygon.

        An improved version of the algorithm of Nordbeck and Rydstedt.

        REF: SLOAN, S.W. (1985): A point-in-polygon program. Adv. Eng.
             Software, Vol 7, No. 1, pp 45-47.

        Parameters
        ----------
        xpoint : array or float
            The x-coord of the point to be tested.
        ypoint : array or float
            The y-coords of the point to be tested.
        smalld : float
            Tolerance within which point is considered to be on a side.

        Returns
        -------
        mindst : array or float
            The distance from the point to the nearest point of the polygon:
                If mindst < 0 then point is outside the polygon.
                If mindst = 0 then point in on a side of the polygon.
                If mindst > 0 then point is inside the polygon.

        """
        xpoint = np.asfarray(xpoint)
        ypoint = np.asfarray(ypoint)

        # Scalar to array
        if xpoint.shape is tuple():
            xpoint = np.array([xpoint], dtype=float)
            ypoint = np.array([ypoint], dtype=float)
            scalar = True
        else:
            scalar = False
        # Check consistency
        if xpoint.shape != ypoint.shape:
            raise IndexError('x and y  must be equally sized.')

        # If snear = True: Dist to nearest side < nearest vertex
        # If snear = False: Dist to nearest vertex < nearest side
        snear = np.ma.masked_all(xpoint.shape, dtype=bool)

        # Initialize arrays
        mindst = np.ones_like(xpoint, dtype=float) * np.inf
        j = np.ma.masked_all(xpoint.shape, dtype=int)
        x = self.x
        y = self.y
        n = len(x) - 1  # Number of sides/vertices defining the polygon

        # Loop over each side defining polygon
        for i in range(n):
            d = np.ones_like(xpoint, dtype=float) * np.inf

            # Start of side has coords (x1, y1)
            # End of side has coords (x2, y2)
            # Point has coords (xpoint, ypoint)
            x1 = x[i]
            y1 = y[i]
            x21 = x[i+1] - x1
            y21 = y[i+1] - y1
            x1p = x1 - xpoint
            y1p = y1 - ypoint

            # Points on infinite line defined by
            #     x = x1 + t * (x1 - x2)
            #     y = y1 + t * (y1 - y2)
            # where
            #     t = 0    at (x1, y1)
            #     t = 1    at (x2, y2)
            # Find where normal passing through (xpoint, ypoint) intersects
            # infinite line
            t = -(x1p * x21 + y1p * y21) / (x21 ** 2 + y21 ** 2)
            tlt0 = t < 0
            tle1 = (0 <= t) & (t <= 1)

            # Normal intersects side
            d[tle1] = ((x1p[tle1] + t[tle1] * x21) ** 2 +
                       (y1p[tle1] + t[tle1] * y21) ** 2)

            # Normal does not intersects side
            # Point is closest to vertex (x1, y1)
            # Compute square of distance to this vertex
            d[tlt0] = x1p[tlt0] ** 2 + y1p[tlt0] ** 2

            # Store distances
            mask = d < mindst
            mindst[mask] = d[mask]
            j[mask] = i

            # Point is closer to (x1, y1) than any other vertex or side
            snear[mask & tlt0] = False

            # Point is closer to this side than to any other side or vertex
            snear[mask & tle1] = True

        if np.ma.count(snear) != snear.size:
            raise IndexError('Error computing distances')
        mindst **= 0.5

        # Point is closer to its nearest vertex than its nearest side, check if
        # nearest vertex is concave.
        # If the nearest vertex is concave then point is inside the polygon,
        # else the point is outside the polygon.
        jo = j.copy()
        jo[j==0] -= 1
        area = _det([x[j+1], x[j], x[jo-1]], [y[j+1], y[j], y[jo-1]])
        mindst[~snear] = np.copysign(mindst, area)[~snear]

        # Point is closer to its nearest side than to its nearest vertex, check
        # if point is to left or right of this side.
        # If point is to left of side it is inside polygon, else point is
        # outside polygon.
        area = _det([x[j], x[j+1], xpoint], [y[j], y[j+1], ypoint])
        mindst[snear] = np.copysign(mindst, area)[snear]

        # Point is on side of polygon
        mindst[np.fabs(mindst) < smalld] = 0

        # If input values were scalar then the output should be too
        if scalar:
            mindst = float(mindst)
        return mindst

    def make_mask(self, shape, **kwargs):
        """
        Creates a mask of a given shape using the Polygon as boundaries.
        All points inside the Polygon will have a value of 1.

        :param shape: Shape of the output mask.
        :type shape: tuple
        :returns: Mask of the Polygon.
        :rtype: array
        """

        mask = np.zeros(shape)

        xmax = int(round(max(self.x)))
        xmin = int(round(min(self.x)))
        ymax = int(round(max(self.y)))
        ymin = int(round(min(self.y)))

        for j in xrange(ymax - ymin):
            for i in xrange(xmax - xmin):
                if self.is_inside(i+xmin, j+ymin, **kwargs) >= 0:
                    self.logger.debug("Point ({0},{1}) ".format(i+xmin,j+ymin) +
                                      "is inside the Polygon")
                    mask[j+ymin,i+xmin] = 1

        return mask

def _det(xvert, yvert):
    """
    Compute twice the area of the triangle defined by points using the
    determinant formula.

    Parameters
    ----------
    xvert : array
        A vector of nodal x-coords.
    yvert : array
        A vector of nodal y-coords.

    Returns
    -------
    area : float
        Twice the area of the triangle defined by the points:
            area is positive if points define polygon in anticlockwise order.
            area is negative if points define polygon in clockwise order.
            area is zero if at least two of the points are concident or if
            all points are collinear.

    """
    xvert = np.asfarray(xvert)
    yvert = np.asfarray(yvert)
    x_prev = np.concatenate(([xvert[-1]], xvert[:-1]))
    y_prev = np.concatenate(([yvert[-1]], yvert[:-1]))
    return np.sum(yvert * x_prev - xvert * y_prev, axis=0)

def beam_area_pix(head):
    """
    Computes the beam area in pixels.
    It uses an approximation accurate to
    within 5%.

    K. Rohlfs and T.L. Wilson, 'Tools of Radio Astronomy', third revised and enlarged edition, 1996, Springer, page 190-191.

    :param head: Image header.
    :type head: Fits header
    :returns: Number of pixels inside the beam.
    :rtype: float
    """

    return 1.133*float(head['BMAJ'])*float(head['BMIN'])/(abs(head['CDELT1'])*abs(head['CDELT2']))

def beam_area(head):
    """
    Computes the beam area in sterradians.
    It uses an approximation accurate to
    within 5%.

    K. Rohlfs and T.L. Wilson, 'Tools of Radio Astronomy', third revised and enlarged edition, 1996, Springer, page 190-191.

    :param head: Image header.
    :type head: Fits header
    :returns: Beam area in sr.
    :rtype: float
    """

    return np.pi/(4.*np.log(2.))*np.deg2rad(float(head['BMAJ']))*np.deg2rad(float(head['BMIN']))

def check_ascending(ra, dec, vel, verbose=False):
    """
    Check if the RA, DEC and VELO axes of a cube are in ascending order.
    It returns a step for every axes which will make it go in ascending order.

    :param ra: RA axis.
    :param dec: DEC axis.
    :param vel: Velocity axis.
    :returns: Step for RA, DEC and velocity.
    :rtype: int,int,int
    """

    if vel[0] > vel[1]:
        vs = -1
        if verbose:
            print("Velocity axis is inverted.")
    else:
        vs = 1

    if ra[0] > ra[1]:
        rs = -1
        if verbose:
            print("RA axis is inverted.")
    else:
        rs = 1

    if dec[0] > dec[1]:
        ds = -1
        if verbose:
            print("DEC axis is inverted.")
    else:
        ds = 1

    return rs, ds, vs

def compare_headers(head1, head2):
    """
    Compares the size and element width of 2 fits headers.
    """

    axes = np.array([False, False, False])

    for i in range(3):
        if head1['CDELT{0}'.format(i+1)] == head2['CDELT{0}'.format(i+1)] \
           and head1['NAXIS{0}'.format(i+1)] == head2['NAXIS{0}'.format(i+1)]:
               axes[i] = True

    if np.prod(axes) == 1:
        return True
    else:
        return False

def draw_beam(header, ax, **kwargs):
    """
    Draws an elliptical beam in a pywcsgrid2 axes object.
    """

    bmaj = header.get("BMAJ")
    bmin = header.get("BMIN")
    pa = header.get("BPA")
    pixx = header.get("CDELT1")
    pixy = header.get("CDELT2")
    ax.add_beam_size(bmaj/np.abs(pixx), bmin/np.abs(pixy), pa, loc=3, **kwargs)

def get_axis(header, axis):
    """
    Constructs a cube axis.

    :param header: Fits cube header.
    :type header: pyfits header
    :param axis: Axis to reconstruct.
    :type axis: int
    :returns: cube axis
    :rtype: numpy array
    """

    axis = str(axis)
    dx = header.get("CDELT" + axis)
    try:
        dx = float(dx)
        p0 = header.get("CRPIX" + axis)
        x0 = header.get("CRVAL" + axis)

    except TypeError:
        dx = 1
        p0 = 1
        x0 = 1

    n = header.get("NAXIS" + axis)

    p0 -= 1 # Fits files index start at 1, not for python.

    axis = np.arange(x0 - p0*dx, x0 - p0*dx + n*dx, dx)

    if len(axis) > n:
        axis = axis[:-1]

    return axis

def get_fits3axes(head):
    """
    """

    ra = get_axis(head, 1)
    de = get_axis(head, 2)
    ve = get_axis(head, 3)

    return ra , de, ve

#def get_contours(x, y, z, levs, segment=0, verbose=False):
#    """
#    Creates an array with the contour vertices.
#    """
#
#    c = QuadContourGenerator.from_rectilinear(x, y, z, shapely_fmt)
#
#    #c = cntr.Cntr(x, y, z)
#
#    segments = []
#    for i,l in enumerate(levs):
#        #res = c.trace(l)
#        res = c.filled_contour(min=1-l, max=None)
#        if res:
#            nseg = len(res) // 2
#            segments.append(res[:nseg][segment])
#            if verbose:
#                print(res[:nseg][segment])
#        else:
#            pass
#
#    # Where should we add missing corners?
#    #if x.max() in np.asarray(segments)[0][:,0] \
#       #and x.max() not in np.asarray(segments)[1][:,0]:
#           #if np.asarray(segments)[1][:,1]
#                #segments[1].append()
#
#    return np.asarray(segments)

def K2Jy(head, freq=0):
    """
    Computes the conversion factor Jy/K.

    :param head: Image header.
    :type head: Fits header
    :returns: Factor to convert K to Jy.
    :rtype: float
    """

    omega = beam_area(head)

    if freq == 0:
        try:
            freq = head['RESTFREQ']
        except KeyError:
            fcol = [s for s in head.keys() if "FREQ" in s]
            freq = head[fcol[0]]

    k2jy = 2.*c.k_B.cgs.value/np.power(c.c.cgs.value/freq, 2.)*omega/1e-23

    return k2jy

def read_casa_polys(filename, image=None, wcs=None):
    """
    Reads casa region file and returns Polygon objects.

    Code adapted from FACTOR
    https://github.com/lofar-astron/factor/blob/reimage/factor/scripts/make_clean_mask.py
    https://github.com/lofar-astron/factor/commit/667b77e8690e9536a61afbe3ed673a3e16889bb1

    :param filename: Path to file containing the casa region.
    :type filename: string
    :param image: pyrap.images.image object, with properly defined coordsys.
    :type image: pyrap.images.image
    :returns: list of Polygons.
    :rtype: Polygon
    """

    logger = logging.getLogger(__name__)

    with open(filename, 'r') as f:
        lines = f.readlines()

    polys = []
    for line in lines:
        if line.startswith('poly'):
            poly_str_temp = line.split('[[')[1]
            poly_str = poly_str_temp.split(']]')[0]
            poly_str_list = poly_str.split('], [')
            ra = []
            dec = []
            for pos in poly_str_list:
                RAstr, Decstr = pos.split(',')
                ra.append(Angle(RAstr, unit='hourangle').to('deg').value)
                dec.append(Angle(Decstr.replace('.', ':', 2), unit='deg').to('deg').value)

            # Convert to image-plane Polygon
            xvert = []
            yvert = []
            for RAvert, Decvert in zip(np.array(ra), np.array(dec)):

                if image:
                    try:
                        pixels = image.topixel([0, 1, Decvert*np.pi/180.0,
                                                RAvert*np.pi/180.0])
                    except:
                        pixels = image.topixel([1, 1, Decvert*np.pi/180.0,
                                                RAvert*np.pi/180.0])
                    xvert.append(pixels[2]) # x -> Dec
                    yvert.append(pixels[3]) # y -> RA

                elif wcs:
                    pixels = wcs.all_world2pix([[RAvert,
                                                 Decvert]], 0)[0]
                    xvert.append(pixels[0])
                    yvert.append(pixels[1])

            polys.append(Polygon(xvert, yvert))

        elif line.startswith('ellipse'):
            ell_str_temp = line.split('[[')[1]
            if '], 0.0' not in ell_str_temp and '], 90.0' not in ell_str_temp:
                logger.error('Only position angles of 0.0 and 90.0 are supported for CASA '
                              'regions of type "ellipse"')
                sys.exit(1)
            if '], 0.0' in ell_str_temp:
                ell_str = ell_str_temp.split('], 0.0')[0]
                pa = 0
            else:
                ell_str = ell_str_temp.split('], 90.0')[0]
                pa = 90
            ell_str_list = ell_str.split('], [')

            # Ellipse center
            RAstr, Decstr = ell_str_list[0].split(',')
            ra_center = Angle(RAstr, unit='hourangle').to('deg').value
            dec_center = Angle(Decstr.replace('.', ':', 2), unit='deg').to('deg').value

            if image:
                pixels = image.topixel([0, 1, dec_center*np.pi/180.0,
                                        ra_center*np.pi/180.0])
                x_center = pixels[2] # x -> Dec
                y_center = pixels[3] # y -> RA

            elif wcs:
                pixels = wcs.all_world2pix([[ra_center, dec_center]], 0)[0]
                x_center = pixels[0] # x -> Dec
                y_center = pixels[1] # y -> RA

            # Ellipse semimajor and semiminor axes
            a_str, b_str = ell_str_list[1].split(',')
            a_deg = float(a_str.split('arcsec')[0])/3600.0
            b_deg = float(b_str.split('arcsec')[0])/3600.0

            if image:
                pixels1 = image.topixel([0, 1, (dec_center-a_deg/2.0)*np.pi/180.0,
                    ra_center*np.pi/180.0])
                a_pix1 = pixels1[2]
                pixels2 = image.topixel([0, 1, (dec_center+a_deg/2.0)*np.pi/180.0,
                    ra_center*np.pi/180.0])
                a_pix2 = pixels2[2]
            elif wcs:
                pixels1 = wcs.all_world2pix([[ra_center, dec_center-a_deg/2.0]], 0)[0]
                a_pix1 = pixels1[1]
                pixels2 = wcs.all_world2pix([[ra_center, dec_center+a_deg/2.0]], 0)[0]
                a_pix2 = pixels2[1]

            a_pix = abs(a_pix2 - a_pix1)
            ex = []
            ey = []
            for th in range(0, 360, 1):
                if pa == 0:
                    # semimajor axis is along x-axis
                    ex.append(a_pix * np.cos(th * np.pi / 180.0)
                        + x_center) # x -> Dec
                    ey.append(a_pix * b_deg / a_deg * np.sin(th * np.pi / 180.0) + y_center) # y -> RA
                elif pa == 90:
                    # semimajor axis is along y-axis
                    ex.append(a_pix * b_deg / a_deg * np.cos(th * np.pi / 180.0)
                        + x_center) # x -> Dec
                    ey.append(a_pix * np.sin(th * np.pi / 180.0) + y_center) # y -> RA

            polys.append(Polygon(ex, ey))

        elif line.startswith('box'):
            poly_str_temp = line.split('[[')[1]
            poly_str = poly_str_temp.split(']]')[0]
            poly_str_list = poly_str.split('], [')
            ra = []
            dec = []
            for pos in poly_str_list:
                RAstr, Decstr = pos.split(',')
                ra.append(Angle(RAstr, unit='hourangle').to('deg').value)
                dec.append(Angle(Decstr.replace('.', ':', 2), unit='deg').to('deg').value)
            ra.insert(1, ra[0])
            dec.insert(1, dec[1])
            ra.append(ra[2])
            dec.append(dec[0])

            # Convert to image-plane Polygon
            xvert = []
            yvert = []
            for RAvert, Decvert in zip(np.array(ra), np.array(dec)):

                if image:
                    try:
                        pixels = image.topixel([0, 1, Decvert*np.pi/180.0,
                                                RAvert*np.pi/180.0])
                    except:
                        pixels = image.topixel([1, 1, Decvert*np.pi/180.0,
                                                RAvert*np.pi/180.0])
                    xvert.append(pixels[2]) # x -> Dec
                    yvert.append(pixels[3]) # y -> RA

                elif wcs:
                    pixels = wcs.all_world2pix([[RAvert, Decvert]], 0)[0]
                    xvert.append(pixels[0])
                    yvert.append(pixels[1])

            polys.append(Polygon(xvert, yvert))

        elif line.startswith('#'):
            pass

        else:
            logger.error('Only CASA regions of type "poly", "box", or "ellipse" are supported')
            sys.exit(1)

    return polys

def remove_nans(contours, indx=0):
    """
    Removes NaN elements from a contour list produced with get_contours().
    """

    mask = np.isnan(contours[indx][:,0])
    contours[indx] = contours[indx][~mask]

    return contours

def sector_mask(shape, centre, radius, angle_range):
    """
    Return a boolean mask for a circular sector. The start/stop angles in
    `angle_range` should be given in clockwise order.
    """

    x,y = np.ogrid[:shape[0],:shape[1]]
    cx,cy = centre
    tmin,tmax = np.deg2rad(angle_range)

    # ensure stop angle > start angle
    if tmax < tmin:
            tmax += 2*np.pi

    # convert cartesian --> polar coordinates
    r2 = (x-cx)*(x-cx) + (y-cy)*(y-cy)
    theta = np.arctan2(x-cx, y-cy) - tmin

    # wrap angles between 0 and 2*pi
    theta %= (2*np.pi)

    # circular mask
    circmask = r2 <= radius*radius

    # angular mask
    anglemask = theta <= (tmax-tmin)

    return circmask*anglemask

def set_tick_bkgd(ax, color, lw, alpha):
    """
    Applies a contour of color to the tick labels of ax.
    """

    labs = ax.cax.get_yaxis().get_ticklabels()
    for lab in labs:
        lab.set_path_effects([withStroke(foreground=color, linewidth=lw)])
        lab.set_alpha(alpha)

def set_wcs(head):
    """
    Build a WCS object given the
    spatial header parameters.
    """

    # Create a new WCS object.
    # The number of axes must be set from the start.
    w = wcs.WCS(naxis=2)

    w.wcs.crpix = [head['CRPIX1'], head['CRPIX2']]
    w.wcs.cdelt = [head['CDELT1'], head['CDELT2']]
    w.wcs.crval = [head['CRVAL1'], head['CRVAL2']]
    w.wcs.ctype = [head['CTYPE1'], head['CTYPE2']]

    return w