text:
describe EvilEvents::Core::Events::Serializers::Base::EventSerializationState, :stub_event_system do
  describe 'instantiation' do
    specify 'via event' do
      event = build_event_class('test_event') do
        payload :a
        payload :b
        payload :c

        metadata :d
        metadata :e
        metadata :f
      end.new(
        payload:  { a: gen_int, b: gen_str,  c: gen_symb  },
        metadata: { d: gen_str, e: gen_symb, f: gen_float }
      )

      state = described_class.build_from_event(event)

      expect(state.instance_variables).to contain_exactly(:@id, :@type, :@metadata, :@payload)
      expect(state.id).to eq(event.id)
      expect(state.type).to eq(event.type)
      expect(state.metadata).to match(event.metadata)
      expect(state.payload).to  match(event.payload)
    end

    specify 'via options' do
      attributes = { id: gen_str, type: gen_str, payload: {}, metadata: {} }

      state = described_class.build_from_options(**attributes)

      expect(state.instance_variables).to contain_exactly(:@id, :@type, :@metadata, :@payload)
      expect(state.id).to eq(attributes[:id])
      expect(state.type).to eq(attributes[:type])
      expect(state.metadata).to match(attributes[:metadata])
      expect(state.payload).to  match(attributes[:payload])
    end

    specify 'via constructor' do
    end
  end

  describe '#valid?' do
    let(:non_hash_values) do
      [gen_str, gen_symb, gen_int, gen_float, gen_obj, gen_bool, gen_lambda]
    end

    let(:non_string_values) do
      [{}, gen_symb, gen_int, gen_float, gen_obj, gen_bool, gen_lambda]
    end

    let(:valid_attributes) do
      { id: gen_str, type: gen_str, payload: {}, metadata: {} }
    end

    specify 'false when type isnt defined' do
      invalid_attributes = valid_attributes.merge(type: nil)
      state = described_class.new(**invalid_attributes)
      expect(state.valid?).to eq(false)
    end

    specify 'false when payload isnt defined' do
      invalid_attributes = valid_attributes.merge(payload: nil)
      state = described_class.new(**invalid_attributes)
      expect(state.valid?).to eq(false)
    end

    specify 'false when metadata isnt defined' do
      invalid_attributes = valid_attributes.merge(metadata: nil)
      state = described_class.new(**invalid_attributes)
      expect(state.valid?).to eq(false)
    end

    specify 'false when payload isnt a hash' do
      non_hash_values.each do |non_hash|
        invalid_attributes = valid_attributes.merge(payload: non_hash)
        state = described_class.new(**invalid_attributes)
        expect(state.valid?).to eq(false)
      end
    end

    specify 'false when metadata isnt a hash' do
      non_hash_values.each do |non_hash|
        invalid_attributes = valid_attributes.merge(metadata: non_hash)
        state = described_class.new(**invalid_attributes)
        expect(state.valid?).to eq(false)
      end
    end

    specify 'false when type isnt a string' do
      non_string_values.each do |non_string|
        invalid_attributes = valid_attributes.merge(type: non_string)
        state = described_class.new(**invalid_attributes)
        expect(state.valid?).to eq(false)
      end
    end

    specify 'true when type/payload/metadata are correctly defined' do
      state = described_class.new(**valid_attributes)
      expect(state.valid?).to eq(true)
      state = described_class.new(**valid_attributes.merge(id: nil))
      expect(state.valid?).to eq(true)
    end
  end
end


text: export { default } from 'rsg-components/TableOfContents/TableOfContents';

redpajama_set_name: RedPajamaGithub


text:
package org.apache.asterix.runtime.evaluators.functions.temporal;

import java.io.DataOutput;

import org.apache.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import org.apache.asterix.om.base.AInterval;
import org.apache.asterix.om.base.AMutableInterval;
import org.apache.asterix.om.base.ANull;
import org.apache.asterix.om.functions.AsterixBuiltinFunctions;
import org.apache.asterix.om.functions.IFunctionDescriptor;
import org.apache.asterix.om.functions.IFunctionDescriptorFactory;
import org.apache.asterix.om.pointables.nonvisitor.AIntervalPointable;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.asterix.om.types.EnumDeserializer;
import org.apache.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.data.std.api.IPointable;
import org.apache.hyracks.data.std.primitive.TaggedValuePointable;
import org.apache.hyracks.data.std.util.ArrayBackedValueStorage;
import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference;

public class GetOverlappingIntervalDescriptor extends AbstractScalarFunctionDynamicDescriptor {
    private static final long serialVersionUID = 1L;
    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
        @Override
        public IFunctionDescriptor createFunctionDescriptor() {
            return new GetOverlappingIntervalDescriptor();
        }
    };

    @Override
    public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args)
            throws AlgebricksException {
        return new IScalarEvaluatorFactory() {

            private static final long serialVersionUID = 1L;

            @Override
            public IScalarEvaluator createScalarEvaluator(final IHyracksTaskContext ctx) throws AlgebricksException {
                return new IScalarEvaluator() {

                    protected final IntervalLogic il = new IntervalLogic();
                    private ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage();
                    private DataOutput out = resultStorage.getDataOutput();
                    private TaggedValuePointable argPtr0 = (TaggedValuePointable) TaggedValuePointable.FACTORY
                            .createPointable();
                    private TaggedValuePointable argPtr1 = (TaggedValuePointable) TaggedValuePointable.FACTORY
                            .createPointable();
                    private AIntervalPointable interval0 = (AIntervalPointable) AIntervalPointable.FACTORY
                            .createPointable();
                    private AIntervalPointable interval1 = (AIntervalPointable) AIntervalPointable.FACTORY
                            .createPointable();
                    private IScalarEvaluator eval0 = args[0].createScalarEvaluator(ctx);
                    private IScalarEvaluator eval1 = args[1].createScalarEvaluator(ctx);

                    private final AMutableInterval aInterval = new AMutableInterval(0, 0, (byte) -1);

                    @SuppressWarnings("unchecked")
                    private final ISerializerDeserializer<ANull> nullSerde = AqlSerializerDeserializerProvider.INSTANCE
                            .getSerializerDeserializer(BuiltinType.ANULL);
                    @SuppressWarnings("unchecked")
                    private final ISerializerDeserializer<AInterval> intervalSerde = AqlSerializerDeserializerProvider.INSTANCE
                            .getSerializerDeserializer(BuiltinType.AINTERVAL);

                    @Override
                    public void evaluate(IFrameTupleReference tuple, IPointable result) throws AlgebricksException {
                        resultStorage.reset();
                        eval0.evaluate(tuple, argPtr0);
                        eval1.evaluate(tuple, argPtr1);
                        byte type0 = argPtr0.getTag();
                        byte type1 = argPtr1.getTag();

                        try {
                            if (type0 == ATypeTag.SERIALIZED_NULL_TYPE_TAG
                                    || type1 == ATypeTag.SERIALIZED_NULL_TYPE_TAG) {
                                nullSerde.serialize(ANull.NULL, out);
                            } else if (type0 == ATypeTag.SERIALIZED_INTERVAL_TYPE_TAG && type0 == type1) {
                                argPtr0.getValue(interval0);
                                argPtr1.getValue(interval1);
                                byte intervalType0 = interval0.getType();
                                byte intervalType1 = interval1.getType();

                                if (intervalType0 != intervalType1) {
                                    throw new AlgebricksException(getIdentifier().getName()
                                            + ": expecting two (nullable) interval values with the same internal time type but got interval of "
                                            + interval0.getTypeTag() + " and interval of " + interval1.getTypeTag());
                                }

                                if (il.overlap(interval0, interval1) || il.overlappedBy(interval0, interval1)
                                        || il.covers(interval0, interval1) || il.coveredBy(interval0, interval1)) {
                                    long start = Math.max(interval0.getStartValue(), interval1.getStartValue());
                                    long end = Math.min(interval0.getEndValue(), interval1.getEndValue());
                                    aInterval.setValue(start, end, intervalType0);
                                    intervalSerde.serialize(aInterval, out);
                                } else {
                                    nullSerde.serialize(ANull.NULL, out);
                                }
                            } else {
                                throw new AlgebricksException(getIdentifier().getName()
                                        + ": expecting two (nullable) interval values but got "
                                        + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(type0) + " and "
                                        + EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(type1));
                            }
                        } catch (HyracksDataException hex) {
                            throw new AlgebricksException(hex);
                        }
                        result.set(resultStorage);
                    }

                };
            }
        };
    }

    @Override
    public FunctionIdentifier getIdentifier() {
        return AsterixBuiltinFunctions.GET_OVERLAPPING_INTERVAL;
    }
}


text:
import Ember from 'ember';

import AbstractRoute from './abstract';

export default AbstractRoute.extend({
  model() {
    return Ember.RSVP.hash({
      clusterMetrics: this.store.findAll('ClusterMetric', {reload: true}),
      apps: this.store.query('yarn-app',
        {
          state: "RUNNING"
        }),
      queues: this.store.query('yarn-queue.yarn-queue', {}),
    });
  },

  afterModel() {
    this.controllerFor("ClusterOverview").set("loading", false);
  },

  unloadAll() {
    this.store.unloadAll('ClusterMetric');
    this.store.unloadAll('yarn-app');
    this.store.unloadAll('yarn-queue.yarn-queue');
  }
});


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>File: babelphish.rake</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

babelphish.rake

      Path:
      lib/tasks/babelphish.rake

      Last Update:
      Sat Aug 15 11:44:54 -0600 2009

desc "Translate files via Google Translate." task :babelphish do

  require 'babelphish/translator'
  options={}
  yml = ENV['yml']
  html = ENV['html']
  language = ENV['language']
  overwrite = ENV['overwrite'] == 'yes'
  translate_to = ENV['translate_to'] || nil
  translate_tos = ENV['translate_tos'] || nil

  begin
    translate_tos = translate_tos.split(',') if translate_tos
  rescue
    STDERR.puts "An error occured while parsing the specified language codes #{translate_tos}.  Please be sure to use a comman delimited list.  ie es,fr,jp"
    return
  end

  begin
    if yml
      STDERR.puts "Translating #{yml}"
      translate_tos ||= Babelphish::GoogleTranslate::LANGUAGES
      Babelphish::YmlTranslator.translate(yml, overwrite, translate_to, translate_tos)
    elsif html
      if language.nil?
        STDERR.puts "No source language specified when using 'html' option.  Defaulting to 'en'"
        language = 'en'
      end
      STDERR.puts "Translating files in #{html}"
      translate_tos ||= Babelphish::GoogleTranslate::LANGUAGES
      Babelphish::HtmlTranslator.translate(html, translate_tos, language, overwrite)
    else
      STDERR.puts "Please specify the directory where your files live. i.e. babelphish -y ./my/locales  or babelphish -h ./some/directory/with/erb_or_html/files"
    end
  rescue Babelphish::Exceptions::GoogleResponseError => ex
    STDERR.puts ex
  end

end

[Validate]


text:
@implementation NIMLocationContentConfig
- (CGSize)contentSize:(CGFloat)cellWidth
{
    return CGSizeMake(110.f, 105.f);
}

- (NSString *)cellContent
{
    return @"NIMSessionLocationContentView";
}

