text:
module Api
  ApiError = Class.new(StandardError)
  AuthenticationError = Class.new(ApiError)
  ForbiddenError = Class.new(ApiError)
  BadRequestError = Class.new(ApiError)
  NotFoundError = Class.new(ApiError)
  UnsupportedMediaTypeError = Class.new(ApiError)

  def self.encrypted_attribute?(attr)
    Environment.normalized_attributes[:encrypted].key?(attr.to_s) || attr.to_s.include?('password')
  end
end


text:
package com.madgnome.jira.plugins.jirachievements.data.services.impl;

import com.atlassian.activeobjects.external.ActiveObjects;
import com.atlassian.activeobjects.test.TestActiveObjects;
import com.madgnome.jira.plugins.jirachievements.data.DatabaseProcessor;
import net.java.ao.EntityManager;
import net.java.ao.test.jdbc.Data;
import net.java.ao.test.jdbc.DynamicJdbcConfiguration;
import net.java.ao.test.jdbc.Jdbc;
import net.java.ao.test.junit.ActiveObjectsJUnitRunner;
import org.junit.runner.RunWith;

@RunWith(ActiveObjectsJUnitRunner.class)
@Jdbc(DynamicJdbcConfiguration.class)
@Data(DatabaseProcessor.class)
public abstract class AbstractServiceTest
{
  protected EntityManager entityManager;

  protected ActiveObjects createActiveObjects()
  {
    return new TestActiveObjects(entityManager);
  }
}

redpajama_set_name: RedPajamaGithub


text:
layout: post
title: Field Season 2014 Round 2 Complete
tags:
- MORails
comments: true
---

Somehow the 2014 field season is already half over, and once again the weather and the birds are throwing a totally different suite of challenges our way.

2012 was a drought year, 2013 migration was delayed. 2014 is the year of rain, and lots of it. We've now had flooding on five of my ten study sites either during my field season or just before. The past two years we've had one night where weather kept us from surveying, this year we've had five already.

But that is the joy of field work, and the reason that you study ecological processes like migration over many years because there is so much variation, so many different pieces to the puzzle.

We saw our first two Virginia Rails this past round, with many more to come *fingers crossed*. No Yellow Rails yet, but it's still early.

One very exciting moment was when we released one of the Sora we banded we took some video of him and he dove underwater, a behavior that many people don't seem to believe when I tell them about it. The internet here isn't good enough to upload the video, but here's a picture of him after he came back up with just his head poking out of the water.

With all the flooding there has been lots of trash out in the wetlands, but these balloons aren't flood trash, someone released them. Releasing balloons is littering, and can cause big issues for wildlife, please don't release them.

Every individual bird has it's own personality, and Sora are no exception, especially these guy. He was spunky and full of energy.

This fall has brought us many beautiful clouds, including these two beautiful shots

So we're half way done, we've visited each of these sites twice, and we're headed out to do two more visits before October 22. Peak Migration should be in the next two weeks, we're excited to see what the season throws our way.

Season by the Numbers

Trips to the ATV repair place – 5

ATVs borrowed while others are being fixed – 4

Surveys completed = 155

Sora observed = 608

Virginia Rail observed = 2


text:
var Class = require('../../utils/Class');
var Components = require('../components');
var GameObject = require('../GameObject');
var SpriteRender = require('./SpriteRender');

/**
 * @classdesc
 * A Sprite Game Object.
 *
 * A Sprite Game Object is used for the display of both static and animated images in your game.
 * Sprites can have input events and physics bodies. They can also be tweened, tinted, scrolled
 * and animated.
 *
 * The main difference between a Sprite and an Image Game Object is that you cannot animate Images.
 * As such, Sprites take a fraction longer to process and have a larger API footprint due to the Animation
 * Component. If you do not require animation then you can safely use Images to replace Sprites in all cases.
 *
 * @class Sprite
 * @extends Phaser.GameObjects.GameObject
 * @memberof Phaser.GameObjects
 * @constructor
 * @since 3.0.0
 *
 * @extends Phaser.GameObjects.Components.Alpha
 * @extends Phaser.GameObjects.Components.BlendMode
 * @extends Phaser.GameObjects.Components.Depth
 * @extends Phaser.GameObjects.Components.Flip
 * @extends Phaser.GameObjects.Components.GetBounds
 * @extends Phaser.GameObjects.Components.Mask
 * @extends Phaser.GameObjects.Components.Origin
 * @extends Phaser.GameObjects.Components.Pipeline
 * @extends Phaser.GameObjects.Components.ScrollFactor
 * @extends Phaser.GameObjects.Components.Size
 * @extends Phaser.GameObjects.Components.TextureCrop
 * @extends Phaser.GameObjects.Components.Tint
 * @extends Phaser.GameObjects.Components.Transform
 * @extends Phaser.GameObjects.Components.Visible
 *
 * @param {Phaser.Scene} scene - The Scene to which this Game Object belongs. A Game Object can only belong to one Scene at a time.
 * @param {number} x - The horizontal position of this Game Object in the world.
 * @param {number} y - The vertical position of this Game Object in the world.
 * @param {string} texture - The key of the Texture this Game Object will use to render with, as stored in the Texture Manager.
 * @param {(string|integer)} [frame] - An optional frame from the Texture this Game Object is rendering with.
 */
