text:
/*
 * L.Control.Loading is a control that shows a loading indicator when tiles are
 * loading or when map-related AJAX requests are taking place.
 */

(function () {

    var console = window.console || {
        error: function () {},
        warn: function () {}
    };

    function defineLeafletLoading(L) {
        L.Control.Loading = L.Control.extend({
            options: {
                delayIndicator: null,
                position: 'topleft',
                separate: false,
                zoomControl: null,
                spinjs: false,
                spin: {
                    lines: 7,
                    length: 3,
                    width: 3,
                    radius: 5,
                    rotate: 13,
                    top: "83%"
                }
            },

            initialize: function(options) {
                L.setOptions(this, options);
                this._dataLoaders = {};

                // Try to set the zoom control this control is attached to from
                // the options
                if (this.options.zoomControl !== null) {
                    this.zoomControl = this.options.zoomControl;
                }
            },

            onAdd: function(map) {
                if (this.options.spinjs && (typeof Spinner !== 'function')) {
                    return console.error("Leaflet.loading cannot load because you didn't load spin.js (http://fgnass.github.io/spin.js/), even though you set it in options.");
                }
                this._addLayerListeners(map);
                this._addMapListeners(map);

                // Try to set the zoom control this control is attached to from the map
                // the control is being added to
                if (!this.options.separate && !this.zoomControl) {
                    if (map.zoomControl) {
                        this.zoomControl = map.zoomControl;
                    } else if (map.zoomsliderControl) {
                        this.zoomControl = map.zoomsliderControl;
                    }
                }

                // Create the loading indicator
                var classes = 'leaflet-control-loading';
                var container;
                if (this.zoomControl && !this.options.separate) {
                    // If there is a zoom control, hook into the bottom of it
                    container = this.zoomControl._container;
                    // These classes are no longer used as of Leaflet 0.6
                    classes += ' leaflet-bar-part-bottom leaflet-bar-part last';

                    // Loading control will be added to the zoom control. So the visible last element is not the
                    // last dom element anymore. So add the part-bottom class.
                    L.DomUtil.addClass(this._getLastControlButton(), 'leaflet-bar-part-bottom');
                }
                else {
                    // Otherwise, create a container for the indicator
                    container = L.DomUtil.create('div', 'leaflet-control-zoom leaflet-control-layer-container leaflet-bar');
                }
                this._indicatorContainer = container;
                this._indicator = L.DomUtil.create('a', classes, container);
                if (this.options.spinjs) {
                    this._spinner = new Spinner(this.options.spin).spin();
                    this._indicator.appendChild(this._spinner.el);
                }
                return container;
            },

            onRemove: function(map) {
                this._removeLayerListeners(map);
                this._removeMapListeners(map);
            },

            removeFrom: function (map) {
                if (this.zoomControl && !this.options.separate) {
                    // Override Control.removeFrom() to avoid clobbering the entire
                    // _container, which is the same as zoomControl's
                    this._container.removeChild(this._indicator);
                    this._map = null;
                    this.onRemove(map);
                    return this;
                }
                else {
                    // If this control is separate from the zoomControl, call the
                    // parent method so we don't leave behind an empty container
                    return L.Control.prototype.removeFrom.call(this, map);
                }
            },

            addLoader: function(id) {
                this._dataLoaders[id] = true;
                if (this.options.delayIndicator && !this.delayIndicatorTimeout) {
                    // If we are delaying showing the indicator and we're not
                    // already waiting for that delay, set up a timeout.
                    var that = this;
                    this.delayIndicatorTimeout = setTimeout(function () {
                        that.updateIndicator();
                        that.delayIndicatorTimeout = null;
                    }, this.options.delayIndicator);
                }
                else {
                    // Otherwise show the indicator immediately
                    this.updateIndicator();
                }
            },

            removeLoader: function(id) {
                delete this._dataLoaders[id];
                this.updateIndicator();

                // If removing this loader means we're in no danger of loading,
                // clear the timeout. This prevents old delays from instantly
                // triggering the indicator.
                if (this.options.delayIndicator && this.delayIndicatorTimeout && !this.isLoading()) {
                    clearTimeout(this.delayIndicatorTimeout);
                    this.delayIndicatorTimeout = null;
                }
            },

            updateIndicator: function() {
                if (this.isLoading()) {
                    this._showIndicator();
                }
                else {
                    this._hideIndicator();
                }
            },

            isLoading: function() {
                return this._countLoaders() > 0;
            },

            _countLoaders: function() {
                var size = 0, key;
                for (key in this._dataLoaders) {
                    if (this._dataLoaders.hasOwnProperty(key)) size++;
                }
                return size;
            },

            _showIndicator: function() {
                // Show loading indicator
                L.DomUtil.addClass(this._indicator, 'is-loading');
                L.DomUtil.addClass(this._indicatorContainer, 'is-loading');

                // If zoomControl exists, make the zoom-out button not last
                if (!this.options.separate) {
                    if (this.zoomControl instanceof L.Control.Zoom) {
                        L.DomUtil.removeClass(this._getLastControlButton(), 'leaflet-bar-part-bottom');
                    }
                    else if (typeof L.Control.Zoomslider === 'function' && this.zoomControl instanceof L.Control.Zoomslider) {
                        L.DomUtil.removeClass(this.zoomControl._ui.zoomOut, 'leaflet-bar-part-bottom');
                    }
                }
            },

            _hideIndicator: function() {
                // Hide loading indicator
                L.DomUtil.removeClass(this._indicator, 'is-loading');
                L.DomUtil.removeClass(this._indicatorContainer, 'is-loading');

                // If zoomControl exists, make the zoom-out button last
                if (!this.options.separate) {
                    if (this.zoomControl instanceof L.Control.Zoom) {
                        L.DomUtil.addClass(this._getLastControlButton(), 'leaflet-bar-part-bottom');
                    }
                    else if (typeof L.Control.Zoomslider === 'function' && this.zoomControl instanceof L.Control.Zoomslider) {
                        L.DomUtil.addClass(this.zoomControl._ui.zoomOut, 'leaflet-bar-part-bottom');
                    }
                }
            },

            _getLastControlButton: function() {
                var container = this.zoomControl._container,
                    index = container.children.length - 1;

                // Find the last visible control button that is not our loading
                // indicator
                while (index > 0) {
                    var button = container.children[index];
                    if (!(this._indicator === button || button.offsetWidth === 0 || button.offsetHeight === 0)) {
                        break;
                    }
                    index--;
                }

                return container.children[index];
            },

            _handleLoading: function(e) {
                this.addLoader(this.getEventId(e));
            },

            _handleBaseLayerChange: function (e) {
                var that = this;

                // Check for a target 'layer' that contains multiple layers, such as
                // L.LayerGroup. This will happen if you have an L.LayerGroup in an
                // L.Control.Layers.
                if (e.layer && e.layer.eachLayer && typeof e.layer.eachLayer === 'function') {
                    e.layer.eachLayer(function (layer) {
                        that._handleBaseLayerChange({ layer: layer });
                    });
                }
                else {
                    // If we're changing to a canvas layer, don't handle loading
                    // as canvas layers will not fire load events.
                    if (!(L.TileLayer.Canvas && e.layer instanceof L.TileLayer.Canvas)) {
                        that._handleLoading(e);
                    }
                }
            },

            _handleLoad: function(e) {
                this.removeLoader(this.getEventId(e));
            },

            getEventId: function(e) {
                if (e.id) {
                    return e.id;
                }
                else if (e.layer) {
                    return e.layer._leaflet_id;
                }
                return e.target._leaflet_id;
            },

            _layerAdd: function(e) {
                if (!e.layer || !e.layer.on) return
                try {
                    e.layer.on({
                        loading: this._handleLoading,
                        load: this._handleLoad
                    }, this);
                }
                catch (exception) {
                    console.warn('L.Control.Loading: Tried and failed to add ' +
                                 ' event handlers to layer', e.layer);
                    console.warn('L.Control.Loading: Full details', exception);
                }
            },

            _layerRemove: function(e) {
                if (!e.layer || !e.layer.off) return;
                try {
                    e.layer.off({
                        loading: this._handleLoading,
                        load: this._handleLoad
                    }, this);
                }
                catch (exception) {
                    console.warn('L.Control.Loading: Tried and failed to remove ' +
                                 'event handlers from layer', e.layer);
                    console.warn('L.Control.Loading: Full details', exception);
                }
            },

            _addLayerListeners: function(map) {
                // Add listeners for begin and end of load to any layers already
                // on the map
                map.eachLayer(function(layer) {
                    if (!layer.on) return;
                    layer.on({
                        loading: this._handleLoading,
                        load: this._handleLoad
                    }, this);
                }, this);

                // When a layer is added to the map, add listeners for begin and
                // end of load
                map.on('layeradd', this._layerAdd, this);
                map.on('layerremove', this._layerRemove, this);
            },

            _removeLayerListeners: function(map) {
                // Remove listeners for begin and end of load from all layers
                map.eachLayer(function(layer) {
                    if (!layer.off) return;
                    layer.off({
                        loading: this._handleLoading,
                        load: this._handleLoad
                    }, this);
                }, this);

                // Remove layeradd/layerremove listener from map
                map.off('layeradd', this._layerAdd, this);
                map.off('layerremove', this._layerRemove, this);
            },

            _addMapListeners: function(map) {
                // Add listeners to the map for (custom) dataloading and dataload
                // events, eg, for AJAX calls that affect the map but will not be
                // reflected in the above layer events.
                map.on({
                    baselayerchange: this._handleBaseLayerChange,
                    dataloading: this._handleLoading,
                    dataload: this._handleLoad,
                    layerremove: this._handleLoad
                }, this);
            },

            _removeMapListeners: function(map) {
                map.off({
                    baselayerchange: this._handleBaseLayerChange,
                    dataloading: this._handleLoading,
                    dataload: this._handleLoad,
                    layerremove: this._handleLoad
                }, this);
            }
        });

        L.Map.addInitHook(function () {
            if (this.options.loadingControl) {
                this.loadingControl = new L.Control.Loading();
                this.addControl(this.loadingControl);
            }
        });

        L.Control.loading = function(options) {
            return new L.Control.Loading(options);
        };
    }

    if (typeof define === 'function' && define.amd) {
        // Try to add leaflet.loading to Leaflet using AMD
        define(['leaflet'], function (L) {
            defineLeafletLoading(L);
        });
    }
    else {
        // Else use the global L
        defineLeafletLoading(L);
    }

})();


text:
var selftest = require('../tool-testing/selftest.js');
const { AVAILABLE_SKELETONS } = require("../cli/commands");
var Sandbox = selftest.Sandbox;
const SIMPLE_WAREHOUSE = { v1: { recommended: true } };