- (UIEdgeInsets)contentViewInsets
{
    return self.message.isOutgoingMsg ? UIEdgeInsetsMake(3,3,3,8) : UIEdgeInsetsMake(3,8,3,3);
}
@end


text:
layout: post
title: Like my father
image: lakeview.jpg
---

I've noticed lately that there have been many latent influences that have slowly made their way into the foreground of my life. Some of these are artistic pursuits that I tried as a child and have since become central themes in my life, others are more subtle. It seems I'm slowly turning into my father.

I've long cherished the thought of embarrassing my future spawn with awkward songs, bad catchphrases, and (intentionally) terrible dancing. The legacy of my father in imitable form.

However, there are more subtle things that I've been noticing. An interest in Bonsai, the New York reflection of my father's green thumb. A focus on esoteric athletic activity, climbing and capoeira instead of racquetball and rowing. A desire to sit and really listen to albums.

At one point these similarities would have concerned me, who wants to turn into their parents? But as I get a little older (no comment on related attributes), I've started to cherish the connection that these attributes create with my old man. So… Cheers to doing it right.


text:
namespace v8 {
namespace base {
namespace bits {

// CountSetBits32(value) returns the number of bits set in |value|.
inline uint32_t CountSetBits32(uint32_t value) {
#if V8_HAS_BUILTIN_POPCOUNT
  return __builtin_popcount(value);
#else
  value = ((value >> 1) & 0x55555555) + (value & 0x55555555);
  value = ((value >> 2) & 0x33333333) + (value & 0x33333333);
  value = ((value >> 4) & 0x0f0f0f0f) + (value & 0x0f0f0f0f);
  value = ((value >> 8) & 0x00ff00ff) + (value & 0x00ff00ff);
  value = ((value >> 16) & 0x0000ffff) + (value & 0x0000ffff);
  return value;
#endif
}

// CountLeadingZeros32(value) returns the number of zero bits following the most
// significant 1 bit in |value| if |value| is non-zero, otherwise it returns 32.
inline uint32_t CountLeadingZeros32(uint32_t value) {
#if V8_HAS_BUILTIN_CLZ
  return value ? __builtin_clz(value) : 32;
#elif V8_CC_MSVC
  unsigned long result;  // NOLINT(runtime/int)
  if (!_BitScanReverse(&result, value)) return 32;
  return static_cast<uint32_t>(31 - result);
#else
  value = value | (value >> 1);
  value = value | (value >> 2);
  value = value | (value >> 4);
  value = value | (value >> 8);
  value = value | (value >> 16);
  return CountSetBits32(~value);
#endif
}

// CountTrailingZeros32(value) returns the number of zero bits preceding the
// least significant 1 bit in |value| if |value| is non-zero, otherwise it
// returns 32.
inline uint32_t CountTrailingZeros32(uint32_t value) {
#if V8_HAS_BUILTIN_CTZ
  return value ? __builtin_ctz(value) : 32;
#elif V8_CC_MSVC
  unsigned long result;  // NOLINT(runtime/int)
  if (!_BitScanForward(&result, value)) return 32;
  return static_cast<uint32_t>(result);
#else
  if (value == 0) return 32;
  unsigned count = 0;
  for (value ^= value - 1; value >>= 1; ++count)
    ;
  return count;
#endif
}

inline uint32_t RotateRight32(uint32_t value, uint32_t shift) {
  if (shift == 0) return value;
  return (value >> shift) | (value << (32 - shift));
}

inline uint64_t RotateRight64(uint64_t value, uint64_t shift) {
  if (shift == 0) return value;
  return (value >> shift) | (value << (64 - shift));
}

}  // namespace bits
}  // namespace base
}  // namespace v8

#endif  // V8_BASE_BITS_H_


text:
/* $Id$ */
/*
 * (c) copyright 1987 by the Vrije Universiteit, Amsterdam, The Netherlands.
 * See the copyright notice in the ACK home directory, in the file "Copyright".
 */
#include <em_reg.h>
#include <em_mnem.h>
#include "../share/types.h"
#include "../share/alloc.h"
#include "../share/lset.h"
#include "../share/aux.h"
#include "../share/global.h"
#include "../share/debug.h"
#include "cs.h"
#include "cs_avail.h"
#include "cs_alloc.h"
#include "cs_aux.h"
#include "cs_debug.h"
#include "cs_profit.h"
#include "cs_partit.h"
#include "cs_debug.h"

static void dlink(line_p l1, line_p l2)
{
	/* Doubly link the lines in l1 and l2. */

	if (l1 != (line_p) 0)
		l1->l_next = l2;
	if (l2 != (line_p) 0)
		l2->l_prev = l1;
}

static void remove_lines(line_p first, line_p last)
{
	/* Throw away the lines between and including first and last.
	 * Don't worry about any pointers; the (must) have been taken care of.
	 */
	line_p lnp, next;

	last->l_next = (line_p) 0; /* Delimit the list. */
	for (lnp = first; lnp != (line_p) 0; lnp = next) {
		next = lnp->l_next;
		oldline(lnp);
	}
}

static bool contained(occur_p ocp1, occur_p ocp2)
{
	/* Determine whether ocp1 is contained within ocp2. */

	line_p lnp, next;

	for (lnp = ocp2->oc_lfirst; lnp != (line_p) 0; lnp = next) {
		next = lnp != ocp2->oc_llast ? lnp->l_next : (line_p) 0;

		if (lnp == ocp1->oc_llast) return TRUE;
	}
	return FALSE;
}

static void delete(occur_p ocp, avail_p start)
{
	/* Delete all occurrences that are contained within ocp.
	 * They must have been entered in the list before start:
	 * if an expression is contained with an other, its operator line
	 * appears before the operator line of the other because EM-expressions
	 * are postfix.
	 */
	avail_p ravp;
	Lindex	i, next;

	for (ravp = start; ravp != (avail_p) 0; ravp = ravp->av_before) {
		for (i = Lfirst(ravp->av_occurs); i != (Lindex) 0; i = next) {
			next = Lnext(i, ravp->av_occurs);

			if (contained(occ_elem(i), ocp)) {
				OUTTRACE("delete contained occurrence", 0);
#				ifdef TRACE
					SHOWOCCUR(occ_elem(i));
#				endif
				oldoccur(occ_elem(i));
				Lremove(Lelem(i), &ravp->av_occurs);
			}
		}
	}
}

static void complete_aar(line_p lnp, int instr, valnum descr_vn)
{
	/* Lnp is an instruction that loads the address of an array-element.
	 * Instr tells us what effect we should achieve; load (instr is op_lar)
	 * or store (instr is op_sar) this array-element. Descr_vn is the
	 * valuenumber of the address of the descriptor of this array.
	 * We append a loi or sti of the correct number of bytes.
	 */
	line_p lindir;

	lindir = int_line(array_elemsize(descr_vn));
	lindir->l_instr = instr == op_lar ? op_loi : op_sti;
	dlink(lindir, lnp->l_next);
	dlink(lnp, lindir);
}

static void replace(occur_p ocp, offset tmp, avail_p avp)
{
	/* Replace the lines in the occurrence in ocp by a load of the
	 * temporary with offset tmp.
	 */
	line_p lol, first, last;

	assert(avp->av_size == ws || avp->av_size == 2*ws);

	first = ocp->oc_lfirst; last = ocp->oc_llast;

	lol = int_line(tmp);
	lol->l_instr = avp->av_size == ws ? op_lol : op_ldl;
	dlink(lol, last->l_next);

	if (first->l_prev == (line_p) 0) ocp->oc_belongs->b_start = lol;
	dlink(first->l_prev, lol);

	if (avp->av_instr == (byte) op_aar) {
		/* There may actually be a LAR or a SAR instruction; in that
		 * case we have to complete the array-instruction.
		 */
		int instr = INSTR(last);

		if (instr != op_aar) complete_aar(lol, instr, avp->av_othird);
	}

	/* Throw away the by now useless lines. */
	remove_lines(first, last);
}

static void append(avail_p avp, offset tmp)
{
	/* Avp->av_found points to a line with an operator in it. This
	 * routine emits a sequence of instructions that saves the result
	 * in a local with offset tmp. In most cases we just append
	 * avp->av_found with stl/sdl tmp and lol/ldl tmp depending on
	 * avp->av_size. If however the operator is an aar contained
	 * within a lar or sar, we must first generate the aar.
	 */
	line_p stl, lol;

	assert(avp->av_size == ws || avp->av_size == 2*ws);

	stl = int_line(tmp);
	stl->l_instr = avp->av_size == ws ? op_stl : op_sdl;
	lol = int_line(tmp);
	lol->l_instr = avp->av_size == ws ? op_lol : op_ldl;

	dlink(lol, avp->av_found->l_next);
	dlink(stl, lol);
	dlink(avp->av_found, stl);

	if (avp->av_instr == (byte) op_aar) {
		int instr = INSTR(avp->av_found);

		if (instr != op_aar) {
			complete_aar(lol, instr, avp->av_othird);
			avp->av_found->l_instr = op_aar;
		}
	}
}

static void set_replace(avail_p avp, offset tmp)
{
	/* Avp->av_occurs is now a set of occurrences, each of which will be
	 * replaced by a reference to a local.
	 * Each time we eliminate an expression, we delete from our
	 * list those expressions that are physically contained in them,
	 * because we cannot eliminate them again.
	 */
	Lindex i;
	lset s = avp->av_occurs;

	for (i = Lfirst(s); i != (Lindex) 0; i = Lnext(i, s)) {
		OUTVERBOSE("eliminate duplicate", 0);
		SHOWOCCUR(occ_elem(i));
		Scs++;
		delete(occ_elem(i), avp->av_before);
		replace(occ_elem(i), tmp, avp);
	}
}

static int reg_score(entity_p enp)
{
	/* Enp is a local that will go into a register.
	 * We return its score upto now.
	 */
	assert(is_regvar(enp->en_loc));
	return regv_arg(enp->en_loc, 4);
}

static line_p gen_mesreg(offset off, avail_p avp, proc_p pp)
{
	/* Generate a register message for the local that will hold the
	 * result of the expression in avp, at the appropriate place in
	 * the procedure in pp.
	 */
	line_p reg;

	reg = reg_mes(off, (short) avp->av_size, regtype(avp->av_instr), 0);
	appnd_line(reg, pp->p_start->b_start);

	return reg;
}

static void change_score(line_p mes, int score)
{
	/* Change the score in the register message in mes to score. */

	arg_p ap = ARG(mes);

	ap = ap->a_next; /* Offset. */
	ap = ap->a_next; /* Size. */
	ap = ap->a_next; /* Type. */
	ap = ap->a_next; /* Score. */

	ap->a_a.a_offset = score;
}

