text:
package com.example.karan.traffikill.Adapters;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.example.karan.traffikill.R;
import com.example.karan.traffikill.models.ResultData;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

public class NearbyPlaceAdapter extends RecyclerView.Adapter<NearbyPlaceAdapter.NearbyPlaceHolder> {

    private ArrayList<ResultData> itemList;
    private Context context;

    public NearbyPlaceAdapter(Context context, ArrayList<ResultData> itemList) {
        this.itemList = itemList;
        this.context = context;
    }

    @Override
    public NearbyPlaceHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layoutView = layoutInflater.inflate(R.layout.nearby_place_list_item, null);
        return new NearbyPlaceHolder(layoutView);
    }

    @Override
    public void onBindViewHolder(NearbyPlaceHolder holder, int position) {
        Picasso.with(context)
                .load("https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&key=AIzaSyCcWcxyuUpiemoDQzHGzJx-yd5jW0Pwt14" +
                        "&maxwidth=260&photoreference=" +
                        (this.itemList.get(position).getPhotosData() != null ?
                                this.itemList.get(position).getPhotosData().get(0).getPhotoReference() : ""))
                .fit()
                .placeholder(R.drawable.ic_placeholder)
                .error(R.drawable.ic_error)
                .into(holder.placePhoto);
        holder.placeName.setText(this.itemList.get(position).getName());
        holder.ratingBar.setRating(this.itemList.get(position).getRating());
        final int x = position;
        holder.showInMaps.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri gmmIntentUri = Uri.parse("geo:0,0?q=" +
                        NearbyPlaceAdapter.this.itemList.get(x).getGeometry().getLocationData().getLatitude() + "," +
                        NearbyPlaceAdapter.this.itemList.get(x).getGeometry().getLocationData().getLongitude() +
                        "(" + NearbyPlaceAdapter.this.itemList.get(x).getName() + ")");
                Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
                mapIntent.setPackage("com.google.android.apps.maps");
                NearbyPlaceAdapter.this.context.startActivity(mapIntent);
            }
        });
    }

    @Override
    public int getItemCount() {
        return this.itemList.size();
    }

    public void updateData(ArrayList<ResultData> restaurantList) {
        this.itemList.clear();
        this.itemList.addAll(restaurantList);
        notifyDataSetChanged();
    }

    public class NearbyPlaceHolder extends RecyclerView.ViewHolder {
        ImageView placePhoto;
        TextView placeName;
        RatingBar ratingBar;
        TextView showInMaps;

        public NearbyPlaceHolder(View itemView) {
            super(itemView);
            this.placePhoto = (ImageView) itemView.findViewById(R.id.iv_place_photo);
            this.placeName = (TextView) itemView.findViewById(R.id.place_name);
            this.ratingBar = (RatingBar) itemView.findViewById(R.id.ratingBar);
            this.showInMaps = (TextView) itemView.findViewById(R.id.tvMaps);
        }
    }
}


text:
namespace Content.Shared.Chat;

public abstract class SharedChatSystem : EntitySystem {}

redpajama_set_name: RedPajamaGithub


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using InBloomClient.Enum;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace InBloomClient.Entities
{
    public class GradingPeriod
    {
        /// <summary>
        /// Month, day, and year of the first day of the grading period.
        /// </summary>
        public DateTime beginDate { get; set; }

        /// <summary>
        /// Month, day, and year of the last day of the grading period.
        /// </summary>
        public DateTime endDate { get; set; }

        /// <summary>
        /// The name of the period for which grades are reported
        /// values:First Six Weeks, Second Six Weeks, Third Six Weeks, Fourth Six Weeks, Fifth Six Weeks, Sixth Six Weeks, First Semester,
        /// Second Semester, First Summer Session, Second Summer Session, Third Summer Session, Summer Semester, First Nine Weeks,
        /// Second Nine Weeks, Third Nine Weeks, Fourth Nine Weeks, First Trimester, Second Trimester, Third Trimester, End of Year
        /// </summary>
        [JsonConverter(typeof(StringEnumConverter))]
        public GradingPeriodType gradingPeriod { get; set; }

        /// <summary>
        /// Total days available for educational instruction during the grading period.
        /// </summary>
        public int totalInstructionalDays { get; set; }

        /// <summary>
        /// Days associated with the grading period.
        /// </summary>
        public List<CalendarDate> calendarDates { get; set; }
    }
}


text:
import * as React from "react";
import QRCode from 'qrcode.react';
import { parseUrl } from 'query-string';
import ValidationErrors from 'app/lib/ValidationErrors';
import Panel from 'app/components/shared/Panel';
import Button from 'app/components/shared/Button';
import TokenCodeInput from 'app/components/shared/TokenCodeInput';
import buildkiteqr from './buildkite.svg';

type ValidationError = {
  field: string,
  message: string
};

type Props = {
  onActivateOtp: (token: string, callback?: () => void) => void,
  provisioningUri: string
};

type State = {
  errors: ?Array<ValidationError>,
  isActivating: boolean,
  totpCodeValue: string,
  copiedOTPSecretKey: boolean
};

export default class TwoFactorConfigureActivate extends React.PureComponent<Props, State> {
  tokenInputRef: React.Ref<typeof TokenCodeInput>;
  state = {
    errors: [],
    isActivating: false,
    totpCodeValue: '',
    copiedOTPSecretKey: false
  };

  constructor(props: Props) {
    super(props);
    this.tokenInputRef = React.createRef();
  }

  render() {
    const errors = new ValidationErrors(this.state.errors);
    const provisioningUriSecret = parseUrl(this.props.provisioningUri).query.secret;

    return (
      <React.Fragment>

          To activate two-factor authentication, scan this barcode with your authenticator application, then enter the generated One Time Password below.

        <Panel className="mb3">

                <QRCode
                  renderAs="svg"
                  fgColor="currentColor"
                  bgColor="transparent"
                  width="260"
                  height="260"
                  className="block mx-auto"
                  level="H" // approx 30% error correction
                  style={{ maxWidth: '100%' }}
                  value={this.props.provisioningUri}
                />

                Can't use the barcode?
You can use this secret key instead: {provisioningUriSecret}

        </Panel>

          <TokenCodeInput
            ref={this.tokenInputRef}
            errors={errors.findForField('token')}
            disabled={this.state.isActivating}
            value={this.state.totpCodeValue}
            onChange={this.handleTotpCodeChange}
          />

        <Button
          className="col-12"
          disabled={this.state.isActivating}
          theme="success"
          onClick={this.handleTotpActivate}
        >
          Activate
        </Button>
      </React.Fragment>
    );
  }

  handleTotpCodeChange = (totpCodeValue: string) => {
    this.setState({ totpCodeValue });
  }

  handleTotpActivate = () => {
    this.setState({ isActivating: true }, () => {
      this.props.onActivateOtp(this.state.totpCodeValue, (errors) => {
        if (errors) {
          this.setState({ errors, isActivating: false }, () => {
            if (this.tokenInputRef.current) {
              // $FlowExpectError Typing createRefs seems broken at the moment, hopefully we can fis this at some point.
              this.tokenInputRef.current.focus();
            }
          });
        } else {
          this.setState({ errors: [], isActivating: false });
        }
      });
    });
  }
}


text:
<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring MVC application</display-name>

    <filter>
        <filter-name>encoding-filter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encoding-filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>HelloWeb</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWeb</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Loads Spring Security config file -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>


text:
package org.scalacoin.script.locktime

import org.scalatest.{FlatSpec, MustMatchers}

/**
 * Created by chris on 1/6/16.
 */
class LocktimeOperationTest extends FlatSpec with MustMatchers {

  "LocktimeOperations" must "define OP_CHECKLOCKTIMEVERIFY" in {
    OP_CHECKLOCKTIMEVERIFY.opCode must be (177)
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

using Xunit;

using Moq;

using MyoSharp.Communication;
using MyoSharp.Device;
using MyoSharp.Internal;
using MyoSharp.Exceptions;

namespace MyoSharp.Tests.Unit.Communication
{
    public class ChannelDriverTests
    {
        #region Methods
        [Fact]
        public void Create_NullChannelBridge_ThrowsNullArgumentException()
        {
            // Setup
            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);

            // Execute
            Assert.ThrowsDelegate method = () => ChannelDriver.Create(null, errorHandlerDriver.Object);

            // Assert
            var exception = Assert.Throws<ArgumentNullException>(method);
            Assert.Equal("channelBridge", exception.ParamName);
        }

        [Fact]
        public void Create_NullMyoErrorHandlerDriver_ThrowsNullArgumentException()
        {
            // Setup
            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);

            // Execute
            Assert.ThrowsDelegate method = () => ChannelDriver.Create(bridge.Object, null);

            // Assert
            var exception = Assert.Throws<ArgumentNullException>(method);
            Assert.Equal("myoErrorHandlerDriver", exception.ParamName);
        }

        [Fact]
        public void Create_ValidParameters_NewInstance()
        {
            // Setup
            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);

            // Execute
            var result = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Assert
            Assert.NotNull(result);
        }

        [Fact]
        public void GetMyoForEvent_ValidParameters_ExpectedBridgeCalls()
        {
            // Setup
            var eventHandle = new IntPtr(123);
            var myoHandle = new IntPtr(789);
            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.EventGetMyo32(eventHandle))
                .Returns(myoHandle);
            bridge
                .Setup(x => x.EventGetMyo64(eventHandle))
                .Returns(myoHandle);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            var result = driver.GetMyoForEvent(eventHandle);

            // Assert
            Assert.Equal(myoHandle, result);