selftest.define("create main", function () {
  // We need a warehouse so the tool doesn't think we are running from checkout
  var s = new Sandbox({ warehouse: SIMPLE_WAREHOUSE });
  // Can we create an app? Yes!
  var run = s.run("create", "foobar", "--blaze");
  run.match("Created a new Meteor app in 'foobar'.");
  run.match("To run your new app");
  run.expectExit(0);

  // Test that the release constraints have been written to .meteor/packages
  s.cd("foobar");
  const packages = s.read(".meteor/packages");
  if (!packages.match('meteor-base@')) {
    selftest.fail("Failed to add a version specifier to `meteor-base` package");
  }

  const packageJson = JSON.parse(s.read("package.json"));
  if (! packageJson.dependencies.hasOwnProperty("@babel/runtime")) {
    selftest.fail("New app package.json does not depend on @babel/runtime");
  }

  // Install basic packages like babel-runtime and meteor-node-stubs from
  // package.json.
  run = s.run("npm", "install");
  run.expectExit(0);

  // Now, can we run it?
  run = s.run();
  run.match("foobar");
  run.match("proxy.");
  // Do not print out the changes to the versions file!
  run.waitSecs(5);
  run.read("=> Started MongoDB", false);
  run.match("your app");
  run.match("running at");
  run.match("localhost");
  run.stop();

  run = s.run("create", "--list");
  run.read('Available');
  run.match('leaderboard');
  run.expectExit(0);
});

AVAILABLE_SKELETONS.forEach(template => {
  selftest.define("create --" + template, function () {
    const s = new Sandbox;

    // Can we create an app? Yes!
    let run = s.run("create", "--" + template, template);
    run.waitSecs(60);
    run.match("Created a new Meteor app in '" + template + "'.");
    run.match("To run your new app");

    s.cd(template);
    run = s.run();
    run.waitSecs(60);
    run.match(template);
    run.match("proxy")
    run.waitSecs(60);
    run.match("your app");
    run.waitSecs(5);
    run.match("running at");
    run.match("localhost");

    run.stop();
  });
});

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllosticta weigeliana Bubák & Kabát

### Remarks
null


text:
using InputHelper;
using MenuBuddy;
using Microsoft.Xna.Framework;
using System.Threading.Tasks;

namespace InsertCoinBuddy
{
	/// <summary>
	/// The options screen is brought up over the top of the main menu
	/// screen, and gives the user a chance to configure the game in various hopefully useful ways.
	/// If you'd like to add more options to this screen, inherit from it and use SettingsComponent<YourScreen>()
	/// </summary>
	public class SettingsScreen : MenuStackScreen
	{
		#region Fields

		/// <summary>
		/// menu entry to change the difficulty
		/// </summary>
		private MenuEntryInt _difficulty;

		/// <summary>
		/// menu entry to change the num credits to play
		/// </summary>
		private MenuEntryInt _numCredits;

		/// <summary>
		/// menu entry to change the attract mode sound on/off
		/// </summary>
		private MenuEntryBool _attractModeSound;

		/// <summary>
		/// menu entry to change the attract mode music on/off
		/// </summary>
		private MenuEntryBool _attractModeMusic;

		private MenuEntry _doneMenuEntry;

		public ISettingsComponent Settings { get; set; }

		#endregion

		#region Initialization

		/// <summary>
		/// Constructor.
		/// </summary>
		public SettingsScreen()
			: base("Operator Settings")
		{
			CoverOtherScreens = true;
			CoveredByOtherScreens = false;
		}

		public override async Task LoadContent()
		{
			await base.LoadContent();

			//Create our menu entries.
			_difficulty = new MenuEntryInt("Difficulty", Settings.Settings.Difficulty, Content)
			{
				Step = 1,
				Min = 1,
				Max = 10,
			};

			_numCredits = new MenuEntryInt("Credits Per Play", Settings.Settings.CoinsPerCredit, Content)
			{
				Step = 1,
				Min = 0,
				Max = 20,
			};

			_attractModeSound = new MenuEntryBool("Attract Mode Sound", Settings.Settings.AttractModeSound, Content)
			{
			};

			_attractModeMusic = new MenuEntryBool("Attract Mode Music", Settings.Settings.AttractModeMusic, Content)
			{
			};

			_doneMenuEntry = new MenuEntry("Done", Content)
			{
			};

			_doneMenuEntry.OnClick += Done;

			//Add entries to the menu.
			AddMenuEntry(_difficulty);
			AddMenuEntry(_numCredits);
			AddMenuEntry(_attractModeSound);
			AddMenuEntry(_attractModeMusic);
			AddMenuEntry(_doneMenuEntry);
		}

		#endregion

		#region Handle Input

		/// <summary>
		/// Handler for when the user has cancelled the menu.
		/// </summary>
		protected virtual void Done(object obj, ClickEventArgs e)
		{
			//update settings object from menu entries
			Settings.Settings.Difficulty = _difficulty.Value;
			Settings.Settings.CoinsPerCredit = _numCredits.Value;
			Settings.Settings.AttractModeSound = _attractModeSound.Value;
			Settings.Settings.AttractModeMusic = _attractModeMusic.Value;

			//save settings
			Settings.SaveSettings();

			ExitScreen();
		}

		public override void Draw(GameTime gameTime)
		{
			//Draw on a black background
			ScreenManager.SpriteBatchBegin();
			FadeBackground();
			ScreenManager.SpriteBatchEnd();

			base.Draw(gameTime);
		}

		#endregion
	}
}


text:
from bs4 import BeautifulSoup
import login
import transcript

class MinervaReader:

	def __init__(self, site):
		self.site = site

	def login(self, html):

		"""
		Parses the result login page and extract the info message that determines a successful login.
		"""

		if not 'WELCOME' in html.geturl():
			return None, login.welcomeerr(html)
		else:
			return True, login.welcomemsg(html)

	def logout(self, html):
		"""
		Parses the content of the logout page and returns the message parsed.
		"""

		return 'You were successfully logged out.'

	def transcript(self, html, semester='all'):
		"""
		Parses the transcript page to extract the transcript as a json object.
		"""

		soup = BeautifulSoup(html)

		# Gets the div containing the table
		div = soup.body.find('div', {'class':'pagebodydiv'})

		# Gets the table inside that div
		tbl = div.find('table', {'class':'dataentrytable', 'width':'100%'})

		# Turns the html table into a list of lists (2D list)
		table = [col.findAll('td') for col in tbl.findAll('tr')]

		curriculum = transcript.get_curriculum(table)

		return curriculum


text:
package droidicus.aquaregia.util;

import net.minecraft.util.IStringSerializable;

/**
 * An interface representing a block or item variant.
 *
 * @author Choonster
 */
public interface IVariant extends IStringSerializable {

    /**
     * Get the metadata value of this variant.
     *
     * @return The metadata value
     */
    int getMeta();
}


text:
#include "src/core/lib/iomgr/port.h"

// This test won't work except with libuv
#ifdef GRPC_UV

#include <uv.h>

#include <string.h>

#include "src/core/lib/iomgr/tcp_client.h"

#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>

#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/pollset.h"
#include "src/core/lib/iomgr/timer.h"
#include "test/core/util/test_config.h"

static gpr_mu *g_mu;
static grpc_pollset *g_pollset;
static int g_connections_complete = 0;
static grpc_endpoint *g_connecting = NULL;

static gpr_timespec test_deadline(void) {
  return grpc_timeout_seconds_to_deadline(10);
}

static void finish_connection() {
  gpr_mu_lock(g_mu);
  g_connections_complete++;
  GPR_ASSERT(
      GRPC_LOG_IF_ERROR("pollset_kick", grpc_pollset_kick(g_pollset, NULL)));
  gpr_mu_unlock(g_mu);
}

static void must_succeed(grpc_exec_ctx *exec_ctx, void *arg,
                         grpc_error *error) {
  GPR_ASSERT(g_connecting != NULL);
  GPR_ASSERT(error == GRPC_ERROR_NONE);
  grpc_endpoint_shutdown(exec_ctx, g_connecting,
                         GRPC_ERROR_CREATE("must_succeed called"));
  grpc_endpoint_destroy(exec_ctx, g_connecting);
  g_connecting = NULL;
  finish_connection();
}

static void must_fail(grpc_exec_ctx *exec_ctx, void *arg, grpc_error *error) {
  GPR_ASSERT(g_connecting == NULL);
  GPR_ASSERT(error != GRPC_ERROR_NONE);
  finish_connection();
}

static void close_cb(uv_handle_t *handle) { gpr_free(handle); }

static void connection_cb(uv_stream_t *server, int status) {
  uv_tcp_t *client_handle = gpr_malloc(sizeof(uv_tcp_t));
  GPR_ASSERT(0 == status);
  GPR_ASSERT(0 == uv_tcp_init(uv_default_loop(), client_handle));
  GPR_ASSERT(0 == uv_accept(server, (uv_stream_t *)client_handle));
  uv_close((uv_handle_t *)client_handle, close_cb);
}

void test_succeeds(void) {
  grpc_resolved_address resolved_addr;
  struct sockaddr_in *addr = (struct sockaddr_in *)resolved_addr.addr;
  uv_tcp_t *svr_handle = gpr_malloc(sizeof(uv_tcp_t));
  int connections_complete_before;
  grpc_closure done;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;

  gpr_log(GPR_DEBUG, "test_succeeds");

  memset(&resolved_addr, 0, sizeof(resolved_addr));
  resolved_addr.len = sizeof(struct sockaddr_in);
  addr->sin_family = AF_INET;

  /* create a dummy server */
  GPR_ASSERT(0 == uv_tcp_init(uv_default_loop(), svr_handle));
  GPR_ASSERT(0 == uv_tcp_bind(svr_handle, (struct sockaddr *)addr, 0));
  GPR_ASSERT(0 == uv_listen((uv_stream_t *)svr_handle, 1, connection_cb));

  gpr_mu_lock(g_mu);
  connections_complete_before = g_connections_complete;
  gpr_mu_unlock(g_mu);

  /* connect to it */
  GPR_ASSERT(uv_tcp_getsockname(svr_handle, (struct sockaddr *)addr,
                                (int *)&resolved_addr.len) == 0);
  grpc_closure_init(&done, must_succeed, NULL, grpc_schedule_on_exec_ctx);
  grpc_tcp_client_connect(&exec_ctx, &done, &g_connecting, NULL, NULL,
                          &resolved_addr, gpr_inf_future(GPR_CLOCK_REALTIME));

  gpr_mu_lock(g_mu);

  while (g_connections_complete == connections_complete_before) {
    grpc_pollset_worker *worker = NULL;
    GPR_ASSERT(GRPC_LOG_IF_ERROR(
        "pollset_work",
        grpc_pollset_work(&exec_ctx, g_pollset, &worker,
                          gpr_now(GPR_CLOCK_MONOTONIC),
                          grpc_timeout_seconds_to_deadline(5))));
    gpr_mu_unlock(g_mu);
    grpc_exec_ctx_flush(&exec_ctx);
    gpr_mu_lock(g_mu);
  }

  // This will get cleaned up when the pollset runs again or gets shutdown
  uv_close((uv_handle_t *)svr_handle, close_cb);

  gpr_mu_unlock(g_mu);

  grpc_exec_ctx_finish(&exec_ctx);
}

