text:
title: Switching to Ubuntu MATE 16.10 - first impressions
date: 2017-04-05 00:00:00 Z
permalink: "/ubuntu-mate-16-10-first-impressions/"
excerpt: It's been just over 72 hours since I switched to Ubuntu MATE 16.10 from Fedora
  and I have to say it's been a pleasant experience thus far
teaser: ubuntu-mate.png
---

It's been just over 72 hours since I switched to Ubuntu MATE 16.10 after spending close to one year on Fedora. Overall, Fedora was pretty good, but I started experiencing problems when I changed my hardware two months ago.

At first, I could live with the odd GNOME crash, because they were few and far between, and it would usually restart itself after a few seconds. Recently though, the crashes became fairly regular and more disruptive. It wasn't uncommon for me to attempt restarting GNOME from the virtual terminal which didn't always work.

I reinstalled twice or so to see if that would fix the problem but the crashes persisted so I felt it was time for me to break up with GNOME and try something else.

While I'm comfortable with Fedora Workstation, I do not like any of the other spins because they do not appear to be 1st-class citizens for their respective desktops.

My reasoning was that, if I'm going to switch to another desktop environment, I might as well use the distro that provided the best support for that desktop.

Choosing a new desktop environment was hard for me. I was strongly inclined to try something completely new so I decided to go with the MATE desktop (and Ubuntu MATE) which I only had a passing familiarity with prior to this moment.

Installing Ubuntu MATE was a pleasant experience despite the fact that I had to do it twice before grub installed properly. Within a short amount of time, everything was done and I was able to boot into my shiny new desktop.

It took me a few hours to set things up the way I like, which was a painful reminder that I need to setup a post-install script of some sort to do the work for me in these situations.

I just want to put down my initial impressions about this distribution, especially the desktop environment, after using it for a little over three days.

## Interface & Customization

By default, Ubuntu MATE is setup to have two panels, one at the top of the screen and the other at the bottom, much like the old GNOME 2 interface which it was forked from.

I generally don't stick with the defaults so I explored the settings to see what other options were available.

After trying a few things, I settled for the "Redmond" layout with a single bottom panel, much like you will find on a Windows 7 or 10 desktop.

I also changed the default wallpaper and placed some icons on my desktop so that unless one looks really closely, you could be forgiven for thinking I was using Windows with a custom theme.

My desktop

This should reduce some of the "what OS is this?" questions I get when working in a public place, such as my university.