            bridge.Verify(x => x.EventGetMyo32(eventHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.EventGetMyo64(eventHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());
        }

        [Fact]
        public void GetEventType_ValidParameters_ExpectedBridgeCalls()
        {
            // Setup
            var eventHandle = new IntPtr(123);
            var eventType = MyoEventType.Paired;
            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.EventGetType32(eventHandle))
                .Returns(eventType);
            bridge
                .Setup(x => x.EventGetType64(eventHandle))
                .Returns(eventType);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            var result = driver.GetEventType(eventHandle);

            // Assert
            Assert.Equal(eventType, result);

            bridge.Verify(x => x.EventGetType32(eventHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.EventGetType64(eventHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());
        }

        [Fact]
        public void Run_InvalidParameters_ThrowsNullArgumentException()
        {
            // Setup
            var myoHandle = new IntPtr(123);
            var userData = new IntPtr(789);
            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            Assert.ThrowsDelegate method = () => driver.Run(myoHandle, null, userData);

            // Assert
            var result = Assert.Throws<ArgumentNullException>(method);
            Assert.Equal("handler", result.ParamName);

            IntPtr errorHandle;
            bridge.Verify(x => x.Run32(It.IsAny<IntPtr>(), It.IsAny<uint>(), It.IsAny<MyoRunHandler>(), It.IsAny<IntPtr>(), out errorHandle), Times.Never());
            bridge.Verify(x => x.Run64(It.IsAny<IntPtr>(), It.IsAny<uint>(), It.IsAny<MyoRunHandler>(), It.IsAny<IntPtr>(), out errorHandle), Times.Never());
        }

        [Fact]
        public void Run_ValidParameters_ExpectedBridgeCalls()
        {
            // Setup
            var myoHandle = new IntPtr(123);
            var userData = new IntPtr(789);
            var bridge = new Mock<IChannelBridge>();

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);
            errorHandlerDriver
                .Setup(x => x.FreeMyoError(IntPtr.Zero));

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);
            MyoRunHandler handler = (_, __) => MyoRunHandlerResult.Continue;

            // Execute
            driver.Run(myoHandle, handler, userData);

            // Assert
            IntPtr errorHandle;
            bridge.Verify(x => x.Run32(myoHandle, 50, handler, userData, out errorHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.Run64(myoHandle, 50, handler, userData, out errorHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());

            errorHandlerDriver.Verify(x => x.FreeMyoError(IntPtr.Zero), Times.Once());
        }

        [Fact]
        public void GetEventTimestamp_ValidParameters_ExpectedBridgeCalls()
        {
            // Setup
            var eventHandle = new IntPtr(123);
            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.EventGetTimestamp32(eventHandle))
                .Returns(10000);
            bridge
                .Setup(x => x.EventGetTimestamp64(eventHandle))
                .Returns(10000);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            var result = driver.GetEventTimestamp(eventHandle);

            // Assert
            Assert.Equal(new DateTime(1970, 1, 1).Add(TimeSpan.FromMilliseconds(10000 / 1000)), result);

            bridge.Verify(x => x.EventGetTimestamp32(eventHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.EventGetTimestamp64(eventHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());
        }

        [Fact]
        public void InitializeMyoHub_ValidParameters_ExpectedBridgeCalls()
        {
            // Setup
            IntPtr errorHandle = IntPtr.Zero;
            IntPtr myoHandle = new IntPtr(123);
            var applicationIdentifier = "com.myosharp.tests";

            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.InitHub32(out myoHandle, applicationIdentifier, out errorHandle))
                .Returns(MyoResult.Success);
            bridge
                .Setup(x => x.InitHub64(out myoHandle, applicationIdentifier, out errorHandle))
                .Returns(MyoResult.Success);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);
            errorHandlerDriver
                .Setup(x => x.FreeMyoError(errorHandle));

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            var result = driver.InitializeMyoHub(applicationIdentifier);

            // Assert
            Assert.Equal(new IntPtr(123), result);

            bridge.Verify(x => x.InitHub32(out myoHandle, applicationIdentifier, out errorHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.InitHub64(out myoHandle, applicationIdentifier, out errorHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());

            errorHandlerDriver.Verify(x => x.GetErrorString(errorHandle), Times.Never());
            errorHandlerDriver.Verify(x => x.FreeMyoError(errorHandle), Times.Once());
        }

        [Fact]
        public void InitializeMyoHub_HubErrorInvalidArgument_ThrowsArgumentException()
        {
            // Setup
            IntPtr errorHandle = new IntPtr(789);
            IntPtr myoHandle = new IntPtr(123);
            var applicationIdentifier = "com.myosharp.tests";

            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.InitHub32(out myoHandle, applicationIdentifier, out errorHandle))
                .Returns(MyoResult.ErrorInvalidArgument);
            bridge
                .Setup(x => x.InitHub64(out myoHandle, applicationIdentifier, out errorHandle))
                .Returns(MyoResult.ErrorInvalidArgument);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);
            errorHandlerDriver
                .Setup(x => x.GetErrorString(errorHandle))
                .Returns("The error message.");
            errorHandlerDriver
                .Setup(x => x.FreeMyoError(errorHandle));

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            Assert.ThrowsDelegate method = () => driver.InitializeMyoHub(applicationIdentifier);

            // Assert
            Assert.Throws<ArgumentException>(method);

            bridge.Verify(x => x.InitHub32(out myoHandle, applicationIdentifier, out errorHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.InitHub64(out myoHandle, applicationIdentifier, out errorHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());

            errorHandlerDriver.Verify(x => x.GetErrorString(errorHandle), Times.Once());
            errorHandlerDriver.Verify(x => x.FreeMyoError(errorHandle), Times.Once());
        }

        [Fact]
        public void InitializeMyoHub_HubError_ThrowsInvalidOperationException()
        {
            // Setup
            IntPtr errorHandle = new IntPtr(789);
            IntPtr myoHandle = new IntPtr(123);
            var applicationIdentifier = "com.myosharp.tests";

            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.InitHub32(out myoHandle, applicationIdentifier, out errorHandle))
                .Returns(MyoResult.Error);
            bridge
                .Setup(x => x.InitHub64(out myoHandle, applicationIdentifier, out errorHandle))
                .Returns(MyoResult.Error);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);
            errorHandlerDriver
                .Setup(x => x.GetErrorString(errorHandle))
                .Returns("The error message.");
            errorHandlerDriver
                .Setup(x => x.FreeMyoError(errorHandle));

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            Assert.ThrowsDelegate method = () => driver.InitializeMyoHub(applicationIdentifier);

            // Assert
            Assert.Throws<InvalidOperationException>(method);

            bridge.Verify(x => x.InitHub32(out myoHandle, applicationIdentifier, out errorHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.InitHub64(out myoHandle, applicationIdentifier, out errorHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());

            errorHandlerDriver.Verify(x => x.GetErrorString(errorHandle), Times.Once());
            errorHandlerDriver.Verify(x => x.FreeMyoError(errorHandle), Times.Once());
        }

        [Fact]
        public void ShutdownMyoHub_ValidParameters_ExpectedBridgeCalls()
        {
            // Setup
            IntPtr errorHandle;
            IntPtr myoHandle = new IntPtr(123);

            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.ShutdownHub32(myoHandle, out errorHandle))
                .Returns(MyoResult.Success);
            bridge
                .Setup(x => x.ShutdownHub64(myoHandle, out errorHandle))
                .Returns(MyoResult.Success);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);
            errorHandlerDriver
                .Setup(x => x.FreeMyoError(IntPtr.Zero));

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            driver.ShutdownMyoHub(myoHandle);

            // Assert
            bridge.Verify(x => x.ShutdownHub32(myoHandle, out errorHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.ShutdownHub64(myoHandle, out errorHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());

            errorHandlerDriver.Verify(x => x.FreeMyoError(IntPtr.Zero), Times.Once());
        }

        [Fact]
        public void ShutdownMyoHub_HubErrorInvalidArgument_ThrowsArgumentException()
        {
            // Setup
            IntPtr errorHandle = new IntPtr(789);
            IntPtr myoHandle = new IntPtr(123);

            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.ShutdownHub32(myoHandle, out errorHandle))
                .Returns(MyoResult.ErrorInvalidArgument);
            bridge
                .Setup(x => x.ShutdownHub64(myoHandle, out errorHandle))
                .Returns(MyoResult.ErrorInvalidArgument);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);
            errorHandlerDriver
                .Setup(x => x.GetErrorString(errorHandle))
                .Returns("The error message.");
            errorHandlerDriver
                .Setup(x => x.FreeMyoError(errorHandle));

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            Assert.ThrowsDelegate method = () => driver.ShutdownMyoHub(myoHandle);

            // Assert
            Assert.Throws<ArgumentException>(method);

            bridge.Verify(x => x.ShutdownHub32(myoHandle, out errorHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.ShutdownHub64(myoHandle, out errorHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());

            errorHandlerDriver.Verify(x => x.GetErrorString(errorHandle), Times.Once());
            errorHandlerDriver.Verify(x => x.FreeMyoError(errorHandle), Times.Once());
        }

        [Fact]
        public void ShutdownMyoHub_HubError_ThrowsInvalidOperationException()
        {
            // Setup
            IntPtr errorHandle = new IntPtr(789);
            IntPtr myoHandle = new IntPtr(123);

            var bridge = new Mock<IChannelBridge>(MockBehavior.Strict);
            bridge
                .Setup(x => x.ShutdownHub32(myoHandle, out errorHandle))
                .Returns(MyoResult.Error);
            bridge
                .Setup(x => x.ShutdownHub64(myoHandle, out errorHandle))
                .Returns(MyoResult.Error);

            var errorHandlerDriver = new Mock<IMyoErrorHandlerDriver>(MockBehavior.Strict);
            errorHandlerDriver
                .Setup(x => x.GetErrorString(errorHandle))
                .Returns("The error message.");
            errorHandlerDriver
                .Setup(x => x.FreeMyoError(errorHandle));

            var driver = ChannelDriver.Create(bridge.Object, errorHandlerDriver.Object);

            // Execute
            Assert.ThrowsDelegate method = () => driver.ShutdownMyoHub(myoHandle);

            // Assert
            Assert.Throws<InvalidOperationException>(method);

            bridge.Verify(x => x.ShutdownHub32(myoHandle, out errorHandle), PlatformInvocation.Running32Bit ? Times.Once() : Times.Never());
            bridge.Verify(x => x.ShutdownHub64(myoHandle, out errorHandle), PlatformInvocation.Running32Bit ? Times.Never() : Times.Once());

            errorHandlerDriver.Verify(x => x.GetErrorString(errorHandle), Times.Once());
            errorHandlerDriver.Verify(x => x.FreeMyoError(errorHandle), Times.Once());
        }
        #endregion
    }
}


text:
package haus

import(
	"os"
	"fmt"
	"strings"
	"path/filepath"
	"io/ioutil"

	"gopkg.in/yaml.v2"
	"github.com/searchspring/repo-tsar/gitutils"
)

// Config represents the configurations in haus config file.
type Config struct {
	Name string
	Email string
	Path string
	Pwd string
	Hausrepo string
	Environments map[string]Environment
	Variables map[string]string
}

// ReadConfig reads the config file from the supplied full path and
// returns a Config and error.
func ReadConfig(filename string, usrcfgfile string, branch string, path string, variables map[string]string )(*Config, error) {
	config := &Config{}

	// Check for current directory config
	curdir,err := filepath.Abs("./")
	if err != nil {
		return config, err
	}
	curdircfg := fmt.Sprintf("%s/.hauscfg.yaml", curdir)
	_,err = os.Stat(curdircfg)
	has_curdircfg :=  false
	if err == nil {
		has_curdircfg = true
	}

	// If the configfile is missing, try to check it out from git repo
	_,err = os.Stat(filename)
	if err != nil {
		// Get the url for the git repo from user config
		err = readCfg(usrcfgfile,config)
		if err != nil {
			return config,err
		}

		// If there's a .hauscfg.yaml in the current directory, let it supercede the usrcfgfile
		if has_curdircfg {
			err = readCfg(curdircfg, config)
			if err != nil {
				return config,err
			}
		}

		// If the url is defined, clone the repo
		if config.Hausrepo != "" {
			cloneinfo := &gitutils.CloneInfo{
				Reponame: "hauscfg",
				Path: ".",
				URL: config.Hausrepo,
				Branch: branch,
			}
			fmt.Printf("Cloning repo hauscfg from %s\n", config.Hausrepo)
			_,err = cloneinfo.CloneRepo()
			if err != nil {
				return config, err
			}
		} else {
			// There's no haus yaml, and hausrepo isn't defined in the user config
			err = fmt.Errorf("No %s file and %s missing 'hausrepo'.", filename,usrcfgfile)
			return config, err
		}
	}

	// Read haus yaml file
	err = readCfg(filename, config)
	if err != nil {
		return config, err
	}

	// Read user config haus yaml
	err = readCfg(usrcfgfile, config)
	if err != nil {
		return config, err
	}

	// If there's a .hauscfg.yaml in the current directory, let it supercede the usrcfgfile
	if has_curdircfg {
		err = readCfg(curdircfg, config)
		if err != nil {
			return config,err
		}
	}

	// Process default variables
	for k, v := range config.Variables {
		for name, env := range config.Environments {
			if _, ok := env.Variables[k]; ok {
			} else {
				if env.Variables == nil {
					env.Variables = make(map[string]string)
				}
				env.Variables[k] = v
				config.Environments[name] = env
			}
		}
	}

	// Pass variables from command line into config
	for k, v := range variables {
		for name, env := range config.Environments {
			if _,ok := env.Variables[k]; ok {
				config.Environments[name].Variables[k] = v
			}
		}
	}

	// Set path
	config.Path = path

	// Store the current path
	config.Pwd,err = os.Getwd()
	if err != nil {
		return config,err
	}
	return config, nil
}

// readCfg reads a file and parses it for yaml and unmarshals it into config.
func readCfg(cfgfile string, config *Config) (error) {
	// Read config from user home a overrite anything

	_,err := os.Stat(expandTilde(cfgfile))
	if err != nil {
		fmt.Printf("Config file %#v missing\n", cfgfile)
	} else {
		cfg,err := ioutil.ReadFile(expandTilde(cfgfile))
		if err != nil {
			return err
		}
		err = yaml.Unmarshal(cfg, config)
		if err != nil {
			return err
		}
	}
	return nil
}

// expandTilde expands ~ to value of ENV HOME
func expandTilde(f string) string {
	if strings.HasPrefix(f, "~"+string(filepath.Separator)) {
		return os.Getenv("HOME") + f[1:]
	}
	return f
}


text:
/**
 * @module CoreModule
 */ /** */
import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';

import { StatusBarService } from '../status-bar/status-bar.service';
/**
 * @whatItDoes Manages all layout functions for the {@link AppComponent}.
 * @purpose The goal for this component is to encapsulate all logic relating to how the app's layout
 * should function.
 *
 * **This allows:**
 * - all sub-components to focus on their own encapsulated behaviour
 * - most layout changes to be made in one place
 * - the {@link AppComponent} to stay lean and focused on its main task, orchestrating the app as a whole
 * - the layout to be separate from other non-layout dependant elements such as modals and alerts
 * - the layout to later be put inside a lazy-loaded route if the site requires a different
 * layout for signed in users
 *
 * For example, a change in the {@link FooterComponent} design shouldn't also require a change in the
 * {@link LayoutComponent} or {@link NavComponent}.
 */
@Component({
  selector: 'app-layout',
  templateUrl: './layout.component.html',
  styleUrls: ['./layout.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class LayoutComponent implements OnInit {
  /**
   * Route specific layout options.
   *
   * This lets the {@link NavComponent} view know about any number of route specific
   * layout customization options that are set in the {@link AppRoutingModule} config.
   */
  layout: LayoutOptions;
  /**
   * Current padding of the layout, updated by {@link onHeightChange}.
   *
   * **Padding is set dynamically so that:**
   * - {@link LayoutComponent} does not need to know about other elements' styling
   * - layout sub-components can be made without a predefined height
   * @param padding.top Responds to the height of {@link NavComponent}. Defaults to `20px`.
   * @param padding.bottom Responds to the height of {@link FooterComponent}. Defaults to `20px`.
   */
  padding = {
    top: '20',
    bottom: '20'
  };
  /**
   * Creates the {@link LayoutComponent}.
   */
  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private statusBarService: StatusBarService) { }
  /**
   * When {@link NavComponent} or {@link FooterComponent} emits a height change,
   * {@link onHeightChange} adds the new height to the padding of the `.content-area` element.
   * @param position           accepts `top` or `bottom`.
   * @param newHeight          the new pixel height of the element being measured
   * @param additionalPadding  extra padding beyond the pixel height of the element being measured.
   */
  onHeightChange(position: string, newHeight: number, additionalPadding: number) {
    this.padding[position] = newHeight + additionalPadding;
  }
  /**
   * Sets up the route change listener.
   */
  ngOnInit() {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.onNewRoute();
      }
    });
  }
  /**
   * {@link onNewRoute} is responsible for setting up route specific elements relating to the layout.
   *
   * **`this.layout`:** Tells the {@link NavComponent} view about any number of route specific
   * layout customization options that are set in the {@link AppRoutingModule} config.
   *
   * **`scrollTop`:** Scrolls the page to the top.
   * - Without this users will stay at their current scroll position when navigating between pages
   * which is unexpected.
   */
  private onNewRoute() {
    this.layout = this.activatedRoute.snapshot.firstChild.data['layout'];
    document.body.scrollTop = 0;
  }
}
/**
 * Route specific layout options.
 */
