text:
package com.phaxio.repositories;

import com.phaxio.services.Requests;
import com.phaxio.resources.Fax;
import com.phaxio.restclient.entities.RestRequest;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class FaxRepository {
    private Requests client;

    public FaxRepository (Requests client) {
        this.client = client;
    }

    /**
     * Sends a fax
     * @param options A HashMap representing all the parameters for the fax. See the Phaxio documentation for the exact parameter names.
     *                Note that for fields that allow multiple items, use square brackets in the key and a Collection as the value.
     * @return The newly created Fax
     */
    public Fax create (Map<String, Object> options) {
        RestRequest request = new RestRequest();
        request.resource = "faxes";

        for (Entry<String, Object> option : options.entrySet()) {
            if (option.getKey().equals("to[]")) {
                Collection<String> recipients = (Collection<String>)option.getValue();
                for (String recipient : recipients) {
                    request.addParameter(option.getKey(), recipient);
                }
            } else if (option.getKey().equals("content_url[]")) {
                Collection<String> urls = (Collection<String>)option.getValue();
                for (String url : urls) {
                    request.addParameter(option.getKey(), url);
                }
            } else if (option.getKey().equals("file")) {
                addFile((File)option.getValue(), request);
            } else if (option.getKey().equals("file[]")) {
                Collection<File> files = (Collection<File>)option.getValue();
                for (File file : files) {
                    addFile(file, request);
                }
            } else {
                request.addParameter(option.getKey(), option.getValue());
            }
        }

        Fax fax = client.post(request, Fax.class);

        fax.setClient(client);

        return fax;
    }

    /**
     * Retrieves a fax by id
     * @param id The ID of the fax you'd like to retrieve
     * @return The fax
     */
    public Fax retrieve(int id) {
        RestRequest request = new RestRequest();
        request.resource = "faxes/" + id;

        return client.get(request, Fax.class);
    }

    /**
     * Lists sent faxes
     * @return A list of faxes
     */
    public Iterable<Fax> list() {
        return list(new HashMap<String, Object>());
    }

    /**
     * Lists sent faxes that match the given filters
     * @param filters The filters to apply (see the API documentation for parameters)
     * @return A list of faxes
     */
    public Iterable<Fax> list(Map<String, Object> filters) {
        RestRequest request = new RestRequest();
        request.resource = "faxes";

        for (Entry<String, Object> option : filters.entrySet()) {
            request.addParameter(option.getKey(), option.getValue());
        }

        return client.list(request, Fax.class);
    }

    /**
     * Sends a request to Phaxio to test a callback (web hook).
     * @param options The options for the callback - see the API documentation for the parameter names
     */
    public void testReceiveCallback(Map<String, Object> options)
    {
        RestRequest request = new RestRequest();
        request.resource = "faxes";

        request.addParameter("direction", "received");

        for (Entry<String, Object> option : options.entrySet()) {
            if (option.getKey().equals("file")) {
                addFile((File)option.getValue(), request, false);
            } else {
                request.addParameter(option.getKey(), option.getValue());
            }
        }

        client.post(request);
    }

    private void addFile (File file, RestRequest request) {
        addFile(file, request, true);
    }

    private void addFile (File file, RestRequest request, boolean multiple) {
        String param = multiple ? "file[]" : "file";

        try {
            byte[] bytes = IOUtils.toByteArray(new FileInputStream(file));
            request.addFile(param, bytes, file.getName(), null);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
package mesosphere.marathon
package api.v2

import java.time.Clock
import javax.inject.Inject
import javax.servlet.http.HttpServletRequest
import javax.ws.rs._
import javax.ws.rs.core.{ Context, MediaType, Response }

import mesosphere.marathon.api.{ AuthResource, MarathonMediaType }
import mesosphere.marathon.core.launchqueue.LaunchQueue
import mesosphere.marathon.plugin.auth.{ Authenticator, Authorizer, UpdateRunSpec, ViewRunSpec }
import mesosphere.marathon.raml.Raml
import mesosphere.marathon.state.PathId._

@Path("v2/queue")
@Consumes(Array(MediaType.APPLICATION_JSON))
class QueueResource @Inject() (
    clock: Clock,
    launchQueue: LaunchQueue,
    val authenticator: Authenticator,
    val authorizer: Authorizer,
    val config: MarathonConf) extends AuthResource {

  @GET
  @Produces(Array(MarathonMediaType.PREFERRED_APPLICATION_JSON))
  def index(@Context req: HttpServletRequest, @QueryParam("embed") embed: java.util.Set[String]): Response = authenticated(req) { implicit identity =>
    val embedLastUnusedOffers = embed.contains(QueueResource.EmbedLastUnusedOffers)
    val infos = launchQueue.listWithStatistics.filter(t => t.inProgress && isAuthorized(ViewRunSpec, t.runSpec))
    ok(Raml.toRaml((infos, embedLastUnusedOffers, clock)))
  }

  @DELETE
  @Path("""{appId:.+}/delay""")
  def resetDelay(
    @PathParam("appId") id: String,
    @Context req: HttpServletRequest): Response = authenticated(req) { implicit identity =>
    val appId = id.toRootPath
    val maybeApp = launchQueue.list.find(_.runSpec.id == appId).map(_.runSpec)
    withAuthorization(UpdateRunSpec, maybeApp, notFound(s"Application $appId not found in tasks queue.")) { app =>
      launchQueue.resetDelay(app)
      noContent
    }
  }
}

object QueueResource {
  val EmbedLastUnusedOffers = "lastUnusedOffers"
}

redpajama_set_name: RedPajamaGithub


text:
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../../bower_components/polymer/polymer.html">
<script src="../../bower_components/jquery/dist/jquery.min.js"></script>
<script src="../../bower_components/select2/dist/js/select2.full.min.js"></script>
<link rel="stylesheet" href="../../bower_components/select2/dist/css/select2.min.css">
<!--
Polymer 1.0 wrapper for Select2

Example:

    <select2-wrapper id="my_select2_element"></select2-wrapper>
    <script>
      document.getElementById('my_select2_element').model = [
        {
          label: 'Asia',
          value: 'AS'
        }
      ];
    </script>

@group Wrappers
@element select2-wrapper
@demo http://kolarski.github.io/select2-wrapper/bower_components/select2-wrapper/demo/
@hero hero.svg
-->
<dom-module id="select2-wrapper">

  <style>
    :host {
      display: block;
      box-sizing: border-box;
    }
  </style>

  <template>
    <select id="select2-wrapper-tag" style="width: 100%">
      <template is="dom-repeat" items="{{model}}">
        <option value="{{item.value}}">{{item.label}}</option>
      </template>
    </select>
  </template>

</dom-module>

<script>

  Polymer({

    is: 'select2-wrapper',

    _onUpdateSelectItems: function (data) {
      if (data){
        $(document).ready(function () {
          $("#select2-wrapper-tag").select2({
            data: data
          });
        });
      }
    },
    properties: {
      /**
       * This property sets the select2 items
       * @type Array
       */
      model: {
        type: Array,
        value: null,
        observer: '_onUpdateSelectItems'
      }
    }
  });

</script>


text:
package alec_wam.CrystalMod.tiles.machine.power.converter;

import alec_wam.CrystalMod.network.CrystalModNetwork;
import alec_wam.CrystalMod.network.IMessageHandler;
import alec_wam.CrystalMod.network.packets.PacketTileMessage;
import alec_wam.CrystalMod.tiles.TileEntityMod;
import net.minecraft.nbt.NBTTagCompound;

public abstract class TileEnergyConveterBase extends TileEntityMod implements IMessageHandler {

	public abstract PowerUnits getUnitType();

	public abstract void setEnergyStored(int power);
	public abstract int getEnergyStored();
	public abstract int getMaxEnergyStored();

	protected float lastSyncPowerStored = -1;
	@Override
	public void update(){
		super.update();
		if(!getWorld().isRemote){
			boolean powerChanged = (lastSyncPowerStored != getEnergyStored() && shouldDoWorkThisTick(5));
		    if(powerChanged) {
		      lastSyncPowerStored = getEnergyStored();
		      NBTTagCompound nbt = new NBTTagCompound();
		      nbt.setInteger("Power", getEnergyStored());
		      CrystalModNetwork.sendToAllAround(new PacketTileMessage(getPos(), "UpdatePower", nbt), this);
		    }
		}

	}

	protected final int getPowerNeeded( final PowerUnits externalUnit, final int maxPowerRequired )
	{
		return getUnitType().convertTo( externalUnit, Math.max( 0, getFunnelPowerNeeded( externalUnit.convertTo( getUnitType(), maxPowerRequired ) ) ) );
	}

	protected int getFunnelPowerNeeded( final double maxRequired )
	{
		return getMaxEnergyStored() - getEnergyStored();
	}

	public final int injectExternalPower( final PowerUnits input, final int amt )
	{
		return getUnitType().convertTo( input, this.funnelPowerIntoStorage( input.convertTo( getUnitType(), amt ), false ) );
	}

	protected int funnelPowerIntoStorage( int amt, final boolean sim )
	{
		if( sim )
		{
			final int fakeBattery = getEnergyStored() + amt;

			if( fakeBattery > getMaxEnergyStored() )
			{
				return fakeBattery - getMaxEnergyStored();
			}

			return 0;
		}
		else
		{
			final int old = getEnergyStored();
			setEnergyStored( getEnergyStored() + amt );
			if( old+amt > getMaxEnergyStored() )
			{
				amt = old - getMaxEnergyStored();
				return amt;
			}

			return 0;
		}
	}

	@Override
	public void handleMessage(String messageId, NBTTagCompound messageData,	boolean client) {
		if(messageId.equalsIgnoreCase("UpdatePower")){
			int newPower = messageData.getInteger("Power");
			setEnergyStored(newPower);
		}
	}

}


text:
package interfaces;// interfaces/RandVals.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Initializing interface fields with
// non-constant initializers
import java.util.*;

public interface RandVals {
  Random RAND = new Random(47);
  int RANDOM_INT = RAND.nextInt(10);
  long RANDOM_LONG = RAND.nextLong() * 10;
  float RANDOM_FLOAT = RAND.nextLong() * 10;
  double RANDOM_DOUBLE = RAND.nextDouble() * 10;
}


text:
function uploads_multimedia_init (title, btnName, editing, multiple) {
		var outArray = [];
		var file_frame;
		if (file_frame) {
			file_frame.open();
			return;
		}

		file_frame = wp.media.editor.send.attachment  = wp.media({
			 title: title,
		     button: {
						text: btnName
					 },
			 editing:    editing,
			 multiple:   multiple,
		});
		return file_frame;
}

jQuery(document).ready(function() {
   jQuery('.upload_btn').live('click', function( event ) {
			event.preventDefault();
			var vLinkElem = jQuery(this);
			var customData = vLinkElem.data('imagetype');
			var customClass = '';

			var file_frame = uploads_multimedia_init('Upload Image', 'Select Image', true, false);
			file_frame.on( 'select', function() {
				var selection = file_frame.state().get('selection');
					selection.map( function( attachment ) {
						attachment = attachment.toJSON();
						var image_url = attachment.url,
							image_id  = attachment.id;

							vLinkElem.parent().find('.boxes').css('background-image', 'url(' + image_url + ')');
							vLinkElem.parent().find('.boxes').append('<input class="button delete-img remove" type="submit" name="remove_bg" value="x" />');
							vLinkElem.parent().parent().find('input[type="hidden"]').val(image_id);
					});

			});

			file_frame.open();
			return false;
		});

		jQuery('.delete-img').live('click', function( event ) {
			event.preventDefault();
				var vLinkElem = jQuery(this);
					vLinkElem.parent().css('background-image', 'none');
					vLinkElem.parent().parent().parent().find('input[type="hidden"]').val('');
					vLinkElem.remove();
			return false;
		});

});


text:
class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /.@./
      record.errors.add attribute, options.fetch(:message, "invalid address")
    end
  end
end


text:
package org.unitime.timetable.model.base;

import java.util.List;

import org.unitime.timetable.model.EventDateMapping;
import org.unitime.timetable.model.dao._RootDAO;
import org.unitime.timetable.model.dao.EventDateMappingDAO;

/**
 * Do not change this class. It has been automatically generated using ant create-model.
 * @see org.unitime.commons.ant.CreateBaseModelFromXml
 */
public abstract class BaseEventDateMappingDAO extends _RootDAO<EventDateMapping,Long> {

	private static EventDateMappingDAO sInstance;

	public static EventDateMappingDAO getInstance() {
		if (sInstance == null) sInstance = new EventDateMappingDAO();
		return sInstance;
	}

	public Class<EventDateMapping> getReferenceClass() {
		return EventDateMapping.class;
	}

	@SuppressWarnings("unchecked")
	public List<EventDateMapping> findBySession(org.hibernate.Session hibSession, Long sessionId) {
		return hibSession.createQuery("from EventDateMapping x where x.session.uniqueId = :sessionId").setLong("sessionId", sessionId).list();
	}
}


text:
package repository

import (
	"bytes"
	"fmt"
	"os/exec"
	"strings"

	"github.com/vito/gocart/command_runner"
)

type GitRepository struct {
	path   string
	runner command_runner.CommandRunner
}

func (r *GitRepository) Checkout(version string) error {
	return r.runner.Run(r.gitCmd("checkout", version))
}

func (r *GitRepository) CurrentVersion() (string, error) {
	cmd := r.gitCmd("rev-parse", "HEAD")

	out, err := r.cmdOutput(cmd)
	if err != nil {
		return "", err
	}

	return strings.TrimRight(out, "\n"), nil
}

func (r *GitRepository) Update() error {
	return r.runner.Run(r.gitCmd("fetch"))
}

func (r *GitRepository) Status() (string, error) {
	return r.cmdOutput(r.gitCmd("status", "--porcelain"))
}

func (r *GitRepository) Log(from, to string) (string, error) {
	return r.cmdOutput(r.gitCmd("log", "--oneline", fmt.Sprintf("%s..%s", from, to)))
}

func (r *GitRepository) gitCmd(args ...string) *exec.Cmd {
	cmd := exec.Command("git", args...)
	cmd.Dir = r.path

	return cmd
}

func (r *GitRepository) cmdOutput(cmd *exec.Cmd) (string, error) {
	buf := new(bytes.Buffer)

	cmd.Stdout = buf
	cmd.Stderr = buf

	err := r.runner.Run(cmd)
	if err != nil {
		return "", err
	}

	return string(buf.Bytes()), nil
}


text:
Vue.component('CategoryItemInfo', {
    props: {
        // Contents of the item
        item: {type: Object, required: true},
    },

    computed: {
        // Item group, e.g. "PCRE-based" or "POSIX-based" for regex libraries
        group: function() {
            return this.item.group_ || "other" },
        // Link to the "official site" or something
        link: function () {
            return this.item.link || null },
        // Link to the Hackage page (for Haskell packages)
        hackageLink: function () {
            return (this.item.kind.tag == "Library") ? this.item.kind.contents :
                   (this.item.kind.tag == "Tool") ? this.item.kind.contents :
                   null },
    },

    // TODO: this template is somewhat messy; styles should be moved out;
    // spans and divs used like here are weird, too
    template: `

        #

        {{ item.name }}
        {{ item.name }}
        <template v-if="hackageLink !== null">
            (Hackage)
        </template>

        {{ group }}

`,
});

////////////////////////////////////////////////////////////////////////////
// Item info edit form
//
// Shown when you press the cog in the item titlebar.
////////////////////////////////////////////////////////////////////////////

Vue.component('CategoryItemInfoEdit', {
    props: {
        // Contents of the item
        item: {type: Object, required: true},
    },

    // We use 'autocomplete=off' everywhere due to this:
    // http://stackoverflow.com/q/8311455
    template: `
<form class="item-info-edit-form" onsubmit="submitItemInfo('{{item.uid}}', this); return false;">
  Name
  <input id="name" name="name" value="{{item.name}}"
          type="text" autocomplete="off">

  Kind
  <select id="kind" name="kind" autocomplete="off">
    {{! possible_kinds would have stuff like "library", "tool", "other" }}
    {{#possible_kinds}}
      <option value="{{name}}" {{%selectIf selected}}>{{caption}}</option>
    {{/possible_kinds}}
  </select>

  Name on Hackage
  <input id="hackage-name" name="hackage-name" value="{{#item.kind.hackageName}}{{.}}{{/item.kind.hackageName}}"
          type="text" autocomplete="off">

  Site (optional)
  <input id="site" name="link" value="{{item.link}}"
          type="text" autocomplete="off">

  Group
  {{! When "new group" is selected in the list, we show a field for
      entering new group's name }}
  <select id="group" name="group" onchange="itemGroupSelectHandler(this);"
          autocomplete="off">
    <option value="-" {{%selectIf item_no_group}}>-</option>
    {{# category_groups }}
      <option value="{{name}}" {{%selectIf selected}}>{{name}}</option>
    {{/ category_groups }}
    <option value="">New group...</option>
  </select>

  <input hidden class="custom-group-input" name="custom-group"
         type="text" autocomplete="off">

    <input value="Save" class="save" type="submit">
    <input value="Cancel" class="cancel" type="button"
          onclick="itemInfoCancelEdit('{{item.uid}}');">

</form>
`,
});


text:
<?php

namespace iim\ChocolateBundle\Manager;

class ArticleManager extends Manager
{

}


text:
### Style guide

##### Comments

``` java
/**
 * Multiple lines of doc text are written here,
 * wrapped normally...
 */
public int method(String p1) { ... }
```

``` java
/**
 * Lines end at the first period followed by a blank space.
 * Likes this.
*/
```

``` java
/**
 * Lines shouldn't be longer than 100 characters
*/
```

##### Variable names
- lower Camel casing should be used with the variables.
- Variable names should be self explanatory.
- Names should not have an identifier of their types.
- CONSTANT_CASE should be used for constants.

##### Whitespace
- Tabs consist of spaces, not tabs.
- A space should be used around reserved words and method definition parentheses.

##### Class naming
- UpperCamelCasing.
- Class names are typically nouns or noun phrases.

``` java
public class MainActivity() extends AppCompatActivity { // Call activities Activity
```

##### Method naming
- lowerCamelCasing
- Use verb or verb phrases.

##### Column limit
- Java code has a column limit of 100 characters.

##### Flow
- Else should be on the same line as the ending } from the if statement.
- Use switches when possible


text: export * from './manpowerSummaryTable.component';


text:
// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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.

/**
 * @final
 */
export default class DaemonSetInfoController {
  /**
   * Constructs daemon set info object.
   */
  constructor() {
    /**
     * Daemon set details. Initialized from the scope.
     * @export {!backendApi.DaemonSetDetail}
     */
    this.daemonSet;

    /** @export */
    this.i18n = i18n(this.daemonSet);
  }

  /**
   * @return {boolean}
   * @export
   */
  areDesiredPodsRunning() {
    return this.daemonSet.podInfo.running === this.daemonSet.podInfo.desired;
  }
}

/**
 * Definition object for the component that displays daemon set info.
 *
 * @return {!angular.Directive}
 */
export const daemonSetInfoComponent = {
  controller: DaemonSetInfoController,
  templateUrl: 'daemonsetdetail/daemonsetinfo.html',
  bindings: {
    /** {!backendApi.DaemonSetDetail} */
    'daemonSet': '=',
  },
};

/**
 * @param  {!backendApi.DaemonSetDetail} daemonSet
 * @return {!Object} a dictionary of translatable messages
 */
function i18n(daemonSet) {
  return {
    /** @export {string} @desc Subtitle 'Details' for the left section with general information
       about a daemon set on the daemonset details page.*/
    MSG_DAEMON_SET_INFO_DETAILS_SUBTITLE: goog.getMsg('Details'),
    /** @export {string} @desc Label 'Namespace' for the daemon set namespace on the details page.*/
    MSG_DAEMON_SET_INFO_NAMESPACE_LABEL: goog.getMsg('Namespace'),
    /** @export {string} @desc Label 'Name' for the daemon set name on the details page.*/
    MSG_DAEMON_SET_INFO_NAME_LABEL: goog.getMsg('Name'),
    /** @export {string} @desc Label 'Labels' for the daemon set's labels list on the
    daemon set details page.*/
    MSG_DAEMON_SET_INFO_LABELS_LABEL: goog.getMsg('Labels'),
    /** @export {string} @desc Label 'Images' for the list of images used in a daemon set, on its
       details page. */
    MSG_DAEMON_SET_INFO_IMAGES_LABEL: goog.getMsg('Images'),
    /** @export {string} @desc Subtitle 'Status' for the right section with pod status information
       on the daemon set details page.*/
    MSG_DAEMON_SET_INFO_STATUS_SUBTITLE: goog.getMsg('Status'),
    /** @export {string} @desc Label 'Pods' for the pods in a daemon set on its details page.*/
    MSG_DAEMON_SET_INFO_PODS_LABEL: goog.getMsg('Pods'),
    /** @export {string} @desc Label 'Pods status' for the status of the pods in a daemon set, on
       the daemon set details page.*/
    MSG_DAEMON_SET_INFO_PODS_STATUS_LABEL: goog.getMsg('Pods status'),
    /** @export {string} @desc The message says that that many pods were created
    (daemon set details page). */
    MSG_DAEMON_SET_INFO_PODS_CREATED_LABEL:
        goog.getMsg('{$podsCount} created', {'podsCount': daemonSet.podInfo.current}),
    /** @export {string} @desc The message says that that many pods are running
    (daemon set details page). */
    MSG_DAEMON_SET_INFO_PODS_RUNNING_LABEL:
        goog.getMsg('{$podsCount} running', {'podsCount': daemonSet.podInfo.running}),
    /** @export {string} @desc The message says that that many pods are pending
    (daemon set details page). */
    MSG_DAEMON_SET_INFO_PODS_PENDING_LABEL:
        goog.getMsg('{$podsCount} pending', {'podsCount': daemonSet.podInfo.pending}),
    /** @export {string} @desc The message says that that many pods have failed
    (daemon set details page). */
    MSG_DAEMON_SET_INFO_PODS_FAILED_LABEL:
        goog.getMsg('{$podsCount} failed', {'podsCount': daemonSet.podInfo.failed}),
    /** @export {string} @desc The message says that that many pods are desired to run
    (daemon set details page). */
    MSG_DAEMON_SET_INFO_PODS_DESIRED_LABEL:
        goog.getMsg('{$podsCount} desired', {'podsCount': daemonSet.podInfo.desired}),
  };
}


text:
using System.Linq;
using AllReady.Areas.Admin.Models;
using AllReady.Models;
using MediatR;
using Microsoft.Data.Entity;

namespace AllReady.Features.Notifications
{
    public class ActivityDetailForNotificationQueryHandler : IRequestHandler<ActivityDetailForNotificationQuery, ActivityDetailForNotificationModel>
    {
        private AllReadyContext _context;

        public ActivityDetailForNotificationQueryHandler(AllReadyContext context)
        {
            _context = context;
        }

        public ActivityDetailForNotificationModel Handle(ActivityDetailForNotificationQuery message)
        {
            ActivityDetailForNotificationModel result = null;

            var activity = _context.Activities
                .AsNoTracking()
                .Include(a => a.Campaign)
                .Include(a => a.Campaign.CampaignContacts).ThenInclude(c => c.Contact)
                .Include(a => a.Tasks).ThenInclude(t => t.AssignedVolunteers).ThenInclude(av => av.User)
                .Include(a => a.UsersSignedUp).ThenInclude(a => a.User)
                .SingleOrDefault(a => a.Id == message.ActivityId);

            if (activity != null)
            {
                result = new ActivityDetailForNotificationModel
                {
                    ActivityId = activity.Id,
                    CampaignName = activity.Campaign.Name,
                    CampaignContacts = activity.Campaign.CampaignContacts,
                    ActivityName = activity.Name,
                    Description = activity.Description,
                    UsersSignedUp = activity.UsersSignedUp,
                    NumberOfVolunteersRequired = activity.NumberOfVolunteersRequired,
                    Tasks = activity.Tasks.Select(t => new TaskSummaryModel()
                    {
                        Id = t.Id,
                        Name = t.Name,
                        StartDateTime = t.StartDateTime,
                        EndDateTime = t.EndDateTime,
                        AssignedVolunteers = t.AssignedVolunteers.Select(assignedVolunteer => new VolunteerModel
                        {
                            UserId = assignedVolunteer.User.Id,
                            UserName = assignedVolunteer.User.UserName,
                            HasVolunteered = true
                        }).ToList()
                    }).OrderBy(t => t.StartDateTime).ThenBy(t => t.Name).ToList(),
                };
            }
            return result;
        }
    }
}


text:
import os
import tempfile

from numpy.testing import assert_equal, assert_raises

from fuel.config_parser import (Configuration, ConfigurationError,
                                extra_downloader_converter)

class TestExtraDownloaderConverter(object):
    def test_iterable(self):
        assert_equal(extra_downloader_converter(['a.b.c', 'd.e.f']),
                     ['a.b.c', 'd.e.f'])

    def test_str(self):
        assert_equal(extra_downloader_converter("a.b.c d.e.f"),
                     ['a.b.c', 'd.e.f'])

    def test_str_one_element(self):
        assert_equal(extra_downloader_converter("a.b.c"), ['a.b.c'])

def test_config_parser():
    _environ = dict(os.environ)
    try:

        with tempfile.NamedTemporaryFile(mode='w', delete=False) as f:
            f.write('data_path: yaml_path')
            filename = f.name
        os.environ['FUEL_CONFIG'] = filename
        if 'FUEL_DATA_PATH' in os.environ:
            del os.environ['FUEL_DATA_PATH']
        config = Configuration()
        config.add_config('data_path', str, env_var='FUEL_DATA_PATH')
        config.add_config('config_with_default', int, default='1',
                          env_var='FUEL_CONFIG_TEST')
        config.add_config('config_without_default', str)
        config.load_yaml()
        assert config.data_path == 'yaml_path'
        os.environ['FUEL_DATA_PATH'] = 'env_path'
        assert config.data_path == 'env_path'
        assert config.config_with_default == 1
        os.environ['FUEL_CONFIG_TEST'] = '2'
        assert config.config_with_default == 2
        assert_raises(AttributeError, getattr, config,
                      'non_existing_config')
        assert_raises(ConfigurationError, getattr, config,
                      'config_without_default')
        config.data_path = 'manual_path'
        assert config.data_path == 'manual_path'
        config.new_config = 'new_config'
        assert config.new_config == 'new_config'
    finally:
        os.environ.clear()
        os.environ.update(_environ)


text:
import * as path from '@node-compat/path';

console.log(path.resolve ("/hi/there", "./bar"));
console.log(path.resolve ("/hi/there", "../bar"));
console.log(path.resolve ("/hi/there", "../../bar"));
console.log(path.resolve ("/hi/there", "../../../bar"));
console.log(path.resolve ("/hi/there", "../../../../bar"));
console.log(path.resolve ("/hi/there", "../../../../bar/fweep"));
console.log(path.resolve ("/hi//there", "bar"));
console.log(path.resolve ("/hi////there", "bar"));
console.log(path.resolve ("/hi/there", "/fweep"));


text:
#ifndef IVW_ALGORITHMOPTIONS_H
#define IVW_ALGORITHMOPTIONS_H

#include <modules/base/basemoduledefine.h>

namespace inviwo {

enum class IgnoreSpecialValues { No, Yes };

}  // namespace inviwo

#endif  // IVW_ALGORITHMOPTIONS_H


text:
package pl.srw.todos.presenter.task;

import android.os.AsyncTask;

import java.util.Collection;

import javax.inject.Inject;

import pl.srw.todos.model.Repository;
import pl.srw.todos.model.Todo;
import timber.log.Timber;

/**
 * Async task for retrieving data from repository
 */
public class GetTask extends AsyncTask<Void, Void, Collection<Todo>> {

    private Caller caller;
    private Repository repository;

    @Inject
    public GetTask(Repository repository) {
        this.repository = repository;
    }

    @Override
    protected Collection<Todo> doInBackground(Void... params) {
        Timber.d("Requesting data...");
        return repository.get();
    }

    @Override
    protected void onPostExecute(Collection<Todo> todos) {
        if (caller != null) {
            caller.onDataRetrieved(todos);
        }
    }

    public void execute(Caller caller) {
        this.caller = caller;
        this.execute();
    }

    /**
     * Callback with get results
     */
    public interface Caller {
        void onDataRetrieved(Collection<Todo> todos);
    }
}


text:
Welcome all kinds of features requested, bugs caught and enhancement suggestions or anything else.

Just open new [issues](https://github.com/arrowrowe/tam/issues).

## Send a Pull Request

Thanks a lot in advance.

Feel free to fork and send PRs,
only two rules:
no old tests broken, and always 100% coverage.

(We use [ghooks](https://github.com/gtramontina/ghooks) to perform tests before any commit.)


text:
var fs = require("fs");
var data = fs.readFileSync("package.json", "utf8");
var packagejson = JSON.parse(data);
fs.writeFileSync("component.json", JSON.stringify({
        name: packagejson.name,
        description: packagejson.description,
        version: packagejson.version,
        keywords: packagejson.keywords,
        main: "bean.js",
        scripts: ["bean.js"],
        repo: "https://github.com/fat/bean"
    }, null, 2)
);


text:
<?php

/**
 * Exception that is thrown when a process times out.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 */
class Symfony_Process_Exception_ProcessTimedOutException extends Exception implements Symfony_Process_Exception_ExceptionInterface
{
    const TYPE_GENERAL = 1;
    const TYPE_IDLE    = 2;

    private $process;
    private $timeoutType;

    public function __construct(Symfony_Process_Process $process, $timeoutType)
    {
        $this->process     = $process;
        $this->timeoutType = $timeoutType;

        parent::__construct(sprintf(
          'The process "%s" exceeded the timeout of %s seconds.',
          $process->getCommandLine(),
          $this->getExceededTimeout()
        ));
    }

    public function getProcess()
    {
        return $this->process;
    }

    public function isGeneralTimeout()
    {
        return $this->timeoutType === self::TYPE_GENERAL;
    }

    public function isIdleTimeout()
    {
        return $this->timeoutType === self::TYPE_IDLE;
    }

    public function getExceededTimeout()
    {
        switch ($this->timeoutType) {
            case self::TYPE_GENERAL:
                return $this->process->getTimeout();

            case self::TYPE_IDLE:
                return $this->process->getIdleTimeout();

            default:
                throw new Symfony_Process_Exception_LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType));
        }
    }
}


text:
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

## [3.0.3](https://github.com/kenhowardpdx/vscode-gist/compare/v3.0.2...v3.0.3) (2019-02-03)

## [3.0.2](https://github.com/kenhowardpdx/vscode-gist/compare/v3.0.1...v3.0.2) (2019-02-03)

## [3.0.1](https://github.com/kenhowardpdx/vscode-gist/compare/v3.0.0...v3.0.1) (2019-02-03)

# [3.0.0](https://github.com/kenhowardpdx/vscode-gist/compare/v2.1.2...v3.0.0) (2019-02-03)

### Bug Fixes

* public and private gist labels match reality ([9b74fea](https://github.com/kenhowardpdx/vscode-gist/commit/9b74fea)), closes [#96](https://github.com/kenhowardpdx/vscode-gist/issues/96)
* **insights:** use proper message key for exceptions ([2af8946](https://github.com/kenhowardpdx/vscode-gist/commit/2af8946)), closes [#90](https://github.com/kenhowardpdx/vscode-gist/issues/90)

### Features

* **create gist:** adds dialog when gist is created ([08c1bdf](https://github.com/kenhowardpdx/vscode-gist/commit/08c1bdf))
* **settings:** adds profileOptions to override profile values ([dc74e38](https://github.com/kenhowardpdx/vscode-gist/commit/dc74e38)), closes [#83](https://github.com/kenhowardpdx/vscode-gist/issues/83)

### BREAKING CHANGES

* **create gist:** uprev required vscode version to 1.30

## [2.1.2](https://github.com/kenhowardpdx/vscode-gist/compare/v2.1.1...v2.1.2) (2019-01-12)

### Bug Fixes

* change telemetry write key ([5e6fd13](https://github.com/kenhowardpdx/vscode-gist/commit/5e6fd13))
* changes reset profiles keyboard mapping ([e5e9521](https://github.com/kenhowardpdx/vscode-gist/commit/e5e9521)), closes [#84](https://github.com/kenhowardpdx/vscode-gist/issues/84)

## [2.1.1](https://github.com/kenhowardpdx/vscode-gist/compare/v2.1.0...v2.1.1) (2018-12-29)

# [2.1.0](https://github.com/kenhowardpdx/vscode-gist/compare/v1.2.1...v2.1.0) (2018-12-29)

### Bug Fixes

* create gist prompts for filename ([e82f2cd](https://github.com/kenhowardpdx/vscode-gist/commit/e82f2cd))

### Features

* adds ability to open remote gists ([663a386](https://github.com/kenhowardpdx/vscode-gist/commit/663a386))
* adds add file/selection ([9965742](https://github.com/kenhowardpdx/vscode-gist/commit/9965742))
* adds configuration options ([30d1e31](https://github.com/kenhowardpdx/vscode-gist/commit/30d1e31))
* adds create gist ([0265bdf](https://github.com/kenhowardpdx/vscode-gist/commit/0265bdf))
* adds debug flag when debugging ([20a6d61](https://github.com/kenhowardpdx/vscode-gist/commit/20a6d61))
* adds delete file from gist ([9d6afea](https://github.com/kenhowardpdx/vscode-gist/commit/9d6afea))
* adds delete gist ([37447b5](https://github.com/kenhowardpdx/vscode-gist/commit/37447b5))
* adds gists service ([7bec570](https://github.com/kenhowardpdx/vscode-gist/commit/7bec570))
* adds insert text from gist ([7e7c359](https://github.com/kenhowardpdx/vscode-gist/commit/7e7c359))
* adds logger ([4db0d27](https://github.com/kenhowardpdx/vscode-gist/commit/4db0d27))
* adds migrations ([7c9518e](https://github.com/kenhowardpdx/vscode-gist/commit/7c9518e))
* adds notify ([3c9c0d7](https://github.com/kenhowardpdx/vscode-gist/commit/3c9c0d7))
* adds open favorite ([29b9cb3](https://github.com/kenhowardpdx/vscode-gist/commit/29b9cb3))
* adds open in browser ([d3666e8](https://github.com/kenhowardpdx/vscode-gist/commit/d3666e8))
* adds output channel ([22ede07](https://github.com/kenhowardpdx/vscode-gist/commit/22ede07))
* adds profiles ([40a4f86](https://github.com/kenhowardpdx/vscode-gist/commit/40a4f86))
* adds quickpick list for gists ([c60e787](https://github.com/kenhowardpdx/vscode-gist/commit/c60e787))
* adds telemetry ([9b91159](https://github.com/kenhowardpdx/vscode-gist/commit/9b91159))
* adds temporary file sync ([6009e1b](https://github.com/kenhowardpdx/vscode-gist/commit/6009e1b))
* adds updateCodeBlock ([0865240](https://github.com/kenhowardpdx/vscode-gist/commit/0865240))
* store package version for future updates ([6c91211](https://github.com/kenhowardpdx/vscode-gist/commit/6c91211))

# [2.0.0](https://github.com/kenhowardpdx/vscode-gist/compare/v1.2.1...v2.0.0) (2018-12-29)

### Features

* adds ability to open remote gists ([663a386](https://github.com/kenhowardpdx/vscode-gist/commit/663a386))
* adds add file/selection ([9965742](https://github.com/kenhowardpdx/vscode-gist/commit/9965742))
* adds configuration options ([30d1e31](https://github.com/kenhowardpdx/vscode-gist/commit/30d1e31))
* adds create gist ([0265bdf](https://github.com/kenhowardpdx/vscode-gist/commit/0265bdf))
* adds debug flag when debugging ([20a6d61](https://github.com/kenhowardpdx/vscode-gist/commit/20a6d61))
* adds delete file from gist ([9d6afea](https://github.com/kenhowardpdx/vscode-gist/commit/9d6afea))
* adds delete gist ([37447b5](https://github.com/kenhowardpdx/vscode-gist/commit/37447b5))
* adds gists service ([7bec570](https://github.com/kenhowardpdx/vscode-gist/commit/7bec570))
* adds insert text from gist ([7e7c359](https://github.com/kenhowardpdx/vscode-gist/commit/7e7c359))
* adds logger ([4db0d27](https://github.com/kenhowardpdx/vscode-gist/commit/4db0d27))
* adds migrations ([7c9518e](https://github.com/kenhowardpdx/vscode-gist/commit/7c9518e))
* adds notify ([3c9c0d7](https://github.com/kenhowardpdx/vscode-gist/commit/3c9c0d7))
* adds open favorite ([29b9cb3](https://github.com/kenhowardpdx/vscode-gist/commit/29b9cb3))
* adds open in browser ([d3666e8](https://github.com/kenhowardpdx/vscode-gist/commit/d3666e8))
* adds output channel ([22ede07](https://github.com/kenhowardpdx/vscode-gist/commit/22ede07))
* adds profiles ([40a4f86](https://github.com/kenhowardpdx/vscode-gist/commit/40a4f86))
* adds quickpick list for gists ([c60e787](https://github.com/kenhowardpdx/vscode-gist/commit/c60e787))
* adds telemetry ([9b91159](https://github.com/kenhowardpdx/vscode-gist/commit/9b91159))
* adds temporary file sync ([6009e1b](https://github.com/kenhowardpdx/vscode-gist/commit/6009e1b))
* adds updateCodeBlock ([0865240](https://github.com/kenhowardpdx/vscode-gist/commit/0865240))
* store package version for future updates ([6c91211](https://github.com/kenhowardpdx/vscode-gist/commit/6c91211))

## [1.2.1](https://github.com/kenhowardpdx/vscode-gist/compare/v1.1.5...v1.2.1) (2018-06-10)

### Bug Fixes

* **deps:** update github pkg to [@octokit](https://github.com/octokit)/rest pkg ([36e1b5a](https://github.com/kenhowardpdx/vscode-gist/commit/36e1b5a))

### Vulnerability Updates

* upgraded to latest dependencies to address vulnerability in hoek v2.16.3 ([CVE-2018-3728](https://nvd.nist.gov/vuln/detail/CVE-2018-3728), [9bc973c](https://github.com/kenhowardpdx/vscode-gist/commit/9bc973c))

### Notes

* Prevents `.vscode-test` folder from published with the extension. ([86f39ac](https://github.com/kenhowardpdx/vscode-gist/commit/86f39ac))
* Updates README.md with note on logging in with access tokens. ([27f7b67](https://github.com/kenhowardpdx/vscode-gist/commit/27f7b67))

# [1.2.0](https://github.com/kenhowardpdx/vscode-gist/compare/v1.1.5...v1.2.0) (2018-01-03)

### Features

* **default file threshold:** Add codeBlockFileNotificationThreshold user setting. ([233fab6](https://github.com/kenhowardpdx/vscode-gist/commit/233fab6))
* **open single:** Open a single file if block has more than 10 files ([9352558](https://github.com/kenhowardpdx/vscode-gist/commit/9352558))

## [1.1.5](https://github.com/kenhowardpdx/vscode-gist/compare/v1.1.4...v1.1.5) (2017-11-07)

### Bug Fixes

* **Initialization test:** return actual instance of controller. ([d14b333](https://github.com/kenhowardpdx/vscode-gist/commit/d14b333))
* **open multiple files:** keep editor open, don't split ([936a5a7](https://github.com/kenhowardpdx/vscode-gist/commit/936a5a7)), closes [#18](https://github.com/kenhowardpdx/vscode-gist/issues/18)
* **openCodeBlock:** remove condition that closes other editors  ([e9d1017](https://github.com/kenhowardpdx/vscode-gist/commit/e9d1017)), closes [#16](https://github.com/kenhowardpdx/vscode-gist/issues/16)

### Features

* **Log Out:** Added status bar "GIST" to indicate logged in status. ([93edeeb](https://github.com/kenhowardpdx/vscode-gist/commit/93edeeb)), closes [#14](https://github.com/kenhowardpdx/vscode-gist/issues/14)

## [1.1.4](https://github.com/kenhowardpdx/vscode-gist/compare/v1.1.3...v1.1.4) (2017-08-30)

## [1.1.3](https://github.com/kenhowardpdx/vscode-gist/compare/v1.1.2...v1.1.3) (2017-08-30)

### Bug Fixes

* **save:** pass doc to onSaveTextDocument ([9528eb8](https://github.com/kenhowardpdx/vscode-gist/commit/9528eb8)), closes [#9](https://github.com/kenhowardpdx/vscode-gist/issues/9)

## [1.1.2](https://github.com/kenhowardpdx/vscode-gist/compare/v1.1.1...v1.1.2) (2017-08-29)

## [1.1.1](https://github.com/kenhowardpdx/vscode-gist/compare/v1.1.0...v1.1.1) (2017-08-29)

### Features

* **Insert Text:** Add insert text feature ([96e3609](https://github.com/kenhowardpdx/vscode-gist/commit/96e3609)), closes [#5](https://github.com/kenhowardpdx/vscode-gist/issues/5)

## [1.0.1](https://github.com/kenhowardpdx/vscode-gist/compare/v1.0.0...v1.0.1) (2017-08-16)

# [1.0.0](https://github.com/kenhowardpdx/vscode-gist/compare/v1.0.0-beta.1...v1.0.0) (2017-08-16)

# [1.0.0-beta.1](https://github.com/kenhowardpdx/vscode-gist/compare/v1.0.0-beta.0...v1.0.0-beta.1) (2017-07-10)

# [1.0.0-beta.0](https://github.com/kenhowardpdx/vscode-gist/compare/v0.5.3...v1.0.0-beta.0) (2017-03-30)

This release is a precursor for future development enabling adding providers other that GitHub Gists.

### Features

* **Add File:** Add a file to existing code block ([b2e3637](https://github.com/kenhowardpdx/vscode-gist/commit/b2e3637))
* **Change Description:** Enable change description ([484b6b2](https://github.com/kenhowardpdx/vscode-gist/commit/484b6b2))
* **Create Block:** Add ability to create a code block ([7bb2738](https://github.com/kenhowardpdx/vscode-gist/commit/7bb2738))
* **Delete Block:** Allow users to delete current code block ([e79645e](https://github.com/kenhowardpdx/vscode-gist/commit/e79645e))
* **Open Favorite:** Add ability to open favorite code block ([a19e22d](https://github.com/kenhowardpdx/vscode-gist/commit/a19e22d))
* **Open in browser:** Adds ability to open current gist in browser ([f378050](https://github.com/kenhowardpdx/vscode-gist/commit/f378050))
* **Remove File:** Users can remove a file from a code block ([a7b0b78](https://github.com/kenhowardpdx/vscode-gist/commit/a7b0b78))
* **Save Files:** Save a 'CodeFile' ([c70c595](https://github.com/kenhowardpdx/vscode-gist/commit/c70c595))

### TODO

* **Select Provider:** Currently we only have Gists as a provider. We need to let the user select a provider on the first attempt to authenticate.
* **Change Provider:** The user should be able to change a provider easily.
* **Add Provider:** We'll be adding providers like Bitbucket Snippets ([#12](https://github.com/kenhowardpdx/vscode-gist/issues/12))

### Breaking Changes

* **VSCode Version**: Bump minimum required VSCode version to 1.9.0

## [0.5.3](https://github.com/kenhowardpdx/vscode-gist/compare/v0.5.2...v0.5.3) (2017-03-02)

### Bug Fixes

* **bug** Adjust regex to work with windows paths ([#13](https://github.com/kenhowardpdx/vscode-gist/pull/13)), closes [#6](https://github.com/kenhowardpdx/vscode-gist/issues/6)
* **bug** Fixes "Cannot read property 'url' of undefined" ([88e46c8](https://github.com/kenhowardpdx/vscode-gist/commit/88e46c83b6e2decacd28dda4becf1052bc793fb7)), closes [#11](https://github.com/kenhowardpdx/vscode-gist/issues/11)

## 0.5.2 (2016-10-06)


text:
package org.marble.commons.executor.streamer;

import org.marble.model.domain.model.Job;
import org.marble.model.domain.model.Post;
import org.marble.model.domain.model.Topic;
import org.marble.model.model.GeoLocation;
import org.marble.model.model.JobParameters;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;

import org.marble.commons.exception.InvalidExecutionException;
import org.marble.commons.exception.InvalidModuleException;
import org.marble.commons.exception.InvalidTopicException;
import org.marble.commons.executor.extractor.TwitterExtractionExecutor;
import org.marble.commons.executor.processor.ProcessorExecutor;
import org.marble.commons.model.JobRestResult;
import org.marble.commons.model.RestResult;
import org.marble.commons.service.JobService;
import org.marble.commons.service.PostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.StatusListener;

public class TwitterStreamingListener implements StatusListener {

  JobService jobService;

  PostService postService;
  private boolean failure = false;
  private boolean stopping = false;
  private String topicName;
  private String[] keywords;
  private ArrayList<double[]> locations;
  private Topic topic;
  private static final Logger log = LoggerFactory.getLogger(TwitterExtractionExecutor.class);
  private long count;
  private Job job;

  public TwitterStreamingListener(Topic topic, Job job, PostService postService,
      JobService executionService) {
    this.topic = topic;
    String keywordsString = topic.getKeywords();
    if (keywordsString != null) {
      keywordsString = keywordsString.toLowerCase();
    }
    this.keywords = keywordsString.split("\\|");

    this.job = job;
    this.postService = postService;
    this.topicName = topic.getName();
    this.jobService = executionService;

    Double longitude = topic.getGeoLongitude();
    Double latitude = topic.getGeoLatitude();
    Double radius = topic.getGeoRadius();
    if (longitude != null && latitude != null && radius != null) {
      this.locations = getSquareAroundPoint(latitude, longitude, radius);
    }
    count = 0;
  }

  private ArrayList<double[]> getSquareAroundPoint(Double lat, Double lon, Double radius) {
    double R = 6371;
    double distance = radius.doubleValue();

    double north = (lat * Math.PI / 180 + distance / R) * 180 / Math.PI;
    if (north > 90)
      north = 90;

    double neast = (lon + (Math.atan2(Math.sin(distance / R) * Math.cos(lat * Math.PI / 180),
        Math.cos(distance / R)
            - Math.sin(lat * Math.PI / 180) * Math.sin(lat * Math.PI / 180 + distance / R)))
        * 180 / Math.PI);
    double nwest = (lon + (Math.atan2(-Math.sin(distance / R) * Math.cos(lat * Math.PI / 180),
        Math.cos(distance / R)
            - Math.sin(lat * Math.PI / 180) * Math.sin(lat * Math.PI / 180 + distance / R)))
        * 180 / Math.PI);

    double south = (lat * Math.PI / 180 - distance / R) * 180 / Math.PI;
    if (south < -90)
      south = -90;
    double seast = (lon + (Math.atan2(Math.sin(distance / R) * Math.cos(lat * Math.PI / 180),
        Math.cos(distance / R)
            - Math.sin(lat * Math.PI / 180) * Math.sin(lat * Math.PI / 180 - distance / R)))
        * 180 / Math.PI);
    double swest = (lon + (Math.atan2(-Math.sin(distance / R) * Math.cos(lat * Math.PI / 180),
        Math.cos(distance / R)
            - Math.sin(lat * Math.PI / 180) * Math.sin(lat * Math.PI / 180 - distance / R)))
        * 180 / Math.PI);

    double east = Math.max(seast, neast);
    double west = Math.min(swest, nwest);
    while (east > 180)
      east -= 360;
    while (east <= -180)
      east += 360;
    while (west > 180)
      east -= 360;
    while (west <= -180)
      east += 360;
    ArrayList<double[]> coords = new ArrayList<double[]>();
    double[] southwest = {west, south};
    double[] northeast = {east, north};
    coords.add(southwest);
    coords.add(northeast);
    return coords;
  }

  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((keywords == null) ? 0 : keywords.hashCode());
    result = prime * result + ((topicName == null) ? 0 : topicName.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    TwitterStreamingListener other = (TwitterStreamingListener) obj;
    if (keywords == null) {
      if (other.keywords != null)
        return false;
    } else if (!keywords.equals(other.keywords))
      return false;
    if (topicName == null) {
      if (other.topicName != null)
        return false;
    } else if (!topicName.equals(other.topicName))
      return false;
    return true;
  }

  public String getTopicName() {
    return topicName;
  }

  public void setTopicName(String topicName) {
    this.topicName = topicName;
  }

  public long getCount() {
    return count;
  }

  public void setCount(long count) {
    this.count = count;
  }

  public void setKeywords(String[] keywords) {
    this.keywords = keywords;
  }

  public String[] getKeywords() {
    return keywords;
  }

  public Topic getTopic() {
    return topic;
  }

  public void setTopic(Topic topic) {
    this.topic = topic;
  }

  public String getLanguage() {
    return topic.getLanguage();
  }

  public ArrayList<double[]> getLocations() {
    return locations;
  }

  public Job getJob() {
    return job;
  }

  public void setJob(Job job) {
    this.job = job;
  }

  public void onStatus(Status status) {

    String msg =
        "Received new post <" + status.getId() + ">. Matching for topic <" + topic.getName() + ">.";
    log.info(msg);
    job.appendLog(msg);

    try {
      jobService.save(job);
    } catch (InvalidExecutionException e) {
      log.error("Couldn't persist job object.", e);
    }

    if (keywords != null && keywords.length > 0) {
      String[] phrases = keywords;
      String tweetText = status.getText().toLowerCase();
      Boolean matchesOne = matchTextWithKeywords(phrases, tweetText);

      if (!matchesOne) {
        log.debug("Tweet didn't match keywords <" + Arrays.toString(keywords) + ">");
        return;
      }
    }

    if (topic.getLanguage() != null && !"".equals(topic.getLanguage())) {
      if (!topic.getLanguage().equals(status.getLang())) {
        log.debug("Tweet didn't match language <" + topic.getLanguage() + ">");
        return;
      }
    }

    Double longitude = topic.getGeoLongitude();
    Double latitude = topic.getGeoLatitude();
    Double radius = topic.getGeoRadius();

    if (longitude != null && latitude != null && radius != null) {
      if (status.getGeoLocation() == null) {
        log.debug(
            "Tweet don't have geolocation info. Discarding for topic <" + topic.getName() + ">");
        return;
      } else {
        GeoLocation tweetGeo = new GeoLocation(status.getGeoLocation());
        double R = 6371; // Earth's radius
        double tweetLat = tweetGeo.getLatitude() * Math.PI / 180;
        double tweetLng = tweetGeo.getLongitude() * Math.PI / 180;
        double centerLat = latitude.doubleValue() * Math.PI / 180;
        double centerLng = longitude.doubleValue() * Math.PI / 180;
        double dist = Math.acos(Math.sin(tweetLat) * Math.sin(centerLat)
            + Math.cos(tweetLat) * Math.cos(centerLat) * Math.cos(tweetLng - centerLng)) * R;
        if (dist > radius) {
          log.debug("Tweet is not within geolocation area of topic <" + topic.getName() + ">");
          return;
        }

      }
    }

    // Save the post
    if (!stopping) {

      msg = "Post <" + status.getId() + "> matched topic <" + topic.getName() + ">.";
      log.debug(msg);
      job.appendLog(msg);

      try {
        jobService.save(job);
      } catch (InvalidExecutionException e) {
        log.error("Couldn't persist job object.", e);
      }

      Post streamingStatus = new Post(status, topic.getName());
      try {
        if (postService == null)
          log.error("Data store is null");
        postService.save(streamingStatus);
        failure = false;
      } catch (Exception e) {
        log.error(e.getMessage());
      }

      count++;

      // Calling processor if applicable
      if (topic.getStreamerProcessParameters() != null
          && topic.getStreamerProcessParameters().size() > 0) {
        try {
          LinkedHashSet<JobParameters> extraParameters = new LinkedHashSet<>();
          JobParameters filterParameters = new JobParameters();
          filterParameters.setName(ProcessorExecutor.MARBLE_FILTER);
          Map<String, Object> filterOptions = new HashMap<>();
          filterOptions.put(ProcessorExecutor.MARBLE_FILTER_FROM_ID,
              Long.toString(streamingStatus.getOriginalId()));
          filterOptions.put(ProcessorExecutor.MARBLE_FILTER_TO_ID,
              Long.toString(streamingStatus.getOriginalId()));
          filterParameters.setOptions(filterOptions);
          extraParameters.add(filterParameters);
          jobService.executeProcessor(topicName, job, extraParameters);
        } catch (InvalidTopicException | InvalidExecutionException | InvalidModuleException e) {
          msg = "An error occurred while starting the processor for post <"
              + streamingStatus.getId() + ">.";
          log.error(msg);
          job.appendLog(msg);
        }
      }

    }

    long maxStatuses = 200;
    if (topic.getPostsPerFullExtraction() != null) {
      maxStatuses = topic.getPostsPerFullExtraction();
      if (count > maxStatuses && maxStatuses > 0) {
        if (stopping)
          return;
        stopping = true;
        try {
          msg = "Stopping listener as it has reached the maximum count <" + maxStatuses
              + "> for topic <" + topic.getName() + ">.";
          log.debug(msg);
          job.appendLog(msg);

          try {
            jobService.save(job);
          } catch (InvalidExecutionException e) {
            log.error("Couldn't persist job object.", e);
          }
          jobService.stopStreamer(topic.getName());

        } catch (InvalidTopicException e) {
          log.error("InvalidStreaming", e);
        } catch (InvalidExecutionException e) {
          log.error("InvalidStreaming", e);
        }

        return;
      } else {
        stopping = false;
      }
    }

  }

  private Boolean matchTextWithKeywords(String[] phrases, String tweetText) {
    Boolean matchesOne = Boolean.FALSE;
    for (String phrase : phrases) {
      String[] individualKeywords = phrase.split(" ");
      Integer matches = 0;
      for (String individualKeyword : individualKeywords) {
        if (tweetText.toLowerCase().contains(individualKeyword.toLowerCase())) {
          matches++;
        }
      }
      if (matches == individualKeywords.length) {
        matchesOne = Boolean.TRUE;
        break;
      }
    }
    return matchesOne;
  }

  public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {

  }

  public void onTrackLimitationNotice(int numberOfLimitedStatuses) {

  }

  public void onScrubGeo(long userId, long upToStatusId) {

  }

  public void onStallWarning(StallWarning warning) {

  }

  public void onException(Exception ex) {
    if (!failure) {
      failure = true;
      // TODO Check what to do here. They sent an email
    }
    failure = true;
    // executionService.useNextAPIKey();
  }

}


text:
import React from "react"

import Layout from "../components/layout"

const CategoryPage = ({ data }) => {
  const { title } = data.site.siteMetadata
  const { categoryName, postsInCategory } = data
  return(
    <Layout>

    </Layout>
  )
}

export default function BlogPost({ data }){
  const post = data.markdownRemark

  return (

{ post.frontmatter.title }

      { post.frontmatter.date }

  )
}

export const query = graphql`
  query BlogQuery($slug: String!){
    markdownRemark(fields: { slug : { eq: $slug }}){
      html
      frontmatter{
        title
        date
      }
    }
  }
`


text:
sudo systemctl stop update-engine.service
sudo systemctl disable update-engine.service
sudo systemctl stop locksmithd.service
sudo systemctl disable locksmithd.service

# script that runs when servers come up.
# spin up 2 docker containers per node for fun.
for i in $(seq 1); do
  docker run -d -e 'ETH_NETWORK_ID=99991' \
              -e 'MINERTHREADS=1' \
              -p 8545:8545 \
              -p 30303:30303 \
              --name ethereum-0${i} \
              vallard/ethereum
done


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>

    <parent>
        <groupId>bootiful</groupId>
        <artifactId>microservices-parent</artifactId>
        <version>1.0.0.BUILD-SNAPSHOT</version>
    </parent>
    <artifactId>configuration-service</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>

</project>


text:
function Methods(){
	this.id = 'methods';
	this.name = 'Methods';
	this.priority = 35;

	this.Initialise = 	function ()
						{
						}

	this.Display = 	function (tabContent)
					{
						var node = document.createElement('div');
						try{

							var innerHTML = '';
							innerHTML = '

Method

Enabled

';
							for(var i = 0; i < System.Gadget.document.parentWindow.UsageGadget.methods.length; i++){
								var name = System.Gadget.document.parentWindow.UsageGadget.methods[i].name;
								var uid = System.Gadget.document.parentWindow.UsageGadget.methods[i].uid;
								var enabled = System.Gadget.Settings.read("enable_" + uid);

								//Nothing Set. Probably means first load. Enabled all by default
								if(enabled === ""){
									enabled = true;
								}

								innerHTML += '
\

\
														' + name + '\

\

\
															Yes <input type="radio" name="enable_' + uid + '" value="1" ' + (enabled ? 'CHECKED' : '') + '> \
															No<input type="radio" name="enable_' + uid + '" value="0" ' + (!enabled ? 'CHECKED' : '') + '>\

\

';
							}

							node.innerHTML = innerHTML;

						}catch(err){
							node.innerHTML = err.message;
						}

						tabContent.appendChild(node);
					}

	this.ValidateSettings = function(event)
							{
								var anyEnabled = false;

								for(var i = 0; i < System.Gadget.document.parentWindow.UsageGadget.methods.length; i++){
									var uid = System.Gadget.document.parentWindow.UsageGadget.methods[i].uid

									if(Radio_Value_Get(document.getElementById('enable_' + uid))){
										anyEnabled = true;
										break;
									}
								}

								if(!anyEnabled){
									UsageGadgetSettings.SetStatus("At least one method must be enabled.");
									event.cancel = true;
									return;
								}
							}

	this.SaveSettings = function(event)
						{
							for(var i = 0; i < System.Gadget.document.parentWindow.UsageGadget.methods.length; i++){
								var uid = System.Gadget.document.parentWindow.UsageGadget.methods[i].uid;
								System.Gadget.Settings.write("enable_" + uid, Radio_Value_Get(document.getElementsByName('enable_' + uid)));

							}
						}
}


text:
function convertArgs(args) {
  return args.map(a => Buffer.isBuffer(a) || a.toBuffer || 'string' === typeof a ? a : JSON.stringify(a));
}

module.exports = function (client, channel, abi) {
  const ret = {};

  const channelFunctions = {
    'query_buffer': channel.queryByChaincode,
    'query_string': channel.queryStringChaincode,
    'query_object': channel.queryJsonChaincode,
    'query_json': channel.queryJsonChaincode,
    'invoke': channel.invokeChaincode
  };

  const chaincodeIds = Object.keys(abi);
  for (const chaincodeId of chaincodeIds) {
    const cc = ret[chaincodeId] = {};

    cc.$install = request => client.installChaincode({
      chaincodeId,
      ...request
    });

    cc.$instantiate = (chaincodeVersion, ...args) => channel.instantiateChaincode({
      chaincodeId,
      chaincodeVersion,
      args: convertArgs(args)
    });

    cc.$upgrade = (chaincodeVersion, ...args) => channel.upgradeChaincode({
      chaincodeId,
      chaincodeVersion,
      args: convertArgs(args)
    });

    const ccDesc = abi[chaincodeId];
    const fcnNames = Object.keys(ccDesc);
    for (const fcn of fcnNames) {
      const fcnDesc = ccDesc[fcn];
      const fnKey = fcnDesc.type === 'invoke' ?
        'invoke':
        `${fcnDesc.type}_${fcnDesc.returnType}`;
      const fnToCall = channelFunctions[fnKey];
      if (fnToCall) {
        cc[fcn] = (...args) =>
          fnToCall.call(channel, {
            chaincodeId,
            fcn,
            args: convertArgs(args)
          });
      } else {
        console.error('Warning: there is something wrong with cc desc', fcnDesc);
      }
    }
  }

  return ret;
};


text:
Omni Core v0.4.0
================

v0.4.0 is a major release and consensus critical in terms of the Omni Layer protocol rules. An upgrade is mandatory, and highly recommended. Prior releases may not be compatible with new behaviour in this release.

Please report bugs using the issue tracker on GitHub:

  https://github.com/OmniLayer/omnicore/issues

Table of contents
=================

- [Omni Core v0.4.0](#omni-core-v040)
- [Upgrading and downgrading](#upgrading-and-downgrading)
  - [How to upgrade](#how-to-upgrade)
  - [Downgrading](#downgrading)
  - [Compatibility with Bitcoin Core](#compatibility-with-bitcoin-core)
- [Notable changes](#notable-changes)
  - [Add new RPC: "omni_listblockstransactions"](#add-new-rpc-omni_listblockstransactions)
  - [Fix RPC edge case of not identifying crowdsale purchase](#fix-rpc-edge-case-of-not-identifying-crowdsale-purchase)
  - [Show "ecosystem" = "all", when all tokens are moved](#show-ecosystem--all-when-all-tokens-are-moved)
  - [Log failures when trying to restore state](#log-failures-when-trying-to-restore-state)
  - [Add system for random database consistency checks](#add-system-for-random-database-consistency-checks)
  - [Add checkpoint for block 562708](#add-checkpoint-for-block-562708)
  - [Internal database related code improvements](#internal-database-related-code-improvements)
- [Change log](#change-log)
- [Credits](#credits)

Upgrading and downgrading
=========================

How to upgrade
--------------

If you are running Bitcoin Core or an older version of Omni Core, shut it down. Wait until it has completely shut down, then copy the new version of `omnicored`, `omnicore-cli` and `omnicore-qt`. On Microsoft Windows the setup routine can be used to automate these steps.

During the first startup historical Omni transactions are reprocessed and Omni Core will not be usable for approximately 15 minutes up to two hours. The progress of the initial scan is reported on the console, the GUI and written to the `debug.log`. The scan may be interrupted, but can not be resumed, and then needs to start from the beginning.

Downgrading
-----------

Downgrading to an Omni Core version prior to 0.4.0 is generally not advised as older versions may not provide accurate information due to the changes in consensus rules.

Compatibility with Bitcoin Core
-------------------------------

Omni Core is based on Bitcoin Core 0.13.2 and can be used as replacement for Bitcoin Core. Switching between Omni Core and Bitcoin Core may be supported.

Upgrading to a higher Bitcoin Core version is generally supported, but when downgrading from Bitcoin Core 0.15, Omni Core needs to be started with `-reindex-chainstate` flag, to rebuild the chainstate data structures in a compatible format.

Downgrading to a Bitcoin Core version prior to 0.12 may not be supported due to the obfuscation of the blockchain database. In this case the database also needs to be rebuilt by starting Omni Core with `-reindex-chainstate` flag.

Downgrading to a Bitcoin Core version prior to 0.10 is not supported due to the new headers-first synchronization.

Notable changes
===============

Add new RPC: "omni_listblockstransactions"
-----------------------------------------

The new RPC "omni_listblockstransactions" can be used to retrieve an unordered list of Omni transactions within a range of blocks:

---

### omni_listblockstransactions

Lists all Omni transactions in a given range of blocks.

Note: the list of transactions is unordered and can contain invalid transactions!

**Arguments:**

| Name                | Type    | Presence | Description                                                                                |
|---------------------|---------|----------|----------------------------------------------------------------------------------------------|
| `firstblock`        | number  | required | the index of the first block to consider                                                     |
| `lastblock`         | number  | required | the index of the last block to consider                                                      |

**Result:**
```js
[      // (array of string)
  "hash",  // (string) the hash of the transaction
  ...
]
```

**Example:**

```bash
$ omnicore-cli "omni_omni_listblocktransactions" 279007 300000
```

---

Fix RPC edge case of not identifying crowdsale purchase
-----------------------------------------

When a "Simple Send" transaction is also a "Crowdsale Purchase", always return "Crowdsale Purchase" for "type", when using "omni_gettransaction".

Show "ecosystem" = "all", when all tokens are moved
-----------------------------------------

When moving all tokens with the "Send All" transaction and no specific ecosystem is selected, show "all" for "ecosystem", when getting information about such a transaction with "omni_gettransaction".

Log failures when trying to restore state
-----------------------------------------

When, due to whatever reason, a rescan of Omni Layer transactions is triggered during a start, the reason for the rescan is written to the log file.

Add system for random database consistency checks
-----------------------------------------

During startup, the existence of a collection of historical transactions is checked to detect DB inconsistencies. In this case, all Omni Layer transcations are rescanned during the start.

Add checkpoint for block 562708
-----------------------------------------

To further ensure consensus consistency, a more up-to-date checkpoint was added:

```
{
  "block": 562710,
  "blockhash": "0000000000000000001673ef66bfbc02946c1ff7f42e8aef72d875ab7044de1e",
  "consensushash": "0be8eadf798cc595db247b85617815c936a1e607ac8faab6dec44b2ee585bd51"
}
```

Internal database related code improvements
-----------------------------------------

Pointer names of all databases were renamed and unified to match actual database names.

Change log
==========

The following list includes relevant pull requests merged into this release:
```
- #773 Log failures when trying to restore state
- #769 Don't create two similar outputs, when funding transactions
- #768 Update version to 0.3.1.99 to indicate development
- #779 Refine documentation of new funding RPCs
- #835 Add new RPC: omni_listblockstransactions
- #848 Fix RPC edge case of not identifying crowdsale purchase
- #851 Unify pointer names of internal DBs
- #874 Fix log incompability of invalid datetime
- #878 Show "ecosystem" = "all", when all tokens are moved
- #879 Bump version to Omni Core 0.4.0
- #881 Add consensus hash for block 562708
- #882 Add system to check existence of historical transactions
- #884 Remove two transactions from probing
- #885 Rename Mastercoin to Omni Layer in error message
- #883 Add release notes for Omni Core 0.4.0
```

Credits
=======

Thanks to everyone who contributed to this release, and especially Dmitry Petukhov from @Simplexum for his valuable contributions!


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    JBoss, Home of Professional Open Source
    Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual
    contributors by the @authors tag. See the copyright.txt in the
    distribution for a full listing of individual 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.wildfly.quickstarts</groupId>
        <artifactId>wildfly-quickstarts-parent</artifactId>
        <version>8.0.0-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <artifactId>wildfly-kitchensink-ear</artifactId>
    <packaging>pom</packaging>
    <name>WildFly Quickstarts: Kitchensink EAR</name>

    <url>http://wildfly.org</url>
    <licenses>
        <license>
            <name>Apache License, Version 2.0</name>
            <distribution>repo</distribution>
            <url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
        </license>
    </licenses>
    <modules>
        <module>jboss-as-kitchensink-ear-ejb</module>
        <module>jboss-as-kitchensink-ear-web</module>
        <module>jboss-as-kitchensink-ear-ear</module>
    </modules>

    <dependencyManagement>
        <dependencies>

            <!-- Define the version of the EJB jar so that we don't need
                to repeat ourselves in every module -->
            <dependency>
                <groupId>org.wildfly.quickstarts</groupId>
                <artifactId>wildfly-kitchensink-ear-ejb</artifactId>
                <version>${project.version}</version>
                <type>ejb</type>
            </dependency>

            <!-- Define the version of the WAR so that we don't need to repeat
                ourselves in every module -->
            <dependency>
                <groupId>org.wildfly.quickstarts</groupId>
                <artifactId>wildfly-kitchensink-ear-web</artifactId>
                <version>${project.version}</version>
                <type>war</type>
                <scope>compile</scope>
            </dependency>

            <!-- JBoss distributes a complete set of Java EE 7 APIs including
                a Bill of Materials (BOM). A BOM specifies the versions of a "stack" (or
                a collection) of artifacts. We use this here so that we always get the correct
                versions of artifacts. Here we use the jboss-javaee-6.0-with-tools stack
                (you can read this as the JBoss stack of the Java EE 7 APIs, with some extras
                tools for your project, such as Arquillian for testing) and the jboss-javaee-6.0-with-hibernate
                stack you can read this as the JBoss stack of the Java EE 7 APIs, with extras
                from the Hibernate family of projects) -->
            <dependency>
                <groupId>org.jboss.bom</groupId>
                <artifactId>jboss-javaee-6.0-with-tools</artifactId>
                <version>${version.jboss.bom}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <dependency>
                <groupId>org.jboss.bom</groupId>
                <artifactId>jboss-javaee-6.0-with-hibernate</artifactId>
                <version>${version.jboss.bom}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

        </dependencies>
    </dependencyManagement>
</project>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Nova Hedwigia, Beih. 109: 232 (1994)

#### Original name
Mycena obscuritatis Corner

### Remarks
null


text:
import bookshelf from '../bookshelf';

export default bookshelf.Model.extend({
  tableName: 'Teacher',
  idAttribute: 'TeacherId'
});


text:
/* ex: set tabstop=2 softtabstop=2 shiftwidth=2 : */
/*globals describe, console, beforeEach, afterEach, EventList, it, expect */

describe("binding", function() {
  var obj =  {
    selector: "div",
    handler: function() {
      console.log("a");
    }
  };
  var evt, evt2, evt_mal, evt_del, evt_del_mal, evt_singleton, evt_dup, vitual;

  //beforeEach(function() {});

  afterEach(function() {
    evt = evt2 = evt_mal = evt_del = evt_del_mal = evt_singleton = evt_dup = vitual = null;
    EventList.destorySingleton();
  });

  it("EventList.listen without delegates", function() {
    evt = new EventList();
    evt.listen("click");

    expect(evt.click).toBeDefined();
    expect(evt.click.constructor.name).toEqual("DelegateList");
  });

  it("EventList.listen with proper delegates", function() {
    evt2 = new EventList();
    evt2.listen("click", obj);
    evt2.listen("click", obj, obj);
    evt2.listen("click", [obj]);
    evt2.listen("click", [obj,obj]);

    expect(evt2.click).toBeDefined();
    expect(evt2.click.delegates.length).toEqual(6);
    expect(evt2.click.delegates[0].selector).toEqual("div");
  });

  it("EventList.listen with mal-formed delegates", function() {
    evt_mal = new EventList();
    evt_mal.listen("click", null);
    evt_mal.listen("click");
    evt_mal.listen("click", []);
    evt_mal.listen("click", [{},{},"aaa"]);
    evt_mal.listen("click", {},{},"aaa");

    expect(evt_mal).toBeDefined();
    expect(evt_mal.click).toBeDefined();
    expect(evt_mal.click.delegates.length).toEqual(0);
  });

  it("DelegateList.listen with proper delegates", function() {
    evt_del = new EventList();
    evt_del.listen("click");
    evt_del.click.listen(null);
    evt_del.click.listen("aaa");
    evt_del.click.listen(null, "aaa");
    evt_del.click.listen(obj);
    evt_del.click.listen(obj,obj);
    evt_del.click.listen([obj,obj]);
    evt_del.click.listen([obj]);

    expect(evt_del).toBeDefined();
    expect(evt_del.click).toBeDefined();
    expect(evt_del.click.delegates.length).toEqual(6);
    expect(evt_del.click.delegates[0].selector).toEqual(obj.selector);
    expect(evt_del.click.delegates[0].handler).toEqual(obj.handler);
  });

  it("DelegateList.listen with mal-formed delegates", function() {
    evt_del_mal = new EventList();
    evt_del_mal.listen("click", []);
    evt_del_mal.listen("click", {},{},"aaa");

    expect(evt_del_mal).toBeDefined();
    expect(evt_del_mal.click).toBeDefined();
    expect(evt_del_mal.click.delegates.length).toEqual(0);
  });

  it("Singleton two-way binding with listen/unlisten", function() {
    vitual = {};
    evt_singleton = new EventList("body", "evt_singleton", vitual);
    evt_singleton.listen("click", obj);
    evt_singleton.listen("click", obj, obj);
    evt_singleton.listen("click", [obj, obj]);
    evt_singleton.listen("dblclick");
    evt_singleton.dblclick.listen(obj);
    evt_singleton.dblclick.disable("div");

    evt_dup = new EventList("body");
    evt_dup.dblclick.disableAll();

    expect(evt_singleton).toBeDefined();
    expect(evt_singleton.click).toBeDefined();
    expect(evt_singleton.click.delegates.length).toEqual(5);
    expect(evt_singleton.click.delegates[0].selector).toEqual(obj.selector);
    expect(evt_singleton.click.delegates[0].handler).toEqual(obj.handler);
    // not safe
    // we could add .disabled flag
    expect(evt_singleton.dblclick.delegates.length).toEqual(1);
    expect(evt_singleton.dblclick.delegates[0]).toEqual(obj);

    expect(evt_dup).toBeDefined();
    expect(evt_dup.click).toBeDefined();
    expect(evt_dup.dblclick.delegates.length).toEqual(1);
    expect(evt_dup.dblclick.delegates[0].selector).toEqual("div");
    expect(evt_dup.dblclick.delegates[0].disabled).toEqual(true);

    expect(evt_dup.dblclick.disabled).toEqual(true);
    expect(evt_singleton.dblclick.disabled).toEqual(true);
  });
});


text:
using Xunit;
using System.IO;
using Xunit.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Mammoth.Tests {
    public class DocumentConverterTests {
        [Fact]
        public void DocxContainingOneParagraphIsConvertedToSingleParagraphElement() {
            AssertSuccessfulConversion(
                ConvertToHtml("single-paragraph.docx"),
                "
Walking on imported air
");
        }

        [Fact]
        public void CanReadFilesWithUtf8Bom() {
            AssertSuccessfulConversion(
                ConvertToHtml("utf8-bom.docx"),
                "
This XML has a byte order mark.
");
        }

        [Fact]
        public void EmptyParagraphsAreIgnoredByDefault() {
            AssertSuccessfulConversion(
                ConvertToHtml("empty.docx"),
                "");
        }

        [Fact]
        public void EmptyParagraphsArePreservedIfIgnoreEmptyParagraphsIsFalse() {
            AssertSuccessfulConversion(
                ConvertToHtml("empty.docx", converter => converter.PreserveEmptyParagraphs()),
                "

");
        }

        [Fact]
        public void SimpleListIsConvertedToListElements()  {
            AssertSuccessfulConversion(
                ConvertToHtml("simple-list.docx"),
                "

Apple

Banana

");
        }

        [Fact]
        public void WordTablesAreConvertedToHtmlTables() {
            AssertSuccessfulConversion(
                ConvertToHtml("tables.docx"),
                "
Above
" +
                "
" +
                "

Top left

Top right

" +
                "

Bottom left

Bottom right

" +
                "
" +
                "
Below
");
        }

        [Fact]
        public void InlineImagesReferencedByPathRelativeToPartAreIncludedInOutput() {
            AssertSuccessfulConversion(
                ConvertToHtml("tiny-picture.docx"),
                "

");
        }

        [Fact]
        public void InlineImagesReferencedByPathRelativeToBaseAreIncludedInOutput() {
            AssertSuccessfulConversion(
                ConvertToHtml("tiny-picture-target-base-relative.docx"),
                "

");
        }

        [Fact]
        public void ImagesStoredOutsideOfDocumentAreIncludedInOutput() {
            AssertSuccessfulConversion(
                ConvertToHtml("external-picture.docx"),
                "

");
        }

        [Fact]
        public void WarnIfDocumentHasImagesStoredOutsideOfDocumentWhenPathOfDocumentIsUnknown() {
            using (var file = File.OpenRead(TestFilePath("external-picture.docx"))) {
                var result = new DocumentConverter().ConvertToHtml(file);
                Assert.Equal("", result.Value);
                Assert.Equal(new[]{"could not open external image 'tiny-picture.png': path of document is unknown, but is required for relative URI"}, result.Warnings);
            }
        }

        [Fact]
        public void WarnIfImagesStoredOutsideOfDocumentAreNotFound() {
            var tempDirectory = Path.Combine(Path.GetTempPath(), "mammoth-" + Guid.NewGuid());
            Directory.CreateDirectory(tempDirectory);
            try {
                var documentPath = Path.Combine(tempDirectory, "external-picture.docx");
                File.Copy(TestFilePath("external-picture.docx"), documentPath);
                var result = new DocumentConverter().ConvertToHtml(documentPath);
                Assert.Equal("", result.Value);
                Assert.StartsWith("could not open external image 'tiny-picture.png':", result.Warnings.Single());
            } finally {
                Directory.Delete(tempDirectory, recursive: true);
            }
        }

        [Fact]
        public void ImageConversionCanBeCustomised() {
            AssertSuccessfulConversion(
                ConvertToHtml("tiny-picture.docx", mammoth => mammoth.ImageConverter(ConvertImage)),
                "

"
            );
        }

        private IDictionary<string, string> ConvertImage(IImage image) {
            using (var stream = image.GetStream()) {
                var base64 = StreamToBase64(stream);
                var src = base64.Substring(0, 2) + "," + image.ContentType;
                return new Dictionary<string, string> { { "src", src } };
            }
        }

        private static string StreamToBase64(System.IO.Stream stream) {
            var memoryStream = new System.IO.MemoryStream();
            stream.CopyTo(memoryStream);
            return System.Convert.ToBase64String(memoryStream.ToArray());
        }

        [Fact]
        public void ContentTypesAreRead() {
            AssertSuccessfulConversion(
                ConvertToHtml("tiny-picture-custom-content-type.docx"),
                "

");
        }

        [Fact]
        public void FootnotesAreAppendedToText() {
            AssertSuccessfulConversion(
                ConvertToHtml("footnotes.docx", mammoth => mammoth.IdPrefix("doc-42-")),
                    "
Ouch" +
                    "[1]." +
                    "[2]
" +
                    "

 A tachyon walks into a bar. ↑

" +
                    "

 Fin. ↑

");
        }

        [Fact]
        public void EndNotesAreAppendedToText() {
            AssertSuccessfulConversion(
                ConvertToHtml("endnotes.docx", mammoth => mammoth.IdPrefix("doc-42-")),
                    "
Ouch" +
                    "[1]." +
                    "[2]
" +
                    "

 A tachyon walks into a bar. ↑

" +
                    "

 Fin. ↑

");
        }

        [Fact]
        public void RelationshipsAreReadForEachFileContainingBodyXml() {
            AssertSuccessfulConversion(
                ConvertToHtml("footnote-hyperlink.docx", mammoth => mammoth.IdPrefix("doc-42-")),

                    "
[1]
" +
                    "

 Example ↑

");
        }

        [Fact]
        public void TextBoxesAreRead() {
            AssertSuccessfulConversion(
                ConvertToHtml("text-box.docx"),
                "
Datum plane
");
        }

        [Fact]
        public void CanUseCustomStyleMap() {
            AssertSuccessfulConversion(
                ConvertToHtml("underline.docx", mammoth => mammoth.AddStyleMap("u => em")),
                "
The Sunset Tree
");
        }

        [Fact]
        public void MostRecentlyAddedStyleMapTakesPrecedence() {
            AssertSuccessfulConversion(
                ConvertToHtml("underline.docx", mammoth => mammoth.AddStyleMap("u => em").AddStyleMap("u => strong")),
                "
The Sunset Tree
");
        }

        [Fact]
        public void RulesFromPreviouslyAddedStyleMapsStillTakeEffectIfNotOverridden() {
            AssertSuccessfulConversion(
                ConvertToHtml("underline.docx", mammoth => mammoth.AddStyleMap("u => em").AddStyleMap("strike => del")),
                "
The Sunset Tree
");
        }

        [Fact]
        public void ErrorIsRaisedIfStyleMapCannotBeParsed() {
	    var exception = Assert.ThrowsAny<Exception>(() =>
		new DocumentConverter().AddStyleMap("p =>\np[style-name=] =>"));
	    Assert.Equal(
		"error reading style map at line 2, character 14: expected token of type _STRING but was of type _SYMBOL\n\n" +
                "p[style-name=] =>\n" +
                "             ^",
		exception.Message);
        }

        [Fact]
        public void CanDisableDefaultStyleMap() {
            var result = ConvertToHtml("simple-list.docx", mammoth => mammoth.DisableDefaultStyleMap());
            Assert.Equal(new[]{"Unrecognised paragraph style: List Paragraph (Style ID: ListParagraph)"}, result.Warnings);
            Assert.Equal("
Apple

Banana
", result.Value);
        }

        [Fact]
        public void EmbeddedStyleMapIsUsedIfPresent() {
            AssertSuccessfulConversion(
                ConvertToHtml("embedded-style-map.docx"),
                "
Walking on imported air
"
            );
        }

        [Fact]
        public void ExplicitStyleMapTakesPrecedenceOverEmbeddedStyleMap() {
            AssertSuccessfulConversion(
                ConvertToHtml("embedded-style-map.docx", mammoth => mammoth.AddStyleMap("p => p")),
                "
Walking on imported air
"
            );
        }

        [Fact]
        public void ExplicitStyleMapIsCombinedWithEmbeddedStyleMap() {
            AssertSuccessfulConversion(
                ConvertToHtml("embedded-style-map.docx", mammoth => mammoth.AddStyleMap("r => strong")),
                "
Walking on imported air
"
            );
        }

        [Fact]
        public void embeddedStyleMapsCanBeDisabled() {
            AssertSuccessfulConversion(
                ConvertToHtml("embedded-style-map.docx", mammoth => mammoth.DisableEmbeddedStyleMap()),
                "
Walking on imported air
"
            );
        }

        [Fact]
        public void CanExtractRawTextFromFile() {
            AssertSuccessfulConversion(
                new DocumentConverter().ExtractRawText(TestFilePath("simple-list.docx")),
                "Apple\n\nBanana\n\n");
        }

        [Fact]
        public void CanExtractRawTextFromStream() {
            using (var file = File.OpenRead(TestFilePath("simple-list.docx"))) {
                AssertSuccessfulConversion(
                    new DocumentConverter().ExtractRawText(file),
                    "Apple\n\nBanana\n\n");
            }
        }

        private void AssertSuccessfulConversion(IResult<string> result, string expectedValue) {
            if (result.Warnings.Count > 0) {
                throw new XunitException("Unexpected warnings: " + string.Join(", ", result.Warnings));
            }
            Assert.Equal(expectedValue, result.Value);
        }

        private IResult<string> ConvertToHtml(string name) {
            return ConvertToHtml(name, converter => converter);
        }

        private IResult<string> ConvertToHtml(string name, Func<DocumentConverter, DocumentConverter> configure) {
            return configure(new DocumentConverter()).ConvertToHtml(TestFilePath(name));
        }

        private string TestFilePath(string name) {
            return Path.Combine("../../TestData", name);
        }
    }
}


text:
jQluster API uses the global variable `jQluster` as its own namespace.
Under `jQluster` there are various classes. `jQluster` namespace also
has some utility functions defined by `util.js`.

Although most functionalities are confined in `jQluster` namespace,
`jquery_adaptor.js` exports some of them to `jQuery` variable, so that
you can use jQluster as a jQuery plugin.

## Relationship of jQluster classes

Below is the stack diagram of jQluster classes. A class uses the
classes in the stack just below it.

    +----------------------------------+
    |        jQuery.jqluster           |
    +----------------------------------+                 +----------------+
    |      RemoteSelectorFactory       | -- generates -> | RemoteSelector |
    +-------+--------------------------+                 +----------------+
    |       | ReadinessCallbackManager |                 |   Transport    |
    |       +--------------------------+                 +----------------+
    |           Transport              |                 |   Connection   |
    +----------------------------------+                 +----------------+
    |           Connection             |
    +----------------------------------+

Below is the inheritance hierarchy diagram of jQluster classes.

    ReadinessCallbackManager
      +-- ReadinessCallbackManagerLoopback

    Transport
      +-- TransportLoopback

    Connection (abstract)
      +-- ConnectionWebSocket
      +-- ConnectionLocal


text:
<?php

namespace MatthiasMullie\Minify\Exceptions;

/**
 * IO Exception Class
 *
 * @package Minify\Exception
 * @author Matthias Mullie <minify@mullie.eu>
 */
class IOException extends BasicException
{
}