void test_fails(void) {
  grpc_resolved_address resolved_addr;
  struct sockaddr_in *addr = (struct sockaddr_in *)resolved_addr.addr;
  int connections_complete_before;
  grpc_closure done;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;

  gpr_log(GPR_DEBUG, "test_fails");

  memset(&resolved_addr, 0, sizeof(resolved_addr));
  resolved_addr.len = sizeof(struct sockaddr_in);
  addr->sin_family = AF_INET;

  gpr_mu_lock(g_mu);
  connections_complete_before = g_connections_complete;
  gpr_mu_unlock(g_mu);

  /* connect to a broken address */
  grpc_closure_init(&done, must_fail, NULL, grpc_schedule_on_exec_ctx);
  grpc_tcp_client_connect(&exec_ctx, &done, &g_connecting, NULL, NULL,
                          &resolved_addr, gpr_inf_future(GPR_CLOCK_REALTIME));

  gpr_mu_lock(g_mu);

  /* wait for the connection callback to finish */
  while (g_connections_complete == connections_complete_before) {
    grpc_pollset_worker *worker = NULL;
    gpr_timespec now = gpr_now(GPR_CLOCK_MONOTONIC);
    gpr_timespec polling_deadline = test_deadline();
    if (!grpc_timer_check(&exec_ctx, now, &polling_deadline)) {
      GPR_ASSERT(GRPC_LOG_IF_ERROR(
          "pollset_work", grpc_pollset_work(&exec_ctx, g_pollset, &worker, now,
                                            polling_deadline)));
    }
    gpr_mu_unlock(g_mu);
    grpc_exec_ctx_flush(&exec_ctx);
    gpr_mu_lock(g_mu);
  }

  gpr_mu_unlock(g_mu);
  grpc_exec_ctx_finish(&exec_ctx);
}

static void destroy_pollset(grpc_exec_ctx *exec_ctx, void *p,
                            grpc_error *error) {
  grpc_pollset_destroy(p);
}

int main(int argc, char **argv) {
  grpc_closure destroyed;
  grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT;
  grpc_test_init(argc, argv);
  grpc_init();
  g_pollset = gpr_malloc(grpc_pollset_size());
  grpc_pollset_init(g_pollset, &g_mu);
  grpc_exec_ctx_finish(&exec_ctx);
  test_succeeds();
  gpr_log(GPR_ERROR, "End of first test");
  test_fails();
  grpc_closure_init(&destroyed, destroy_pollset, g_pollset,
                    grpc_schedule_on_exec_ctx);
  grpc_pollset_shutdown(&exec_ctx, g_pollset, &destroyed);
  grpc_exec_ctx_finish(&exec_ctx);
  grpc_shutdown();
  gpr_free(g_pollset);
  return 0;
}

#else /* GRPC_UV */

int main(int argc, char **argv) { return 1; }

#endif /* GRPC_UV */


text:
FAQ
===

Sprinter keeps overriding my custom *rc! How can I stop it?
-----------------------------------------------------------

Sprinter will always inject itself after everything in a profile or rc
file, with the exception of text in a block surrounded by
#SPRINTER_OVERRIDES. These will always run after any sprinter
configuration.

How do I make a sprinter formula?
---------------------------------

A sprinter formula is just a python module or egg that a python class
extends the 'formulabase' class, located in
`sprinter.formula.formulabase
<https://github.com/toumorokoshi/sprinter/blob/develop/sprinter/formulabase.py>`_.

If you're not familiar with python, it's easier to just follow an
example, like this one: https://github.com/toumorokoshi/yt.formula.node.

I need help! Who do I talk to?
------------------------------

If you have a question about a specific formula, it's best to pots a bug or talk to the author or the formula.

If you have questions about sprinter, your best bet is to post a message in the
`Google Group
<https://groups.google.com/forum/#!forum/sprinter-dev>`_.

If there's behaviour that you think is a bug, you can also
`create a ticket <https://github.com/toumorokoshi/sprinter/issues?state=open>`_.


text:
package render

const (
	ROWS          = 4
	COLUMNS       = 16
	COLS_PER_BEAT = 10
)

type Transition struct {
	Color    uint32
	Location float64 // [0,1]
	Length   float64 // [0,1]
}

type State struct {
	LEDs        [ROWS][COLUMNS]uint32
	Transitions [ROWS][COLUMNS]Transition
}

type Renderer interface {
	Render(state State)
}

// TODO: move this to somewhere more LED specific ?

type LedRenderer interface {
	Init(
		freq int,
		gpioPin1 int, ledCount1 int, brightness1 int,
		gpioPin2 int, ledCount2 int, brightness2 int,
	) error

	Fini()
	Render() error
	Wait() error
	SetLed(channel int, index int, value uint32)
	Clear()
	SetBitmap(channel int, a []uint32)
}


text:
package es.joseoc.learning.java.refactoring.switchifstatement.math.operation;

public final class SubractionExecutor implements BinaryOperation
{
	@Override
	public int execute(int operand1, int operand2) {
		return operand1 - operand2;
	}

}


text:
/*
 * Live view display of PCSC Card readers
 *
 * @author Edouard Lafargue, ed@lafargue.name
 */

define(function (require) {
    "use strict";

    var $ = require('jquery'),
        _ = require('underscore'),
        Backbone = require('backbone'),
        template = require('js/tpl/instruments/bleloc/LiveView.js'),
        bvtemplate = require('js/tpl/instruments/bleloc/bvView.js');

    // Need to load these, but no related variables.
    require('bootstrap');

    var beaconView = Backbone.View.extend({
        tagName: "div",
        className: "col-xs-2",

        initialize: function() {
            console.log('Model', this.model);
        },
        render: function() {
            this.$el.html(bvtemplate(this.model));
            return this;
        }
    });

    return Backbone.View.extend({

        initialize: function (options) {

            this.update_count = 0;
            this.datasetlength = 0;

            this.stations = [];
            this.cards = [];

            if (vizapp.type == 'cordova') {
                var wz_settings = instrumentManager.getInstrument().get('wizkers_settings');
                if (wz_settings) {
                    if (wz_settings.screen_no_dim == 'true') {
                        keepscreenon.enable();
                    } else {
                        keepscreenon.disable();
                    }
                } else {
                    // Happens when the user never explicitely set the screen dim
                    keepscreenon.disable();
                }
            }

            linkManager.on('status', this.updatestatus, this);
            linkManager.on('input', this.showInput, this);

        },

        events: {
            'click .utility_close': 'closeUtil'
        },

        tab_shown: function (e) {
            if (this.rsc)
                this.rsc();
        },

        render: function () {
            var self = this;
            console.log('Main render of BLE Loc view');
            this.$el.html(template());

            linkManager.requestStatus();
            return this;
        },

        onClose: function () {
            console.log("BLE Loc live view closing...");
            linkManager.stopLiveStream();
            linkManager.off('status', this.updatestatus);
            linkManager.off('input', this.showInput);
        },

        appendToResponse: function(str) {
            var i = this.$('#cardresponse');
            i.val(i.val() + str );
            // Autoscroll:
            i.scrollTop(i[0].scrollHeight - i.height());
        },

        updatestatus: function (data) {
            console.log("BLE Loc live display: link status update");
        },

        clear: function () {
            console.log('Clear');
        },

        // We get there whenever we receive something from the serial port
        showInput: function (data) {
            var self = this;
            console.log('Data', data);
            if (data.address) {
                var mac = data.address.replace(/:/g,'')
                if (this.stations[mac]) {
                    data.mac = mac;
                    this.cards[mac].model = data;
                    this.cards[mac].render();
                    self.$('#' + mac + ' .rssi').addClass('bg-warning');
                    setTimeout(function() {self.$('#' + mac + ' .rssi').removeClass('bg-warning');}, 200 );
                } else {
                    this.stations[mac] = data;
                    data.mac = mac;
                    this.cards[mac] = new beaconView({ model: data});
                    this.$('#beaconlist').append(
                        this.cards[mac].render().el
                    );
                }
            }

        },
    });

});


text:
use metrics::{Metric, Metrics};

metrics!(ClusterMetrics {
    errors: u64,
    poll_notifications: u64,
    joins: u64,
    leaves: u64,
    received_local_envelopes: u64,
    received_remote_envelopes: u64,
    status_requests: u64,
    accepted_connections: u64,
    connection_attempts: u64
});


text:
// ============================================================================
// declarations
// ============================================================================

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------

// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"

#ifdef __BORLANDC__
    #pragma hdrstop
#endif

#if wxUSE_LISTBOX

#include "wx/vlbox.h"

#ifndef WX_PRECOMP
    #include "wx/settings.h"
    #include "wx/dcclient.h"
    #include "wx/listbox.h"
#endif //WX_PRECOMP

#include "wx/dcbuffer.h"
#include "wx/selstore.h"
#include "wx/renderer.h"

// ----------------------------------------------------------------------------
// event tables
// ----------------------------------------------------------------------------

BEGIN_EVENT_TABLE(wxVListBox, wxVScrolledWindow)
    EVT_PAINT(wxVListBox::OnPaint)

    EVT_KEY_DOWN(wxVListBox::OnKeyDown)
    EVT_LEFT_DOWN(wxVListBox::OnLeftDown)
    EVT_LEFT_DCLICK(wxVListBox::OnLeftDClick)

    EVT_SET_FOCUS(wxVListBox::OnSetOrKillFocus)
    EVT_KILL_FOCUS(wxVListBox::OnSetOrKillFocus)

    EVT_SIZE(wxVListBox::OnSize)
END_EVENT_TABLE()

// ============================================================================
// implementation
// ============================================================================

IMPLEMENT_ABSTRACT_CLASS(wxVListBox, wxVScrolledWindow)
const char wxVListBoxNameStr[] = "wxVListBox";

// ----------------------------------------------------------------------------
// wxVListBox creation
// ----------------------------------------------------------------------------

void wxVListBox::Init()
{
    m_current =
    m_anchor = wxNOT_FOUND;
    m_selStore = NULL;
}