export interface LayoutOptions {
  [propName: string]: boolean|number|string;
}


text:
require 'vf-snapshots/version'

require 'thor'
require 'aws-sdk'
require 'yaml'
require 'rainbow'
require 'pony'
require 'byebug'

require 'vf-snapshots/config'
require 'vf-snapshots/account'
require 'vf-snapshots/instance'
require 'vf-snapshots/volume'
require 'vf-snapshots/backup'

module VfSnapshots

  # a regex to detect snapshots that originated with us
  DESC_REGEX = /\d{14}\ i-/
  DEFAULT_BACKUP_DAYS = 7

  def self.verbose message
    puts message if Config.options[:verbose]
  end

  def self.current_time_string
    Time.now.strftime('%Y%m%d%H%M%S')
  end

  class Snapshots < Thor

    no_commands do

      def send_email subject, body

        return if options[:no_emails]

        VfSnapshots::verbose "\n\nEMAIL SUBJECT: #{subject}"
        VfSnapshots::verbose body
        VfSnapshots::verbose "\n"

        emails = VfSnapshots::Config.email_recipients
        unless emails.empty?
          emails.each do |email|
            VfSnapshots::verbose "Sending mail to: #{email}"
            opts = {:from => VfSnapshots::Config.mail[:from], :to => email, :subject => subject, :body => body, :via => VfSnapshots::Config.mail[:via], :via_options => VfSnapshots::Config.mail[:via_options]}
            Pony.mail(opts)
          end
        end

      end
    end

    desc 'create', 'create new snapshots of all mounted volumes in the configured AWS accounts'
    option :config, :desc => 'alternate file for config, default is /etc/vf-snapshots.yml.  example file is in gem source at config/vf-snapshots.yml.example'
    option :dry_run, :type => :boolean, :desc => "don't actually create a snapshot, but do everything else"
    option :verbose, :type => :boolean, :desc => 'tell me more stuff!'
    option :account, :desc => 'specify account'
    def create
      VfSnapshots::Config.options = options
      Account.for_each(options[:account]) do |account, ec2|
        begin
          account.volumes.each do |volume|
            message = "Creating #{volume.current_snapshot_name}"
            if options[:dry_run]
              VfSnapshots::verbose "#{message} (dry run, not really creating)"
            else
              VfSnapshots::verbose message
              volume.create_snapshot
            end
          end
        rescue Aws::EC2::Errors::AuthFailure
          vmsg = Rainbow("X #{account.name}: INVALID AUTHENTICATION").magenta
          puts vmsg
        end
      end
      VfSnapshots::verbose "\n"
    end

    desc 'verify', 'verify recent snapshots for all mounted volumes in the configured AWS accounts'
    option :emails, :desc => 'comma-separated list of email recipients of a status report'
    option :no_emails, :type => :boolean, :desc => 'suppress email output'
    option :config, :desc => 'alternate file for config, default is /etc/vf-snapshots.yml.  example file is in gem source at config/vf-snapshots.yml.example'
    option :verbose, :type => :boolean, :desc => 'tell me more stuff!'
    option :account, :desc => 'specify account'
    def verify
      begin
        VfSnapshots::Config.options = options
        messages = []
        subject = 'AWS Snapshots'
        body = "Hi,\n\n"
        details = ''
        volume_count = 0
        volume_count_with_recent_snapshot = 0
        Account.for_each(options[:account]) do |account|
          begin
            details << "\nAccount: #{account.name}\n"
            #Aws.memoize do
            volume_count += account.volumes.count
            account.volumes.each do |volume|
              vmsg = "Verifying current snapshot for #{volume.name}"
              if volume.recent_snapshot_exists?
                volume_count_with_recent_snapshot += 1
                vmsg = Rainbow("✓ #{vmsg}").green
                VfSnapshots::verbose vmsg
                details << "  ok: #{volume.name}\n"
                details << "      #{volume.other_details}\n"
              else
                vmsg = Rainbow("X #{account.name}: FAILURE #{vmsg}; most recent was #{volume.most_recent_snapshot_date.to_s}").red
                messages << "  #{account.name}: No recent snapshot found for #{volume.name}, most recent was #{volume.most_recent_snapshot_date.to_s}"
                details << "  XX: #{volume.name}\n"
                puts vmsg
              end
            end
            #end
          rescue Aws::EC2::Errors::AuthFailure
            puts "Error: #{$!}"
            details << "  INVALID AUTHENTICATION\n"
            messages << "  #{account.name}: AWS Authentication Error"
            vmsg = Rainbow("X #{account.name}: INVALID AUTHENTICATION").magenta
            puts vmsg
          end
        end
        if messages.empty?
          body << "Everything is fine, there are current snapshots for #{volume_count} volumes.\n"

          subject << ' completed OK'
          body << details + "\n\n"
          body << "Thanks,\n\n"
          body << "The friendly AWS Snapshotter service.\n\n"
        else
          subject << ' -- ACHTUNG!!! THERE ARE PROBLEMS!!!!!'
          body << "There should be recent snapshots for #{volume_count} volumes, and there #{volume_count_with_recent_snapshot == 1 ? 'was' : 'were'} only #{volume_count_with_recent_snapshot}.  Here are some more details:\n\n"
          body << messages.join("\n")
          body << "\n"
          body << details + "\n\n"
          body << "Sorry for the bad news,\n\n"
          body << "The concerned AWS Snapshotter service.\n\n"
        end
      rescue => exception
        puts "Error: #{$!}"
        puts exception.backtrace
        subject = 'AWS Snapshots -- DANGER WILL ROBINSON!!!'
        body = "Something has gone really wrong here.\n\n"
        body << $!.inspect
      end
      send_email subject, body
    end

    desc 'show-accounts', 'shows the currently configured accounts'
    def show_accounts
      puts "Accounts"
      puts "--------"
      puts Config.accounts.keys.join("\n")
      puts
    end

    desc 'show-instances', 'show available instance names for an account'
    option :account, :required => true, :desc => 'specify account'
    def show_instances
      VfSnapshots::Config.options = options
      Account.for_each(options[:account]) do |account|
        begin
          # printf "%-20s %s\n", value_name, value
          fields = {
            'Instance ID' => 'instance.id',
            'Status'      => 'instance.state.name',
            'Name'        => "instance.tags.select{|tag| tag.key == 'Name'}.first.value",
            'Public IP'   => 'instance.public_ip_address',
            'Private IP'  => 'instance.private_ip_address',
          }
          puts "Account: #{account.name}"
          puts
          output = []
          widths = []
          account.ec2.instances.each do |instance|
            line = []
            fields.values.collect { |f| eval(f) }.each_with_index do |f,idx|
              widths[idx] = [ widths[idx].to_i, f.respond_to?(:length) ? f.length : 20 ].max
              line << f
            end
            output << line
          end

          div = ''
          widths.each do |width|
            div << '-'*width
            div << ' '
          end
          widths = widths.collect { |w| "%-#{w.to_s}s" }.join(' ') + "\n"
          printf widths, *fields.keys
          puts div
          output.each do |line|
            printf widths, *line
          end
          puts

        rescue Aws::EC2::Errors::AuthFailure
          puts "INVALID AUTHENTICATION"
          puts
        end
      end
    end

    desc 'show-snapshots', 'show available snapshots for an instance'
    option :account, :required => true, :desc => 'show snapshots for an instance'
    option :name, :required => true, :desc => 'instance name'
    option :snapshot_filter, :desc => "beginning snapshot desc to use, partial is ok, i.e. '2014090412', use 'show-snapshots' command to find"
    def show_snapshots
      VfSnapshots::Config.options = options
      account = Account.new(options[:account])
      instance = account.find_instance_by_name(options[:name])