Finally, I changed the icon set to a combination of [Arc](https://github.com/horst3180/arc-icon-theme) and [Papirus](https://github.com/PapirusDevelopmentTeam/papirus-icon-theme) icon theme but I'm keeping the default GTK theme for now.

## Software

I was happy to see that many useful applications were installed by default. Thunderbird, Firefox, LibreOffice, Rhythmbox and Transmission are some of the notable ones.

Surprisingly, VLC was present in the default collection which meant that I could actually watch some videos. This is unlike in Fedora and stock Ubuntu, both of which ship a perfectly useless video player, Totem, that does jack squat until you hunt down and install multimedia codecs.

Many (all?) of the core applications are forks of the old GNOME 2 components: Caja was forked from Nautilus, Eye of MATE from Eye of GNOME, Atril from Evince, and Pluma from Gedit so they felt really familiar to me.

Ubuntu MATE also provides a software boutique where you can find and install from a selection of popular software choices. My understanding is that the software boutique is not meant to provide all the applications available in the repositories, only a select few.

Naturally, I installed most of the programs I use from the terminal, but I did find some good stuff on the software boutique and I didn't experience any problems using it.

## Performance

It's hard to gauge the long-term performance of a distribution after only using it for around 72 hours but my initial impressions are very good.

As I expected, the MATE desktop takes up only a small amount of RAM which means I can distribute my 8GB of RAM more generously across the apps I use.

Everything is really fast and responsive unlike GNOME which can get sluggish sometimes. Absolutely zero crashes!

I was able to mount my Android phone successfully, and play music off it using Rhythmbox. All my peripherals, such as my wireless mouse and external drives worked flawlessly.

I haven't tried bluetooth yet, but I won't hold my breath.

## Issues

I don't have much to complain about in my three days with this distribution except that some apps have refused to open since I installed them.

This includes Anki, [Cryptomator](https://cryptomator.org/) and gPodder. When I try to launch them from the terminal, I get different errors for each app.

I haven't gotten around to finding out what's causing these errors but I reckon they should not be too hard to fix.

The other (minor) annoyance is that I get notifications about some internal error from time to time, but I don't notice any side effects whatsoever.

These error messages mean nothing for the most part

It's quite odd to see a Debian logo on the error dialog though, isn't it?

## What's next

Ubuntu MATE 17.04 is scheduled to be released within the next week and I plan to upgrade to that not long after its out.

I should have another post by the end of the month looking at the upgrade process and all the updates in the new release.

You should subscribe to my [RSS feed](https://ayoisaiah.com/feed) so you don't miss that.


text:
labels:
summary: 'Module enabling "on-hold" functionality'
...

Introduction
============

Enable mod\_onhold to allow temporarily placing messages from particular
JIDs "on hold" -- i.e. store them, but do not deliver them until the
hold status is taken away.

Details
=======

Right now, it is configured through adding JIDs to a list in
prosody.cfg.lua. Eventually, more dynamically configurable support will
be added (i.e. with ad-hoc commands or some such thing).

Simply enable mod\_onhold in your list of modules, and then add a line:

onhold\_jids = { "someone@address.com", "someoneelse@address2.com" }

Until those JIDs are removed, messages from those JIDs will not be
delivered. Once they are removed and prosody is restarted, they will be
delivered the next time the user to which they are directed logs on.

redpajama_set_name: RedPajamaGithub


text:
from wasabi import Printer

from .. import tags_to_entities
from ...training import iob_to_biluo
from ...tokens import Doc, Span
from ...errors import Errors
from ...util import load_model, get_lang_class

def conll_ner_to_docs(
    input_data, n_sents=10, seg_sents=False, model=None, no_print=False, **kwargs
):
    """
    Convert files in the CoNLL-2003 NER format and similar
    whitespace-separated columns into Doc objects.

    The first column is the tokens, the final column is the IOB tags. If an
    additional second column is present, the second column is the tags.

    Sentences are separated with whitespace and documents can be separated
    using the line "-DOCSTART- -X- O O".

    Sample format:

    -DOCSTART- -X- O O

    I O
    like O
    London B-GPE
    and O
    New B-GPE
    York I-GPE
    City I-GPE
    . O

    """
    msg = Printer(no_print=no_print)
    doc_delimiter = "-DOCSTART- -X- O O"
    # check for existing delimiters, which should be preserved
    if "\n\n" in input_data and seg_sents:
        msg.warn(
            "Sentence boundaries found, automatic sentence segmentation with "
            "`-s` disabled."
        )
        seg_sents = False
    if doc_delimiter in input_data and n_sents:
        msg.warn(
            "Document delimiters found, automatic document segmentation with "
            "`-n` disabled."
        )
        n_sents = 0
    # do document segmentation with existing sentences
    if "\n\n" in input_data and doc_delimiter not in input_data and n_sents:
        n_sents_info(msg, n_sents)
        input_data = segment_docs(input_data, n_sents, doc_delimiter)
    # do sentence segmentation with existing documents
    if "\n\n" not in input_data and doc_delimiter in input_data and seg_sents:
        input_data = segment_sents_and_docs(input_data, 0, "", model=model, msg=msg)
    # do both sentence segmentation and document segmentation according
    # to options
    if "\n\n" not in input_data and doc_delimiter not in input_data:
        # sentence segmentation required for document segmentation
        if n_sents > 0 and not seg_sents:
            msg.warn(
                f"No sentence boundaries found to use with option `-n {n_sents}`. "
                f"Use `-s` to automatically segment sentences or `-n 0` "
                f"to disable."
            )
        else:
            n_sents_info(msg, n_sents)
            input_data = segment_sents_and_docs(
                input_data, n_sents, doc_delimiter, model=model, msg=msg
            )
    # provide warnings for problematic data
    if "\n\n" not in input_data:
        msg.warn(
            "No sentence boundaries found. Use `-s` to automatically segment "
            "sentences."
        )
    if doc_delimiter not in input_data:
        msg.warn(
            "No document delimiters found. Use `-n` to automatically group "
            "sentences into documents."
        )

    if model:
        nlp = load_model(model)
    else:
        nlp = get_lang_class("xx")()
    for conll_doc in input_data.strip().split(doc_delimiter):
        conll_doc = conll_doc.strip()
        if not conll_doc:
            continue
        words = []
        sent_starts = []
        pos_tags = []
        biluo_tags = []
        for conll_sent in conll_doc.split("\n\n"):
            conll_sent = conll_sent.strip()
            if not conll_sent:
                continue
            lines = [line.strip() for line in conll_sent.split("\n") if line.strip()]
            cols = list(zip(*[line.split() for line in lines]))
            if len(cols) < 2:
                raise ValueError(Errors.E903)
            length = len(cols[0])
            words.extend(cols[0])
            sent_starts.extend([True] + [False] * (length - 1))
            biluo_tags.extend(iob_to_biluo(cols[-1]))
            pos_tags.extend(cols[1] if len(cols) > 2 else ["-"] * length)

        doc = Doc(nlp.vocab, words=words)
        for i, token in enumerate(doc):
            token.tag_ = pos_tags[i]
            token.is_sent_start = sent_starts[i]
        entities = tags_to_entities(biluo_tags)
        doc.ents = [Span(doc, start=s, end=e + 1, label=L) for L, s, e in entities]
        yield doc

def segment_sents_and_docs(doc, n_sents, doc_delimiter, model=None, msg=None):
    sentencizer = None
    if model:
        nlp = load_model(model)
        if "parser" in nlp.pipe_names:
            msg.info(f"Segmenting sentences with parser from model '{model}'.")
            sentencizer = nlp.get_pipe("parser")
    if not sentencizer:
        msg.info(
            "Segmenting sentences with sentencizer. (Use `-b model` for "
            "improved parser-based sentence segmentation.)"
        )
        nlp = get_lang_class("xx")()
        sentencizer = nlp.create_pipe("sentencizer")
    lines = doc.strip().split("\n")
    words = [line.strip().split()[0] for line in lines]
    nlpdoc = Doc(nlp.vocab, words=words)
    sentencizer(nlpdoc)
    lines_with_segs = []
    sent_count = 0
    for i, token in enumerate(nlpdoc):
        if token.is_sent_start:
            if n_sents and sent_count % n_sents == 0:
                lines_with_segs.append(doc_delimiter)
            lines_with_segs.append("")
            sent_count += 1
        lines_with_segs.append(lines[i])
    return "\n".join(lines_with_segs)

def segment_docs(input_data, n_sents, doc_delimiter):
    sent_delimiter = "\n\n"
    sents = input_data.split(sent_delimiter)
    docs = [sents[i : i + n_sents] for i in range(0, len(sents), n_sents)]
    input_data = ""
    for doc in docs:
        input_data += sent_delimiter + doc_delimiter
        input_data += sent_delimiter.join(doc)
    return input_data

def n_sents_info(msg, n_sents):
    msg.info(f"Grouping every {n_sents} sentences into a document.")
    if n_sents == 1:
        msg.warn(
            "To generate better training data, you may want to group "
            "sentences into documents with `-n 10`."
        )


text:
<?php

namespace CachetHQ\Cachet\Composers;

use DateTime;
use DateTimeZone;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Arr;

/**
 * This is the timezone locale composer class.
 *
 * @author Joseph Cohen <joe@alt-three.com>
 * @author James Brooks <james@alt-three.com>
 * @author Graham Campbell <graham@alt-three.com>
 */
class TimezoneLocaleComposer
{
    /**
     * The illuminate config instance.
     *
     * @var \Illuminate\Contracts\Config\Repository
     */
    protected $config;

    /**
     * Create a new timezone locale composer.
     *
     * @param \Illuminate\Contracts\Config\Repository $config
     *
     * @return void
     */
    public function __construct(Repository $config)
    {
        $this->config = $config;
    }

    /**
     * Timezones and Locales composer.
     *
     * @param \Illuminate\Contracts\View\View $view
     *
     * @return void
     */
    public function compose(View $view)
    {
        $enabledLangs = $this->config->get('langs');

        $langs = array_map(function ($lang) use ($enabledLangs) {
            $locale = basename($lang);

            return [$locale => Arr::get($enabledLangs, $locale, [
                'name'   => $locale,
                'subset' => null,
            ])];
        }, glob(base_path('resources/lang').'/*'));

        $langs = call_user_func_array('array_merge', $langs);

        $regions = [
            'UTC'        => DateTimeZone::UTC,
            'Africa'     => DateTimeZone::AFRICA,
            'America'    => DateTimeZone::AMERICA,
            'Antarctica' => DateTimeZone::ANTARCTICA,
            'Arctic'     => DateTimeZone::ARCTIC,
            'Asia'       => DateTimeZone::ASIA,
            'Atlantic'   => DateTimeZone::ATLANTIC,
            'Australia'  => DateTimeZone::AUSTRALIA,
            'Europe'     => DateTimeZone::EUROPE,
            'Indian'     => DateTimeZone::INDIAN,
            'Pacific'    => DateTimeZone::PACIFIC,
        ];

        $timezones = [];

        foreach ($regions as $name => $mask) {
            $zones = DateTimeZone::listIdentifiers($mask);

            foreach ($zones as $timezone) {
                // Lets sample the time there right now
                $time = new DateTime(null, new DateTimeZone($timezone));

                if ($timezone !== 'UTC') {
                    // Remove region name and add a sample time
                    $timezones[$name][$timezone] = substr($timezone, strlen($name) + 1).' - '.$time->format('H:i');
                } else {
                    $timezones[$name][$timezone] = 'UTC - '.$time->format('H:i');
                }

                $timezones[$name] = str_replace('_', ' ', $timezones[$name]);
            }
        }

        $view->withTimezones($timezones);
        $view->withLangs($langs);
    }
}


text:
package com.vmware.vim25;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for ArrayOfCustomizationAdapterMapping complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="ArrayOfCustomizationAdapterMapping">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="CustomizationAdapterMapping" type="{urn:vim25}CustomizationAdapterMapping" maxOccurs="unbounded" minOccurs="0"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfCustomizationAdapterMapping", propOrder = {
    "customizationAdapterMapping"
})
public class ArrayOfCustomizationAdapterMapping {

    @XmlElement(name = "CustomizationAdapterMapping")
    protected List<CustomizationAdapterMapping> customizationAdapterMapping;

    /**
     * Gets the value of the customizationAdapterMapping property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the customizationAdapterMapping property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getCustomizationAdapterMapping().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link CustomizationAdapterMapping }
     *
     *
     */
    public List<CustomizationAdapterMapping> getCustomizationAdapterMapping() {
        if (customizationAdapterMapping == null) {
            customizationAdapterMapping = new ArrayList<CustomizationAdapterMapping>();
        }
        return this.customizationAdapterMapping;
    }

}


text:
package org.pocketserver.api;

import org.slf4j.impl.SimpleLogger;

public class TestLogger {

    static {
        System.setProperty(SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "debug");
        System.setProperty(SimpleLogger.SHOW_THREAD_NAME_KEY, "false");
        System.setProperty(SimpleLogger.LEVEL_IN_BRACKETS_KEY, "true");
        System.setProperty(SimpleLogger.SHOW_DATE_TIME_KEY, "false");
    }

    public static void init() {
        /*
         * Do nothing. We just want the static block to be executed.
         */
    }
}


text:
package com.infinityraider.agricraft.plugins.jade;

import com.infinityraider.agricraft.content.irrigation.TileEntityIrrigationChannel;
import com.infinityraider.agricraft.content.irrigation.TileEntityIrrigationComponent;
import com.infinityraider.agricraft.reference.AgriToolTips;
import mcp.mobius.waila.api.BlockAccessor;
import mcp.mobius.waila.api.IComponentProvider;
import mcp.mobius.waila.api.ITooltip;
import mcp.mobius.waila.api.config.IPluginConfig;
import net.minecraft.network.chat.TextComponent;
import net.minecraft.world.level.block.entity.BlockEntity;

public class AgriWailaIrrigationBlockInfoProvider implements IComponentProvider {
    private static final AgriWailaIrrigationBlockInfoProvider INSTANCE = new AgriWailaIrrigationBlockInfoProvider();

    public static AgriWailaIrrigationBlockInfoProvider getInstance() {
        return INSTANCE;
    }

    private AgriWailaIrrigationBlockInfoProvider() {}

    @Override
    public void appendTooltip(ITooltip tooltip, BlockAccessor accessor, IPluginConfig config) {
        BlockEntity tile = accessor.getBlockEntity();
        if(tile instanceof TileEntityIrrigationComponent) {
            if (tile instanceof TileEntityIrrigationChannel) {
                TileEntityIrrigationChannel channel = (TileEntityIrrigationChannel) tile;
                if (channel.hasValve()) {
                    if (channel.isOpen()) {
                        tooltip.add(AgriToolTips.VALVE_INFO_OPEN);
                    } else {
                        tooltip.add(AgriToolTips.VALVE_INFO_CLOSED);
                    }
                }
            }
            TileEntityIrrigationComponent component = (TileEntityIrrigationComponent) tile;
            tooltip.add(new TextComponent(component.getContent() + " / " + component.getCapacity() + " mB"));
        }
    }
}


text:
/*
 *
 *
 */

const Discord = require('discord.js')
const Commando = require('discord.js-commando')
const Logger = require('../../logger')

class TestCommand extends Commando.Command {
  constructor (client) {
    super(client, {
      name: 'test',
      memberName: 'test',
      group: 'test',
      description: 'Testcommand',
      examples: [ 'test' ]
    })
  }

  async run (message, args) {
    // let channel = message.channel
    // let webhooks = await channel.fetchWebhooks()
    // console.log(webhooks)

    // const hook = new Discord.WebhookClient('392686247358889984', 'oFrYehI-cZH3L4co8C2xyBOTWmTqPyZ2zP9R81EL4Od7SEEAVDZdXB6Wc_GULc3ooYII')
    // hook.send('I am now alive!')

    console.log('---- Test finished ----')
  }
}

module.exports = TestCommand


text:
require 'abstract_unit'
require "fixtures/person"
require "fixtures/street_address"

class FormatTest < Test::Unit::TestCase
  def setup
    @matz  = { :id => 1, :name => 'Matz' }
    @david = { :id => 2, :name => 'David' }

    @programmers = [ @matz, @david ]
  end

  def test_http_format_header_name
    header_name = ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:get]
    assert_equal 'Accept', header_name

    headers_names = [ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:put], ActiveResource::Connection::HTTP_FORMAT_HEADER_NAMES[:post]]
    headers_names.each{ |name| assert_equal 'Content-Type', name }
  end

  def test_formats_on_single_element
    for format in [ :json, :xml ]
      using_format(Person, format) do
        ActiveResource::HttpMock.respond_to.get "/people/1.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david)
        assert_equal @david[:name], Person.find(1).name
      end
    end
  end

  def test_formats_on_collection
    for format in [ :json, :xml ]
      using_format(Person, format) do
        ActiveResource::HttpMock.respond_to.get "/people.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@programmers)
        remote_programmers = Person.find(:all)
        assert_equal 2, remote_programmers.size
        assert remote_programmers.select { |p| p.name == 'David' }
      end
    end
  end

  def test_formats_on_custom_collection_method
    for format in [ :json, :xml ]
      using_format(Person, format) do
        ActiveResource::HttpMock.respond_to.get "/people/retrieve.#{format}?name=David", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode([@david])
        remote_programmers = Person.get(:retrieve, :name => 'David')
        assert_equal 1, remote_programmers.size
        assert_equal @david[:id], remote_programmers[0]['id']
        assert_equal @david[:name], remote_programmers[0]['name']
      end
    end
  end

  def test_formats_on_custom_element_method
    for format in [ :json, :xml ]
      using_format(Person, format) do
        ActiveResource::HttpMock.respond_to do |mock|
          mock.get "/people/2.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david)
          mock.get "/people/2/shallow.#{format}", {'Accept' => ActiveResource::Formats[format].mime_type}, ActiveResource::Formats[format].encode(@david)
        end
        remote_programmer = Person.find(2).get(:shallow)
        assert_equal @david[:id], remote_programmer['id']
        assert_equal @david[:name], remote_programmer['name']
      end
    end

    for format in [ :json, :xml ]
      ryan = ActiveResource::Formats[format].encode({ :name => 'Ryan' })
      using_format(Person, format) do
        remote_ryan = Person.new(:name => 'Ryan')
        ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"}
        remote_ryan.save

        remote_ryan = Person.new(:name => 'Ryan')
        ActiveResource::HttpMock.respond_to.post "/people/new/register.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, ryan, 201, {'Location' => "/people/5.#{format}"}
        assert_equal ActiveResource::Response.new(ryan, 201, {'Location' => "/people/5.#{format}"}), remote_ryan.post(:register)
      end
    end
  end

  def test_setting_format_before_site
    resource = Class.new(ActiveResource::Base)
    resource.format = :json
    resource.site   = 'http://37s.sunrise.i:3000'
    assert_equal ActiveResource::Formats[:json], resource.connection.format
  end

  def test_serialization_of_nested_resource
    address  = { :street => '12345 Street' }
    person  = { :name=> 'Rus', :address => address}

    [:json, :xml].each do |format|
      encoded_person = ActiveResource::Formats[format].encode(person)
      assert_match(/12345 Street/, encoded_person)
      remote_person = Person.new(person.update({:address => StreetAddress.new(address)}))
      assert_kind_of StreetAddress, remote_person.address
      using_format(Person, format) do
        ActiveResource::HttpMock.respond_to.post "/people.#{format}", {'Content-Type' => ActiveResource::Formats[format].mime_type}, encoded_person, 201, {'Location' => "/people/5.#{format}"}
        remote_person.save
      end
    end
  end

  private
    def using_format(klass, mime_type_reference)
      previous_format = klass.format
      klass.format = mime_type_reference

      yield
    ensure
      klass.format = previous_format
    end