var Sprite = new Class({

    Extends: GameObject,

    Mixins: [
        Components.Alpha,
        Components.BlendMode,
        Components.Depth,
        Components.Flip,
        Components.GetBounds,
        Components.Mask,
        Components.Origin,
        Components.Pipeline,
        Components.ScrollFactor,
        Components.Size,
        Components.TextureCrop,
        Components.Tint,
        Components.Transform,
        Components.Visible,
        SpriteRender
    ],

    initialize:

    function Sprite (scene, x, y, texture, frame)
    {
        GameObject.call(this, scene, 'Sprite');

        /**
         * The internal crop data object, as used by `setCrop` and passed to the `Frame.setCropUVs` method.
         *
         * @name Phaser.GameObjects.Sprite#_crop
         * @type {object}
         * @private
         * @since 3.11.0
         */
        this._crop = this.resetCropObject();

        /**
         * The Animation Controller of this Sprite.
         *
         * @name Phaser.GameObjects.Sprite#anims
         * @type {Phaser.GameObjects.Components.Animation}
         * @since 3.0.0
         */
        this.anims = new Components.Animation(this);

        this.setTexture(texture, frame);
        this.setPosition(x, y);
        this.setSizeToFrame();
        this.setOriginFromFrame();
        this.initPipeline();
    },

    /**
     * Update this Sprite's animations.
     *
     * @method Phaser.GameObjects.Sprite#preUpdate
     * @protected
     * @since 3.0.0
     *
     * @param {number} time - The current timestamp.
     * @param {number} delta - The delta time, in ms, elapsed since the last frame.
     */
    preUpdate: function (time, delta)
    {
        this.anims.update(time, delta);
    },

    /**
     * Start playing the given animation.
     *
     * @method Phaser.GameObjects.Sprite#play
     * @since 3.0.0
     *
     * @param {string} key - The string-based key of the animation to play.
     * @param {boolean} [ignoreIfPlaying=false] - If an animation is already playing then ignore this call.
     * @param {integer} [startFrame=0] - Optionally start the animation playing from this frame index.
     *
     * @return {Phaser.GameObjects.Sprite} This Game Object.
     */
    play: function (key, ignoreIfPlaying, startFrame)
    {
        this.anims.play(key, ignoreIfPlaying, startFrame);

        return this;
    },

    /**
     * Build a JSON representation of this Sprite.
     *
     * @method Phaser.GameObjects.Sprite#toJSON
     * @since 3.0.0
     *
     * @return {Phaser.Types.GameObjects.JSONGameObject} A JSON representation of the Game Object.
     */
    toJSON: function ()
    {
        var data = Components.ToJSON(this);

        //  Extra Sprite data is added here

        return data;
    },

    /**
     * Handles the pre-destroy step for the Sprite, which removes the Animation component.
     *
     * @method Phaser.GameObjects.Sprite#preDestroy
     * @private
     * @since 3.14.0
     */
    preDestroy: function ()
    {
        this.anims.destroy();

        this.anims = undefined;
    }

});

module.exports = Sprite;


text:
package com.tomtom.speedtools.rest;

import akka.actor.OneForOneStrategy;
import akka.actor.SupervisorStrategy;
import com.google.inject.Injector;
import com.tomtom.speedtools.guice.HasProperties;
import com.tomtom.speedtools.guice.InvalidPropertyValueException;
import com.tomtom.speedtools.utils.MathUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.Duration;
import scala.concurrent.duration.FiniteDuration;

import javax.annotation.Nonnull;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.concurrent.TimeUnit;

/**
 * Standard supervisor strategies.
 */