#          widths = widths.collect { |w| "%-#{w.to_s}s" }.join(' ') + "\n"
#          printf widths, *fields.keys
      widths = [ 20,20,20 ]
      data = []
      instance.volumes.each do |volume|
        volume.snapshots.each do |snapshot|
          line = [ snapshot.id, Rainbow(snapshot.start_time).blue, Rainbow(snapshot.description).yellow ]
          data << line
          line.each_with_index do |l,idx|
            widths[idx] = [ widths[idx], l.length ].max
          end
        end
      end

      printf "\n%-#{widths[0].to_s}s %-#{widths[1].to_s}s %-#{widths[2].to_s}s\n", 'ID', Rainbow('START TIME').blue, Rainbow('DESC').yellow

      data.each do |line|
        printf "%-#{widths[0].to_s}s %-#{widths[1].to_s}s %-#{widths[2].to_s}s\n", *line
      end
      puts
    end

    desc 'clone-instance', 'clone a instance and its volumes'
    option :verbose, :type => :boolean, :default => true
    option :account, :required => true, :desc => 'account name, use show-accounts to view all configured accounts'
    option :name, :required => true, :desc => 'instance name'
    option :snapshot_filter, :desc => "beginning snapshot desc to use, partial is ok, i.e. '2014090412', use 'show-snapshots' command to find"
    option :date
    option :security_group_id, :required => false, :desc => "optional security group id override, useful when moving an instance into a vpc.  can be 'none' to not specify at all."
    option :subnet_id, :required => false, :desc => "optional subnet id, useful when moving an instance into a vpc"

    def clone_instance
      VfSnapshots::Config.options = options
      account = Account.new(options[:account])
      instance = account.find_instance_by_name(options[:name])
      instance.clone
    end

    desc 'test_email', 'send a test email'
    option :emails, :desc => 'comma-separated list of email recipients of the test.'
    option :no_emails, :type => :boolean, :desc => 'suppress email output'

    option :verbose, :type => :boolean
    def test_email
      VfSnapshots::Config.options = options
      send_email 'This is a test email', "\n\nThis is a test email to confirm the AwsSnapshot gem bin can send email.\n"
      VfSnapshots::verbose "\n"
    end

    desc 'prune', 'prune old snapshots'
    option :keep, :desc => 'number of old snapshots to keep, not including monthlies', :default => DEFAULT_BACKUP_DAYS
    option :keep_monthly, :desc => 'number of old snapshots to keep from the 1st of the month', :default => 3
    option :dry_run, :type => :boolean, :desc => "don't actually prune anything, just tell us what would be deleted"
    option :old_format, :type => :boolean, :desc => "also find snapshots using the original format.  this option will be removed when all of the olds are gone"
    option :verbose, :type => :boolean
    def prune
      VfSnapshots::Config.options = options
      total_deleted = {}
      Account.for_each(options[:account]) do |account|
        begin
          total_deleted[account.name] = 0
          VfSnapshots::verbose "\n"
          VfSnapshots::verbose "ACCOUNT: #{account.name}"
          account.volumes.each do |volume|
            dailies = []
            monthlies = []
            volume.snapshots.each do |snapshot|
              # determine if this is 'our' snapshot
              # by checking for timestamp at start of desc.
              # TODO use a dedicated tag
              if (/^(\d{6})(\d{2})(\d{6})\s/ =~ snapshot.description) || (options[:old_format] && /^(\d{4})-(\d{2})-(\d{2})\s/ =~ snapshot.description)
                if $2 == '01' # we got a monthly
                  monthlies << snapshot
                else
                  dailies << snapshot
                end
              end
            end
            dailies.sort! { |a,b| b.description.slice(0,14) <=> a.description.slice(0,14) }
            monthlies.sort! { |a,b| b.description.slice(0,14) <=> a.description.slice(0,14) }
            tbe = dailies.slice(options[:keep].to_i,99999).to_a + monthlies.slice(options[:keep_monthly].to_i,99999).to_a

            VfSnapshots::verbose "#{volume.name} | #{tbe.length} for deletion"
            total_deleted[account.name] += tbe.length
            if options[:dry_run]
              VfSnapshots::verbose "Not deleting, --dry-run:"
              VfSnapshots::verbose tbe.collect(&:description).inspect
            else
              tbe.each do |s|
                begin
                  s.delete
                rescue
                  puts "Error deleting snapshot: #{$!}"
                end
              end
            end
          end
          VfSnapshots::verbose "Total account deletions: #{ total_deleted[account.name].to_s }"
        rescue Aws::EC2::Errors::AuthFailure
          vmsg = Rainbow("X #{account.name}: INVALID AUTHENTICATION").magenta
          puts vmsg
        end
      end
      VfSnapshots::verbose "\n"
      VfSnapshots::verbose "Total deletions: #{ total_deleted.values.inject{|sum,x| sum + x } }"
      VfSnapshots::verbose "\n"

    end

    desc 'show-orphans', 'show snapshots not associated with volumes'
    # option :old_format, :type => :boolean, :desc => "also find snapshots using the original format.  this option will be removed when all of the olds are gone"
    option :verbose, :type => :boolean
    option :account, :desc => 'account name, use show-accounts to view all configured accounts'
    option :delete, :type => :boolean
    def show_orphans
      VfSnapshots::Config.options = options
      orphans = []
      Account.for_each(options[:account]) do |account|
        begin
          VfSnapshots::verbose "\n"
          VfSnapshots::verbose "ACCOUNT: #{account.name}"
          # puts account.volumes.collect { |v| v.attachment.inspect }
          VfSnapshots::verbose "\nGetting all volumes for account, might be slow..."
          all_volume_ids = account.volumes.collect { |v| v.ec2_volume.id }
          VfSnapshots::verbose "All Volume IDs: #{all_volume_ids.inspect}"

          VfSnapshots::verbose "\nGetting all snapshots for account, might be slow..."
          all_snapshots = account.snapshots
          VfSnapshots::verbose "\nSnapshot count: #{all_snapshots.count}"

          VfSnapshots::verbose "\nFinding orphans..."
          orphan_snapshots = all_snapshots.select { |s| !all_volume_ids.include?(s.volume_id) }
          VfSnapshots::verbose "\nFound orphans (#{orphan_snapshots.length}), getting details.\n"
          results = []
          orphan_snapshots.each do |orphan_snapshot|
            results << {
                         snapshot: orphan_snapshot,
                         snapshot_id: orphan_snapshot.id,
                         #snapshot_name: orphan_snapshot.tags.to_h['Name'],
                         volume_id: orphan_snapshot.volume_id,
                         #volume_name: orphan_snapshot.volume.tags.to_h['Name']
                         start_date: orphan_snapshot.start_time.to_date,
            }
          end
          deleted_count = 0
          results.sort { |a,b| a[:volume_id] <=> b[:volume_id] }.each_with_index do |orphan_snapshot,idx|
            if options[:delete]
              begin
                orphan_snapshot[:snapshot].delete
                puts "[#{idx}] #{orphan_snapshot[:start_date]} DELETED volume_id:#{orphan_snapshot[:volume_id]} snapshot_id:#{orphan_snapshot[:snapshot_id]}"
                deleted_count += 1
              rescue
                puts "[#{idx}] #{orphan_snapshot[:start_date]} ERROR DELETING: volume_id:#{orphan_snapshot[:volume_id]} snapshot_id:#{orphan_snapshot[:snapshot_id]}"
                puts "[#{idx}] ERROR: #{$!}"
              end
            else
              puts "[#{idx}] #{orphan_snapshot[:start_date]} volume_id:#{orphan_snapshot[:volume_id]} snapshot_id:#{orphan_snapshot[:snapshot_id]}"
            end
          end

          puts
          puts "Total Snapshots: #{all_snapshots.length}"
          puts "Orphaned Snapshots: #{results.length}"
          puts "Deleted Snapshots: #{deleted_count}"
          puts

        rescue Aws::EC2::Errors::AuthFailure
          vmsg = Rainbow("X #{account.name}: INVALID AUTHENTICATION").magenta
          puts vmsg
        end
      end
      VfSnapshots::verbose "\n"

    end

    desc 'backup', 'sync snapshots with backup account, if provided'
    option :dry_run, :type => :boolean, :desc => 'just show the backup info'
    option :account, :desc => 'account name, use show-accounts to view all configured accounts'
    option :verbose, :type => :boolean, :desc => 'tell me more stuff!'
    def backup
      VfSnapshots::Config.options = options
      orphans = []
      Account.for_each(options[:account]) do |account|
        begin
          VfSnapshots::verbose "\n"
          VfSnapshots::verbose "ACCOUNT: #{account.name}"

          if account.has_backup?
            backup = Backup.new(account)
            missing = backup.enumerate_missing
            if options[:dry_run]
              VfSnapshots::verbose "Snapshots to backup: #{missing.length}"
              missing.each do |m|
                VfSnapshots::verbose "[#{idx+1} of #{missing.lenfth} #{m.description}"
              end
            else
              backup.copy_snapshots! missing unless options[:dry_run]
            end
          end

        rescue Aws::EC2::Errors::AuthFailure
          vmsg = Rainbow("X #{account.name}: INVALID AUTHENTICATION").magenta
          puts vmsg
        end
      end
      VfSnapshots::verbose "\n"

    end

    # at present backup prune casts a wide net, and deletes ALL snapshots
    # whose descriptions match the basic regex
    # on the backup account that are older than backup[:days].  be careful!
    desc 'backup-prune', 'prune backup account, if provided'
    option :dry_run, :type => :boolean, :desc => 'just show the backup snapshots to be pruned'
    option :account, :desc => 'account name, use show-accounts to view all configured accounts'
    option :verbose, :type => :boolean, :desc => 'tell me more stuff!'
    def backup_prune
      VfSnapshots::Config.options = options
      orphans = []
      Account.for_each(options[:account]) do |account|
        begin
          VfSnapshots::verbose "\n"
          VfSnapshots::verbose "ACCOUNT: #{account.name}"

          if account.has_backup?
            backup = Backup.new(account)
            prunees = backup.enumerate_snapshots_to_be_pruned
            VfSnapshots::verbose "SNAPSHOTS TO PRUNE: #{prunees.length}"
            if options[:dry_run]
              VfSnapshots::verbose "Snapshot backups to prune: #{prunees.length}"
              prunees.each_with_index do |snap,idx|
                VfSnapshots::verbose "[#{idx+1} of #{prunees.length}] #{snap.description}"
              end
            else
              backup.delete! prunees
            end
          end

        rescue Aws::EC2::Errors::AuthFailure
          vmsg = Rainbow("X #{account.name}: INVALID AUTHENTICATION").magenta
          puts vmsg
        end
      end
      VfSnapshots::verbose "\n"

    end

    # at present backup prune casts a wide net, and deletes ALL snapshots
    # whose descriptions match the basic regex
    # on the backup account that are older than backup[:days].  be careful!
    desc 'backup-tag', 'tag snapshots in backup account'
    option :account, :desc => 'account name, use show-accounts to view all configured accounts'
    option :verbose, :type => :boolean, :desc => 'tell me more stuff!'
    def backup_tag
      VfSnapshots::Config.options = options
      orphans = []
      Account.for_each(options[:account]) do |account|
        begin
          VfSnapshots::verbose "\n"
          VfSnapshots::verbose "ACCOUNT: #{account.name}"

          if account.has_backup?
            backup = Backup.new(account)
            backup.tag_accounts!
          end

        rescue Aws::EC2::Errors::AuthFailure
          vmsg = Rainbow("X #{account.name}: INVALID AUTHENTICATION").magenta
          puts vmsg
        end
      end
      VfSnapshots::verbose "\n"
    end

    desc 'version', 'show gem version number'
    def version
      puts "vf-snapshots version #{VfSnapshots::VERSION}"
    end

  end