bool wxVListBox::Create(wxWindow *parent,
                        wxWindowID id,
                        const wxPoint& pos,
                        const wxSize& size,
                        long style,
                        const wxString& name)
{
#ifdef __WXMSW__
    if ( (style & wxBORDER_MASK) == wxDEFAULT )
        style |= wxBORDER_THEME;
#endif

    style |= wxWANTS_CHARS | wxFULL_REPAINT_ON_RESIZE;
    if ( !wxVScrolledWindow::Create(parent, id, pos, size, style, name) )
        return false;

    if ( style & wxLB_MULTIPLE )
        m_selStore = new wxSelectionStore;

    // make sure the native widget has the right colour since we do
    // transparent drawing by default
    SetBackgroundColour(GetBackgroundColour());

    // leave m_colBgSel in an invalid state: it means for OnDrawBackground()
    // to use wxRendererNative instead of painting selection bg ourselves
    m_colBgSel = wxNullColour;

    // flicker-free drawing requires this
    SetBackgroundStyle(wxBG_STYLE_CUSTOM);

    return true;
}

wxVListBox::~wxVListBox()
{
    delete m_selStore;
}

void wxVListBox::SetItemCount(size_t count)
{
    // don't leave the current index invalid
    if ( m_current != wxNOT_FOUND && (size_t)m_current >= count )
        m_current = count - 1; // also ok when count == 0 as wxNOT_FOUND == -1

    if ( m_selStore )
    {
        // tell the selection store that our number of items has changed
        m_selStore->SetItemCount(count);
    }

    SetRowCount(count);
}

// ----------------------------------------------------------------------------
// selection handling
// ----------------------------------------------------------------------------

bool wxVListBox::IsSelected(size_t line) const
{
    return m_selStore ? m_selStore->IsSelected(line) : (int)line == m_current;
}

bool wxVListBox::Select(size_t item, bool select)
{
    wxCHECK_MSG( m_selStore, false,
                 wxT("Select() may only be used with multiselection listbox") );

    wxCHECK_MSG( item < GetItemCount(), false,
                 wxT("Select(): invalid item index") );

    bool changed = m_selStore->SelectItem(item, select);
    if ( changed )
    {
        // selection really changed
        RefreshRow(item);
    }

    DoSetCurrent(item);

    return changed;
}

bool wxVListBox::SelectRange(size_t from, size_t to)
{
    wxCHECK_MSG( m_selStore, false,
                 wxT("SelectRange() may only be used with multiselection listbox") );

    // make sure items are in correct order
    if ( from > to )
    {
        size_t tmp = from;
        from = to;
        to = tmp;
    }

    wxCHECK_MSG( to < GetItemCount(), false,
                    wxT("SelectRange(): invalid item index") );

    wxArrayInt changed;
    if ( !m_selStore->SelectRange(from, to, true, &changed) )
    {
        // too many items have changed, we didn't record them in changed array
        // so we have no choice but to refresh everything between from and to
        RefreshRows(from, to);
    }
    else // we've got the indices of the changed items
    {
        const size_t count = changed.GetCount();
        if ( !count )
        {
            // nothing changed
            return false;
        }

        // refresh just the lines which have really changed
        for ( size_t n = 0; n < count; n++ )
        {
            RefreshRow(changed[n]);
        }
    }

    // something changed
    return true;
}

bool wxVListBox::DoSelectAll(bool select)
{
    wxCHECK_MSG( m_selStore, false,
                 wxT("SelectAll may only be used with multiselection listbox") );

    size_t count = GetItemCount();
    if ( count )
    {
        wxArrayInt changed;
        if ( !m_selStore->SelectRange(0, count - 1, select) ||
                !changed.IsEmpty() )
        {
            Refresh();

            // something changed
            return true;
        }
    }

    return false;
}

bool wxVListBox::DoSetCurrent(int current)
{
    wxASSERT_MSG( current == wxNOT_FOUND ||
                    (current >= 0 && (size_t)current < GetItemCount()),
                  wxT("wxVListBox::DoSetCurrent(): invalid item index") );

    if ( current == m_current )
    {
        // nothing to do
        return false;
    }

    if ( m_current != wxNOT_FOUND )
        RefreshRow(m_current);

    m_current = current;

    if ( m_current != wxNOT_FOUND )
    {
        // if the line is not visible at all, we scroll it into view but we
        // don't need to refresh it -- it will be redrawn anyhow
        if ( !IsVisible(m_current) )
        {
            ScrollToRow(m_current);
        }
        else // line is at least partly visible
        {
            // it is, indeed, only partly visible, so scroll it into view to
            // make it entirely visible
            while ( (size_t)m_current + 1 == GetVisibleRowsEnd() &&
                    ScrollToRow(GetVisibleBegin() + 1) ) ;

            // but in any case refresh it as even if it was only partly visible
            // before we need to redraw it entirely as its background changed
            RefreshRow(m_current);
        }
    }

    return true;
}

void wxVListBox::InitEvent(wxCommandEvent& event, int n)
{
    event.SetEventObject(this);
    event.SetInt(n);
}

void wxVListBox::SendSelectedEvent()
{
    wxASSERT_MSG( m_current != wxNOT_FOUND,
                    wxT("SendSelectedEvent() shouldn't be called") );

    wxCommandEvent event(wxEVT_COMMAND_LISTBOX_SELECTED, GetId());
    InitEvent(event, m_current);
    (void)GetEventHandler()->ProcessEvent(event);
}

void wxVListBox::SetSelection(int selection)
{
    wxCHECK_RET( selection == wxNOT_FOUND ||
                  (selection >= 0 && (size_t)selection < GetItemCount()),
                  wxT("wxVListBox::SetSelection(): invalid item index") );

    if ( HasMultipleSelection() )
    {
        if (selection != wxNOT_FOUND)
            Select(selection);
        else
            DeselectAll();
        m_anchor = selection;
    }

    DoSetCurrent(selection);
}

size_t wxVListBox::GetSelectedCount() const
{
    return m_selStore ? m_selStore->GetSelectedCount()
                      : m_current == wxNOT_FOUND ? 0 : 1;
}

int wxVListBox::GetFirstSelected(unsigned long& cookie) const
{
    cookie = 0;

    return GetNextSelected(cookie);
}

int wxVListBox::GetNextSelected(unsigned long& cookie) const
{
    wxCHECK_MSG( m_selStore, wxNOT_FOUND,
                  wxT("GetFirst/NextSelected() may only be used with multiselection listboxes") );

    while ( cookie < GetItemCount() )
    {
        if ( IsSelected(cookie++) )
            return cookie - 1;
    }

    return wxNOT_FOUND;
}

void wxVListBox::RefreshSelected()
{
    // only refresh those items which are currently visible and selected:
    for ( size_t n = GetVisibleBegin(), end = GetVisibleEnd(); n < end; n++ )
    {
        if ( IsSelected(n) )
            RefreshRow(n);
    }
}

wxRect wxVListBox::GetItemRect(size_t n) const
{
    wxRect itemrect;

    // check that this item is visible
    const size_t lineMax = GetVisibleEnd();
    if ( n >= lineMax )
        return itemrect;
    size_t line = GetVisibleBegin();
    if ( n < line )
        return itemrect;

    while ( line <= n )
    {
        itemrect.y += itemrect.height;
        itemrect.height = OnGetRowHeight(line);

        line++;
    }

    itemrect.width = GetClientSize().x;

    return itemrect;
}

// ----------------------------------------------------------------------------
// wxVListBox appearance parameters
// ----------------------------------------------------------------------------

void wxVListBox::SetMargins(const wxPoint& pt)
{
    if ( pt != m_ptMargins )
    {
        m_ptMargins = pt;

        Refresh();
    }
}

void wxVListBox::SetSelectionBackground(const wxColour& col)
{
    m_colBgSel = col;
}

// ----------------------------------------------------------------------------
// wxVListBox painting
// ----------------------------------------------------------------------------

wxCoord wxVListBox::OnGetRowHeight(size_t line) const
{
    return OnMeasureItem(line) + 2*m_ptMargins.y;
}

void wxVListBox::OnDrawSeparator(wxDC& WXUNUSED(dc),
                                 wxRect& WXUNUSED(rect),
                                 size_t WXUNUSED(n)) const
{
}

bool
wxVListBox::DoDrawSolidBackground(const wxColour& col,
                                  wxDC& dc,
                                  const wxRect& rect,
                                  size_t n) const
{
    if ( !col.IsOk() )
        return false;

    // we need to render selected and current items differently
    const bool isSelected = IsSelected(n),
               isCurrent = IsCurrent(n);
    if ( isSelected || isCurrent )
    {
        if ( isSelected )
        {
            dc.SetBrush(wxBrush(col, wxBRUSHSTYLE_SOLID));
        }
        else // !selected
        {
            dc.SetBrush(*wxTRANSPARENT_BRUSH);
        }
        dc.SetPen(*(isCurrent ? wxBLACK_PEN : wxTRANSPARENT_PEN));
        dc.DrawRectangle(rect);
    }
    //else: do nothing for the normal items

    return true;
}

void wxVListBox::OnDrawBackground(wxDC& dc, const wxRect& rect, size_t n) const
{
    // use wxRendererNative for more native look unless we use custom bg colour
    if ( !DoDrawSolidBackground(m_colBgSel, dc, rect, n) )
    {
        int flags = 0;
        if ( IsSelected(n) )
            flags |= wxCONTROL_SELECTED;
        if ( IsCurrent(n) )
            flags |= wxCONTROL_CURRENT;
        if ( wxWindow::FindFocus() == const_cast<wxVListBox*>(this) )
            flags |= wxCONTROL_FOCUSED;

        wxRendererNative::Get().DrawItemSelectionRect(
            const_cast<wxVListBox *>(this), dc, rect, flags);
    }
}

void wxVListBox::OnPaint(wxPaintEvent& WXUNUSED(event))
{
    wxSize clientSize = GetClientSize();

    wxAutoBufferedPaintDC dc(this);

    // the update rectangle
    wxRect rectUpdate = GetUpdateClientRect();

    // fill it with background colour
    dc.SetBackground(GetBackgroundColour());
    dc.Clear();

    // the bounding rectangle of the current line
    wxRect rectRow;
    rectRow.width = clientSize.x;

    // iterate over all visible lines
    const size_t lineMax = GetVisibleEnd();
    for ( size_t line = GetVisibleBegin(); line < lineMax; line++ )
    {
        const wxCoord hRow = OnGetRowHeight(line);

        rectRow.height = hRow;

        // and draw the ones which intersect the update rect
        if ( rectRow.Intersects(rectUpdate) )
        {
            // don't allow drawing outside of the lines rectangle
            wxDCClipper clip(dc, rectRow);

            wxRect rect = rectRow;
            OnDrawBackground(dc, rect, line);

            OnDrawSeparator(dc, rect, line);

            rect.Deflate(m_ptMargins.x, m_ptMargins.y);
            OnDrawItem(dc, rect, line);
        }
        else // no intersection
        {
            if ( rectRow.GetTop() > rectUpdate.GetBottom() )
            {
                // we are already below the update rect, no need to continue
                // further
                break;
            }
            //else: the next line may intersect the update rect
        }

        rectRow.y += hRow;
    }
}