public class SupervisorStrategies implements HasProperties {
    private static final Logger LOG = LoggerFactory.getLogger(SupervisorStrategies.class);

    @Nonnull
    private final OneForOneStrategy restartChildStrategy;
    @Nonnull
    private final OneForOneStrategy stopChildStrategy;

    private static final int MAX_RETRIES = 100;
    private static final int MAX_WITHIN_TIME_RANGE_SECS = 60 * 60 * 24; // 1 day.

    /**
     * Akka supervisor properties.
     *
     * @param injector            Injector.
     * @param maxNrOfRetries      Maximum number a child can be restarted within restartChildWithinTimeRangeSecs before
     *                            it dies. Must be >= 0.
     * @param withinTimeRangeSecs If more than restartChildMaxNrOfRetries failures of a child occur within
     *                            restartChildWithinTimeRangeSecs, the child dies. Must be >= 1.
     */
    @Inject
    public SupervisorStrategies(
            @Nonnull final Injector injector,
            @Named("SupervisorStrategies.RestartChild.maxNrOfRetries") final int maxNrOfRetries,
            @Named("SupervisorStrategies.RestartChild.withinTimeRangeSecs") final int withinTimeRangeSecs)
            throws InvalidPropertyValueException {
        assert injector != null;

        if (!MathUtils.isBetween(maxNrOfRetries, 0, MAX_RETRIES)) {
            throw new InvalidPropertyValueException("RestartChildStragy.maxNrOfRetries should be in range [0, " +
                    MAX_RETRIES + "].");
        }

        if (!MathUtils.isBetween(withinTimeRangeSecs, 1, MAX_WITHIN_TIME_RANGE_SECS)) {
            throw new InvalidPropertyValueException("RestartChildStragy.withinTimeRangeSecs should be in range [1, " +
                    MAX_WITHIN_TIME_RANGE_SECS + "].");
        }

        this.restartChildStrategy = new OneForOneStrategy(
                maxNrOfRetries,
                FiniteDuration.create(withinTimeRangeSecs, TimeUnit.SECONDS), (Throwable param) -> {

            assert param != null;
            if (param instanceof Error) {
                LOG.error("apply (restartChildStrategy): Error occurred in actor", param);
            }
            LOG.warn("apply (restartChildStrategy): Actor restarted (maxNrOfRetries=" +
                    maxNrOfRetries + ", " +
                    "withinTimeRangeSecs=" +
                    withinTimeRangeSecs + ')', param);
            return SupervisorStrategy.restart();
        }
        );

        this.stopChildStrategy = new OneForOneStrategy(0, Duration.Inf(), (Throwable param) -> {
            assert param != null;
            if (param instanceof Error) {
                LOG.error("apply (stopChildStrategy): Error occurred in actor", param);
            }
            LOG.warn("apply (stopChildStrategy): Actor stopped", param);
            return SupervisorStrategy.stop();
        }
        );
    }

    @Nonnull
    public OneForOneStrategy getRestartChildStrategy() {
        return restartChildStrategy;
    }

    @Nonnull
    public OneForOneStrategy getStopChildStrategy() {
        return stopChildStrategy;
    }
}


text:
package org.apache.sling.testing.teleporter.client;