void eliminate(proc_p pp)
{
	/* Eliminate costly common subexpressions within procedure pp.
	 * We scan the available expressions in - with respect to time found -
	 * reverse order, to find largest first, e.g. `A + B + C' before
	 * `A + B'.
	 * We do not eliminate an expression when the size
	 * is not one of ws or 2*ws, because then we cannot use lol or ldl.
	 * Code is appended to the first occurrence of the expression
	 * to store the result into a local.
	 */
	avail_p ravp;
	int score;
	offset tmp;
	line_p mes;

	for (ravp = avails; ravp != (avail_p) 0; ravp = ravp->av_before) {

		if (ravp->av_size != ws && ravp->av_size != 2*ws) continue;

		if (ravp->av_saveloc == (entity_p) 0) {
			/* We save it ourselves. */
			score = 2; /* Stl and lol. */
		} else {
			score = reg_score(ravp->av_saveloc);
		}
		if (desirable(ravp)) {
			score += Lnrelems(ravp->av_occurs);
			OUTTRACE("temporary local score %d", score);
			if (ravp->av_saveloc != (entity_p) 0) {
				tmp = ravp->av_saveloc->en_loc;
				mes = find_mesreg(tmp);
				OUTVERBOSE("re-using %ld(LB)", tmp);
			} else {
				tmp = tmplocal(pp,  ravp->av_size);
				mes = gen_mesreg(tmp, ravp, pp);
				append(ravp, tmp);
			}
			change_score(mes, score);
			set_replace(ravp, tmp);
		}
	}
}


text:
package org.motechproject.it;

import org.hamcrest.core.IsEqual;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.motechproject.config.core.domain.BootstrapConfig;
import org.motechproject.config.service.ConfigurationService;
import org.motechproject.testing.osgi.BasePaxIT;
import org.motechproject.testing.osgi.container.MotechNativeTestContainerFactory;
import org.ops4j.pax.exam.ExamFactory;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerSuite;

import javax.inject.Inject;
import java.io.IOException;
import java.util.Properties;

import static org.junit.Assert.assertThat;

@RunWith(PaxExam.class)
@ExamReactorStrategy(PerSuite.class)
@ExamFactory(MotechNativeTestContainerFactory.class)
public class ConfigurationServiceBundleIT extends BasePaxIT {

    @Inject
    private ConfigurationService configurationService;

    @Test
    public void shouldSaveBootstrapConfigToDefaultLocationAndLoadFromTheSameLocation() {
        BootstrapConfig existingBootstrapConfig = configurationService.loadBootstrapConfig();
        BootstrapConfig bootstrapConfig = new BootstrapConfig(existingBootstrapConfig.getSqlConfig(), "tenant-abc", existingBootstrapConfig.getConfigSource(), "./felix", existingBootstrapConfig.getQueueUrl(), existingBootstrapConfig.getActiveMqProperties());

        configurationService.save(bootstrapConfig);

        assertThat(configurationService.loadBootstrapConfig(), IsEqual.equalTo(bootstrapConfig));
    }

    @Test
    public void shouldPersistAndRetrieveBundlePropertiesFromDatabase() throws IOException, InterruptedException {
        Properties newProperties = new Properties();
        newProperties.put("test_prop3", "test3");
        newProperties.put("test_prop", "test_1");
        newProperties.put("test_prop2", "test_other");
        configurationService.addOrUpdateProperties("test_module", "1.0.0", "file1", newProperties, getDefaultProperties());

        Thread.sleep(2000);

        Properties retrievedProperties = configurationService.getBundleProperties("test_module", "file1", getDefaultProperties());
        assertThat(retrievedProperties, IsEqual.equalTo(newProperties));
    }

    private Properties getDefaultProperties() {
        Properties p = new Properties();
        p.put("test_prop", "test_1");
        p.put("test_prop2", "test_2");
        return p;
    }
}


text:
import { Poll, PollItem } from '../../types/models';
import axios from 'axios';

const DEFAULTS = {
  max_items: 1,
  length: 0,
  items: [
    {text: ''},
    {text: ''}
  ]
};

const state = {
  poll: DEFAULTS
}

const mutations = {
  init(state, poll: Poll) {
    if (poll) {
      state.poll = poll;
    }
  },

  removeItem(state, item: PollItem) {
    if (state.poll.items.length > 2) {
      state.poll.items.splice(state.poll.items.indexOf(item), 1);
    }
  },

  addItem(state) {
    state.poll.items.push({});
  },

  resetDefaults(state) {
    state.poll = DEFAULTS;
  }
}

const actions = {
  vote({ state, commit }, options: number[]) {
    return axios.post(`/Forum/Poll/${state.poll.id}`, { items: options }).then(result => commit('init', result.data));
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
};


text:
OpenTexonBlogger is a free blog platform for Linux/Mac. Wich has everything you'll need for a simple blog, accounts, easy to use article posting, reading articles and comment on them and much more. OpenTexonBlogger is also highly customizable.

### Prerequisites

To Install the OpenTexonBlogger you'll need these things:

* PHP5
* Apache2
* Mod_rewrite
* PEAR
* The following pear modules: mail, Net_SMTP, Auth_SASL, mail_meme

To install these do the following commands

```sh
$ sudo apt-get update
$ sudo apt-get install apache2
$ sudo apt-get install php5
$ sudo a2enmod rewrite
$ sudo apt-get install php-pear
$ sudo pear install mail
$ sudo pear install Net_SMTP
$ sudo pear install Auth_SASL
$ sudo pear install mail_mime
$ sudo service apache2 restart
$ sudo chown -R www-data /var/www
```

Also you must make sure that .htaccess is enabled on your server configuration and that apache2 has read access to the web directory.

This software is NOT compatible with Windows, only Linux or Mac. Also this software uses CloudFlare to get ip information such as country and therefore some features will not work unless you use CloudFlare.

### Installing OpenTexonBlogger

Download the source and put it in your web server then open the file php/config.php and edit to your liking making sure to set a web server address and where the website location is. After that navigate to http://yoursite.com/install and follow the onscreen instructions.

### Configuring the config.php file

Before you install OpenTexonBlogger you must configure the php/config.php file.

Heres what all the options do:

```php
// General settings

// The domain of your website
define("Website_Url","http://example.com");

// The name of your website
define("Website_Name","Example");

// Website copyright to display at the bottom of the page
define("Website_Copyright","Copyright © ".constant("Website_Name")." 2014-".date("Y")." All Rights Reserved<br>Powered by the <a href='https://opentexon.com/blog'>OpenTexon Blog Platform</a> | <a href='terms'>Terms & Conditions</a>");

// If the site is on maintenance and should not allow any traffic to the website
define("Website_Lockdown","false");

// IP Addresses that are allowed to visit the site on maintenance mode
define("Excpetions_IP_Addresses","");

// IP Addresses that are blocked from visiting the website
define("Blocker_Blocked_IPS","");

// Country CODES that are blocked from visitng the website
define("Blocker_Blocked_Countries","");

// IP Addresses that should be ignored by the logger
define("Excpetions_IP_Ignore_Log","");

// The email address of the site owner
define("Website_Server_Admin","example@gmail.com");

// When the site should be online when it's on maintenance
define("Website_Maintaince","22:00 CET 15 feb 2016");

// If normal users can post articles
define("Website_Article_CanPost","true");

// The website language
define("Website_Language","EN");

// If it should set the language based on the visitor location
define("Language_Auto","false");

// If users can register an account
define("Website_Allow_Register","true");

// If users must login to view the website
define("Website_Require_Login","false");

// If two step authentication is enabled when logging in
define("Security_EmailLoginVerification","false");

// If it should block users with AdBlock enabled
define("Block_AdBlock","false");

// Email server settings

// Your email server username
define("Email_Username","");

// Your email server password
define("Email_Password","");

// Your email server host
define("Email_Host","");

// Your email server port
define("Email_Port","");

// Location settings

// The location of the logs
define("Logger_Dir","/var/wwwlogs/");

// The location of stored data for accounts etc (Please do NOT store in your web directory)
define("Website_Data_dir","/var/opentexon/");

// The location of the website
define("Website_Location","/var/www/opentexon.com/");

// Website backend information (Do NOT change)
define("Website_Version","0.0.3");

// Update settigns
// If the website should look for updates (Recommended to have set to true)
define("Update_LookForUpdates","true");

// Social media Links
// Just put your web addresses for your social accounts for the webiste
define("Social_Facebook","");
define("Social_Twitter","");
define("Social_GPlus","");
define("Social_YouTube","");
define("Social_LinkedIn","");
define("Social_Dribbble","");
```

### Translations

Feel free to translate this software into your language, head into lang/EN/language.php and create a request and translate to your language.

Current supported languages are:
* Swedish
* English

There is also an option to auto detect what language the user is on depending on their ip address.

### Todos

 - Add more info to account.php
 - Automatic updater
 - Translate more

License
----

This software is licensed under the MIT license.

If you wish to modify this software please give credit and link to this git.


text:
namespace NotificationsExtensions.Tiles
{
    [NotificationXmlElement("image")]
    internal sealed class Element_TileImage : IElement_TileBindingChild, IElement_TileSubgroupChild
    {
        internal const TileImagePlacement DEFAULT_PLACEMENT = TileImagePlacement.Inline;
        internal const TileImageCrop DEFAULT_CROP = TileImageCrop.None;
        internal const bool DEFAULT_REMOVE_MARGIN = false;
        internal const TileImageAlign DEFAULT_ALIGN = TileImageAlign.Stretch;

        [NotificationXmlAttribute("id")]
        public int? Id { get; set; }

        [NotificationXmlAttribute("src")]
        public string Src { get; set; }

        [NotificationXmlAttribute("alt")]
        public string Alt { get; set; }

        [NotificationXmlAttribute("addImageQuery")]
        public bool? AddImageQuery { get; set; }

        [NotificationXmlAttribute("placement", DEFAULT_PLACEMENT)]
        public TileImagePlacement Placement { get; set; } = DEFAULT_PLACEMENT;

        [NotificationXmlAttribute("hint-align", DEFAULT_ALIGN)]
        public TileImageAlign Align { get; set; } = DEFAULT_ALIGN;

        [NotificationXmlAttribute("hint-crop", DEFAULT_CROP)]
        public TileImageCrop Crop { get; set; } = DEFAULT_CROP;

        [NotificationXmlAttribute("hint-removeMargin", DEFAULT_REMOVE_MARGIN)]
        public bool RemoveMargin { get; set; } = DEFAULT_REMOVE_MARGIN;

        private int? _overlay;
        [NotificationXmlAttribute("hint-overlay")]
        public int? Overlay
        {
            get { return _overlay; }
            set
            {
                if (value != null)
                    Element_TileBinding.CheckOverlayValue(value.Value);

                _overlay = value;
            }
        }
    }
}


text:
package com.tech.freak.referencearchitecture.presentation.main;

import javax.inject.Inject;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import butterknife.InjectView;

import com.globant.mvp.BaseActivity;
import com.tech.freak.referencearchitecture.R;
import com.tech.freak.referencearchitecture.data.model.Jokes;
import com.tech.freak.referencearchitecture.presentation.ReferenceArchitectureApp;
import com.tech.freak.referencearchitecture.presentation.main.adapters.DividerItemDecoration;
import com.tech.freak.referencearchitecture.presentation.main.adapters.JokesAdapter;

public class MainActivity extends BaseActivity<MainPresenter>implements MainView {

    @InjectView(R.id.recyclerView)
    RecyclerView recyclerView;

    @InjectView(R.id.textViewError)
    TextView textViewError;

    @InjectView(R.id.progressBar)
    ProgressBar progressBar;

    @Inject
    JokesAdapter jokesAdapter;

    @Inject
    MainPresenter mainPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        mainPresenter.onCreate(savedInstanceState);
    }

    @Override
    protected MainPresenter createPresenter() {
        return mainPresenter;
    }

    @Override
    protected void injectDependencies() {
        MainComponent mainComponent = DaggerMainComponent.builder()
                .appComponent(((ReferenceArchitectureApp) getApplication()).getAppComponent())
                .mainModule(new MainModule(this)).build();
        mainComponent.inject(this);
    }

    @Override
    public void showJokes(Jokes jokes) {
        jokesAdapter.setData(jokes);
        recyclerView.setVisibility(View.VISIBLE);
        textViewError.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showError(Throwable e) {
        recyclerView.setVisibility(View.GONE);
        textViewError.setVisibility(View.VISIBLE);
        progressBar.setVisibility(View.GONE);

        textViewError.setText(R.string.error_msg);
        Log.e(MainActivity.class.getSimpleName(), "Error ", e);
    }

    @Override
    public void showLoading() {
        recyclerView.setVisibility(View.GONE);
        textViewError.setVisibility(View.GONE);
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mainPresenter.onSaveInstanceState(outState);
    }

    private void initViews() {
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        jokesAdapter = new JokesAdapter();
        recyclerView.setAdapter(jokesAdapter);
    }
}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160301224946 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');

        $this->addSql('CREATE SEQUENCE user_timetables_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
        $this->addSql('CREATE SEQUENCE person_services_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
        $this->addSql('CREATE SEQUENCE app_reminders_id_seq INCREMENT BY 1 MINVALUE 1 START 1');
        $this->addSql('CREATE TABLE user_timetables (id INT NOT NULL, user_id INT DEFAULT NULL, office_id INT DEFAULT NULL, dow INT NOT NULL, start_hour INT NOT NULL, start_minute INT NOT NULL, end_hour INT NOT NULL, end_minute INT NOT NULL, PRIMARY KEY(id))');
        $this->addSql('CREATE INDEX IDX_EC6AC92DA76ED395 ON user_timetables (user_id)');
        $this->addSql('CREATE INDEX IDX_EC6AC92DFFA0C224 ON user_timetables (office_id)');
        $this->addSql('CREATE TABLE person_services (id INT NOT NULL, client_id INT DEFAULT NULL, person_id INT DEFAULT NULL, appointment_id INT DEFAULT NULL, service_id INT DEFAULT NULL, date TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, PRIMARY KEY(id))');
        $this->addSql('CREATE INDEX IDX_E774445E19EB6921 ON person_services (client_id)');
        $this->addSql('CREATE INDEX IDX_E774445E217BBB47 ON person_services (person_id)');
        $this->addSql('CREATE INDEX IDX_E774445EE5B533F9 ON person_services (appointment_id)');
        $this->addSql('CREATE INDEX IDX_E774445EED5CA9E6 ON person_services (service_id)');
        $this->addSql('CREATE TABLE app_reminders (id INT NOT NULL, appointment_id INT DEFAULT NULL, person_id INT DEFAULT NULL, date_time TIMESTAMP(0) WITHOUT TIME ZONE NOT NULL, description VARCHAR(255) NOT NULL, PRIMARY KEY(id))');
        $this->addSql('CREATE INDEX IDX_C5FDE6E1E5B533F9 ON app_reminders (appointment_id)');
        $this->addSql('CREATE INDEX IDX_C5FDE6E1217BBB47 ON app_reminders (person_id)');
        $this->addSql('ALTER TABLE user_timetables ADD CONSTRAINT FK_EC6AC92DA76ED395 FOREIGN KEY (user_id) REFERENCES users (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE user_timetables ADD CONSTRAINT FK_EC6AC92DFFA0C224 FOREIGN KEY (office_id) REFERENCES offices (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE person_services ADD CONSTRAINT FK_E774445E19EB6921 FOREIGN KEY (client_id) REFERENCES clients (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE person_services ADD CONSTRAINT FK_E774445E217BBB47 FOREIGN KEY (person_id) REFERENCES persons (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE person_services ADD CONSTRAINT FK_E774445EE5B533F9 FOREIGN KEY (appointment_id) REFERENCES appointments (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE person_services ADD CONSTRAINT FK_E774445EED5CA9E6 FOREIGN KEY (service_id) REFERENCES services (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE app_reminders ADD CONSTRAINT FK_C5FDE6E1E5B533F9 FOREIGN KEY (appointment_id) REFERENCES appointments (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE app_reminders ADD CONSTRAINT FK_C5FDE6E1217BBB47 FOREIGN KEY (person_id) REFERENCES persons (id) NOT DEFERRABLE INITIALLY IMMEDIATE');
        $this->addSql('ALTER TABLE persons ADD is_client BOOLEAN DEFAULT \'false\' NOT NULL');
        $this->addSql('ALTER TABLE persons ADD gender VARCHAR(255) DEFAULT NULL');
        $this->addSql('ALTER TABLE countries ALTER length DROP DEFAULT');
        $this->addSql('ALTER TABLE countries ALTER length SET NOT NULL');
        $this->addSql('ALTER TABLE appointments ADD forwarder VARCHAR(255) DEFAULT NULL');
        $this->addSql('ALTER TABLE appointments ALTER date_time DROP DEFAULT');
        $this->addSql('ALTER TABLE appointments ALTER date_time SET NOT NULL');
        $this->addSql('ALTER TABLE appointments ALTER state DROP DEFAULT');
        $this->addSql('ALTER TABLE appointments ALTER state SET NOT NULL');
        $this->addSql('ALTER TABLE appointments ALTER duration SET NOT NULL');
        $this->addSql('ALTER TABLE users ALTER name SET NOT NULL');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'postgresql', 'Migration can only be executed safely on \'postgresql\'.');

        $this->addSql('CREATE SCHEMA public');
        $this->addSql('DROP SEQUENCE user_timetables_id_seq CASCADE');
        $this->addSql('DROP SEQUENCE person_services_id_seq CASCADE');
        $this->addSql('DROP SEQUENCE app_reminders_id_seq CASCADE');
        $this->addSql('DROP TABLE user_timetables');
        $this->addSql('DROP TABLE person_services');
        $this->addSql('DROP TABLE app_reminders');
        $this->addSql('ALTER TABLE countries ALTER length SET DEFAULT 12');
        $this->addSql('ALTER TABLE countries ALTER length DROP NOT NULL');
        $this->addSql('ALTER TABLE users ALTER name DROP NOT NULL');

        $this->addSql('ALTER TABLE appointments DROP forwarder');
        $this->addSql('ALTER TABLE appointments ALTER date_time SET DEFAULT \'now()\'');
        $this->addSql('ALTER TABLE appointments ALTER date_time DROP NOT NULL');
        $this->addSql('ALTER TABLE appointments ALTER state SET DEFAULT 1');
        $this->addSql('ALTER TABLE appointments ALTER state DROP NOT NULL');
        $this->addSql('ALTER TABLE appointments ALTER duration DROP NOT NULL');
        $this->addSql('ALTER TABLE persons DROP is_client');
        $this->addSql('ALTER TABLE persons DROP gender');
    }
}