void wxVListBox::OnSetOrKillFocus(wxFocusEvent& WXUNUSED(event))
{
    // we need to repaint the selection when we get the focus since
    // wxRendererNative in general draws the focused selection differently
    // from the unfocused selection (see OnDrawItem):
    RefreshSelected();
}

void wxVListBox::OnSize(wxSizeEvent& event)
{
    UpdateScrollbar();
    event.Skip();
}

// ============================================================================
// wxVListBox keyboard/mouse handling
// ============================================================================

void wxVListBox::DoHandleItemClick(int item, int flags)
{
    // has anything worth telling the client code about happened?
    bool notify = false;

    if ( HasMultipleSelection() )
    {
        // select the iteem clicked?
        bool select = true;

        // NB: the keyboard interface we implement here corresponds to
        //     wxLB_EXTENDED rather than wxLB_MULTIPLE but this one makes more
        //     sense IMHO
        if ( flags & ItemClick_Shift )
        {
            if ( m_current != wxNOT_FOUND )
            {
                if ( m_anchor == wxNOT_FOUND )
                    m_anchor = m_current;

                select = false;

                // only the range from the selection anchor to new m_current
                // must be selected
                if ( DeselectAll() )
                    notify = true;

                if ( SelectRange(m_anchor, item) )
                    notify = true;
            }
            //else: treat it as ordinary click/keypress
        }
        else // Shift not pressed
        {
            m_anchor = item;

            if ( flags & ItemClick_Ctrl )
            {
                select = false;

                if ( !(flags & ItemClick_Kbd) )
                {
                    Toggle(item);

                    // the status of the item has definitely changed
                    notify = true;
                }
                //else: Ctrl-arrow pressed, don't change selection
            }
            //else: behave as in single selection case
        }

        if ( select )
        {
            // make the clicked item the only selection
            if ( DeselectAll() )
                notify = true;

            if ( Select(item) )
                notify = true;
        }
    }

    // in any case the item should become the current one
    if ( DoSetCurrent(item) )
    {
        if ( !HasMultipleSelection() )
        {
            // this has also changed the selection for single selection case
            notify = true;
        }
    }

    if ( notify )
    {
        // notify the user about the selection change
        SendSelectedEvent();
    }
    //else: nothing changed at all
}

// ----------------------------------------------------------------------------
// keyboard handling
// ----------------------------------------------------------------------------

void wxVListBox::OnKeyDown(wxKeyEvent& event)
{
    // flags for DoHandleItemClick()
    int flags = ItemClick_Kbd;

    int current;
    switch ( event.GetKeyCode() )
    {
        case WXK_HOME:
        case WXK_NUMPAD_HOME:
            current = 0;
            break;

        case WXK_END:
        case WXK_NUMPAD_END:
            current = GetRowCount() - 1;
            break;

        case WXK_DOWN:
        case WXK_NUMPAD_DOWN:
            if ( m_current == (int)GetRowCount() - 1 )
                return;

            current = m_current + 1;
            break;

        case WXK_UP:
        case WXK_NUMPAD_UP:
            if ( m_current == wxNOT_FOUND )
                current = GetRowCount() - 1;
            else if ( m_current != 0 )
                current = m_current - 1;
            else // m_current == 0
                return;
            break;

        case WXK_PAGEDOWN:
        case WXK_NUMPAD_PAGEDOWN:
            PageDown();
            current = GetVisibleBegin();
            break;

        case WXK_PAGEUP:
        case WXK_NUMPAD_PAGEUP:
            if ( m_current == (int)GetVisibleBegin() )
            {
                PageUp();
            }

            current = GetVisibleBegin();
            break;

        case WXK_SPACE:
            // hack: pressing space should work like a mouse click rather than
            // like a keyboard arrow press, so trick DoHandleItemClick() in
            // thinking we were clicked
            flags &= ~ItemClick_Kbd;
            current = m_current;
            break;

#ifdef __WXMSW__
        case WXK_TAB:
            // Since we are using wxWANTS_CHARS we need to send navigation
            // events for the tabs on MSW
            HandleAsNavigationKey(event);
            // fall through to default
#endif
        default:
            event.Skip();
            current = 0; // just to silent the stupid compiler warnings
            wxUnusedVar(current);
            return;
    }

    if ( event.ShiftDown() )
       flags |= ItemClick_Shift;
    if ( event.ControlDown() )
        flags |= ItemClick_Ctrl;

    DoHandleItemClick(current, flags);
}

// ----------------------------------------------------------------------------
// wxVListBox mouse handling
// ----------------------------------------------------------------------------

void wxVListBox::OnLeftDown(wxMouseEvent& event)
{
    SetFocus();

    int item = VirtualHitTest(event.GetPosition().y);

    if ( item != wxNOT_FOUND )
    {
        int flags = 0;
        if ( event.ShiftDown() )
           flags |= ItemClick_Shift;

        // under Mac Apple-click is used in the same way as Ctrl-click
        // elsewhere
#ifdef __WXMAC__
        if ( event.MetaDown() )
#else
        if ( event.ControlDown() )
#endif
            flags |= ItemClick_Ctrl;

        DoHandleItemClick(item, flags);
    }
}

void wxVListBox::OnLeftDClick(wxMouseEvent& eventMouse)
{
    int item = VirtualHitTest(eventMouse.GetPosition().y);
    if ( item != wxNOT_FOUND )
    {

        // if item double-clicked was not yet selected, then treat
        // this event as a left-click instead
        if ( item == m_current )
        {
            wxCommandEvent event(wxEVT_COMMAND_LISTBOX_DOUBLECLICKED, GetId());
            InitEvent(event, item);
            (void)GetEventHandler()->ProcessEvent(event);
        }
        else
        {
            OnLeftDown(eventMouse);
        }

    }
}

// ----------------------------------------------------------------------------
// use the same default attributes as wxListBox
// ----------------------------------------------------------------------------

//static
wxVisualAttributes
wxVListBox::GetClassDefaultAttributes(wxWindowVariant variant)
{
    return wxListBox::GetClassDefaultAttributes(variant);
}

#endif


text:
from django import template

register = template.Library()

@register.filter(is_safe=True)
def to_str(value):
    if type(value) == list:
        value_str = '\n'.join(value)
        return value_str
    elif type(value) == dict:
        value_l = []
        for key in value:
            tmp = str(key) + '\n    ' + str(value[key])
            value_l.append(tmp)
        value_str = '\n'.join(value_l)
        return value_str
    else:
        return value

@register.filter(is_safe=True)
def ListToStr(l,nu):
    return l[nu]


text: A collection of useful C# MonoBehaviour classes, and other assets for Unity game development.


text:
FactoryGirl.define do
  factory :user do
    email "user@user.com"
    username 'username'
    password 'password'
  end

  trait :admin do
    user_type_id 3
  end

  trait :designer do
    user_type_id 1
  end

end


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Carrier'
        db.create_table(u'carriers_carrier', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('is_active', self.gf('django.db.models.fields.BooleanField')(default=True)),
            ('created_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'carriers_carrier_creations', to=orm['auth.User'])),
            ('created_on', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, blank=True)),
            ('modified_by', self.gf('django.db.models.fields.related.ForeignKey')(related_name=u'carriers_carrier_modifications', to=orm['auth.User'])),
            ('modified_on', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, blank=True)),
            ('name', self.gf('django.db.models.fields.CharField')(max_length=32)),
        ))
        db.send_create_signal(u'carriers', ['Carrier'])

    def backwards(self, orm):
        # Deleting model 'Carrier'
        db.delete_table(u'carriers_carrier')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        u'carriers.carrier': {
            'Meta': {'object_name': 'Carrier'},
            'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'carriers_carrier_creations'", 'to': u"orm['auth.User']"}),
            'created_on': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'modified_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "u'carriers_carrier_modifications'", 'to': u"orm['auth.User']"}),
            'modified_on': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '32'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        }
    }

    complete_apps = ['carriers']


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <title>Apt & Yum Repos Now Available for Venom | Tox Development blog</title>
  <meta name="viewport" content="width=device-width">
  <meta name="description" content="It's been a long timesince we've starting packaging Venom builds as .deb and .rpm, but they never made it into their own repository's. Today, that changes. For those of you who've wanted to install an">
<meta property="og:type" content="article">
<meta property="og:title" content="Apt & Yum Repos Now Available for Venom">
<meta property="og:url" content="https://blog.tox.im/2014/08/01/apt-yum-repos-now-available-for-venom/">
<meta property="og:site_name" content="Tox Development blog">
<meta property="og:description" content="It's been a long timesince we've starting packaging Venom builds as .deb and .rpm, but they never made it into their own repository's. Today, that changes. For those of you who've wanted to install an">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Apt & Yum Repos Now Available for Venom">
<meta name="twitter:description" content="It's been a long timesince we've starting packaging Venom builds as .deb and .rpm, but they never made it into their own repository's. Today, that changes. For those of you who've wanted to install an">

    <link rel="alternative" href="/atom.xml" title="Tox Development blog" type="application/atom+xml">

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

  <link rel="stylesheet" href="/css/style.css" type="text/css">

		Tox Development blog

Home

Archives

		<form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><input type="submit" value="" class="search-form-submit"><input type="hidden" name="q" value="site:https://blog.tox.im"></form>

  <time datetime="2014-08-01T07:39:21.000Z" itemprop="datePublished">Aug 1 2014</time>

		Tox Foundation

      Apt & Yum Repos Now Available for Venom

It's been a long timesince we've starting packaging Venom builds as .deb and .rpm, but they never made it into their own repository's. Today, that changes. For those of you who've wanted to install and update your Tox clients via your built-in package manager, your dream has come true.

Apt/Aptitude (Debian, Ubuntu, Mint, etc.)

If you want to set the repo up under Debian or any of its' derivatives, simply run wget https://repo.tox.im/tox-apt.sh && sudo chmod +x ./tox-apt.sh && ./tox-apt.sh in your favorite terminal and then apt-get install venom.
If you want to update venom, simply run apt-get update && apt-get upgrade

Yum (Fedora, CentOS, RHEL, etc.)

Simply add https://repo.tox.im/tox.repo to your repo list, and then yum install venom

    qTox»Venom

      Newer

          To 5,000 and beyond!

      Older

          μTox updates [0.1.0]

  <form action="//google.com/search" method="get" accept-charset="utf-8">
    <input type="search" name="q" results="0" placeholder="Search">
    <input type="hidden" name="q" value="site:blog.tox.im">
  </form>

		Tox Development blog

		© 2015 Tox Foundation

		Modify from Apollo theme, designed by SANOGRAPHIX.NET

		Powered by Hexo

<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">


text:
package stemmer;

import java.util.ArrayList;

import utils.PythonRunner;

public class WordNet extends Stemmer {

	public WordNet(String[] words) {
		super(words);
	}

