text:
Using lessc, compile /static/css from the static files available
`cd static/css && lessc style.less > style.min.css`
Minify with your tool of choice

## !! Changes made to this Theme
See [docs/riot.md](/docs/riot.md) for specific instructions around customisations in this Theme

# The Timber Starter Theme

The "_s" for Timber: a dead-simple theme that you can build from. The primary purpose of this theme is to provide a file structure rather than a framework for markup or styles. Configure your Sass, scripts, and task runners however you would like!

[![Build Status](https://travis-ci.org/timber/starter-theme.svg)](https://travis-ci.org/timber/starter-theme)

## Installing the Theme

Install this theme as you would any other, and be sure the Timber plugin is activated. But hey, let's break it down into some bullets:

1. Make sure you have installed the plugin for the [Timber Library](https://wordpress.org/plugins/timber-library/) (and Advanced Custom Fields - they [play quite nicely](https://github.com/jarednova/timber/wiki/ACF-Cookbook) together).
2. Download the zip for this theme (or clone it) and move it to `wp-content/themes` in your WordPress installation.
3. Rename the folder to something that makes sense for your website (generally no spaces and all lowercase). You could keep the name `timber-starter-theme` but the point of a starter theme is to make it your own!
4. Activate the theme in Appearance >  Themes.
5. Do your thing! And read [the docs](https://github.com/jarednova/timber/wiki).

## What's here?

`static/` is where you can keep your static front-end scripts, styles, or images. In other words, your Sass files, JS files, fonts, and SVGs would live here.

`templates/` contains all of your Twig templates. These pretty much correspond 1 to 1 with the PHP files that respond to the WordPress template hierarchy. At the end of each PHP template, you'll notice a `Timber::render()` function whose first parameter is the Twig file where that data (or `$context`) will be used. Just an FYI.

`bin/` and `tests/` ... basically don't worry about (or remove) these unless you know what they are and want to.

## Other Resources

The [main Timber Wiki](https://github.com/jarednova/timber/wiki) is super great, so reference those often. Also, check out these articles and projects for more info:

* [This branch](https://github.com/laras126/timber-starter-theme/tree/tackle-box) of the starter theme has some more example code with ACF and a slightly different set up.
* [Twig for Timber Cheatsheet](http://notlaura.com/the-twig-for-timber-cheatsheet/)
* [Timber and Twig Reignited My Love for WordPress](https://css-tricks.com/timber-and-twig-reignited-my-love-for-wordpress/) on CSS-Tricks
* [A real live Timber theme](https://github.com/laras126/yuling-theme).
* [Timber Video Tutorials](https://github.com/jarednova/timber/wiki/Video-Tutorials) and [an incomplete set of screencasts](https://www.youtube.com/playlist?list=PLuIlodXmVQ6pkqWyR6mtQ5gQZ6BrnuFx-) for building a Timber theme from scratch.

redpajama_set_name: RedPajamaGithub


text:
#define LOG_TAG "BitmapRegionDecoder"

#include "BitmapFactory.h"
#include "CreateJavaOutputStreamAdaptor.h"
#include "GraphicsJNI.h"
#include "Utils.h"

#include "SkBitmap.h"
#include "SkBitmapRegionDecoder.h"
#include "SkCodec.h"
#include "SkData.h"
#include "SkUtils.h"
#include "SkPixelRef.h"
#include "SkStream.h"

#include "android_nio_utils.h"
#include "android_util_Binder.h"
#include "core_jni_helpers.h"

#include <JNIHelp.h>
#include <androidfw/Asset.h>
#include <binder/Parcel.h>
#include <jni.h>
#include <sys/stat.h>

using namespace android;

// Takes ownership of the SkStreamRewindable. For consistency, deletes stream even
// when returning null.
static jobject createBitmapRegionDecoder(JNIEnv* env, SkStreamRewindable* stream) {
    SkAutoTDelete<SkBitmapRegionDecoder> brd(
            SkBitmapRegionDecoder::Create(stream, SkBitmapRegionDecoder::kAndroidCodec_Strategy));
    if (NULL == brd) {
        doThrowIOE(env, "Image format not supported");
        return nullObjectReturn("CreateBitmapRegionDecoder returned null");
    }

    return GraphicsJNI::createBitmapRegionDecoder(env, brd.detach());
}

static jobject nativeNewInstanceFromByteArray(JNIEnv* env, jobject, jbyteArray byteArray,
                                     jint offset, jint length, jboolean isShareable) {
    /*  If isShareable we could decide to just wrap the java array and
        share it, but that means adding a globalref to the java array object
        For now we just always copy the array's data if isShareable.
     */
    AutoJavaByteArray ar(env, byteArray);
    SkMemoryStream* stream = new SkMemoryStream(ar.ptr() + offset, length, true);

    // the decoder owns the stream.
    jobject brd = createBitmapRegionDecoder(env, stream);
    return brd;
}

static jobject nativeNewInstanceFromFileDescriptor(JNIEnv* env, jobject clazz,
                                          jobject fileDescriptor, jboolean isShareable) {
    NPE_CHECK_RETURN_ZERO(env, fileDescriptor);

    jint descriptor = jniGetFDFromFileDescriptor(env, fileDescriptor);

    struct stat fdStat;
    if (fstat(descriptor, &fdStat) == -1) {
        doThrowIOE(env, "broken file descriptor");
        return nullObjectReturn("fstat return -1");
    }

    SkAutoTUnref<SkData> data(SkData::NewFromFD(descriptor));
    SkMemoryStream* stream = new SkMemoryStream(data);

    // the decoder owns the stream.
    jobject brd = createBitmapRegionDecoder(env, stream);
    return brd;
}

static jobject nativeNewInstanceFromStream(JNIEnv* env, jobject clazz,
                                  jobject is,       // InputStream
                                  jbyteArray storage, // byte[]
                                  jboolean isShareable) {
    jobject brd = NULL;
    // for now we don't allow shareable with java inputstreams
    SkStreamRewindable* stream = CopyJavaInputStream(env, is, storage);

    if (stream) {
        // the decoder owns the stream.
        brd = createBitmapRegionDecoder(env, stream);
    }
    return brd;
}

static jobject nativeNewInstanceFromAsset(JNIEnv* env, jobject clazz,
                                 jlong native_asset, // Asset
                                 jboolean isShareable) {
    Asset* asset = reinterpret_cast<Asset*>(native_asset);
    SkMemoryStream* stream = CopyAssetToStream(asset);
    if (NULL == stream) {
        return NULL;
    }

    // the decoder owns the stream.
    jobject brd = createBitmapRegionDecoder(env, stream);
    return brd;
}

/*
 * nine patch not supported
 * purgeable not supported
 * reportSizeToVM not supported
 */
static jobject nativeDecodeRegion(JNIEnv* env, jobject, jlong brdHandle, jint inputX,
        jint inputY, jint inputWidth, jint inputHeight, jobject options) {

    // Set default options.
    int sampleSize = 1;
    SkColorType colorType = kN32_SkColorType;
    bool requireUnpremul = false;
    jobject javaBitmap = NULL;

    // Update the default options with any options supplied by the client.
    if (NULL != options) {
        sampleSize = env->GetIntField(options, gOptions_sampleSizeFieldID);
        jobject jconfig = env->GetObjectField(options, gOptions_configFieldID);
        colorType = GraphicsJNI::getNativeBitmapColorType(env, jconfig);
        requireUnpremul = !env->GetBooleanField(options, gOptions_premultipliedFieldID);
        javaBitmap = env->GetObjectField(options, gOptions_bitmapFieldID);
        // The Java options of ditherMode and preferQualityOverSpeed are deprecated.  We will
        // ignore the values of these fields.

        // Initialize these fields to indicate a failure.  If the decode succeeds, we
        // will update them later on.
        env->SetIntField(options, gOptions_widthFieldID, -1);
        env->SetIntField(options, gOptions_heightFieldID, -1);
        env->SetObjectField(options, gOptions_mimeFieldID, 0);
    }

    // Recycle a bitmap if possible.
    android::Bitmap* recycledBitmap = nullptr;
    size_t recycledBytes = 0;
    if (javaBitmap) {
        recycledBitmap = GraphicsJNI::getBitmap(env, javaBitmap);
        if (recycledBitmap->peekAtPixelRef()->isImmutable()) {
            ALOGW("Warning: Reusing an immutable bitmap as an image decoder target.");
        }
        recycledBytes = GraphicsJNI::getBitmapAllocationByteCount(env, javaBitmap);
    }

    // Set up the pixel allocator
    SkBRDAllocator* allocator = nullptr;
    RecyclingClippingPixelAllocator recycleAlloc(recycledBitmap, recycledBytes);
    JavaPixelAllocator javaAlloc(env);
    if (javaBitmap) {
        allocator = &recycleAlloc;
        // We are required to match the color type of the recycled bitmap.
        colorType = recycledBitmap->info().colorType();
    } else {
        allocator = &javaAlloc;
    }

    // Decode the region.
    SkIRect subset = SkIRect::MakeXYWH(inputX, inputY, inputWidth, inputHeight);
    SkBitmapRegionDecoder* brd =
            reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
    SkBitmap bitmap;
    if (!brd->decodeRegion(&bitmap, allocator, subset, sampleSize, colorType, requireUnpremul)) {
        return nullObjectReturn("Failed to decode region.");
    }

    // If the client provided options, indicate that the decode was successful.
    if (NULL != options) {
        env->SetIntField(options, gOptions_widthFieldID, bitmap.width());
        env->SetIntField(options, gOptions_heightFieldID, bitmap.height());
        env->SetObjectField(options, gOptions_mimeFieldID,
                encodedFormatToString(env, brd->getEncodedFormat()));
        if (env->ExceptionCheck()) {
            return nullObjectReturn("OOM in encodedFormatToString()");
        }
    }

    // If we may have reused a bitmap, we need to indicate that the pixels have changed.
    if (javaBitmap) {
        recycleAlloc.copyIfNecessary();
        return javaBitmap;
    }

    int bitmapCreateFlags = 0;
    if (!requireUnpremul) {
        bitmapCreateFlags |= GraphicsJNI::kBitmapCreateFlag_Premultiplied;
    }
    return GraphicsJNI::createBitmap(env, javaAlloc.getStorageObjAndReset(), bitmapCreateFlags);
}

static jint nativeGetHeight(JNIEnv* env, jobject, jlong brdHandle) {
    SkBitmapRegionDecoder* brd =
            reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
    return static_cast<jint>(brd->height());
}

static jint nativeGetWidth(JNIEnv* env, jobject, jlong brdHandle) {
    SkBitmapRegionDecoder* brd =
            reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
    return static_cast<jint>(brd->width());
}

static void nativeClean(JNIEnv* env, jobject, jlong brdHandle) {
    SkBitmapRegionDecoder* brd =
            reinterpret_cast<SkBitmapRegionDecoder*>(brdHandle);
    delete brd;
}

///////////////////////////////////////////////////////////////////////////////

static const JNINativeMethod gBitmapRegionDecoderMethods[] = {
    {   "nativeDecodeRegion",
        "(JIIIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;",
        (void*)nativeDecodeRegion},

    {   "nativeGetHeight", "(J)I", (void*)nativeGetHeight},

    {   "nativeGetWidth", "(J)I", (void*)nativeGetWidth},

    {   "nativeClean", "(J)V", (void*)nativeClean},

    {   "nativeNewInstance",
        "([BIIZ)Landroid/graphics/BitmapRegionDecoder;",
        (void*)nativeNewInstanceFromByteArray
    },

    {   "nativeNewInstance",
        "(Ljava/io/InputStream;[BZ)Landroid/graphics/BitmapRegionDecoder;",
        (void*)nativeNewInstanceFromStream
    },

    {   "nativeNewInstance",
        "(Ljava/io/FileDescriptor;Z)Landroid/graphics/BitmapRegionDecoder;",
        (void*)nativeNewInstanceFromFileDescriptor
    },

    {   "nativeNewInstance",
        "(JZ)Landroid/graphics/BitmapRegionDecoder;",
        (void*)nativeNewInstanceFromAsset
    },
};

int register_android_graphics_BitmapRegionDecoder(JNIEnv* env)
{
    return android::RegisterMethodsOrDie(env, "android/graphics/BitmapRegionDecoder",
            gBitmapRegionDecoderMethods, NELEM(gBitmapRegionDecoderMethods));
}


text:
var Poem = null;
	var levels = null;
	var EventDispatcher = require('./utils/EventDispatcher');

	var currentLevel = null;
	var currentPoem = null;
	var titleHideTimeout = null;

	function showTitles() {

		$('.score').css('opacity', 0);
		$('.timer').css('opacity', 0);

		clearTimeout( titleHideTimeout );

		$('#title')
			.removeClass('transform-transition')
			.addClass('hide')
			.addClass('transform-transition')
			.show();

		setTimeout(function() {
			$('#title').removeClass('hide');
		}, 8000);

	}

	function hideTitles() {

		$('.score').css('opacity', 0.9);
		$('.timer').css('opacity', 0.9);

		if( $('#title:visible').length > 0 ) {

			$('#title')
				.addClass('transform-transition')
				.addClass('hide');

			titleHideTimeout = setTimeout(function() {

				$('#title').hide();

			}, 1000);
		}
		$('#countdown3')
			.removeClass('hide')
			.removeClass('transform-transition')
			.addClass('transform-transition')
			.show();
		setTimeout(function(){
			$('#countdown3')
			.addClass('transform-transition')
			.addClass('hide');
		}, 750);

		setTimeout(function() {
			$('#countdown2')
			.removeClass('hide')
			.removeClass('transform-transition')
			.addClass('transform-transition')
			.show();
			setTimeout(function(){
				$('#countdown2')
				.addClass('transform-transition')
				.addClass('hide');
			}, 1000);
		}, 1500);
		setTimeout(function() {
			$('#countdownGo')
			.removeClass('hide')
			.removeClass('transform-transition')
			.addClass('transform-transition')
			.show();
			setTimeout(function(){
				$('#countdownGo')
				.addClass('transform-transition')
				.addClass('hide');
			}, 1250);
		}, 4500);

	}

	var levelLoader = {

	init : function( PoemClass, levelsObject ) {
		Poem = PoemClass;
		levels = levelsObject;
	},

	load : function( slug ) {

		if( !_.isObject(levels[slug]) ) {
			return false;
		}

		if(currentPoem) currentPoem.destroy();

		currentLevel = levels[slug];
		currentPoem = new Poem( currentLevel, slug );

		if( slug === "menu" ) {
			showTitles();
		} else {
			hideTitles();
		}

		this.dispatch({
			type: "newLevel",
			level: currentLevel,
			poem: currentPoem
		});

		window.poem = currentPoem;

		this.isFirefox = typeof InstallTrigger !== 'undefined';
		if (this.isFirefox) {
			$('.title-firefox').show();
			currentPoem.pause();
		}

		return true;
	}

	};


text:
package org.apache.pdfbox.examples.signature;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;

import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;

public abstract class CreateSignatureBase implements SignatureInterface
{
    private PrivateKey privateKey;
    private Certificate[] certificateChain;
    private String tsaUrl;
    private boolean externalSigning;

    /**
     * Initialize the signature creator with a keystore (pkcs12) and pin that should be used for the
     * signature.
     *
     * @param keystore is a pkcs12 keystore.
     * @param pin is the pin for the keystore / private key
     * @throws KeyStoreException if the keystore has not been initialized (loaded)
     * @throws NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
     * @throws UnrecoverableKeyException if the given password is wrong
     * @throws CertificateException if the certificate is not valid as signing time
     * @throws IOException if no certificate could be found
     */
    public CreateSignatureBase(KeyStore keystore, char[] pin)
            throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, CertificateException
    {
        // grabs the first alias from the keystore and get the private key. An
        // alternative method or constructor could be used for setting a specific
        // alias that should be used.
        Enumeration<String> aliases = keystore.aliases();
        String alias;
        Certificate cert = null;
        while (cert == null && aliases.hasMoreElements())
        {
            alias = aliases.nextElement();
            setPrivateKey((PrivateKey) keystore.getKey(alias, pin));
            Certificate[] certChain = keystore.getCertificateChain(alias);
            if (certChain != null)
            {
                setCertificateChain(certChain);
                cert = certChain[0];
                if (cert instanceof X509Certificate)
                {
                    // avoid expired certificate
                    ((X509Certificate) cert).checkValidity();

                    SigUtils.checkCertificateUsage((X509Certificate) cert);
                }
            }
        }

        if (cert == null)
        {
            throw new IOException("Could not find certificate");
        }
    }

    public final void setPrivateKey(PrivateKey privateKey)
    {
        this.privateKey = privateKey;
    }

    public final void setCertificateChain(final Certificate[] certificateChain)
    {
        this.certificateChain = certificateChain;
    }

    public Certificate[] getCertificateChain()
    {
        return certificateChain;
    }

    public void setTsaUrl(String tsaUrl)
    {
        this.tsaUrl = tsaUrl;
    }

    /**
     * SignatureInterface sample implementation.
     *

     * This method will be called from inside of the pdfbox and create the PKCS #7 signature.
     * The given InputStream contains the bytes that are given by the byte range.
     *

     * This method is for internal use only.
     *

     * Use your favorite cryptographic library to implement PKCS #7 signature creation.
     * If you want to create the hash and the signature separately (e.g. to transfer only the hash
     * to an external application), read this
     * answer or this answer.
     *
     * @throws IOException
     */
    @Override
    public byte[] sign(InputStream content) throws IOException
    {
        // cannot be done private (interface)
        try
        {
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
            X509Certificate cert = (X509Certificate) certificateChain[0];
            ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
            gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(sha1Signer, cert));
            gen.addCertificates(new JcaCertStore(Arrays.asList(certificateChain)));
            CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
            CMSSignedData signedData = gen.generate(msg, false);
            if (tsaUrl != null && tsaUrl.length() > 0)
            {
                ValidationTimeStamp validation = new ValidationTimeStamp(tsaUrl);
                signedData = validation.addSignedTimeStamp(signedData);
            }
            return signedData.getEncoded();
        }
        catch (GeneralSecurityException | CMSException | OperatorCreationException e)
        {
            throw new IOException(e);
        }
    }

    /**
     * Set if external signing scenario should be used.
     * If {@code false}, SignatureInterface would be used for signing.
     *

     *     Default: {@code false}
     *

     * @param externalSigning {@code true} if external signing should be performed
     */
    public void setExternalSigning(boolean externalSigning)
    {
        this.externalSigning = externalSigning;
    }

    public boolean isExternalSigning()
    {
        return externalSigning;
    }
}


text:
resources :profiles
resources :shared_objects
resources :homepages

resources :streams, :only => [:index, :show], :member => {:network => :get}

with_options(:controller => 'groups') do |group|
  group.tag_groups       '/groups/tag/:tag',                         :action => 'tag'
end

resources :groups, :collection => { :search => :get }, :member => { :join => :get, :leave => :get, :accept_invitation => :get, :reject_invitation => :get }

namespace(:member) do |member|
  member.resources :profiles
  member.resources :groups
  member.resources :shared_objects
  member.with_options(:controller => 'groups') do |group|
    group.group_pending_members '/:id/members/pending',         :action => 'pending_members'
    group.group_accept_member   '/:id/members/:user_id/accept', :action => 'accept_member'
    group.group_reject_member   '/:id/members/:user_id/reject', :action => 'reject_member'
    group.group_invite          '/group/invite',                :action => 'invite'
  end
  member.with_options(:controller => 'friendships') do |friendship|
    friendship.add_friend     '/friend/:friend_id/add',     :action => 'add_friend'
    friendship.confirm_friend '/friend/:friend_id/confirm', :action => 'confirm_friend'
    friendship.follow_user    '/follow/:friend_id',         :action => 'follow'
    friendship.unfollow_user  '/unfollow/:friend_id',       :action => 'unfollow'
  end
  member.with_options(:controller => 'sharings') do |sharing|
    sharing.share '/sharings/share/:group_id/:shareable_type/:shareable_id', :action => 'create', :conditions => { :method => :post }
    sharing.new_sharing '/sharings/:shareable_type/:shareable_id/new', :action => 'new'
    sharing.sharings '/sharings', :action => 'index'
    sharing.destroy_sharing '/sharings/:group_id/:id', :action => 'destroy', :conditions => { :method => :delete }
#    sharing.destroy_sharing '/group/:id/remove/:shareable_type/:shareable_id', :action => 'destroy', :method => :delete
  end
  member.with_options(:controller => 'shared_objects') do |shared_object|
     shared_object.new_shared_object '/:group_id/shared_objects/new', :action =>'new'
     shared_object.create_shared_object '/shared_objects/:group_id', :action =>'create', :conditions => { :method => :post}
     shared_object.update_shared_object '/shared_objects/:id', :action => 'update', :conditions => { :method => :put }
     shared_object.delete_shared_object '/:group_id/shared_objects/:id/delete/:mode', :action => 'delete', :conditions => {:method => :post}
     shared_object.destroy_shared_object '/:group_id/shared_objects/:id/destroy/:mode', :action => 'destroy', :conditions => {:method => :delete}
     shared_object.publish_shared_object '/shared_objects/:id/publish', :action => 'publish'
     shared_object.approve_sharing '/sharings/:id/approve', :action => 'approve'
     shared_object.share_existing_shared_object '/shared_objects/:id/share', :action =>'share'
  end
end

namespace(:admin) do |admin|
  admin.resources :groups, :member => { :activate => :post}
end

# => oauth support
resources :oauth_clients
authorize     '/oauth/authorize',     :controller=>'oauth', :action=>'authorize'
request_token '/oauth/request_token', :controller=>'oauth', :action=>'request_token'
access_token  '/oauth/access_token',  :controller=>'oauth', :action=>'access_token'
test_request  '/oauth/test_request',  :controller=>'oauth', :action=>'test_request'

x1 '/oauth_test',     :controller=>'oauth_test', :action=>'test'
x2 '/oauth_callback', :controller=>'oauth_test', :action=>'callback'
# => oauth support


text:
import { uniques, flatten, adUnitsFilter, getBidderRequest } from './utils';
import {getPriceBucketString} from './cpmBucketManager';
import {NATIVE_KEYS, nativeBidIsValid} from './native';
import { store } from './videoCache';
import { Renderer } from 'src/Renderer';

var CONSTANTS = require('./constants.json');
var AUCTION_END = CONSTANTS.EVENTS.AUCTION_END;
var utils = require('./utils.js');
var events = require('./events');

var externalCallbacks = {byAdUnit: [], all: [], oneTime: null, timer: false};
var _granularity = CONSTANTS.GRANULARITY_OPTIONS.MEDIUM;
let _customPriceBucket;
var defaultBidderSettingsMap = {};

exports.setCustomPriceBucket = function(customConfig) {
  _customPriceBucket = customConfig;
};

/**
 * Returns a list of bidders that we haven't received a response yet
 * @return {array} [description]
 */
exports.getTimedOutBidders = function () {
  return $$PREBID_GLOBAL$$._bidsRequested
    .map(getBidderCode)
    .filter(uniques)
    .filter(bidder => $$PREBID_GLOBAL$$._bidsReceived
      .map(getBidders)
      .filter(uniques)
      .indexOf(bidder) < 0);
};

function timestamp() { return new Date().getTime(); }

function getBidderCode(bidSet) {
  return bidSet.bidderCode;
}

function getBidders(bid) {
  return bid.bidder;
}

function bidsBackAdUnit(adUnitCode) {
  const requested = $$PREBID_GLOBAL$$._bidsRequested
    .map(request => request.bids
      .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes))
      .filter(bid => bid.placementCode === adUnitCode))
    .reduce(flatten, [])
    .map(bid => {
      return bid.bidder === 'indexExchange'
        ? bid.sizes.length
        : 1;
    }).reduce(add, 0);

  const received = $$PREBID_GLOBAL$$._bidsReceived.filter(bid => bid.adUnitCode === adUnitCode).length;
  return requested === received;
}

function add(a, b) {
  return a + b;
}

function bidsBackAll() {
  const requested = $$PREBID_GLOBAL$$._bidsRequested
    .map(request => request.bids)
    .reduce(flatten, [])
    .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes))
    .map(bid => {
      return bid.bidder === 'indexExchange'
        ? bid.sizes.length
        : 1;
    }).reduce((a, b) => a + b, 0);

  const received = $$PREBID_GLOBAL$$._bidsReceived
    .filter(adUnitsFilter.bind(this, $$PREBID_GLOBAL$$._adUnitCodes)).length;

  return requested === received;
}

exports.bidsBackAll = function () {
  return bidsBackAll();
};

/*
 *   This function should be called to by the bidder adapter to register a bid response
 */
exports.addBidResponse = function (adUnitCode, bid) {
  if (isValid()) {
    prepareBidForAuction();

    if (bid.mediaType === 'video') {
      tryAddVideoBid(bid);
    } else {
      doCallbacksIfNeeded();
      addBidToAuction(bid);
    }
  }

  // Actual method logic is above. Everything below is helper functions.

  // Validate the arguments sent to us by the adapter. If this returns false, the bid should be totally ignored.
  function isValid() {
    function errorMessage(msg) {
      return `Invalid bid from ${bid.bidderCode}. Ignoring bid: ${msg}`;
    }

    if (!adUnitCode) {
      utils.logWarn('No adUnitCode was supplied to addBidResponse.');
      return false;
    }
    if (!bid) {
      utils.logWarn(`Some adapter tried to add an undefined bid for ${adUnitCode}.`);
      return false;
    }
    if (bid.mediaType === 'native' && !nativeBidIsValid(bid)) {
      utils.logError(errorMessage('Native bid missing some required properties.'));
      return false;
    }
    if (bid.mediaType === 'video' && !bid.vastUrl) {
      utils.logError(errorMessage(`Video bid does not have required vastUrl property.`));
      return false;
    }
    return true;
  }

  // Postprocess the bids so that all the universal properties exist, no matter which bidder they came from.
  // This should be called before addBidToAuction().
  function prepareBidForAuction() {
    const bidRequest = getBidderRequest(bid.bidderCode, adUnitCode);

    Object.assign(bid, {
      requestId: bidRequest.requestId,
      responseTimestamp: timestamp(),
      requestTimestamp: bidRequest.start,
      cpm: parseFloat(bid.cpm) || 0,
      bidder: bid.bidderCode,
      adUnitCode
    });

    bid.timeToRespond = bid.responseTimestamp - bid.requestTimestamp;

    // Let listeners know that now is the time to adjust the bid, if they want to.
    //
    // CAREFUL: Publishers rely on certain bid properties to be available (like cpm),
    // but others to not be set yet (like priceStrings). See #1372 and #1389.
    events.emit(CONSTANTS.EVENTS.BID_ADJUSTMENT, bid);

    // a publisher-defined renderer can be used to render bids
    const adUnitRenderer =
      bidRequest.bids && bidRequest.bids[0] && bidRequest.bids[0].renderer;

    if (adUnitRenderer) {
      bid.renderer = Renderer.install({ url: adUnitRenderer.url });
      bid.renderer.setRender(adUnitRenderer.render);
    }

    const priceStringsObj = getPriceBucketString(bid.cpm, _customPriceBucket);
    bid.pbLg = priceStringsObj.low;
    bid.pbMg = priceStringsObj.med;
    bid.pbHg = priceStringsObj.high;
    bid.pbAg = priceStringsObj.auto;
    bid.pbDg = priceStringsObj.dense;
    bid.pbCg = priceStringsObj.custom;

    // if there is any key value pairs to map do here
    var keyValues = {};
    if (bid.bidderCode && (bid.cpm > 0 || bid.dealId)) {
      keyValues = getKeyValueTargetingPairs(bid.bidderCode, bid);
    }

    bid.adserverTargeting = keyValues;
  }

  function doCallbacksIfNeeded() {
    if (bid.timeToRespond > $$PREBID_GLOBAL$$.cbTimeout + $$PREBID_GLOBAL$$.timeoutBuffer) {
      const timedOut = true;
      exports.executeCallback(timedOut);
    }
  }

  // Add a bid to the auction.
  function addBidToAuction() {
    events.emit(CONSTANTS.EVENTS.BID_RESPONSE, bid);

    $$PREBID_GLOBAL$$._bidsReceived.push(bid);

    if (bid.adUnitCode && bidsBackAdUnit(bid.adUnitCode)) {
      triggerAdUnitCallbacks(bid.adUnitCode);
    }

    if (bidsBackAll()) {
      exports.executeCallback();
    }
  }

  // Video bids may fail if the cache is down, or there's trouble on the network.
  function tryAddVideoBid(bid) {
    store([bid], function(error, cacheIds) {
      if (error) {
        utils.logWarn(`Failed to save to the video cache: ${error}. Video bid must be discarded.`);
      } else {
        bid.videoCacheKey = cacheIds[0].uuid;
        addBidToAuction(bid);
      }
      doCallbacksIfNeeded();
    });
  }
};

function getKeyValueTargetingPairs(bidderCode, custBidObj) {
  var keyValues = {};
  var bidder_settings = $$PREBID_GLOBAL$$.bidderSettings;

  // 1) set the keys from "standard" setting or from prebid defaults
  if (custBidObj && bidder_settings) {
    // initialize default if not set
    const standardSettings = getStandardBidderSettings();
    setKeys(keyValues, standardSettings, custBidObj);
  }

  // 2) set keys from specific bidder setting override if they exist
  if (bidderCode && custBidObj && bidder_settings && bidder_settings[bidderCode] && bidder_settings[bidderCode][CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING]) {
    setKeys(keyValues, bidder_settings[bidderCode], custBidObj);
    custBidObj.alwaysUseBid = bidder_settings[bidderCode].alwaysUseBid;
    custBidObj.sendStandardTargeting = bidder_settings[bidderCode].sendStandardTargeting;
  }

  // 2) set keys from standard setting. NOTE: this API doesn't seem to be in use by any Adapter
  else if (defaultBidderSettingsMap[bidderCode]) {
    setKeys(keyValues, defaultBidderSettingsMap[bidderCode], custBidObj);
    custBidObj.alwaysUseBid = defaultBidderSettingsMap[bidderCode].alwaysUseBid;
    custBidObj.sendStandardTargeting = defaultBidderSettingsMap[bidderCode].sendStandardTargeting;
  }

  // set native key value targeting
  if (custBidObj.native) {
    Object.keys(custBidObj.native).forEach(asset => {
      const key = NATIVE_KEYS[asset];
      const value = custBidObj.native[asset];
      if (key) { keyValues[key] = value; }
    });
  }

  return keyValues;
}

exports.getKeyValueTargetingPairs = function() {
  return getKeyValueTargetingPairs(...arguments);
};

function setKeys(keyValues, bidderSettings, custBidObj) {
  var targeting = bidderSettings[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING];
  custBidObj.size = custBidObj.getSize();

  utils._each(targeting, function (kvPair) {
    var key = kvPair.key;
    var value = kvPair.val;

    if (keyValues[key]) {
      utils.logWarn('The key: ' + key + ' is getting ovewritten');
    }

    if (utils.isFn(value)) {
      try {
        value = value(custBidObj);
      } catch (e) {
        utils.logError('bidmanager', 'ERROR', e);
      }
    }

    if (
      ((typeof bidderSettings.suppressEmptyKeys !== 'undefined' && bidderSettings.suppressEmptyKeys === true) ||
      key === 'hb_deal') && // hb_deal is suppressed automatically if not set
      (
        utils.isEmptyStr(value) ||
        value === null ||
        value === undefined
      )
    ) {
      utils.logInfo("suppressing empty key '" + key + "' from adserver targeting");
    } else {
      keyValues[key] = value;
    }
  });

  return keyValues;
}

exports.setPriceGranularity = function setPriceGranularity(granularity) {
  var granularityOptions = CONSTANTS.GRANULARITY_OPTIONS;
  if (Object.keys(granularityOptions).filter(option => granularity === granularityOptions[option])) {
    _granularity = granularity;
  } else {
    utils.logWarn('Prebid Warning: setPriceGranularity was called with invalid setting, using' +
      ' `medium` as default.');
    _granularity = CONSTANTS.GRANULARITY_OPTIONS.MEDIUM;
  }
};

exports.registerDefaultBidderSetting = function (bidderCode, defaultSetting) {
  defaultBidderSettingsMap[bidderCode] = defaultSetting;
};

exports.executeCallback = function (timedOut) {
  // if there's still a timeout running, clear it now
  if (!timedOut && externalCallbacks.timer) {
    clearTimeout(externalCallbacks.timer);
  }

  if (externalCallbacks.all.called !== true) {
    processCallbacks(externalCallbacks.all);
    externalCallbacks.all.called = true;

    if (timedOut) {
      const timedOutBidders = exports.getTimedOutBidders();

      if (timedOutBidders.length) {
        events.emit(CONSTANTS.EVENTS.BID_TIMEOUT, timedOutBidders);
      }
    }
  }

  // execute one time callback
  if (externalCallbacks.oneTime) {
    events.emit(AUCTION_END);
    try {
      processCallbacks([externalCallbacks.oneTime]);
    } catch (e) {
      utils.logError('Error executing bidsBackHandler', null, e);
    } finally {
      externalCallbacks.oneTime = null;
      externalCallbacks.timer = false;
      $$PREBID_GLOBAL$$.clearAuction();
    }
  }
};

exports.externalCallbackReset = function () {
  externalCallbacks.all.called = false;
};

function triggerAdUnitCallbacks(adUnitCode) {
  // todo : get bid responses and send in args
  var singleAdUnitCode = [adUnitCode];
  processCallbacks(externalCallbacks.byAdUnit, singleAdUnitCode);
}

function processCallbacks(callbackQueue, singleAdUnitCode) {
  if (utils.isArray(callbackQueue)) {
    callbackQueue.forEach(callback => {
      const adUnitCodes = singleAdUnitCode || $$PREBID_GLOBAL$$._adUnitCodes;
      const bids = [$$PREBID_GLOBAL$$._bidsReceived
        .filter(adUnitsFilter.bind(this, adUnitCodes))
        .reduce(groupByPlacement, {})];

      callback.apply($$PREBID_GLOBAL$$, bids);
    });
  }
}

/**
 * groupByPlacement is a reduce function that converts an array of Bid objects
 * to an object with placement codes as keys, with each key representing an object
 * with an array of `Bid` objects for that placement
 * @returns {*} as { [adUnitCode]: { bids: [Bid, Bid, Bid] } }
 */
function groupByPlacement(bidsByPlacement, bid) {
  if (!bidsByPlacement[bid.adUnitCode]) { bidsByPlacement[bid.adUnitCode] = { bids: [] }; }

  bidsByPlacement[bid.adUnitCode].bids.push(bid);

  return bidsByPlacement;
}

/**
 * Add a one time callback, that is discarded after it is called
 * @param {Function} callback
 * @param timer Timer to clear if callback is triggered before timer time's out
 */
exports.addOneTimeCallback = function (callback, timer) {
  externalCallbacks.oneTime = callback;
  externalCallbacks.timer = timer;
};

exports.addCallback = function (id, callback, cbEvent) {
  callback.id = id;
  if (CONSTANTS.CB.TYPE.ALL_BIDS_BACK === cbEvent) {
    externalCallbacks.all.push(callback);
  } else if (CONSTANTS.CB.TYPE.AD_UNIT_BIDS_BACK === cbEvent) {
    externalCallbacks.byAdUnit.push(callback);
  }
};

// register event for bid adjustment
events.on(CONSTANTS.EVENTS.BID_ADJUSTMENT, function (bid) {
  adjustBids(bid);
});

function adjustBids(bid) {
  var code = bid.bidderCode;
  var bidPriceAdjusted = bid.cpm;
  if (code && $$PREBID_GLOBAL$$.bidderSettings && $$PREBID_GLOBAL$$.bidderSettings[code]) {
    if (typeof $$PREBID_GLOBAL$$.bidderSettings[code].bidCpmAdjustment === 'function') {
      try {
        bidPriceAdjusted = $$PREBID_GLOBAL$$.bidderSettings[code].bidCpmAdjustment.call(null, bid.cpm, Object.assign({}, bid));
      } catch (e) {
        utils.logError('Error during bid adjustment', 'bidmanager.js', e);
      }
    }
  }

  if (bidPriceAdjusted >= 0) {
    bid.cpm = bidPriceAdjusted;
  }
}

exports.adjustBids = function() {
  return adjustBids(...arguments);
};

function getStandardBidderSettings() {
  let bidder_settings = $$PREBID_GLOBAL$$.bidderSettings;
  if (!bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD]) {
    bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD] = {
      adserverTargeting: [
        {
          key: 'hb_bidder',
          val: function (bidResponse) {
            return bidResponse.bidderCode;
          }
        }, {
          key: 'hb_adid',
          val: function (bidResponse) {
            return bidResponse.adId;
          }
        }, {
          key: 'hb_pb',
          val: function (bidResponse) {
            if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.AUTO) {
              return bidResponse.pbAg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.DENSE) {
              return bidResponse.pbDg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.LOW) {
              return bidResponse.pbLg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.MEDIUM) {
              return bidResponse.pbMg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.HIGH) {
              return bidResponse.pbHg;
            } else if (_granularity === CONSTANTS.GRANULARITY_OPTIONS.CUSTOM) {
              return bidResponse.pbCg;
            }
          }
        }, {
          key: 'hb_size',
          val: function (bidResponse) {
            return bidResponse.size;
          }
        }, {
          key: 'hb_deal',
          val: function (bidResponse) {
            return bidResponse.dealId;
          }
        }
      ]
    };
  }
  return bidder_settings[CONSTANTS.JSON_MAPPING.BD_SETTING_STANDARD];
}

function getStandardBidderAdServerTargeting() {
  return getStandardBidderSettings()[CONSTANTS.JSON_MAPPING.ADSERVER_TARGETING];
}

exports.getStandardBidderAdServerTargeting = getStandardBidderAdServerTargeting;


text:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright (c) 2012, Michael Gelbart (michael.gelbart@gmail.com)
% All rights reserved.
%
% Redistribution and use in source and binary forms, with or without modification,
% are permitted provided that the following conditions are met:
%
% - Redistributions of source code must retain the above copyright notice,
%   this list of conditions and the following disclaimer.
%
% - Redistributions in binary form must reproduce the above copyright notice,
%   this list of conditions and the following disclaimer in the documentation
%   and/or other materials provided with the distribution.
%
% THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
% AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
% IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
% ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
% LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
% DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
% LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
% ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
% NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
% EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Go to a particular image in either semiauto or EDGE. Changes the sliders
% and the text, as well as the image.

function handles = go_to_image(handles, T, Z)

% called by update_embryo~~
set(handles.t_text, 'String', num2str(T));
set(handles.z_text, 'String', num2str(Z));

t_slider_value = abs(T - handles.info.start_time);
z_slider_value = abs(Z - handles.info.bottom_layer);
set(handles.t_slider, 'Value', t_slider_value);
set(handles.z_slider, 'Value', z_slider_value);

handles = semiauto_change_image_callbacks(handles);

% redraw
handles = slider_callbacks_draw_image_slice(handles);


text:
<!doctype html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Portfolio Single 3 | Avoc | Awesome Parallax Template</title>

<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Maven+Pro:400,700,900" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Lato:300,400,700,900" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Josefin+Sans:400,700" rel="stylesheet" type="text/css">

<link rel="stylesheet" id="default-style-css"  href="files/css/style.css" type="text/css" media="all" />
<link rel="stylesheet" id="wolf-css" href="files/css/wolf.css" type="text/css" media="all" />
<link rel="stylesheet" id="fontawesome-style-css" href="files/css/font-awesome.min.css" type="text/css" media="all" />
<link rel="stylesheet" id="ionic-icons-style-css" href="files/css/ionicons.css" type="text/css" media="all" />
<link rel="stylesheet" id="mqueries-style-css"  href="files/css/mqueries.css" type="text/css" media="all" />

<link rel="shortcut icon" href="files/uploads/favicon.png"/>

Loading

                Menu

Home

Portfolio Main

Portfolio Creative

Photography

Classic Masonry

Agency

Pages

About classic

About creative

About bold minimal

Services

404 Page

Blog

Features

General Elements

Header / Footer

Hero Options

Contact

                Share

                    Close

Share

RAD

        Scroll Down

© Mariana Garcia

Previous Project

Back To Works

Next Project

Copyright © 2014 by Avoc

                Made with Love by Spab Rice

            Back To Top


text:
{-# OPTIONS_HADDOCK hide #-}
{-# LANGUAGE RankNTypes #-}

module Graphics.Gloss.Internals.Interface.ViewState.KeyMouse
        (callback_viewState_keyMouse)
where
import Graphics.Gloss.Data.ViewState
import Graphics.Gloss.Internals.Interface.Backend
import Graphics.Gloss.Internals.Interface.Event
import Data.IORef

-- | Callback to handle keyboard and mouse button events
--      for controlling the 'ViewState'.
callback_viewState_keyMouse
        :: IORef ViewState
        -> Callback

callback_viewState_keyMouse viewStateRef
        = KeyMouse (viewState_keyMouse viewStateRef)

viewState_keyMouse :: IORef ViewState -> KeyboardMouseCallback
viewState_keyMouse viewStateRef stateRef key keyState keyMods pos
 = do   viewState <- readIORef viewStateRef
        ev        <- keyMouseEvent stateRef key keyState keyMods pos
        case updateViewStateWithEventMaybe ev viewState of
                Nothing -> return ()
                Just viewState'
                 -> do  viewStateRef `writeIORef` viewState'
                        postRedisplay stateRef


text:
package org.hhorton.rules;

/**
 * Created by hunterhorton on 6/4/17.
 */
public class PointsRules {
    public static final int POINTS_PER_RECEPTION = 1;
    public static final int Every_25_passing_yards = 1;
    public static final int Each_passing_TD = 6;
    public static final int Each_interception_thrown = -2;
    public static final int Every_10_rushing_yards = 1;
    public static final int Each_rushing_TD = 6;
    public static final int Every_10_receiving_yards = 1;
    public static final int Each_receiving_TD = 6;
    public static final int Each_return_TD = 6;
    public static final int Each_Off_Fum_Ret_TD = 6;
    public static final int Each_2_Point_conversion_ = 2;
    public static final int Each_fumble_lost = -2;
    public static final int Field_goal_0_to_19_yards_ = 3;
    public static final int Field_goal_20_to_29_yards_ = 3;
    public static final int Field_goal_30_to_39_yards_ = 3;
    public static final int Field_goal_40_to_49_yards_ = 4;
    public static final int Field_goal_50_plus_yards_ = 5;
    public static final int Each_extra = 1;
    public static final int Each_sack = 1;
    public static final int Each_interception = 2;
    public static final int Each_fumble_recovery = 2;
    public static final int Each_touchdown = 6;
    public static final int Each_safety = 2;
    public static final int Each_blocked_kick = 2;
    public static final int Kickoff_and_Punt_Return_Touchdowns = 6;
    public static final int Shutout = 10;
    public static final int PA_1_to_6_allowed = 7;
    public static final int PA_7_to_13_allowed = 4;
    public static final int PA_14_to_20_allowed = 1;
    public static final int PA_21_to_27_allowed = 0;
    public static final int PA_28_to_34_allowed = -1;
    public static final int PA_35_plus_allowed = -4;
}


text:
{-# LANGUAGE GADTs #-}

module Sampling where

  import qualified Data.Array.Repa as R
  import Matrix

  class Sampleable s where
    lower_bound :: s -> Int
    upper_bound :: s -> Int
    elementAt :: (Sampleable r) => s -> Int -> r

  data Sampler a where
    Sampler :: (Sampleable a, Sampleable b) => (a -> b) -> Sampler a


text:
My path to a free self-taught education in Sustainable Cities! *I will be adding pizzas to the ones I finish to track my progress.* :relaxed:

## Contents

- [About](#about)
- [Preparation](#preparation)
- [Courses](#courses)
- [Books](#books)
- [Articles](#articles)
- [Research](#research)
- [Capstone Project](#capstoneproject)

## About

I looked online for free MOOCs that would offer a strong background for anyone interested in Sustainable cities. The structure is inspired from [The Dual Master's in Sustainable Smart Cities](https://www.uab.edu/smartcities/masters-program/program-details) from the University of Alabama at Birmingham and Staffordshire University. I will continue to improve the list as I find new courses.

## Preparation

A great MOOC that gives you easy access to the invaluable learning techniques used by experts in art, music, literature, math, science, sports, and many other disciplines.

- [Learning How to Learn](https://www.coursera.org/learn/learning-how-to-learn) :pizza:

Also I think MOOCs for learning how to use solution-based journalism to impel positive social change would also prove useful :)

- [Journalism for Social Change](https://www.edx.org/course/journalism-social-change-uc-berkeleyx-j4sc101x-0) by University of California, Berkeley - 7 weeks of study, 2 - 4 hours per week
- [Journalism Skills for Engaged Citizens](https://www.coursera.org/learn/journalism-skills) by The University of Melbourne - 6 weeks of study, 4-6 hours/week

Also learning how to research and present an effective and persuasive position paper or policy advice might prove useful.

- [Be Persuasive: Write a Convincing Position Paper or Policy Advice (Project-Centered Course)](https://www.coursera.org/learn/persuasive-writing) by Universiteit Leiden - 4 weeks of study, 2-4 hours of study, 4-5 hours of active project work

## Courses

### Principles of Sustainable Development

- [Introduction to Sustainability](https://www.coursera.org/learn/sustainability/) by University of Illinois at Urbana-Champaign - 8 weeks of study, 8-10 hours/week :pizza:
- [The Age of Sustainable Development](https://www.coursera.org/learn/sustainable-development) by Columbia University - 14 weeks of study, 2 hours of lectures per module
- [Greening the Economy: Lessons from Scandinavia](https://www.coursera.org/learn/greening-the-economy) by Lund University - 5 weeks of study, 5-8 hours/week :pizza:
- [Our Earth: Its Climate, History, and Processes](https://www.coursera.org/learn/our-earth) by University of Manchester - 5 weeks of study

#### Optional

- [Introduction to Environmental Law and Policy](https://www.coursera.org/learn/environmental-law) by the University of North Carolina at Chapel Hill - 6 weeks of study, 4-6 hours/week

### Introduction to Sustainable Smart Cities

- [Smart cities](https://www.futurelearn.com/courses/smart-cities) by The Open University - 6 weeks of study, 3 hours/week :pizza:
- [Greening the Economy: Sustainable Cities](https://www.coursera.org/learn/gte-sustainable-cities/) by Lund University - 5 weeks of study, 5 hours/week :pizza:
- [Sustainable Urban Development](https://courses.edx.org/courses/course-v1:DelftWageningenX+AMS.URB.1x+1T2016/info) by Delft University of Technology - 7 weeks of study
- [Cities are back in town : urban sociology for a globalizing urban world](https://www.coursera.org/learn/urban-development) by Sciences Po - 8 weeks of study
- [Sustainable Cities](https://courses.sdgacademy.org/learn/sustainable-cities-may-2017) by SDG Academy - 10 weeks of study
- [Ecodesign for Cities and Suburbs](https://www.edx.org/course/ecodesign-cities-suburbs-ubcx-ecodesignx-0?utm_medium=social&utm_source=facebook&utm_campaign=ubcx%252Cecodesign-for-cities-suburbs%252Ccourse%252Capr82018) by University of British Columbia - 6 weeks of study

### Low Carbon and Renewable Energy Systems

- [Energy 101: The Big Picture](https://www.coursera.org/learn/energy-101) by Georgia Institute of Technology - 6 weeks of study, 5-7 hours/week
- [Our Energy Future](https://www.coursera.org/learn/future-of-energy) by University of California, San Diego - 9 weeks of study, 45 hours of videos, quizzes and peer reviews
- [Politics and Economics of International Energy](https://www.coursera.org/learn/global-energy) by Paris School of International Affairs (PSIA) Sciences Po - 8 weeks of study, 1-3 hours/week
- [Introduction to Sustainable Energy](https://ocw.mit.edu/courses/nuclear-engineering/22-081j-introduction-to-sustainable-energy-fall-2010/) by MIT - [lectures and reading material](https://ocw.mit.edu/courses/nuclear-engineering/22-081j-introduction-to-sustainable-energy-fall-2010/lectures-and-readings/) available online

### Managing Natural Resources and Sustainable Smart Cities

- [Livable Future Cities](https://courses.edx.org/courses/course-v1:ETHx+FC-02x+2T2016/info) - by ETH Zurich - 11 weeks of study :pizza:
- [Urban Water - Innovations for Environmental Sustainability](https://www.edx.org/course/urban-water-innovations-environmental-ubcx-water201x#.VPXUIVPF9vo) by University of British Columbia -  6 weeks of study, 3 - 4 hours/week
- [Global Environmental Management](https://www.coursera.org/learn/global-environmental-management) by Technical University of Denmark (DTU) - 5 weeks of study
- [Global Warming I: The Science and Modeling of Climate Change](https://www.coursera.org/learn/global-warming) by The University of Chicago - 12 weeks of study

#### Optional

- [Water Resources Management and Policy](https://www.coursera.org/learn/water-management) by University of Geneva - 5 weeks of study, 1-3 hours/week
- [Sustainable Agricultural Land Management](https://www.coursera.org/learn/sustainable-agriculture) by University of Florida - 8 weeks of study
- [Climate Change Mitigation in Developing Countries](https://www.coursera.org/learn/climate-change-mitigation) by University of Cape Town - 6 weeks of study, 1-3 hours/week
- [Natural Attenuation of Groundwater Contaminants: New Paradigms, Technologies, and Applications](https://www.coursera.org/learn/natural-attenuation-of-groundwater-contaminants) by Rice University - 9 weeks of study
- [Shale gas and fracking](https://www.futurelearn.com/courses/shale-gas/2/todo/1576) by the University of Nottingham - 4 weeks of study
- [A Circular Economy of Metals: Towards a Sustainable Societal Metabolism](https://www.coursera.org/learn/circular-economy-metals) by Universiteit Leiden - 6 weeks of study, 5-7 hours per week

### Green Infrastructure and Transportation

- [Smart Cities – Management of Smart Urban Infrastructures](https://www.coursera.org/learn/smart-cities) by École Polytechnique Fédérale de Lausanne - 5 weeks of study, 2-3 hours per week
- [Management of Urban Infrastructures – part 1](https://www.coursera.org/learn/managing-urban-infrastructures-1) by École Polytechnique Fédérale de Lausanne - 5 weeks of study, 1-3 hours/week
- [Planning & Design of Sanitation Systems and Technologies](https://www.coursera.org/learn/sanitation) by École Polytechnique Fédérale de Lausanne - 5 weeks of study, 4-6 hours/week
- [Municipal Solid Waste Management in Developing Countries](https://www.coursera.org/learn/solid-waste-management) by École Polytechnique Fédérale de Lausanne - 5 weeks of study, 1-2 hours/week
- [Sustainable Urban Freight Transport: A Global Perspective](https://online-learning.tudelft.nl/courses/sustainable-urban-freight-transport-a-global-perspective/) by TUDelft - 5 weeks of study, 4-6 hours per week
- [Supply Chain Fundamentals](https://www.edx.org/course/supply-chain-fundamentals) by MIT
- [Supply Chain Analytics](https://www.edx.org/course/supply-chain-analytics) by MIT
- [Leveraging Urban Mobility Disruptions to Create Better Cities](https://www.edx.org/course/leveraging-urban-mobility-disruptions-to-create-better-cities) by MIT

### Green Buildings

- [Resilient Architecture Research](https://www.ooed.org/learn/resilient-architecture-research-fall-2014) by Open Online Academy
- [Sustainable Building Design](https://www.edx.org/course/environmental-technologies-in-buildings) by MIT

### Health & Liveability

- [Community Change in Public Health](https://www.coursera.org/learn/community-public-health) by Johns Hopkins University - 5 weeks of study, 1-3 hours/week
- [Climate Change and Health](https://iversity.org/en/courses/climate-change-and-health) by Heidelberg University - 5 weeks of study
- [Global Warming Science](https://www.edx.org/course/global-warming-science) by MIT

#### Optional

- [Sustainable Food Production Through Livestock Health Management](https://www.coursera.org/learn/livestock-farming) by University of Illinois at Urbana-Champaign - 6 weeks of study; 5-7 hours/week

### Smart Technologies for Cities & Buildings

- [Introduction to Metrics for Smart Cities](https://www.edx.org/course/introduction-metrics-smart-cities-ieeex-scmtx-1x#.VPXTolPF9vo) by IEEE - 4 weeks of study, 5 - 7 hours/week
- [Future Cities](https://www.edx.org/course/future-cities-ethx-fc-01x-2#.VPXTtFPF9vo) by ETH Zurich  - 10 weeks of study, 3 hours per week
- [Smart Cities](https://courses.edx.org/courses/course-v1:ETHx+ETHx-FC-03x+1T2017/info) by ETH Zurich - 10 weeks of study
- [Internet of Things: How did we get here?](https://www.coursera.org/learn/internet-of-things-history) by University of California, San Diego - 2 weeks of study, 2-3 hours/week
- [A developer's guide to the Internet of Things ](https://www.coursera.org/learn/developer-iot/home/welcome) by IBM - 4 weeks of study

### Big Data & Smart Cities

- [Introduction to Big Data](https://www.coursera.org/learn/big-data-introduction) by University of California, San Diego - 3 weeks of study, 5-6 hours/week
- [A Crash Course in Data Science](https://www.coursera.org/learn/data-science-course) by Johns Hopkins University - 1 week of study, 4-6 hours
- [Fundamentals of GIS](https://www.coursera.org/learn/gis) by University of California, Davis - 4 weeks of study, 3-5 hours/week
- [Cloud Computing Concepts, Part 1](https://www.coursera.org/learn/cloud-computing) by University of Illinois at Urbana-Champaign - 5 weeks of study

#### Optional

- [Cloud Computing Concepts: Part 2](https://www.coursera.org/learn/cloud-computing-2) by University of Illinois at Urbana-Champaign - 5 weeks of study
- [Data Management and Visualization](https://www.coursera.org/learn/data-visualization) by Wesleyan University - 4 weeks of study, 4-5 hours/week
- [Social Computing](https://www.coursera.org/learn/social-computing) by University of California, San Diego - 3 weeks, 2-3 hours/week

### Research Methods & Project Planning

- [Understanding Research Methods](https://www.coursera.org/learn/research-methods/home/info) by University of London & SOAS University of London - 4 weeks of study
- [Social Norms, Social Change I](https://www.coursera.org/learn/norms) by University of Pennsylvania, Unicef, 4 weeks of study, 2-3 hours/week
- [Social Norms, Social Change II](https://www.coursera.org/learn/change) by University of Pennsylvania, Unicef, 4 weeks of study, 2-3 hours of work per week
- [Introduction to Environmental Law and Policy](https://www.coursera.org/learn/environmental-law) by The University of North Carolina at Chapel Hill - 6 weeks of study, 4-6 hours/week
- [Citizen Engagement: A Game Changer for Development](https://www.edx.org/course/citizen-engagement-game-changer-wbgx-ce01x) by World Bank Group  - 5 weeks of study, 2-4 hours/week
- [U.Lab: Transforming Business, Society, and Self](https://courses.edx.org/courses/course-v1:MITx+15.671x+3T2015/info) by MITx - 8 weeks of study

## Books

- [Citizen-Driven Innovation](http://www.openlivinglabs.eu/sites/enoll.org/files/Citizen_Driven_Innovation_Full%284%29.pdf)
- [Economic Foundations for Sustainable Urbanization](http://unhabitat.org/books/economic-foundations-for-sustainable-urbanization-a-study-on-three-pronged-approach-planned-city-extensions-legal-framework-and-municipal-finance/)
- [Guiding Principles for City Climate Action Planning](http://unhabitat.org/books/guiding-principles-for-climate-city-planning-action/)
- [Science and the City: The Mechanics Behind the Metropolis](https://www.goodreads.com/book/show/28260428-science-and-the-city)
- [Shaping cities](https://www.amazon.co.uk/Shaping-Cities-Urban-Ricky-Burdett/dp/071487728X)

## Articles

- [Co-Creating the Cities of the Future](http://www.mdpi.com/1424-8220/16/11/1971)

## Research

- [Urban age](https://urbanage.lsecities.net/)

## Capstone Project

List of datasets for projects:

- [on kaggle.com](https://www.kaggle.com/datasets?sortBy=relevance&group=featured&search=city)


text:
MAXCOUNT=10
count=1

echo
echo "$MAXCOUNT random numbers:"
echo "-----------------"
while [ "$count" -le $MAXCOUNT ]      # Generate 10 ($MAXCOUNT) random integers.
do
  number=$RANDOM
  echo $number
  let "count += 1"  # Increment count.
done
echo "-----------------"

# If you need a random int within a certain range, use the 'modulo' operator.
# This returns the remainder of a division operation.

RANGE=500

echo

number=$RANDOM
let "number %= $RANGE"
#           ^^
echo "Random number less than $RANGE  ---  $number"

echo

#  If you need a random integer greater than a lower bound,
#+ then set up a test to discard all numbers below that.

FLOOR=200

number=0   #initialize
while [ "$number" -le $FLOOR ]
do
  number=$RANDOM
done
echo "Random number greater than $FLOOR ---  $number"
echo

   # Let's examine a simple alternative to the above loop, namely
   #       let "number = $RANDOM + $FLOOR"
   # That would eliminate the while-loop and run faster.
   # But, there might be a problem with that. What is it?

# Combine above two techniques to retrieve random number between two limits.
number=0   #initialize
while [ "$number" -le $FLOOR ]
do
  number=$RANDOM
  let "number %= $RANGE"  # Scales $number down within $RANGE.
done
echo "Random number between $FLOOR and $RANGE ---  $number"
echo

# Generate binary choice, that is, "true" or "false" value.
BINARY=2
T=1
number=$RANDOM

let "number %= $BINARY"
#  Note that    let "number >>= 14"    gives a better random distribution
#+ (right shifts out everything except last binary digit).
if [ "$number" -eq $T ]
then
  echo "TRUE"
else
  echo "FALSE"
fi

echo

# Generate a toss of the dice.
SPOTS=6   # Modulo 6 gives range 0 - 5.
          # Incrementing by 1 gives desired range of 1 - 6.
          # Thanks, Paulo Marcel Coelho Aragao, for the simplification.
die1=0
die2=0
# Would it be better to just set SPOTS=7 and not add 1? Why or why not?

# Tosses each die separately, and so gives correct odds.

    let "die1 = $RANDOM % $SPOTS +1" # Roll first one.
    let "die2 = $RANDOM % $SPOTS +1" # Roll second one.
    #  Which arithmetic operation, above, has greater precedence --
    #+ modulo (%) or addition (+)?

let "throw = $die1 + $die2"
echo "Throw of the dice = $throw"
echo

exit 0


text:
class ClearingTest < Librato::Services::TestCase

  class ClearingService < Service
    def receive_alert_clear
    end
    def sample_payload
      {}
    end
  end

  class NotClearingService < Service
    def sample_payload
      {}
    end
  end

  def test_sends_clear
    event = :alert
    settings = {}
    payload = { clear: true }
    assert ClearingService.receive(event, settings, payload)
  end

  def does_not_send_clear
    event = :alert
    settings = {}
    payload = { clear: true }
    assert !NotClearingService.receive(event, settings, payload)
  end

end


text:
from vitrage.common.constants import DatasourceAction
from vitrage.common.constants import DatasourceProperties as DSProps
from vitrage.common.constants import EdgeLabel
from vitrage.common.constants import EntityCategory
from vitrage.common.constants import GraphAction
from vitrage.common.constants import VertexProperties as VProps
from vitrage.datasources.alarm_properties import AlarmProperties as AlarmProps
from vitrage.datasources.aodh.properties import AodhProperties as AodhProps
from vitrage.datasources.aodh.properties import AodhState
from vitrage.datasources.nova.instance import NOVA_INSTANCE_DATASOURCE
from vitrage.datasources.transformer_base import TransformerBase
from vitrage.graph.driver.elements import Vertex
from vitrage.tests import base

class AodhTransformerBaseTest(base.BaseTest):

    def _validate_aodh_vertex_props(self, vertex, event):

        self.assertEqual(EntityCategory.ALARM, vertex[VProps.VITRAGE_CATEGORY])
        self.assertEqual(event[DSProps.ENTITY_TYPE],
                         vertex[VProps.VITRAGE_TYPE])
        self.assertEqual(event[AodhProps.NAME], vertex[VProps.NAME])
        self.assertEqual(event[AodhProps.SEVERITY], vertex[VProps.SEVERITY])
        self.assertEqual(event[AodhProps.DESCRIPTION],
                         vertex[AodhProps.DESCRIPTION])
        self.assertEqual(event[AodhProps.ENABLED], vertex[AodhProps.ENABLED])
        self.assertEqual(event[AodhProps.PROJECT_ID],
                         vertex[VProps.PROJECT_ID])
        self.assertEqual(event[AodhProps.REPEAT_ACTIONS],
                         vertex[AodhProps.REPEAT_ACTIONS])
        self.assertEqual(event[AodhProps.TYPE], vertex['alarm_type'])
        if event[AodhProps.TYPE] == AodhProps.EVENT:
            self.assertEqual(event[AodhProps.EVENT_TYPE],
                             vertex[AodhProps.EVENT_TYPE])
        elif event[AodhProps.TYPE] == AodhProps.THRESHOLD:
            self.assertEqual(event[AodhProps.STATE_TIMESTAMP],
                             vertex[AodhProps.STATE_TIMESTAMP])
        self.assertEqual(event[DSProps.SAMPLE_DATE],
                         vertex[VProps.VITRAGE_SAMPLE_TIMESTAMP])

        event_status = event[AodhProps.STATE]
        if event_status == AodhState.OK:
            self.assertEqual(AlarmProps.INACTIVE_STATE,
                             vertex[VProps.STATE])
        else:
            self.assertEqual(AlarmProps.ACTIVE_STATE,
                             vertex[VProps.STATE])
        self.assertFalse(vertex[VProps.VITRAGE_IS_PLACEHOLDER])
        self.assertFalse(vertex[VProps.VITRAGE_IS_DELETED])

    def _validate_action(self, alarm, wrapper):
        if DSProps.EVENT_TYPE in alarm \
                and alarm[DSProps.EVENT_TYPE] in vars(GraphAction).values():
            self.assertEqual(alarm[DSProps.EVENT_TYPE], wrapper.action)
            return

        ds_action = alarm[DSProps.DATASOURCE_ACTION]
        if ds_action in (DatasourceAction.SNAPSHOT, DatasourceAction.UPDATE):
            self.assertEqual(GraphAction.UPDATE_ENTITY, wrapper.action)
        else:
            self.assertEqual(GraphAction.CREATE_ENTITY, wrapper.action)

    def _validate_neighbors(self, neighbors, alarm_id, event):
        resource_counter = 0

        for neighbor in neighbors:
            resource_id = event[AodhProps.RESOURCE_ID]
            self._validate_instance_neighbor(neighbor,
                                             resource_id,
                                             alarm_id)
            resource_counter += 1

        self.assertEqual(1,
                         resource_counter,
                         'Alarm can be belonged to only one resource')

    def _validate_instance_neighbor(self,
                                    alarm_neighbor,
                                    resource_id,
                                    alarm_vertex_id):
        # validate neighbor vertex
        self.assertEqual(EntityCategory.RESOURCE,
                         alarm_neighbor.vertex[VProps.VITRAGE_CATEGORY])
        self.assertEqual(NOVA_INSTANCE_DATASOURCE,
                         alarm_neighbor.vertex[VProps.VITRAGE_TYPE])
        self.assertEqual(resource_id, alarm_neighbor.vertex[VProps.ID])
        self.assertFalse(alarm_neighbor.vertex[VProps.VITRAGE_IS_PLACEHOLDER])
        self.assertFalse(alarm_neighbor.vertex[VProps.VITRAGE_IS_DELETED])

        # Validate neighbor edge
        edge = alarm_neighbor.edge
        self.assertEqual(edge.target_id, alarm_neighbor.vertex.vertex_id)
        self.assertEqual(edge.source_id, alarm_vertex_id)
        self.assertEqual(edge.label, EdgeLabel.ON)

    def _convert_dist_to_vertex(self, neighbor):
        ver_id = neighbor[VProps.VITRAGE_CATEGORY] + \
            TransformerBase.KEY_SEPARATOR + neighbor[VProps.VITRAGE_TYPE] + \
            TransformerBase.KEY_SEPARATOR + neighbor[VProps.ID]
        return Vertex(vertex_id=ver_id, properties=neighbor)


text:
#include "audio.h"
#include "ugen/ugen.h"

#include <stdlib.h>

extern int open_ckvugen(lua_State *L);
static void open_audio_libs(CKVAudio audio, CKVM vm);
static int ckv_audio_ffwd(lua_State *L);

struct _CKVAudio {
	CKVM vm;
	unsigned int now;
	float silent_until;
	int sample_rate;
	int channels;
	double hard_clip;
	int print_time;
};

CKVAudio
ckva_open(CKVM vm, int sample_rate, int channels, double hard_clip, int print_time)
{
	lua_State *L;
	CKVAudio audio;

	audio = (CKVAudio)malloc(sizeof(struct _CKVAudio));
	audio->vm = vm;
	audio->now = (int) ckvm_now(vm);
	audio->silent_until = 0;
	audio->sample_rate = sample_rate;
	audio->channels = channels;
	audio->hard_clip = hard_clip;
	audio->print_time = print_time;

	open_audio_libs(audio, vm);

	L = ckvm_global_state(vm);
	lua_pushlightuserdata(L, audio);
	lua_setfield(L, LUA_REGISTRYINDEX, "audio");

	return audio;
}

void
ckva_destroy(CKVAudio audio)
{
	free(audio);
}

int
ckva_sample_rate(CKVAudio audio)
{
	return audio->sample_rate;
}

int
ckva_channels(CKVAudio audio)
{
	return audio->channels;
}

void
ckva_fill_buffer(CKVAudio audio, double *outputBuffer, double *inputBuffer, int frames)
{
	lua_State *L;
	int i, c;
	int oldtop, adc, dac, sinks, ugen_graph, tick_all;
	double sample;

	if(!ckvm_running(audio->vm)) {
		for(i = 0; i < frames; i++)
			for(c = 0; c < audio->channels; c++)
				outputBuffer[i * audio->channels + c] = 0;
		return;
	}

	L = ckvm_global_state(audio->vm);

	oldtop = lua_gettop(L);

	lua_getglobal(L, "adc");
	adc = lua_gettop(L);

	lua_getglobal(L, "dac");
	dac = lua_gettop(L);

	/* sinks */
	lua_createtable(L, 2 /* array */, 0 /* non-array */);
	lua_getglobal(L, "dac");
	lua_rawseti(L, -2, 1);
	lua_getglobal(L, "blackhole");
	lua_rawseti(L, -2, 2);
	sinks = lua_gettop(L);

	lua_getfield(L, LUA_REGISTRYINDEX, "ugen_graph");
	ugen_graph = lua_gettop(L);

	lua_getfield(L, ugen_graph, "tick_all");
	tick_all = lua_gettop(L);

	for(i = 0; i < frames; ) {
		ckvm_run_until(audio->vm, audio->now);

		if(!ckvm_running(audio->vm)) {
			for(; i < frames; i++)
				for(c = 0; c < audio->channels; c++)
					outputBuffer[i * audio->channels + c] = 0;
			break;
		}

		/* set mic sample */
		lua_pushnumber(L, inputBuffer[i]);
		lua_setfield(L, adc, "next");

		/* tick all ugens */
		lua_pushvalue(L, tick_all);
		lua_pushvalue(L, ugen_graph);
		lua_pushvalue(L, sinks);
		lua_call(L, 2, 0);

		/* get sample */
		lua_getfield(L, dac, "last");
		sample = lua_tonumber(L, -1);
		lua_pop(L, 1);

		/* clip if requested */
		if(audio->hard_clip > 0) {
			if(sample > audio->hard_clip)
				sample = audio->hard_clip;
			if(sample < -audio->hard_clip)
				sample = -audio->hard_clip;
		}

		/* audio => speaker */
		outputBuffer[i * 2] = sample;
		outputBuffer[i * 2 + 1] = sample;

		audio->now++;
		if(audio->print_time && audio->now % audio->sample_rate == 0) {
			int second = audio->now / audio->sample_rate;
			fprintf(stderr, "[ckv] %02d:%02d:%02d\n", (int) (second / 60.0 / 60.0), (int) (second / 60.0) % 60, second % 60);
		}

		if(audio->now >= audio->silent_until)
			i++;
	}

	lua_settop(L, oldtop);
}

static
void
open_audio_libs(CKVAudio audio, CKVM vm)
{
	lua_State *L = ckvm_global_state(vm);

	lua_gc(L, LUA_GCSTOP, 0); /* stop collector during initialization */
	lua_pushcfunction(L, open_ckvugen); lua_call(L, 0, 0);
	lua_gc(L, LUA_GCRESTART, 0);

	/* set the sample rate */
	lua_pushnumber(L, audio->sample_rate);
	lua_setglobal(L, "sample_rate");

	/* set duration helper variables */
	lua_pushnumber(L, 1);
	lua_pushnumber(L, 1);
	lua_setglobal(L, "sample");
	lua_setglobal(L, "samples");
	lua_pushnumber(L, audio->sample_rate / 1000.0);
	lua_setglobal(L, "ms");
	lua_pushnumber(L, audio->sample_rate);
	lua_pushnumber(L, audio->sample_rate);
	lua_setglobal(L, "second");
	lua_setglobal(L, "seconds");
	lua_pushnumber(L, audio->sample_rate * 60);
	lua_pushnumber(L, audio->sample_rate * 60);
	lua_setglobal(L, "minute");
	lua_setglobal(L, "minutes");
	lua_pushnumber(L, audio->sample_rate * 60 * 60);
	lua_pushnumber(L, audio->sample_rate * 60 * 60);
	lua_setglobal(L, "hour");
	lua_setglobal(L, "hours");
	lua_pushnumber(L, audio->sample_rate * 60 * 60 * 24);
	lua_pushnumber(L, audio->sample_rate * 60 * 60 * 24);
	lua_setglobal(L, "day");
	lua_setglobal(L, "days");
	lua_pushnumber(L, audio->sample_rate * 60 * 60 * 24 * 7);
	lua_pushnumber(L, audio->sample_rate * 60 * 60 * 24 * 7);
	lua_setglobal(L, "week");
	lua_setglobal(L, "weeks");
	lua_pushnumber(L, audio->sample_rate * 60 * 60 * 24 * 7 * 2);
	lua_pushnumber(L, audio->sample_rate * 60 * 60 * 24 * 7 * 2);
	lua_setglobal(L, "fortnight");
	lua_setglobal(L, "fortnights");

	/* function for fast-forwarding in audio stream */
	lua_pushcfunction(L, ckv_audio_ffwd); lua_setglobal(L, "audio_ffwd");
}

static
int
ckv_audio_ffwd(lua_State *L)
{
	CKVAudio audio;
	lua_Number amt;

	amt = luaL_checknumber(L, 1);
	if(amt < 0) {
		fprintf(stderr, "[ckv] attempt to audio_ffwd with negative value\n");
		return 0;
	}

	lua_getfield(L, LUA_REGISTRYINDEX, "audio");
	audio = lua_touserdata(L, -1);
	if(audio->silent_until < audio->now + amt)
		audio->silent_until = audio->now + amt;

	lua_pushnumber(L, amt);
	return 1;
}


text:
<?php

include('include/views/js/configuration.services.edit.js.php');

global $ZBX_MESSAGES;

$service = $this->data['service'];

$servicesWidget = new CWidget();
$servicesWidget->setRootClass('services-edit');
$servicesWidget->addPageHeader(_('CONFIGURATION OF IT SERVICES'));

// create form
$servicesForm = new CForm();
$servicesForm->setName('servicesForm');
$servicesForm->addVar('form', $this->data['form']);
$servicesForm->addVar('parentid', $this->data['parentid']);
$servicesForm->addVar('parentname', $this->data['parentname']);
$servicesForm->addVar('triggerid', $this->data['triggerid']);
if (isset($this->data['service'])) {
	$servicesForm->addVar('serviceid', $this->data['service']['serviceid']);
}

// create form list
$servicesFormList = new CFormList('servicesFormList');
$nameTextBox = new CTextBox('name', $this->data['name'], ZBX_TEXTBOX_STANDARD_SIZE, false, 128);
$nameTextBox->attr('autofocus', 'autofocus');
$servicesFormList->addRow(_('Name'), $nameTextBox);

// append parent link to form list
$servicesFormList->addRow(_('Parent service'), array(
	new CTextBox('parent_name', $this->data['parentname'], ZBX_TEXTBOX_STANDARD_SIZE, true, 128),
	new CButton('select_parent', _('Change'), "javascript: openWinCentered('services.php?pservices=1".url_param('serviceid')."', 'ZBX_Services_List', 740, 420, 'scrollbars=1, toolbar=0, menubar=0, resizable=1, dialog=0');", 'formlist')
));

// append algorithm to form list
$algorithmComboBox = new CComboBox('algorithm', $this->data['algorithm']);
$algorithmComboBox->addItems(serviceAlgorythm());
$servicesFormList->addRow(_('Status calculation algorithm'), $algorithmComboBox);

// append SLA to form list
$showslaCheckbox = new CCheckBox('showsla', ($this->data['showsla'] == 0) ? 'no' : 'yes', null, 1);
$goodslaTextBox = new CTextBox('goodsla', $this->data['goodsla'], 6, false, 8);
if (!$this->data['showsla']) {
	$goodslaTextBox->setAttribute('disabled', 'disabled');
}
$servicesFormList->addRow(_('Calculate SLA, acceptable SLA (in %)'), array($showslaCheckbox, $goodslaTextBox));

// append trigger to form list
$servicesFormList->addRow(_('Trigger'), array(
	new CTextBox('trigger', $this->data['trigger'], ZBX_TEXTBOX_STANDARD_SIZE, true),
	new CButton('btn1', _('Select'),
		'return PopUp("popup.php?'.
			'dstfrm='.$servicesForm->getName().
			'&dstfld1=triggerid'.
			'&dstfld2=trigger'.
			'&srctbl=triggers'.
			'&srcfld1=triggerid'.
			'&srcfld2=description'.
			'&real_hosts=1'.
			'&with_triggers=1");',
		'formlist'
	)
));
$servicesFormList->addRow(_('Sort order (0->999)'), new CTextBox('sortorder', $this->data['sortorder'], 3, false, 3));

/*
 * Dependencies tab
 */
$servicesChildTable = new CTable(_('No dependencies defined.'), 'formElementTable');
$servicesChildTable->setAttribute('style', 'min-width:500px;');
$servicesChildTable->setAttribute('id', 'service_children');
$servicesChildTable->setHeader(array(_('Services'), _('Soft'), _('Trigger'), _('Action')));
foreach ($this->data['children'] as $child) {
	$childrenLink = new CLink($child['name'], 'services.php?form=1&serviceid='.$child['serviceid']);
	$childrenLink->setAttribute('target', '_blank');

	$row = new CRow(array(
		array(
			$childrenLink,
			new CVar('children['.$child['serviceid'].'][name]', $child['name']),
			new CVar('children['.$child['serviceid'].'][serviceid]', $child['serviceid'])
		),
		new CCheckBox(
			'children['.$child['serviceid'].'][soft]',
			isset($child['soft']) && !empty($child['soft']) ? 'checked' : 'no',
			null,
			1
		),
		!empty($child['trigger']) ? $child['trigger'] : '-',
		new CButton('remove', _('Remove'), 'javascript: removeDependentChild(\''.$child['serviceid'].'\');', 'link_menu')
	));
	$row->setAttribute('id', 'children_'.$child['serviceid']);
	$servicesChildTable->addRow($row);
}
$servicesDependenciesFormList = new CFormList('servicesDependensiesFormList');
$servicesDependenciesFormList->addRow(
	_('Depends on'),
	new CDiv(array(
		$servicesChildTable,
		new CButton('add_child_service', _('Add'), "javascript: openWinCentered('services.php?cservices=1".url_param('serviceid')."', 'ZBX_Services_List', 640, 520, 'scrollbars=1, toolbar=0, menubar=0, resizable=0');", 'link_menu'),
	),
	'objectgroup inlineblock border_dotted ui-corner-all')
);

/*
 * Service times tab
 */
$servicesTimeFormList = new CFormList('servicesTimeFormList');
$servicesTimeTable = new CTable(_('No times defined. Work 24x7.'), 'formElementTable');
$servicesTimeTable->setAttribute('style', 'min-width: 500px;');
$servicesTimeTable->setHeader(array(_('Type'), _('Interval'), _('Note'), _('Action')));

$i = 0;
foreach ($this->data['times'] as $serviceTime) {
	switch ($serviceTime['type']) {
		case SERVICE_TIME_TYPE_UPTIME:
			$type = new CSpan(_('Uptime'), 'enabled');
			$from = dowHrMinToStr($serviceTime['ts_from']);
			$to = dowHrMinToStr($serviceTime['ts_to'], true);
			break;
		case SERVICE_TIME_TYPE_DOWNTIME:
			$type = new CSpan(_('Downtime'), 'disabled');
			$from = dowHrMinToStr($serviceTime['ts_from']);
			$to = dowHrMinToStr($serviceTime['ts_to'], true);
			break;
		case SERVICE_TIME_TYPE_ONETIME_DOWNTIME:
			$type = new CSpan(_('One-time downtime'), 'disabled');
			$from = zbx_date2str(DATE_TIME_FORMAT, $serviceTime['ts_from']);
			$to = zbx_date2str(DATE_TIME_FORMAT, $serviceTime['ts_to']);
			break;
	}
	$row = new CRow(array(
		array(
			$type,
			new CVar('times['.$i.'][type]', $serviceTime['type']),
			new CVar('times['.$i.'][ts_from]', $serviceTime['ts_from']),
			new CVar('times['.$i.'][ts_to]', $serviceTime['ts_to']),
			new CVar('times['.$i.'][note]', $serviceTime['note'])
		),
		$from.' - '.$to,
		htmlspecialchars($serviceTime['note']),
		new CButton('remove', _('Remove'), 'javascript: removeTime(\''.$i.'\');', 'link_menu')
	));
	$row->setAttribute('id', 'times_'.$i);
	$servicesTimeTable->addRow($row);
	$i++;
}
$servicesTimeFormList->addRow(
	_('Service times'),
	new CDiv($servicesTimeTable, 'objectgroup inlineblock border_dotted ui-corner-all')
);

// create service time table
$serviceTimeTable = new CTable(null, 'formElementTable');
if ($this->data['new_service_time']['type'] == SERVICE_TIME_TYPE_ONETIME_DOWNTIME) {
	// downtime since
	if (isset($_REQUEST['new_service_time']['from'])) {
		$fromYear = getRequest('new_service_time_from_year');
		$fromMonth = getRequest('new_service_time_from_month');
		$fromDay = getRequest('new_service_time_from_day');
		$fromHours = getRequest('new_service_time_from_hour');
		$fromMinutes = getRequest('new_service_time_from_minute');
		$fromDate = array(
			'y' => $fromYear,
			'm' => $fromMonth,
			'd' => $fromDay,
			'h' => $fromHours,
			'i' => $fromMinutes
		);
		$serviceTimeFrom = $fromYear.$fromMonth.$fromDay.$fromHours.$fromMinutes;
	}
	else {
		$downtimeSince = date(TIMESTAMP_FORMAT_ZERO_TIME);
		$fromDate = zbxDateToTime($downtimeSince);
		$serviceTimeFrom = $downtimeSince;
	}
	$servicesForm->addVar('new_service_time[from]', $serviceTimeFrom);

	// downtime till
	if (isset($_REQUEST['new_service_time']['to'])) {
		$toYear = getRequest('new_service_time_to_year');
		$toMonth = getRequest('new_service_time_to_month');
		$toDay = getRequest('new_service_time_to_day');
		$toHours = getRequest('new_service_time_to_hour');
		$toMinutes = getRequest('new_service_time_to_minute');
		$toDate = array(
			'y' => $toYear,
			'm' => $toMonth,
			'd' => $toDay,
			'h' => $toHours,
			'i' => $toMinutes
		);
		$serviceTimeTo = $toYear.$toMonth.$toDay.$toHours.$toMinutes;
	}
	else {
		$downtimeTill = date(TIMESTAMP_FORMAT_ZERO_TIME, time() + SEC_PER_DAY);
		$toDate = zbxDateToTime($downtimeTill);
		$serviceTimeTo = $downtimeTill;
	}
	$servicesForm->addVar('new_service_time[to]', $serviceTimeTo);

	// create calendar table
	$timeCalendarTable = new CTable();

	$noteTextBox = new CTextBox('new_service_time[note]', '', ZBX_TEXTBOX_STANDARD_SIZE);
	$noteTextBox->setAttribute('placeholder', _('short description'));
	$timeCalendarTable->addRow(array(_('Note'), $noteTextBox));
	$timeCalendarTable->addRow(array(_('From'), createDateSelector('new_service_time_from', $fromDate, 'new_service_time_to')));
	$timeCalendarTable->addRow(array(_('Till'), createDateSelector('new_service_time_to', $toDate, 'new_service_time_from')));
	$serviceTimeTable->addRow($timeCalendarTable);
}
else {
	$weekFromComboBox = new CComboBox('new_service_time[from_week]', isset($_REQUEST['new_service_time']['from_week'])
			? $_REQUEST['new_service_time']['from_week'] : 0);
	$weekToComboBox = new CComboBox('new_service_time[to_week]', isset($_REQUEST['new_service_time']['from_week'])
			? $_REQUEST['new_service_time']['to_week'] : 0);
	for ($dow = 0; $dow < 7; $dow++) {
		$weekFromComboBox->addItem($dow, getDayOfWeekCaption($dow));
		$weekToComboBox->addItem($dow, getDayOfWeekCaption($dow));
	}
	$timeFromHourTextBox = new CTextBox('new_service_time[from_hour]', isset($_REQUEST['new_service_time']['from_hour'])
			? $_REQUEST['new_service_time']['from_hour'] : '', 2, false, 2);
	$timeFromHourTextBox->setAttribute('placeholder', _('hh'));
	$timeFromMinuteTextBox = new CTextBox('new_service_time[from_minute]', isset($_REQUEST['new_service_time']['from_minute'])
			? $_REQUEST['new_service_time']['from_minute'] : '', 2, false, 2);
	$timeFromMinuteTextBox->setAttribute('placeholder', _('mm'));
	$timeToHourTextBox = new CTextBox('new_service_time[to_hour]', isset($_REQUEST['new_service_time']['to_hour'])
			? $_REQUEST['new_service_time']['to_hour'] : '', 2, false, 2);
	$timeToHourTextBox->setAttribute('placeholder', _('hh'));
	$timeToMinuteTextBox = new CTextBox('new_service_time[to_minute]', isset($_REQUEST['new_service_time']['to_minute'])
			? $_REQUEST['new_service_time']['to_minute'] : '', 2, false, 2);
	$timeToMinuteTextBox->setAttribute('placeholder', _('mm'));

	$serviceTimeTable->addRow(array(_('From'), $weekFromComboBox, new CCol(array(_('Time'), SPACE, $timeFromHourTextBox, ' : ', $timeFromMinuteTextBox))));
	$serviceTimeTable->addRow(array(_('Till'), $weekToComboBox, new CCol(array(_('Time'), SPACE, $timeToHourTextBox, ' : ', $timeToMinuteTextBox))));
	$servicesForm->addVar('new_service_time[note]', '');
}

$timeTypeComboBox = new CComboBox('new_service_time[type]', $this->data['new_service_time']['type'], 'javascript: document.forms[0].action += \'?form=1\'; submit();');
$timeTypeComboBox->addItem(SERVICE_TIME_TYPE_UPTIME, _('Uptime'));
$timeTypeComboBox->addItem(SERVICE_TIME_TYPE_DOWNTIME, _('Downtime'));
$timeTypeComboBox->addItem(SERVICE_TIME_TYPE_ONETIME_DOWNTIME, _('One-time downtime'));
$servicesTimeFormList->addRow(
	_('New service time'),
	new CDiv(array(
		new CDiv($timeTypeComboBox, 'time-type-combobox'),
		$serviceTimeTable,
		new CButton('add_service_time', _('Add'), null, 'link_menu')
	),
	'objectgroup inlineblock border_dotted ui-corner-all')
);

/*
 * Append tabs to form
 */
$servicesTab = new CTabView();
if (!$this->data['form_refresh']) {
	$servicesTab->setSelected(0);
}
$servicesTab->addTab('servicesTab', _('Service'), $servicesFormList);
$servicesTab->addTab('servicesDependenciesTab', _('Dependencies'), $servicesDependenciesFormList);
$servicesTab->addTab('servicesTimeTab', _('Time'), $servicesTimeFormList);
$servicesForm->addItem($servicesTab);

// append buttons to form
if ($service['serviceid']) {
	if ($service['dependencies']) {
		$btnDelete = null;
	}
	else {
		$btnDelete = new CButtonDelete(
			'Delete selected service?',
			url_param('form').url_param('serviceid').'&saction=1'
		);
	}

	$servicesForm->addItem(makeFormFooter(
		new CSubmit('update', _('Update'), 'javascript: document.forms[0].action += \'?saction=1\';'),
		array (
			$btnDelete,
			new CButtonCancel()
		)
	));
}
else {
	$servicesForm->addItem(makeFormFooter(
		new CSubmit('add', _('Add'), 'javascript: document.forms[0].action += \'?saction=1\';'),
		new CButtonCancel()
	));
}

// append form to widget
$servicesWidget->addItem($servicesForm);

return $servicesWidget;


text:
namespace Minesweeper.Menu
{
    using Minesweeper.Engine;
    using Minesweeper.Enumerations;
    using System;

    internal class ProcessInput
    {
        /// <summary>
        /// Process the set choice from RETURN/EXIT MENU and retrieves the result from it
        /// </summary>
        /// <param name="currentChoice">takes the set choice from the user as argument</param>
        /// <param name="game">imports the game engine</param>
        public static void ProcessSecondMenu(int currentChoice, MinesweeperEngine game)
        {
            switch (currentChoice)
            {
                case 0:
                    Console.Clear();
                    PrintLogo.Print();
                    MainMenu.PrintMenu(game);
                    break;
                case 1:
                    game.ExecuteCommand("exit");
                    break;
            }
        }

        /// <summary>
        /// Process the set choice from GAMEDIFFICULTY MENU and retrieves the result from it
        /// </summary>
        /// <param name="currentChoice">takes the set choice from the user as argument</param>
        /// <param name="game">imports the game engine</param>
        public static void ProcessGameDifficulty(int currentChoice, MinesweeperEngine game)
        {
            switch (currentChoice)
            {
                case 0:
                    game.ExecuteCommand("start small");
                    break;
                case 1:
                    game.ExecuteCommand("start medium");
                    break;
                case 2:
                    game.ExecuteCommand("start big");
                    break;
            }
        }

        /// <summary>
        /// Process the set choice from LIGHT/DARK MENU and retrieves the result from it
        /// </summary>
        /// <param name="currentChoice">takes the set choice from the user as argument</param>
        /// <param name="game">imports the game engine</param>
        public static void ProcessGameMode(int currentChoice, MinesweeperEngine game)
        {
            switch (currentChoice)
            {
                case 0:
                    game.ExecuteCommand("mode light");
                    break;
                case 1:
                    game.ExecuteCommand("mode dark");
                    break;
            }

            Navigation.ReturnExitNavigation(game, new SecondMenuOptions());
        }

        /// <summary>
        /// Process the set choice from MAIN MENU and retrieves the result from it
        /// </summary>
        /// <param name="inputChoice">takes the set choice from the user as argument</param>
        /// <param name="game">imports the game engine</param>
        public static void ProcessMainMenu(int inputChoice, MinesweeperEngine game)
        {
            if (inputChoice == 0)
            {
                Console.Clear();
                PrintLogo.Print();
                Console.SetCursorPosition((CustomizeConsole.Width / 2) - 10, 10);
                Console.WriteLine("- CHOOSE GAME DIFFICULTY -\n\n\n");

                Navigation.GameDifficultyNavigation(game, new MatrixTypes());
            }
            else if (inputChoice == 1)
            {
                Console.Clear();
                PrintLogo.Print();
                Console.SetCursorPosition((CustomizeConsole.Width / 2) - 10, 10);
                Console.WriteLine("- HIGH SCORES -\n\n\n");
                game.ExecuteCommand("highscore");
                Navigation.ReturnExitNavigation(game, new SecondMenuOptions());
            }
            else if (inputChoice == 2)
            {
                Console.Clear();
                PrintLogo.Print();
                Console.SetCursorPosition((CustomizeConsole.Width / 2) - 10, 10);
                Console.WriteLine("- CHOOSE MODE TO PLAY -\n\n\n");

                Navigation.GameModeNavigation(game, new ModeOptions());

                Navigation.ReturnExitNavigation(game, new SecondMenuOptions());
            }
            else if (inputChoice == 3)
            {
                Console.Clear();
                PrintLogo.Print();
                Console.SetCursorPosition(20, 9);
                Console.WriteLine(" - HOW TO PLAY - \n\n\n");
                Console.WriteLine("   * Enter 'turn row col' (where row and col are numbers) to open a new field");
                Console.WriteLine("   * Enter 'exit' to Exit the game");
                Console.WriteLine("   * Enter 'save' to Save the current state of the game");
                Console.WriteLine("   * Enter 'load' to Load previously saved game");
                Console.WriteLine("   * Enter 'menu' to return to Main Menu");
                Console.WriteLine("   * Enter 'highscore' to review the highscores table");

                Navigation.ReturnExitNavigation(game, new SecondMenuOptions());
            }
            else if (inputChoice == 4)
            {
                game.ExecuteCommand("exit");
            }
        }
    }
}


text:
<?php
/**
 * Theme related functions.
 *
 */

/**
 * Get title for the webpage by concatenating page specific title with site-wide title.
 *
 * @param string $title for this page.
 * @return string/null wether the favicon is defined or not.
 */
function get_title($title) {
  global $vason;
  return $title . (isset($vason['title_append']) ? $vason['title_append'] : null);
}

/**
 * Create a navigation bar / menu, with submenu.
 *
 * @param string $menu for the navigation bar.
 * @return string as the html for the menu.
 */
function get_navbar($menu) {
  // Keep default options in an array and merge with incoming options that can override the defaults.
  $default = array(
    'id'      => null,
    'class'   => null,
    'wrapper' => 'nav',
  );
  $menu = array_replace_recursive($default, $menu);

  // Create the ul li menu from the array, use an anonomous recursive function that returns an array of values.
  $create_menu = function($items, $callback) use (&$create_menu) {
    $html = null;
    $hasItemIsSelected = false;

    foreach($items as $item) {

      // has submenu, call recursivly and keep track on if the submenu has a selected item in it.
      $submenu        = null;
      $selectedParent = null;
      if(isset($item['submenu'])) {
        list($submenu, $selectedParent) = $create_menu($item['submenu']['items'], $callback);
        $selectedParent = $selectedParent ? " selected-parent" : null;
      }

      // Check if the current menuitem is selected
      $selected = $callback($item['url']) ? 'selected' : null;
      if($selected) {
        $hasItemIsSelected = true;
      }
      $selected = ($selected || $selectedParent) ? " class='${selected}{$selectedParent}' " : null;
      $html .= "\n
{$item['text']}{$submenu}
\n";
    }

    return array("\n
$html
\n", $hasItemIsSelected);
  };

  // Call the anonomous function to create the menu, and submenues if any.
  list($html, $ignore) = $create_menu($menu['items'], $menu['callback']);

  // Set the id & class element, only if it exists in the menu-array
  $id      = isset($menu['id'])    ? " id='{$menu['id']}'"       : null;
  $class   = isset($menu['class']) ? " class='{$menu['class']}'" : null;
  $wrapper = $menu['wrapper'];

  return "\n<{$wrapper}{$id}{$class}>{$html}</{$wrapper}>\n";
}


text:
package com.blackducksoftware.integration.jira.web.controller;

import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.atlassian.jira.issue.fields.FieldManager;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.workflow.WorkflowManager;
import com.atlassian.jira.workflow.WorkflowSchemeManager;
import com.atlassian.sal.api.pluginsettings.PluginSettingsFactory;
import com.atlassian.sal.api.transaction.TransactionTemplate;
import com.atlassian.sal.api.user.UserManager;
import com.blackducksoftware.integration.jira.common.WorkflowHelper;
import com.blackducksoftware.integration.jira.data.accessor.JiraSettingsAccessor;
import com.blackducksoftware.integration.jira.web.action.IssueFieldMappingConfigActions;
import com.blackducksoftware.integration.jira.web.action.ProjectMappingConfigActions;
import com.blackducksoftware.integration.jira.web.model.BlackDuckJiraConfigSerializable;
import com.blackducksoftware.integration.jira.web.model.BlackDuckJiraFieldCopyConfigSerializable;
import com.blackducksoftware.integration.jira.web.model.Fields;
import com.blackducksoftware.integration.jira.web.model.ProjectFieldCopyMapping;

@Path("/config/issue/field/mapping")
public class IssueFieldMappingConfigController extends ConfigController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    final FieldManager fieldManager;
    private final IssueFieldMappingConfigActions issueFieldMappingConfigActions;
    private final ProjectMappingConfigActions projectMappingConfigActions;

    public IssueFieldMappingConfigController(final PluginSettingsFactory pluginSettingsFactory, final TransactionTemplate transactionTemplate, final UserManager userManager, final FieldManager fieldManager,
        final WorkflowManager workflowManager, final WorkflowSchemeManager workflowSchemeManager, final ProjectManager projectManager, final Properties i18nProperties) {
        super(pluginSettingsFactory, transactionTemplate, userManager);
        this.fieldManager = fieldManager;

        final JiraSettingsAccessor jiraSettingsAccessor = new JiraSettingsAccessor(pluginSettingsFactory.createGlobalSettings());
        this.issueFieldMappingConfigActions = new IssueFieldMappingConfigActions(jiraSettingsAccessor, i18nProperties, fieldManager);
        this.projectMappingConfigActions = new ProjectMappingConfigActions(jiraSettingsAccessor, new WorkflowHelper(workflowManager, workflowSchemeManager, projectManager));
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    // FIXME move this to a ProjectMappingConfigController in the next major version
    public Response getMappings(@Context final HttpServletRequest request) {
        final Object config;
        try {
            final boolean validAuthentication = isAuthorized(request);
            if (!validAuthentication) {
                return Response.status(Status.UNAUTHORIZED).build();
            }
            config = executeAsTransaction(() -> projectMappingConfigActions.getMappings());
        } catch (final Exception e) {
            final BlackDuckJiraConfigSerializable errorConfig = new BlackDuckJiraConfigSerializable();
            final String msg = "Error getting project mappings: " + e.getMessage();
            logger.error(msg, e);
            return Response.ok(errorConfig).build();
        }
        return Response.ok(config).build();
    }

    @Path("/sources")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getSourceFields(@Context final HttpServletRequest request) {
        final Object sourceFields;
        try {
            final boolean validAuthentication = isAuthorized(request);
            if (!validAuthentication) {
                return Response.status(Status.UNAUTHORIZED).build();
            }

            sourceFields = executeAsTransaction(() -> issueFieldMappingConfigActions.getSourceFields());
        } catch (final Exception e) {
            final Fields errorSourceFields = new Fields();
            final String msg = "Error getting source fields: " + e.getMessage();
            logger.error(msg, e);
            errorSourceFields.setErrorMessage(msg);
            return Response.ok(errorSourceFields).build();
        }
        return Response.ok(sourceFields).build();
    }

    @Path("/targets")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getTargetFields(@Context final HttpServletRequest request) {
        final Object targetFields;
        try {
            final boolean validAuthentication = isAuthorized(request);
            if (!validAuthentication) {
                return Response.status(Status.UNAUTHORIZED).build();
            }

            targetFields = executeAsTransaction(() -> issueFieldMappingConfigActions.getTargetFields());
        } catch (final Exception e) {
            final Fields errorTargetFields = new Fields();
            final String msg = "Error getting target fields: " + e.getMessage();
            logger.error(msg, e);
            errorTargetFields.setErrorMessage(msg);
            return Response.ok(errorTargetFields).build();
        }
        return Response.ok(targetFields).build();
    }

    @Path("/copies")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Response getFieldCopyMappings(@Context final HttpServletRequest request) {
        final Object config;
        try {
            logger.debug("Get /copies");
            final boolean validAuthentication = isAuthorized(request);
            if (!validAuthentication) {
                return Response.status(Status.UNAUTHORIZED).build();
            }
            config = executeAsTransaction(() -> issueFieldMappingConfigActions.getFieldCopyMappings());
        } catch (final Exception e) {
            final BlackDuckJiraConfigSerializable errorConfig = new BlackDuckJiraConfigSerializable();
            final String msg = "Error getting field mappings: " + e.getMessage();
            logger.error(msg, e);
            return Response.ok(errorConfig).build();
        }

        final BlackDuckJiraFieldCopyConfigSerializable returnValue = (BlackDuckJiraFieldCopyConfigSerializable) config;
        logger.debug("returnValue: " + returnValue);
        return Response.ok(config).build();
    }

    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    public Response updateFieldCopyConfiguration(final BlackDuckJiraFieldCopyConfigSerializable fieldCopyConfig, @Context final HttpServletRequest request) {
        try {
            logger.debug("updateFieldCopyConfiguration() received " + fieldCopyConfig.getProjectFieldCopyMappings().size() + " rows.");
            logger.debug("fieldCopyConfig.getProjectFieldCopyMappings(): " + fieldCopyConfig.getProjectFieldCopyMappings());
            for (final ProjectFieldCopyMapping projectFieldCopyMapping : fieldCopyConfig.getProjectFieldCopyMappings()) {
                logger.debug("projectFieldCopyMapping: " + projectFieldCopyMapping);
            }

            final boolean validAuthentication = isAuthorized(request);
            if (!validAuthentication) {
                return Response.status(Status.UNAUTHORIZED).build();
            }
            executeAsTransaction(() -> issueFieldMappingConfigActions.updateFieldCopyMappings(fieldCopyConfig));
        } catch (final Exception e) {
            final String msg = "Exception during admin save: " + e.getMessage();
            logger.error(msg, e);
            fieldCopyConfig.setErrorMessage(msg);
        }
        if (fieldCopyConfig.hasErrors()) {
            return Response.ok(fieldCopyConfig).status(Status.BAD_REQUEST).build();
        }
        return Response.noContent().build();
    }

}