end


text:
extern crate anybar;

#[cfg(test)]
mod colorset {
    use anybar::*;

    // Integration test to test functionality
    #[test]
    fn set_color() {
        let mut anyb = Anybar::default();

        anyb.set_color(Color::White).unwrap();
    }
}


text:
/*
 *  Written for the Pkcs11Interop project by:
 *  Jaroslav IMRICH <jimrich@jimrich.sk>
 */

using System;

// Note: Code in this file is maintained manually.

namespace Net.Pkcs11Interop.HighLevelAPI.MechanismParams
{
    /// <summary>
    /// Parameters for the CKM_KEA_DERIVE mechanism
    /// </summary>
    public interface ICkKeaDeriveParams : IMechanismParams
    {

    }
}


text:
<?php
namespace ChristianBudde\Part\util\traits;
/**
 * User: budde
 * Date: 10/27/12
 * Time: 11:31 AM
 */
trait RequestTrait
{

    protected function URLFromGET()
    {
        return '?' . http_build_query($_GET);
    }

    protected function URLWithoutVariableFromGET($variable)
    {
        $getAr = $_GET;
        unset($getAr[$variable]);
        return '?' . http_build_query($getAr);
    }

    protected function GETValueOfIndexIfSetElseDefault($index, $default = null)
    {
        return isset($_GET[$index]) ? $_GET[$index] : $default;
    }