	@Override
	public ArrayList<String> stem() {
		ArrayList<String> stemmedWords = new ArrayList<>(words.length);
		for (String word : words) {
			stemmedWords.add(PythonRunner.execute(interpreter, "wordnet_single", word));
		}
		return stemmedWords;
	}

}


text:
from typing import Any
from typing import Dict
from typing import List
from typing import Tuple
from typing import cast

# third party
from sqlalchemy.engine import Engine
from sqlalchemy.orm import sessionmaker

# relative
from ..... import serialize
from ....common.uid import UID
from ..node_table.bin_obj_dataset import BinObjDataset
from ..node_table.dataset import Dataset
from .database_manager import DatabaseManager

class DatasetManager(DatabaseManager):

    schema = Dataset

    def __init__(self, database: Engine) -> None:
        super().__init__(schema=DatasetManager.schema, db=database)

    def register(self, **kwargs: Any) -> str:
        """Register e  new object into the database.

        Args:
            parameters : List of object parameters.
        Returns:
            object: Database Object
        """
        tags = list(map(str, kwargs.get("tags", [])))
        manifest = str(kwargs.get("manifest", ""))
        name = str(kwargs.get("name", ""))
        description = str(kwargs.get("description", ""))

        blob_metadata = {}
        str_metadata = {}
        for key, value in kwargs.items():
            if (
                key != "tags"
                and key != "manifest"
                and key != "description"
                and key != "name"
            ):
                if isinstance(key, str) and isinstance(value, str):
                    str_metadata[key] = value
                else:
                    blob_metadata[str(key)] = cast(
                        bytes, serialize(value, to_bytes=True)
                    ).hex()

        _obj = self._schema(
            id=str(UID().value),
            name=name,
            tags=tags,
            manifest=manifest,
            description=description,
            str_metadata=str_metadata,
            blob_metadata=blob_metadata,
        )
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        session_local.add(_obj)
        obj_id = _obj.id
        session_local.commit()
        session_local.close()
        return obj_id

    def add(
        self, name: str, dataset_id: str, obj_id: str, dtype: str, shape: str
    ) -> None:

        obj_dataset_relation = BinObjDataset(
            name=name,
            dataset=dataset_id,
            obj=obj_id,
            dtype=dtype,
            shape=shape,
        )
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        session_local.add(obj_dataset_relation)
        session_local.commit()
        session_local.close()

    def get(self, dataset_id: str) -> Tuple[Dataset, List[bytes]]:
        session_local = sessionmaker(autocommit=False, autoflush=False, bind=self.db)()
        ds = session_local.query(Dataset).filter_by(id=dataset_id).first()
        objs = list(
            session_local.query(BinObjDataset).filter_by(dataset=dataset_id).all()
        )
        session_local.close()
        return ds, objs

    def set(self, dataset_id: str, metadata: Dict) -> None:
        self.modify({"id": dataset_id}, metadata)


text:
from django.db import models

from djorm_pgarray.fields import ArrayField

class Entry(models.Model):
    tags = ArrayField(dbtype="varchar(255)")
    """
    tags is a list of tag strings related to the word. Ex. "isim".
    """

    extra_info = ArrayField(dbtype="varchar(255)")
    """
    extra_info is a list of strings that contain info that is not
    a tag.
    Ex. "ingilizce typhoon"
    """

    keyword = models.CharField(max_length=255, unique=True)
    normalized = models.CharField(max_length=255, db_index=True)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return "%s" % self.keyword

class Meaning(models.Model):
    tags = ArrayField(dbtype="varchar(255)")
    """
    Each meaning also can have different tags associated with it. Such as
    /isim/, /meteoroloji/ etc.
    """

    content = models.TextField()
    """
    This is the content of the meaning.
    """

    example = models.TextField(null=True)
    """
    This is an example sentence.
    """

    entry = models.ForeignKey(Entry)


text:
var UnoAppManifest = {

    splashScreenImage: "Assets/SplashScreen.png",
    splashScreenColor: "#fff",
    displayName: "SkiaSharpSample"

}


text:
.signupLink {
  position: absolute;
  bottom: -20px;
  left: 50%;
  transform: translateX(-50%);
  color: white;
  cursor: pointer;
  font-size: 1.05rem;
}


text:
package mw

import (
	"net/http"

	"github.com/go-on/stack/responsewriter"
)

// ContentType writes the content type if the next handler was successful
// and did not set a content-type
type ContentType string

// SetContentType sets the content type in the given ResponseWriter
func (c ContentType) SetContentType(w http.ResponseWriter) {
	w.Header().Set("Content-Type", string(c))
}

// ServeHandle serves the given request with the next handler and after that
// writes the content type, if the next handler was successful
// and did not set a content-type
func (c ContentType) ServeHTTP(wr http.ResponseWriter, req *http.Request, next http.Handler) {

	var bodyWritten = false
	checked := responsewriter.NewPeek(wr, func(ck *responsewriter.Peek) bool {
		if ck.IsOk() {
			c.SetContentType(ck)
		}
		ck.FlushHeaders()
		ck.FlushCode()
		bodyWritten = true
		return true
	})

	next.ServeHTTP(checked, req)

	if !bodyWritten {
		c.SetContentType(checked)
	}
	checked.FlushMissing()
}

var (
	JSONContentType       = ContentType("application/json; charset=utf-8")
	TextContentType       = ContentType("text/plain; charset=utf-8")
	CSSContentType        = ContentType("text/css; charset=utf-8")
	HTMLContentType       = ContentType("text/html; charset=utf-8")
	JavaScriptContentType = ContentType("application/javascript; charset=utf-8")
	RSSFeedContentType    = ContentType("application/rss+xml; charset=utf-8")
	AtomFeedContentType   = ContentType("application/atom+xml; charset=utf-8")
	PDFContentType        = ContentType("application/pdf")
)


text:
/*
 * Copyright 2017 Google Inc.
 * Copyright 2020 The Open GEE Contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef _khProgressMeter_h_
#define _khProgressMeter_h_

#include <stdlib.h>
#include <string>
#include <qdatetime.h>
#include <deque>
#include "khTypes.h"
#include <cstdint>

namespace std {
  template<class T>
  T abs(const T& val) {
    return (val > 0 ? val : -val);
  }
}

class khProgressMeter
{
  class IntervalStats {
   public:
    std::int64_t totalCount;
    std::int64_t doneCount;
    std::int64_t skippedCount;
    std::int64_t elapsedMS;

    inline std::int64_t processedCount(void) const {
      return doneCount + skippedCount;
    }
    inline double progressFraction(void) const {
      return double(processedCount()) / double(totalCount);
    }

    IntervalStats(std::int64_t total,
                  std::int64_t done = 0, std::int64_t skipped = 0,
                  std::int64_t elapsed = 0) :
        totalCount(total),
        doneCount(done),
        skippedCount(skipped),
        elapsedMS(elapsed)
    { }
  };

  // private and unimplemented - illegal to copy
  khProgressMeter(const khProgressMeter&);
  khProgressMeter& operator=(const khProgressMeter &);
 public:
  khProgressMeter( std::int64_t totalSteps, const QString &desc_ = "tiles", const std::string& progress_meter_prefix = "");
  ~khProgressMeter(void);

  inline void incrementDone(std::int64_t delta = 1);
  inline void incrementSkipped(std::int64_t delta = 1);
  inline void incrementTotal(std::int64_t delta);

  // convenience for backward compatibility
  inline void increment(void) { incrementDone(1); }

  // call for explicit finalization, otherwise will finalize in destructor
  // prints summary statistics
  void finalize(void);

  // just a little utility, for myself and others
  static QString msToString( std::int64_t ms );
 private:
  QString desc;

  // use signed rather than unsigned so logic doesn't need to worry
  // about wrapping if dropping below 0
  IntervalStats overallStats;

  // List of previous report intervals. Always contains at least one.
  // If you want a running average over 3 intervals, the deque will actually
  // contain up to 4 records. The 1st entry gives you the starting numbers
  // for the remaining intervals.
  static const unsigned int NumRunningAverageIntervals = 5;
  std::deque<IntervalStats> intervals;
  const IntervalStats& prevStats(void) const { return intervals.back(); }

  std::int64_t countUntilNextCheck;
  QTime timer;
  bool finalized;
  const std::string progress_meter_prefix_;

  static const double reportTotalChangedByFraction;
  static const double reportFractionDoneInterval;
  static const double reportMSInterval;

  double RunningTilesPerMS(void) const;
  double AverageTilesPerMS(void) const;
  bool NeedReport(void) const;
  void CheckAndReportIfNecessary(void);
  void DoReport(void);
};

inline void khProgressMeter::incrementDone(std::int64_t delta) {
  overallStats.doneCount += delta;
  countUntilNextCheck -= std::abs(delta);
  if (countUntilNextCheck <= 0) {
    CheckAndReportIfNecessary();
  }
}

inline void khProgressMeter::incrementSkipped(std::int64_t delta) {
  overallStats.skippedCount += delta;
  countUntilNextCheck -= std::abs(delta);
  if (countUntilNextCheck <= 0) {
    CheckAndReportIfNecessary();
  }
}

inline void khProgressMeter::incrementTotal(std::int64_t delta) {
  overallStats.totalCount += delta;
  countUntilNextCheck -= std::abs(delta);
  if (countUntilNextCheck <= 0) {
    CheckAndReportIfNecessary();
  }
}

#endif // ! _khProgressMeter_h_


text:
package com.google.cloud.memcache.v1.samples;

// [START memcache_v1_generated_CloudMemcache_CreateInstance_LRO_async]
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.memcache.v1.CloudMemcacheClient;
import com.google.cloud.memcache.v1.CreateInstanceRequest;
import com.google.cloud.memcache.v1.Instance;
import com.google.cloud.memcache.v1.LocationName;
import com.google.cloud.memcache.v1.OperationMetadata;

public class AsyncCreateInstanceLRO {

  public static void main(String[] args) throws Exception {
    asyncCreateInstanceLRO();
  }

  public static void asyncCreateInstanceLRO() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudMemcacheClient cloudMemcacheClient = CloudMemcacheClient.create()) {
      CreateInstanceRequest request =
          CreateInstanceRequest.newBuilder()
              .setParent(LocationName.of("[PROJECT]", "[LOCATION]").toString())
              .setInstanceId("instanceId902024336")
              .setInstance(Instance.newBuilder().build())
              .build();
      OperationFuture<Instance, OperationMetadata> future =
          cloudMemcacheClient.createInstanceOperationCallable().futureCall(request);
      // Do something.
      Instance response = future.get();
    }
  }
}
// [END memcache_v1_generated_CloudMemcache_CreateInstance_LRO_async]


text:
package com.lw.basic.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lw.basic.dao.BrandMapper;
import com.lw.basic.entity.Brand;

@Service
public class BrandService {
	@Autowired BrandMapper brandMapper;

	public List<Brand> finAll(){
		return brandMapper.findAll();
	}
}


text:
package grails.plugin.cache.web;

import java.io.Serializable;

import javax.servlet.http.Cookie;

/**
 * Based on net.sf.ehcache.constructs.web.SerializableCookie.
 *
 * @author Greg Luck
 * @author Adam Murdoch
 * @author Burt Beckwith
 */