end


text:
namespace AngleSharp.Dom.Html
{
    using AngleSharp.Extensions;
    using AngleSharp.Html;
    using System;

    /// <summary>
    /// Represents an anchor element.
    /// </summary>
    sealed class HtmlAnchorElement : HtmlUrlBaseElement, IHtmlAnchorElement
    {
        #region ctor

        /// <summary>
        /// Creates a new anchor element.
        /// </summary>
        public HtmlAnchorElement(Document owner, String prefix = null)
            : base(owner, Tags.A, prefix, NodeFlags.HtmlFormatting)
        {
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the character encoding for the target resource.
        /// </summary>
        public String Charset
        {
            get { return this.GetOwnAttribute(AttributeNames.Charset); }
            set { this.SetOwnAttribute(AttributeNames.Charset, value); }
        }

        /// <summary>
        /// Gets or sets the anchor name.
        /// </summary>
        public String Name
        {
            get { return this.GetOwnAttribute(AttributeNames.Name); }
            set { this.SetOwnAttribute(AttributeNames.Name, value); }
        }

        /// <summary>
        /// Gets or sets the text of the anchor tag (same as TextContent).
        /// </summary>
        public String Text
        {
            get { return TextContent; }
            set { TextContent = value; }
        }

        #endregion

        #region Helpers

        public override void DoFocus()
        {
            if (this.HasOwnAttribute(AttributeNames.Href))
                IsFocused = true;
        }

        #endregion
    }
}


text:
using Microsoft.DotNet.InternalAbstractions;

namespace Microsoft.DotNet.Cli.Utils
{
    public class AppBaseCommandResolver : AbstractPathBasedCommandResolver
    {
        public AppBaseCommandResolver(IEnvironmentProvider environment,
            IPlatformCommandSpecFactory commandSpecFactory) : base(environment, commandSpecFactory) { }

        internal override string ResolveCommandPath(CommandResolverArguments commandResolverArguments)
        {
            return _environment.GetCommandPathFromRootPath(
                ApplicationEnvironment.ApplicationBasePath,
                commandResolverArguments.CommandName);
        }

        internal override CommandResolutionStrategy GetCommandResolutionStrategy()
        {
            return CommandResolutionStrategy.BaseDirectory;
        }
    }
}


text:
using System;

namespace NoesisLabs.Elve.VenstarColorTouch.Models
{
	public class Sensor
	{
		public int Humidity { get; set; }
		public string Name { get; set; }
		public double Temperature { get; set; }
	}
}


text:
module client {
    requires jakarta.xml.ws;

      requires java.logging;

    // generated by WsimportTool
    exports client.dispatch.header.doclit;
    exports client.dispatch.header.doclit.client;
}


text:
package application;

public class Icons {

	private Icons(){}

	 public static final String USER_ICON = "\uf2bd";

}


text:
package org.cronhub.managesystem.modules.record.done.action;

import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.cronhub.managesystem.commons.dao.bean.TaskRecordDone;
import org.cronhub.managesystem.commons.params.Params;
import org.cronhub.managesystem.commons.thrift.process.RemoteExecutCmdProcessor;
import org.cronhub.managesystem.commons.utils.PageIOUtils;

import javax.servlet.http.HttpServletRequest;

public class RemoteExecuteCallerAction extends ActionSupport{
	private RemoteExecutCmdProcessor processor;

	public void setProcessor(RemoteExecutCmdProcessor processor) {
		this.processor = processor;
	}

	public String remoteExecute(){
		HttpServletRequest req = ServletActionContext.getRequest();
		final Long id = Long.valueOf(req.getParameter("id"));
		final String tableName = req.getParameter("tableName");
		TaskRecordDone record = null;
		try {
			record = this.processor.remoteExecute(id,tableName,Params.EXECTYPE_BTNREDO);
		} catch (Exception e) {
			PageIOUtils.printToPage(e.getMessage());
			e.printStackTrace();
		}
		if(record == null){
			return NONE;
		}
		JSONObject ajaxJson = new JSONObject();
		ajaxJson.put(Params.PAGE_RECORD_COMPLETE_STATS, record.getComplete_success_ISO());
		ajaxJson.put(Params.PAGE_RECORD_DURATION, record.getDuration_ISO());
		ajaxJson.put(Params.PAGE_RECORD_EXIT_CODE, record.getExit_code_ISO());
		ajaxJson.put(Params.PAGE_RECORD_END_DATETIME,record.getEnd_datetime_ISO());
		ajaxJson.put(Params.PAGE_RECORD_EXEC_TYPE, record.getExec_type_ISO());
		ajaxJson.put(Params.PAGE_RECORD_EXEC_RETURN_STR, record.getExec_return_str());
		ajaxJson.put(Params.PAGE_RECORD_START_DATETIME, record.getStart_datetime_ISO());
		ajaxJson.put("id",id);//这里把id放回去是为了前端ajax多线程并发的时候(ajax自身在并发的时候回调函数会混乱调错),ajax回调函数不至于找错行。
		PageIOUtils.printToPage(ajaxJson.toString());
		return NONE;
	}
}


text:
using System.Xml.Linq;

namespace VimeoSharp.Simple {

	[XmlElement (ElementName="user")]
	public class User {

		public User ()
		{
		}

		[XmlElement (ElementName="id",
		             ConversionType=ConversionType.Integer)]
		public int Id {
			get;
			set;
		}

		[XmlElement (ElementName="display_name")]
		public string DisplayName {
			get;
			set;
		}

		// TODO: use datatime
		[XmlElement (ElementName="created_on")]
		public string CreatedOn {
			get;
			set;
		}

		[XmlElement (ElementName="is_staff",
		             ConversionType=ConversionType.Boolean)]
		public bool IsStaff {
			get;
			set;
		}

		[XmlElement (ElementName="is_plus",
		             ConversionType=ConversionType.Boolean)]
		public bool IsPlus {
			get;
			set;
		}

		[XmlElement (ElementName="location")]
		public string Location {
			get;
			set;
		}

		[XmlElement (ElementName="url")]
		public string Url {
			get;
			set;
		}

		[XmlElement (ElementName="bio")]
		public string Bio {
			get;
			set;
		}

		[XmlElement (ElementName="profile_url")]
		public string ProfileUrl {
			get;
			set;
		}

		[XmlElement (ElementName="videos_url")]
		public string VideosUrl {
			get;
			set;
		}

		[XmlElement (ElementName="total_videos_uploaded",
		             ConversionType=ConversionType.Integer)]
		public int TotalVideosUploaded {
			get;
			set;
		}

		[XmlElement (ElementName="total_videos_appears_in",
		             ConversionType=ConversionType.Integer)]
		public int TotalVideoAppearsIn {
			get;
			set;
		}

		[XmlElement (ElementName="total_videos_liked",
		             ConversionType=ConversionType.Integer)]
		public int TotalVideosLiked {
			get;
			set;
		}

		[XmlElement (ElementName="total_contacts",
		             ConversionType=ConversionType.Integer)]
		public int TotalContacts {
			get;
			set;
		}

		[XmlElement (ElementName="total_albums",
		             ConversionType=ConversionType.Integer)]
		public int TotalAlbums {
			get;
			set;
		}

		[XmlElement (ElementName="total_channels",
		             ConversionType=ConversionType.Integer)]
		public int TotalChannels {
			get;
			set;
		}

		[XmlElement (ElementName="portrait_small")]
		public string PortraitSmall {
			get;
			set;
		}

		[XmlElement (ElementName="portrait_medium")]
		public string PortraitMedium {
			get;
			set;
		}

		[XmlElement (ElementName="portrait_large")]
		public string PortraitLarge {
			get;
			set;
		}
	}
}


text:
#pragma once

#include <dtkCore/dtkPlugin.h>
#include <itkFiltersPluginExport.h>

class ITKFILTERSPLUGIN_EXPORT itkFiltersPluginPrivate;

class ITKFILTERSPLUGIN_EXPORT itkFiltersPlugin : public dtkPlugin
{
    Q_OBJECT
    Q_INTERFACES(dtkPlugin)

public:
    itkFiltersPlugin(QObject *parent = 0);
    ~itkFiltersPlugin();

    virtual bool initialize();
    virtual bool uninitialize();

    virtual QString contact() const;
    virtual QString description() const;
    virtual QString name() const;
    virtual QString version() const;
    virtual QStringList authors() const;
    virtual QStringList contributors() const;
    virtual QStringList dependencies() const;