    protected function POSTValueOfIndexIfSetElseDefault($index, $default = null)
    {
        return isset($_POST[$index]) ? $_POST[$index] : $default;
    }

    protected function COOKIEValueOfIndexIfSetElseDefault($index, $default = null)
    {
        return isset($_COOKIE[$index]) ? $_COOKIE[$index] : $default;
    }

    protected function SESSIONValueOfIndexIfSetElseDefault($index, $default = null)
    {
        return isset($_SESSION[$index]) ? $_SESSION[$index] : $default;
    }
}


text:
package com.hp.ov.sdk.dto.rack;

public enum RackMountLocation {
    CenterBack, CenterFront, Left, Right
}


text:
module Heatmap {
    'use strict';

    import Feature       = csComp.Services.Feature;
    import IFeature      = csComp.Services.IFeature;
    import IFeatureType  = csComp.Services.IFeatureType;
    import IPropertyType = csComp.Services.IPropertyType;

    export interface IHeatmapScope extends ng.IScope {
        vm: HeatmapCtrl;
        ratingStates: any;
        projLayer: csComp.Services.ProjectLayer;
    }

    declare var String;//: csComp.StringExt.IStringExt;

    export class HeatmapCtrl {
        private static confirmationMsg1: string;
        private static confirmationMsg2: string;
        heatmap        : L.GeoJSON = L.geoJson([]);
        heatmapModel   : HeatmapModel;
        heatmapModels  : HeatmapModel[] = [];
        heatmapSettings: IHeatmapSettings;
        expertMode     : boolean = true;
        moveListenerInitialized: boolean = false;
        projLayer = new csComp.Services.ProjectLayer();