import java.util.Properties;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class DefaultPropertyBasedCustomizerTest {

    private DefaultPropertyBasedCustomizer customizer;
    @Mock
    private ClientSideTeleporter clientSideTeleporter;

    @Before
    public void setUp() {
        // remove all properties starting with "ClientSideTeleporter."
        // removing all properties without conditions would prevent other java code from being executed without errors, because some java code at least relies on "java.home" being set!
        Properties oldProperties = System.getProperties();
        Properties newProperties = new Properties();
        for (Object key : oldProperties.keySet()) {
            if (!((String)key).startsWith("ClientSideTeleporter.")) {
                newProperties.put(key, oldProperties.get(key));
            }
        }
        System.setProperties(newProperties);
    }

    @Test(expected=AssertionError.class)
    public void testBaseUrlNotSet() {
        customizer = new DefaultPropertyBasedCustomizer();
        customizer.customize(clientSideTeleporter, null);
    }

    @Test(expected=AssertionError.class)
    public void testEmptyBaseUrl() {
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_BASE_URL, "   ");
        customizer = new DefaultPropertyBasedCustomizer();
        customizer.customize(clientSideTeleporter, null);
    }

    @Test
    public void testSettingAllProperties() {
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_BASE_URL, "base-url");
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_INCLUDE_DEPENDENCY_PREFIXES, "include-dependency1,include-dependency2");
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_EXCLUDE_DEPENDENCY_PREFIXES, "exclude-dependency1,exclude-dependency2");
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_EMBED_CLASSES, "org.apache.sling.testing.teleporter.client.ClassResourceVisitor,org.apache.sling.testing.teleporter.client.ClientSideTeleporter");
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_TESTREADY_TIMEOUT_SECONDS, "50");
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_SERVER_USERNAME, "adminuser");
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_SERVER_PASSWORD, "adminpassword");
        customizer = new DefaultPropertyBasedCustomizer();
        customizer.customize(clientSideTeleporter, null);
        Mockito.verify(clientSideTeleporter).setBaseUrl("base-url");
        Mockito.verify(clientSideTeleporter).includeDependencyPrefix("include-dependency1");
        Mockito.verify(clientSideTeleporter).includeDependencyPrefix("include-dependency2");
        Mockito.verify(clientSideTeleporter).excludeDependencyPrefix("exclude-dependency1");
        Mockito.verify(clientSideTeleporter).excludeDependencyPrefix("exclude-dependency2");
        Mockito.verify(clientSideTeleporter).embedClass(ClassResourceVisitor.class);
        Mockito.verify(clientSideTeleporter).embedClass(ClientSideTeleporter.class);
        Mockito.verify(clientSideTeleporter).setTestReadyTimeoutSeconds(50);
        Mockito.verify(clientSideTeleporter).setServerCredentials("adminuser", "adminpassword");
    }

    @Test(expected=AssertionError.class)
    public void testEmbeddingInvalidClass() {
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_BASE_URL, "base-url");
        System.setProperty(DefaultPropertyBasedCustomizer.PROPERTY_EMBED_CLASSES, "org.apache.sling.testing.teleporter.client.InvalidClass");
        customizer = new DefaultPropertyBasedCustomizer();
        customizer.customize(clientSideTeleporter, null);
    }
}


text:
package org.apache.activemq.artemis.core.protocol;

import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_RECEIVE_LARGE_MSG;
import static org.apache.activemq.artemis.core.protocol.core.impl.PacketImpl.SESS_RECEIVE_MSG;

import org.apache.activemq.artemis.api.core.ActiveMQBuffer;
import org.apache.activemq.artemis.core.client.impl.ClientLargeMessageImpl;
import org.apache.activemq.artemis.core.client.impl.ClientMessageImpl;
import org.apache.activemq.artemis.core.protocol.core.Packet;
import org.apache.activemq.artemis.core.protocol.core.impl.PacketDecoder;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionReceiveClientLargeMessage;
import org.apache.activemq.artemis.core.protocol.core.impl.wireformat.SessionReceiveMessage;

public class ClientPacketDecoder extends PacketDecoder {

   private static final long serialVersionUID = 6952614096979334582L;
   public static final ClientPacketDecoder INSTANCE = new ClientPacketDecoder();

   @Override
   public Packet decode(final ActiveMQBuffer in) {
      final byte packetType = in.readByte();

      Packet packet = decode(packetType);

      packet.decode(in);

      return packet;
   }

   @Override
   public Packet decode(byte packetType) {
      Packet packet;

      switch (packetType) {
         case SESS_RECEIVE_MSG: {
            packet = new SessionReceiveMessage(new ClientMessageImpl());
            break;
         }
         case SESS_RECEIVE_LARGE_MSG: {
            packet = new SessionReceiveClientLargeMessage(new ClientLargeMessageImpl());
            break;
         }
         default: {
            packet = super.decode(packetType);
         }
      }
      return packet;
   }
}


text:
import './about.scss'

class Ctrl {
  /** @ngInject */
    constructor(Employee, Common) {
    // DI
    this.common = Common;
    this.isAuthorized = Common.isAuthorized;
    this.user = this.common.user;
  }

  $onInit() {
  }
}

export default {
  template: require('./about.html'),
  controller: Ctrl,
  controllerAs: 'vm'
};


text:
package com.bitcoins.clightning.rpc

import akka.http.scaladsl.model._
import akka.util._
import org.newsclub.net.unix.AFUNIXSocketAddress
import play.api.libs.json._

import java.io._
import java.util.UUID
import scala.concurrent._
import scala.util._

abstract class CLightningUnixSocketHandler { self: CLightningRpcClient =>

