package awsiam

import (
	"encoding/json"
	"errors"

	"code.cloudfoundry.org/lager"
	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/iam"
)

type UserPolicy struct {
	Version    string                `json:"Version"`
	ID         string                `json:"Id"`
	Statements []UserPolicyStatement `json:"Statement"`
}

type UserPolicyStatement struct {
	SID      string `json:"Sid"`
	Effect   string `json:"Effect"`
	Action   string `json:"Action"`
	Resource string `json:"Resource"`
}

type IAMUser struct {
	iamsvc *iam.IAM
	logger lager.Logger
}

func NewIAMUser(
	iamsvc *iam.IAM,
	logger lager.Logger,
) *IAMUser {
	return &IAMUser{
		iamsvc: iamsvc,
		logger: logger.Session("iam-user"),
	}
}

func (i *IAMUser) Describe(userName string) (UserDetails, error) {
	userDetails := UserDetails{
		UserName: userName,
	}

	getUserInput := &iam.GetUserInput{
		UserName: aws.String(userName),
	}
	i.logger.Debug("get-user", lager.Data{"input": getUserInput})

	getUserOutput, err := i.iamsvc.GetUser(getUserInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return userDetails, errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return userDetails, err
	}
	i.logger.Debug("get-user", lager.Data{"output": getUserOutput})

	userDetails.UserARN = aws.StringValue(getUserOutput.User.Arn)
	userDetails.UserID = aws.StringValue(getUserOutput.User.UserId)

	return userDetails, nil
}

func (i *IAMUser) Create(userName string) (string, error) {
	createUserInput := &iam.CreateUserInput{
		UserName: aws.String(userName),
	}
	i.logger.Debug("create-user", lager.Data{"input": createUserInput})

	createUserOutput, err := i.iamsvc.CreateUser(createUserInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return "", errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return "", err
	}
	i.logger.Debug("create-user", lager.Data{"output": createUserOutput})

	return aws.StringValue(createUserOutput.User.Arn), nil
}

func (i *IAMUser) Delete(userName string) error {
	deleteUserInput := &iam.DeleteUserInput{
		UserName: aws.String(userName),
	}
	i.logger.Debug("delete-user", lager.Data{"input": deleteUserInput})

	deleteUserOutput, err := i.iamsvc.DeleteUser(deleteUserInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return err
	}
	i.logger.Debug("delete-user", lager.Data{"output": deleteUserOutput})

	return nil
}

func (i *IAMUser) ListAccessKeys(userName string) ([]string, error) {
	var accessKeys []string

	listAccessKeysInput := &iam.ListAccessKeysInput{
		UserName: aws.String(userName),
	}
	i.logger.Debug("list-access-keys", lager.Data{"input": listAccessKeysInput})

	listAccessKeysOutput, err := i.iamsvc.ListAccessKeys(listAccessKeysInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return accessKeys, errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return accessKeys, err
	}
	i.logger.Debug("list-access-keys", lager.Data{"output": listAccessKeysOutput})

	for _, accessKey := range listAccessKeysOutput.AccessKeyMetadata {
		accessKeys = append(accessKeys, aws.StringValue(accessKey.AccessKeyId))
	}

	return accessKeys, nil
}

func (i *IAMUser) CreateAccessKey(userName string) (string, string, error) {
	createAccessKeyInput := &iam.CreateAccessKeyInput{
		UserName: aws.String(userName),
	}
	i.logger.Debug("create-access-key", lager.Data{"input": createAccessKeyInput})

	createAccessKeyOutput, err := i.iamsvc.CreateAccessKey(createAccessKeyInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return "", "", errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return "", "", err
	}
	i.logger.Debug("create-access-key", lager.Data{"output": createAccessKeyOutput})

	return aws.StringValue(createAccessKeyOutput.AccessKey.AccessKeyId), aws.StringValue(createAccessKeyOutput.AccessKey.SecretAccessKey), nil
}

func (i *IAMUser) DeleteAccessKey(userName string, accessKeyID string) error {
	deleteAccessKeyInput := &iam.DeleteAccessKeyInput{
		UserName:    aws.String(userName),
		AccessKeyId: aws.String(accessKeyID),
	}
	i.logger.Debug("delete-access-key", lager.Data{"input": deleteAccessKeyInput})

	deleteAccessKeyOutput, err := i.iamsvc.DeleteAccessKey(deleteAccessKeyInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return err
	}
	i.logger.Debug("delete-access-key", lager.Data{"output": deleteAccessKeyOutput})

	return nil
}

func (i *IAMUser) CreatePolicy(policyName string, effect string, action string, resource string) (string, error) {
	policyDocument, err := i.buildUserPolicy(policyName, effect, action, resource)
	if err != nil {
		return "", err
	}

	createPolicyInput := &iam.CreatePolicyInput{
		PolicyName:     aws.String(policyName),
		PolicyDocument: aws.String(policyDocument),
	}
	i.logger.Debug("create-policy", lager.Data{"input": createPolicyInput})

	createPolicyOutput, err := i.iamsvc.CreatePolicy(createPolicyInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return "", errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return "", err
	}
	i.logger.Debug("create-policy", lager.Data{"output": createPolicyOutput})

	return aws.StringValue(createPolicyOutput.Policy.Arn), nil
}

func (i *IAMUser) DeletePolicy(policyARN string) error {
	deletePolicyInput := &iam.DeletePolicyInput{
		PolicyArn: aws.String(policyARN),
	}
	i.logger.Debug("delete-policy", lager.Data{"input": deletePolicyInput})

	deletePolicyOutput, err := i.iamsvc.DeletePolicy(deletePolicyInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return err
	}
	i.logger.Debug("delete-policy", lager.Data{"output": deletePolicyOutput})

	return nil
}

func (i *IAMUser) ListAttachedUserPolicies(userName string) ([]string, error) {
	var userPolicies []string

	listAttachedUserPoliciesInput := &iam.ListAttachedUserPoliciesInput{
		UserName: aws.String(userName),
	}
	i.logger.Debug("list-attached-user-policies", lager.Data{"input": listAttachedUserPoliciesInput})

	listAttachedUserPoliciesOutput, err := i.iamsvc.ListAttachedUserPolicies(listAttachedUserPoliciesInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return userPolicies, errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return userPolicies, err
	}
	i.logger.Debug("list-attached-user-policies", lager.Data{"output": listAttachedUserPoliciesOutput})

	for _, userPolicy := range listAttachedUserPoliciesOutput.AttachedPolicies {
		userPolicies = append(userPolicies, aws.StringValue(userPolicy.PolicyArn))
	}

	return userPolicies, nil
}

func (i *IAMUser) AttachUserPolicy(userName string, policyARN string) error {
	attachUserPolicyInput := &iam.AttachUserPolicyInput{
		PolicyArn: aws.String(policyARN),
		UserName:  aws.String(userName),
	}
	i.logger.Debug("attach-user-policy", lager.Data{"input": attachUserPolicyInput})

	attachUserPolicyOutput, err := i.iamsvc.AttachUserPolicy(attachUserPolicyInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return err
	}
	i.logger.Debug("attach-user-policy", lager.Data{"output": attachUserPolicyOutput})

	return nil
}

func (i *IAMUser) DetachUserPolicy(userName string, policyARN string) error {
	detachUserPolicyInput := &iam.DetachUserPolicyInput{
		PolicyArn: aws.String(policyARN),
		UserName:  aws.String(userName),
	}
	i.logger.Debug("detach-user-policy", lager.Data{"input": detachUserPolicyInput})

	detachUserPolicyOutput, err := i.iamsvc.DetachUserPolicy(detachUserPolicyInput)
	if err != nil {
		i.logger.Error("aws-iam-error", err)
		if awsErr, ok := err.(awserr.Error); ok {
			return errors.New(awsErr.Code() + ": " + awsErr.Message())
		}
		return err
	}
	i.logger.Debug("detach-user-policy", lager.Data{"output": detachUserPolicyOutput})

	return nil
}

func (i *IAMUser) buildUserPolicy(policyID string, effect string, action string, resource string) (string, error) {
	userPolicy := UserPolicy{
		Version: "2012-10-17",
		ID:      policyID,
		Statements: []UserPolicyStatement{
			UserPolicyStatement{
				SID:      "1",
				Effect:   effect,
				Action:   action,
				Resource: resource,
			},
			UserPolicyStatement{
				SID:      "2",
				Effect:   effect,
				Action:   action,
				Resource: resource + "/*",
			},
		},
	}

	policy, err := json.Marshal(userPolicy)
	if err != nil {
		return "", err
	}

	return string(policy), nil
}


<?php

/**
 * Subclass for representing a row from the 'sf_user_recommendation' table.
 *
 *
 *
 * @package plugins.sfPropelActAsRecommendableBehaviorPlugin.lib.model
 */
class sfUserRecommendation extends BasesfUserRecommendation
{
}


