text:
lib

Configuration, singleton. By default, NodeJS does caching on required objects in a way a singleton, so this is simply a Java-look-n-feel design.

lib

general controller functions used as REST services.

## Members

_

Created by psenger on 4/21/16.

## lib
Configuration, singleton. By default, NodeJS does caching on required objects in a way a singleton, so this is simply a Java-look-n-feel design.

**Date**: 04/21/2016
**Author:** philip.senger

* [lib](#module_lib)
    * _static_
        * [.getInstance()](#module_lib.getInstance) ⇒ \*
    * _inner_
        * [~query(options)](#module_lib..query) ⇒ query
        * [~detail(options)](#module_lib..detail) ⇒ detail

### lib.getInstance() ⇒ \*
Get the instance, create it if it doesnt exist.

**Kind**: static method of [lib](#module_lib)

### lib~query(options) ⇒ query
queryClosure

**Kind**: inner method of [lib](#module_lib)

| Param |
| --- |
| options |

### lib~detail(options) ⇒ detail
detailClosure

**Kind**: inner method of [lib](#module_lib)

| Param |
| --- |
| options |

## lib
general controller functions used as REST services.

**Date**: 04/21/2016
**Author:** philip.senger

* [lib](#module_lib)
    * _static_
        * [.getInstance()](#module_lib.getInstance) ⇒ \*
    * _inner_
        * [~query(options)](#module_lib..query) ⇒ query
        * [~detail(options)](#module_lib..detail) ⇒ detail

### lib.getInstance() ⇒ \*
Get the instance, create it if it doesnt exist.

**Kind**: static method of [lib](#module_lib)

### lib~query(options) ⇒ query
queryClosure

**Kind**: inner method of [lib](#module_lib)

| Param |
| --- |
| options |

### lib~detail(options) ⇒ detail
detailClosure

**Kind**: inner method of [lib](#module_lib)

| Param |
| --- |
| options |

## _
Created by psenger on 4/21/16.

**Kind**: global variable

redpajama_set_name: RedPajamaGithub


text:
package com.sap.cloud.lm.sl.cf.core.liquibase;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.sap.cloud.lm.sl.cf.core.message.Messages;
import com.sap.cloud.lm.sl.cf.persistence.changes.liquibase.AbstractChange;
import com.sap.cloud.lm.sl.cf.persistence.util.JdbcUtil;

import liquibase.database.jvm.JdbcConnection;

public class DropConfigurationRegistryUniqueConstraintPostgresqlChange extends AbstractChange {

    private static final String POSTGRESQL_SEARCH_QUERY = "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE TABLE_NAME='configuration_registry' and CONSTRAINT_TYPE='UNIQUE'";
    private static final String DROP_QUERY = "ALTER TABLE configuration_registry DROP CONSTRAINT %s";
    private static final String CONSTRAINT_NAME_COLUMN = "CONSTRAINT_NAME";

    @Override
    public String getConfirmationMessage() {
        return Messages.DROPPED_UNNAMED_UNIQUE_CONSTRAINT_FOR_CONFIGURATION_REGISTRY;
    }

    @Override
    protected void executeInTransaction(JdbcConnection jdbcConnection) throws Exception {
        String constraintName = retrieveConstraintName(jdbcConnection);
        dropConstraint(jdbcConnection, constraintName);
    }

    private String retrieveConstraintName(JdbcConnection jdbcConnection) throws Exception {
        PreparedStatement preparedStatement = null;
        ResultSet result = null;

        try {
            String searchQuery = getSearchQuery(jdbcConnection);
            preparedStatement = jdbcConnection.prepareStatement(searchQuery);
            result = preparedStatement.executeQuery();
            result.next();
            String constraintName = result.getString(CONSTRAINT_NAME_COLUMN);
            logger.info(String.format("Executed statement '%s' returned constraint name: %s", searchQuery, constraintName));
            return constraintName;
        } finally {
            JdbcUtil.closeQuietly(result);
            JdbcUtil.closeQuietly(preparedStatement);
        }
    }

    protected String getSearchQuery(JdbcConnection jdbcConnection) throws SQLException {
        return POSTGRESQL_SEARCH_QUERY;
    }

    private void dropConstraint(JdbcConnection jdbcConnection, String constraintName) throws Exception {
        Statement statement = null;

        try {
            statement = jdbcConnection.createStatement();
            String dropQuery = String.format(DROP_QUERY, constraintName);
            statement.execute(dropQuery);
            logger.info(String.format("Executed statement '%s'.", dropQuery));
        } finally {
            JdbcUtil.closeQuietly(statement);
        }
    }

}


text:
package stainless
package utils

import inox.utils._

import java.io.OutputStream

import scala.reflect._

import stainless.termination.{TerminationReport => TR}

class StainlessSerializer(override val trees: ast.Trees, serializeProducts: Boolean = false)
  extends InoxSerializer(trees, serializeProducts) {
  import trees._

  final inline def stainlessClassSerializer[T: ClassTag](inline id: Int): (Class[_], Serializer[T]) =
    classTag[T].runtimeClass -> stainlessClassSerializerMacro[T](this, id).asInstanceOf[Serializer[T]]

  /** An extension to the set of registered classes in the `InoxSerializer`.
    * occur within Stainless programs.
    *
    * The new identifiers in the mapping range from 120 to 172.
    *
    * NEXT ID: 173
    */
  override protected def classSerializers: Map[Class[_], Serializer[_]] =
    super.classSerializers ++ Map(
      stainlessClassSerializer[NoTree]             (120),
      stainlessClassSerializer[Error]              (121),
      stainlessClassSerializer[Require]            (122),
      stainlessClassSerializer[Annotated]          (123),
      stainlessClassSerializer[Ensuring]           (124),
      stainlessClassSerializer[Assert]             (125),
      stainlessClassSerializer[MatchExpr]          (126),
      stainlessClassSerializer[MatchCase]          (127),
      stainlessClassSerializer[WildcardPattern]    (128),
      stainlessClassSerializer[ADTPattern]         (129),
      stainlessClassSerializer[TuplePattern]       (130),
      stainlessClassSerializer[LiteralPattern[Any]](131),
      stainlessClassSerializer[UnapplyPattern]     (132),
      stainlessClassSerializer[FiniteArray]        (133),
      stainlessClassSerializer[LargeArray]         (134),
      stainlessClassSerializer[ArraySelect]        (135),
      stainlessClassSerializer[ArrayUpdated]       (136),
      stainlessClassSerializer[ArrayLength]        (137),
      stainlessClassSerializer[SizedADT]           (154),
      stainlessClassSerializer[Passes]             (158),

      stainlessClassSerializer[Max]                (160),

      // Stainless ast Types
      stainlessClassSerializer[ArrayType]    (138),
      stainlessClassSerializer[RecursiveType](152),
      stainlessClassSerializer[ValueType]    (153),
      stainlessClassSerializer[AnnotatedType](157),
      // Stainless Flags
      stainlessClassSerializer[Extern.type]      (139),
      stainlessClassSerializer[Opaque.type]      (140),
      stainlessClassSerializer[DropVCs.type]     (141),
      stainlessClassSerializer[Library.type]     (168),
      stainlessClassSerializer[Derived]          (142),
      stainlessClassSerializer[IsField]          (143),
      stainlessClassSerializer[IsUnapply]        (144),
      stainlessClassSerializer[ClassParamInit]   (170),
      stainlessClassSerializer[DropConjunct.type](171),
      stainlessClassSerializer[SplitVC.type]     (172),

      stainlessClassSerializer[TerminationStatus]      (161),
      stainlessClassSerializer[TR.Unknown.type]        (162),
      stainlessClassSerializer[TR.Terminating.type]    (163),
      stainlessClassSerializer[TR.NonTerminating.type] (164),

      mappingSerializer[SymbolIdentifier](145)
        (id => (id.globalId, id.id, id.symbol.path, id.symbol.id))
        (p => new SymbolIdentifier(new Identifier(p._3.last, p._1, p._2), new Symbol(p._3, p._4))),

      stainlessClassSerializer[PartialEval.type]    (146),
      stainlessClassSerializer[Law.type]            (150),
      stainlessClassSerializer[Ghost.type]          (147),
      stainlessClassSerializer[Private.type]        (148),
      stainlessClassSerializer[Final.type]          (149),
      stainlessClassSerializer[Decreases]           (151),
      stainlessClassSerializer[Erasable.type]       (155),
      stainlessClassSerializer[IndexedAt]           (156),
      stainlessClassSerializer[Wrapping.type]       (159),
      stainlessClassSerializer[Synthetic.type]      (165),
      stainlessClassSerializer[InlineInvariant.type](166),
      stainlessClassSerializer[Lazy.type]           (167),
      stainlessClassSerializer[Template.type]       (169),
    )
}

class XLangSerializer(override val trees: extraction.xlang.Trees, serializeProducts: Boolean = false)
  extends StainlessSerializer(trees, serializeProducts) {
  import trees._

  /** An extension to the set of registered classes in the `StainlessSerializer`.
    * occur within Stainless programs.
    *
    * The new identifiers in the mapping range from 180 to 261.
    *
    * NEXT ID: 262
    */
  override protected def classSerializers: Map[Class[_], Serializer[_]] =
    super.classSerializers ++ Map(
      // Termination trees
      stainlessClassSerializer[Decreases](180),

      // Induction trees
      stainlessClassSerializer[TraceInduct.type] (244),
      stainlessClassSerializer[Induct.type]      (258),
      stainlessClassSerializer[MkTest.type]      (261),

      // Inlining trees
      stainlessClassSerializer[Inline.type]    (181),
      stainlessClassSerializer[InlineOnce.type](228),

      // Inner-function trees
      stainlessClassSerializer[LocalFunDef](183),
      stainlessClassSerializer[LetRec]     (184),
      stainlessClassSerializer[ApplyLetRec](185),
      stainlessClassSerializer[Outer]      (186),
      stainlessClassSerializer[Inner]      (187),

      // Imperative trees
      stainlessClassSerializer[Block]                  (188),
      stainlessClassSerializer[LetVar]                 (189),
      stainlessClassSerializer[Assignment]             (190),
      stainlessClassSerializer[FieldAssignment]        (191),
      stainlessClassSerializer[While]                  (192),
      stainlessClassSerializer[ArrayUpdate]            (193),
      stainlessClassSerializer[Old]                    (194),
      stainlessClassSerializer[BoolBitwiseAnd]         (195),
      stainlessClassSerializer[BoolBitwiseOr]          (196),
      stainlessClassSerializer[BoolBitwiseXor]         (197),
      stainlessClassSerializer[IsVar.type]             (198),
      stainlessClassSerializer[IsMutable.type]         (199),
      stainlessClassSerializer[IsPure.type]            (230),
      stainlessClassSerializer[Snapshot]               (239),
      stainlessClassSerializer[MutableMapType]         (248),
      stainlessClassSerializer[MutableMapWithDefault]  (249),
      stainlessClassSerializer[MutableMapApply]        (250),
      stainlessClassSerializer[MutableMapUpdate]       (251),
      stainlessClassSerializer[MutableMapUpdated]      (252),
      stainlessClassSerializer[MutableMapDuplicate]    (253),
      stainlessClassSerializer[Swap]                   (259),
      stainlessClassSerializer[FreshCopy]              (260),
      stainlessClassSerializer[Reads]                  (182),
      stainlessClassSerializer[Modifies]               (210),

      // Object-oriented trees
      stainlessClassSerializer[ClassConstructor] (200),
      stainlessClassSerializer[ClassSelector]    (201),
      stainlessClassSerializer[IsInstanceOf]     (202),
      stainlessClassSerializer[AsInstanceOf]     (203),
      stainlessClassSerializer[ClassPattern]     (204),
      stainlessClassSerializer[InstanceOfPattern](205),
      stainlessClassSerializer[ClassType]        (206),
      stainlessClassSerializer[AnyType]          (207),
      stainlessClassSerializer[NothingType]      (208),
      // `UnionType` and `IntersectionType` are package-private to `oo`
      stainlessClassSerializer[TypeBounds]       (209),
      stainlessClassSerializer[ClassDef]         (222),
      stainlessClassSerializer[IsInvariant.type] (223),
      stainlessClassSerializer[IsAbstract.type]  (224),
      stainlessClassSerializer[IsSealed.type]    (225),
      stainlessClassSerializer[Bounds]           (226),
      stainlessClassSerializer[Variance]         (227),
      stainlessClassSerializer[IsCaseObject.type](229),
      stainlessClassSerializer[TypeSelect]       (237),
      stainlessClassSerializer[TypeApply]        (254),
      stainlessClassSerializer[TypeDef]          (255),
      stainlessClassSerializer[IsTypeMemberOf]   (246),

      // Inner classes trees
      stainlessClassSerializer[LetClass]             (232),
      stainlessClassSerializer[LocalClassDef]        (233),
      stainlessClassSerializer[LocalMethodDef]       (234),
      stainlessClassSerializer[LocalMethodInvocation](240),
      stainlessClassSerializer[LocalClassConstructor](235),
      stainlessClassSerializer[LocalClassSelector]   (241),
      stainlessClassSerializer[LocalClassType]       (236),
      stainlessClassSerializer[LocalThis]            (242),
      stainlessClassSerializer[LocalTypeDef]         (247),

      // Throwing trees
      stainlessClassSerializer[Throwing](211),
      stainlessClassSerializer[Throw]   (212),
      stainlessClassSerializer[Try]     (213),
      stainlessClassSerializer[Return]  (257),

      // Methods trees
      stainlessClassSerializer[This]            (214),
      stainlessClassSerializer[Super]           (215),
      stainlessClassSerializer[MethodInvocation](216),
      stainlessClassSerializer[IsMethodOf]      (217),
      stainlessClassSerializer[IsAccessor]      (231),
      stainlessClassSerializer[ValueClass.type] (243),

      // XLang trees
      stainlessClassSerializer[Ignore.type]     (218),
      stainlessClassSerializer[FieldDefPosition](245),
      stainlessClassSerializer[Import]          (219),
      stainlessClassSerializer[UnitDef]         (220),
      stainlessClassSerializer[ModuleDef]       (221),
      stainlessClassSerializer[UnknownType]     (238),
      stainlessClassSerializer[StrictBV.type]   (256),
    )
}

object Serializer {
  def apply(t: ast.Trees, serializeProducts: Boolean = false): Serializer { val trees: t.type } =
    (t match {
      case xt: extraction.xlang.Trees => new XLangSerializer(xt)
      case _ => new StainlessSerializer(t)
    }).asInstanceOf[Serializer { val trees: t.type }]
}


text:
package org.jasig.portal.security.provider.cas;

import java.util.ArrayList;
import java.util.List;
import java.security.Principal;

import junit.framework.TestCase;

/**
 * A JUnit test that exercises the CasSecurityContextMock mock object.
 * The mock object is useless if it cannot be relied upon to correctly emulate
 * an ICasSecurityContext instance as configured.  This test is intended to
 * increase confidence that the mock object behaves as advertised.
 */
public class CasSecurityContextMockTest
    extends TestCase {

    /**
     * Test that the mock object properly logs targets.
     */
    public void testTargetsLog() throws CasProxyTicketAcquisitionException {

        CasSecurityContextMock mock = new CasSecurityContextMock();

        mock.getCasServiceToken("aTarget");
        mock.getCasServiceToken("anotherTarget");

        List expectedTargets = new ArrayList();
        expectedTargets.add("aTarget");
        expectedTargets.add("anotherTarget");

        assertEquals(expectedTargets, mock.getServiceTokenTargets());

    }

    /**
     * Test that the mock object returns and throws as designed.
     */
    public void testProgrammedReturns() {
        CasSecurityContextMock mock = new CasSecurityContextMock();

        List dummyProxyTickets = new ArrayList();
        dummyProxyTickets.add("token1");
        dummyProxyTickets.add("token2");

        mock.setServiceTokensToVend(dummyProxyTickets);

        try {
            assertEquals("token1", mock.getCasServiceToken("aTarget"));
            assertEquals("token2", mock.getCasServiceToken("anotherTarget"));
        } catch (CasProxyTicketAcquisitionException cptae) {
            fail("Threw where should have returned the given Strings.");
        }

        List vendedTokens = new ArrayList();
        vendedTokens.add("token1");
        vendedTokens.add("token2");

        assertEquals(vendedTokens, mock.getVendedServiceTokens());

        List dummyExceptions = new ArrayList();
        RuntimeException dummyRuntimeException = new RuntimeException();
        dummyExceptions.add(dummyRuntimeException);

        CasProxyTicketAcquisitionException cptae
            = new CasProxyTicketAcquisitionException("dummyservice", new Principal() {
            public String getName() {
                return "test";
            }
        });

        dummyExceptions.add(cptae);

        mock.setServiceTokensToVend(dummyExceptions);

        boolean exceptionThrown = false;
        try {
            mock.getCasServiceToken("yetAnotherTarget");
        }  catch (CasProxyTicketAcquisitionException e) {
            fail("Expected RuntimeException, not CasProxyTicketAcquisitionException");
        } catch (RuntimeException re) {
            assertEquals(dummyRuntimeException, re);
            exceptionThrown = true;
        }

        assertTrue(exceptionThrown);

        exceptionThrown = false;
        try {
            mock.getCasServiceToken("finalTarget");
        } catch (CasProxyTicketAcquisitionException e) {
            assertEquals(cptae, e);
            exceptionThrown = true;
        }

        assertTrue(exceptionThrown);

        vendedTokens.addAll(dummyExceptions);

        assertEquals(vendedTokens, mock.getVendedServiceTokens());

    }

}


text:
require 'rails_helper'

describe CommentsController, type: :controller do
  let(:user) { create(:user, :confirmed) }

  before do
    allow(request.env['warden']).to receive(:authenticate!).and_return(user)
    allow(controller).to receive(:current_user).and_return(user)
  end

  describe 'POST #create' do
    describe 'post comment' do
      let(:site_post) { create(:post, user: user) }

      it 'with valid attributes saves the new comment in the database' do
        post :create, params: {
                        comment: { comment: 'Neat words'},
                        commentable_type: 'Post',
                        commentable_id: site_post.id,
                      }, format: 'js'
        expect(Comment.count).to eq(1)
      end

      it 'with invalid attributes does not save the new comment in the database' do
        post :create, params: {
                        comment: { comment: ''},
                        commentable_type: 'Post',
                        commentable_id: site_post.id,
                      }, format: 'js'
        expect(Comment.count).to eq(0)
      end
    end

    describe 'event comment' do
      let(:event) { create(:event, user: user) }

      it 'with valid attributes saves the new comment in the database' do
        post :create, params: {
                        comment: { comment: 'Neat words'},
                        commentable_type: 'Event',
                        commentable_id: event.id,
                      }, format: 'js'
        expect(Comment.count).to eq(1)
      end

      it 'with invalid attributes does not save the new comment in the database' do
        post :create, params: {
                        comment: { comment: ''},
                        commentable_type: 'Event',
                        commentable_id: event.id,
                      }, format: 'js'
        expect(Comment.count).to eq(0)
      end
    end
  end

  describe 'DELETE #destroy' do
    describe 'post comment' do
      let(:site_post) { create(:post, user: user) }
      let(:comment) { create(:comment, commentable_type: site_post.class.to_s,
                                       commentable_id: site_post.id,
                                       user: user) }

      it 'deletes the comment from the database' do
        delete :destroy, params: {
                           id: comment.id,
                           commentable_type: 'Post',
                           commentable_id: site_post.id,
                         }, format: 'js'
        expect(Comment.count).to eq(0)
      end
    end

    describe 'event comment' do
      let(:event) { create(:event, user: user) }
      let(:comment) { create(:comment, commentable_type: event.class.to_s,
                                       commentable_id: event.id,
                                       user: user) }

      it 'deletes the comment from the database' do
        delete :destroy, params: {
                           id: comment.id,
                           commentable_type: 'Event',
                           commentable_id: event.id,
                         }, format: 'js'
        expect(Comment.count).to eq(0)
      end
    end
  end
end


text:
#include "mfcpch.h"
#include "errcode.h"
#ifdef __UNIX__
#include <assert.h>
#include <stdarg.h>
#endif
#include <time.h>
#include "memry.h"
#include "scrollview.h"
//#include          "evnts.h"
#include "varable.h"
#include "callcpp.h"
#include "tprintf.h"
//#include                                      "strace.h"
#include "host.h"
#include "unichar.h"

// Include automatically generated configuration file if running autoconf.
#ifdef HAVE_CONFIG_H
#include "config_auto.h"
#endif

//extern "C" {

INT_VAR (tess_cp_mapping0, 0, "Mappings for class pruner distance");
INT_VAR (tess_cp_mapping1, 1, "Mappings for class pruner distance");
INT_VAR (tess_cp_mapping2, 2, "Mappings for class pruner distance");
INT_VAR (tess_cp_mapping3, 3, "Mappings for class pruner distance");
INT_VAR (record_matcher_output, 0, "Record detailed matcher info");
INT_VAR (il1_adaption_test, 0, "Dont adapt to i/I at beginning of word");
double_VAR (permuter_pending_threshold, 0.0,
"Worst conf for using pending dictionary");
//Global matcher info from the class pruner.
inT32 cp_maps[4];
//Global info to control writes of matcher info
char blob_answer[UNICHAR_LEN + 1]; //correct char
char *word_answer;                 //correct word
inT32 bits_in_states;              //no of bits in states

void setup_cp_maps() {
  cp_maps[0] = tess_cp_mapping0;
  cp_maps[1] = tess_cp_mapping1;
  cp_maps[2] = tess_cp_mapping2;
  cp_maps[3] = tess_cp_mapping3;
}

void
cprintf (                        //Trace printf
const char *format, ...          //special message
) {
  va_list args;                  //variable args
  char msg[1000];

  va_start(args, format);  //variable list
  vsprintf(msg, format, args);  //Format into msg
  va_end(args);

  tprintf ("%s", msg);
}

#ifndef GRAPHICS_DISABLED
ScrollView *c_create_window(                   /*create a window */
                      const char *name,  /*name/title of window */
                      inT16 xpos,        /*coords of window */
                      inT16 ypos,        /*coords of window */
                      inT16 xsize,       /*size of window */
                      inT16 ysize,       /*size of window */
                      double xmin,       /*scrolling limits */
                      double xmax,       /*to stop users */
                      double ymin,       /*getting lost in */
                      double ymax        /*empty space */
                     ) {
   return new ScrollView(name, xpos, ypos, xsize, ysize, xmax - xmin, ymax - ymin, true);
}

void c_line_color_index(  /*set color */
                        void *win,
                        C_COL index) {
 // The colors are the same as the SV ones except that SV has COLOR:NONE --> offset of 1
 ScrollView* window = (ScrollView*) win;
 window->Pen((ScrollView::Color) (index + 1));
}

void c_move(  /*move pen */
            void *win,
            double x,
            double y) {
  ScrollView* window = (ScrollView*) win;
  window->SetCursor((int) x, (int) y);
}

void c_draw(  /*move pen */
            void *win,
            double x,
            double y) {
  ScrollView* window = (ScrollView*) win;
  window->DrawTo((int) x, (int) y);
}

void c_make_current(  /*move pen */
                    void *win) {
  ScrollView* window = (ScrollView*) win;
  window->Update();
}

void c_clear_window(  /*move pen */
                    void *win) {
  ScrollView* window = (ScrollView*) win;
  window->Clear();
}

char window_wait(ScrollView* win) {
  SVEvent* ev;
  // Wait till an input or click event (all others are thrown away)
  char ret = '\0';
  SVEventType ev_type = SVET_ANY;
  do {
    ev = win->AwaitEvent(SVET_ANY);
    ev_type = ev->type;
    if (ev_type == SVET_INPUT)
      ret = ev->parameter[0];
    delete ev;
  } while (ev_type != SVET_INPUT && ev_type != SVET_CLICK);
  return ret;
}
#endif

void reverse32(void *ptr) {
  char tmp;
  char *cptr = (char *) ptr;

  tmp = *cptr;
  *cptr = *(cptr + 3);
  *(cptr + 3) = tmp;
  tmp = *(cptr + 1);
  *(cptr + 1) = *(cptr + 2);
  *(cptr + 2) = tmp;
}

void reverse16(void *ptr) {
  char tmp;
  char *cptr = (char *) ptr;

  tmp = *cptr;
  *cptr = *(cptr + 1);
  *(cptr + 1) = tmp;
}

//};


text:
package org.dozer.classmap;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.dozer.converters.CustomConverterContainer;
import org.dozer.util.DozerConstants;

/**
 * Internal class that represents the configuration block specified in the mapping xml file(s). Only intended for
 * internal use.
 *
 * @author garsombke.franz
 * @author sullins.ben
 * @author tierney.matt
 *
 */
public class Configuration {

  private Boolean wildcard;
  private Boolean stopOnErrors;
  private Boolean trimStrings;
  private Boolean mapNull;
  private Boolean mapEmptyString;
  private String dateFormat;
  private String beanFactory;
  private RelationshipType relationshipType;

  private final CustomConverterContainer customConverters = new CustomConverterContainer();
  private final CopyByReferenceContainer copyByReferences = new CopyByReferenceContainer();
  private final AllowedExceptionContainer allowedExceptions = new AllowedExceptionContainer();

  public AllowedExceptionContainer getAllowedExceptions() {
    return allowedExceptions;
  }

  public CustomConverterContainer getCustomConverters() {
    return customConverters;
  }

  public String getDateFormat() {
    return dateFormat;
  }

  public void setDateFormat(String format) {
    dateFormat = format;
  }

  public Boolean getWildcard() {
    return wildcard != null ? wildcard : Boolean.valueOf(DozerConstants.DEFAULT_WILDCARD_POLICY);
  }

  public void setWildcard(Boolean globalWildcardPolicy) {
    wildcard = globalWildcardPolicy;
  }

  public Boolean getStopOnErrors() {
    return stopOnErrors != null ? stopOnErrors : Boolean.valueOf(DozerConstants.DEFAULT_ERROR_POLICY);
  }

  public void setStopOnErrors(Boolean stopOnErrors) {
    this.stopOnErrors = stopOnErrors;
  }

  public Boolean getMapNull() {
    return mapNull != null ? mapNull : Boolean .valueOf(DozerConstants.DEFAULT_MAP_NULL_POLICY);
  }

  public void setMapNull(Boolean globalMapNullPolicy) {
    mapNull = globalMapNullPolicy;
  }

  public Boolean getMapEmptyString() {
    return mapEmptyString != null ? mapEmptyString : Boolean.valueOf(DozerConstants.DEFAULT_MAP_EMPTY_STRING_POLICY);
  }

  public void setMapEmptyString(Boolean globalMapEmptyStringPolicy) {
    mapEmptyString = globalMapEmptyStringPolicy;
  }

  public String getBeanFactory() {
    return beanFactory;
  }

  public void setBeanFactory(String beanFactory) {
    this.beanFactory = beanFactory;
  }

  public CopyByReferenceContainer getCopyByReferences() {
    return copyByReferences;
  }

  public Boolean getTrimStrings() {
    return trimStrings != null ? trimStrings : Boolean.valueOf(DozerConstants.DEFAULT_TRIM_STRINGS_POLICY);
  }

  public void setTrimStrings(Boolean trimStrings) {
    this.trimStrings = trimStrings;
  }

  public RelationshipType getRelationshipType() {
    return relationshipType;
  }

  public void setRelationshipType(RelationshipType relationshipType) {
    this.relationshipType = relationshipType;
  }

  @Override
  public String toString() {
    return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
  }
}


text:
package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"

	"context"

	"github.com/xiaoyao1991/chukonu/core"
	"github.com/xiaoyao1991/chukonu/impl"
)

type DruidRequestProvider struct {
}

func (m *DruidRequestProvider) UseEngine() func(core.ChukonuConfig) core.Engine {
	return impl.NewHttpEngine
}

func (m *DruidRequestProvider) MetricsManager() core.MetricsManager {
	return impl.NewHttpMetricsManager()
}

func (m *DruidRequestProvider) Provide(queue chan *core.ChukonuWorkflow) {
	// throttle := time.Tick(200 * time.Millisecond)
	i := 0
	for {
		// <-throttle
		// fmt.Printf("Generating %dth request\n", i)
		workflow := core.NewWorkflow("druid_workflow")

		var fn1 = func(ctx context.Context) core.ChukonuRequest {
			req, err := http.NewRequest("GET", "http://40.71.182.255:8082/druid/v2/datasources", nil)
			if err != nil {
				fmt.Println(err)
				return nil
			}
			return impl.NewChukonuHttpRequest("datasources_req", 0, true, true, func(ctx context.Context, resp core.ChukonuResponse) context.Context {
				defer resp.RawResponse().(*http.Response).Body.Close()
				// dump, err := resp.Dump()
				// if err != nil {
				// 	log.Fatal(err)
				// }
				// fmt.Println(string(dump))
				bodyBytes, _ := ioutil.ReadAll(resp.RawResponse().(*http.Response).Body)
				bodyString := string(bodyBytes)
				datasource := bodyString[2 : len(bodyString)-2]
				return context.WithValue(ctx, "datasource", datasource)
			}, nil, req)
		}

		workflow.AddRequest(fn1)

		var fn2 = func(ctx context.Context) core.ChukonuRequest {
			var jsonStr = []byte(fmt.Sprintf(`
        {
          "queryType" : "topN",
          "dataSource" : "%s",
          "intervals" : ["2013-08-01/2013-08-03"],
          "granularity" : "all",
          "dimension" : "page",
          "metric" : "edits",
          "threshold" : 25,
          "aggregations" : [
            {
              "type" : "longSum",
              "name" : "edits",
              "fieldName" : "count"
            }
          ]
        }`, ctx.Value("datasource")))
			req, err := http.NewRequest("POST", "http://40.71.182.255:8082/druid/v2/", bytes.NewBuffer(jsonStr))
			req.Header.Set("Content-Type", "application/json")
			if err != nil {
				fmt.Println(err)
				return nil
			}
			return impl.NewChukonuHttpRequest("topN", 0, true, true, func(ctx context.Context, resp core.ChukonuResponse) context.Context {
				defer resp.RawResponse().(*http.Response).Body.Close()
				// dump, err := resp.Dump()
				// if err != nil {
				// 	log.Fatal(err)
				// }
				// fmt.Println(string(dump))
				io.Copy(ioutil.Discard, resp.RawResponse().(*http.Response).Body)
				return ctx
			}, nil, req)
		}

		workflow.AddRequest(fn2)

		queue <- workflow
		i++

		// if i == 100 {
		// 	break
		// }
	}

	// close(queue)
}

var TestPlan DruidRequestProvider


text:
import socket
import time

HOST = ''
PORT = 1234
BUFSIZE = 1024
ADDR = (HOST, PORT)

udpSerSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udpSerSock.bind(ADDR)

while True:
    print('Waiting for message...')
    try:
        data, addr = udpSerSock.recvfrom(BUFSIZE)
    except KeyboardInterrupt as e:
        print('server is closing...')
        udpSerSock.close()
        break
    udpSerSock.sendto('[{}] {}'.format(time.ctime(), data), addr)
    print('...received from add returned to:', addr)


text:
module Hanuman
  class ObservationPhoto < ActiveRecord::Base
    has_paper_trail
    mount_uploader :photo, PhotoUploader

    # Relations
    belongs_to :observation, -> { unscope(:includes, :order) }
    has_one    :survey, through: :observation

    after_commit :set_media_access_mode_to_authenticated, on: :create
    def set_media_access_mode_to_authenticated
      SetMediaAccessModeWorker.perform_async(self.id, 'photo')
    end

  end
end


text:
package ui.client;

import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import react.client.BaseProps;
import react.client.ExternalComponent;
import react.client.ReactClass;
import react.client.StyleProps;

import javax.inject.Inject;
import javax.inject.Singleton;

/**
 *
 */
@Singleton
public class ToolbarGroup extends ExternalComponent<ToolbarGroup.Props> {

    @Inject
    public ToolbarGroup() {
    }

    @Override
    protected native ReactClass getReactClass() /*-{
        return $wnd.MaterialUi.ToolbarGroup;
    }-*/;

    @JsType(isNative = true)
    public interface Props extends BaseProps {
//        String className;
//        boolean firstChild; // for first child left gap
//        // invalid Variable name 'float' changed below
//        String floatGroup; // enum 'left' 'right'
//        boolean lastChild; // for last child right gap
//        StyleProps style;
//        // not sure we want on onClick for the whole group

        @JsProperty
        String getClassName();

        @JsProperty
        void setClassName(String className);

        @JsProperty
        boolean isFirstChild();

        @JsProperty
        void setFirstChild(boolean firstChild);

        @JsProperty
        String getFloatGroup();

        @JsProperty
        void setFloatGroup(String floatGroup);

        @JsProperty
        boolean isLastChild();

        @JsProperty
        void setLastChild(boolean lastChild);

        @JsProperty
        StyleProps getStyle();

        @JsProperty
        void setStyle(StyleProps style);

        ////////////////////
        // fluent setters
        ////////////////////

        @JsOverlay
        default Props className(final String className) {
            setClassName(className);
            return this;
        }

        @JsOverlay
        default Props firstChild(final boolean firstChild) {
            setFirstChild(firstChild);
            return this;
        }

        @JsOverlay
        default Props floatGroup(final String floatGroup) {
            setFloatGroup(floatGroup);
            return this;
        }

        @JsOverlay
        default Props lastChild(final boolean lastChild) {
            setLastChild(lastChild);
            return this;
        }

        @JsOverlay
        default Props style(final StyleProps style) {
            setStyle(style);
            return this;
        }

    }
}


text:
        <x-marker class="highlight" data-is-selection="true" data-selection-id="new-id" data-is-highlight-node="true"
                  data-original-index="0" data-original-offset-start="0" original-text-node-index="0"
                  data-is-start-end="data-is-start-end">This
        </x-marker>
        <x-marker data-is-selection="true" data-original-index="0" data-original-offset-start="5"
                  original-text-node-index="0">is a Test
        </x-marker>
        What is going on!!

Another Node This is a test now!

Another Node

What is is going on


text:
require 'pact/consumer/mock_service/app'
require 'rack/test'
require 'cgi'

describe Pact::Consumer::MockService do

  include Rack::Test::Methods

  let(:app) do
    Pact::Consumer::MockService.new(pact_dir: 'tmp/pacts', log_file: StringIO.new)
  end

  # NOTE: the admin_headers are Rack headers, they will be converted
  # to X-Pact-Mock-Service and Content-Type by the framework
  let(:admin_headers) { {'HTTP_X_PACT_MOCK_SERVICE' => 'true', 'CONTENT_TYPE' => 'application/json'} }

  let(:expected_interaction) do
    {
      description: "a request for a greeting",
      provider_state: "someone is talking to us",
      request: {
        method: :get, path: '/greeting'
      },
      response: {
        status: 200, body: "Hello world"
      }
    }.to_json
  end

  context "when some expected interactions have not been executed" do
    context "/interactions/missing" do
      it "returns the number of missing interactions so we can poll to determine when the test is finished" do | example |
        post "/interactions", expected_interaction, admin_headers
        get "/interactions/missing", nil, admin_headers
        expect(JSON.parse(last_response.body)['size']).to eq 1
      end
    end
  end
end


text:
import UI_ROOT from "../../UIRoot";
import Button from "./Button";

export default class WasabiButton extends Button {
  //   static GUID = "unknown";

  getElTag(): string {
    return "button";
  }

  constructor() {
    super();
    this.registerDimensions();
  }

  setXmlAttr(key: string, value: string): boolean {
    if (super.setXmlAttr(key, value)) {
      return true;
    }
    switch (key) {
      case "text":
        this._div.innerText = value;
        break;
      default:
        return false;
    }
    return true;
  }

  registerDimensions() {
    UI_ROOT.addHeight("button-border-top", "wasabi.button.top");
    UI_ROOT.addHeight("button-border-bottom", "wasabi.button.bottom");
    UI_ROOT.addWidth("button-border-left", "wasabi.button.left");
    UI_ROOT.addWidth("button-border-right", "wasabi.button.right");
  }

  draw() {
    super.draw();
    this._div.classList.remove("webamp--img");
    this._div.classList.add("wasabi");
    this._div.setAttribute("data-obj-name", "WasabiButton");
  }

  /*
  extern ToggleButton.onToggle(Boolean onoff);
  extern int TOggleButton.getCurCfgVal()
  */
}


text:
package org.innovateuk.ifs.questionnaire.resource;

public enum QuestionnaireSecurityType {

    PUBLIC,
    USER_ONLY,
    LINK;

}


text:
var CarbonClient = require('@carbon-io/carbon-client')

var client = new CarbonClient("http://localhost:8888")

//  patch /users
client.getEndpoint("users/1234").patch({
    "name": "bob"
  },
  function(e, res) {
    console.log("Response from /users:")
    console.log(res.body)
  })


text:
class DB::DataStore
  attr_reader :deltas, :records

  def initialize remote_data_store, delta_raw_db, record_raw_db
    @records = DB::Record.new record_raw_db, remote_data_store.records
    @deltas  = DB::Delta.new  delta_raw_db, records, remote_data_store.deltas
    @sync    = remote_data_store.syncs.new deltas
    @remote  = remote_data_store
  end

  def sync!
    @sync.sync!
  end

  def push_local_change change
    @sync.reserve_local_change change
  end
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Crsytal SDK for iOS: /Users/gareth/hg/test/test/Doxygen/input/CrystalLeaderboards.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Modules

Classes

Files

File List

/Users/gareth/hg/test/test/Doxygen/input/CrystalLeaderboards.h

00001 //
00002 //  CrystalLeaderboards.h
00003 //  Crystal
00004 //
00005 //  Created by Gareth Reese on 16/04/2010.
00006 //  Copyright 2010 Chillingo Ltd. All rights reserved.
00007 //
00008
00009 #import <Foundation/Foundation.h>
00010
00016 typedef enum
00017 {
00018         CLCTop20                        = 0x1,
00019         CLCTop20Friends         = 0x2,
00020         CLCRandom20                     = 0x4,
00021         CLCCurrentUser          = 0x8,
00022 } CrystalLeaderboardCategories;
00023
00024
00025 @protocol CrystalLeaderboardDelegate <NSObject>
00026 @required
00031 - (void) crystalLeaderboardUpdated:(NSString*)leaderboardId;
00032
00033 @end
00034
00042 @interface CrystalLeaderboards : NSObject
00043 {
00044 @public
00045         CrystalLeaderboardCategories categoriesToGet;
00046         id<CrystalLeaderboardDelegate> delegate;
00047 }
00048
00049 @property (nonatomic)                                                           CrystalLeaderboardCategories categoriesToGet;
00050 @property (nonatomic, assign, setter=setDelegate:)      id<CrystalLeaderboardDelegate> delegate;
00051
00052
00061 + (CrystalLeaderboards*) sharedInstance;
00062
00070 - (void) downloadLeaderboardDataForID:(NSString*)leaderboardID;
00071
00072
00074 // Get an array of leaderboard entries
00075
00081 - (NSArray*) top20EntriesForLeaderboardID:(NSString*)leaderboardID;
00082
00088 - (NSArray*) top20FriendsForLeaderboardID:(NSString*)leaderboardID;
00089
00095 - (NSArray*) random20ForLeaderboardID:(NSString*)leaderboardID;
00096
00102 - (NSDictionary*) currentUserEntryForLeaderboardID:(NSString*)leaderboardID;
00103
00104
00106 // Accessing leaderboard entry data
00107
00113 - (NSString*) usernameForLeaderboardEntry:(NSDictionary*)leaderboardEntry;
00114
00121 - (int) positionForLeaderboardEntry:(NSDictionary*)leaderboardEntry;
00122
00130 - (double) scoreForLeaderboardEntry:(NSDictionary*)leaderboardEntry;
00131
00139 - (NSTimeInterval) timeForLeaderboardEntry:(NSDictionary*)leaderboardEntry;
00140
00141 @end

<address class="footer">Generated on Tue Oct 26 2010 15:32:36 for Crsytal SDK for iOS by

 1.7.2 </address>


text:
package edu.gemini.phase2.template.factory.impl.gmos

import edu.gemini.pot.sp.{ISPObservation, ISPGroup}
import edu.gemini.spModel.gemini.gmos.blueprint.SpGmosSBlueprintIfu
import edu.gemini.spModel.gemini.gmos.GmosSouthType
import GmosSouthType.FPUnitSouth._
import GmosSouthType.FilterSouth._
import edu.gemini.phase2.template.factory.impl.TemplateDb
import edu.gemini.spModel.gemini.gmos.InstGmosCommon
import edu.gemini.spModel.gemini.gmos.GmosSouthType.FilterSouth

case class GmosSIfu(blueprint:SpGmosSBlueprintIfu) extends GmosSBase[SpGmosSBlueprintIfu] {

//  IF SPECTROSCOPY MODE == IFU
//          INCLUDE FROM 'IFU BP' IN,
//              Target group: {36}-{37}
//              Baseline folder: {38}-{42}
//          Where FPU!=None in BP (static and iterator), SET FPU from PI
//              IFU acq obs have an iterator titled "Field image" with
//                  FPU=None, the FPU must not be set here.
//              IF FPU = 'IFU 1 SLIT' in PI then SET FPU='IFU Right Slit (red)' in OT
//          If not acq SET DISPERSER FROM PI
//          For filter changes below, do not adjust exposure times.
//          If acq ({36}, {41})
//             If filter from PI != None, SET FILTER in static component
//               to ugriz filter closest in central
//               wavelength to the filter from PI
//             else SET FILTER=r (as in BP)
//          else SET FILTER FROM PI
//              IF FPU = "IFU 2 slits" in PI:
//  	        IF FILTER=None, SET FILTER=r_G0326
//                  SET CENTRAL WAVELENGTHS TO THE FILTER EFF WAVELENGTH
//                   AND EFF WAVELENGTH + 5nm (if iteration over wavelength)
//                  See http://www.gemini.edu/node/10637

  val targetGroup = 36 to 37
  val baselineFolder = 38 to 42
  val notes = Seq.empty

  val acq = Seq(36, 41)

  def initialize(group:ISPGroup, db:TemplateDb):Either[String, Unit] = forObservations(group, forAll)

  def piFpu                    = if (blueprint.fpu == IFU_2) IFU_3 else blueprint.fpu
  def noneOrPiFpu(libFpu: Any) = if (libFpu == FPU_NONE) FPU_NONE else piFpu

  def forAll(o:ISPObservation):Either[String, Unit] = for {

    // Where FPU!=None in BP (static and iterator), SET FPU from PI
    // (here BP means the library not the blueprint!)
    fpuInLIB <- o.getFpu.right
    _ <- o.setFpu(noneOrPiFpu(fpuInLIB)).right
    _ <- o.ed.modifySeqAllKey(InstGmosCommon.FPU_PROP_NAME) {
           case libFpu => noneOrPiFpu(libFpu)
         }.right

    // If not acq SET DISPERSER FROM PI
    _ <- when(!o.memberOf(acq)) {
      o.setDisperser(blueprint.disperser)
    }.right

    _ <- (if (o.memberOf(acq)) {
      if (blueprint.filter != NONE)
        o.setFilter(closestUGRIZ(blueprint.filter.getWavelength.toDouble))
      else
        o.setFilter(r_G0326)
    } else {
      for {
        _ <- o.setFilter(blueprint.filter).right

        // For IFU 2-slit, set wavelengths
        _ <- when(blueprint.fpu == IFU_1) {

          // Handle empty filter
          val f = if (blueprint.filter == FilterSouth.NONE) FilterSouth.r_G0326 else blueprint.filter

          // Set observing wavelength
          val lambda = f.getWavelength.toDouble * 1000.0 // seriously ?!??
          for {
            _ <- o.setFilter(f).right
            _ <- o.setDisperserLambda(lambda).right
            _ <- o.ed.modifySeqAllKey(InstGmosCommon.DISPERSER_LAMBDA_PROP.getName){
              case 630 => lambda
              case 635 => lambda + 5.0
            }.right
          } yield ()
        }.right

      } yield ()
    }).right

  } yield ()

}


text:
var url = require('url');
var EventEmitter = require('events').EventEmitter;
var mailer = require('nodemailer');
var ent = require('ent');

module.exports = function (opts) {
    if (typeof opts === 'string') {
        opts = { uri : opts };
    }

    var transport;
    if (opts.transportType && opts.transportOptions) {
        transport = mailer.createTransport(opts.transportType, opts.transportOptions);
    } else {
        console.log("No transport type specified!");
    }

    var reset = new Forgot(opts);

    var self = function (email, cb) {
        var session = reset.generate();
        if (!session) return;

        var uri = session.uri = opts.uri + '?' + session.id;

        transport.sendMail({
            sender  : opts.from || 'nodepasswordreset@localhost',
            to      : email,
            subject : opts.subject || 'Password reset request',
            text : opts.text || "",
            html :  opts.html || [
                'Click this link to reset your password:\r\n',
                '
',
                '',
                ent.encode(uri),
                '',
                ''
            ].join('\r\n')
        }, function (error, success) {
            if (error) {
                if (cb.error) cb.error(error);
                delete reset.sessions[session.id];
            } else {
                if(cb.success) cb.success(success)
            }
        });

        return session;
    };

    self.middleware = reset.middleware.bind(reset);

    self.expire = function (id) {
        delete reset.sessions[id];
    };

    return self;
};

function Forgot (opts) {
    this.sessions = opts.sessions || {};
    this.mount = url.parse(opts.uri);
    this.mount.port = this.mount.port || 80;
}

Forgot.prototype.generate = function () {
    var buf = new Buffer(16);
    for (var i = 0; i < buf.length; i++) {
        buf[i] = Math.floor(Math.random() * 256);
    }
    var id = buf.toString('base64');

    var session = this.sessions[id] = new EventEmitter;
    session.id = id;
    return session;
};

Forgot.prototype.middleware = function (req, res, next) {
    if (!next) next = function (err) {
        if (err) res.end(err)
    }

    var u = url.parse('http://' + req.headers.host + req.url);
    u.port = u.port || 80;
    var id = u.query;

    if (u.hostname !== this.mount.hostname
    || parseInt(u.port, 10) !== parseInt(this.mount.port, 10)
    || u.pathname !== this.mount.pathname) {
        next()
    }
    else if (!id) {
        res.statusCode = 400;
        next('No auth token specified.');
    }
    else if (!this.sessions[id]) {
        res.statusCode = 410;
        next('auth token expired');
    }
    else {
        this.sessions[id].emit('request', req, res);
    }
};


text:
package com.cchtw.videorecorderlib.javacv;

import org.bytedeco.javacpp.BytePointer;
import org.bytedeco.javacpp.DoublePointer;
import org.bytedeco.javacpp.FloatPointer;
import org.bytedeco.javacpp.IntPointer;
import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacpp.Pointer;
import org.bytedeco.javacpp.PointerPointer;
import org.bytedeco.javacpp.ShortPointer;

import java.io.File;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.Map.Entry;

import static org.bytedeco.javacpp.avcodec.AVCodec;
import static org.bytedeco.javacpp.avcodec.AVCodecContext;
import static org.bytedeco.javacpp.avcodec.AVPacket;
import static org.bytedeco.javacpp.avcodec.AVPicture;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_AAC;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_FFV1;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_FLV1;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_H263;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_H264;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_HUFFYUV;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_MPEG1VIDEO;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_MPEG2VIDEO;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_MPEG4;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_NONE;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_PCM_S16BE;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_PCM_S16LE;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_PCM_U16BE;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_PCM_U16LE;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_PNG;
import static org.bytedeco.javacpp.avcodec.AV_CODEC_ID_RAWVIDEO;
import static org.bytedeco.javacpp.avcodec.AV_PKT_FLAG_KEY;
import static org.bytedeco.javacpp.avcodec.CODEC_CAP_EXPERIMENTAL;
import static org.bytedeco.javacpp.avcodec.CODEC_FLAG_GLOBAL_HEADER;
import static org.bytedeco.javacpp.avcodec.CODEC_FLAG_QSCALE;
import static org.bytedeco.javacpp.avcodec.FF_MIN_BUFFER_SIZE;
import static org.bytedeco.javacpp.avcodec.av_init_packet;
import static org.bytedeco.javacpp.avcodec.avcodec_close;
import static org.bytedeco.javacpp.avcodec.avcodec_encode_audio2;
import static org.bytedeco.javacpp.avcodec.avcodec_encode_video2;
import static org.bytedeco.javacpp.avcodec.avcodec_fill_audio_frame;
import static org.bytedeco.javacpp.avcodec.avcodec_find_encoder;
import static org.bytedeco.javacpp.avcodec.avcodec_find_encoder_by_name;
import static org.bytedeco.javacpp.avcodec.avcodec_open2;
import static org.bytedeco.javacpp.avcodec.avpicture_fill;
import static org.bytedeco.javacpp.avcodec.avpicture_get_size;
import static org.bytedeco.javacpp.avformat.AVFMT_GLOBALHEADER;
import static org.bytedeco.javacpp.avformat.AVFMT_NOFILE;
import static org.bytedeco.javacpp.avformat.AVFMT_RAWPICTURE;
import static org.bytedeco.javacpp.avformat.AVFormatContext;
import static org.bytedeco.javacpp.avformat.AVIOContext;
import static org.bytedeco.javacpp.avformat.AVIO_FLAG_WRITE;
import static org.bytedeco.javacpp.avformat.AVOutputFormat;
import static org.bytedeco.javacpp.avformat.AVStream;
import static org.bytedeco.javacpp.avformat.av_dump_format;
import static org.bytedeco.javacpp.avformat.av_guess_format;
import static org.bytedeco.javacpp.avformat.av_interleaved_write_frame;
import static org.bytedeco.javacpp.avformat.av_register_all;
import static org.bytedeco.javacpp.avformat.av_write_frame;
import static org.bytedeco.javacpp.avformat.av_write_trailer;
import static org.bytedeco.javacpp.avformat.avformat_alloc_context;
import static org.bytedeco.javacpp.avformat.avformat_network_init;
import static org.bytedeco.javacpp.avformat.avformat_new_stream;
import static org.bytedeco.javacpp.avformat.avformat_write_header;
import static org.bytedeco.javacpp.avformat.avio_close;
import static org.bytedeco.javacpp.avformat.avio_open;
import static org.bytedeco.javacpp.avutil.AVDictionary;
import static org.bytedeco.javacpp.avutil.AVFrame;
import static org.bytedeco.javacpp.avutil.AVMEDIA_TYPE_AUDIO;
import static org.bytedeco.javacpp.avutil.AVMEDIA_TYPE_VIDEO;
import static org.bytedeco.javacpp.avutil.AVRational;
import static org.bytedeco.javacpp.avutil.AV_NOPTS_VALUE;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_BGR24;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_GRAY16BE;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_GRAY16LE;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_GRAY8;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_NONE;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_NV21;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_RGB32;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_RGBA;
import static org.bytedeco.javacpp.avutil.AV_PIX_FMT_YUV420P;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_DBL;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_DBLP;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_FLT;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_FLTP;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_NONE;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_S16;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_S16P;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_S32;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_S32P;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_U8;
import static org.bytedeco.javacpp.avutil.AV_SAMPLE_FMT_U8P;
import static org.bytedeco.javacpp.avutil.FF_QP2LAMBDA;
import static org.bytedeco.javacpp.avutil.av_d2q;
import static org.bytedeco.javacpp.avutil.av_dict_free;
import static org.bytedeco.javacpp.avutil.av_dict_set;
import static org.bytedeco.javacpp.avutil.av_find_nearest_q_idx;
import static org.bytedeco.javacpp.avutil.av_frame_alloc;
import static org.bytedeco.javacpp.avutil.av_frame_free;
import static org.bytedeco.javacpp.avutil.av_free;
import static org.bytedeco.javacpp.avutil.av_get_bytes_per_sample;
import static org.bytedeco.javacpp.avutil.av_get_default_channel_layout;
import static org.bytedeco.javacpp.avutil.av_inv_q;
import static org.bytedeco.javacpp.avutil.av_malloc;
import static org.bytedeco.javacpp.avutil.av_rescale_q;
import static org.bytedeco.javacpp.avutil.av_sample_fmt_is_planar;
import static org.bytedeco.javacpp.avutil.av_samples_get_buffer_size;
import static org.bytedeco.javacpp.swresample.SwrContext;
import static org.bytedeco.javacpp.swresample.swr_alloc_set_opts;
import static org.bytedeco.javacpp.swresample.swr_convert;
import static org.bytedeco.javacpp.swresample.swr_free;
import static org.bytedeco.javacpp.swresample.swr_init;
import static org.bytedeco.javacpp.swscale.SWS_BILINEAR;
import static org.bytedeco.javacpp.swscale.SwsContext;
import static org.bytedeco.javacpp.swscale.sws_freeContext;
import static org.bytedeco.javacpp.swscale.sws_getCachedContext;
import static org.bytedeco.javacpp.swscale.sws_scale;

/**
 *
 * @author Samuel Audet
 */
public class FFmpegFrameRecorder extends FrameRecorder {
    public static FFmpegFrameRecorder createDefault(File f, int w, int h)   throws Exception { return new FFmpegFrameRecorder(f, w, h); }
    public static FFmpegFrameRecorder createDefault(String f, int w, int h) throws Exception { return new FFmpegFrameRecorder(f, w, h); }

    private static Exception loadingException = null;
    public static void tryLoad() throws Exception {
        if (loadingException != null) {
            throw loadingException;
        } else {
            try {
                Loader.load(org.bytedeco.javacpp.avutil.class);
                Loader.load(org.bytedeco.javacpp.swresample.class);
                Loader.load(org.bytedeco.javacpp.avcodec.class);
                Loader.load(org.bytedeco.javacpp.avformat.class);
                Loader.load(org.bytedeco.javacpp.swscale.class);

                /* initialize libavcodec, and register all codecs and formats */
                av_register_all();
                avformat_network_init();
            } catch (Throwable t) {
                if (t instanceof Exception) {
                    throw loadingException = (Exception)t;
                } else {
                    throw loadingException = new Exception("Failed to load " + FFmpegFrameRecorder.class, t);
                }
            }
        }
    }

    static {
        try {
            tryLoad();
        } catch (Exception ex) { }
    }

    public FFmpegFrameRecorder(File file, int audioChannels) {
        this(file, 0, 0, audioChannels);
    }
    public FFmpegFrameRecorder(String filename, int audioChannels) {
        this(filename, 0, 0, audioChannels);
    }
    public FFmpegFrameRecorder(File file, int imageWidth, int imageHeight) {
        this(file, imageWidth, imageHeight, 0);
    }
    public FFmpegFrameRecorder(String filename, int imageWidth, int imageHeight) {
        this(filename, imageWidth, imageHeight, 0);
    }
    public FFmpegFrameRecorder(File file, int imageWidth, int imageHeight, int audioChannels) {
        this(file.getAbsolutePath(), imageWidth, imageHeight, audioChannels);
    }
    public FFmpegFrameRecorder(String filename, int imageWidth, int imageHeight, int audioChannels) {
        this.filename      = filename;
        this.imageWidth    = imageWidth;
        this.imageHeight   = imageHeight;
        this.audioChannels = audioChannels;

        this.pixelFormat   = AV_PIX_FMT_NONE;
        this.videoCodec    = AV_CODEC_ID_NONE;
        this.videoBitrate  = 400000;
        this.frameRate     = 30;

        this.sampleFormat  = AV_SAMPLE_FMT_NONE;
        this.audioCodec    = AV_CODEC_ID_NONE;
        this.audioBitrate  = 64000;
        this.sampleRate    = 44100;

        this.interleaved = true;

        this.video_pkt = new AVPacket();
        this.audio_pkt = new AVPacket();
    }
    public void release() throws Exception {
        synchronized (org.bytedeco.javacpp.avcodec.class) {
            releaseUnsafe();
        }
    }
    void releaseUnsafe() throws Exception {
        /* close each codec */
        if (video_c != null) {
            avcodec_close(video_c);
            video_c = null;
        }
        if (audio_c != null) {
            avcodec_close(audio_c);
            audio_c = null;
        }
        if (picture_buf != null) {
            av_free(picture_buf);
            picture_buf = null;
        }
        if (picture != null) {
            av_frame_free(picture);
            picture = null;
        }
        if (tmp_picture != null) {
            av_frame_free(tmp_picture);
            tmp_picture = null;
        }
        if (video_outbuf != null) {
            av_free(video_outbuf);
            video_outbuf = null;
        }
        if (frame != null) {
            av_frame_free(frame);
            frame = null;
        }
        if (samples_out != null) {
            for (int i = 0; i < samples_out.length; i++) {
                av_free(samples_out[i].position(0));
            }
            samples_out = null;
        }
        if (audio_outbuf != null) {
            av_free(audio_outbuf);
            audio_outbuf = null;
        }
        if (video_st != null && video_st.metadata() != null) {
            av_dict_free(video_st.metadata());
            video_st.metadata(null);
        }
        if (audio_st != null && audio_st.metadata() != null) {
            av_dict_free(audio_st.metadata());
            audio_st.metadata(null);
        }
        video_st = null;
        audio_st = null;

        if (oc != null && !oc.isNull()) {
            if ((oformat.flags() & AVFMT_NOFILE) == 0) {
                /* close the output file */
                avio_close(oc.pb());
            }

            /* free the streams */
            int nb_streams = oc.nb_streams();
            for(int i = 0; i < nb_streams; i++) {
                av_free(oc.streams(i).codec());
                av_free(oc.streams(i));
            }

            /* free metadata */
            if (oc.metadata() != null) {
                av_dict_free(oc.metadata());
                oc.metadata(null);
            }

            /* free the stream */
            av_free(oc);
            oc = null;
        }

        if (img_convert_ctx != null) {
            sws_freeContext(img_convert_ctx);
            img_convert_ctx = null;
        }

        if (samples_convert_ctx != null) {
            swr_free(samples_convert_ctx);
            samples_convert_ctx = null;
        }
    }
    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        release();
    }

    private String filename;
    private AVFrame picture, tmp_picture;
    private BytePointer picture_buf;
    private BytePointer video_outbuf;
    private int video_outbuf_size;
    private AVFrame frame;
    private Pointer[] samples_in;
    private BytePointer[] samples_out;
    private PointerPointer samples_in_ptr;
    private PointerPointer samples_out_ptr;
    private BytePointer audio_outbuf;
    private int audio_outbuf_size;
    private int audio_input_frame_size;
    private AVOutputFormat oformat;
    private AVFormatContext oc;
    private AVCodec video_codec, audio_codec;
    private AVCodecContext video_c, audio_c;
    private AVStream video_st, audio_st;
    private SwsContext img_convert_ctx;
    private SwrContext samples_convert_ctx;
    private int samples_channels, samples_format, samples_rate;
    private AVPacket video_pkt, audio_pkt;
    private int[] got_video_packet, got_audio_packet;

    @Override
    public int getFrameNumber() {
        return picture == null ? super.getFrameNumber() : (int)picture.pts();
    }
    @Override
    public void setFrameNumber(int frameNumber) {
        if (picture == null) { super.setFrameNumber(frameNumber); } else { picture.pts(frameNumber); }
    }

    // best guess for timestamp in microseconds...
    @Override
    public long getTimestamp() {
        return Math.round(getFrameNumber() * 1000000L / getFrameRate());
    }
    @Override
    public void setTimestamp(long timestamp)  {
        setFrameNumber((int) Math.round(timestamp * getFrameRate() / 1000000L));
    }

    public void start() throws Exception {
        synchronized (org.bytedeco.javacpp.avcodec.class) {
            startUnsafe();
        }
    }
    void startUnsafe() throws Exception {
        int ret;
        picture = null;
        tmp_picture = null;
        picture_buf = null;
        frame = null;
        video_outbuf = null;
        audio_outbuf = null;
        oc = null;
        video_c = null;
        audio_c = null;
        video_st = null;
        audio_st = null;
        got_video_packet = new int[1];
        got_audio_packet = new int[1];

        /* auto detect the output format from the name. */
        String format_name = format == null || format.length() == 0 ? null : format;
        if ((oformat = av_guess_format(format_name, filename, null)) == null) {
            int proto = filename.indexOf("://");
            if (proto > 0) {
                format_name = filename.substring(0, proto);
            }
            if ((oformat = av_guess_format(format_name, filename, null)) == null) {
                throw new Exception("av_guess_format() error: Could not guess output format for \"" + filename + "\" and " + format + " format.");
            }
        }
        format_name = oformat.name().getString();

        /* allocate the output media context */
        if ((oc = avformat_alloc_context()) == null) {
            throw new Exception("avformat_alloc_context() error: Could not allocate format context");
        }

        oc.oformat(oformat);
        oc.filename().putString(filename);

        /* add the audio and video streams using the format codecs
           and initialize the codecs */

        if (imageWidth > 0 && imageHeight > 0) {
            if (videoCodec != AV_CODEC_ID_NONE) {
                oformat.video_codec(videoCodec);
            } else if ("flv".equals(format_name)) {
                oformat.video_codec(AV_CODEC_ID_FLV1);
            } else if ("mp4".equals(format_name)) {
                oformat.video_codec(AV_CODEC_ID_MPEG4);
            } else if ("3gp".equals(format_name)) {
                oformat.video_codec(AV_CODEC_ID_H263);
            } else if ("avi".equals(format_name)) {
                oformat.video_codec(AV_CODEC_ID_HUFFYUV);
            }

            /* find the video encoder */
            if ((video_codec = avcodec_find_encoder_by_name(videoCodecName)) == null &&
                (video_codec = avcodec_find_encoder(oformat.video_codec())) == null) {
                release();
                throw new Exception("avcodec_find_encoder() error: Video codec not found.");
            }
            oformat.video_codec(video_codec.id());

            AVRational frame_rate = av_d2q(frameRate, 1001000);
            AVRational supported_framerates = video_codec.supported_framerates();
            if (supported_framerates != null) {
                int idx = av_find_nearest_q_idx(frame_rate, supported_framerates);
                frame_rate = supported_framerates.position(idx);
            }

            /* add a video output stream */
            if ((video_st = avformat_new_stream(oc, video_codec)) == null) {
                release();
                throw new Exception("avformat_new_stream() error: Could not allocate video stream.");
            }
            video_c = video_st.codec();
            video_c.codec_id(oformat.video_codec());
            video_c.codec_type(AVMEDIA_TYPE_VIDEO);

            /* put sample parameters */
            video_c.bit_rate(videoBitrate);
            /* resolution must be a multiple of two, but round up to 16 as often required */
            video_c.width((imageWidth + 15) / 16 * 16);
            video_c.height(imageHeight);
            if (aspectRatio > 0) {
                AVRational r = av_d2q(aspectRatio, 255);
                video_c.sample_aspect_ratio(r);
                video_st.sample_aspect_ratio(r);
            }
            /* time base: this is the fundamental unit of time (in seconds) in terms
               of which frame timestamps are represented. for fixed-fps content,
               timebase should be 1/framerate and timestamp increments should be
               identically 1. */
            video_c.time_base(av_inv_q(frame_rate));
            video_st.time_base(av_inv_q(frame_rate));
            if (gopSize >= 0) {
                video_c.gop_size(gopSize); /* emit one intra frame every gopSize frames at most */
            }
            if (videoQuality >= 0) {
                video_c.flags(video_c.flags() | CODEC_FLAG_QSCALE);
                video_c.global_quality((int) Math.round(FF_QP2LAMBDA * videoQuality));
            }

            if (pixelFormat != AV_PIX_FMT_NONE) {
                video_c.pix_fmt(pixelFormat);
            } else if (video_c.codec_id() == AV_CODEC_ID_RAWVIDEO || video_c.codec_id() == AV_CODEC_ID_PNG ||
                       video_c.codec_id() == AV_CODEC_ID_HUFFYUV  || video_c.codec_id() == AV_CODEC_ID_FFV1) {
                video_c.pix_fmt(AV_PIX_FMT_RGB32);   // appropriate for common lossless formats
            } else {
                video_c.pix_fmt(AV_PIX_FMT_YUV420P); // lossy, but works with about everything
            }

            if (video_c.codec_id() == AV_CODEC_ID_MPEG2VIDEO) {
                /* just for testing, we also add B frames */
                video_c.max_b_frames(2);
            } else if (video_c.codec_id() == AV_CODEC_ID_MPEG1VIDEO) {
                /* Needed to avoid using macroblocks in which some coeffs overflow.
                   This does not happen with normal video, it just happens here as
                   the motion of the chroma plane does not match the luma plane. */
                video_c.mb_decision(2);
            } else if (video_c.codec_id() == AV_CODEC_ID_H263) {
                // H.263 does not support any other resolution than the following
                if (imageWidth <= 128 && imageHeight <= 96) {
                    video_c.width(128).height(96);
                } else if (imageWidth <= 176 && imageHeight <= 144) {
                    video_c.width(176).height(144);
                } else if (imageWidth <= 352 && imageHeight <= 288) {
                    video_c.width(352).height(288);
                } else if (imageWidth <= 704 && imageHeight <= 576) {
                    video_c.width(704).height(576);
                } else {
                    video_c.width(1408).height(1152);
                }
            } else if (video_c.codec_id() == AV_CODEC_ID_H264) {
                // default to constrained baseline to produce content that plays back on anything,
                // without any significant tradeoffs for most use cases
                video_c.profile(AVCodecContext.FF_PROFILE_H264_CONSTRAINED_BASELINE);
            }

            // some formats want stream headers to be separate
            if ((oformat.flags() & AVFMT_GLOBALHEADER) != 0) {
                video_c.flags(video_c.flags() | CODEC_FLAG_GLOBAL_HEADER);
            }

            if ((video_codec.capabilities() & CODEC_CAP_EXPERIMENTAL) != 0) {
                video_c.strict_std_compliance(AVCodecContext.FF_COMPLIANCE_EXPERIMENTAL);
            }
        }

        /*
         * add an audio output stream
         */
        if (audioChannels > 0 && audioBitrate > 0 && sampleRate > 0) {
            if (audioCodec != AV_CODEC_ID_NONE) {
                oformat.audio_codec(audioCodec);
            } else if ("flv".equals(format_name) || "mp4".equals(format_name) || "3gp".equals(format_name)) {
                oformat.audio_codec(AV_CODEC_ID_AAC);
            } else if ("avi".equals(format_name)) {
                oformat.audio_codec(AV_CODEC_ID_PCM_S16LE);
            }

            /* find the audio encoder */
            if ((audio_codec = avcodec_find_encoder_by_name(audioCodecName)) == null &&
                (audio_codec = avcodec_find_encoder(oformat.audio_codec())) == null) {
                release();
                throw new Exception("avcodec_find_encoder() error: Audio codec not found.");
            }
            oformat.audio_codec(audio_codec.id());

            if ((audio_st = avformat_new_stream(oc, audio_codec)) == null) {
                release();
                throw new Exception("avformat_new_stream() error: Could not allocate audio stream.");
            }
            audio_c = audio_st.codec();
            audio_c.codec_id(oformat.audio_codec());
            audio_c.codec_type(AVMEDIA_TYPE_AUDIO);

            /* put sample parameters */
            audio_c.bit_rate(audioBitrate);
            audio_c.sample_rate(sampleRate);
            audio_c.channels(audioChannels);
            audio_c.channel_layout(av_get_default_channel_layout(audioChannels));
            if (sampleFormat != AV_SAMPLE_FMT_NONE) {
                audio_c.sample_fmt(sampleFormat);
            } else {
                // use AV_SAMPLE_FMT_S16 by default, if available
                audio_c.sample_fmt(AV_SAMPLE_FMT_FLTP);
                IntPointer formats = audio_c.codec().sample_fmts();
                for (int i = 0; formats.get(i) != -1; i++) {
                    if (formats.get(i) == AV_SAMPLE_FMT_S16) {
                        audio_c.sample_fmt(AV_SAMPLE_FMT_S16);
                        break;
                    }
                }
            }
            audio_c.time_base().num(1).den(sampleRate);
            audio_st.time_base().num(1).den(sampleRate);
            switch (audio_c.sample_fmt()) {
                case AV_SAMPLE_FMT_U8:
                case AV_SAMPLE_FMT_U8P:  audio_c.bits_per_raw_sample(8);  break;
                case AV_SAMPLE_FMT_S16:
                case AV_SAMPLE_FMT_S16P: audio_c.bits_per_raw_sample(16); break;
                case AV_SAMPLE_FMT_S32:
                case AV_SAMPLE_FMT_S32P: audio_c.bits_per_raw_sample(32); break;
                case AV_SAMPLE_FMT_FLT:
                case AV_SAMPLE_FMT_FLTP: audio_c.bits_per_raw_sample(32); break;
                case AV_SAMPLE_FMT_DBL:
                case AV_SAMPLE_FMT_DBLP: audio_c.bits_per_raw_sample(64); break;
                default: assert false;
            }
            if (audioQuality >= 0) {
                audio_c.flags(audio_c.flags() | CODEC_FLAG_QSCALE);
                audio_c.global_quality((int) Math.round(FF_QP2LAMBDA * audioQuality));
            }

            // some formats want stream headers to be separate
            if ((oformat.flags() & AVFMT_GLOBALHEADER) != 0) {
                audio_c.flags(audio_c.flags() | CODEC_FLAG_GLOBAL_HEADER);
            }

            if ((audio_codec.capabilities() & CODEC_CAP_EXPERIMENTAL) != 0) {
                audio_c.strict_std_compliance(AVCodecContext.FF_COMPLIANCE_EXPERIMENTAL);
            }
        }

        av_dump_format(oc, 0, filename, 1);

        /* now that all the parameters are set, we can open the audio and
           video codecs and allocate the necessary encode buffers */
        if (video_st != null) {
            AVDictionary options = new AVDictionary(null);
            if (videoQuality >= 0) {
                av_dict_set(options, "crf", "" + videoQuality, 0);
            }
            for (Entry<String, String> e : videoOptions.entrySet()) {
                av_dict_set(options, e.getKey(), e.getValue(), 0);
            }
            /* open the codec */
            if ((ret = avcodec_open2(video_c, video_codec, options)) < 0) {
                release();
                throw new Exception("avcodec_open2() error " + ret + ": Could not open video codec.");
            }
            av_dict_free(options);

            video_outbuf = null;
            if ((oformat.flags() & AVFMT_RAWPICTURE) == 0) {
                /* allocate output buffer */
                /* XXX: API change will be done */
                /* buffers passed into lav* can be allocated any way you prefer,
                   as long as they're aligned enough for the architecture, and
                   they're freed appropriately (such as using av_free for buffers
                   allocated with av_malloc) */
                video_outbuf_size = Math.max(256 * 1024, 8 * video_c.width() * video_c.height()); // a la ffmpeg.c
                video_outbuf = new BytePointer(av_malloc(video_outbuf_size));
            }

            /* allocate the encoded raw picture */
            if ((picture = av_frame_alloc()) == null) {
                release();
                throw new Exception("av_frame_alloc() error: Could not allocate picture.");
            }
            picture.pts(0); // magic required by libx264

            int size = avpicture_get_size(video_c.pix_fmt(), video_c.width(), video_c.height());
            if ((picture_buf = new BytePointer(av_malloc(size))).isNull()) {
                release();
                throw new Exception("av_malloc() error: Could not allocate picture buffer.");
            }

            /* if the output format is not equal to the image format, then a temporary
               picture is needed too. It is then converted to the required output format */
            if ((tmp_picture = av_frame_alloc()) == null) {
                release();
                throw new Exception("av_frame_alloc() error: Could not allocate temporary picture.");
            }

            AVDictionary metadata = new AVDictionary(null);
            for (Entry<String, String> e : videoMetadata.entrySet()) {
                av_dict_set(metadata, e.getKey(), e.getValue(), 0);
            }
            video_st.metadata(metadata);
        }

        if (audio_st != null) {
            AVDictionary options = new AVDictionary(null);
            if (audioQuality >= 0) {
                av_dict_set(options, "crf", "" + audioQuality, 0);
            }
            for (Entry<String, String> e : audioOptions.entrySet()) {
                av_dict_set(options, e.getKey(), e.getValue(), 0);
            }
            /* open the codec */
            if ((ret = avcodec_open2(audio_c, audio_codec, options)) < 0) {
                release();
                throw new Exception("avcodec_open2() error " + ret + ": Could not open audio codec.");
            }
            av_dict_free(options);

            audio_outbuf_size = 256 * 1024;
            audio_outbuf = new BytePointer(av_malloc(audio_outbuf_size));

            /* ugly hack for PCM codecs (will be removed ASAP with new PCM
               support to compute the input frame size in samples */
            if (audio_c.frame_size() <= 1) {
                audio_outbuf_size = FF_MIN_BUFFER_SIZE;
                audio_input_frame_size = audio_outbuf_size / audio_c.channels();
                switch (audio_c.codec_id()) {
                    case AV_CODEC_ID_PCM_S16LE:
                    case AV_CODEC_ID_PCM_S16BE:
                    case AV_CODEC_ID_PCM_U16LE:
                    case AV_CODEC_ID_PCM_U16BE:
                        audio_input_frame_size >>= 1;
                        break;
                    default:
                        break;
                }
            } else {
                audio_input_frame_size = audio_c.frame_size();
            }
            //int bufferSize = audio_input_frame_size * audio_c.bits_per_raw_sample()/8 * audio_c.channels();
            int planes = av_sample_fmt_is_planar(audio_c.sample_fmt()) != 0 ? (int)audio_c.channels() : 1;
            int data_size = av_samples_get_buffer_size((IntPointer)null, audio_c.channels(),
                    audio_input_frame_size, audio_c.sample_fmt(), 1) / planes;
            samples_out = new BytePointer[planes];
            for (int i = 0; i < samples_out.length; i++) {
                samples_out[i] = new BytePointer(av_malloc(data_size)).capacity(data_size);
            }
            samples_in = new Pointer[AVFrame.AV_NUM_DATA_POINTERS];
            samples_in_ptr  = new PointerPointer(AVFrame.AV_NUM_DATA_POINTERS);
            samples_out_ptr = new PointerPointer(AVFrame.AV_NUM_DATA_POINTERS);

            /* allocate the audio frame */
            if ((frame = av_frame_alloc()) == null) {
                release();
                throw new Exception("av_frame_alloc() error: Could not allocate audio frame.");
            }
            frame.pts(0); // magic required by libvorbis and webm

            AVDictionary metadata = new AVDictionary(null);
            for (Entry<String, String> e : audioMetadata.entrySet()) {
                av_dict_set(metadata, e.getKey(), e.getValue(), 0);
            }
            audio_st.metadata(metadata);
        }

        /* open the output file, if needed */
        if ((oformat.flags() & AVFMT_NOFILE) == 0) {
            AVIOContext pb = new AVIOContext(null);
            if ((ret = avio_open(pb, filename, AVIO_FLAG_WRITE)) < 0) {
                release();
                throw new Exception("avio_open error() error " + ret + ": Could not open '" + filename + "'");
            }
            oc.pb(pb);
        }

        AVDictionary options = new AVDictionary(null);
        for (Entry<String, String> e : this.options.entrySet()) {
            av_dict_set(options, e.getKey(), e.getValue(), 0);
        }
        AVDictionary metadata = new AVDictionary(null);
        for (Entry<String, String> e : this.metadata.entrySet()) {
            av_dict_set(metadata, e.getKey(), e.getValue(), 0);
        }
        /* write the stream header, if any */
        avformat_write_header(oc.metadata(metadata), options);
        av_dict_free(options);
    }

    public void stop() throws Exception {
        if (oc != null) {
            try {
                /* flush all the buffers */
                while (video_st != null && recordImage(0, 0, 0, 0, 0, AV_PIX_FMT_NONE, (Buffer[])null));
                while (audio_st != null && recordSamples(0, 0, (Buffer[])null));

                if (interleaved && video_st != null && audio_st != null) {
                    av_interleaved_write_frame(oc, null);
                } else {
                    av_write_frame(oc, null);
                }

                /* write the trailer, if any */
                av_write_trailer(oc);
            } finally {
                release();
            }
        }
    }

    @Override
    public void record(Frame frame) throws Exception {
        record(frame, AV_PIX_FMT_NONE);
    }
    public void record(Frame frame, int pixelFormat) throws Exception {
        if (frame == null || (frame.image == null && frame.samples == null)) {
            recordImage(0, 0, 0, 0, 0, pixelFormat, (Buffer[])null);
        } else {
            if (frame.image != null) {
                frame.keyFrame = recordImage(frame.imageWidth, frame.imageHeight, frame.imageDepth,
                        frame.imageChannels, frame.imageStride, pixelFormat, frame.image);
            }
            if (frame.samples != null) {
                frame.keyFrame = recordSamples(frame.sampleRate, frame.audioChannels, frame.samples);
            }
        }
    }

    public boolean recordImage(int width, int height, int depth, int channels, int stride, int pixelFormat, Buffer... image) throws Exception {
        if (video_st == null) {
            throw new Exception("No video output stream (Is imageWidth > 0 && imageHeight > 0 and has start() been called?)");
        }
        int ret;

        if (image == null || image.length == 0) {
            /* no more frame to compress. The codec has a latency of a few
               frames if using B frames, so we get the last frames by
               passing the same picture again */
        } else {
            int step = stride * Math.abs(depth) / 8;
            BytePointer data = image[0] instanceof ByteBuffer
                    ? new BytePointer((ByteBuffer)image[0].position(0))
                    : new BytePointer(new Pointer(image[0].position(0)));

            if (pixelFormat == AV_PIX_FMT_NONE) {
                if ((depth == Frame.DEPTH_UBYTE || depth == Frame.DEPTH_BYTE) && channels == 3) {
                    pixelFormat = AV_PIX_FMT_BGR24;
                } else if ((depth == Frame.DEPTH_UBYTE || depth == Frame.DEPTH_BYTE) && channels == 1) {
                    pixelFormat = AV_PIX_FMT_GRAY8;
                } else if ((depth == Frame.DEPTH_USHORT || depth == Frame.DEPTH_SHORT) && channels == 1) {
                    pixelFormat = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN) ?
                            AV_PIX_FMT_GRAY16BE : AV_PIX_FMT_GRAY16LE;
                } else if ((depth == Frame.DEPTH_UBYTE || depth == Frame.DEPTH_BYTE) && channels == 4) {
                    pixelFormat = AV_PIX_FMT_RGBA;
                } else if ((depth == Frame.DEPTH_UBYTE || depth == Frame.DEPTH_BYTE) && channels == 2) {
                    pixelFormat = AV_PIX_FMT_NV21; // Android's camera capture format
                    step = width;
                } else {
                    throw new Exception("Could not guess pixel format of image: depth=" + depth + ", channels=" + channels);
                }
            }

            if (video_c.pix_fmt() != pixelFormat || video_c.width() != width || video_c.height() != height) {
                /* convert to the codec pixel format if needed */
                img_convert_ctx = sws_getCachedContext(img_convert_ctx, width, height, pixelFormat,
                        video_c.width(), video_c.height(), video_c.pix_fmt(), SWS_BILINEAR,
                        null, null, (DoublePointer)null);
                if (img_convert_ctx == null) {
                    throw new Exception("sws_getCachedContext() error: Cannot initialize the conversion context.");
                }
                avpicture_fill(new AVPicture(tmp_picture), data, pixelFormat, width, height);
                avpicture_fill(new AVPicture(picture), picture_buf, video_c.pix_fmt(), video_c.width(), video_c.height());
                tmp_picture.linesize(0, step);
                tmp_picture.format(pixelFormat);
                tmp_picture.width(width);
                tmp_picture.height(height);
                picture.format(video_c.pix_fmt());
                picture.width(video_c.width());
                picture.height(video_c.height());
                sws_scale(img_convert_ctx, new PointerPointer(tmp_picture), tmp_picture.linesize(),
                          0, height, new PointerPointer(picture), picture.linesize());
            } else {
                avpicture_fill(new AVPicture(picture), data, pixelFormat, width, height);
                picture.linesize(0, step);
                picture.format(pixelFormat);
                picture.width(width);
                picture.height(height);
            }
        }

        if ((oformat.flags() & AVFMT_RAWPICTURE) != 0) {
            if (image == null || image.length == 0) {
                return false;
            }
            /* raw video case. The API may change slightly in the future for that? */
            av_init_packet(video_pkt);
            video_pkt.flags(video_pkt.flags() | AV_PKT_FLAG_KEY);
            video_pkt.stream_index(video_st.index());
            video_pkt.data(new BytePointer(picture));
            video_pkt.size(Loader.sizeof(AVPicture.class));
        } else {
            /* encode the image */
            av_init_packet(video_pkt);
            video_pkt.data(video_outbuf);
            video_pkt.size(video_outbuf_size);
            picture.quality(video_c.global_quality());
            if ((ret = avcodec_encode_video2(video_c, video_pkt, image == null || image.length == 0 ? null : picture, got_video_packet)) < 0) {
                throw new Exception("avcodec_encode_video2() error " + ret + ": Could not encode video packet.");
            }
            picture.pts(picture.pts() + 1); // magic required by libx264

            /* if zero size, it means the image was buffered */
            if (got_video_packet[0] != 0) {
                if (video_pkt.pts() != AV_NOPTS_VALUE) {
                    video_pkt.pts(av_rescale_q(video_pkt.pts(), video_c.time_base(), video_st.time_base()));
                }
                if (video_pkt.dts() != AV_NOPTS_VALUE) {
                    video_pkt.dts(av_rescale_q(video_pkt.dts(), video_c.time_base(), video_st.time_base()));
                }
                video_pkt.stream_index(video_st.index());
            } else {
                return false;
            }
        }

        synchronized (oc) {
            /* write the compressed frame in the media file */
            if (interleaved && audio_st != null) {
                if ((ret = av_interleaved_write_frame(oc, video_pkt)) < 0) {
                    throw new Exception("av_interleaved_write_frame() error " + ret + " while writing interleaved video frame.");
                }
            } else {
                if ((ret = av_write_frame(oc, video_pkt)) < 0) {
                    throw new Exception("av_write_frame() error " + ret + " while writing video frame.");
                }
            }
        }
        return image != null ? (video_pkt.flags() & AV_PKT_FLAG_KEY) != 0 : got_video_packet[0] != 0;
    }

    public boolean recordSamples(Buffer... samples) throws Exception {
        return recordSamples(0, 0, samples);
    }
    public boolean recordSamples(int sampleRate, int audioChannels, Buffer... samples) throws Exception {
        if (audio_st == null) {
            throw new Exception("No audio output stream (Is audioChannels > 0 and has start() been called?)");
        }
        int ret;

        if (sampleRate <= 0) {
            sampleRate = audio_c.sample_rate();
        }
        if (audioChannels <= 0) {
            audioChannels = audio_c.channels();
        }
        int inputSize = samples != null ? samples[0].limit() - samples[0].position() : 0;
        int inputFormat = AV_SAMPLE_FMT_NONE;
        int inputChannels = samples != null && samples.length > 1 ? 1 : audioChannels;
        int inputDepth = 0;
        int outputFormat = audio_c.sample_fmt();
        int outputChannels = samples_out.length > 1 ? 1 : audio_c.channels();
        int outputDepth = av_get_bytes_per_sample(outputFormat);
        if (samples != null && samples[0] instanceof ByteBuffer) {
            inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_U8P : AV_SAMPLE_FMT_U8;
            inputDepth = 1;
            for (int i = 0; i < samples.length; i++) {
                ByteBuffer b = (ByteBuffer)samples[i];
                if (samples_in[i] instanceof BytePointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                    ((BytePointer)samples_in[i]).position(0).put(b.array(), b.position(), inputSize);
                } else {
                    samples_in[i] = new BytePointer(b);
                }
            }
        } else if (samples != null && samples[0] instanceof ShortBuffer) {
            inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_S16P : AV_SAMPLE_FMT_S16;
            inputDepth = 2;
            for (int i = 0; i < samples.length; i++) {
                ShortBuffer b = (ShortBuffer)samples[i];
                if (samples_in[i] instanceof ShortPointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                    ((ShortPointer)samples_in[i]).position(0).put(b.array(), samples[i].position(), inputSize);
                } else {
                    samples_in[i] = new ShortPointer(b);
                }
            }
        } else if (samples != null && samples[0] instanceof IntBuffer) {
            inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_S32P : AV_SAMPLE_FMT_S32;
            inputDepth = 4;
            for (int i = 0; i < samples.length; i++) {
                IntBuffer b = (IntBuffer)samples[i];
                if (samples_in[i] instanceof IntPointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                    ((IntPointer)samples_in[i]).position(0).put(b.array(), samples[i].position(), inputSize);
                } else {
                    samples_in[i] = new IntPointer(b);
                }
            }
        } else if (samples != null && samples[0] instanceof FloatBuffer) {
            inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_FLTP : AV_SAMPLE_FMT_FLT;
            inputDepth = 4;
            for (int i = 0; i < samples.length; i++) {
                FloatBuffer b = (FloatBuffer)samples[i];
                if (samples_in[i] instanceof FloatPointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                    ((FloatPointer)samples_in[i]).position(0).put(b.array(), b.position(), inputSize);
                } else {
                    samples_in[i] = new FloatPointer(b);
                }
            }
        } else if (samples != null && samples[0] instanceof DoubleBuffer) {
            inputFormat = samples.length > 1 ? AV_SAMPLE_FMT_DBLP : AV_SAMPLE_FMT_DBL;
            inputDepth = 8;
            for (int i = 0; i < samples.length; i++) {
                DoubleBuffer b = (DoubleBuffer)samples[i];
                if (samples_in[i] instanceof DoublePointer && samples_in[i].capacity() >= inputSize && b.hasArray()) {
                    ((DoublePointer)samples_in[i]).position(0).put(b.array(), b.position(), inputSize);
                } else {
                    samples_in[i] = new DoublePointer(b);
                }
            }
        } else if (samples != null) {
            throw new Exception("Audio samples Buffer has unsupported type: " + samples);
        }

        if (samples_convert_ctx == null || samples_channels != audioChannels || samples_format != inputFormat || samples_rate != sampleRate) {
            samples_convert_ctx = swr_alloc_set_opts(samples_convert_ctx, audio_c.channel_layout(), outputFormat, audio_c.sample_rate(),
                    av_get_default_channel_layout(audioChannels), inputFormat, sampleRate, 0, null);
            if (samples_convert_ctx == null) {
                throw new Exception("swr_alloc_set_opts() error: Cannot allocate the conversion context.");
            } else if ((ret = swr_init(samples_convert_ctx)) < 0) {
                throw new Exception("swr_init() error " + ret + ": Cannot initialize the conversion context.");
            }
            samples_channels = audioChannels;
            samples_format = inputFormat;
            samples_rate = sampleRate;
        }

        for (int i = 0; samples != null && i < samples.length; i++) {
            samples_in[i].position(samples_in[i].position() * inputDepth).
                    limit((samples_in[i].position() + inputSize) * inputDepth);
        }
        while (true) {
            int inputCount = samples != null ? (samples_in[0].limit() - samples_in[0].position()) / (inputChannels * inputDepth) : 0;
            int outputCount = (samples_out[0].limit() - samples_out[0].position()) / (outputChannels * outputDepth);
            inputCount = Math.min(inputCount, (outputCount * sampleRate + audio_c.sample_rate() - 1) / audio_c.sample_rate());
            for (int i = 0; samples != null && i < samples.length; i++) {
                samples_in_ptr.put(i, samples_in[i]);
            }
            for (int i = 0; i < samples_out.length; i++) {
                samples_out_ptr.put(i, samples_out[i]);
            }
            if ((ret = swr_convert(samples_convert_ctx, samples_out_ptr, outputCount, samples_in_ptr, inputCount)) < 0) {
                throw new Exception("swr_convert() error " + ret + ": Cannot convert audio samples.");
            } else if (ret == 0) {
                break;
            }
            for (int i = 0; samples != null && i < samples.length; i++) {
                samples_in[i].position(samples_in[i].position() + inputCount * inputChannels * inputDepth);
            }
            for (int i = 0; i < samples_out.length; i++) {
                samples_out[i].position(samples_out[i].position() + ret * outputChannels * outputDepth);
            }

            if (samples == null || samples_out[0].position() >= samples_out[0].limit()) {
                frame.nb_samples(audio_input_frame_size);
                avcodec_fill_audio_frame(frame, audio_c.channels(), outputFormat, samples_out[0], samples_out[0].limit(), 0);
                for (int i = 0; i < samples_out.length; i++) {
                    frame.data(i, samples_out[i].position(0));
                    frame.linesize(i, samples_out[i].limit());
                }
                frame.quality(audio_c.global_quality());
                record(frame);
            }
        }
        return samples != null ? frame.key_frame() != 0 : record((AVFrame)null);
    }

    boolean record(AVFrame frame) throws Exception {
        int ret;

        av_init_packet(audio_pkt);
        audio_pkt.data(audio_outbuf);
        audio_pkt.size(audio_outbuf_size);
        if ((ret = avcodec_encode_audio2(audio_c, audio_pkt, frame, got_audio_packet)) < 0) {
            throw new Exception("avcodec_encode_audio2() error " + ret + ": Could not encode audio packet.");
        }
        if (frame != null) {
            frame.pts(frame.pts() + frame.nb_samples()); // magic required by libvorbis and webm
        }
        if (got_audio_packet[0] != 0) {
            if (audio_pkt.pts() != AV_NOPTS_VALUE) {
                audio_pkt.pts(av_rescale_q(audio_pkt.pts(), audio_c.time_base(), audio_st.time_base()));
            }
            if (audio_pkt.dts() != AV_NOPTS_VALUE) {
                audio_pkt.dts(av_rescale_q(audio_pkt.dts(), audio_c.time_base(), audio_st.time_base()));
            }
            audio_pkt.flags(audio_pkt.flags() | AV_PKT_FLAG_KEY);
            audio_pkt.stream_index(audio_st.index());
        } else {
            return false;
        }

        /* write the compressed frame in the media file */
        synchronized (oc) {
            if (interleaved && video_st != null) {
                if ((ret = av_interleaved_write_frame(oc, audio_pkt)) < 0) {
                    throw new Exception("av_interleaved_write_frame() error " + ret + " while writing interleaved audio frame.");
                }
            } else {
                if ((ret = av_write_frame(oc, audio_pkt)) < 0) {
                    throw new Exception("av_write_frame() error " + ret + " while writing audio frame.");
                }
            }
        }
        return true;
    }
}


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

<title>demo</title>
<meta name="date" content="2017-08-12">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

demo

Classes

SearchPagingDemo

SearchToJsonDemo

SearchToListDemo

SerpsToCsvDemo

SerpsToFeatureVector

SerpToRelevanceModel

SerpToSearchHitsDemo


text:
title: Fox Hunting Results
tags: ham-radio, fox-hunting
description: Fox Hunting Results
---

Last month, I posted about fox hunting [equipment](/posts/2014-04-21-fox-hunting-equipment.html) and [software](/posts/2014-04-22-fox-hunting-software.html) that [Mary](http://www.marypattison.com) and her friend Emily used[^1] for a final project. I forgot to mention some other tools: a compass to take bearings, a GPS to take latitude and longitude, and [ArcGIS](http://www.esri.com/) to map the data.

First, I put the transmitter in a known location, then we went around our neighborhood to take bearings from a few different locations. After getting their bearings (no pun intended), I went and hid with the transmitter and waited for them to find me. After they found me, I went and hid in a more challenging place and waited again.

![Mary and Emily taking a bearing.](/images/2014-04-17-foxhunt/mary-and-emily.jpg)

Mary and Emily took their bearings and locations (including the transmitter locations), imported them into ArcGIS to show how triangulation can be used to estimate a transmitter location. The transmitter can be assumed to be within the intersections of successful bearings.

![One of the resulting maps.](/images/2014-04-17-foxhunt/second-location.jpg)

Mary and I are planning on attending [HF in the Park](http://www.hamoperator.com/Park/) next Saturday, where there will be an organized fox hunt. We'll have to assemble the 2m portion of our Yagi antenna, but we're looking forward to refining our newly acquired skills.

[^1]: Since Mary doesn't (yet!) have her ham radio license, I assisted with the transmitter.


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('prerequisites', '0002_auto_20170717_1642'),
    ]

    operations = [
        migrations.AlterField(
            model_name='requirementitem',
            name='concurrentRule',
            field=models.CharField(choices=[('P', 'Must have previously taken'), ('1', 'May register/begin with one class remaining'), ('1', 'May register/begin with two classes remaining'), ('A', 'Concurrent registration allowed'), ('R', 'Concurrent registration required')], default='P', max_length=1, verbose_name='Concurrency Rule'),
        ),
    ]


text:
import Autosave from './src/autosave';

declare const _default: {
    Autosave: typeof Autosave;
};

export default _default;


text:
numpy.ma.MaskedArray.__div__
============================

.. currentmodule:: numpy.ma

.. automethod:: MaskedArray.__div__


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

namespace Microsoft.Common.Core.OS {
    public interface IUserCredentials {
        string Username { get; set; }
        string Sid { get; set; }
        string Domain { get; set; }
    }
}