        selectedFeature: IFeature;
        properties     : FeatureProps.CallOutProperty[];
        showFeature    : boolean;
        showChart      : boolean;
        featureIcon    : string;

        static $inject = [
          '$scope',
          '$modal',
          '$translate',
          '$timeout',
          'localStorageService',
          'layerService',
          'mapService',
          'messageBusService'
        ];

        constructor(
          private $scope              : IHeatmapScope,
          private $modal              : any,
          private $translate          : ng.translate.ITranslateService,
          private $timeout            : ng.ITimeoutService,
          private $localStorageService: angular.local.storage.ILocalStorageService<any>,
          private $layerService       : csComp.Services.LayerService,
          private $mapService         : csComp.Services.MapService,
          private messageBusService   : csComp.Services.MessageBusService
        ) {
          $scope.vm = this;

          messageBusService.subscribe('layer',(title, layer) => {//, layer: csComp.Services.ProjectLayer) => {
              switch (title) {
                  case 'deactivate':
                      /* For an explanation to the removing of layers, see the bottom of this file */
                      if (layer.type && layer.type === "heatmap" && layer.id === this.projLayer.id && layer != this.projLayer) {
                          this.$layerService.removeLayer(this.projLayer);
                          delete (this.heatmapModel);
                          this.initializeHeatmap();
                      }
                      break;
                  case 'activated':
                      if (layer.type && layer.type === "heatmap") this.updateAvailableHeatmaps();
                      if (layer.type && layer.type === "geojson") {
                          // When the final, required feature layer is loaded, update the heatmap
                          if (this.heatmapModel && this.heatmapModel.heatmapSettings.referenceList.length > 0) {
                              if (layer.reference && layer.reference == this.heatmapModel.heatmapSettings.referenceList[this.heatmapModel.heatmapSettings.referenceList.length - 1]) {
                                  this.updateHeatmap();
                              }
                          }
                      }
                      //this.updateHeatmap();
                      break;
              }
          });

          messageBusService.subscribe('project',(title) => {//, layer: csComp.Services.ProjectLayer) => {
              switch (title) {
                  case 'loaded':
                      this.expertMode = $layerService.project != null
                      && $layerService.project.hasOwnProperty('userPrivileges')
                      && $layerService.project.userPrivileges.hasOwnProperty('heatmap')
                      && $layerService.project.userPrivileges.heatmap.hasOwnProperty('expertMode')
                      && $layerService.project.userPrivileges.heatmap.expertMode;

                      this.updateAvailableHeatmaps();

                      this.initializeHeatmap();
                      break;
              }
          });

          /*messageBusService.subscribe('feature', this.featureMessageReceived);*/

          $translate('HEATMAP.DELETE_MSG').then(translation => {
              HeatmapCtrl.confirmationMsg1 = translation;
          });
          $translate('HEATMAP.DELETE_MSG2').then(translation => {
              HeatmapCtrl.confirmationMsg2 = translation;
          });
        }