'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Collapsible = _react2.default.createClass({
  displayName: 'Collapsible',

  //Set validation for prop types
  propTypes: {
    transitionTime: _react2.default.PropTypes.number,
    easing: _react2.default.PropTypes.string,
    open: _react2.default.PropTypes.bool,
    classParentString: _react2.default.PropTypes.string,
    openedClassName: _react2.default.PropTypes.string,
    triggerClassName: _react2.default.PropTypes.string,
    triggerOpenedClassName: _react2.default.PropTypes.string,
    contentOuterClassName: _react2.default.PropTypes.string,
    contentInnerClassName: _react2.default.PropTypes.string,
    accordionPosition: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.number]),
    handleTriggerClick: _react2.default.PropTypes.func,
    trigger: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.element]),
    triggerWhenOpen: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.element]),
    triggerDisabled: _react2.default.PropTypes.bool,
    lazyRender: _react2.default.PropTypes.bool,
    overflowWhenOpen: _react2.default.PropTypes.oneOf(['hidden', 'visible', 'auto', 'scroll', 'inherit', 'initial', 'unset']),
    triggerSibling: _react2.default.PropTypes.element
  },

  //If no transition time or easing is passed then default to this
  getDefaultProps: function getDefaultProps() {
    return {
      transitionTime: 400,
      easing: 'linear',
      open: false,
      classParentString: 'Collapsible',
      triggerDisabled: false,
      lazyRender: false,
      overflowWhenOpen: 'hidden',
      openedClassName: '',
      triggerClassName: '',
      triggerOpenedClassName: '',
      contentOuterClassName: '',
      contentInnerClassName: '',
      className: '',
      triggerSibling: null
    };
  },

  //Defaults the dropdown to be closed
  getInitialState: function getInitialState() {

    if (this.props.open) {
      return {
        isClosed: false,
        shouldSwitchAutoOnNextCycle: false,
        height: 'auto',
        transition: 'none',
        hasBeenOpened: true,
        overflow: this.props.overflowWhenOpen
      };
    } else {
      return {
        isClosed: true,
        shouldSwitchAutoOnNextCycle: false,
        height: 0,
        transition: 'height ' + this.props.transitionTime + 'ms ' + this.props.easing,
        hasBeenOpened: false,
        overflow: 'hidden'
      };
    }
  },

  // Taken from https://github.com/EvandroLG/transitionEnd/
  // Determines which prefixed event to listen for
  whichTransitionEnd: function whichTransitionEnd(element) {
    var transitions = {
      'WebkitTransition': 'webkitTransitionEnd',
      'MozTransition': 'transitionend',
      'OTransition': 'oTransitionEnd otransitionend',
      'transition': 'transitionend'
    };

    for (var t in transitions) {
      if (element.style[t] !== undefined) {
        return transitions[t];
      }
    }
  },

  componentDidMount: function componentDidMount() {
    var _this = this;

    //Set up event listener to listen to transitionend so we can switch the height from fixed pixel to auto for much responsiveness;
    //TODO:  Once Synthetic transitionend events have been exposed in the next release of React move this funciton to a function handed to the onTransitionEnd prop

    this.refs.outer.addEventListener(this.whichTransitionEnd(this.refs.outer), function (event) {
      if (_this.state.isClosed === false) {
        _this.setState({
          shouldSwitchAutoOnNextCycle: true
        });
      }
    });
  },

  componentDidUpdate: function componentDidUpdate(prevProps) {

    if (this.state.shouldSwitchAutoOnNextCycle === true && this.state.isClosed === false) {
      //Set the height to auto to make compoenent re-render with the height set to auto.
      //This way the dropdown will be responsive and also change height if there is another dropdown within it.
      this.makeResponsive();
    }

    if (this.state.shouldSwitchAutoOnNextCycle === true && this.state.isClosed === true) {
      this.prepareToOpen();
    }

    //If there has been a change in the open prop (controlled by accordion)
    if (prevProps.open != this.props.open) {
      if (this.props.open === true) {
        this.openCollapsible();
      } else {
        this.closeCollapsible();
      }
    }
  },

  handleTriggerClick: function handleTriggerClick(event) {

    event.preventDefault();

    if (this.props.triggerDisabled) {
      return;
    }

    if (this.props.handleTriggerClick) {
      this.props.handleTriggerClick(this.props.accordionPosition);
    } else {

      if (this.state.isClosed === true) {
        this.openCollapsible();
      } else {
        this.closeCollapsible();
      }
    }
  },

  closeCollapsible: function closeCollapsible() {
    this.setState({
      isClosed: true,
      shouldSwitchAutoOnNextCycle: true,
      height: this.refs.inner.offsetHeight,
      overflow: 'hidden'
    });
  },

  openCollapsible: function openCollapsible() {
    this.setState({
      height: this.refs.inner.offsetHeight,
      transition: 'height ' + this.props.transitionTime + 'ms ' + this.props.easing,
      isClosed: false,
      hasBeenOpened: true
    });
    if(typeof(this.props.onOpen) != 'undefined' &&  typeof(this.props.dateString) != 'undefined')
      this.props.onOpen(this.props.dateString);
  },

  makeResponsive: function makeResponsive() {
    this.setState({
      height: 'auto',
      transition: 'none',
      shouldSwitchAutoOnNextCycle: false,
      overflow: this.props.overflowWhenOpen
    });
  },

  prepareToOpen: function prepareToOpen() {
    var _this2 = this;

    //The height has been changes back to fixed pixel, we set a small timeout to force the CSS transition back to 0 on the next tick.
    window.setTimeout(function () {
      _this2.setState({
        height: 0,
        shouldSwitchAutoOnNextCycle: false,
        transition: 'height ' + _this2.props.transitionTime + 'ms ' + _this2.props.easing
      });
    }, 50);
  },

  renderNonClickableTriggerElement: function renderNonClickableTriggerElement() {
    if (this.props.triggerSibling) {
      return _react2.default.createElement(
        'span',
        { className: this.props.classParentString + "__trigger-sibling" },
        this.props.triggerSibling
      );
    }

    return null;
  },

  render: function render() {

    var dropdownStyle = {
      height: this.state.height,
      WebkitTransition: this.state.transition,
      msTransition: this.state.transition,
      transition: this.state.transition,
      overflow: this.state.overflow
    };

    var openClass = this.state.isClosed ? 'is-closed' : 'is-open';
    var disabledClass = this.props.triggerDisabled ? 'is-disabled' : '';

    //If user wants different text when tray is open
    var trigger = this.state.isClosed === false && this.props.triggerWhenOpen !== undefined ? this.props.triggerWhenOpen : this.props.trigger;

    // Don't render children until the first opening of the Collapsible if lazy rendering is enabled
    var children = this.props.children;
    if (this.props.lazyRender) if (!this.state.hasBeenOpened) children = null;

    var triggerClassName = this.props.classParentString + "__trigger" + ' ' + openClass + ' ' + disabledClass;

    if (this.state.isClosed) {
      triggerClassName = triggerClassName + ' ' + this.props.triggerClassName;
    } else {
      triggerClassName = triggerClassName + ' ' + this.props.triggerOpenedClassName;
    }

    return _react2.default.createElement(
      'div',
      { className: this.props.classParentString + ' ' + (this.state.isClosed ? this.props.className : this.props.openedClassName) },
      _react2.default.createElement(
        'span',
        { className: triggerClassName.trim(), onClick: this.handleTriggerClick },
        trigger
      ),
      this.renderNonClickableTriggerElement(),
      _react2.default.createElement(
        'div',
        { className: this.props.classParentString + "__contentOuter" + ' ' + this.props.contentOuterClassName, ref: 'outer', style: dropdownStyle },
        _react2.default.createElement(
          'div',
          { className: this.props.classParentString + "__contentInner" + ' ' + this.props.contentInnerClassName, ref: 'inner' },
          children
        )
      )
    );
  }
});

exports.default = Collapsible;


using System;
using System.Collections.Generic;
using CH.Testing.T2.Interface;

namespace CH.Testing.T2.Component
{
    internal sealed class LineParser : ILineParser
    {
        private static readonly string[] Separator = {Environment.NewLine};

        IEnumerable<string> ILineParser.Parse(string s)
        {
            return s.Split(Separator, int.MaxValue, StringSplitOptions.None);
        }
    }
}


import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;
import com.google.android.libraries.social.autobackup.MediaRecordEntry;
import java.io.IOException;

public final class hbm
{
  private static final String a = MediaRecordEntry.a.a;
  private static final String b;
  private static final String c;
  private static final String d;
  private static final String e;

  static
  {
    String str1 = String.valueOf("upload_account_id = -1 AND _id > ? AND media_url NOT IN ( SELECT media_url FROM ");
    String str2 = a;
    String str3 = String.valueOf("upload_account_id");
    String str4 = String.valueOf("bucket_id");
    String str5 = String.valueOf("bucket_id");
    String str6 = String.valueOf("bucket_id");
    String str7 = String.valueOf("exclude_bucket");
    b = 57 + String.valueOf(str1).length() + String.valueOf(str2).length() + String.valueOf(str3).length() + String.valueOf(str4).length() + String.valueOf(str5).length() + String.valueOf(str6).length() + String.valueOf(str7).length() + str1 + str2 + " WHERE " + str3 + " = ? )" + " AND (" + str4 + " IS NULL OR " + str5 + " NOT IN ( SELECT " + str6 + " FROM " + str7 + " ))";
    String str8 = String.valueOf(MediaRecordEntry.a.a);
    String str9 = String.valueOf("upload_account_id = ? AND upload_state = 100");
    c = 28 + String.valueOf(str8).length() + String.valueOf(str9).length() + "SELECT count(*) FROM " + str8 + " WHERE " + str9;
    String str10 = a;
    String str11 = String.valueOf("upload_account_id = ? AND ( upload_state = 100 OR upload_state = 200 ) AND upload_reason = ?");
    d = 28 + String.valueOf(str10).length() + String.valueOf(str11).length() + "SELECT COUNT(*) FROM " + str10 + " WHERE " + str11;
    String str12 = String.valueOf("upload_account_id = -1 AND bucket_id = ? AND media_url NOT IN ( SELECT media_url FROM ");
    String str13 = a;
    String str14 = String.valueOf("upload_account_id");
    e = 13 + String.valueOf(str12).length() + String.valueOf(str13).length() + String.valueOf(str14).length() + str12 + str13 + " WHERE " + str14 + " = ? )";
  }

  private static int a(SQLiteDatabase paramSQLiteDatabase, int paramInt1, int paramInt2)
  {
    Cursor localCursor = a(paramSQLiteDatabase, paramInt1, -1L, 500);
    int i = 0;
    try
    {
      while (localCursor.moveToNext())
      {
        MediaRecordEntry localMediaRecordEntry = MediaRecordEntry.a(localCursor);
        localMediaRecordEntry.id = 0L;
        localMediaRecordEntry.mUploadAccountId = paramInt1;
        localMediaRecordEntry.mUploadReason = paramInt2;
        localMediaRecordEntry.mUploadState = 100;
        MediaRecordEntry.a.a(paramSQLiteDatabase, localMediaRecordEntry);
        i++;
      }
      return i;
    }
    finally
    {
      localCursor.close();
    }
  }

  static Cursor a(SQLiteDatabase paramSQLiteDatabase, int paramInt1, long paramLong, int paramInt2)
  {
    String str1 = a;
    String[] arrayOfString1 = MediaRecordEntry.a.b;
    String str2 = b;
    String[] arrayOfString2 = new String[2];
    arrayOfString2[0] = Long.toString(paramLong);
    arrayOfString2[1] = Integer.toString(paramInt1);
    return paramSQLiteDatabase.query(true, str1, arrayOfString1, str2, arrayOfString2, null, null, "_id ASC", Integer.toString(paramInt2));
  }

  public static void a(SQLiteDatabase paramSQLiteDatabase, int paramInt, String paramString)
  {
    if (paramInt == -1) {}
    int i;
    do
    {
      return;
      i = 0;
      int j;
      do
      {
        j = b(paramSQLiteDatabase, paramInt, paramString);
        if (Log.isLoggable("iu.UploadsManager", 4)) {
          new StringBuilder(56).append("ADD; medias added in batch: ").append(j).append("; iu: ").append(paramInt);
        }
        i += j;
      } while (j > 0);
    } while (!Log.isLoggable("iu.UploadsManager", 4));
    new StringBuilder(60).append("ADD; complete; total scheduled: ").append(i).append("; iu: ").append(paramInt);
  }

  public static void a(SQLiteDatabase paramSQLiteDatabase, String paramString)
  {
    paramSQLiteDatabase.delete(a, "upload_account_id != -1 AND bucket_id = ? AND upload_state != 400", new String[] { paramString });
  }

  public static void a(hci paramhci, int paramInt)
  {
    if (paramInt == -1) {
      return;
    }
    String[] arrayOfString = new String[1];
    arrayOfString[0] = Integer.toString(paramInt);
    paramhci.getWritableDatabase().delete(a, "upload_account_id = ? AND upload_state = 100", arrayOfString);
  }

  static void a(hci paramhci, int paramInt1, int paramInt2)
  {
    if ((paramInt2 != 40) && (paramInt2 != 30)) {
      throw new IllegalArgumentException("only REASON_UPLOAD_ALL and REASON_INSTANT_UPLOAD supported");
    }
    SQLiteDatabase localSQLiteDatabase = paramhci.getWritableDatabase();
    String str = a;
    String[] arrayOfString = new String[2];
    arrayOfString[0] = Integer.toString(paramInt1);
    arrayOfString[1] = Integer.toString(paramInt2);
    localSQLiteDatabase.delete(str, "upload_account_id = ? AND ( upload_state = 100 OR upload_state = 200 ) AND upload_reason = ?", arrayOfString);
  }