text:
//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_AAC_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Audio/File_Aac.h"
#if MEDIAINFO_ADVANCED
    #include "MediaInfo/MediaInfo_Config_MediaInfo.h"
#endif //MEDIAINFO_ADVANCED
#include <cmath>
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Infos
//***************************************************************************

//---------------------------------------------------------------------------
extern const int32u Aac_sampling_frequency[13]=
{96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
 16000, 12000, 11025,  8000,  7350};

//---------------------------------------------------------------------------
const char* Aac_Adts_ID[]=
{
    "MPEG-4",
    "MPEG-2",
};

//---------------------------------------------------------------------------
const char* Aac_Format(int8u ID)
{
    switch (ID)
    {
        case    1 :
        case    2 :
        case    3 :
        case    4 : return "AAC";
        case    5 : return "SBR";
        case    6 : return "AAC Scalable";
        case    7 : return "TwinVQ";
        case    8 : return "CELP";
        case    9 : return "HVXC";
        case   12 : return "TTSI";
        case   13 : return "Main synthetic";
        case   14 : return "Wavetable synthesis";
        case   15 : return "General MIDI";
        case   16 : return "Algorithmic Synthesis and Audio FX";
        case   17 :
        case   19 :
        case   20 : return "ER AAC";
        case   21 : return "ER TwinVQ";
        case   22 : return "ER BSAC";
        case   23 : return "ER AAC LD";
        case   24 : return "ER CELP";
        case   25 : return "ER HVXC";
        case   26 : return "ER HILN";
        case   27 : return "ER Parametric";
        case   28 : return "SSC";
        case   29 : return "ParametricStereo";
        case   32 : return "Layer-1";
        case   33 : return "Layer-2";
        case   34 : return "Layer-3";
        case   35 : return "DST";
        case   36 : return "ALS";
        case   37 :
        case   38 : return "SLS";
        case   39 : return "ER AAC ELD";
        case   40 : return "SMR Simple";
        case   41 : return "SMR Main";
        default   : return "";
    }
}

//---------------------------------------------------------------------------
const char* Aac_Format_Profile(int8u ID)
{
    switch (ID)
    {
        case    1 : return "Main";
        case    2 : return "LC";
        case    3 : return "SSR";
        case    4 : return "LTP";
        case   17 : return "LC";
        case   19 : return "LTP";
        case   37 : return "non-core";
        default   : return "";
    }
}

//---------------------------------------------------------------------------
const char* Aac_audioObjectType(int8u audioObjectType)
{
    switch (audioObjectType)
    {
        case    1 : return "AAC Main";
        case    2 : return "AAC LC";
        case    3 : return "AAC SSR";
        case    4 : return "AAC LTP";
        case    5 : return "SBR";
        case    6 : return "AAC Scalable";
        case    7 : return "TwinVQ";
        case    8 : return "CELP";
        case    9 : return "HVXC";
        case   12 : return "TTSI";
        case   13 : return "Main synthetic";
        case   14 : return "Wavetable synthesis";
        case   15 : return "General MIDI";
        case   16 : return "Algorithmic Synthesis and Audio FX";
        case   17 : return "ER AAC LC";
        case   19 : return "ER AAC LTP";
        case   20 : return "ER AAC Scalable";
        case   21 : return "ER TwinVQ";
        case   22 : return "ER BSAC";
        case   23 : return "ER AAC LD";
        case   24 : return "ER CELP";
        case   25 : return "ER HVXC";
        case   26 : return "ER HILN";
        case   27 : return "ER Parametric";
        case   28 : return "SSC";
        case   29 : return "PS";
        case   31 : return "(escape)";
        case   32 : return "Layer-1";
        case   33 : return "Layer-2";
        case   34 : return "Layer-3";
        case   35 : return "DST";
        case   36 : return "ALS";
        case   37 : return "SLS";
        case   38 : return "SLS non-core";
        case   39 : return "ER AAC ELD";
        case   40 : return "SMR Simple";
        case   41 : return "SMR Main";
        default   : return "";
    }
}

//---------------------------------------------------------------------------
const int8u Aac_Channels[]=
{
    0,
    1,
    2,
    3,
    4,
    5,
    6,
    8,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0,
};

//---------------------------------------------------------------------------
const char* Aac_ChannelConfiguration[]=
{
    "",
    "Front: C",
    "Front: L R",
    "Front: L C R",
    "Front: L C R, Side: C",
    "Front: L C R, Side: L R",
    "Front: L C R, Side: L R, LFE",
    "Front: L C R, Side: L R, Back: L R, LFE",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
};