public class SerializableCookie implements Serializable {

	private static final long serialVersionUID = 1;

	protected String name;
	protected String value;
	protected String comment;
	protected String domain;
	protected int maxAge;
	protected String path;
	protected boolean secure;
	protected int version;

	public SerializableCookie(final Cookie cookie) {
		name = cookie.getName();
		value = cookie.getValue();
		comment = cookie.getComment();
		domain = cookie.getDomain();
		maxAge = cookie.getMaxAge();
		path = cookie.getPath();
		secure = cookie.getSecure();
		version = cookie.getVersion();
	}

	public Cookie toCookie() {
		Cookie cookie = new Cookie(name, value);
		cookie.setComment(comment);
		if (domain != null) {
			cookie.setDomain(domain);
		}
		cookie.setMaxAge(maxAge);
		cookie.setPath(path);
		cookie.setSecure(secure);
		cookie.setVersion(version);
		return cookie;
	}
}


text:
/*jslint nomen:true*/
/*global define*/
define([
    'oroui/js/app/models/base/collection',
    './note-model'
], function (BaseCollection, NoteModel) {
    'use strict';

    var NotesCollection;

    NotesCollection =  BaseCollection.extend({
        model: NoteModel,
        baseUrl: '',
        sorting: 'DESC',

        url: function () {
            return this.baseUrl + '?sorting=' + this.sorting;
        },

        getSorting: function () {
            return this.sorting;
        },

        setSorting: function (mode) {
            this.sorting = mode;
        }
    });

    return NotesCollection;
});


text:
package org.jfree.chart.labels;

import org.jfree.data.contour.ContourDataset;

public interface ContourToolTipGenerator {
    String generateToolTip(ContourDataset contourDataset, int i);
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('projects', '0005_auto_20160720_1140'),
        ('surveys', '0010_auto_20160920_0854'),
    ]

    operations = [
        migrations.CreateModel(
            name='AggregateAnswer',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('value', models.FloatField()),
                ('project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='projects.Project')),
            ],
        ),
        migrations.AlterField(
            model_name='question',
            name='aggregation',
            field=models.CharField(blank=True, choices=[(b'sum', b'Sum'), (b'average', b'Average')], max_length=200, null=True),
        ),
        migrations.AddField(
            model_name='aggregateanswer',
            name='question',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='surveys.Question'),
        ),
    ]


text:
package net.ripe.db.whois.api;

import net.ripe.db.whois.api.acl.ApiKeyFilter;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.StringWriter;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.*;

@RunWith(MockitoJUnitRunner.class)
public class ApiKeyFilterTest {
    StringWriter writer;
    @Mock HttpServletRequest request;
    @Mock HttpServletResponse response;
    @Mock FilterChain filterChain;

    @InjectMocks
    ApiKeyFilter subject;

    @Before
    public void setUp() throws Exception {
        subject.setApiKey("KEY");

        writer = new StringWriter();
        when(response.getWriter()).thenReturn(new PrintWriter(writer));
    }

    @Test
    public void init() throws Exception {
        subject.init(null);
    }

    @Test
    public void destroy() {
        subject.destroy();
    }

    @Test
    public void key_omitted() throws Exception {
        subject.doFilter(request, response, filterChain);

        assertThat(writer.toString(), is("No apiKey parameter specified"));
        verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN);
        verifyZeroInteractions(filterChain);
    }

    @Test
    public void key_invalid() throws Exception {
        when(request.getParameter("apiKey")).thenReturn("OOPS");
        subject.doFilter(request, response, filterChain);

        assertThat(writer.toString(), is("Invalid apiKey"));
        verify(response).setStatus(HttpServletResponse.SC_FORBIDDEN);
        verifyZeroInteractions(filterChain);
    }

    @Test
    public void key_valid() throws Exception {
        when(request.getParameter("apiKey")).thenReturn("KEY");
        subject.doFilter(request, response, filterChain);

        assertThat(writer.toString(), is(""));
        verify(filterChain).doFilter(request, response);
    }
}


text:
<?php

namespace AppBundle\Entity;

use AppBundle\Annotation\EzabatuMarka;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Annotation\UdalaEgiaztatu;
use JMS\Serializer\Annotation as Serializer;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Azpiatala
 *
 * @ORM\Table(name="azpiatala", indexes={@ORM\Index(name="atala_id_idx", columns={"atala_id"})})
 * @ORM\Entity
 * @ExclusionPolicy("all")
 * @UdalaEgiaztatu(userFieldName="udala_id")
 * @EzabatuMarka(userFieldName="ezabatu")
 */
class Azpiatala
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @Expose
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     * @Expose
     * @ORM\Column(name="origenid", type="bigint", nullable=true)
     */
    private $origenid;

    /**
     * @var string
     *
     * @ORM\Column(name="kodea", type="string", length=9, nullable=true)
     */
    private $kodea;

    /**
     * @var string
     * @Expose
     *
     * @ORM\Column(name="kodea_prod", type="string", length=9, nullable=true)
     */
    private $kodea_prod;

    /**
     * @var string
     *
     * @ORM\Column(name="izenburuaeu", type="text", length=65535, nullable=true)
     */
    private $izenburuaeu;

    /**
     * @var string
     * @Expose
     *
     * @ORM\Column(name="izenburuaeu_prod", type="text", length=65535, nullable=true)
     */
    private $izenburuaeu_prod;

    /**
     * @var string
     *
     * @ORM\Column(name="izenburuaes", type="text", length=65535, nullable=true)
     */
    private $izenburuaes;

    /**
     * @var string
     * @Expose
     *
     * @ORM\Column(name="izenburuaes_prod", type="text", length=65535, nullable=true)
     */
    private $izenburuaes_prod;

    /**
     * @var bool
     *
     * @ORM\Column(name="ezabatu", type="boolean", nullable=true)
     */
    private $ezabatu;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=false)
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=false)
     */
    private $updatedAt;

    /**
     * @var string $createdBy
     *
     * @Gedmo\Blameable(on="create")
     * @ORM\Column(nullable=true)
     */
    private $createdBy;

    /**
     * @var string $updatedBy
     *
     * @Gedmo\Blameable(on="update")
     * @ORM\Column(nullable=true)
     */
    private $updatedBy;

    /**
     * ************************************************************************************************************************************************************************
     * ************************************************************************************************************************************************************************
     * ***** ERLAZIOAK
     * ************************************************************************************************************************************************************************
     * ************************************************************************************************************************************************************************
     */

    /**
     * @var \Atala
     *
     * @ORM\ManyToOne(targetEntity="Atala",inversedBy="azpiatalak")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="atala_id", referencedColumnName="id", onDelete="SET NULL")
     * })
     */
    private $atala;

    /**
     * @var Azpiatalaparrafoa
     * @ORM\OneToMany(targetEntity="Azpiatalaparrafoa", mappedBy="azpiatala", cascade={"remove", "persist"})
     * @Expose()
     * @ORM\OrderBy({"ordena" = "ASC"})
     */
    protected $parrafoak;

    /**
     * @var Azpiatalaparrafoaondoren
     * @ORM\OneToMany(targetEntity="Azpiatalaparrafoaondoren", mappedBy="azpiatala", cascade={"remove", "persist"})
     * @Expose()
     * @ORM\OrderBy({"ordena" = "ASC"})
     */
    protected $parrafoakondoren;

    /**
     * @var Kontzeptua
     * @Expose
     * @ORM\OrderBy({"kodea"="ASC"})
     * @ORM\OneToMany(targetEntity="Kontzeptua", mappedBy="azpiatala", cascade={"remove"})
     */
    protected $kontzeptuak;

    /**
     * @var Udala
     * @ORM\ManyToOne(targetEntity="Udala")
     */
    private $udala;

    public function __construct()
    {
        $this->createdAt = new \DateTime();
        $this->updatedAt = new \DateTime();
    }

    public function __toString()
    {
        if ($this->getIzenburuaeu() == null)
        {
            return "";
        } else
        {
            return $this->getIzenburuaeu();
        }
    }

    /**
     * ************************************************************************************************************************************************************************
     * ************************************************************************************************************************************************************************
     * ***** ERLAZIOAK
     * ************************************************************************************************************************************************************************
     * ************************************************************************************************************************************************************************
     */

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set kodea
     *
     * @param string $kodea
     *
     * @return Azpiatala
     */
    public function setKodea($kodea)
    {
        $this->kodea = $kodea;

        return $this;
    }

    /**
     * Get kodea
     *
     * @return string
     */
    public function getKodea()
    {
        return $this->kodea;
    }

    /**
     * Set izenburuaeu
     *
     * @param string $izenburuaeu
     *
     * @return Azpiatala
     */
    public function setIzenburuaeu($izenburuaeu)
    {
        $this->izenburuaeu = $izenburuaeu;

        return $this;
    }

    /**
     * Get izenburuaeu
     *
     * @return string
     */
    public function getIzenburuaeu()
    {
        return $this->izenburuaeu;
    }

    /**
     * Set izenburuaes
     *
     * @param string $izenburuaes
     *
     * @return Azpiatala
     */
    public function setIzenburuaes($izenburuaes)
    {
        $this->izenburuaes = $izenburuaes;

        return $this;
    }

    /**
     * Get izenburuaes
     *
     * @return string
     */
    public function getIzenburuaes()
    {
        return $this->izenburuaes;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     *
     * @return Azpiatala
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     *
     * @return Azpiatala
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set atala
     *
     * @param \AppBundle\Entity\Atala $atala
     *
     * @return Azpiatala
     */
    public function setAtala(\AppBundle\Entity\Atala $atala = null)
    {
        $this->atala = $atala;

        return $this;
    }

    /**
     * Get atala
     *
     * @return \AppBundle\Entity\Atala
     */
    public function getAtala()
    {
        return $this->atala;
    }

    /**
     * Add parrafoak
     *
     * @param \AppBundle\Entity\Azpiatalaparrafoa $parrafoak
     *
     * @return Azpiatala
     */
    public function addParrafoak(\AppBundle\Entity\Azpiatalaparrafoa $parrafoak)
    {
        $this->parrafoak[] = $parrafoak;

        return $this;
    }

    /**
     * Remove parrafoak
     *
     * @param \AppBundle\Entity\Azpiatalaparrafoa $parrafoak
     */
    public function removeParrafoak(\AppBundle\Entity\Azpiatalaparrafoa $parrafoak)
    {
        $this->parrafoak->removeElement($parrafoak);
    }

    /**
     * Get parrafoak
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getParrafoak()
    {
        return $this->parrafoak;
    }

    /**
     * Add kontzeptuak
     *
     * @param \AppBundle\Entity\Kontzeptua $kontzeptuak
     *
     * @return Azpiatala
     */
    public function addKontzeptuak(\AppBundle\Entity\Kontzeptua $kontzeptuak)
    {
        $this->kontzeptuak[] = $kontzeptuak;

        return $this;
    }

    /**
     * Remove kontzeptuak
     *
     * @param \AppBundle\Entity\Kontzeptua $kontzeptuak
     */
    public function removeKontzeptuak(\AppBundle\Entity\Kontzeptua $kontzeptuak)
    {
        $this->kontzeptuak->removeElement($kontzeptuak);
    }

    /**
     * Get kontzeptuak
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getKontzeptuak()
    {
        return $this->kontzeptuak;
    }

    /**
     * Set udala
     *
     * @param \AppBundle\Entity\Udala $udala
     *
     * @return Azpiatala
     */
    public function setUdala(\AppBundle\Entity\Udala $udala = null)
    {
        $this->udala = $udala;

        return $this;
    }

    /**
     * Get udala
     *
     * @return \AppBundle\Entity\Udala
     */
    public function getUdala()
    {
        return $this->udala;
    }

    /**
     * Set kodeaProd
     *
     * @param string $kodeaProd
     *
     * @return Azpiatala
     */
    public function setKodeaProd($kodeaProd)
    {
        $this->kodea_prod = $kodeaProd;

        return $this;
    }

    /**
     * Get kodeaProd
     *
     * @return string
     */
    public function getKodeaProd()
    {
        return $this->kodea_prod;
    }

    /**
     * Set izenburuaeuProd
     *
     * @param string $izenburuaeuProd
     *
     * @return Azpiatala
     */
    public function setIzenburuaeuProd($izenburuaeuProd)
    {
        $this->izenburuaeu_prod = $izenburuaeuProd;

        return $this;
    }

    /**
     * Get izenburuaeuProd
     *
     * @return string
     */
    public function getIzenburuaeuProd()
    {
        return $this->izenburuaeu_prod;
    }

    /**
     * Set izenburuaesProd
     *
     * @param string $izenburuaesProd
     *
     * @return Azpiatala
     */
    public function setIzenburuaesProd($izenburuaesProd)
    {
        $this->izenburuaes_prod = $izenburuaesProd;

        return $this;
    }

    /**
     * Get izenburuaesProd
     *
     * @return string
     */
    public function getIzenburuaesProd()
    {
        return $this->izenburuaes_prod;
    }

    /**
     * Set ezabatu
     *
     * @param boolean $ezabatu
     *
     * @return Azpiatala
     */
    public function setEzabatu($ezabatu)
    {
        $this->ezabatu = $ezabatu;

        return $this;
    }

    /**
     * Get ezabatu
     *
     * @return boolean
     */
    public function getEzabatu()
    {
        return $this->ezabatu;
    }

    /**
     * Add parrafoakondoren
     *
     * @param \AppBundle\Entity\Azpiatalaparrafoaondoren $parrafoakondoren
     *
     * @return Azpiatala
     */
    public function addParrafoakondoren(\AppBundle\Entity\Azpiatalaparrafoaondoren $parrafoakondoren)
    {
        $this->parrafoakondoren[] = $parrafoakondoren;

        return $this;
    }

    /**
     * Remove parrafoakondoren
     *
     * @param \AppBundle\Entity\Azpiatalaparrafoaondoren $parrafoakondoren
     */
    public function removeParrafoakondoren(\AppBundle\Entity\Azpiatalaparrafoaondoren $parrafoakondoren)
    {
        $this->parrafoakondoren->removeElement($parrafoakondoren);
    }

    /**
     * Get parrafoakondoren
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getParrafoakondoren()
    {
        return $this->parrafoakondoren;
    }

    /**
     * Set createdBy
     *
     * @param string $createdBy
     *
     * @return Azpiatala
     */
    public function setCreatedBy($createdBy)
    {
        $this->createdBy = $createdBy;

        return $this;
    }

    /**
     * Get createdBy
     *
     * @return string
     */
    public function getCreatedBy()
    {
        return $this->createdBy;
    }

    /**
     * Set updatedBy
     *
     * @param string $updatedBy
     *
     * @return Azpiatala
     */
    public function setUpdatedBy($updatedBy)
    {
        $this->updatedBy = $updatedBy;

        return $this;
    }

    /**
     * Get updatedBy
     *
     * @return string
     */
    public function getUpdatedBy()
    {
        return $this->updatedBy;
    }

    /**
     * Set origenid
     *
     * @param integer $origenid
     *
     * @return Azpiatala
     */
    public function setOrigenid($origenid)
    {
        $this->origenid = $origenid;

        return $this;
    }

    /**
     * Get origenid
     *
     * @return integer
     */
    public function getOrigenid()
    {
        return $this->origenid;
    }
}