  static boolean a(ContentResolver paramContentResolver, Uri paramUri)
  {
    String str1 = efj.a(paramContentResolver, paramUri, "_data");
    if (str1 != null)
    {
      int i = str1.lastIndexOf('.');
      if (i >= 0) {}
      for (String str2 = str1.substring(i + 1); (!"jpg".equalsIgnoreCase(str2)) && (!"jpeg".equalsIgnoreCase(str2)); str2 = "") {
        return false;
      }
      for (;;)
      {
        try
        {
          hxp localhxp = new hxp();
          try
          {
            localhxp.a(str1);
            int j = hxp.h;
            localhya = localhxp.a(j, localhxp.d(j));
            if (localhya != null) {
              continue;
            }
            localObject = null;
            if ((localObject == null) || (!((String)localObject).contains("Google"))) {
              break label290;
            }
            if (!Log.isLoggable("iu.UploadsManager", 4)) {
              break label292;
            }
            String str4 = String.valueOf(localObject);
            if (str4.length() == 0) {
              continue;
            }
            "*** Found Google EXIF tag; value: ".concat(str4);
          }
          catch (IOException localIOException)
          {
            if (!Log.isLoggable("iu.UploadsManager", 4)) {
              break label294;
            }
          }
          new StringBuilder(37 + String.valueOf(str1).length()).append("INFO: ").append(str1).append(" does not contain any EXIF data");
        }
        catch (Throwable localThrowable)
        {
          hya localhya;
          Object localObject;
          if (!Log.isLoggable("iu.UploadsManager", 4)) {
            continue;
          }
          String str3 = String.valueOf(localThrowable);
          new StringBuilder(27 + String.valueOf(str1).length() + String.valueOf(str3).length()).append("INFO: ").append(str1).append(" error getting EXIF; ").append(str3);
          return false;
        }
        localObject = localhya.a();
      }
      new String("*** Found Google EXIF tag; value: ");
    }
    else
    {
      label290:
      return false;
    }
    label292:
    return true;
    label294:
    return false;
  }

  static boolean a(Context paramContext)
  {
    Cursor localCursor = ((hci)mbb.a(paramContext, hci.class)).getReadableDatabase().query(true, a, MediaRecordEntry.a.b, "upload_reason = 30 AND upload_state = 400", null, null, null, null, "1");
    try
    {
      boolean bool = localCursor.moveToFirst();
      return bool;
    }
    finally
    {
      localCursor.close();
    }
  }

  public static boolean a(Context paramContext, int paramInt1, int paramInt2)
  {
    hci localhci = (hci)mbb.a(paramContext, hci.class);
    String str1;
    String[] arrayOfString;
    if (paramInt1 == -1)
    {
      str1 = "upload_account_id != -1 AND upload_state = 200";
      arrayOfString = null;
    }
    for (;;)
    {
      if (Log.isLoggable("iu.UploadsManager", 4))
      {
        String str2 = a;
        String str3 = 28 + String.valueOf(str2).length() + String.valueOf(str1).length() + "SELECT COUNT(*) FROM " + str2 + " WHERE " + str1;
        long l = DatabaseUtils.longForQuery(localhci.getReadableDatabase(), str3, arrayOfString);
        new StringBuilder(40).append("num queued entries: ").append(l);
      }
      ContentValues localContentValues = new ContentValues(1);
      localContentValues.put("upload_state", Integer.valueOf(100));
      int i = localhci.getWritableDatabase().update(a, localContentValues, str1, arrayOfString);
      if (Log.isLoggable("iu.UploadsManager", 4)) {
        new StringBuilder(32).append("num updated entries: ").append(i);
      }
      if (i <= 0) {
        break;
      }
      return true;
      str1 = "upload_account_id = ? AND upload_state = 200";
      arrayOfString = new String[1];
      arrayOfString[0] = Integer.toString(paramInt1);
    }
    return false;
  }

  public static boolean a(Context paramContext, ContentResolver paramContentResolver, SQLiteDatabase paramSQLiteDatabase, ContentValues paramContentValues, String paramString, long paramLong, Uri paramUri, boolean paramBoolean1, boolean paramBoolean2)
  {
    hba localhba = (hba)mbb.a(paramContext, hba.class);
    String str1 = paramUri.toString();
    paramContentValues.clear();
    paramContentValues.putNull("album_id");
    paramContentValues.putNull("event_id");
    paramContentValues.put("upload_account_id", Integer.valueOf(-1));
    paramContentValues.put("bucket_id", paramString);
    paramContentValues.put("is_image", Boolean.valueOf(paramBoolean1));
    paramContentValues.put("media_id", Long.valueOf(paramLong));
    paramContentValues.put("media_time", Long.valueOf(efj.a(paramContentResolver, paramUri)));
    String str2 = efj.a(paramContentResolver, paramUri, "_data");
    if (str2 == null) {
      str2 = str1;
    }
    paramContentValues.put("media_hash", Integer.valueOf(str2.hashCode()));
    paramContentValues.put("media_url", str1);
    paramContentValues.put("upload_reason", Integer.valueOf(0));
    paramContentValues.put("upload_state", Integer.valueOf(500));
    MediaRecordEntry.a.a(paramSQLiteDatabase, MediaRecordEntry.a(paramContentValues));
    if ((!paramBoolean2) || (a(paramContentResolver, paramUri))) {
      return false;
    }
    int i = localhba.d();
    paramContentValues.putNull("event_id");
    if (!hbj.a(paramContext))
    {
      paramContentValues.put("upload_account_id", Integer.valueOf(i));
      paramContentValues.put("upload_reason", Integer.valueOf(30));
      paramContentValues.put("upload_state", Integer.valueOf(100));
      MediaRecordEntry.a.a(paramSQLiteDatabase, MediaRecordEntry.a(paramContentValues));
      if (Log.isLoggable("iu.UploadsManager", 4)) {
        new StringBuilder(59).append("NEW; upload media id: ").append(paramLong).append("; iu: ").append(i);
      }
    }
    if (Log.isLoggable("iu.UploadsManager", 4)) {
      new StringBuilder(39).append("NEW; add media id: ").append(paramLong);
    }
    return true;
  }

  /* Error */
  private static int b(SQLiteDatabase paramSQLiteDatabase, int paramInt, String paramString)
  {
    // Byte code:
    //   0: aload_0
    //   1: invokevirtual 370	android/database/sqlite/SQLiteDatabase:beginTransaction	()V
    //   4: getstatic 22	hbm:a	Ljava/lang/String;
    //   7: astore 4
    //   9: getstatic 17	com/google/android/libraries/social/autobackup/MediaRecordEntry:a	Liao;
    //   12: getfield 124	iao:b	[Ljava/lang/String;
    //   15: astore 5
    //   17: getstatic 86	hbm:e	Ljava/lang/String;
    //   20: astore 6
    //   22: iconst_2
    //   23: anewarray 26	java/lang/String
    //   26: astore 7
    //   28: aload 7
    //   30: iconst_0
    //   31: aload_2
    //   32: aastore
    //   33: aload 7
    //   35: iconst_1
    //   36: iload_1
    //   37: invokestatic 134	java/lang/Integer:toString	(I)Ljava/lang/String;
    //   40: aastore
    //   41: aload_0
    //   42: aload 4
    //   44: aload 5
    //   46: aload 6
    //   48: aload 7
    //   50: aconst_null
    //   51: aconst_null
    //   52: aconst_null
    //   53: sipush 500
    //   56: invokestatic 134	java/lang/Integer:toString	(I)Ljava/lang/String;
    //   59: invokevirtual 373	android/database/sqlite/SQLiteDatabase:query	(Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;
    //   62: astore 8
    //   64: iconst_0
    //   65: istore 9
    //   67: aload 8
    //   69: invokeinterface 98 1 0
    //   74: ifeq +52 -> 126
    //   77: aload 8
    //   79: invokestatic 101	com/google/android/libraries/social/autobackup/MediaRecordEntry:a	(Landroid/database/Cursor;)Lcom/google/android/libraries/social/autobackup/MediaRecordEntry;
    //   82: astore 11
    //   84: aload 11
    //   86: lconst_0
    //   87: putfield 105	com/google/android/libraries/social/autobackup/MediaRecordEntry:id	J
    //   90: aload 11
    //   92: iload_1
    //   93: putfield 109	com/google/android/libraries/social/autobackup/MediaRecordEntry:mUploadAccountId	I
    //   96: aload 11
    //   98: bipush 30
    //   100: putfield 112	com/google/android/libraries/social/autobackup/MediaRecordEntry:mUploadReason	I
    //   103: aload 11
    //   105: bipush 100
    //   107: putfield 115	com/google/android/libraries/social/autobackup/MediaRecordEntry:mUploadState	I
    //   110: getstatic 17	com/google/android/libraries/social/autobackup/MediaRecordEntry:a	Liao;
    //   113: aload_0
    //   114: aload 11
    //   116: invokevirtual 118	iao:a	(Landroid/database/sqlite/SQLiteDatabase;Lial;)J
    //   119: pop2
    //   120: iinc 9 1
    //   123: goto -56 -> 67
    //   126: aload_0
    //   127: invokevirtual 376	android/database/sqlite/SQLiteDatabase:setTransactionSuccessful	()V
    //   130: aload 8
    //   132: invokeinterface 121 1 0
    //   137: aload_0
    //   138: invokevirtual 379	android/database/sqlite/SQLiteDatabase:endTransaction	()V
    //   141: iload 9
    //   143: ireturn
    //   144: astore 10
    //   146: aload 8
    //   148: invokeinterface 121 1 0
    //   153: aload 10
    //   155: athrow
    //   156: astore_3
    //   157: aload_0
    //   158: invokevirtual 379	android/database/sqlite/SQLiteDatabase:endTransaction	()V
    //   161: aload_3
    //   162: athrow
    // Local variable table:
    //   start	length	slot	name	signature
    //   0	163	0	paramSQLiteDatabase	SQLiteDatabase
    //   0	163	1	paramInt	int
    //   0	163	2	paramString	String
    //   156	6	3	localObject1	Object
    //   7	36	4	str1	String
    //   15	30	5	arrayOfString1	String[]
    //   20	27	6	str2	String
    //   26	23	7	arrayOfString2	String[]
    //   62	85	8	localCursor	Cursor
    //   65	77	9	i	int
    //   144	10	10	localObject2	Object
    //   82	33	11	localMediaRecordEntry	MediaRecordEntry
    // Exception table:
    //   from	to	target	type
    //   67	120	144	finally
    //   126	130	144	finally
    //   4	64	156	finally
    //   130	137	156	finally
    //   146	156	156	finally
  }

  static int b(hci paramhci, int paramInt1, int paramInt2)
  {
    if (paramInt1 == -1) {
      return 0;
    }
    SQLiteDatabase localSQLiteDatabase = paramhci.getReadableDatabase();
    String str = d;
    String[] arrayOfString = new String[2];
    arrayOfString[0] = Integer.toString(paramInt1);
    arrayOfString[1] = Integer.toString(paramInt2);
    return (int)DatabaseUtils.longForQuery(localSQLiteDatabase, str, arrayOfString);
  }

  public static MediaRecordEntry b(hci paramhci, int paramInt)
  {
    String str;
    String[] arrayOfString;
    if (paramInt == -1)
    {
      str = "upload_account_id != -1 AND upload_state = 100";
      arrayOfString = null;
    }
    for (;;)
    {
      Cursor localCursor = paramhci.getReadableDatabase().query(a, MediaRecordEntry.a.b, str, arrayOfString, null, null, "upload_reason ASC, upload_state ASC, upload_status ASC, is_image DESC, retry_end_time ASC LIMIT 1");
      try
      {
        if (localCursor.moveToNext())
        {
          MediaRecordEntry localMediaRecordEntry = MediaRecordEntry.a(localCursor);
          return localMediaRecordEntry;
          str = "upload_account_id = ? AND upload_state = 100";
          arrayOfString = new String[1];
          arrayOfString[0] = Integer.toString(paramInt);
          continue;
        }
        return null;
      }
      finally
      {
        localCursor.close();
      }
    }
  }

  public static int c(hci paramhci, int paramInt)
  {
    SQLiteDatabase localSQLiteDatabase = paramhci.getReadableDatabase();
    String str = c;
    String[] arrayOfString = new String[1];
    arrayOfString[0] = Integer.toString(paramInt);
    return (int)DatabaseUtils.longForQuery(localSQLiteDatabase, str, arrayOfString);
  }