//---------------------------------------------------------------------------
const char* Aac_ChannelConfiguration2[]=
{
    "",
    "1/0/0",
    "2/0/0",
    "3/0/0",
    "3/1/0",
    "3/2/0",
    "3/2/0.1",
    "3/2/2.1",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
};

//---------------------------------------------------------------------------
const char* Aac_ChannelLayout[]=
{
    "",
    "C",
    "L R",
    "C L R",
    "C L R Cs",
    "C L R Ls Rs",
    "C L R Ls Rs LFE",
    "C L R Ls Rs Lrs Rrs LFE",
};

int8u Aac_AudioSpecificConfig_sampling_frequency_index(const int64s sampling_frequency)
{
    if (sampling_frequency>=92017) return 0;
    if (sampling_frequency>=75132) return 1;
    if (sampling_frequency>=55426) return 2;
    if (sampling_frequency>=46009) return 3;
    if (sampling_frequency>=37566) return 4;
    if (sampling_frequency>=27713) return 5;
    if (sampling_frequency>=23004) return 6;
    if (sampling_frequency>=18783) return 7;
    if (sampling_frequency>=13856) return 8;
    if (sampling_frequency>=11502) return 9;
    if (sampling_frequency>=9391) return 10;
    return 11;
}

//---------------------------------------------------------------------------
void File_Aac::AudioSpecificConfig (size_t End)
{
    //Parsing
    bool    sbrData=false, sbrPresentFlag=false, psData=false, psPresentFlag=false;
    Element_Begin1("AudioSpecificConfig");
    GetAudioObjectType(audioObjectType,                         "audioObjectType");
    Get_S1 (4, sampling_frequency_index,                        "samplingFrequencyIndex"); Param_Info1(Aac_sampling_frequency[sampling_frequency_index]);
    if (sampling_frequency_index==0xF)
    {
        int32u samplingFrequency;
        Get_S3 (24, samplingFrequency,                          "samplingFrequency");
        Frequency_b=samplingFrequency;
        sampling_frequency_index=Aac_AudioSpecificConfig_sampling_frequency_index(Frequency_b);
    }
    else
        Frequency_b=Aac_sampling_frequency[sampling_frequency_index];
    Get_S1 (4, channelConfiguration,                            "channelConfiguration"); Param_Info1(Aac_ChannelConfiguration[channelConfiguration]);
    if (audioObjectType==5 || audioObjectType==29)
    {
        extensionAudioObjectType=5;
        sbrPresentFlag=true;
        if (audioObjectType==29)
            psPresentFlag=true;
        Get_S1 (4, extension_sampling_frequency_index,          "extensionSamplingFrequencyIndex"); Param_Info1(Aac_sampling_frequency[extension_sampling_frequency_index]);
        if (extension_sampling_frequency_index==0xF)
        {
            Get_S3 (24, extension_sampling_frequency,           "extensionSamplingFrequency");
            sampling_frequency_index=Aac_AudioSpecificConfig_sampling_frequency_index(extension_sampling_frequency);
        }
        else
            extension_sampling_frequency=Aac_sampling_frequency[extension_sampling_frequency_index];
        GetAudioObjectType(audioObjectType,                     "audioObjectType");
        if (audioObjectType==22) //BSAC
            Skip_S1(4,                                          "extensionChannelConfiguration");
    }
    else
        extensionAudioObjectType=0x00;

    switch (audioObjectType)
    {
        case 1:
        case 2:
        case 3:
        case 4:
        case 6:
        case 7:
        case 17:
        case 19:
        case 20:
        case 21:
        case 22:
        case 23:
            GASpecificConfig();
            break;
        case 8:
            CelpSpecificConfig();
            break;
        case 9:
            HvxcSpecificConfig();
            break;
        case 12:
            TTSSpecificConfig();
            break;
        //~ case 13:
        //~ case 14:
        //~ case 15:
        //~ case 16:
            //~ StructuredAudioSpecificConfig();
            //~ break;
        case 24:
            ErrorResilientCelpSpecificConfig();
            break;
        case 25:
            ErrorResilientHvxcSpecificConfig();
            break;
        case 26:
        case 27:
            ParametricSpecificConfig();
            break;
        case 28:
            SSCSpecificConfig();
            break;
        //~ case 30:
            //~ Skip_S1(1,                                          "sacPayloadEmbedding");
            //~ SpatialSpecificConfig(); //ISO/IEC 23003-1
            //~ break;
        case 32:
        case 33:
        case 34:
            MPEG_1_2_SpecificConfig();
            break;
        case 35:
            DSTSpecificConfig();
            break;
        case 36:
            Skip_S1(5,                                          "fillBits");
            ALSSpecificConfig();
            break;
        case 37:
        case 38:
            SLSSpecificConfig();
            break;
        case 39:
            ELDSpecificConfig();
            break;
        //~ case 40:
        //~ case 41:
            //~ SymbolicMusicSpecificConfig(); //ISO/IEC 14496-23
            //~ break;
        default:
            Element_Begin1("not implemented part");
            Skip_BS(Data_BS_Remain()-((End==(size_t)-1)?0:End), "(Not implemented)");
            Element_End0();
            FILLING_BEGIN()
                if (Mode==File_Aac::Mode_ADIF || Mode==File_Aac::Mode_ADTS)
                    File__Tags_Helper::Finish();
                else if (Mode==Mode_AudioSpecificConfig)
                    File__Analyze::Finish();
                Frame_Count=(size_t)-1; //Forcing not to parse following data anymore (if ParseSpeed==1)
            FILLING_END()
            return;
    }

    switch (audioObjectType)
    {
        case 17:
        case 19:
        case 20:
        case 21:
        case 22:
        case 23:
        case 24:
        case 25:
        case 26:
        case 27:
        case 39:
            int8u epConfig;
            Get_S1(2,epConfig,                                  "epConfig");
            if ( epConfig == 2 || epConfig == 3 )
                ErrorProtectionSpecificConfig();
            if ( epConfig == 3 )
            {
                bool directMapping;
                Get_SB(directMapping,                           "directMapping");
                if ( ! directMapping )
                {
                    Element_Begin1("not implemented part");
                    Skip_BS(Data_BS_Remain()-((End==(size_t)-1)?0:End), "(Not implemented)");
                    Element_End0();
                    if (Mode==File_Aac::Mode_ADIF || Mode==File_Aac::Mode_ADTS)
                        File__Tags_Helper::Finish();
                    else
                    {
                        if (Mode==Mode_LATM)
                            File__Analyze::Accept();
                        File__Analyze::Finish();
                    }
                    Frame_Count=(size_t)-1; //Forcing not to parse following data anymore (if ParseSpeed==1)
                    return;
                }
            }
        default : ;
    }

    if (extensionAudioObjectType!=5 && End!=(size_t)-1 && Data_BS_Remain()>=End+16)
    {
        int16u syncExtensionType;
        Get_S2(11,syncExtensionType,                            "syncExtensionType");
        if (syncExtensionType == 0x2b7)
        {
            sbrData=true;
            GetAudioObjectType(extensionAudioObjectType,        "extensionAudioObjectType");
            if (extensionAudioObjectType==5 )
            {
                Get_SB(sbrPresentFlag,                          "sbrPresentFlag");
                if (sbrPresentFlag)
                {
                    Get_S1 (4, extension_sampling_frequency_index, "extensionSamplingFrequencyIndex"); Param_Info1(Aac_sampling_frequency[extension_sampling_frequency_index]);
                    if (extension_sampling_frequency_index==0xF)
                    {
                        Get_S3 (24, extension_sampling_frequency, "extensionSamplingFrequency");
                        extension_sampling_frequency_index=Aac_AudioSpecificConfig_sampling_frequency_index(extension_sampling_frequency);
                    }
                    else
                        extension_sampling_frequency=Aac_sampling_frequency[extension_sampling_frequency_index];
                    if (End!=(size_t)-1 && Data_BS_Remain()>=End+12)
                    {
                        int16u syncExtensionType;
                        Get_S2(11,syncExtensionType,            "syncExtensionType");
                        if (syncExtensionType == 0x548)
                        {
                            psData=true;
                            Get_SB (psPresentFlag,              "psPresentFlag");
                        }
                    }
                }
            }
            if ( extensionAudioObjectType == 22 )
            {
                Get_SB(sbrPresentFlag,                          "sbrPresentFlag");
                if (sbrPresentFlag)
                {
                    Get_S1 (4, extension_sampling_frequency_index, "extensionSamplingFrequencyIndex"); Param_Info1(Aac_sampling_frequency[extension_sampling_frequency_index]);
                    if (extension_sampling_frequency_index==0xF)
                    {
                        Get_S3 (24, extension_sampling_frequency, "extensionSamplingFrequency");
                        extension_sampling_frequency_index=Aac_AudioSpecificConfig_sampling_frequency_index(extension_sampling_frequency);
                    }
                    else
                        extension_sampling_frequency=Aac_sampling_frequency[extension_sampling_frequency_index];
                }
                Skip_S1(4,                                      "extensionChannelConfiguration");
            }
        }
    }
    Element_End0();
    if (Data_BS_Remain()>End)
    {
        int8u LastByte=0xFF;
        if (Data_BS_Remain()-End<8)
            Peek_S1((int8u)(Data_BS_Remain()-End), LastByte);
        Skip_BS(Data_BS_Remain()-End,                           LastByte?"Unknown":"Padding");
    }

    FILLING_BEGIN();
        AudioSpecificConfig_OutOfBand (Frequency_b, audioObjectType, sbrData, psData, sbrPresentFlag, psPresentFlag);
    FILLING_END();
}