text:
GO_EASY_ON_ME := 1
ARCHS = armv7 arm64
TARGET_IPHONEOS_DEPLOYMENT_VERSION=7.0

include theos/makefiles/common.mk

BUNDLE_NAME = ColoredVK
ColoredVK_FILES = ColoredVKListController.m ColoredVKListControllerConfig.m ColoredVKColorPickerViewController.m ColoredVKHeaderCell.m ColoredVKColorCell.m NKOColorPickerView.m MBProgressHUD/MBProgressHUD.m
ColoredVK_INSTALL_PATH = /Library/PreferenceBundles
ColoredVK_FRAMEWORKS = Social UIKit MessageUI CoreGraphics Foundation
ColoredVK_PRIVATE_FRAMEWORKS = Preferences
ColoredVK_LDFLAGS = -lMobileGestalt
ColoredVK_CFLAGS = -fobjc-arc

include $(THEOS_MAKE_PATH)/bundle.mk

internal-stage::
	$(ECHO_NOTHING)mkdir -p $(THEOS_STAGING_DIR)/Library/PreferenceLoader/Preferences$(ECHO_END)
	$(ECHO_NOTHING)cp ColoredVK.plist $(THEOS_STAGING_DIR)/Library/PreferenceLoader/Preferences/ColoredVK.plist$(ECHO_END)


text:
```
npm install
npm run watch

cd public
python -m SimpleHTTPServer 8080

navigate browser to localhost:8080
```

### Release

This project is continuously deployed on every push to master.


text:
#ifndef _VERSION_NATIVE_AIO

// This definition needs to match org.apache.activemq.artemis.core.asyncio.impl.AsynchronousFileImpl.EXPECTED_NATIVE_VERSION
// Or else the native module won't be loaded because of version mismatches
#define _VERSION_NATIVE_AIO 52
#endif


text:
module.exports = {

    provides: "schemaFileObject",

    re: [
        /https:\/\/(?:docs|drive)\.google\.com\/(forms|document|presentation|spreadsheets|file)\/d\//i
    ],

    mixins: [
        "favicon",
        "og-title",
        "og-image",
        "og-description",
        "twitter-player-responsive" // fallback mixin
    ],

    getMeta: function (schemaFileObject) {

        return {
            title: schemaFileObject.name,
            site: "Google Docs"

            // Mute canonical to bypass the validation and allow player.href=canonical
            // Especially for video files and presentations:

            // canonical: schemaFileObject.url
        };

    },

    getLink: function(urlMatch, schemaFileObject) {

        if (schemaFileObject.embedURL || schemaFileObject.embedUrl) {

            var file = {
                rel: [CONFIG.R.file, CONFIG.R.html5],
                href: schemaFileObject.embedURL || schemaFileObject.embedUrl,
                type: CONFIG.T.text_html
            };

            if (schemaFileObject.playerType) {
                // file.rel.push(CONFIG.R.player);
                // There is a problem with player as embedURL: x-frame-options is SAMEORIGIN
                return;
            }

            if (urlMatch[1] === "forms" || urlMatch[1] === "document" || (urlMatch[1] === "file" && /\.pdf$/i.test(schemaFileObject.name))) {
                file["aspect-ratio"] = 1 / Math.sqrt(2); // A4 portrait
                // "App" to prevent Google Forms be presented as Player through Twitter-player mixin as Player prevails on Readers
                file.rel.push (urlMatch[1] === "forms" ? CONFIG.R.app : CONFIG.R.reader);

            } else if (urlMatch[1] === "spreadsheets" ) {
                file["aspect-ratio"] = Math.sqrt(2); // A4 landscape
                file.rel.push (CONFIG.R.reader);

            } else {
                file["aspect-ratio"] = 4/3;
                file.rel.push (CONFIG.R.player);
            }

            return file;
        }

    },

    getData: function(cheerio, decode) {

        var $scope = cheerio('[itemscope]');

        if ($scope.length) {

            var $aScope = cheerio($scope);

            var result = {};

            $aScope.find('[itemprop]').each(function() {
                var $el = cheerio(this);

                var scope = $el.attr('itemscope');
                if (typeof scope !== 'undefined') {
                    return;
                }

                var key = $el.attr('itemprop');
                if (key) {
                    var value = decode($el.attr('content') || $el.attr('href'));
                    result[key] = value;
                }
            });

            return {
                schemaFileObject: result
            };
        }
    },

    tests: [
        "https://docs.google.com/document/d/17jg1RRL3RI969cLwbKBIcoGDsPwqaEdBxafGNYGwiY4/preview?sle=true",
        "https://docs.google.com/document/d/1KHLQiZkTFvMvBHmYgntEQtNxXswOQISjkbpnRO3jLrk/edit",
        "https://docs.google.com/presentation/d/1fE0PW1FMlYU9Xhig_QIGF8Yk1ApVfQQvntEEi4GbCm8/edit#slide=id.p",
        "https://docs.google.com/presentation/d/1fE0PW1FMlYU9Xhig_QIGF8Yk1ApVfQQvntEEi4GbCm8/preview",
        "https://docs.google.com/forms/d/1mJcBz16JAfxomVXIohDJv8w-AJw8t-jhAd1HgIwTlF8/viewform?c=0&w=1",
        "https://docs.google.com/file/d/0BzufrRo-waV_NlpOTlI0ZnB4eVE/preview",
        "https://drive.google.com/file/d/0BwGT3x6igRtkTWNtLWlhV3paZjA/view",
        "https://docs.google.com/spreadsheets/d/10JLM1UniyGNuLaYTfs2fnki-U1iYFsQl4XNHPZTYunw/edit?pli=1#gid=0",
        {
            skipMixins: [
                "og-image", "og-title", "og-description", "twitter-player-responsive"
            ],
            skipMethods: [
                "getLink",
                "getMeta",
                "getData"
            ]
        }

    ]

};