  static void c(hci paramhci, int paramInt1, int paramInt2)
  {
    if (paramInt1 == -1) {
      throw new IllegalStateException(52 + "can't enable upload for invalid account: " + paramInt1);
    }
    SQLiteDatabase localSQLiteDatabase1 = paramhci.getWritableDatabase();
    int i = 0;
    for (;;)
    {
      localSQLiteDatabase1.beginTransaction();
      try
      {
        int j = a(localSQLiteDatabase1, paramInt1, 40);
        localSQLiteDatabase1.setTransactionSuccessful();
        localSQLiteDatabase1.endTransaction();
        i += j;
        if (j <= 0)
        {
          if (Log.isLoggable("iu.UploadsManager", 4)) {
            new StringBuilder(35).append("START; scheduled ").append(i).append(" photos");
          }
          SQLiteDatabase localSQLiteDatabase2 = paramhci.getReadableDatabase();
          String str = a;
          String[] arrayOfString1 = MediaRecordEntry.a.b;
          String[] arrayOfString2 = new String[1];
          arrayOfString2[0] = Integer.toString(paramInt1);
          Cursor localCursor = localSQLiteDatabase2.query(true, str, arrayOfString1, "upload_account_id = ? AND upload_state = 300", arrayOfString2, null, null, null, null);
          MediaRecordEntry localMediaRecordEntry;
          localCursor.close();
        }
      }
      finally {}
    }
  }

  /* Error */
  static int d(hci paramhci, int paramInt)
  {
    // Byte code:
    //   0: aload_0
    //   1: invokevirtual 260	hci:getReadableDatabase	()Landroid/database/sqlite/SQLiteDatabase;
    //   4: iconst_1
    //   5: getstatic 22	hbm:a	Ljava/lang/String;
    //   8: iconst_1
    //   9: anewarray 26	java/lang/String
    //   12: dup
    //   13: iconst_0
    //   14: ldc_w 404
    //   17: aastore
    //   18: ldc_w 406
    //   21: aconst_null
    //   22: aconst_null
    //   23: aconst_null
    //   24: aconst_null
    //   25: aconst_null
    //   26: invokevirtual 142	android/database/sqlite/SQLiteDatabase:query	(ZLjava/lang/String;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Landroid/database/Cursor;
    //   29: astore_2
    //   30: aload_2
    //   31: invokeinterface 98 1 0
    //   36: ifeq +25 -> 61
    //   39: aload_2
    //   40: iconst_0
    //   41: invokeinterface 409 2 0
    //   46: istore 5
    //   48: iload 5
    //   50: istore 4
    //   52: aload_2
    //   53: invokeinterface 121 1 0
    //   58: iload 4
    //   60: ireturn
    //   61: iconst_0
    //   62: istore 4
    //   64: goto -12 -> 52
    //   67: astore_3
    //   68: aload_2
    //   69: invokeinterface 121 1 0
    //   74: aload_3
    //   75: athrow
    // Local variable table:
    //   start	length	slot	name	signature
    //   0	76	0	paramhci	hci
    //   0	76	1	paramInt	int
    //   29	40	2	localCursor	Cursor
    //   67	8	3	localObject	Object
    //   50	13	4	i	int
    //   46	3	5	j	int
    // Exception table:
    //   from	to	target	type
    //   30	48	67	finally
  }
}

/* Location:           F:\apktool\apktool\com.google.android.apps.plus\classes-dex2jar.jar

 * Qualified Name:     hbm

 * JD-Core Version:    0.7.0.1

 */


import {
  Component
} from '@angular/core';

@Component({
  templateUrl: 'index.html',
  styleUrls: ['index.css'],
})
export
class Home { }


var params = {
  tables: 14,
  currentTable: 0,
  currentQuestion: -1
};
var questions = [
  { q: "¿Cuál es el color preferido de Silvina?", o: [ "Verde", "Amarillo", "Azul" ], a: 1 },
  { q: "¿A qué edad salió Pablo del closet?", o: [ "15", "18", "Hoy" ], a: 0 },
  { q: "¿Quién se tomó todo el vino?", o: [ "La mona Gimenez", "Silchu", "Pablo" ], a: 2 },
  { q: "¿Cual de estas prendas no usaria pablo?", o: [ "Pollera", "Zapatos con taco", "Medias de red" ], a: 0 }
];

$().ready(function() {

  var nextTable = function() {
    params.currentTable++;
    params.currentQuestion = -1;
    next();
  };

  var showQuestion = function() {
    var question = questions[params.currentQuestion];
    $('#question').text(question.q);
    $('#answers').empty();
    for (var i in question.o) {
      var value = question.o[i];
      $('#answers').append($('<button />').addClass('btn btn-danger').text(value));
    }

    $('#prev').toggle(params.currentQuestion > 0);
    $('#next').attr('disabled', 'disabled').toggle(params.currentQuestion <= questions.length);
  };

  var next = function() {
    if (params.currentQuestion == questions.length)
      nextTable();

    params.currentQuestion++;
    showQuestion();
  };

  var prev = function() {
    params.currentQuestion--;
    showQuestion();
  };

  $('#next').click(next);
  $('#prev').click(prev);
  $('#answers').on('click', 'button', function() {
    $('#next').removeAttr('disabled');
  });

  nextTable();
});


import { Component } from '@angular/core';

@Component({
    selector: 'footer-sticky',
    template: require('./footer-sticky.component.html')
})
export class FooterStickyComponent {
}


struct QVariantMeshWrapper
{
    QVariantMeshWrapper() {}
    Ogre::Item* item;
};

Q_DECLARE_METATYPE(QVariantMeshWrapper);

SaveAsDialog::SaveAsDialog(QWidget* parent, OgreManager* ogre) : QDialog(parent)
{
    ui = new Ui::SaveAsDialog;
    ui->setupUi(this);

    mOgre = ogre;
    ui->progressBar->setVisible(false);

    connect(ui->browseButton, &QPushButton::clicked, this, &SaveAsDialog::browseButtonClicked);
    connect(ui->saveButton, &QPushButton::clicked, this, &SaveAsDialog::saveButtonClicked);
    connect(ui->cancelButton, &QPushButton::clicked, this, &SaveAsDialog::cancelButtonClicked);
}

SaveAsDialog::~SaveAsDialog()
{
    delete ui;
}

void SaveAsDialog::showEvent(QShowEvent*)
{
    if (!mInitialized)
    {
        ui->savePathText->setText(mOutputFolder);

        listAllMeshesFromScene();
        mInitialized = true;
    }
}

void SaveAsDialog::browseButtonClicked()
{
    QString initialPath = ui->savePathText->text();
    QString folder = QFileDialog::getExistingDirectory(this, "Output path", initialPath);

    if (!folder.isEmpty())
    {
        ui->savePathText->setText(folder);
        mOutputFolder = folder;
    }
}

void SaveAsDialog::saveButtonClicked()
{
    lockListWidget();

    std::vector<Ogre::Item*> ogreItems;

    QListWidget* listWidget = ui->listWidget;
    for (int i = 0; i < listWidget->count(); ++i)
    {
        QListWidgetItem* item = listWidget->item(i);
        bool checked = (item->checkState() == Qt::Checked);
        if (checked)
        {
            auto wrapper = item->data(Qt::UserRole).value<QVariantMeshWrapper>();
            ogreItems.push_back(wrapper.item);
        }
    }

    ui->progressBar->setVisible(true);
    ui->progressBar->setMaximum(ogreItems.size());
    QApplication::processEvents(QEventLoop::DialogExec);

    saveOgreMeshes(ogreItems);

    Ogre::SceneNode* rootNode = mOgre->meshRootNode();
    std::vector<Ogre::SceneNode*> nodes;
    collectNodeRecursively(rootNode, nodes);

    saveLuaScript(nodes, ogreItems);

    QSettings settings("OgreV2ModelViewer", "OgreV2ModelViewer");
    settings.setValue("actionSaveMesh", mOutputFolder);

    accept();
}

void SaveAsDialog::cancelButtonClicked()
{
    reject();
}

void SaveAsDialog::listAllMeshesFromScene()
{
    Ogre::SceneNode* node = mOgre->meshRootNode();

    std::vector<Ogre::Item*> items;
    collectMeshRecursively(node, items);

    for (const Ogre::Item* m : items)
    {
        qDebug() << m->getName().c_str();
    }

    createListItems(items);
}

void SaveAsDialog::collectMeshRecursively(Ogre::SceneNode* node, std::vector<Ogre::Item*>& ogreItems)
{
    size_t count = node->numAttachedObjects();
    for (size_t i = 0; i < count; ++i)
    {
        Ogre::Item* item = dynamic_cast<Ogre::Item*>(node->getAttachedObject(i));
        if (item)
        {
            ogreItems.push_back(item);
        }
    }

    for (int i = 0; i < node->numChildren(); ++i)
    {
        Ogre::SceneNode* child = static_cast<Ogre::SceneNode*>(node->getChild(i));
        collectMeshRecursively(child, ogreItems);
    }
}

void SaveAsDialog::collectNodeRecursively(Ogre::SceneNode* node, std::vector<Ogre::SceneNode*>& ogreNodes)
{
    ogreNodes.push_back(node);

    for (int i = 0; i < node->numChildren(); ++i)
    {
        Ogre::SceneNode* child = static_cast<Ogre::SceneNode*>(node->getChild(i));
        collectNodeRecursively(child, ogreNodes);
    }
}

void SaveAsDialog::createListItems(const std::vector<Ogre::Item*>& ogreItems)
{
    for (Ogre::Item* i : ogreItems)
    {
        QString meshName = QString::fromStdString(i->getName());

        QListWidgetItem* listItem = new QListWidgetItem(meshName, ui->listWidget);
        listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable);
        listItem->setCheckState(Qt::Checked);

        QVariantMeshWrapper wrapper;
        wrapper.item = i;
        listItem->setData(Qt::UserRole, QVariant::fromValue(wrapper));

        ui->listWidget->addItem(listItem);
    }

    //QSignalBlocker b(ui->selectAllCheckbox);
    //ui->selectAllCheckbox->setChecked(true);
}

void SaveAsDialog::lockListWidget()
{
    QListWidget* listWidget = ui->listWidget;
    for (int i = 0; i < listWidget->count(); ++i)
    {
        QListWidgetItem* item = listWidget->item(i);
        item->setFlags(Qt::NoItemFlags);
    }
    QApplication::processEvents(QEventLoop::DialogExec);
}

void SaveAsDialog::saveOgreMeshes(const std::vector<Ogre::Item*>& ogreItems)
{
    for (int i = 0; i < ogreItems.size(); ++i)
    {
        applySubMeshMaterialNames(ogreItems[i]);

        QString meshName = validateFileName(QString::fromStdString(ogreItems[i]->getMesh()->getName()));

        QString fullPath = QDir(mOutputFolder).filePath(meshName);
        Ogre::Mesh* mesh = ogreItems[i]->getMesh().get();

        Ogre::Root* root = mOgre->ogreRoot();
        Ogre::MeshSerializer meshSerializer2(root->getRenderSystem()->getVaoManager());
        meshSerializer2.exportMesh(mesh, fullPath.toStdString());

        saveHlmsJson(ogreItems[i]);

        ui->progressBar->setValue(i + 1);
        QApplication::processEvents(QEventLoop::DialogExec);
    }
}

void SaveAsDialog::saveHlmsJson(const Ogre::Item* ogreItem)
{
    auto hlmsManager = Ogre::Root::getSingleton().getHlmsManager();

    size_t numSubItem = ogreItem->getNumSubItems();
    for (int i = 0; i < numSubItem; ++i)
    {
        Ogre::HlmsDatablock* datablock = ogreItem->getSubItem(i)->getDatablock();

        Ogre::HlmsJson hlmsJson(hlmsManager, nullptr);
        std::string outJson;
        hlmsJson.saveMaterial(datablock, outJson, "");

        QString outputPath = QDir(mOutputFolder).filePath(datablock->getNameStr()->c_str());
        if (!outputPath.endsWith(".material.json"))
        {
            outputPath.append(".material.json");
        }

        QFile f(outputPath);
        if (f.open(QFile::WriteOnly))
        {
            QTextStream fout(&f);
            fout.setCodec("UTF-8");
            fout << QString::fromStdString(outJson);
        }
        f.close();

        qDebug() << "Write Hlms Json: " << outputPath;
    }
}