//---------------------------------------------------------------------------
void File_Aac::AudioSpecificConfig_OutOfBand (int64s sampling_frequency_, int8u audioObjectType_, bool sbrData, bool psData, bool sbrPresentFlag, bool psPresentFlag)
{
    if (!Frequency_b && sampling_frequency_) //Only if not yet set
    {
        Frequency_b=sampling_frequency_;
        sampling_frequency_index=Aac_AudioSpecificConfig_sampling_frequency_index((int32u)Frequency_b);
    }

    if (audioObjectType_==(int8u)-1)
    {
        if (audioObjectType==(int8u)-1)
            return; //All data is not yet available
        if (Infos.find("Format_Settings_SBR")!=Infos.end())
        {
            sbrData=true;
            sbrPresentFlag=Infos["Format_Settings_SBR"].find(__T("Yes"))!=string::npos;
        }
        else
        {
            sbrData=false;
            sbrPresentFlag=false;
        }
        if (Infos.find("Format_Settings_PS")!=Infos.end())
        {
            psData=true;
            psPresentFlag=Infos["Format_Settings_PS"].find(__T("Yes"))!=string::npos;
        }
        else
        {
            psData=false;
            psPresentFlag=false;
        }
    }
    else
        audioObjectType=audioObjectType_;

    if (Frequency_b)
        Infos["SamplingRate"].From_Number(Frequency_b);
    Infos["Format"].From_Local(Aac_Format(audioObjectType));
    Infos["Format_Profile"].From_Local(Aac_Format_Profile(audioObjectType));
    Infos["Codec"].From_Local(Aac_audioObjectType(audioObjectType));
    if (channelConfiguration && channelConfiguration<8)
    {
        Infos["Channel(s)"].From_Number(Aac_Channels[channelConfiguration]);
        Infos["ChannelPositions"].From_Local(Aac_ChannelConfiguration[channelConfiguration]);
        Infos["ChannelPositions/String2"].From_Local(Aac_ChannelConfiguration2[channelConfiguration]);
        Infos["ChannelLayout"].From_Local(Aac_ChannelLayout[channelConfiguration]);
    }

    if (sbrPresentFlag || !Infos["Format_Settings_SBR"].empty())
    {
        Infos["Format_Profile"]=__T("HE-AAC");
        Ztring SamplingRate_Previous=Infos["SamplingRate"];
        int32u SamplingRate=(extension_sampling_frequency_index==(int8u)-1)?(((int32u)Frequency_b)*2):extension_sampling_frequency;
        if (SamplingRate)
        {
            Infos["SamplingRate"].From_Number(SamplingRate, 10);
            if (MediaInfoLib::Config.LegacyStreamDisplay_Get())
            {
                Infos["Format_Profile"]+=__T(" / LC");
                Infos["SamplingRate"]+=__T(" / ")+SamplingRate_Previous;
            }
        }
        Infos["Format_Settings_SBR"]=__T("Yes (Implicit)");
        Infos["Codec"]=Ztring().From_Local(Aac_audioObjectType(audioObjectType))+__T("-SBR");
    }
    else if (sbrData)
        Infos["Format_Settings_SBR"]=__T("No (Explicit)");

    if (psPresentFlag || !Infos["Format_Settings_PS"].empty())
    {
        Infos["Format_Profile"]=__T("HE-AACv2");
        Ztring Channels=Infos["Channel(s)"];
        Ztring ChannelPositions=Infos["ChannelPositions"];
        Ztring SamplingRate_Previous=Infos["SamplingRate"];
        Infos["Channel(s)"]=__T("2");
        Infos["ChannelPositions"]=__T("Front: L R");
        if (MediaInfoLib::Config.LegacyStreamDisplay_Get())
        {
            Infos["Format_Profile"]+=__T(" / HE-AAC / LC");
            Infos["Channel(s)"]+=__T(" / ")+Channels+__T(" / ")+Channels;
            Infos["ChannelPositions"]+=__T(" / ")+ChannelPositions+__T(" / ")+ChannelPositions;
            int32u SamplingRate=(extension_sampling_frequency_index==(int8u)-1)?(((int32u)Frequency_b)*2):extension_sampling_frequency;
            if (SamplingRate)
                Infos["SamplingRate"]=Ztring().From_Number(SamplingRate, 10)+__T(" / ")+SamplingRate_Previous;
        }
        Infos["Format_Settings_PS"]=__T("Yes (Implicit)");
        if (StreamPos_Last!=(size_t)-1)
        {
            Ztring Codec=Retrieve(Stream_Audio, StreamPos_Last, Audio_Codec);
            Infos["Codec"]=Ztring().From_Local(Aac_audioObjectType(audioObjectType))+__T("-SBR-PS");
        }
    }
    else if (psData)
        Infos["Format_Settings_PS"]=__T("No (Explicit)");
}

//---------------------------------------------------------------------------
void File_Aac::GetAudioObjectType(int8u &ObjectType, const char* Name)
{
    Element_Begin1(Name);
    Get_S1(5, ObjectType,                                       "audioObjectType");
    if (ObjectType==31)
    {
        Get_S1(6, ObjectType,                                   "audioObjectTypeExt");
        ObjectType+=32;
    }
    Element_Info1(ObjectType); Element_Info1(Aac_Format_Profile(ObjectType));
    Element_End0();
}

//***************************************************************************
// Elements - Multiplex layer
//***************************************************************************

//---------------------------------------------------------------------------
void File_Aac::AudioMuxElement()
{
    Element_Begin1("AudioMuxElement");
    if (muxConfigPresent)
    {
        bool useSameStreamMux;
        Get_SB (useSameStreamMux,                               "useSameStreamMux");
        if (!useSameStreamMux)
            StreamMuxConfig();
    }
    if (sampling_frequency_index==(int8u)-1) //No previous config
    {
        CanFill=false;
        Skip_BS(Data_BS_Remain(),                               "(Waiting for configuration)");
        return;
    }
    if (audioMuxVersionA==0)
    {
        for (int8u i=0; i<=numSubFrames; i++)
        {
            PayloadLengthInfo();
            PayloadMux();
        }
        if (otherDataPresent)
        {
            for(int32u i=0; i<otherDataLenBits; i++)
                Skip_SB(                                        "otherDataBit");
        }
    }
    else
    {
        Element_Begin1("(not implemented)");
        Skip_BS(Data_BS_Remain(),                               "(not implemented)");
        Element_End0();
    }
    if (Data_BS_Remain()%8)
        Skip_S1(Data_BS_Remain()%8,                             "byte_alignment");
    Element_End0();
}

//---------------------------------------------------------------------------
void File_Aac::StreamMuxConfig()
{
    Element_Begin1("StreamMuxConfig");

    bool audioMuxVersion;
    Get_SB (audioMuxVersion,                                    "audioMuxVersion");
    if (audioMuxVersion)
        Get_SB (audioMuxVersionA,                               "audioMuxVersionA");
    else
        audioMuxVersionA=false;

    if (!audioMuxVersionA)
    {
        if (audioMuxVersion==1)
        {
            Element_Begin1("(not implemented)");
            Skip_BS(Data_BS_Remain(),                               "(not implemented)");
            Element_End0();
            //taraBufferFullness=LatmGetValue();
        }

        int8u streamCnt = 0;
        bool useSameConfig;

        Get_SB (allStreamsSameTimeFraming,                      "allStreamsSameTimeFraming");
        Get_S1 (6, numSubFrames,                                "numSubFrames");
        Get_S1 (4, numProgram,                                  "numProgram");

        for (int8u prog=0; prog<=numProgram; prog++)
        {
            Get_S1(3,numLayer,                                  "numLayer");
            for (int8u lay=0; lay<=numLayer; lay++)
            {
                progSIndx[streamCnt]=prog;
                laySIndx[streamCnt]=lay;
                streamID[prog][lay]=streamCnt++;
                if (prog==0 && lay==0)
                    useSameConfig=0;
                else
                    Get_SB(useSameConfig,                       "useSameConfig");

                if (!useSameConfig)
                {
                    if (audioMuxVersion==0)
                        AudioSpecificConfig();
                    else
                    {
                        int ascLen=LatmGetValue();
                        AudioSpecificConfig(Data_BS_Remain()-ascLen);
                    }
                }

                Get_S1(3,frameLengthType[streamID[prog][lay]],  "frameLengthType[streamID[prog][lay]]");
                switch(frameLengthType[streamID[prog][lay]])
                {
                    case 0 :
                            Skip_S1(8,                          "latmBufferFullness[streamID[prog][lay]]");
                            if(!allStreamsSameTimeFraming)
                            {
                                Element_Begin1("(not implemented)");
                                Skip_BS(Data_BS_Remain(),       "(not implemented)");
                                Element_End0();
                            }
                            //~ if ((!allStreamsSameTimeFraming) &&
                            //~ (AudioObjectType[lay] == 6 || AudioObjectType[lay] == 20) &&
                            //~ (AudioObjectType[lay-1] == 8 || AudioObjectType[lay-1] == 24))
                            //~ {
                                //~ Skip_S1(6,                          "coreFrameOffset");
                            //~ }
                            break;
                    case 1 :
                            Get_S2(9,frameLength[streamID[prog][lay]],"frameLength[streamID[prog][lay]]");
                            break;
                    case 3 :
                    case 4 :
                    case 5 :
                            Skip_S1(6,                          "CELPframeLengthTableIndex[streamID[prog][lay]]");
                            break;
                    case 6 :
                    case 7 :
                            Skip_S1(1,                          "HVXCframeLengthTableIndex[streamID[prog][lay]]");
                            break;
                    default :
                            Element_Begin1("(not implemented)");
                            Skip_BS(Data_BS_Remain(),       "(not implemented)");
                            Element_End0();
                }
            }
        }
        bool crcCheckPresent;
        Get_SB (otherDataPresent,                               "otherDataPresent");
        if (otherDataPresent)
        {
            if (audioMuxVersion==1)
                otherDataLenBits=LatmGetValue();
            else
            {
                otherDataLenBits=0;
                bool otherDataLenEsc;
                do
                {
                    int8u otherDataLenTmp;
                    otherDataLenBits<<=8;
                    Get_SB(   otherDataLenEsc,                   "otherDataLenEsc");
                    Get_S1(8, otherDataLenTmp,                   "otherDataLenTmp");
                    otherDataLenBits+=otherDataLenTmp;
                }
                while (otherDataLenEsc);
            }
        }
        Get_SB(crcCheckPresent,                                 "crcCheckPresent");
        if(crcCheckPresent)
            Skip_S1(8,                                          "crcCheckSum");
    }
    else
    {
        Element_Begin1("(not implemented)");
        Skip_BS(Data_BS_Remain(),                               "(not implemented)");
        Element_End0();
    }
    Element_End0();

    FILLING_BEGIN();
        CanFill=true;
    FILLING_END();
}

//---------------------------------------------------------------------------
int32u File_Aac::LatmGetValue()
{
    Element_Begin1("LatmGetValue");
    int8u valueTmp, bytesForValue;
    Get_S1(2, bytesForValue,                                    "bytesForValue");
    int32u value=0;
    for (int8u i=0; i<=bytesForValue; i++)
    {
        value<<=8;
        Get_S1(8, valueTmp,                                     "valueTmp");
        value+=valueTmp;
    }
    Element_End0();
    return value;
}

//---------------------------------------------------------------------------
void File_Aac::PayloadLengthInfo()
{
    Element_Begin1("PayloadLengthInfo");
    int8u tmp;
    if (allStreamsSameTimeFraming)
    {
        for (int8u prog=0; prog<=numProgram; prog++)
        {
            for (int8u lay=0; lay<=numLayer; lay++)
            {
                if (frameLengthType[streamID[prog][lay]]==0)
                {
                    MuxSlotLengthBytes[streamID[prog][lay]]=0;
                    do
                    {
                        Get_S1(8, tmp,                          "tmp");
                        MuxSlotLengthBytes[streamID[prog][lay]]+=tmp;
                    }
                    while(tmp==255);
                }
                else if (frameLengthType[streamID[prog][lay]]==3
                      || frameLengthType[streamID[prog][lay]]==5
                      || frameLengthType[streamID[prog][lay]]==7)
                {
                    Skip_S1(2,                                  "MuxSlotLengthCoded[streamID[prog][lay]]");
                }
            }
        }
    }
    else
    {
        int8u streamIndx;
        int8u prog, lay;
        Get_S1(4, numChunk,                                     "numChunk");
        for (int chunkCnt=0; chunkCnt<=numChunk; chunkCnt++)
        {
            Get_S1(4,streamIndx,                                "streamIndx");
            prog=progCIndx[chunkCnt]=progSIndx[streamIndx];
            lay=layCIndx[chunkCnt]=laySIndx[streamIndx];
            if (frameLengthType[streamID[prog][lay]]==0)
            {
                MuxSlotLengthBytes[streamID[prog][lay]]=0;
                do
                {
                    Get_S1(8, tmp,                              "tmp");
                    MuxSlotLengthBytes[streamID[prog][lay]]+=tmp;
                }
                while(tmp==255);
                Skip_SB(                                        "AuEndFlag[streamID[prog][lay]]");
            }
            else if (frameLengthType[streamID[prog][lay]]==3
                  || frameLengthType[streamID[prog][lay]]==5
                  || frameLengthType[streamID[prog][lay]]==7)
            {
                Skip_S1(2,                                      "MuxSlotLengthCoded[streamID[prog][lay]]");
            }
        }
    }
    Element_End0();
}