        updateAvailableHeatmaps() {
            if (!this.heatmapModel) {
                this.heatmapModels = [];
                if (this.$layerService.project.groups) {
                    this.$layerService.project.groups.forEach((group) => {
                        group.layers.forEach((layer) => {
                            if (layer.type === "heatmap") {
                                var hm = new HeatmapModel(layer.title);
                                hm.deserialize(layer);
                                this.heatmapModels.push(hm);
                                if (layer.enabled) this.heatmapModel = hm;
                            }
                        });
                    });
                }
            } else {
                for (var index = 0; index < this.heatmapModels.length; index++) {
                    if (this.heatmapModel.id == this.heatmapModels[index].id) {
                        this.heatmapModels.splice(index, 1);
                        break;
                    }
                }
                this.heatmapModels.push(this.heatmapModel);
            }
        }

        createHeatmap() {
            this.heatmapModel = new HeatmapModel('Heatmap');
            if (this.projLayer.data) this.$layerService.removeLayer(this.projLayer);
            //Create projectlayer for the heatmap
            this.projLayer.type = "heatmap";
            this.projLayer.layerRenderer = "heatmap";
            this.projLayer.enabled = true;
            this.projLayer.group = new csComp.Services.ProjectGroup();
            this.projLayer.group.oneLayerActive = true;
            this.projLayer.group.layers = [];
            this.projLayer.group.filters = [];
            this.projLayer.group.styles = [];
            this.projLayer.group.markers = [];
            this.projLayer.heatmapSettings = new HeatmapSettings();
            this.projLayer.heatmapItems = [];
            this.projLayer.id = csComp.Helpers.getGuid();
            this.projLayer.quickRefresh = false;
            this.heatmap = L.geoJson([]);
            this.showHeatmapEditor(this.heatmapModel);
            //this.$layerService.addLayer(this.projLayer);
        }