  def clightningCall[T](command: String, parameters: JsValue = JsArray.empty)(
      implicit reader: Reads[T]): Future[T] = {
    logger.trace(s"clightning rpc call $command")
    val responseF = sendRequest(command, parameters)

    responseF.map { payload =>
      parseResult(payload, command)
    }
  }

  private def parseResult[T](payload: RpcResult, commandName: String)(implicit
      reader: Reads[T]): T = {
    payload.result match {
      case Some(result) =>
        result.validate[T] match {
          case JsSuccess(value, _) => value
          case JsError(_) =>
            val errMsg =
              s"Could not parse JsResult for command: $commandName json: $result"
            logger.error(errMsg)
            throw new IllegalArgumentException(errMsg)
        }
      case None =>
        payload.error match {
          case Some(errJs) =>
            import RpcResult._
            errJs.validate[RpcError] match {
              case JsSuccess(err, _) =>
                val errMsg =
                  s"Error for command=$commandName, error code: ${err.code}, msg: ${err.message}"
                logger.error(errMsg)
                throw new RuntimeException(err.message)
              case JsError(_) =>
                throw new RuntimeException(
                  s"Could not parse error for command: $commandName, json: $errJs")
            }
          case None =>
            throw new RuntimeException(
              s"Did not get result or error for command: $commandName")
        }
    }
  }

  private def parseJson(response: String): RpcResult = {
    val json = Json.parse(response)

    json
      .validate[RpcResult]
      .getOrElse {
        val errMsg = s"Could not parse $json"
        logger.error(errMsg)
        throw new RuntimeException(errMsg)
      }
  }

  private def sendRequest(
      methodName: String,
      params: JsValue): Future[RpcResult] = {
    val uuid = UUID.randomUUID().toString
    val map: Map[String, JsValue] = Map("jsonrpc" -> JsString("2.0"),
                                        "id" -> JsString(uuid),
                                        "method" -> JsString(methodName),
                                        "params" -> params)

    val request: ByteString =
      HttpEntity(ContentTypes.`application/json`, JsObject(map).toString()).data

    Future.fromTry(doRawCall(request, uuid))
  }

  // -- below cribbed from https://github.com/clightning4j/JRPClightning/blob/7e1708d7ed67511ab5e67e9f4bc103d6b2c5be32/src/main/java/jrpc/service/socket/UnixDomainSocketRpc.java
  // todo make this more scala-y
  import org.newsclub.net.unix.AFUNIXSocket

  import java.net.Socket
  import java.nio.charset.StandardCharsets

  private def doRawCall(message: ByteString, uuid: String): Try[RpcResult] = {
    val socket = AFUNIXSocket.newInstance()
    socket.connect(AFUNIXSocketAddress.of(instance.rpcFile.toPath))
    val outputStream = socket.getOutputStream
    val callT = Try {
      // Send the message
      outputStream.write(message.toVector.toArray)
      outputStream.flush()
      // receive the message
      readAll(socket, uuid)
    }

    // close socket
    outputStream.close()
    socket.close()

    callT
  }

  private def readAll(socket: Socket, uuid: String): RpcResult = {
    val inputStream = socket.getInputStream
    val inputReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)
    val bufferedReader = new BufferedReader(inputReader)
    val stream = bufferedReader.lines()

    stream
      .filter { str =>
        logger.trace(s"Received response: $str")
        Try(parseJson(str).id == uuid).isSuccess
      }
      .map[RpcResult] { str =>
        parseJson(str)
      }
      .findFirst()
      .orElseThrow { () =>
        new RuntimeException(s"Could not find result for call $uuid")
      }
  }
}

private[clightning] case class RpcResult(
    jsonrpc: String,
    id: String,
    result: Option[JsValue],
    error: Option[JsValue])

private[clightning] case class RpcError(code: Long, message: String)

private[clightning] object RpcResult {
  implicit val rpcResultReads: Reads[RpcResult] = Json.reads[RpcResult]
  implicit val rpcErrorReads: Reads[RpcError] = Json.reads[RpcError]

}


text:
function DisplayController(options) {
	this.model = new package.CALC.display.model(options.displaymodel);
	this.view = new package.CALC.display.view({
		el : options.el
	});
}

//interface methods
DisplayController.prototype.setData = function(options) {
	this.view.setData(options);
};

DisplayController.prototype.clearData = function(options) {
	this.view.clearData();
};

package.CALC.display.controller = DisplayController;