//---------------------------------------------------------------------------
void File_Aac::PayloadMux()
{
    Element_Begin1("PayloadMux");
    if (allStreamsSameTimeFraming)
    {
        for (int8u prog=0; prog<=numProgram; prog++)
            for (int8u lay=0; lay<=numLayer; lay++)
            {
                switch(frameLengthType[streamID[prog][lay]])
                {
                    case 0 :
                            if (CA_system_ID_MustSkipSlices)
                            {
                                //Encryption management
                                Skip_BS(8*MuxSlotLengthBytes[streamID[prog][lay]], "Encrypted payload[streamID[prog][lay]]");
                                Frame_Count_Valid=0;
                            }
                            else
                                raw_data_block();
                            break;
                    case 1 :
                            Skip_BS(8 * (frameLength[streamID[prog][lay]] + 20),"payload[streamID[prog][lay]]");
                            break;
                    default:
                            Element_Begin1("(not implemented)");
                            Skip_BS(Data_BS_Remain(),           "(not implemented)");
                            Element_End0();
                }
            }
    }
    else
    {
        for (int8u chunkCnt=0; chunkCnt<=numChunk; chunkCnt++)
        {
            int8u prog=progCIndx[chunkCnt];
            int8u lay=layCIndx[chunkCnt];
            switch(frameLengthType[streamID[prog][lay]])
            {
                case 0 :
                        raw_data_block(); //Skip_BS(MuxSlotLengthBytes[streamID[prog][lay]], "payload[streamID[prog][lay]]");
                        break;
                case 1 :
                        Skip_BS(8*(frameLength[streamID[prog][lay]]+20), "payload[streamID[prog][lay]]");
                        break;
                default:
                        Element_Begin1("not implemented");
                        Element_End0();
            }
        }
    }
    Element_End0();
}

//***************************************************************************
// Elements - Error protection
//***************************************************************************

//---------------------------------------------------------------------------
void File_Aac::ErrorProtectionSpecificConfig()
{
    Element_Begin1("ErrorProtectionSpecificConfig");
    int8u number_of_predefined_set,number_of_concatenated_frame,interleave_type;
    Get_S1(8,number_of_predefined_set,                          "number_of_predefined_set");
    Get_S1(2,interleave_type,                                   "interleave_type");
    Skip_S1(3,                                                  "bit_stuffing");
    Get_S1(3,number_of_concatenated_frame,                      "number_of_concatenated_frame");
    for (int8u i = 0; i < number_of_predefined_set; i++ )
    {
        int8u number_of_class;
        Get_S1(6,number_of_class,                               "number_of_class[i]");
        for (int8u j = 0; j < number_of_class; j++)
        {
            bool length_escape,fec_type,rate_escape,crclen_escape;
            Get_SB(length_escape,                               "length_escape[i][j]");
            Get_SB(rate_escape,                                 "rate_escape[i][j]");
            Get_SB(crclen_escape,                               "crclen_escape[i][j]");
            if (number_of_concatenated_frame != 1)
                Skip_SB(                                        "concatenate_flag[i][j]");
            Get_SB(fec_type,                                    "fec_type[i][j]");
            if(!fec_type)
                Skip_SB(                                        "termination_switch[i][j]");
            if (interleave_type == 2)
                Skip_S1(2,                                      "interleave_switch[i][j]");
            Skip_SB(                                            "class_optional");
            if (length_escape)
            {
                /* ESC */
                Skip_S1(4,                                      "number_of_bits_for_length[i][j]");
            }
            else
            {
                Skip_S2(16,                                     "class_length[i][j]");
            }
            if (!rate_escape)
            { /* not ESC */
                if(fec_type)
                {
                    Skip_S1(7,                                  "class_rate[i][j]");
                }
                else
                {
                    Skip_S1(5,                                  "class_rate[i][j]");
                }
            }
            if (!crclen_escape)
            {
            /* not ESC */
            Skip_S1(5,                                          "class_crclen[i][j]");
            }
        }
        bool class_reordered_output;
        Get_SB(class_reordered_output,                          "class_reordered_output");
        if ( class_reordered_output )
        {
            for (int j = 0; j < number_of_class; j++ )
            {
                Skip_S1(6,                                      "class_output_order[i][j]");
            }
        }
    }
    bool header_protection;
    Get_SB(header_protection,                                   "header_protection");
    if (header_protection)
    {
        Skip_S1(5,                                              "header_rate");
        Skip_S1(5,                                              "header_crclen");
    }
    Element_End0();
}

//***************************************************************************
// Elements - MPEG-2 AAC Audio_Data_Interchange_Format, ADIF
//***************************************************************************

//---------------------------------------------------------------------------
void File_Aac::adif_header()
{
    //Parsing
    int32u bitrate;
    int8u  num_program_config_elements;
    bool   bitstream_type;
    Skip_C4(                                                    "adif_id");
    BS_Begin();
    TEST_SB_SKIP(                                               "copyright_id_present");
        Skip_S4(32,                                             "copyright_id");
        Skip_S4(32,                                             "copyright_id");
        Skip_S4( 8,                                             "copyright_id");
    TEST_SB_END();
    Skip_SB(                                                    "original_copy");
    Skip_SB(                                                    "home");
    Get_SB (    bitstream_type,                                 "bitstream_type"); Param_Info1(bitstream_type?"VBR":"CBR");
    Get_S3 (23, bitrate,                                        "bitrate");
    Get_S1 ( 4, num_program_config_elements,                    "num_program_config_elements");
    if (!bitstream_type)
        Skip_S3(20,                                             "adif_buffer_fullness");
    for (int8u Pos=0; Pos<num_program_config_elements+1; Pos++)
        program_config_element();
    BS_End();

    FILLING_BEGIN();
        Fill(Stream_General, 0, General_Format, "ADIF", Unlimited, true, true);
        Fill(Stream_General, 0, General_HeaderSize, Element_Size);
        Fill(Stream_General, 0, General_OverallBitRate_Mode, bitstream_type?"VBR":"CBR");

        for (size_t StreamPos=0; StreamPos<Count_Get(Stream_Audio); StreamPos++)
            Fill(Stream_Audio, StreamPos, Audio_MuxingMode, "ADIF");
        if (num_program_config_elements==0) //Easy to fill only if 1 audio stream
        {
            Infos["BitRate_Mode"].From_Local(bitstream_type?"VBR":"CBR");
            if (bitrate>0)
                Infos[bitstream_type?"BitRate_Maximum":"BitRate"].From_Number(bitrate);
        }

        //No more need data
        File__Tags_Helper::Finish("ADIF");
    FILLING_END();
}

//***************************************************************************
// Elements - Audio_Data_Transport_Stream frame, ADTS
//***************************************************************************

//---------------------------------------------------------------------------
void File_Aac::adts_frame()
{
    //Parsing
    adts_fixed_header();
    adts_variable_header();

    //Encryption management
    if (CA_system_ID_MustSkipSlices)
    {
        //Is not decodable
        BS_End();
        Skip_XX(Element_Size-Element_Offset,                    "Encrypted data");
        Frame_Count_Valid=0;
        return;
    }

    if (num_raw_data_blocks==0)
    {
        if (!protection_absent)
        {
            Element_Begin1("adts_error_check");
                Skip_S2(16,                                     "crc_check");
            Element_End0();
        }
        raw_data_block();
    }
    else
    {
        Element_Begin1("adts_header_error_check");
            if (!protection_absent)
                for (int i=1; i<=num_raw_data_blocks; i++)
                    Skip_S2(16,                                 "raw_data_block_position(i)");
            Skip_S2(16,                                         "crc_check");
        Element_End0();

        for(int i=0; i<=num_raw_data_blocks; i++)
        {
            raw_data_block();
            if (!protection_absent)
            {
                Element_Begin1("adts_raw_data_block_error_check");
                    Skip_BS(16,                                 "crc_check");
                Element_End0();
            }
        }
    }
}

//---------------------------------------------------------------------------
void File_Aac::adts_fixed_header()
{
    //Parsing
    bool    id;
    Element_Begin1("adts_fixed_header");
    Skip_BS(12,                                                 "syncword");
    Get_SB (    id,                                             "id"); Param_Info1(Aac_Adts_ID[id]);
    Skip_BS( 2,                                                 "layer");
    Get_SB (    protection_absent,                              "protection_absent");
    Get_S1 ( 2, audioObjectType,                                "profile_ObjectType"); audioObjectType++; Param_Info1(Aac_audioObjectType(audioObjectType));
    Get_S1 ( 4, sampling_frequency_index,                       "sampling_frequency_index"); Param_Info2(Aac_sampling_frequency[sampling_frequency_index], " Hz");
    Frequency_b=Aac_sampling_frequency[sampling_frequency_index];
    Skip_SB(                                                    "private");
    Get_S1 ( 3, channelConfiguration,                           "channel_configuration");
    Skip_SB(                                                    "original");
    Skip_SB(                                                    "home");
    Element_End0();

    FILLING_BEGIN();
        if (Infos["Format"].empty())
        {
            Infos_General["Format"].From_Local("ADTS");

            Infos["Format"].From_Local("AAC");
            Infos["Format_Version"].From_Local(id?"Version 2":"Version 4");
            Infos["Format_Profile"].From_Local(Aac_Format_Profile(audioObjectType));
            Infos["Codec"].From_Local(Aac_audioObjectType(audioObjectType));
            if (Aac_sampling_frequency[sampling_frequency_index])
                Infos["SamplingRate"].From_Number(Aac_sampling_frequency[sampling_frequency_index]);
            Infos["Channel(s)"].From_Number(channelConfiguration);
            Infos["ChannelPositions"].From_Local(Aac_ChannelConfiguration[channelConfiguration]);
            Infos["ChannelPositions/String2"].From_Local(Aac_ChannelConfiguration2[channelConfiguration]);
            Infos["ChannelLayout"].From_Local(Aac_ChannelLayout[channelConfiguration]);
            if (IsSub)
                Infos["MuxingMode"].From_Local("ADTS");
        }
    FILLING_END();
}

//---------------------------------------------------------------------------
void File_Aac::adts_variable_header()
{
    //Parsing
    int16u  aac_frame_length, adts_buffer_fullness;
    Element_Begin1("adts_variable_header");
    Skip_SB(                                                    "copyright_id");
    Skip_SB(                                                    "copyright_id_start");
    Get_S2 (13, aac_frame_length,                               "aac_frame_length");
    Get_S2 (11, adts_buffer_fullness,                           "adts_buffer_fullness"); Param_Info1(adts_buffer_fullness==0x7FF?"VBR":"CBR");
    Get_S1 ( 2, num_raw_data_blocks,                            "num_raw_data_blocks");
    Element_End0();

    FILLING_BEGIN();
        if (adts_buffer_fullness==0x7FF)
            adts_buffer_fullness_Is7FF=true;
        #if MEDIAINFO_ADVANCED
            aac_frame_length_Total+=aac_frame_length;
        #endif //MEDIAINFO_ADVANCED
    FILLING_END();
}