        editHeatmap(heatmap: HeatmapModel) {
            this.showHeatmapEditor(heatmap);
        }

        exportHeatmap(heatmap: HeatmapModel) {
            /* Add active feature layer reference to the referencelist (TODO: find reference layer through enabled features) */
            this.heatmapModel.heatmapSettings.referenceList = [];
            this.heatmapModel.heatmapItems.forEach((hi) => {
                if (hi.isSelected) {
                    this.$layerService.project.groups.forEach((group) => {
                        if (group.title == "Features") {
                            group.layers.forEach((l) => {
                                if (l.enabled) {
                                    this.heatmapModel.heatmapSettings.addReference(l.reference);
                                }
                            });
                        }
                    });
                }
            });

            /* Print the heatmap settings to the console in json format */
            console.log("\n-----------------\n" + "Exported heatmap starts here: \n");
            console.log(heatmap.serialize());
            console.log("\n-----------------\n" + "Exported heatmap ends here. \n");
            this.messageBusService.notify('Heatmap exported successfully', 'Your heatmap was exported to the console successfully.', csComp.Services.NotifyLocation.TopLeft);
        }

        removeHeatmap(heatmap: HeatmapModel) {
            if (!heatmap) return;
            var title = String.format(HeatmapCtrl.confirmationMsg1, heatmap.title);
            this.messageBusService.confirm(title, HeatmapCtrl.confirmationMsg2,(result) => {
                if (!result) return;
                this.$timeout(() => {
                    this.deleteHeatmap(heatmap);
                    this.updateAvailableHeatmaps();
                    //if (this.heatmap) this.updateHeatmap();
                    //if (this.heatmap) this.$mapService.map.removeLayer(this.heatmap);
                }, 0);
            });
            this.scopeApply();
        }

        private deleteHeatmap(heatmap: HeatmapModel) {
            if (!heatmap) return;
            var index = this.heatmapModels.indexOf(heatmap);
            if (index >= 0) this.heatmapModels.splice(index, 1);
            this.$layerService.removeLayer(this.projLayer);
            // If the current heatmaplayer was a projectlayer, disable that one too
            if (this.$layerService.project.groups) {
                this.$layerService.project.groups.forEach((group) => {
                    group.layers.forEach((layer) => {
                        if (layer.type === "heatmap" && layer.id === this.projLayer.id) {
                            this.$layerService.removeLayer(layer);
                        }
                    });
                });
            }

            delete (this.heatmapModel);
            delete (this.projLayer);
            this.projLayer = new csComp.Services.ProjectLayer();
            this.initializeHeatmap();
        }

        /**
         * Show the heat map editor in a modal.
         */
        private showHeatmapEditor(heatmap: HeatmapModel): void {
            var modalInstance = this.$modal.open({
                templateUrl: 'directives/Heatmap/HeatmapEditorView.tpl.html',
                controller: HeatmapEditorCtrl,
                resolve: {
                    heatmap: () => heatmap
                }
            });
            modalInstance.result.then((heatmap: HeatmapModel) => {
                this.heatmapModel = heatmap;
                var i = this.heatmapModels.indexOf(heatmap);
                if (i >= 0) this.heatmapModels.splice(i, 1);
                this.heatmapModels.push(heatmap);
                this.updateHeatmap();
                console.log('Updated heatmap');
            }, () => {
                    console.log('Modal dismissed at: ' + new Date());
                    delete (this.heatmapModel);
            });
        }

        private scopeApply() {
            if (this.$scope.$root.$$phase !== '$apply' && this.$scope.$root.$$phase !== '$digest') {
                this.$scope.$apply();
            }
        }

        getVotingClass(hi: IHeatmapItem) {
            if (hi == null || this.heatmapModel == null || hi.userWeight === 0 || hi.userWeight < -5 || hi.userWeight > 5)
                return 'disabledHeatmap';
            return hi.userWeight > 0 ? 'prefer' : 'avoid';
        }

        weightUpdated() {
            if (!this.heatmapModel) return;
            this.heatmapModel.updateWeights();
            this.projLayer.quickRefresh = true;
            this.$layerService.addLayer(this.projLayer);
        }