    virtual QStringList tags() const;
    virtual QStringList types() const;

private:
    itkFiltersPluginPrivate *d;
};


text:
package paladin

import (
	"strings"
	"sync/atomic"
)

// keyNamed key naming to lower case.
func keyNamed(key string) string {
	return strings.ToLower(key)
}

// Map is config map, key(filename) -> value(file).
type Map struct {
	values atomic.Value
}

// Store sets the value of the Value to values map.
func (m *Map) Store(values map[string]*Value) {
	dst := make(map[string]*Value, len(values))
	for k, v := range values {
		dst[keyNamed(k)] = v
	}
	m.values.Store(dst)
}

// Load returns the value set by the most recent Store.
func (m *Map) Load() map[string]*Value {
	return m.values.Load().(map[string]*Value)
}

// Exist check if values map exist a key.
func (m *Map) Exist(key string) bool {
	_, ok := m.Load()[keyNamed(key)]
	return ok
}

// Get return get value by key.
func (m *Map) Get(key string) *Value {
	v, ok := m.Load()[keyNamed(key)]
	if ok {
		return v
	}
	return &Value{}
}

// Keys return map keys.
func (m *Map) Keys() []string {
	values := m.Load()
	keys := make([]string, 0, len(values))
	for key := range values {
		keys = append(keys, key)
	}
	return keys
}


text:
<?php

class Ai1wm_Storage_Exception extends Exception {

}


text:
/* globals Accounts, renderToDiv, clickElement, DomUtils, AccountsAddService,
   WorkaroundIssue5110
 */
"use strict";

if (Meteor.isServer) {
  var attemptCallbackStopper;
  Meteor.methods({
    removeUser: function (email) {
      Meteor.users.remove({
        'emails[0].address': email
      });
    },
    addAttemptCallback: function (msg) {
      attemptCallbackStopper = Accounts.validateLoginAttempt(function () {
        if (msg) {
          throw new Meteor.Error(Accounts.LoginCancelledError.numericError,
            msg);
        }
        return true;
      });
    },
    removeAttemptCallback: function () {
      if (attemptCallbackStopper) {
        attemptCallbackStopper.stop();
      }
      attemptCallbackStopper = undefined;
    }
  });
}

if (Meteor.isClient) {
  Tinytest.add(
    'brettle:workaround-issue-5110 - unit test',
    function (test) {
      var albs = Accounts._loginButtonsSession;
      var closeDropdown = albs.closeDropdown;
      var closeDropdownCalls = 0, expectedCloseDropdownCalls = 0;
      Accounts._loginButtonsSession.closeDropdown = function (/* arguments */) {
        closeDropdownCalls++;
        return closeDropdown.apply(Accounts._loginButtonsSession, arguments);
      };
      albs.errorMessage('Message to ignore');
      test.equal(closeDropdownCalls, expectedCloseDropdownCalls,
        'before addIgnoredMessage()'
      );

      WorkaroundIssue5110.addIgnoredMessage('Message to ignore');
      albs.errorMessage('Message to ignore');
      expectedCloseDropdownCalls++;
      test.equal(closeDropdownCalls, expectedCloseDropdownCalls,
        'after addIgnoredMessage()'
      );

      WorkaroundIssue5110.removeIgnoredMessage('Message to ignore');
      albs.errorMessage('Message to ignore');
      test.equal(closeDropdownCalls, expectedCloseDropdownCalls,
        'after removeIgnoredMessage()');
    }
  );

  Tinytest.addAsync(
    'brettle:workaround-issue-5110 - acceptance test',
    function (test, done) {
      var loginFailureStopper;
      var div;
      WorkaroundIssue5110.addIgnoredMessage("message to ignore");
      Meteor.logout(function (error) {
        test.isUndefined(error, 'Unexpected error during logout');
        removeUser();
      });
      function removeUser() {
        Meteor.call('removeUser', 'testuser5110@example.com', function (error) {
          test.isUndefined(error, 'Unexpected error in removeUser');
          addAttemptCallback();
        });
      }
      function addAttemptCallback() {
        Meteor.call('addAttemptCallback',
          "message to ignore",
          function (error) {
            test.isUndefined(error, 'Unexpected error in addAttemptCallback');
            createUser();
          }
        );
      }
      function createUser() {
        div = renderToDiv(Template.loginButtons);
        document.body.appendChild(div);
        Tracker.flush();
        clickElement(div.querySelector('#login-sign-in-link'));
        Tracker.flush();
        var signUpLink = div.querySelector('#signup-link');
        if (signUpLink) {
          clickElement(signUpLink);
        }
        DomUtils.setElementValue(div.querySelector('#login-email'),
          'testuser5110@example.com');
        DomUtils.setElementValue(div.querySelector('#login-password'),
          'password');
        clickElement(div.querySelector('#login-buttons-password'));
        loginFailureStopper = Accounts.onLoginFailure(updatePage);
      }
      function updatePage() {
        loginFailureStopper.stop();
        Tracker.flush();
        Meteor.setTimeout(checkDropdown, 0);
      }
      function checkDropdown() {
        var errorMessageElem = div.querySelector('.error-message');
        test.isNull(errorMessageElem, 'There should not be an error message');
        var loginDropdownListElem = div.querySelector('#login-dropdown-list');
        test.isNull(loginDropdownListElem, 'The dropdown should be closed');
        cleanUp();
      }
      function cleanUp() {
        document.body.removeChild(div);
        WorkaroundIssue5110.removeIgnoredMessage("message to ignore");
        Meteor.call('removeAttemptCallback', function (error) {
          test.isUndefined(error, 'Unexpected error in removeAttemptCallback');
          done();
        });
      }
    }
  );
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE390_Error_Without_Action__fopen_08.c
Label Definition File: CWE390_Error_Without_Action.label.xml
Template File: point-flaw-08.tmpl.c
*/
/*
 * @description
 * CWE: 390 Detection of Error Condition Without Action
 * Sinks: fopen
 *    GoodSink: Check to see if fopen() failed and handle errors properly
 *    BadSink : Check to see if fopen() failed, but fail to handle errors
 * Flow Variant: 08 Control flow: if(staticReturnsTrue()) and if(staticReturnsFalse())
 *
 * */

#include "std_testcase.h"

/* The two function below always return the same value, so a tool
   should be able to identify that calls to the functions will always
   return a fixed value. */
static int staticReturnsTrue()
{
    return 1;
}

static int staticReturnsFalse()
{
    return 0;
}

#ifndef OMITBAD

void CWE390_Error_Without_Action__fopen_08_bad()
{
    if(staticReturnsTrue())
    {
        {
            FILE * fileDesc = NULL;
            fileDesc = fopen("file.txt", "w+");
            /* FLAW: Check to see if fopen failed, but do nothing about it */
            if (fileDesc == NULL)
            {
                /* do nothing */
            }
            fclose(fileDesc);
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* good1() uses if(staticReturnsFalse()) instead of if(staticReturnsTrue()) */
static void good1()
{
    if(staticReturnsFalse())
    {
        /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
        printLine("Benign, fixed string");
    }
    else
    {
        {
            FILE * fileDesc = NULL;
            fileDesc = fopen("file.txt", "w+");
            /* FIX: Check to see if fopen failed and handle the error */
            if (fileDesc == NULL)
            {
                printLine("fopen() failed");
                exit(1);
            }
            fclose(fileDesc);
        }
    }
}

/* good2() reverses the bodies in the if statement */
static void good2()
{
    if(staticReturnsTrue())
    {
        {
            FILE * fileDesc = NULL;
            fileDesc = fopen("file.txt", "w+");
            /* FIX: Check to see if fopen failed and handle the error */
            if (fileDesc == NULL)
            {
                printLine("fopen() failed");
                exit(1);
            }
            fclose(fileDesc);
        }
    }
}

void CWE390_Error_Without_Action__fopen_08_good()
{
    good1();
    good2();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE390_Error_Without_Action__fopen_08_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE390_Error_Without_Action__fopen_08_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
using System;
using System.Collections.Generic;
using System.Linq;

using Nucleo.Collections;

namespace Nucleo.Orm.Validation
{
	/// <summary>
	/// Represents the collection of validation rules.
	/// </summary>
	public class ValidationRuleCollection : SimpleCollection<IValidationRule>
	{
		/// <summary>
		/// Adds a range of rules to the collection.
		/// </summary>
		/// <param name="rules">The rules to add.</param>
		public void AddRange(IEnumerable<IValidationRule> rules)
		{
			Guard.NotNull(rules);

			foreach (var rule in rules)
				this.Add(rule);
		}
	}
}


text:
---
title: Personal Notes on getting adafruit Trinket to work on Ubuntu 14.04
date: 2014-07-31 00:00:00 Z
categories:
- blog
tags:
- mug
layout: post
---

I bought a couple of [adafruit Trinket](https://learn.adafruit.com/introducing-trinket/introduction) some time ago, but i got the time to work on them only yesterday.

![trinket]({{ site.url }}/assets/trinket.jpg)

As described in their [manual](https://learn.adafruit.com/introducing-trinket/introduction), Linux (and arduino 1.5) is not supported, because sometimes the kernel does not create the device node when trinket is inserted in the usbport.

I suspect the problem lies in the fact that trinket uses only attiny85, and implements the usb stack in software. so probably a subtle bug in linux or in the trinket prevents a proper handshake.

The first time i tried using this board, i was using Ubuntu 13.10, and i believe i had the same problem. Having Upgraded to Ubuntu 14.04, i hoped the situation somewhat improved, as it did.
Now running

	lsusb

return also

	Bus 003 Device 032: ID 1781:0c9f Multiple Vendors USBtiny

which is the right vendorId:productId identifier, and rightly indicates that the device is a USBtiny programmer.

The guide [here](https://learn.adafruit.com/introducing-trinket/setting-up-with-arduino-ide) gives instruction to substitute the installed avrdude.conf with their avrdude.conf, but mine version seems more recent than theirs, so i opted to integrate the changes using [meld](http://meldmerge.org/), a visual merge tool. in the end, the important differences are some valors inside the ATtiny85 section, so it's easier to copy the adafruit's section inside the local version.

first we have to find where avrdude.conf is installed.
the command

	$ find / -name "avrdude.conf" 2>/dev/null

search for `avrdude.conf` from the root. `2>/dev/null` discard every error message about denied permission to read a subdirectory.

on my pc, avrdude.conf is installed in two places: `/etc/avrdude.conf` and `/usr/share/arduino/hardware/tools/avrdude.conf`. To be sure, i will patch them both.

the adafruit's file contains a section, started by

	#------------------------------------------------------------
	# ATtiny85
	#------------------------------------------------------------

that describes the parameters to work with the chip. I just copy the section from this header to the next and substitute it to the equivalent section inside the local copies. For simplicity, this is the part with the correct values to write inside the local copies:

[https://gist.github.com/andijcr/f4a660fde4035fb0a3aa](https://gist.github.com/andijcr/f4a660fde4035fb0a3aa)

remember that you have to be root to modify your local copies.

After patching the avrdude conf the command

	$ sudo avrdude -c usbtiny -p m8

returns

	avrdude: AVR device initialized and ready to accept instructions

	Reading | ################################################## | 100% 0.00s

	avrdude: Device signature = 0x1e930b
	avrdude: Expected signature for ATmega8 is 1E 93 07
			 Double check chip, or use -F to override this check.

	avrdude done.  Thank you.

this means that the trinket should be ready to be programmed!

let's fire up the blink program, from the examples:

{% highlight c++ %}
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain.

To upload to your Gemma or Trinket:
1) Select the proper board from the Tools->Board Menu
2) Select USBtinyISP from the Tools->Programmer
3) Plug in the Gemma/Trinket, make sure you see the green LED lit
4) For windows, install the USBtiny drivers
5) Press the button on the Gemma/Trinket - verify you see
the red LED pulse. This means it is ready to receive data
6) Click the upload button above within 10 seconds
*/
int led = 1; // blink 'digital' pin 1 - AKA the built in red LED

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
	pinMode(led, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
	digitalWrite(led, HIGH);
	delay(1000);
	digitalWrite(led, LOW);
	delay(1000);
}
{% endhighlight %}

as avrdude still requires root to use the device, i use the arduino ide to verify the code. this action produces an uploadable hex in the temp build folder. grab the binary - named sketch_jul30a.cpp.hex in my case - and the command to write the program is this (remember to enter bootloader mode):

	$ sudo avrdude  -c usbtiny -p attiny85 -U flash:w:sketch_jul30a.cpp.hex

if successful:

![yay]({{ site.url }}/assets/blink.gif)

What remains to be done?

working as root to upload a sketch is cumbersome. by adding the correct rules (following [this](http://mightyohm.com/blog/2010/03/run-avrdude-without-root-privs-in-ubuntu/) with some corrections from [this](http://forums.linuxmint.com/viewtopic.php?f=58&t=116115)) is it possible to use avrdude as user, and upload the sketch directly from the arduino ide.

the first step is to add a new rule to /etc/udev/rules.d, and then reload the udev daemon.

{% highlight bash %}
#as root:

$ echo 'SUBSYSTEM=="usb", ATTR{idVendor}=="1781", ATTR{idProduct}=="0c9f", MODE="0666", GROUP="plugdev"' > /etc/udev/rules.d/99-trinket.rules
$ restart udev

{% endhighlight %}

note that the `GROUP` attribute is set to `plugdev`
this value is the name of a group which my user is part of. to know which groups your user belongs, you can run the command

	groups [your user]

and choose an appropriate value.

after doing this, running

	$ avrdude -c usbtiny -p m8

in bootloader mode should give the same result as the `sudo` version.

finally, we can use the arduino ide to upload the blink sketch.


text:
package com.jukusoft.jbackendengine.backendengine;

import com.jukusoft.jbackendengine.backendengine.authentification.IUserManager;
import com.jukusoft.jbackendengine.backendengine.authentification.UserAuthentificationMode;
import com.jukusoft.jbackendengine.backendengine.manager.IManager;
import com.jukusoft.jbackendengine.backendengine.notification.INotificationManager;
import com.jukusoft.jbackendengine.backendengine.serversettings.impl.LocalServerSettings;
import com.jukusoft.jbackendengine.backendengine.database.IDatabaseConnectorManager;
import com.jukusoft.jbackendengine.backendengine.database.impl.DefaultDatabaseConnectorManager;
import com.jukusoft.jbackendengine.backendengine.logger.ILoggerManager;
import com.jukusoft.jbackendengine.backendengine.logger.impl.DefaultLoggerManager;
import com.jukusoft.jbackendengine.backendengine.manager.exception.IManagerNotFoundException;
import com.jukusoft.jbackendengine.backendengine.module.IModule;
import com.jukusoft.jbackendengine.backendengine.module.IModuleManager;
import com.jukusoft.jbackendengine.backendengine.module.impl.DefaultModuleManager;
import com.jukusoft.jbackendengine.backendengine.notification.impl.DefaultNotificationManager;
import com.jukusoft.jbackendengine.backendengine.serversettings.IServerSettings;
import com.jukusoft.jbackendengine.backendengine.service.IService;
import com.jukusoft.jbackendengine.backendengine.service.exception.IServiceNotFoundException;
import com.jukusoft.jbackendengine.backendengine.sessionstore.ISessionStore;
import com.jukusoft.jbackendengine.backendengine.sessionstore.impl.LocalSessionStore;
import com.jukusoft.jbackendengine.backendengine.task.ITaskManager;
import com.jukusoft.jbackendengine.backendengine.task.impl.DefaultTaskManager;
import com.jukusoft.jbackendengine.backendengine.uniqueID.IUniqueUserIDGenerator;
import com.jukusoft.jbackendengine.backendengine.validation.exception.ModuleAccessNotPermittedException;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Justin on 02.07.2015.
 */
public abstract class AbstractBackendEngine implements IEditableBackendEngine {

    protected int BUILD_NUMBER = 2;
    private final String backendEngineVersion = "1.0.0";

    protected IUserManager userManager = null;
    private ISessionStore sessionStore = null;
    private IServerSettings localSettings = null;
    private IServerSettings distributedSettings = null;
    private ITaskManager taskManager = null;
    private IUniqueUserIDGenerator uniqueUserIDGenerator = null;
    private INotificationManager notificationManager = null;
    private IModuleManager moduleManager = null;
    private IDatabaseConnectorManager databaseConnectorManager = null;
    private ILoggerManager loggerManager = null;
    private Map<String,IManager> managerMap = new HashMap<String,IManager>();
    private Map<String,IService> serviceMap = new HashMap<String,IService>();
    private Long serverID = 0l;
    private Map<String,Object> dataMap = new HashMap<String,Object>();

    public AbstractBackendEngine(IServerSettings localSettings) {
        this.localSettings = localSettings;

        int corePoolSize = this.localSettings.getInteger("TaskManager.corePoolSize", 4);
        int maxPoolSize = this.localSettings.getInteger("TaskManager.maxPoolSize", 8);
        int schedulerPoolSize = this.localSettings.getInteger("TaskManager.schedulerPoolSize", 4);

        this.taskManager = new DefaultTaskManager(corePoolSize, maxPoolSize, schedulerPoolSize);
        this.sessionStore = new LocalSessionStore(this);
        this.notificationManager = new DefaultNotificationManager();
        this.moduleManager = new DefaultModuleManager(this);
        this.databaseConnectorManager = new DefaultDatabaseConnectorManager();
        this.loggerManager = new DefaultLoggerManager();
    }

    public AbstractBackendEngine(File configDir) {
        if (!configDir.exists()) {
            configDir.mkdirs();
        }

        this.localSettings = new LocalServerSettings(configDir);
        this.loggerManager = new DefaultLoggerManager();
        this.databaseConnectorManager = new DefaultDatabaseConnectorManager();
        this.moduleManager = new DefaultModuleManager(this);

        int corePoolSize = this.localSettings.getInteger("TaskManager.corePoolSize", 4);
        int maxPoolSize = this.localSettings.getInteger("TaskManager.maxPoolSize", 8);
        int schedulerPoolSize = this.localSettings.getInteger("TaskManager.schedulerPoolSize", 4);

        this.taskManager = new DefaultTaskManager(corePoolSize, maxPoolSize, schedulerPoolSize);
        this.sessionStore = new LocalSessionStore(this);
        this.notificationManager = new DefaultNotificationManager();
    }

    @Override
    public int getBuildNumber() {
        return this.BUILD_NUMBER;
    }

    @Override
    public void setBuildNumber(int BUILD_NUMBER) {
        this.BUILD_NUMBER = BUILD_NUMBER;
    }

    @Override
    public String getBackendEngineVersion() {
        return this.backendEngineVersion;
    }

    @Override
    public IUserManager getUserManager(UserAuthentificationMode authentificationMode) {
        return this.userManager;
    }

    @Override
    public void setUserManager(IUserManager userManager) {
        this.userManager = userManager;
    }

    @Override
    public ISessionStore getSessionStore() {
        return this.sessionStore;
    }

    @Override
    public void setSessionStore(ISessionStore sessionStore) {
        this.sessionStore = sessionStore;
    }

    @Override
    public IServerSettings getLocalSettings() {
        return this.localSettings;
    }

    @Override
    public void setLocalSettings(IServerSettings serverSettings) {
        this.localSettings = serverSettings;
    }

    @Override
    public IServerSettings getDistributedSettings() {
        return this.distributedSettings;
    }

    @Override
    public void setDistributedSettings(IServerSettings serverSettings) {
        this.distributedSettings = serverSettings;
    }

    @Override
    public ITaskManager getTaskManager() {
        return this.taskManager;
    }

    @Override
    public void setTaskManager(ITaskManager taskManager) {
        this.taskManager = taskManager;
    }

    @Override
    public IUniqueUserIDGenerator getUniqueUserIDGenerator() {
        return this.uniqueUserIDGenerator;
    }

    @Override
    public void setUniqueUserIDGenerator(IUniqueUserIDGenerator uniqueUserIDGenerator) {
        this.uniqueUserIDGenerator = uniqueUserIDGenerator;
    }

    @Override
    public INotificationManager getNotificationManager() {
        return this.notificationManager;
    }

    @Override
    public void setNotificationManager(INotificationManager notificationManager) {
        this.notificationManager = notificationManager;
    }

    @Override
    public Long getServerID() {
        return this.serverID;
    }

    @Override
    public void setServerID(Long serverID) {
        this.serverID = serverID;
    }

    @Override
    public IModuleManager getModuleManager() {
        return this.moduleManager;
    }

    @Override
    public void setModuleManager(IModuleManager moduleManager) {
        this.moduleManager = moduleManager;
    }

    @Override
    public IDatabaseConnectorManager getDatabaseConnectorManager() {
        return this.databaseConnectorManager;
    }

    @Override
    public IEditableBackendEngine requestEditableBackendEngine(IModule module) throws ModuleAccessNotPermittedException {
        return null;
    }

    @Override
    public void setDatabaseConnectorManager(IDatabaseConnectorManager databaseConnectorManager) {
        this.databaseConnectorManager = databaseConnectorManager;
    }

    @Override
    public ILoggerManager getLoggerManager() {
        return this.loggerManager;
    }

    @Override
    public void setLoggerManager(ILoggerManager loggerManager) {
        this.loggerManager = loggerManager;
    }

    @Override
    public void registerManager(String name, IManager manager) {
        this.managerMap.put(name, manager);
    }

    @Override
    public void removeManager(String name) {
        this.managerMap.remove(name);
    }

    @Override
    public IManager getManager(String name) throws IManagerNotFoundException {
        if (this.managerMap.containsKey(name)) {
            return this.managerMap.get(name);
        } else {
            throw new IManagerNotFoundException("IManager " + name + " isnt registered.");
        }
    }

    @Override
    public void setData(String key, Object value) {
        this.dataMap.put(key, value);
    }

    @Override
    public void removeData(String key) {
        this.dataMap.remove(key);
    }

    @Override
    public boolean containsData(String key) {
        return this.dataMap.containsKey(key);
    }

    @Override
    public Object getData(String key) {
        if (this.dataMap.containsKey(key)) {
            return this.dataMap.get(key);
        } else {
            return null;
        }
    }

    @Override
    public String getDataAsString(String key) {
        return (String) this.getData(key);
    }

    @Override
    public void addService(String name, IService service) {
        Thread thread = new Thread(service);
        thread.setDaemon(true);
        thread.start();
        this.serviceMap.put(name, service);
    }

    @Override
    public void removeService(String name) {
        this.serviceMap.remove(name);
    }

    @Override
    public IService getService(String name) throws IServiceNotFoundException {
        if (this.serviceMap.containsKey(name)) {
            return this.serviceMap.get(name);
        } else {
            throw new IServiceNotFoundException("service " + name + " not found.");
        }
    }

    @Override
    public void shutdown() {
        this.getLoggerManager().debug("Shutdown backend engine now.");

        //shutdown all modules
        this.getModuleManager().shutdownAllModules();

        //shutdown task manager
        this.getTaskManager().shutdown();
        this.getTaskManager().terminate();

        //cleanup
    }

    @Override
    public abstract void startEngine(IEditableBackendEngine backendEngine);

    public final void startEngine () {
        this.startEngine(this);
    }
}


text:
// Copyright (c) 2015-2016 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file).
// Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using SharpNav.Collections;
using SharpNav.Geometry;
using SharpNav.Pathfinding;
using System.Reflection;

#if MONOGAME
using Vector3 = Microsoft.Xna.Framework.Vector3;
#elif OPENTK
using Vector3 = OpenTK.Vector3;
#elif SHARPDX
using Vector3 = SharpDX.Vector3;
#endif

namespace SharpNav.IO.Json
{
	/// <summary>
	/// Subclass of NavMeshSerializer that implements
	/// serialization/deserializtion in text files with json format
	/// </summary>
	public class NavMeshJsonSerializer : NavMeshSerializer
	{
		private JsonSerializer serializer;

		//increase this once every time the file format changes.
		private static readonly int FormatVersion = 3;

		public NavMeshJsonSerializer()
		{
			serializer = JsonSerializer.Create(new JsonSerializerSettings()
			{
				ReferenceLoopHandling = ReferenceLoopHandling.Error,
				Converters = new List<JsonConverter>() { new Vector3Converter(), new AreaConverter(), new PolyIdConverter() }
			});
		}

		public override void Serialize(string path, TiledNavMesh mesh)
		{
			JObject root = new JObject();

			root.Add("meta", JToken.FromObject(new
			{
				version = new
				{

					snj = FormatVersion,
					sharpnav = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion
				}
			}));

			root.Add("origin", JToken.FromObject(mesh.Origin, serializer));
			root.Add("tileWidth", JToken.FromObject(mesh.TileWidth, serializer));
			root.Add("tileHeight", JToken.FromObject(mesh.TileHeight, serializer));
			root.Add("maxTiles", JToken.FromObject(mesh.MaxTiles, serializer));
			root.Add("maxPolys", JToken.FromObject(mesh.MaxPolys, serializer));

			var tilesArray = new JArray();
			foreach (NavTile tile in mesh.Tiles)
			{
				NavPolyId id = mesh.GetTileRef(tile);
				tilesArray.Add(SerializeMeshTile(tile, id));
			}

			root.Add("tiles", tilesArray);

			File.WriteAllText(path, root.ToString());
		}

		public override TiledNavMesh Deserialize(string path)
		{
			JObject root = JObject.Parse(File.ReadAllText(path));

			if (root["meta"]["version"]["snj"].ToObject<int>() != FormatVersion)
				throw new ArgumentException("The version of the file does not match the version of the parser. Consider using an older version of SharpNav or re-generating your .snj meshes.");

			Vector3 origin = root["origin"].ToObject<Vector3>(serializer);
			float tileWidth = root["tileWidth"].ToObject<float>(serializer);
			float tileHeight = root["tileHeight"].ToObject<float>(serializer);
			int maxTiles = root["maxTiles"].ToObject<int>(serializer);
			int maxPolys = root["maxPolys"].ToObject<int>(serializer);

			var mesh = new TiledNavMesh(origin, tileWidth, tileHeight, maxTiles, maxPolys);

			JArray tilesToken = (JArray) root["tiles"];
			List<NavTile> tiles = new List<NavTile>();
			foreach (JToken tileToken in tilesToken)
			{
				NavPolyId tileRef;
				NavTile tile = DeserializeMeshTile(tileToken, mesh.IdManager, out tileRef);
				mesh.AddTileAt(tile, tileRef);
			}

			return mesh;
		}

		private JObject SerializeMeshTile(NavTile tile, NavPolyId id)
		{
			var result = new JObject();
			result.Add("polyId", JToken.FromObject(id, serializer));
			result.Add("location", JToken.FromObject(tile.Location, serializer));
			result.Add("layer", JToken.FromObject(tile.Layer, serializer));
			result.Add("salt", JToken.FromObject(tile.Salt, serializer));
			result.Add("bounds", JToken.FromObject(tile.Bounds, serializer));
			result.Add("polys", JToken.FromObject(tile.Polys, serializer));
			result.Add("verts", JToken.FromObject(tile.Verts, serializer));
			result.Add("detailMeshes", JToken.FromObject(tile.DetailMeshes, serializer));
			result.Add("detailVerts", JToken.FromObject(tile.DetailVerts, serializer));
			result.Add("detailTris", JToken.FromObject(tile.DetailTris, serializer));
			result.Add("offMeshConnections", JToken.FromObject(tile.OffMeshConnections, serializer));

			JObject treeObject = new JObject();
			JArray treeNodes = new JArray();
			for (int i = 0; i < tile.BVTree.Count; i++)
				treeNodes.Add(JToken.FromObject(tile.BVTree[i], serializer));
			treeObject.Add("nodes", treeNodes);

			result.Add("bvTree", treeObject);
			result.Add("bvQuantFactor", JToken.FromObject(tile.BvQuantFactor, serializer));
			result.Add("bvNodeCount", JToken.FromObject(tile.BvNodeCount, serializer));
			result.Add("walkableClimb", JToken.FromObject(tile.WalkableClimb, serializer));

			return result;
		}

		private NavTile DeserializeMeshTile(JToken token, NavPolyIdManager manager, out NavPolyId refId)
		{
			refId = token["polyId"].ToObject<NavPolyId>(serializer);
			Vector2i location = token["location"].ToObject<Vector2i>(serializer);
			int layer = token["layer"].ToObject<int>(serializer);
			NavTile result = new NavTile(location, layer, manager, refId);

			result.Salt = token["salt"].ToObject<int>(serializer);
			result.Bounds = token["bounds"].ToObject<BBox3>(serializer);
			result.Polys = token["polys"].ToObject<NavPoly[]>(serializer);
			result.PolyCount = result.Polys.Length;
			result.Verts = token["verts"].ToObject<Vector3[]>(serializer);
			result.DetailMeshes = token["detailMeshes"].ToObject<PolyMeshDetail.MeshData[]>(serializer);
			result.DetailVerts = token["detailVerts"].ToObject<Vector3[]>(serializer);
			result.DetailTris = token["detailTris"].ToObject<PolyMeshDetail.TriangleData[]>(serializer);
			result.OffMeshConnections = token["offMeshConnections"].ToObject<OffMeshConnection[]>(serializer);
			result.OffMeshConnectionCount = result.OffMeshConnections.Length;
			result.BvNodeCount = token["bvNodeCount"].ToObject<int>(serializer);
			result.BvQuantFactor = token["bvQuantFactor"].ToObject<float>(serializer);
			result.WalkableClimb = token["walkableClimb"].ToObject<float>(serializer);

			var treeObject = (JObject) token["bvTree"];
			var nodes = treeObject.GetValue("nodes").ToObject<BVTree.Node[]>();

			result.BVTree = new BVTree(nodes);

			return result;
		}
	}
}


text:
import time

from oslo_log import log as logging

from nova import test
from nova.tests import fixtures as nova_fixtures
from nova.tests.functional import fixtures as func_fixtures
from nova.tests.functional import integrated_helpers
from nova.tests.unit import fake_network
from nova.tests.unit import fake_notifier
from nova.tests.unit import policy_fixture

LOG = logging.getLogger(__name__)

class FailedEvacuateStateTests(test.TestCase,
                               integrated_helpers.InstanceHelperMixin):
    """Regression Tests for bug #1713783

    When evacuation fails with NoValidHost, the migration status remains
    'accepted' instead of 'error'. This causes problem in case the compute
    service starts up again and looks for migrations with status 'accepted',
    as it then removes the local instances for those migrations even though
    the instance never actually migrated to another host.
    """

    microversion = 'latest'

    def setUp(self):
        super(FailedEvacuateStateTests, self).setUp()

        self.useFixture(policy_fixture.RealPolicyFixture())
        self.useFixture(nova_fixtures.NeutronFixture(self))
        self.useFixture(nova_fixtures.GlanceFixture(self))
        self.useFixture(func_fixtures.PlacementFixture())

        api_fixture = self.useFixture(nova_fixtures.OSAPIFixture(
            api_version='v2.1'))

        self.api = api_fixture.admin_api
        self.api.microversion = self.microversion

        self.start_service('conductor')
        self.start_service('scheduler')

        self.hostname = 'host1'
        self.compute1 = self.start_service('compute', host=self.hostname)
        fake_network.set_stub_network_methods(self)

    def _wait_for_notification_event_type(self, event_type, max_retries=10):
        retry_counter = 0
        while True:
            if len(fake_notifier.NOTIFICATIONS) > 0:
                for notification in fake_notifier.NOTIFICATIONS:
                    if notification.event_type == event_type:
                        return
            if retry_counter == max_retries:
                self.fail('Wait for notification event type (%s) failed'
                          % event_type)
            retry_counter += 1
            time.sleep(0.5)

    def _boot_a_server(self):
        server_req = self._build_server(
            image_uuid='155d900f-4e14-4e4c-a73d-069cbf4541e6',
            networks='none')
        LOG.info('booting on %s', self.hostname)
        created_server = self.api.post_server({'server': server_req})
        return self._wait_for_state_change(created_server, 'ACTIVE')

    def test_evacuate_no_valid_host(self):
        # Boot a server
        server = self._boot_a_server()

        # Force source compute down
        compute_id = self.api.get_services(
            host=self.hostname, binary='nova-compute')[0]['id']
        self.api.put_service(compute_id, {'forced_down': 'true'})

        fake_notifier.stub_notifier(self)
        fake_notifier.reset()

        # Initiate evacuation
        self._evacuate_server(
            server, expected_state='ERROR', expected_host=self.hostname,
            expected_migration_status='error')
        self._wait_for_notification_event_type('compute_task.rebuild_server')

        # Check migrations
        migrations = self.api.get_migrations()
        self.assertEqual(1, len(migrations))
        self.assertEqual('evacuation', migrations[0]['migration_type'])
        self.assertEqual(server['id'], migrations[0]['instance_uuid'])
        self.assertEqual(self.hostname, migrations[0]['source_compute'])
        self.assertEqual('error', migrations[0]['status'])