QString SaveAsDialog::validateFileName(QString fileName)
{
    if (fileName.endsWith(" (v1)"))
    {
        fileName = fileName.mid(0, fileName.size() - 5); // remove the (v1) part
    }

    if (fileName.endsWith(".mesh.xml"))
    {
        fileName = fileName.mid(0, fileName.size() - 4); // remove the .xml part
    }

    if (!fileName.endsWith(".mesh"))
    {
        fileName.append(".mesh"); // make sure the file extension is .mesh
    }
    return fileName;
}

void SaveAsDialog::applySubMeshMaterialNames(Ogre::Item* ogreItem)
{
    // Otherwise the exported mesh won't contain the material name.
    // Check OgreMesh2SerializerImpl.cpp line 269 (in MeshSerializerImpl::writeSubMesh())

    size_t numSubItems = ogreItem->getNumSubItems();
    for (size_t i = 0; i < numSubItems; ++i)
    {
        std::string datablockName = *ogreItem->getSubItem(i)->getDatablock()->getNameStr();
        ogreItem->getSubItem(i)->getSubMesh()->setMaterialName(datablockName);
    }
}

void SaveAsDialog::saveLuaScript(const std::vector<Ogre::SceneNode*>& nodes, const std::vector<Ogre::Item*>& ogreItems)
{
    // This function is just for my engine.
    QString fileName = "mesh_load2.lua";
    QString fullPath = QDir(mOutputFolder).filePath(fileName);

    QFile f(fullPath);
    if (!f.open(QFile::WriteOnly))
        return;

    QTextStream fout(&f);
    fout << "local node_list = {}\n";

    for (size_t i = 0; i < nodes.size(); ++i)
    {
        Ogre::SceneNode* node = nodes[i];
        Ogre::Vector3 pos = node->getPosition();

        const Ogre::Quaternion quaternion = node->getOrientation();
        Ogre::Matrix3 matrix3;
        quaternion.ToRotationMatrix(matrix3);

        Ogre::Radian rx, ry, rz;
        matrix3.ToEulerAnglesXYZ(rx, ry, rz);

        Ogre::Vector3 scale = node->getScale();

        QString parentNodeName = (node == mOgre->meshRootNode()) ? "main_building" : QString::fromStdString(node->getParent()->getName());

        QString line = QString("node_list[%1] = { name=\"%2\", pos={x=%3, y=%4, z=%5}, rot={x=%6, y=%7, z=%8}, scale={x=%9, y=%10, z=%11}, parent=\"%12\" }")
            .arg(i)
            .arg(node->getName().c_str())
            .arg(pos.x, 0, 'f', 4)
            .arg(pos.y, 0, 'f', 4)
            .arg(pos.z, 0, 'f', 4)
            .arg(rx.valueDegrees(), 0, 'f', 4)
            .arg(ry.valueDegrees(), 0, 'f', 4)
            .arg(rz.valueDegrees(), 0, 'f', 4)
            .arg(scale.x, 0, 'f', 4)
            .arg(scale.y, 0, 'f', 4)
            .arg(scale.z, 0, 'f', 4)
            .arg(parentNodeName);

        fout << line << "\n";
    }

    QString funcNodes = ""
        "\n"
        "function create_nodes() \n"
        "\n"
        "    for key, value in pairs(node_list) do \n"
        "        local node_name = value.name \n"
        "        log_info(key .. ': ' .. node_name) \n"
        "\n"
        "        local parent_node = get_object_by_name(value.parent) \n"
        "\n"
        "        local node = create_persistent_object('CSceneNodeOgre') \n"
        "        node:set_name(node_name) \n"
        "        node:set_ref('Parent', parent_node) \n"
        "        node:set_vec3('Position', { x = value.pos.x, y = value.pos.y, z = value.pos.z }) \n"
        "        node:set_vec3('Rotation', { x = value.rot.x, y = -value.rot.y, z = value.rot.z }) \n"
        "        node:set_vec3('Scale',    { x = value.scale.x, y = value.scale.y, z = value.scale.z }) \n"
        "        node:set_bool('Is Pickable', false) \n"
        "        node:signal_attribute('Parent') \n"
        "        node:signal_attribute('Name') \n"
        "        node:signal_attribute('Position') \n"
        "        node:signal_attribute('Rotation') \n"
        "        node:signal_attribute('Scale') \n"
        "    end \n"
        "end \n";

    fout << funcNodes;
    fout.flush();

    fout << "local mesh_list = {}\n";

    for (size_t i = 0; i < ogreItems.size(); ++i)
    {
        Ogre::Item* item = ogreItems[i];

        QString line = QString("mesh_list[%1] = { name=\"Mesh_%2\", mesh=\"%3\", parent=\"%4\" }")
            .arg(i)
            .arg(QString::fromStdString(item->getName()))
            .arg(QString::fromStdString(item->getMesh()->getName()))
            .arg(QString::fromStdString(item->getParentNode()->getName()));
        fout << line << "\n";
    }
    fout << "\n";

    QString func = "\n"
        "function create_meshes() \n"
        "    local mesh_map = {} \n"

        "    for key, value in pairs(mesh_list) do \n"
        "        local path = 'script/' .. value.mesh .. '.mesh' \n"
        "        log_info(path) \n"
        "\n"
        "        local parent_node = get_object_by_name(value.parent) \n"
        "\n"
        "        local mesh = mesh_map[value.mesh]\n"
        "        if mesh == nil then\n"
        "            mesh = create_persistent_object('COgreMesh')\n"
        "            mesh:set_string('Path', path)\n"
        "            mesh_map[value.mesh] = mesh\n"
        "        end\n"
        "\n"
        "        local node = create_persistent_object('CSceneNodeOgreMesh') \n"
        "        node:set_name(value.name) \n"
        "        node:set_ref('Ogre Mesh', mesh) \n"
        "        node:set_ref('Parent', parent_node) \n"
        "        node:set_bool('Is Pickable', false) \n"
        "        node:signal_attribute('Parent') \n"
        "        node:signal_attribute('Name') \n"
        "    end \n"
        "end \n";

    fout << func;

    fout << "\n"
        "function go()\n"
        "    create_nodes()\n"
        "    create_meshes()\n"
        "end";

    fout.flush();

    f.close();
}


layout: post
title: "Tools of a Developer"
modified:
categories: blog
excerpt: "These are my tools. Hopefully, they're always improving."
tags: [setup,tools]
---

One thing I'm always on the lookout for when someone opens up their laptop in
front of me is what are the tools they use. This could be anything from their
mail client to their terminal emulator. I check their operating system version.
I look at all the icons on their screen and the windows that are open. I don't
do this to be a creep. I do it because I want to know the latest and
greatest tools people use and see if it's better than what I'm using at that
moment.

So in that vain, here's what I'm using at the moment. This is likely to change
(frequently) because of what I just said above, but I think it's always a useful
snapshot to keep track of these things. I'll probably write more detailed posts
about a lot of them later.

### Hardware