        intensityScaleUpdated() {
            if (!this.heatmapModel) return;
            //this.heatmapModel.updateWeights();
            //this.updateHeatmap();
            this.updateHeatmapWithoutRerendering();
        }

        resolutionUpdated() {
            if (!this.heatmapModel) return;
            this.updateHeatmap();
        }

        private updateHeatmapWithoutRerendering() {
            this.projLayer.quickRefresh = true;
            this.$layerService.addLayer(this.projLayer);
        }

        /**
         * Update the available pre-set heatmaps.
         */
        private updateHeatmap() {
            if (this.heatmapModel) {
                // If the current heatmapmodel comes from a projectlayer, disable that layer
                if (this.$layerService.project.groups) {
                    this.$layerService.project.groups.forEach((group) => {
                        group.layers.forEach((layer) => {
                            if (layer.type === "heatmap" && layer.id === this.heatmapModel.id && layer.mapLayer) {
                                this.$layerService.map.map.removeLayer(layer.mapLayer);
                                layer.enabled = true;
                            }
                        });
                    });
                }
                this.projLayer.quickRefresh = false;
                this.projLayer.heatmapItems = this.heatmapModel.heatmapItems;
                this.projLayer.heatmapSettings = this.heatmapModel.heatmapSettings;
                this.projLayer.id = this.heatmapModel.id;
                var currentZoom = this.$mapService.getMap().getZoom();
                if (currentZoom < this.heatmapModel.heatmapSettings.minZoom || currentZoom > this.heatmapModel.heatmapSettings.maxZoom) {
                    console.log("Heatmap is not supported for the current zoom level.");
                    this.$layerService.loadRequiredLayers(this.projLayer); // Make sure to load the required layers even if heatmap is not yet being drawn
                    return;
                } else {
                    //this.heatmapModel.updateWeights();
                    //this.heatmapModel.calculate(this.$layerService, this.$mapService, this.heatmap);
                    //this.projLayer.data = this.heatmap.toGeoJSON();
                    //(<any>(this.projLayer.data)).features.forEach((f) => {
                    //    this.$layerService.initFeature(f, this.projLayer);
                    //});

                    //// Set default style for the heatmap:
                    //if ((<any>(this.projLayer.data)).features[0]) {
                    //    var calloutProp = new FeatureProps.CallOutProperty("intensity", "0", "intensity", true, true,(<any>(this.projLayer.data)).features[0], false);
                    //    var propinfo = new csComp.Services.PropertyInfo();
                    //    // Tweak the group style info to keep constant min/max color values on panning and zooming.
                    //    propinfo.count = (<any>(this.projLayer.data)).features.length;
                    //    propinfo.max = 1;
                    //    propinfo.min = -1;
                    //    propinfo.sdMax = propinfo.max;
                    //    propinfo.sdMin = propinfo.min;
                    //    propinfo.mean = 0;
                    //    propinfo.varience = 0.67;
                    //    propinfo.sd = Math.sqrt(propinfo.varience);
                    //    this.$layerService.setStyle(calloutProp, false, propinfo); // Set the style
                    // }
                }
                this.$layerService.removeLayer(this.projLayer);
                this.$layerService.addLayer(this.projLayer);
            }
        }

        ///**
        //* Add a heatmap layer to the map.
        //*/
        private initializeHeatmap() {
            this.projLayer.type = "heatmap";
            this.projLayer.layerRenderer = "heatmap";
            this.projLayer.enabled = false;
            this.projLayer.group = new csComp.Services.ProjectGroup();
            this.projLayer.group.oneLayerActive = true;
            this.projLayer.group.layers = [];
            this.projLayer.group.filters = [];
            this.projLayer.group.styles = [];
            this.projLayer.group.markers = [];
            this.projLayer.mapLayer = new L.LayerGroup();
            this.projLayer.heatmapSettings = new HeatmapSettings();
            this.projLayer.heatmapItems = [];
            this.projLayer.data = JSON;
            this.projLayer.id = "";
            this.projLayer.quickRefresh = false;

            if (!this.moveListenerInitialized) {
                this.$layerService.map.map.addEventListener('moveend',(event) => {
                    this.updateHeatmap();
                });
                this.moveListenerInitialized = true;
            }
        }
    }
}

/* Heatmap layers:
 * ---------------
 * Two layers are used for the heatmaps, which are both very similar but different in an important way. The difference
 * lies in the fact that one layer comes directly from the project.json file. This layer is parsed and added to the layerservice
 * directly when it is enabled in the 'Layers' panel. The second layer is 'this.projLayer', which looks almost identical to
 * the parsed projectLayer, but it is generated programmatically. When a new heatmap is created, or a predefined heatmap is edited,
 * this.projLayer will be added to the layerservice. Very importantly, the MoveListener is connected to this.projLayer. That means
 * that every time the map is moved, 'this.projLayer' will contain the current heatmap, even when it was added from project.json.
 * Therefore, when one layer is being disabled, it needs to be checked whether the other layer is present in the layerservice,
 * and if so, it should be removed too.
 */