//***************************************************************************
// C++
//***************************************************************************

} //NameSpace

#endif //MEDIAINFO_AAC_YES


text:
Old code.

StatsDBundle
~~~~~~~~~~~~~~

This is a simple bundle that creates a statsd service that you can use to send counters via statsd to graphite.

It is based on the example statsd client found in the statd package: https://github.com/etsy/statsd

Statsd
~~~~~~
Statsd is a network daemon for aggregating statistics (counters and timers), rolling them up, then sending them to [graphite][graphite].

([Etsy][etsy]) [blogged][blog post] about how it works and why they created it

Instalation
-----------

Add to deps::

    [SMStatsDBundle]
        git=git://github.com:tarjei/StatsDBundle.git
        target=/bundles/SM/StatsDBundle

Then register the bundle with your kernel::

    // app/AppKernel.php
    // in AppKernel::registerBundles()
    $bundles = array(
        // ...
        new SM\StatsDBundle\SMStatsDBundle(),
        // ...
    );

Make sure that you also register the namespaces with the autoloader::

    // app/autoload.php
    $loader->registerNamespaces(array(
        // ...
        'SM\\StatsDBundle' => __DIR__ . '/../vendor/bundles',
    ));

Configuration
-------------

The plugin expects statsd to be running localy

In your prod/dev environment::

    # app/config/config.yml
    statsd:
        host:
        port:

Defaults::

    statsd:
        host: localhost
        port: 8125
        noop: false

The noop option is if you want the client to be called but not send a signal or connect to statsd.

Usage
-----

Sample usage::

    // MyController.com
    $stats = $this->get('statsd');
    $stats->increment("users");
    $stats->timing("querytime", $time)

For more info see the StatsD.php file.

TODO
----
* Add loggingservice into the mix
* Consider how we should handle empty stats
* better example

Contributors
-----------------
In lieu of a list of contributors, check out the commit history for the project.

[graphite]: http://graphite.wikidot.com
[etsy]: http://www.etsy.com
[blog post]: http://codeascraft.etsy.com/2011/02/15/measure-anything-measure-everything/
[node]: http://nodejs.org
[udp]: http://enwp.org/udp


text:
package org.spongepowered.api.data.manipulator.immutable.entity;

import org.spongepowered.api.data.manipulator.ImmutableDataManipulator;
import org.spongepowered.api.data.manipulator.mutable.entity.PickupDelayData;
import org.spongepowered.api.data.value.immutable.ImmutableBoundedValue;
import org.spongepowered.api.data.value.immutable.ImmutableValue;
import org.spongepowered.api.entity.Item;

/**
 * An {@link ImmutableDataManipulator} for handling the "pickup delay" of an
 * {@link Item}.
 */
public interface ImmutablePickupDelayData extends ImmutableDataManipulator<ImmutablePickupDelayData, PickupDelayData> {

    /**
     * Gets the {@link ImmutableBoundedValue} for the "pickup delay".
     *
     * @return The immutable bounded value for the "pickup delay"
     */
    ImmutableBoundedValue<Integer> delay();

    /**
     * Gets the {@link ImmutableValue} for the "is infinite" state of
     * the pickup delay.
     *
     * @return The value for the "is infinite" state
     */
    ImmutableValue<Boolean> infinite();

}


text:
var QUnit = require( "qunitjs" ),
	_ = require( "lodash" );

QUnit.load();
QUnit.config.requireExpects = true;
QUnit.config.testTimeout = 3000000;

module.exports = function( callbacks ) {
	[ "begin", "done", "log", "moduleDone", "moduleStart", "testDone", "testStart" ]
		.forEach( function( item ) {
			if ( callbacks[ item ] ) {
				QUnit.config.callbacks[ item ].push( _.bind( callbacks[ item ], QUnit ) );
			}
		} );

	return QUnit;
};


text:
/**
 * A client to Routes API
 *
 *
The interfaces provided are listed below, along with usage samples.
 *
 *
======================= RoutesClient =======================
 *
 *
Service Description: The Routes API.
 *
 *
Sample for RoutesClient:
 *
 *
{@code
 * // This snippet has been automatically generated and should be regarded as a code template only.
 * // It will require modifications to work:
 * // - It may require correct/in-range values for request initialization.
 * // - It may require specifying regional endpoints when creating the service client as shown in
 * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
 * try (RoutesClient routesClient = RoutesClient.create()) {
 *   ComputeRoutesRequest request =
 *       ComputeRoutesRequest.newBuilder()
 *           .setOrigin(Waypoint.newBuilder().build())
 *           .setDestination(Waypoint.newBuilder().build())
 *           .addAllIntermediates(new ArrayList<Waypoint>())
 *           .setTravelMode(RouteTravelMode.forNumber(0))
 *           .setRoutingPreference(RoutingPreference.forNumber(0))
 *           .setPolylineQuality(PolylineQuality.forNumber(0))
 *           .setPolylineEncoding(PolylineEncoding.forNumber(0))
 *           .setDepartureTime(Timestamp.newBuilder().build())
 *           .setComputeAlternativeRoutes(true)
 *           .setRouteModifiers(RouteModifiers.newBuilder().build())
 *           .setLanguageCode("languageCode-2092349083")
 *           .setUnits(Units.forNumber(0))
 *           .addAllRequestedReferenceRoutes(new ArrayList<ComputeRoutesRequest.ReferenceRoute>())
 *           .build();
 *   ComputeRoutesResponse response = routesClient.computeRoutes(request);
 * }
 * }

 */
@Generated("by gapic-generator-java")
package com.google.maps.routing.v2;

import javax.annotation.Generated;


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('info_transportation', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Data',
            fields=[
                ('id', models.AutoField(verbose_name='ID',
                                        serialize=False, auto_created=True, primary_key=True)),
                ('time', models.DateTimeField()),
                ('line', models.ForeignKey(to='info_transportation.Line')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
<!-- Auto-generated by x/build/update-readmes.go -->

[![Go Reference](https://pkg.go.dev/badge/golang.org/x/build/internal/gomote.svg)](https://pkg.go.dev/golang.org/x/build/internal/gomote)

# golang.org/x/build/internal/gomote

Package gomote contains all of the necessary components to implement and use the gomote functionality.


text:
package edu.purdue.app.dining;

import java.util.List;

import edu.purdue.app.R;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class MealListAdapter extends ArrayAdapter{
	private Context mContext;
	private int id;
	private List<Meal> mMeal;

	public MealListAdapter(Context context, int resource, List<Meal> meal){
		super(context, resource, meal);
		mContext = context;
		id = resource;
		mMeal = meal;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View row = convertView;
		MealXML temp = null;
		if ( row == null ){
			LayoutInflater inflater = LayoutInflater.from(mContext);
			row = inflater.inflate(R.layout.meal_list_adapter, parent, false);
			temp.mealTime = (TextView) row.findViewById(R.id.mealItem);
			temp = new MealXML();
			row.setTag(temp);
		} else {
			temp = (MealXML) row.getTag();
		}
		temp.mealTime.setText("This is the food!");
		return super.getView(position, convertView, parent);
	}

	class MealXML {
		TextView mealTime;
	}

}


text:
import json

from tests.integration.integration_test_case import IntegrationTestCase

class TestQuestionnaireCsrf(IntegrationTestCase):

    def test_given_on_interstitial_page_when_submit_with_no_csrf_token_then_forbidden(self):
        # Given
        self.launchSurvey('test', 'interstitial_page')
        self.last_csrf_token = None

        # When
        self.post(action='start_questionnaire')

        # Then
        self.assertStatusCode(401)
        self.assertEqualUrl(self.last_url)

    def test_given_on_interstitial_page_when_submit_with_invalid_csrf_token_then_forbidden(self):
        # Given
        self.launchSurvey('test', 'interstitial_page')
        self.last_csrf_token = 'made-up-token'

        # When
        self.post(action='start_questionnaire')

        # Then
        self.assertStatusCode(401)
        self.assertEqualUrl(self.last_url)

    def test_given_on_introduction_page_when_submit_valid_token_then_redirect_to_next_page(self):
        # Given
        self.launchSurvey('test', 'interstitial_page')

        # When
        self.post(action='start_questionnaire')

        # Then
        self.assertStatusOK()
        self.assertInBody('What is your favourite breakfast food')

    def test_given_answered_question_when_change_answer_with_invalid_csrf_token_then_answers_not_saved(self):
        # Given
        self.launchSurvey('test', 'interstitial_page', roles=['dumper'])
        self.post()
        self.post({'favourite-breakfast': 'Muesli'})

        # When
        self.last_csrf_token = 'made-up-token'
        self.post({'favourite-breakfast': 'Pancakes'})

        # Then
        self.assertStatusCode(401)
        self.get('/dump/answers')
        answers = json.loads(self.getResponseData())
        self.assertEqual('Muesli', answers['answers'][0]['value'])

    def test_given_valid_answer_when_answer_with_invalid_csrf_token_then_answer_not_saved(self):
        # Given
        self.launchSurvey('test', 'checkbox', roles=['dumper'])
        self.post({'mandatory-checkbox-answer': 'Other',
                   'other-answer-mandatory': 'No reason'})

        # When
        self.last_csrf_token = 'made-up-token'
        self.post({'non-mandatory-checkbox-answer': 'None'})

        # Then
        self.assertStatusCode(401)
        self.get('/dump/answers')
        answers = json.loads(self.getResponseData())
        self.assertEqual(2, len(answers['answers']))

    def test_given_valid_answers_when_save_and_sign_out_with_invalid_csrf_token_then_answers_not_saved(self):
        # Given
        self.launchSurvey('test', 'interstitial_page', roles=['dumper'])
        self.post()
        post_data = {'favourite-breakfast': 'Muesli'}

        # When
        self.last_csrf_token = 'made-up-token'
        self.post(post_data=post_data, action='save_sign_out')

        # Then
        self.assertStatusCode(401)
        self.get('/dump/answers')
        answers = json.loads(self.getResponseData())
        self.assertEqual(0, len(answers['answers']))

    def test_given_csrf_attack_when_refresh_then_on_question(self):
        # Given
        self.launchSurvey('test', 'interstitial_page', roles=['dumper'])
        self.post()
        self.last_csrf_token = 'made-up-token'
        self.post({'favourite-breakfast': 'Pancakes'})

        # When
        self.get(self.last_url)

        # Then
        self.assertEqual(self.last_response.status_code, 200)
        self.get('/dump/answers')
        answers = json.loads(self.getResponseData())
        self.assertEqual(0, len(answers['answers']))

    def test_given_csrf_attack_when_submit_new_answers_then_answers_saved(self):
        # Given
        self.launchSurvey('test', 'interstitial_page', roles=['dumper'])
        self.post()
        self.last_csrf_token = 'made-up-token'
        self.post({'favourite-breakfast': 'Muesli'})

        # When
        self.get(self.last_url)
        self.post({'favourite-breakfast': 'Pancakes'})

        # Then
        self.assertStatusOK()
        self.get('/dump/answers')
        answers = json.loads(self.getResponseData())
        self.assertEqual('Pancakes', answers['answers'][0]['value'])