* [Early 2015 MacBook Pro 13" Retina](https://support.apple.com/kb/sp715?locale=en_US)
  * I've been using a Mac since I started grad school and I've never looked back.
    When I was an undergrad with nothing but time, I had a Linux box as my main
    development workstation, but at some point I got tired of doing more system
    administration than software development and gave a Mac a try. Ever since,
    Apple has done a great job of making new hardware (albeit sometimes pricy)
    and I'll keep buying it as far out as I can see. Windows has never been an
    option for me as I can't develop most of the software I work on directly on
    the machine so I'd always either have to be in a VM or an SSH session.
* [Code Keyboard](https://codekeyboards.com/)
  * After reading for years about how great mechanical keyboards are, I finally
    gave this keyboard a shot. I won't say that it's changing my life. I didn't
    get the one with the super clacky keys so my co-workers wouldn't throw things
    at me, but I can't really tell a massive difference between this and a regular
    old rubber dome keyboard. I'd still like to try out the new Apple keyboards
    with the butterfly springs, but it's hard to justify buying another new one.
* [Magic Trackpad 2](https://www.apple.com/shop/product/MJ2R2LL/A/magic-trackpad-2)
  * I love thing thing. It's got lots of nice gesture shortcuts that work well
    with the Mac (for things like starting Expose or Mission Control or whatever
    it's called now). 3-finger dragging is a must for quick selection. It also
    doesn't cramp up your hand the way a mouse can. I won't be doing any gaming
    on this thing, but I have a real mouse for that at home.
* [Fellowes Memory Foam Wrist Rest](https://www.amazon.com/gp/product/B0013CEY0Q)
  * If you're going to use a keyboard, you need a place to put your wrists. I
    picked this one up on Amazon because it was the right size and it was cheap.
    No complaints.
* BenQ GW2765 27" Monitor
  * I didn't really get to pick my monitor at work. I had the option of two low-res
    Dell monitors or this higher resolution one. I picked this one because I've
    never really gotten my workflow to do well with two monitors. I have the one
    big monitor in the center of my desk and the laptop to the side for extra
    windows that I can push over there (documentation, etc.).
* Laptop holder from bathroom stall as laptop stand
  * This was literally a curved piece of metal sitting in a closet somewhere.
    Turns out it's hung on the back of bathroom stalls for people to put their
    laptops in while using the bathroom. Here's hoping this one wasn't in there
    long.
* [Plantronics Backbeat PRO Bluetooth Headphones](http://a.co/2jMNcX9)
  * I don't have great things to say about these. I love the fact that they're
    bluetooth so I stop accidentally pulling the wires out of the headphones
    and/or the computer. However, there's an awful lot of interference that
    results in a clicking/skipping sound when listening to music. At some point,
    I might try using some Bose QC 35's to see if they have the same problem.
* Pen and notebook
  * I take notes. This is where they go. I've tried lots of digital note-taking
    apps, but on the iPad, the writing fidelity is horrible. When typing, I often
    can't keep up with what's going on or I get distracted. The downside is that
    I have to carry a physical thing around though.
* [Fellowes Monitor Stand](https://www.amazon.com/dp/B00006B8J2)
  * I'm pretty tall so having something to get my monitor up to the right height
    is important. They had a bunch of these sitting around at work and it does
    the job. To be fair though, if these weren't around, I would have just used
    a stack of books or something.

### Communication

* Mail
  * Mail.app
    * I've gone back and forth with just about every mail client for Mac. In the
      end, the reason I keep ending up back with the stock app is mostly the
      fault of where I work. It's hard for me to use the non-stock mail app on
      my phone which means I lose a lot of the benefit of the kinds of apps that
      let you "snooze" emails. I'd love to have that ability, but until I can
      get it everywhere, it's not as useful.
  * [Outlook for Mac](https://products.office.com/en-us/outlook/email-and-calendar-software-microsoft-outlook)
    * From time to time, I have to fire up Outlook for work. Usually because I
      want to schedule a meeting and need to be able to best integrate with the
      Exchange server. I don't use this as a daily driver.
* Calendar
  * Calendar.app
    * I've tried a few different alternatives here too, but end up going back to
      the default calendar app because I keep using the default mail app. It's
      very nice to have a mail and calendar app that work together well.
* Instant Messaging
  * [Slack](www.slack.com)
    * Depending on who I need to talk to, I have to use different chat
      clients/servers. In the end though, this is my favorite. It's available
      everywhere. The clients do a good job of exposing features. Notifications
      are good. Lots of integrations. It pretty much does it all.
  * [Rocket.Chat](https://rocket.chat/)
    * Rocket.Chat isn't too bad. It's a poor man's Slack. The reason I use it is
      because we need to have a self-hosted chat client for work and this is
      pretty much all there is. Our install is somewhat crippled due to firewall
      restrictions or I might like it better.
  * Messages.app
    * This is pretty much just used for texting. If you use iMessages, you use
      this.
  * [Skype for Business](https://www.skype.com/en/business/skype-for-business/)
    * This is my least favorite. I have to use it because of work, but I get out
      of it as much as possible. It is still not feature complete (compared to
      the Lync client that it replaced) even after a 1.0 release. It drops
      connections from time to time. It's a **huge** battery hog. It has
      terrible syncing between the desktop and mobile clients. This is a last
      resort.

### Music

* [Spotify (Paid)](https://www.spotify.com/us/)
  * I've tried Amazon Music and Apple Music and I keep coming back to Spotify.
    For me, the differentiator is the curated playlist selection. I like to
    listen to music while at work and I don't want to spend a bunch of time
    picking the next song. Apple and Amazon's playlists are too short and I have
    to pick a new playlist every hour or two. Pandora requires that I know more
    about what I want to listen to before I start (need to "seed" my playlists
    well). I like that Spotify has lots of ambient lists that I can trust to not
    get in my way while I'm trying to work.

### Browser

* [Chrome](https://www.google.com/chrome/)
  * I recently built a Windows PC at home so I decided to switch back to Chrome
    to have a cross-platform browser. I like that Safari is more integrated with
    the OS, but I've also found that Chrome tends to work with more websites,
    especially those that are said to be "IE-only" at work.

### Command Line

* [Neovim](https://neovim.io/)
  * I'm a Vim diehard. Mostly because I never learned Emacs. It's not that I
    have a good argument why Vim is better. I'm just lazy. That being said, I
    did switch over hardcore to Neovim. The big winner here over regular Vim is
    asynchronous background threads for plugins. I use tons of plugins (probably
    discuss that in a different post) and some of them, like linters are pretty
    painful if they block the main thread. Imagine typing and your linter kicks
    in for 2 seconds. You can't get any response from the UI until it's done
    compiling. That's not ok. Don't be that guy. Use Neovim.
* [iTerm2](https://www.iterm2.com/)
  * This is a big improvement over the default Terminal app in MacOS. I'll admit
  that it's been a long time since I"ve use the default app, but at least when I
  switched, iTerm2 had much better handling of splits and windows. Since then,
  the killer feature has been built-in support for remote tmux sessions. I can
  now create and manipulate my splits and windows seamlessly. It's awesome.
* [tmux](https://tmux.github.io/)
  * In my last job, I was able to use mosh. It was awesome. I loved it. My
    sessions just never died. I'd lose a connection. Go home. Get on a plane.
    Doesn't matter. The ssh connection was always there. Fast forward to my new
    job and mosh is no longer an option. Next best thing, I use tmux. Sessions
    always stay alive even when I go home for the day. Combined with the
    integration with iTerm2, this makes working much easier. I no longer fear
    putting my laptop to sleep.
* [bash](https://www.gnu.org/software/bash/)
  * I've tried a few different shells. In the end, I've found them all to be
    pretty similar. Fish was pretty cool, but not really supported everywhere
    (as in, not installed by default) which meant I had to maintain two different
    versions of my environment setup depending on the shell. I gave up on that
    and decided to go with the old standby so I wouldn't have to worry about
    where I was.

### Utilities

* [Alfred 3 (w/ Powerpack)](https://www.alfredapp.com/)
  * This is a great shortcut tool. I use it to search for files on my computer,
    launch applications, open ssh connections, remember passwords, do quick
    calculations, put my computer to sleep, open system preferences, and
    probably a bunch more.
* [KeepingYouAwake](https://github.com/newmarcel/KeepingYouAwake)
  * This is a handy little tool to keep your computer from going to sleep. It's
    really nice when presenting or sitting in a meeting where you're doing
    something (like Powerpoint) that wouldn't otherwise force your computer to
    stay awake.
* [Parallels](https://www.parallels.com/)
  * I haven't tried that many virtualization options on the Mac because I've
    usually had access to Parallels through work and it's always been a pretty
    good solution for me. I work in here very sparingly so I don't have a lot to
    say either way about it.
* [Reeder](http://reederapp.com/mac/)
  * I subscribe to a **lot** of different RSS feeds and Reeder (synced via
    Feedly) is a great way to track and read all of them. It works with lots of
    different services (I use Instapaper for things I don't read immediately)
    and has a pretty good way of displaying articles by default and a good
    browser fallback when necessary.
* [LastPass](https://www.lastpass.com/)
  * This is a must have at this point as I have way too many passwords to
    remember. At one point, we could all just use that one password for everything
    but now a combination of security and password requirements make it hard to
    continue that model. LastPass does a great job of both creating new passwords
    and remembering all of them for you. It will even do an analysis and tell you
    where you have a bunch of duplicated passwords and change (many) of them for
    you automatically. I also have an Alfred plugin so I can access these things
    in any application.


package birdz.lib.environment;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;

public class Goal extends EnvObject {

	private int size = 50;

	public Goal(int x, int y, int size) {
		this.setPosition(x,y);
		this.size = size;
	}

	@Override
	public boolean isTouching(Point p) {
		if(p.x >= this.getRoundedPosition().x && p.x < this.getRoundedPosition().x + size &&
				p.y >= this.getRoundedPosition().y && p.y < this.getRoundedPosition().y + size) return true;
		return false;
	}

	@Override
	public Point[] getHitbox() {
		// TODO Auto-generated method stub
		return new Point[]{new Point(this.getRoundedPosition().x + (size/2), this.getRoundedPosition().y + (size/2))};
	}

	@Override
	public void paint(Graphics g, int x, int y) {
		g.setColor(Color.CYAN);
		g.fillRect(this.getRoundedPosition().x, this.getRoundedPosition().y, size, size);

	}

	@Override
	public EnvObject copy() {
		return new Goal(this.getRoundedPosition().x, this.getRoundedPosition().y, size);
	}

}


'use strict'

const path = require('path')
const os = require('os')
const test = require('tape')
const { GelfFactory } = require(path.resolve('lib/gelf/index.js'))

test('GELFMessageFactory should create basic gelf message with short and detailed message', (t) => {
  t.plan(1)
  const gelfJson = GelfFactory({source: os.hostname(), }, '5')
  const gelfRequiredFields = {
    'version': '1.1',
    'host': os.hostname(),
    'level': 5,
    'short_message': 'short_message not set'
  }
  t.deepEqual(gelfRequiredFields, gelfJson)
})

test('GELFMessageFactory should create gelf message with data', (t) => {
  t.plan(1)
  const gelfJson = GelfFactory({source: os.hostname(), facility: 'some facility', full_message: 'some full message', short_message: 'some short message'}, 'notice')
  const gelfExpectedJson = {
    'version': '1.1',
    'host': os.hostname(),
    'level': 5,
    'short_message': 'some short message',
    'full_message': 'some full message',
    '_facility': 'some facility'
  }
  t.deepEqual(gelfJson, gelfExpectedJson)
})

test('GELFMessageFactory should delete id key', (t) => {
  t.plan(1)
  const gelfJson = GelfFactory({source: os.hostname(), facility: 'some facility', full_message: 'some full message', id: '1', short_message: 'some short message'}, 'notice')
  const gelfExpectedJson = {
    'version': '1.1',
    'host': os.hostname(),
    'level': 5,
    'short_message': 'some short message',
    'full_message': 'some full message',
    '_facility': 'some facility'
  }
  t.deepEqual(gelfJson, gelfExpectedJson)
})

test('Testing tags', (t) => {
  t.plan(8)
  const gelfJsonEmergency = GelfFactory({source: os.hostname(), }, 'emergency')
  const gelfExpectedJsonEmergency = {
    'version': '1.1',
    'host': os.hostname(),
    'level': 0,
    'short_message': 'short_message not set',
  }
  const gelfJsonAlert = GelfFactory({source: os.hostname(), }, 'alert')
  const gelfExpectedJsonAlert = {
    'version': '1.1',
    'host': os.hostname(),
    'level': 1,
    'short_message': 'short_message not set',
  }
  const gelfJsonCritical = GelfFactory({source: os.hostname(), }, 'critical')
  const gelfExpectedJsonCritical = {
    'version': '1.1',
    'host': os.hostname(),
    'level': 2,
    'short_message': 'short_message not set',
  }
  const gelfJsonError = GelfFactory({source: os.hostname(), }, 'error')
  const gelfExpectedJsonError = {
    'version': '1.1',
    'host': os.hostname(),
    'level': 3,
    'short_message': 'short_message not set',
  }
  const gelfJsonWarning = GelfFactory({source: os.hostname(), }, 'warning')
  const gelfExpectedJsonWarning= {
    'version': '1.1',
    'host': os.hostname(),
    'level': 4,
    'short_message': 'short_message not set',
  }
  const gelfJsonNotice = GelfFactory({source: os.hostname(), }, 'notice')
  const gelfExpectedJsonNotice= {
    'version': '1.1',
    'host': os.hostname(),
    'level': 5,
    'short_message': 'short_message not set',
  }
  const gelfJsonInfo = GelfFactory({source: os.hostname(), }, 'info')
  const gelfExpectedJsonInfo= {
    'version': '1.1',
    'host': os.hostname(),
    'level': 6,
    'short_message': 'short_message not set',
  }
  const gelfJsonDebug = GelfFactory({source: os.hostname(), }, 'debug')
  const gelfExpectedJsonDebug= {
    'version': '1.1',
    'host': os.hostname(),
    'level': 7,
    'short_message': 'short_message not set',
  }
  t.deepEqual(gelfJsonEmergency, gelfExpectedJsonEmergency)
  t.deepEqual(gelfJsonAlert, gelfExpectedJsonAlert)
  t.deepEqual(gelfJsonCritical, gelfExpectedJsonCritical)
  t.deepEqual(gelfJsonError, gelfExpectedJsonError)
  t.deepEqual(gelfJsonWarning, gelfExpectedJsonWarning)
  t.deepEqual(gelfJsonNotice, gelfExpectedJsonNotice)
  t.deepEqual(gelfJsonInfo, gelfExpectedJsonInfo)
  t.deepEqual(gelfJsonDebug, gelfExpectedJsonDebug)
})


@font-face {
    font-family: 'Gibson';
    src: url('Gibson-Regular-webfonteccb.eot?3');
    src: url('Gibson-Regular-webfont95c6.eot?3?#iefix') format('embedded-opentype'),
         url('Gibson-Regular-webfonteccb.woff?3') format('woff'),
         url('Gibson-Regular-webfonteccb.ttf?3') format('truetype'),
         url('Gibson-Regular-webfonteccb.svg?3#GibsonRegular') format('svg');
    font-weight: normal;
    font-style: normal;

}

@font-face {
    font-family: 'Gibson';
    src: url('Gibson-SemiBold-webfonteccb.eot?3');
    src: url('Gibson-SemiBold-webfont95c6.eot?3?#iefix') format('embedded-opentype'),
         url('Gibson-SemiBold-webfonteccb.woff?3') format('woff'),
         url('Gibson-SemiBold-webfonteccb.ttf?3') format('truetype'),
         url('Gibson-SemiBold-webfonteccb.svg?3#GibsonLightBold') format('svg');
    font-weight: bold;
    font-style: normal;

}

@font-face {
    font-family: 'Gibson';
    src: url('Gibson-Italic-webfonteccb.eot?3');
    src: url('Gibson-Italic-webfont95c6.eot?3?#iefix') format('embedded-opentype'),
         url('Gibson-Italic-webfonteccb.woff?3') format('woff'),
         url('Gibson-Italic-webfonteccb.ttf?3') format('truetype'),
         url('Gibson-Italic-webfonteccb.svg?3#GibsonItalic') format('svg');
    font-weight: normal;
    font-style: italic;

}

@font-face {
    font-family: 'Gibson';
    src: url('Gibson-SemiBoldItalic-webfonteccb.eot?3');
    src: url('Gibson-SemiBoldItalic-webfont95c6.eot?3?#iefix') format('embedded-opentype'),
         url('Gibson-SemiBoldItalic-webfonteccb.woff?3') format('woff'),
         url('Gibson-SemiBoldItalic-webfonteccb.ttf?3') format('truetype'),
         url('Gibson-SemiBoldItalic-webfonteccb.svg?3#GibsonLightBoldItalic') format('svg');
    font-weight: bold;
    font-style: italic;

}


'use strict';

module.exports = function(grunt) {
  var path = require('path');

  // These plugins provide necessary tasks.
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-execute');
  grunt.loadNpmTasks('amber-dev');

  // Default task.
  grunt.registerTask('default', ['amberc:all']);
  grunt.registerTask('test', ['amberc:test_runner', 'execute:test_runner', 'clean:test_runner']);

  // Project configuration.
  grunt.initConfig({
    // Metadata.
    // pkg: grunt.file.readJSON(''),
    banner: '\n',
    // task configuration
    amberc: {
      options: {
        amber_dir: path.join(__dirname, "bower_components", "amber"),
        library_dirs: ['src'],
        closure_jar: ''
      },
      all: {
        src: [
            'src/Ephestos.st', // list all sources in dependency order
            'src/Ephestos-Tests.st' // list all tests in dependency order
        ],
        libraries: ['SUnit', 'Web']
      },
      test_runner: {
        src: ['node_modules/amber-dev/lib/Test.st'],
        libraries: [
          /* add dependencies packages here */
          'Ephestos', /* add other code-to-test packages here */
          'SUnit',
          'Ephestos-Tests' /* add other test packages here */
        ],
        main_class: 'NodeTestRunner',
        output_name: 'test_runner'
      }
    },

    execute: {
      test_runner: {
        src: ['test_runner.js']
      }
    },

    clean: {
      test_runner: ['test_runner.js']
    }
  });

};


<?php
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>

Congratulations!

You have successfully created your Yii-powered application.


const adjetiveisor = require('../adjetiveisor')
const adjet = adjetiveisor()

test('fails if no configured', () => {
  expect(adjet.translate('any text')).toBe('missing config')
})

test('fails if no text string provided', () => {
  adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' })
  expect(adjet.translate()).toBe('missing text')
})

test('translates "perro" into "puto perro"', () => {
  adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' })
  expect(adjet.translate('perro')).toBe('puto perro')
})

test('translates "el coche" into "el puto coche"', () => {
  adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' })
  expect(adjet.translate('el coche')).toBe('el puto coche')
})

test('does a correct translation on verbose config provided', () => {
  adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' })
  expect(adjet.translate('tengo mi coche en la acera')).toBe('tengo mi coche en la puta acera')
  adjet.verbose(true)
  expect(adjet.translate('tengo mi coche en la acera')).toBe('tengo mi puto coche en la puta acera')
  adjet.verbose(false)
})

test('removes duplicates', () => {
  adjet.config({ ms: 'puto', mp: 'putos', fs: 'puta', fp: 'putas' })
  expect(adjet.translate('el puto coche')).toBe('el puto coche')
})


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Package org.apache.hadoop.filecache (Hadoop 0.20.1 API)
</TITLE>

<META NAME="date" CONTENT="2009-09-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Package
org.apache.hadoop.filecache

No usage of org.apache.hadoop.filecache

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2009 The Apache Software Foundation


(function (window) {
    "use strict";

    var console = window.console,
        $ = window.jQuery,
        gui = window.gui,
        old = $.fn.guiNav;

    $.fn.guiNav = function (option) {

        var defaults = {
            styleName: "",
            itemFadeIn: true,
            animationDuration: 500
        };

        option = $.extend(defaults, option);

        this.each(function () {
            var $guiNav = $(this),
                isVertical = $guiNav.hasClass("gui-nav-vertical");

            if (option.styleName) {
                $guiNav.addClass(option.styleName);
            }

            $guiNav.find("li").mouseenter(function () {
                var $navItem = $(this),
                    $$subMenu = $navItem.children("ul");
                $$subMenu.css("left", (isVertical || !$navItem.parent().hasClass("gui-nav")) ? $navItem.width() : 0);
                if (option.itemFadeIn) {
                    $$subMenu.css("opacity", 0).animate({opacity: 1}, option.animationDuration);
                }
            });
        });

        return gui.plugin.patch($.fn.guiNav, this, option);
    };

    // NO CONFLICT
    // ===============

    $.fn.guiNav.noConflict = function () {
        $.fn.guiNav = old;
        return this;
    };

})(window);


<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Function template wrap_formatter</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="../../../expressions.html#header.boost.log.expressions.formatters.wrap_formatter_hpp" title="Header <boost/log/expressions/formatters/wrap_formatter.hpp>">
<link rel="prev" href="wrapped_formatter_terminal.html" title="Class template wrapped_formatter_terminal">
<link rel="next" href="wrap_for_idm45961920535920.html" title="Function template wrap_formatter">

Function template wrap_formatter

boost::log::expressions::wrap_formatter

Synopsis

// In header: <boost/log/expressions/formatters/wrap_formatter.hpp>

template<typename FunT> unspecified wrap_formatter(FunT const & fun);

Description

The function wraps a function object in order it to be able to participate in formatting expressions. The wrapped function object must be compatible with the following signature:

void (record_view const&, basic_formatting_ostream< CharT >&)

where CharT is the character type of the formatting expression.

Copyright © 2007-2021 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).


class Profile;
class WebRequestPermissions;

namespace extension_web_request_api_helpers {
struct EventResponseDelta;
}

namespace net {
class URLRequest;
}

namespace extensions {

class RulesRegistryService;

typedef linked_ptr<extension_web_request_api_helpers::EventResponseDelta>
    LinkedPtrEventResponseDelta;
typedef DeclarativeRule<WebRequestCondition, WebRequestAction> WebRequestRule;

// The WebRequestRulesRegistry is responsible for managing
// the internal representation of rules for the Declarative Web Request API.
//
// Here is the high level overview of this functionality:
//
// RulesRegistry::Rule consists of Conditions and Actions, these are
// represented as a WebRequestRule with WebRequestConditions and
// WebRequestRuleActions.
//
// WebRequestConditions represent JSON dictionaries as the following:
// {
//   'instanceType': 'URLMatcher',
//   'host_suffix': 'example.com',
//   'path_prefix': '/query',
//   'scheme': 'http'
// }
//
// The evaluation of URL related condition attributes (host_suffix, path_prefix)
// is delegated to a URLMatcher, because this is capable of evaluating many
// of such URL related condition attributes in parallel.
//
// For this, the URLRequestCondition has a URLMatcherConditionSet, which
// represents the {'host_suffix': 'example.com', 'path_prefix': '/query'} part.
// We will then ask the URLMatcher, whether a given URL
// "http://www.example.com/query/" has any matches, and the URLMatcher
// will respond with the URLMatcherConditionSet::ID. We can map this
// to the WebRequestRule and check whether also the other conditions (in this
// example 'scheme': 'http') are fulfilled.
class WebRequestRulesRegistry : public RulesRegistryWithCache {
 public:
  WebRequestRulesRegistry(Profile* profile, Delegate* delegate);

  // TODO(battre): This will become an implementation detail, because we need
  // a way to also execute the actions of the rules.
  std::set<const WebRequestRule*> GetMatches(
      const WebRequestData& request_data_without_ids) const;

  // Returns which modifications should be executed on the network request
  // according to the rules registered in this registry.
  std::list<LinkedPtrEventResponseDelta> CreateDeltas(
      const ExtensionInfoMap* extension_info_map,
      const WebRequestData& request_data,
      bool crosses_incognito);

  // Implementation of RulesRegistryWithCache:
  virtual std::string AddRulesImpl(
      const std::string& extension_id,
      const std::vector<linked_ptr<RulesRegistry::Rule> >& rules) OVERRIDE;
  virtual std::string RemoveRulesImpl(
      const std::string& extension_id,
      const std::vector<std::string>& rule_identifiers) OVERRIDE;
  virtual std::string RemoveAllRulesImpl(
      const std::string& extension_id) OVERRIDE;
  virtual content::BrowserThread::ID GetOwnerThread() const OVERRIDE;

  // Returns true if this object retains no allocated data. Only for debugging.
  bool IsEmpty() const;

 protected:
  virtual ~WebRequestRulesRegistry();

  // Virtual for testing:
  virtual base::Time GetExtensionInstallationTime(
      const std::string& extension_id) const;
  virtual void ClearCacheOnNavigation();

  const std::set<const WebRequestRule*>&
  rules_with_untriggered_conditions_for_test() const {
    return rules_with_untriggered_conditions_;
  }

 private:
  // Checks whether the set of |conditions| and |actions| are consistent,
  // meaning for example that we do not allow combining an |action| that needs
  // to be executed before the |condition| can be fulfilled.
  // Returns true in case of consistency and MUST set |error| otherwise.
  static bool CheckConsistency(const WebRequestConditionSet* conditions,
                               const WebRequestActionSet* actions,
                               std::string* error);

  typedef std::map<URLMatcherConditionSet::ID, WebRequestRule*> RuleTriggers;
  typedef std::map<WebRequestRule::GlobalRuleId, linked_ptr<WebRequestRule> >
      RulesMap;
  typedef std::set<URLMatcherConditionSet::ID> URLMatches;
  typedef std::set<const WebRequestRule*> RuleSet;

  // This is a helper function to GetMatches. Rules triggered by |url_matches|
  // get added to |result| if one of their conditions is fulfilled.
  // |request_data| gets passed to IsFulfilled of the rules' condition sets.
  void AddTriggeredRules(const URLMatches& url_matches,
                         const WebRequestCondition::MatchData& request_data,
                         RuleSet* result) const;

  // Map that tells us which WebRequestRule may match under the condition that
  // the URLMatcherConditionSet::ID was returned by the |url_matcher_|.
  RuleTriggers rule_triggers_;

  // These rules contain condition sets with conditions without URL attributes.
  // Such conditions are not triggered by URL matcher, so we need to test them
  // separately.
  std::set<const WebRequestRule*> rules_with_untriggered_conditions_;

  RulesMap webrequest_rules_;

  URLMatcher url_matcher_;

  scoped_refptr<ExtensionInfoMap> extension_info_map_;

  DISALLOW_COPY_AND_ASSIGN(WebRequestRulesRegistry);
};

}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_DECLARATIVE_WEBREQUEST_WEBREQUEST_RULES_REGISTRY_H_


package org.shaf.core.net;

/**
 * The {@code NetworkRequestException} occurs, when a network request is failed.
 *
 * @author Mykola Galushka
 */
@SuppressWarnings("serial")
public class NetworkRequestException extends NetworkException {

	/**
	 * Constructs a new {@code NetworkRequestException} object.
	 *
	 * @param uri
	 *            the requesting URI.
	 * @param message
	 *            the message.
	 * @param cause
	 *            the cause.
	 */
	public NetworkRequestException(final String message, final Throwable cause) {
		super(message, cause);
	}

	/**
	 * Constructs a new {@code NetworkRequestException} object.
	 *
	 * @param uri
	 *            the requesting URI.
	 * @param message
	 *            the message.
	 */
	public NetworkRequestException(final String message) {
		super(message);
	}
}


import {
  isStandardRule,
  ruleMessages,
  validateOptions,
} from "../../utils"

import { checkRuleEmptyLineBefore } from "../rule-non-nested-empty-line-before"

export const ruleName = "rule-nested-empty-line-before"

export const messages = ruleMessages(ruleName, {
  expected: "Expected empty line before nested rule",
  rejected: "Unexpected empty line before nested rule",
})

export default function (expectation, options) {
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, {
      actual: expectation,
      possible: [
        "always",
        "never",
        "always-multi-line",
        "never-multi-line",
      ],
    }, {
      actual: options,
      possible: {
        ignore: [
          "after-comment",
        ],
        except: [
          "first-nested",
          "after-comment",
        ],
      },
      optional: true,
    })
    if (!validOptions) { return }

    root.walkRules(rule => {

      if (!isStandardRule(rule)) { return }

      // Only attend to nested rule sets
      if (rule.parent === root) { return }

      checkRuleEmptyLineBefore({ rule, expectation, options, result, messages, checkedRuleName: ruleName })
    })
  }
}


function legcoeffs = chebcoeffs2legcoeffs(chebcoeffs)
%CHEBCOEFFS2LEGCOEFFS  Convert Chebyshev coefficients to Legendre coefficients.
%   C_LEG = CHEBCOEFFS2LEGCOEFFS(C_CHEB) converts the vector C_CHEB of Chebyshev
%   coefficients to a vector C_LEG of Legendre coefficients such that
%       C_CHEB(1)*T0 + ... + C_CHEB(N)*T{N-1} = ...
%           C_LEG(1)*P0 + ... + C_LEG(N)*P{N-1},
%   where P{k} is the degree k Legendre polynomial normalized so that
%   max(|P{k}|) = 1.
%
% See also CHEB2LEG.

% Copyright 2015 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

% This command is a wrapper for cheb2leg.
legcoeffs = cheb2leg(chebcoeffs);

end


package org.apache.hadoop.hive.ql;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.txn.TxnDbUtil;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.io.orc.FileDump;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * TODO: this should be merged with TestTxnCommands once that is checked in
 * specifically the tests; the supporting code here is just a clone of TestTxnCommands
 */
public class TestTxnCommands2 {
  private static final String TEST_DATA_DIR = new File(System.getProperty("java.io.tmpdir") +
    File.separator + TestTxnCommands2.class.getCanonicalName()
    + "-" + System.currentTimeMillis()
  ).getPath().replaceAll("\\\\", "/");
  private static final String TEST_WAREHOUSE_DIR = TEST_DATA_DIR + "/warehouse";
  //bucket count for test tables; set it to 1 for easier debugging
  private static int BUCKET_COUNT = 2;
  @Rule
  public TestName testName = new TestName();
  private HiveConf hiveConf;
  private Driver d;
  private static enum Table {
    ACIDTBL("acidTbl"),
    ACIDTBLPART("acidTblPart"),
    NONACIDORCTBL("nonAcidOrcTbl"),
    NONACIDPART("nonAcidPart");

    private final String name;
    @Override
    public String toString() {
      return name;
    }
    Table(String name) {
      this.name = name;
    }
  }

  @Before
  public void setUp() throws Exception {
    tearDown();
    hiveConf = new HiveConf(this.getClass());
    hiveConf.set(HiveConf.ConfVars.PREEXECHOOKS.varname, "");
    hiveConf.set(HiveConf.ConfVars.POSTEXECHOOKS.varname, "");
    hiveConf.set(HiveConf.ConfVars.HIVE_SUPPORT_CONCURRENCY.varname, "false");
    hiveConf.set(HiveConf.ConfVars.METASTOREWAREHOUSE.varname, TEST_WAREHOUSE_DIR);
    TxnDbUtil.setConfValues(hiveConf);
    hiveConf.setBoolVar(HiveConf.ConfVars.HIVEENFORCEBUCKETING, true);
    TxnDbUtil.prepDb();
    File f = new File(TEST_WAREHOUSE_DIR);
    if (f.exists()) {
      FileUtil.fullyDelete(f);
    }
    if (!(new File(TEST_WAREHOUSE_DIR).mkdirs())) {
      throw new RuntimeException("Could not create " + TEST_WAREHOUSE_DIR);
    }
    SessionState.start(new SessionState(hiveConf));
    d = new Driver(hiveConf);
    dropTables();
    runStatementOnDriver("create table " + Table.ACIDTBL + "(a int, b int) clustered by (a) into " + BUCKET_COUNT + " buckets stored as orc TBLPROPERTIES ('transactional'='true')");
    runStatementOnDriver("create table " + Table.ACIDTBLPART + "(a int, b int) partitioned by (p string) clustered by (a) into " + BUCKET_COUNT + " buckets stored as orc TBLPROPERTIES ('transactional'='true')");
    runStatementOnDriver("create table " + Table.NONACIDORCTBL + "(a int, b int) clustered by (a) into " + BUCKET_COUNT + " buckets stored as orc TBLPROPERTIES ('transactional'='false')");
    runStatementOnDriver("create table " + Table.NONACIDPART + "(a int, b int) partitioned by (p string) stored as orc TBLPROPERTIES ('transactional'='false')");
  }
  private void dropTables() throws Exception {
    for(Table t : Table.values()) {
      runStatementOnDriver("drop table if exists " + t);
    }
  }
  @After
  public void tearDown() throws Exception {
    try {
      if (d != null) {
     //   runStatementOnDriver("set autocommit true");
        dropTables();
        d.destroy();
        d.close();
        d = null;
      }
      TxnDbUtil.cleanDb();
    } finally {
      FileUtils.deleteDirectory(new File(TEST_DATA_DIR));
    }
  }
  @Ignore("not needed but useful for testing")
  @Test
  public void testNonAcidInsert() throws Exception {
    runStatementOnDriver("insert into " + Table.NONACIDORCTBL + " values(1,2)");
    List<String> rs = runStatementOnDriver("select a,b from " + Table.NONACIDORCTBL);
    runStatementOnDriver("insert into " + Table.NONACIDORCTBL + " values(2,3)");
    List<String> rs1 = runStatementOnDriver("select a,b from " + Table.NONACIDORCTBL);
  }
  @Test
  public void testUpdateMixedCase() throws Exception {
    int[][] tableData = {{1,2},{3,3},{5,3}};
    runStatementOnDriver("insert into " + Table.ACIDTBL + " " + makeValuesClause(tableData));
    runStatementOnDriver("update " + Table.ACIDTBL + " set B = 7 where A=1");
    List<String> rs = runStatementOnDriver("select a,b from " + Table.ACIDTBL + " order by a,b");
    int[][] updatedData = {{1,7},{3,3},{5,3}};
    Assert.assertEquals("Update failed", stringifyValues(updatedData), rs);
    runStatementOnDriver("update " + Table.ACIDTBL + " set B = B + 1 where A=1");
    List<String> rs2 = runStatementOnDriver("select a,b from " + Table.ACIDTBL + " order by a,b");
    int[][] updatedData2 = {{1,8},{3,3},{5,3}};
    Assert.assertEquals("Update failed", stringifyValues(updatedData2), rs2);
  }

  /**
   * https://issues.apache.org/jira/browse/HIVE-10151
   */
  @Test
  public void testBucketizedInputFormat() throws Exception {
    int[][] tableData = {{1,2}};
    runStatementOnDriver("insert into " + Table.ACIDTBLPART + " partition(p=1) " + makeValuesClause(tableData));

    runStatementOnDriver("insert into " + Table.ACIDTBL + " select a,b from " + Table.ACIDTBLPART + " where p = 1");
    List<String> rs = runStatementOnDriver("select a,b from " + Table.ACIDTBL);//no order by as it's just 1 row
    Assert.assertEquals("Insert into " + Table.ACIDTBL + " didn't match:", stringifyValues(tableData), rs);

    runStatementOnDriver("insert into " + Table.NONACIDORCTBL + " select a,b from " + Table.ACIDTBLPART + " where p = 1");
    List<String> rs2 = runStatementOnDriver("select a,b from " + Table.NONACIDORCTBL);//no order by as it's just 1 row
    Assert.assertEquals("Insert into " + Table.NONACIDORCTBL + " didn't match:", stringifyValues(tableData), rs2);
  }
  @Test
  public void testInsertOverwriteWithSelfJoin() throws Exception {
    int[][] part1Data = {{1,7}};
    runStatementOnDriver("insert into " + Table.NONACIDORCTBL + " " + makeValuesClause(part1Data));
    //this works because logically we need S lock on NONACIDORCTBL to read and X lock to write, but
    //LockRequestBuilder dedups locks on the same entity to only keep the highest level lock requested
    runStatementOnDriver("insert overwrite table " + Table.NONACIDORCTBL + " select 2, 9 from " + Table.NONACIDORCTBL + " T inner join " + Table.NONACIDORCTBL + " S on T.a=S.a");
    List<String> rs = runStatementOnDriver("select a,b from " + Table.NONACIDORCTBL + " order by a,b");
    int[][] joinData = {{2,9}};
    Assert.assertEquals("Self join non-part insert overwrite failed", stringifyValues(joinData), rs);
    int[][] part2Data = {{1,8}};
    runStatementOnDriver("insert into " + Table.NONACIDPART + " partition(p=1) " + makeValuesClause(part1Data));
    runStatementOnDriver("insert into " + Table.NONACIDPART + " partition(p=2) " + makeValuesClause(part2Data));
    //here we need X lock on p=1 partition to write and S lock on 'table' to read which should
    //not block each other since they are part of the same txn
    runStatementOnDriver("insert overwrite table " + Table.NONACIDPART + " partition(p=1) select a,b from " + Table.NONACIDPART);
    List<String> rs2 = runStatementOnDriver("select a,b from " + Table.NONACIDPART + " order by a,b");
    int[][] updatedData = {{1,7},{1,8},{1,8}};
    Assert.assertEquals("Insert overwrite partition failed", stringifyValues(updatedData), rs2);
    //insert overwrite not supported for ACID tables
  }
  /**
   * takes raw data and turns it into a string as if from Driver.getResults()
   * sorts rows in dictionary order
   */
  private List<String> stringifyValues(int[][] rowsIn) {
    assert rowsIn.length > 0;
    int[][] rows = rowsIn.clone();
    Arrays.sort(rows, new RowComp());
    List<String> rs = new ArrayList<String>();
    for(int[] row : rows) {
      assert row.length > 0;
      StringBuilder sb = new StringBuilder();
      for(int value : row) {
        sb.append(value).append("\t");
      }
      sb.setLength(sb.length() - 1);
      rs.add(sb.toString());
    }
    return rs;
  }
  private static final class RowComp implements Comparator<int[]> {
    public int compare(int[] row1, int[] row2) {
      assert row1 != null && row2 != null && row1.length == row2.length;
      for(int i = 0; i < row1.length; i++) {
        int comp = Integer.compare(row1[i], row2[i]);
        if(comp != 0) {
          return comp;
        }
      }
      return 0;
    }
  }
  private String makeValuesClause(int[][] rows) {
    assert rows.length > 0;
    StringBuilder sb = new StringBuilder("values");
    for(int[] row : rows) {
      assert row.length > 0;
      if(row.length > 1) {
        sb.append("(");
      }
      for(int value : row) {
        sb.append(value).append(",");
      }
      sb.setLength(sb.length() - 1);//remove trailing comma
      if(row.length > 1) {
        sb.append(")");
      }
      sb.append(",");
    }
    sb.setLength(sb.length() - 1);//remove trailing comma
    return sb.toString();
  }

  private List<String> runStatementOnDriver(String stmt) throws Exception {
    CommandProcessorResponse cpr = d.run(stmt);
    if(cpr.getResponseCode() != 0) {
      throw new RuntimeException(stmt + " failed: " + cpr);
    }
    List<String> rs = new ArrayList<String>();
    d.getResults(rs);
    return rs;
  }
}