text:
package com.facebook.litho.testing.espresso;

import static com.facebook.litho.testing.espresso.LithoViewMatchers.lithoView;
import static com.facebook.litho.testing.espresso.LithoViewMatchers.withTestKey;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;

import android.widget.TextView;
import androidx.test.InstrumentationRegistry;
import androidx.test.annotation.UiThreadTest;
import androidx.test.runner.AndroidJUnit4;
import com.facebook.litho.Component;
import com.facebook.litho.ComponentContext;
import com.facebook.litho.LithoView;
import com.facebook.litho.config.ComponentsConfiguration;
import com.facebook.testing.screenshot.ViewHelpers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Tests {@link LithoViewMatchers} */
@RunWith(AndroidJUnit4.class)
public class LithoViewMatchersTest {

  private LithoView mView;

  @UiThreadTest
  @Before
  public void before() throws Throwable {
    ComponentsConfiguration.isEndToEndTestRun = true;
    final ComponentContext mComponentContext =
        new ComponentContext(InstrumentationRegistry.getTargetContext());
    final Component mTextComponent = MyComponent.create(mComponentContext).text("foobar").build();
    mView = LithoView.create(InstrumentationRegistry.getTargetContext(), mTextComponent);
    ViewHelpers.setupView(mView).setExactWidthPx(200).setExactHeightPx(100).layout();
  }

  @Test
  public void testIsLithoView() throws Throwable {
    assertThat(new TextView(InstrumentationRegistry.getTargetContext()), is(not(lithoView())));
    assertThat(mView, is(lithoView()));
  }

  @Test
  public void testHasTestKey() throws Throwable {
    assertThat(mView, is(withTestKey("my_test_key")));
    assertThat(mView, is(not(withTestKey("my_non_existant_test_key"))));
  }
}


text:
(function ($) {
    'use strict';

    var selFlextree = $.flextree.getInternal('selFlextree');
    var dataFixDblClickBug = $.flextree.getInternal('dataFixDblClickBug');
    var dataCollapsible = $.flextree.getInternal('dataCollapsible');
    var dataExclusiveNode = $.flextree.getInternal('dataExclusiveNode');

    var selCollapsible = '.ft-collapsible';
    var cssExpanded = 'ft-expanded';
    var dataAttached = 'ft-collapsible-attached';

    $.flextree.components.collapsible = {
        main: function () {
            var $root = $(this).treeRoot();
            var fixDblClickBug = $root.data(dataFixDblClickBug);
            var collapsible = $root.data(dataCollapsible);
            var exclusiveNode = $root.data(dataExclusiveNode);

            if (!collapsible || $root.data(dataAttached))
                return;

            $root.data(dataAttached, true);
            $root.on('click', selCollapsible, function (e) {
                if (fixDblClickBug && !e.isClick)
                    return;

                e.stopPropagation();
                $(this).treeActivate();
            });

            $root.on($.flextree.eventActivate, 'li:not(' + selFlextree + ')', function () {
                $(this).find(selCollapsible).toggleClass(cssExpanded);
                if (exclusiveNode)
                    $(this).treeSiblings().find(selCollapsible).removeClass(cssExpanded);
            });
        }
    };
}(typeof module !== 'undefined' && module.exports ? require('jquery') : jQuery));

redpajama_set_name: RedPajamaGithub


text:
package org.neo4j.unsafe.impl.batchimport.cache;

import java.util.Arrays;

import org.neo4j.helpers.Exceptions;

import static java.lang.String.format;

import static org.neo4j.helpers.Format.bytes;
import static org.neo4j.unsafe.impl.batchimport.Utils.safeCastLongToInt;

/**
 * Factory of {@link LongArray} and {@link IntArray} instances. Users can select in which type of memory
 * the arrays will be placed, either in {@link #HEAP} or {@link #OFF_HEAP}, or even {@link #AUTO} which
 * will have each instance placed where it fits best, favoring off-heap.
 */
public interface NumberArrayFactory
{
    /**
     * @param length size of the array.
     * @param defaultValue value which will represent unset values.
     * @return a fixed size {@link IntArray}.
     */
    IntArray newIntArray( long length, int defaultValue );

    /**
     * @param chunkSize the size of each array (number of items). Where new chunks are added when needed.
     * @param defaultValue value which will represent unset values.
     * @return dynamically growing {@link IntArray}.
     */
    IntArray newDynamicIntArray( long chunkSize, int defaultValue );

    /**
     * @param length size of the array.
     * @param defaultValue value which will represent unset values.
     * @return a fixed size {@link LongArray}.
     */
    LongArray newLongArray( long length, long defaultValue );

    /**
     * @param chunkSize the size of each array (number of items). Where new chunks are added when needed.
     * @param defaultValue value which will represent unset values.
     * @return dynamically growing {@link LongArray}.
     */
    LongArray newDynamicLongArray( long chunkSize, long defaultValue );

    /**
     * Implements the dynamic array methods, because they are the same in most implementations.
     */
    abstract class Adapter implements NumberArrayFactory
    {
        @Override
        public IntArray newDynamicIntArray( long chunkSize, int defaultValue )
        {
            return new DynamicIntArray( this, chunkSize, defaultValue );
        }

        @Override
        public LongArray newDynamicLongArray( long chunkSize, long defaultValue )
        {
            return new DynamicLongArray( this, chunkSize, defaultValue );
        }
    }

    /**
     * Puts arrays inside the heap.
     */
    NumberArrayFactory HEAP = new Adapter()
    {
        @Override
        public IntArray newIntArray( long length, int defaultValue )
        {
            return new HeapIntArray( safeCastLongToInt( length ), defaultValue );
        }

        @Override
        public LongArray newLongArray( long length, long defaultValue )
        {
            return new HeapLongArray( safeCastLongToInt( length ), defaultValue );
        }

        @Override
        public String toString()
        {
            return "HEAP";
        }
    };

    /**
     * Puts arrays off-heap, using unsafe calls.
     */
    NumberArrayFactory OFF_HEAP = new Adapter()
    {
        @Override
        public IntArray newIntArray( long length, int defaultValue )
        {
            return new OffHeapIntArray( length, defaultValue );
        }

        @Override
        public LongArray newLongArray( long length, long defaultValue )
        {
            return new OffHeapLongArray( length, defaultValue );
        }

        @Override
        public String toString()
        {
            return "OFF_HEAP";
        }
    };

    /**
     * Looks at available memory and decides where the requested array fits best. Tries to allocate the whole
     * array off-heap, then inside heap. If all else fails a dynamic array is returned with a smaller chunk size
     * so that collectively the whole array will fit in memory available on the machine.
     */
    class Auto extends Adapter
    {
        private final NumberArrayFactory[] candidates;

        public Auto( NumberArrayFactory... candidates )
        {
            this.candidates = candidates;
        }

        @Override
        public LongArray newLongArray( long length, long defaultValue )
        {
            OutOfMemoryError error = null;
            for ( NumberArrayFactory candidate : candidates )
            {
                try
                {
                    return candidate.newLongArray( length, defaultValue );
                }
                catch ( OutOfMemoryError e )
                {   // Allright let's try the next one
                    error = e;
                }
            }
            throw error( length, 8, error );
        }

        @Override
        public IntArray newIntArray( long length, int defaultValue )
        {
            OutOfMemoryError error = null;
            for ( NumberArrayFactory candidate : candidates )
            {
                try
                {
                    return candidate.newIntArray( length, defaultValue );
                }
                catch ( OutOfMemoryError e )
                {   // Allright let's try the next one
                    error = e;
                }
            }
            throw error( length, 4, error );
        }

        private OutOfMemoryError error( long length, int itemSize, OutOfMemoryError error )
        {
            throw Exceptions.withMessage( error, format( "%s: Not enough memory available for allocating %s, tried %s",
                    error.getMessage(), bytes( length*itemSize ), Arrays.toString( candidates ) ) );
        }
    }

    /**
     * Used as part of the fallback strategy for {@link Auto}. Tries to split up fixed-size arrays
     * ({@link #newLongArray(long, long)} and {@link #newIntArray(long, int)} into smaller chunks where
     * some can live on heap and some off heap.
     */
    NumberArrayFactory CHUNKED_FIXED_SIZE = new Adapter()
    {
        private final NumberArrayFactory delegate = new Auto( OFF_HEAP, HEAP );

        @Override
        public LongArray newLongArray( long length, long defaultValue )
        {
            // Here we want to have the property of a dynamic array which makes some parts of the array
            // live on heap, some off. At the same time we want a fixed size array. Therefore first create
            // the array as a dynamic array, make it grow to the requested length and then fixate.
            DynamicLongArray array = newDynamicLongArray( fractionOf( length ), defaultValue );
            array.ensureChunkAt( length-1 );
            return array.fixate();
        }

        @Override
        public IntArray newIntArray( long length, int defaultValue )
        {
            // Here we want to have the property of a dynamic array which makes some parts of the array
            // live on heap, some off. At the same time we want a fixed size array. Therefore first create
            // the array as a dynamic array, make it grow to the requested length and then fixate.
            DynamicIntArray array = newDynamicIntArray( fractionOf( length ), defaultValue );
            array.ensureChunkAt( length-1 );
            return array.fixate();
        }

        private long fractionOf( long length )
        {
            return length / 10;
        }

        @Override
        public DynamicIntArray newDynamicIntArray( long chunkSize, int defaultValue )
        {
            return new DynamicIntArray( delegate, chunkSize, defaultValue );
        }

        @Override
        public DynamicLongArray newDynamicLongArray( long chunkSize, long defaultValue )
        {
            return new DynamicLongArray( delegate, chunkSize, defaultValue );
        }

        @Override
        public String toString()
        {
            return "CHUNKED_FIXED_SIZE";
        }
    };

    /**
     * {@link Auto} factory which uses JVM stats for gathering information about available memory.
     */
    NumberArrayFactory AUTO = new Auto( OFF_HEAP, HEAP, CHUNKED_FIXED_SIZE );
}


text:
@echo off

rem Just some shortcut functions to test things on Android.

echo Android Test Util by Steve Richey.

rem "test android fast" will just load the current exported APK on the connected device.
if %1_%2==android_fast (
	echo Not building, just sending to device...
	adb shell am force-stop com.dreamshowadventures.drillbunny
	adb shell am start -a android.intent.action.DELETE -d package:com.dreamshowadventures.drillbunny
	adb shell input tap 464 786
	adb install export/android/bin/bin/DrillBunny-debug.apk
	adb shell am start -n com.dreamshowadventures.drillbunny/com.dreamshowadventures.drillbunny.MainActivity
)

rem "test android clean" does a clean build and loads the APK on the device wirelessly.
if %1_%2==android_clean (
	echo Doing clean build, and sending to device wirelessly...
	echo y | rd export /s
	lime build android
	adb tcpip
	adb connect 192.168.1.115:5555
	adb shell am force-stop com.dreamshowadventures.drillbunny
	adb shell am start -a android.intent.action.DELETE -d package:com.dreamshowadventures.drillbunny
	adb shell input tap 464 786
	adb install export/android/bin/bin/DrillBunny-debug.apk
	adb shell am start -n com.dreamshowadventures.drillbunny/com.dreamshowadventures.drillbunny.MainActivity
)

rem "test android" does a standard build and loads the APK on the device.
if %1_%2==android_ (
	echo Doing regular build, sending to device...
	lime build android
	adb shell am force-stop com.dreamshowadventures.drillbunny
	adb shell am start -a android.intent.action.DELETE -d package:com.dreamshowadventures.drillbunny
	adb shell input tap 464 786
	adb install export/android/bin/bin/DrillBunny-debug.apk
	adb shell am start -n com.dreamshowadventures.drillbunny/com.dreamshowadventures.drillbunny.MainActivity
)

if %1_%2==_ (
	echo No target specified! Try "test android", "test android clean", or "test android fast"!
)


text:
package org.apache.pinot.tools.scan.query;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pinot.core.indexsegment.immutable.ImmutableSegment;
import org.apache.pinot.core.query.utils.Pair;
import org.apache.pinot.core.segment.index.metadata.SegmentMetadataImpl;
import org.apache.pinot.core.segment.index.readers.Dictionary;

public class Selection {
  private final ImmutableSegment _immutableSegment;
  private final SegmentMetadataImpl _metadata;
  private final List<Integer> _filteredDocIds;
  private final List<Pair> _selectionColumns;

  public Selection(ImmutableSegment immutableSegment, SegmentMetadataImpl metadata, List<Integer> filteredDocIds,
      List<Pair> selectionColumns) {

    _immutableSegment = immutableSegment;
    _metadata = metadata;
    _filteredDocIds = filteredDocIds;
    _selectionColumns = selectionColumns;
  }

  public ResultTable run() {
    boolean addCountStar = false;
    Map<String, Dictionary> dictionaryMap = new HashMap<>();

    for (Pair pair : _selectionColumns) {
      String column = (String) pair.getFirst();
      if (column.equals("*")) {
        addCountStar = true;
      }
      dictionaryMap.put(column, _immutableSegment.getDictionary(column));
    }

    Projection projection =
        new Projection(_immutableSegment, _metadata, _filteredDocIds, _selectionColumns, dictionaryMap, addCountStar);

    return projection.run();
  }
}


text:
/**
 * @file Template.java
 * @author Valery Samovich
 *
 * The observer pattern is a software design pattern in which an object,
 * called the subject, maintains a list of its dependents, called observers,
 * and notifies them automatically of any state changes, usually by calling
 * one of their methods.
 *
 * Observer vs. Observable
 *  - Observable is a class, Observer is an interface
 *  - Observable class maintain a list of observers
 *  - When an Observable object is updated it invokes the update() method of
 *    each of its observers
 */

package org.samovich.technologies.specialized.patterns.observer;

import java.util.Observable;
import java.util.Observer;

public class ObservableDemo extends Object {

    MyView view;
    MyModel model;

    // Constructor.
    public ObservableDemo() {
        view = new MyView();
        model = new MyModel();
        model.addObserver(view);
    }

    public static void main(String[] args) {

        ObservableDemo myObservable = new ObservableDemo();
        myObservable.demo();
    }

    private void demo() {
        model.changeSomething();
    }

    // The Observer normally maintains a view on the data.
    class MyView implements Observer {
        // For now, we just print the fact that we got notified.
        public void update(Observable obs, Object x) {
            System.out.println("Update(" + obs + ", " + x + ");");
        }
    }

    // The Observable normally maintains the data
    class MyModel extends Observable {
        public void changeSomething() {
            // Notify observers of change
            setChanged();
            notifyObservers();
        }

    }
}


text:
layout: page
title: Helix Software Executive Retreat
date: 2016-05-24
author: Roy Kane
tags: weekly links, java
status: published
summary: Vestibulum laoreet, felis et consectetur convallis, orci nunc.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 07/24/2019
  endDate: 07/26/2019
  ctyhocn: ALBSPHX
  groupCode: HSER
published: true
---
Praesent convallis consequat leo id lobortis. Aenean vitae ullamcorper lacus. Integer in accumsan velit. Donec vulputate, ligula et tristique bibendum, magna nulla pellentesque nibh, eget auctor velit mauris eget velit. Morbi tortor risus, tempus eget mi a, euismod feugiat sapien. Interdum et malesuada fames ac ante ipsum primis in faucibus. Integer hendrerit sodales sollicitudin. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus hendrerit dolor quis odio efficitur tincidunt. Praesent id augue leo. Suspendisse potenti. Proin vel lorem ultrices, vehicula urna sed, tempus ligula.

1 In sed lorem dictum, dictum sem sit amet, aliquet neque
1 Nulla eleifend felis a dignissim elementum
1 Nulla a libero sed erat convallis condimentum
1 Aliquam gravida dolor ut velit venenatis, vitae fermentum tellus condimentum
1 Sed nec massa vitae sapien semper suscipit.

Phasellus id lectus vel quam pharetra tempus sed nec libero. Sed vel ultrices neque. Etiam nec nunc id nulla ultrices ullamcorper. Aliquam a nulla et velit fringilla porta. Integer et sem sed nibh posuere ornare. Donec fringilla elit vitae risus tristique, varius maximus lectus maximus. In a eros id sem auctor auctor. Sed finibus massa lacus, id aliquet risus suscipit eu. Sed in ultrices elit, in aliquet justo. Fusce ornare, urna a varius posuere, tortor ex tincidunt arcu, et rhoncus nulla nulla ut eros. Integer facilisis orci mauris, et consequat enim rutrum quis.


text:
using System;
using System.ComponentModel;

namespace Azure.Containers.ContainerRegistry
{
    /// <summary> The artifact platform's architecture. </summary>
    public readonly partial struct ArtifactArchitecture : IEquatable<ArtifactArchitecture>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="ArtifactArchitecture"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public ArtifactArchitecture(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string I386Value = "386";
        private const string Amd64Value = "amd64";
        private const string ArmValue = "arm";
        private const string Arm64Value = "arm64";
        private const string MipsValue = "mips";
        private const string MipsLeValue = "mipsle";
        private const string Mips64Value = "mips64";
        private const string Mips64LeValue = "mips64le";
        private const string Ppc64Value = "ppc64";
        private const string Ppc64LeValue = "ppc64le";
        private const string RiscV64Value = "riscv64";
        private const string S390XValue = "s390x";
        private const string WasmValue = "wasm";

        /// <summary> i386. </summary>
        public static ArtifactArchitecture I386 { get; } = new ArtifactArchitecture(I386Value);
        /// <summary> AMD64. </summary>
        public static ArtifactArchitecture Amd64 { get; } = new ArtifactArchitecture(Amd64Value);
        /// <summary> ARM. </summary>
        public static ArtifactArchitecture Arm { get; } = new ArtifactArchitecture(ArmValue);
        /// <summary> ARM64. </summary>
        public static ArtifactArchitecture Arm64 { get; } = new ArtifactArchitecture(Arm64Value);
        /// <summary> MIPS. </summary>
        public static ArtifactArchitecture Mips { get; } = new ArtifactArchitecture(MipsValue);
        /// <summary> MIPSLE. </summary>
        public static ArtifactArchitecture MipsLe { get; } = new ArtifactArchitecture(MipsLeValue);
        /// <summary> MIPS64. </summary>
        public static ArtifactArchitecture Mips64 { get; } = new ArtifactArchitecture(Mips64Value);
        /// <summary> MIPS64LE. </summary>
        public static ArtifactArchitecture Mips64Le { get; } = new ArtifactArchitecture(Mips64LeValue);
        /// <summary> PPC64. </summary>
        public static ArtifactArchitecture Ppc64 { get; } = new ArtifactArchitecture(Ppc64Value);
        /// <summary> PPC64LE. </summary>
        public static ArtifactArchitecture Ppc64Le { get; } = new ArtifactArchitecture(Ppc64LeValue);
        /// <summary> RISCv64. </summary>
        public static ArtifactArchitecture RiscV64 { get; } = new ArtifactArchitecture(RiscV64Value);
        /// <summary> s390x. </summary>
        public static ArtifactArchitecture S390X { get; } = new ArtifactArchitecture(S390XValue);
        /// <summary> Wasm. </summary>
        public static ArtifactArchitecture Wasm { get; } = new ArtifactArchitecture(WasmValue);
        /// <summary> Determines if two <see cref="ArtifactArchitecture"/> values are the same. </summary>
        public static bool operator ==(ArtifactArchitecture left, ArtifactArchitecture right) => left.Equals(right);
        /// <summary> Determines if two <see cref="ArtifactArchitecture"/> values are not the same. </summary>
        public static bool operator !=(ArtifactArchitecture left, ArtifactArchitecture right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="ArtifactArchitecture"/>. </summary>
        public static implicit operator ArtifactArchitecture(string value) => new ArtifactArchitecture(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is ArtifactArchitecture other && Equals(other);
        /// <inheritdoc />
        public bool Equals(ArtifactArchitecture other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
declare namespace pLimit {}

export = pLimit;

declare function pLimit<T>(concurrency: number): (fn: () => PromiseLike<T>) => Promise<T>;


text:
package mdutils

import (
	"github.com/ipfs/go-ipfs/blocks/blockstore"
	bsrv "github.com/ipfs/go-ipfs/blockservice"
	"github.com/ipfs/go-ipfs/exchange/offline"
	dag "github.com/ipfs/go-ipfs/merkledag"
	ds "gx/ipfs/QmdHG8MAuARdGHxx4rPQASLcvhz24fzjSQq7AJRAQEorq5/go-datastore"
	dssync "gx/ipfs/QmdHG8MAuARdGHxx4rPQASLcvhz24fzjSQq7AJRAQEorq5/go-datastore/sync"
)

func Mock() dag.DAGService {
	return dag.NewDAGService(Bserv())
}

func Bserv() bsrv.BlockService {
	bstore := blockstore.NewBlockstore(dssync.MutexWrap(ds.NewMapDatastore()))
	return bsrv.New(bstore, offline.Exchange(bstore))
}


text:
//----------------------------------------------
//            NGUI: Next-Gen UI kit
// Copyright © 2011-2014 Tasharen Entertainment
//----------------------------------------------

#if UNITY_3_5
using UnityEngine;
using UnityEditor;

[CanEditMultipleObjects]
[CustomEditor(typeof(UIGrid))]
public class UIGridEditor : UIWidgetContainerEditor
{
}
#endif


text:
/**
 * Created by pablo on 24/3/17.
 */
const sql_source = require('./utils/sql-source');
const crypt_utils = require('./utils/crypt-utils');

const e = global.functions = {
    authRequest: (request) => {
        return new Promise((promise_result, promise_error) => {
            const client_id = request.headers.client_id;
            const client_token = request.headers.client_token;

            const sql_conn = sql_source.connection();
            const query =
                `SELECT fk_user_uuid, client_hash
                FROM UserSession
                WHERE valid='1' AND DATE_ADD(creation,INTERVAL 30 DAY) > NOW()
                AND client_id=${sql_conn.escape(client_id)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                    const sql_result = sql_results[0];
                    const err_message = "No se ha podido verificar la autenticidad del cliente";

                    if(sql_result === undefined){
                        promise_result({ valid: false, message: err_message});
                        sql_conn.end();
                        return;
                    }

                    const client_hash = sql_result.client_hash;

                    if(!crypt_utils.bcrypt_verify(client_token, client_hash)){
                        promise_result({ valid: false, message: err_message});
                        sql_conn.end();
                        return;
                    }

                    promise_result({ valid: true, user_uuid: sql_result.fk_user_uuid });
                    sql_conn.end();
                }
            );
        });
    },
    isUserUUIDRegistered: (uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query = `SELECT COUNT(*) AS count FROM User WHERE uuid=${sql_conn.escape(uuid)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    isUsernameRegistered: (username) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query = `SELECT COUNT(*) AS count FROM User WHERE username=${sql_conn.escape(username)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    getUUIDFromUsername: (username) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query = `SELECT uuid FROM User WHERE username=${sql_conn.escape(username)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].uuid);
                sql_conn.end();
            });
        });
    },
    isCompanyRegistered: (company_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query = `SELECT COUNT(*) AS count FROM Company WHERE uuid=${sql_conn.escape(company_uuid)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    isGroupRegistered: (company_uuid, group_id) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query = `
            SELECT COUNT(*) AS count
            FROM CompanyGroup
            WHERE id=${sql_conn.escape(group_id)}
            AND fk_company_uuid=${sql_conn.escape(company_uuid)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    isUserFromCompany: (company_uuid, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM UserLinkedCompany
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    isUserFromCompanyGroup: (company_uuid, group_id, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM UserLinkedCompanyGroup
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_group_id=${sql_conn.escape(group_id)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    isUserFromCompanyGroupDate: (company_uuid, group_id, date_id, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM UserLinkedCompanyGroupDate
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_group_id=${sql_conn.escape(group_id)}
                AND fk_date_id=${sql_conn.escape(date_id)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    isCompanyGroupRegistered: (company_uuid, group_id) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM CompanyGroup
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND id=${sql_conn.escape(group_id)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    isCompanyGroupDateRegistered: (company_uuid, group_id, date_id) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM CompanyGroupDate
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_group_id=${sql_conn.escape(group_id)}
                AND id=${sql_conn.escape(date_id)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    isPaymentOptionAvailable: (payment_id) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM PaymentOption
                WHERE id=${sql_conn.escape(payment_id)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    hasUserPermissionToEditCompany: (company_uuid, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM UserLinkedCompany
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)}
                AND can_edit='1'`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    hasUserPermissionToEditCompanyGroup: (company_uuid, group_id, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM UserLinkedCompanyGroup
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_group_id=${sql_conn.escape(group_id)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)}
                AND can_edit='1'`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    hasUserPermissionToEditCompanyGroupDate: (company_uuid, group_id, date_id, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COUNT(*) AS count
                FROM UserLinkedCompanyGroupDate
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_date_id=${sql_conn.escape(date_id)}
                AND fk_group_id=${sql_conn.escape(group_id)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)}
                AND can_edit='1'`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].count === 1);
                sql_conn.end();
            });
        });
    },
    getCompanyInfo: (company_uuid, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT uuid, register_timestamp AS register, name,
                description, email, telephone, address, postal_code,
                (
                    SELECT COUNT(*)
                    FROM UserLinkedCompany
                    WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                    AND petition='1'
                ) AS members_count
                FROM Company
                WHERE uuid=${sql_conn.escape(company_uuid)};
                SELECT can_edit
                FROM UserLinkedCompany
                WHERE fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)};
                SELECT name, code
                FROM Country
                WHERE id=(
                    SELECT fk_country_id
                    FROM Company
                    WHERE uuid=${sql_conn.escape(company_uuid)}
                );`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                let company = sql_results[0][0];
                company.can_edit = sql_results[1][0].can_edit;
                company.country = sql_results[2][0];
                promise_result(company);
                sql_conn.end();
            });
        });
    },
    getCompanyGroupInfo: (company_uuid, group_id, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT id, fk_company_uuid AS company_uuid,
                name, description, creation_timestamp AS creation
                FROM CompanyGroup
                WHERE id=${sql_conn.escape(group_id)}
                AND fk_company_uuid=${sql_conn.escape(company_uuid)};
                SELECT can_edit
                FROM UserLinkedCompanyGroup
                WHERE fk_group_id=${sql_conn.escape(group_id)}
                AND fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)};`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                let group = sql_results[0][0];
                if(sql_results[1][0] !== undefined) group.can_edit = sql_results[1][0].can_edit;
                promise_result(group);
                sql_conn.end();
            });
        });
    },
    getCompanyGroupDateInfo: (company_uuid, group_id, date_id, user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT id, fk_group_id AS group_id, fk_company_uuid AS company_uuid,
                title, description, datetime, long_minutes
                FROM CompanyGroupDate
                WHERE id=${sql_conn.escape(date_id)}
                AND fk_company_uuid=${sql_conn.escape(company_uuid)};
                SELECT can_edit
                FROM UserLinkedCompanyGroupDate
                WHERE fk_date_id=${sql_conn.escape(date_id)}
                AND fk_group_id=${sql_conn.escape(group_id)}
                AND fk_company_uuid=${sql_conn.escape(company_uuid)}
                AND fk_user_uuid=${sql_conn.escape(user_uuid)};`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                let group = sql_results[0][0];
                if(sql_results[1][0] !== undefined) group.can_edit = sql_results[1][0].can_edit;
                promise_result(group);
                sql_conn.end();
            });
        });
    },
    getUserInfo: (user_uuid, pub = false) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT u.name, u.username, u.telephone, u.city,
                u.postal_code, u.email, u.register_timestamp,
                c.name AS country_name, c.code AS country_code
                FROM User u
                JOIN Country c
                ON u.fk_country_id = c.id
                WHERE uuid=${sql_conn.escape(user_uuid)}`;
            sql_conn.query(
                query,
                (sql_error, sql_results, sql_fields) => {
                    let sql_result = sql_results[0];
                    //El contenido del usuario es publico
                    if(!pub){
                        const content = {
                            uuid: user_uuid,
                            name: sql_result.name,
                            username: sql_result.username,
                            register_timestamp: sql_result.register_timestamp
                        };
                        promise_result(content);
                        sql_conn.end();
                        return;
                    }
                    //El contenido del usuario es privado
                    const country = {
                        name: sql_result.country_name,
                        code: sql_result.country_code
                    };
                    sql_result.uuid = user_uuid;
                    sql_result.country_name = sql_result.country_code = undefined;
                    sql_result.country = country;
                    promise_result(sql_result);
                    sql_conn.end();
                }
            );
        });
    },
    getUserQuota: (user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            e.getUserMaxQuota(user_uuid).then(user_max_quota => {
                e.getUserCurrentQuota(user_uuid).then(user_current_quota => {
                    promise_result({
                        company_count: user_max_quota.company_count - user_current_quota.company_count,
                        group_count: user_max_quota.group_count - user_current_quota.group_count,
                        user_count: user_max_quota.user_count - user_current_quota.user_count
                    });
                });
            });
        });
    },
    getUserMaxQuota: (user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT COALESCE(SUM(company_count), (SELECT company_count FROM PaymentOption WHERE id=1)) AS company_count,
                COALESCE(SUM(group_count), (SELECT group_count FROM PaymentOption WHERE id=1)) AS group_count,
                COALESCE(SUM(user_count), (SELECT user_count FROM PaymentOption WHERE id=1)) AS user_count
                FROM PaymentOption
                JOIN UserPayment
                ON fk_payment_option_id=id
                WHERE DATE_ADD(timestamp, INTERVAL 30 DAY) > NOW()
                AND fk_user_uuid=${sql_conn.escape(user_uuid)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0])
                sql_conn.end();
            });
        });
    },
    getUserUUIDFromClientId: (client_id) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `SELECT fk_user_uuid AS user_uuid
                FROM UserSession
                WHERE client_id=${sql_conn.escape(client_id)}`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result(sql_results[0].user_uuid);
                sql_conn.end();
            });
        });
    },
    getUserCurrentQuota: (user_uuid) => {
        return new Promise((promise_result, promise_error) => {
            const sql_conn = sql_source.connection();
            const query =
                `#Recuento de compañias que tiene el usuario
                SELECT count(*) AS company_count
                FROM UserLinkedCompany
                WHERE fk_user_uuid=${sql_conn.escape(user_uuid)}
                AND can_edit='1';
                #Recuento de Grupos asociados al usuario
                SELECT count(*) AS group_count
                FROM UserLinkedCompanyGroup
                WHERE fk_user_uuid=${sql_conn.escape(user_uuid)}
                AND can_edit='1';
                #Recuento de usuarios a cargo de las compañias del usuario
                SELECT COUNT(*) -
                (
                    SELECT COUNT(*)
                    FROM UserLinkedCompany
                    WHERE can_edit='1'
                    AND fk_user_uuid=${sql_conn.escape(user_uuid)}
                ) AS user_count
                FROM UserLinkedCompany
                WHERE fk_company_uuid
                IN
                (
                    SELECT fk_company_uuid
                    FROM UserLinkedCompany
                    WHERE can_edit='1'
                    AND fk_user_uuid=${sql_conn.escape(user_uuid)}
                );`;
            sql_conn.query(query, (sql_error, sql_results, sql_fields) => {
                promise_result({
                    company_count: sql_results[0][0].company_count,
                    group_count: sql_results[1][0].group_count,
                    user_count: sql_results[2][0].user_count
                });
                sql_conn.end();
            });
        });
    },
    isValidDate: (datetime) => {
        const datetimeRegex = /^(\d{1,2})\/(\d{1,2})\/(\d{4}) (\d{1,2}):(\d{1,2})$/;
        return new RegExp(datetimeRegex).test(datetime);
    }
};


text:
class AeicDashboardController < ApplicationController
  before_action :require_aeic

  def index
    if params[:track_id].present?
      @track = Track.find(params[:track_id])
      recommend_accept_labels = ["recommend-accept", @track.label].compact.join(",")
      query_scope_labels = ["query-scope", @track.label].compact.join(",")
    else
      params[:track_id] = nil
      recommend_accept_labels = "recommend-accept"
      query_scope_labels = "query-scope"
    end

    @recommend_accept = GITHUB.issues(Rails.application.settings["reviews"], labels: recommend_accept_labels, state:"open")
    @with_query_scope = GITHUB.issues(Rails.application.settings["reviews"], labels: query_scope_labels, state:"open")
  end

end


text:
<?php

namespace Sylius\Component\Core\Currency;

use Sylius\Component\Channel\Context\ChannelContextInterface;
use Sylius\Component\Currency\Model\CurrencyInterface;
use Sylius\Component\Currency\Provider\CurrencyProvider;
use Sylius\Component\Resource\Repository\RepositoryInterface;

/**
 * Currency provider, which returns currencies enabled for this channel.
 *
 * @author Paweł Jędrzejewski <pawel@sylius.org>
 * @author Fernando Caraballo Ortiz <caraballo.ortiz@gmail.com>
 */
class ChannelAwareCurrencyProvider extends CurrencyProvider
{
    /**
     * @var ChannelContextInterface
     */
    protected $channelContext;

    /**
     * @param ChannelContextInterface $channelContext
     * @param RepositoryInterface $currencyRepository
     */
    public function __construct(ChannelContextInterface $channelContext, RepositoryInterface $currencyRepository)
    {
        parent::__construct($currencyRepository);

        $this->channelContext = $channelContext;
    }

    /**
     * {@inheritdoc}
     */
    public function getAvailableCurrencies()
    {
        $currentChannel = $this->channelContext->getChannel();

        return $currentChannel->getCurrencies()->filter(function (CurrencyInterface $currency) {
            return $currency->isEnabled();
        });
    }
}


text:
package com.zhuinden.examplegithubclient.presentation.activity.main;

import com.zhuinden.examplegithubclient.application.injection.ActivityScope;
import com.zhuinden.examplegithubclient.application.injection.modules.InteractorModule;
import com.zhuinden.examplegithubclient.application.injection.modules.NavigationModule;
import com.zhuinden.examplegithubclient.application.injection.modules.OkHttpModule;
import com.zhuinden.examplegithubclient.application.injection.modules.RepositoryModule;
import com.zhuinden.examplegithubclient.application.injection.modules.RetrofitModule;
import com.zhuinden.examplegithubclient.application.injection.modules.ServiceModule;
import com.zhuinden.examplegithubclient.data.model.GithubRepoDataSource;
import com.zhuinden.examplegithubclient.data.repository.GithubRepoRepository;
import com.zhuinden.examplegithubclient.domain.interactor.GetRepositoriesInteractor;
import com.zhuinden.examplegithubclient.domain.interactor.LoginInteractor;
import com.zhuinden.examplegithubclient.domain.networking.HeaderInterceptor;
import com.zhuinden.examplegithubclient.domain.service.GithubService;
import com.zhuinden.examplegithubclient.domain.service.retrofit.RetrofitGithubService;
import com.zhuinden.examplegithubclient.util.AnnotationCache;

import dagger.Component;
import flowless.Flow;
import flowless.KeyManager;
import flowless.ServiceProvider;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;

/**
 * Created by Owner on 2016.12.10.
 */
@ActivityScope
@Component(modules = {OkHttpModule.class, RetrofitModule.class, InteractorModule.class, NavigationModule.class, RepositoryModule.class, ServiceModule.class})
public interface MainComponent {
    Flow flow();

    ServiceProvider serviceProvider();

    KeyManager keyManager();

    HeaderInterceptor headerInterceptor();

    AnnotationCache annotationCache();

    MainPresenter mainPresenter();

    OkHttpClient okHttpClient();

    RetrofitGithubService retrofitGithubService();

    Retrofit retrofit();

    GithubService githubService();

    GetRepositoriesInteractor getRepositoriesInteractor();

    LoginInteractor loginInteractor();

    GithubRepoDataSource repositoryDataSource();

    GithubRepoRepository repositoryRepository();

    void inject(MainActivity mainActivity);

    void inject(MainView mainView);
}


text:
# twitchStreamers

This app displays Streamers in Twitch.

There is the option to search for streamers and the
output shows the information you need.

View the app live at https://ivangeorgiew.github.io/twitchStreamers/

### Feedback

**Feedback** is much **appreciated** since there are still some possibilities for a mistake.

### Installation

I used my [static-boilerplate](https://github.com/ivangeorgiew/static-boilerplate) repo to make the website.
In case you want to install:

1) `cd /*YOUR DIRECTORY*/`

2) `git clone https://github.com/ivangeorgiew/myCalculator.git`

3) `npm i`

4) `gulp`


text:
author: Subutai Ahmad, Jeff Hawkins, Yuwei Cui
brief: Why Do Neurons Have Thousands of Synapses? A Theory of Sequence Memory in Neocortex.
date: 2016/09/21
image:
link: /assets/pdf/posters/BernsteinPoster_V1_narrow.pdf
media: poster
org: Numenta
section: archive
sort: b
tags: hierarchical temporal memory htm jeff hawkins poster conference pdf
title: Bernstein Conference 2016
type: link
---

Bernstein Conference 2016: Why Do Neurons Have Thousands of Synapses? A Theory of Sequence Memory in Neocortex.


text:
/*
	HUD
		Heads Up Display to show values such as: xy-position, altitude, ground speed and bearing,
			 vertical speed, lift (in g's), thrust (in g's) and bearing, helicopter orientation (bearing),
			 missile inclination (degrees), and missile initial speed (5 - 40m/s)

			Notable Functions:
			initializeHudText() creates an instance of all the text objects for the HUD

			Other functions simply set the text of the object to a new string

		Credits:	Brayden Willenborg, David Crossman, Chris Carman
					Karim Naqvi (used lab code)
*/

#include "HUD.h"

HUD::HUD() {

	helpVisible = false;
    camera = new osg::Camera;
    hudGeode = new osg::Geode;
    camera->setClearMask( GL_DEPTH_BUFFER_BIT);
    camera->setProjectionMatrixAsOrtho2D(0,1280,0,1024);
    camera->setViewMatrix(osg::Matrix::identity());
    camera->setRenderOrder( osg::Camera::POST_RENDER );
    camera->setReferenceFrame( osg::Camera::ABSOLUTE_RF );
}

void HUD::initializeHUD() {

	//initialize our crash pointer;
    crash  = initializeText("", osg::Vec3(20,170,0));

    //initialize our title pointer;
    title  = initializeText("HEADS UP DISPLAY", osg::Vec3(20,140,0));

    //initialize our position pointer;
    position  = initializeText("Position:", osg::Vec3(25,110,0));

	//initialize our speed pointer;
    velocity  = initializeText("Speed:", osg::Vec3(25,80,0));

	//initialize our thrust pointer;
    acceleration  = initializeText("Thrust:", osg::Vec3(25,50,0));

	//initialize our missile orientation pointer;
    missiles  = initializeText("Missiles:", osg::Vec3(25,20,0));

	//initialize out help screen
	std::string instructions = "W     - Pitch Forward\n";
	instructions += "A     - Pitch Left\n";
	instructions += "S     - Pitch Back\n";
	instructions += "D     - Pitch Right\n";
	instructions += "N     - Set Rotor to Hover\n";
	instructions += "X     - Stop Rotor\n";
	instructions += "F     - Fire Missile\n";
	instructions += "PgUp  - Missile Incline ++\n";
	instructions += "PgDn  - Missile Incline --\n";
	instructions += "Up    - Throttle ++\n";
	instructions += "Down  - Throttle --\n";
	instructions += "Left  - Rotate Left\n";
	instructions += "Right - Rotate Right\n";
	instructions += "H     - Toggle Help Menu\n";
	instructions += "Z     - Toggle Friction\n";
	instructions += "R     - Reset if Crashed\n";
	instructions += "L     - Run Logger\n";
	instructions += "T     - Runs Test\n";
	help = initializeText(instructions, osg::Vec3(900,1000,0));
	help->setColor(osg::Vec4(0, 0, 0, 0));

    hudGeode->addDrawable(title);
    hudGeode->addDrawable(help);
    hudGeode->addDrawable(position);
    hudGeode->addDrawable(velocity);
    hudGeode->addDrawable(acceleration);
	hudGeode->addDrawable(missiles);
    hudGeode->addDrawable(crash);

    camera->addChild(hudGeode);
}

osgText::Text * HUD::initializeText(std::string word, osg::Vec3 position) {
	osgText::Text * text = new osgText::Text;
    text->setFont(osgText::readFontFile("fonts/arial.ttf"));
	text->setDataVariance(osg::Object::DYNAMIC );
    text->setColor(osg::Vec4(199, 77, 15, 1));
    text->setCharacterSize(24.0f);
    text->setLayout( osgText::Text::LEFT_TO_RIGHT );
    text->setText(word);
    text->setPosition(position);
	return text;
}

void HUD::toggleHelpText() {
	if (helpVisible == false) {
		help->setColor(osg::Vec4(199, 77, 15, 1));
		helpVisible = true;
	}
	else {
		help->setColor(osg::Vec4(0, 0, 0, 0));
		helpVisible = false;
	}
}

osg::Camera * HUD::getHudCamera() {

    return camera;
}

osg::Geode * HUD::getHudGeode() {

    return hudGeode;
}

void HUD::setText(const std::string& hudText) {

    title->setText(hudText);
}

void HUD::setPosition(osg::Vec3f value) {

	std::string text =   "X: " + Logger::getInstance()->f2s(value.x()) + "m" +
		" Y: " + Logger::getInstance()->f2s(value.y()) + " m" +
		" Altitiude: " + Logger::getInstance()->f2s(value.z()) + "m";

	position->setText(text);
}

void HUD::setVelocity(osg::Vec3f value) {

	osg::Vec2f magBearing = Physics::getInstance()->xyToMagnitudeBearing(value.x(), value.y());
	std::string text = "Speed: " + Logger::getInstance()->f2s(magBearing.x()) + "m/s" +
		" Bearing: " + Logger::getInstance()->f2s(magBearing.y()) + " degrees" +
		" Climb: " + Logger::getInstance()->f2s(value.z()) + "m/s";

	velocity->setText(text);
}

void HUD::setAcceleration(osg::Vec3f value) {

	osg::Vec2f magBearing = Physics::getInstance()->xyToMagnitudeBearing(value.x(), value.y());
	float gravity = Physics::getInstance()->getGravity();

	std::string text = "Thrust: " + Logger::getInstance()->f2s(magBearing.x() / gravity) + "g" +
		" Bearing: " + Logger::getInstance()->f2s(magBearing.y()) + " degrees" +
		" Lift: " + Logger::getInstance()->f2s(value.z() / gravity) + "g";

	acceleration->setText(text);
}

void HUD::setMissiles(unsigned int remaining, float speed, float orientation) {

	std::string text = "Missiles: Orientation: " + Logger::getInstance()->f2s(orientation) +
		" Remaining: " + Logger::getInstance()->f2s(remaining) + " Speed: " +
		Logger::getInstance()->f2s(speed);

	missiles->setText(text);
}

void HUD::setWarning(const std::string& hudText)
{
    crash->setText(hudText);
}


text:
/*\file
 *
 * \brief Declares the System class as well as a host of functions for
 * performing common tasks associated with the system.
 */

#pragma once

#include <unordered_map>
#include <unordered_set>
#include "pulsar/system/Atom.hpp"
#include "pulsar/system/Space.hpp"
#include "pulsar/system/BasisSet.hpp"
#include "pulsar/math/MathSet.hpp"
#include "pulsar/math/PointManipulation.hpp"
#include "bphash/Hasher.hpp"
#include "pulsar/util/Hash.hpp"

// Instantiated in the cpp file
extern template class pulsar::Universe<pulsar::Atom>;
extern template class pulsar::MathSet<pulsar::Atom>;

namespace pulsar{

/*! \brief All atoms that may be used in a group of Systems */
typedef Universe<Atom> AtomSetUniverse;

/*! \brief A collection of Atoms and the space around them
 *
 *  This class is described in detail in the page
 *  [How to Make and Use Systems](@ref systems).  The main
 *  take away from a developer standpoint is that only the set of
 *  atoms is private.  This is because adding/removing atoms modifies the
 *  properties of the system as a whole (charge,mass, etc.).  Consequentially,
 *  we need thin wrappers around the member functions of the MathSet class.
 */
class System {
private:
    using AtomSet=MathSet<Atom>;//!< Type of atom storage container
    AtomSet atoms_;//!< Actual set of atoms

    /*! \brief Construct a system given a universe
     *
     * The universe will be shared with the data that was passed in
     *
     * \param [in] universe The universe this system should use
     * \param [in] fill If true system contains all the elements of the universe
     */
    explicit System(std::shared_ptr<const AtomSetUniverse> universe, bool fill);

    /* \brief Sets charge, multiplicity, and nelectrons as determined from the Atoms in this set */
    void SetDefaults_(void);

    //! \name Serialization and Hashing
    ///@{

    DECLARE_SERIALIZATION_FRIENDS
    BPHASH_DECLARE_HASHING_FRIENDS

    template<class Archive>
    void serialize(Archive & ar)
    {
        ar(atoms_, mass, charge, multiplicity, nelectrons);
    }

    void hash(bphash::Hasher & h) const;

    ///@}

public:

    using value_type=AtomSet::value_type;///< The type of an atom
    using const_iterator=AtomSet::const_iterator;///< Iterator over atoms
    using SelectorFunc=AtomSet::SelectorFunc;///<\copydoc MathSet::SelectorFunc
    using TransformerFunc=AtomSet::TransformerFunc;///<\copydoc MathSet::TransformerFunc

    double mass;   //!<Total mass of the system
    double charge; //!< Total charge on this system
    double multiplicity; //!< Total multiplicity of the system
    double nelectrons; //!< Total number of electrons in the system
    Space space;//!< The space this system lives in

    ///Copies the atoms in \p universe and add the atoms if \p fill is true
    explicit System(const AtomSetUniverse& universe, bool fill);
    ///Takes ownership of atoms in \p universe and adds them if \p fill is true
    explicit System(AtomSetUniverse&& universe,bool fill);

    /*! \brief For serialization only
     *
     * \warning NOT FOR USE OUTSIDE OF SERIALIZATION
     * \todo Replace if cereal fixes this
     */
    System() = default;

    // compiler generated ok
    // Copies will share storage in the AtomSet, but have their
    // own sets of contained atoms
    System(const System & rhs) = default;
    System(System && rhs) = default;
    System & operator=(const System & rhs) = default;
    System & operator=(System && rhs) = default;

    /** \brief Copies a system and optionally fills it
     *
     *
     *  \warning This constructor with \p fill set to true is, in general, not
     *  the same as the copy constructor becasue rhs.atoms_ may include some
     *  intermeidate set of atoms between empty and the universe
     */
    System(const System& rhs,bool fill)
            :System(rhs.atoms_.get_universe(),fill)
    {
    }

    /*! \name General System properties
     */
    ///@{
    void clear();///< Clears the atoms in this system, NOT universe

    size_t size(void) const;///< Returns atoms in system NOT universe

    double get_sum_charge(void) const;///< Returns sum of charg on each atom

    double get_sum_n_electrons(void) const;///< Returns sum of each atoms' electrons

    double get_sum_mass(void) const;///< Returns the sum of the atoms' masses

    bool count(const Atom& AnAtom)const;///< Returns true if atom is in system

    bool compare_info(const System & RHS)const;///<Compares data not in Space or atoms

    bphash::HashValue my_hash(void) const;///< Returns hash of System

    ///@}

    std::ostream& print(std::ostream & os) const;

    ///@{

    /*! \brief Return an iterator to the beginning of this system (first atom) */
    const_iterator begin(void) const{return atoms_.begin();}

    /*! \brief Return an iterator to the end of this system (just past the last atom) */
    const_iterator end(void) const{return atoms_.end();}

    ///@}

    /*! \name Set operations
     */
    ///@{

    /*! \brief Insert an atom into this system
     *
     * The Atom must already be a part of this System's universe
     *
     * \todo Exceptions from MathSet
     */
    System & insert(const Atom & atom);

    ///For compatability with STL algorithms
    template<typename T>
    System & insert(const T&,const Atom& atom){
        return this->insert(atom);
    }

    ///Range based insertion
    template<typename Begin_t,typename End_t>
    System & insert(Begin_t begin,End_t end){
        while(begin!=end){
            this->insert(*begin);
            ++begin;
        }
        return *this;
    }

    /*! \brief Insert an atom into this system
     *
     * The Atom must already be a part of this System's universe
     *
     * \todo Exceptions from MathSet
     */
    System & insert(Atom && atom);

    ///For compatability with STL algorithms
    template<typename T>
    System & insert(const T&,Atom&& atom){
        return this->insert(std::move(atom));
    }

    ///This becomes union of this and RHS
    System & union_assign(const System& RHS);
    System set_union(const System& RHS) const;///<Returns union of this and RHS
    ///This becomes intersection of this and RHS
    System & intersection_assign(const System& RHS);
    ///Returns intersection of this and RHS
    System intersection(const System& RHS) const;
    ///This becomes difference of this and RHS
    System & difference_assign(const System& RHS);
    ///Returns the set difference of this and RHS
    System difference(const System& RHS) const;

    /*! \brief Return all atoms that are in the universe but not in this system */
    System complement(void) const;

    /** \brief Returns true if this is a proper subset of other
     *
     *   This is a proper subset of RHS if the atoms are a proper subset
     *   of other.  Charge, multiplicity, and number of electrons are
     *   ignored.
     *
     *   \param[in] RHS The system to compare to
     *   \return True if this is a proper subset of other
     *
     */
    bool is_proper_subset_of(const System& RHS) const;

    /** \brief Returns true if this is a subset of other
     *
     *   This is a subset of RHS if the atoms are a subset
     *   of other.  Charge, multiplicity, and number of electrons are
     *   ignored.
     *
     *   \param[in] RHS The set to comapre to
     *   \return True if this is a subset of other
     *
     */
    bool is_subset_of(const System& RHS) const;

    /** \brief Returns true if this is a proper superset of other
     *
     *  This is a proper superset of other, iff other is a proper subset
     *  of this.
     *
     *  \param[in] RHS Set to compare to
     *  \return True if this is a proper superset of other
     *
     */
    bool is_proper_superset_of(const System& RHS) const;

    /** \brief Returns true if this is a superset of other
     *
     *  This is a superset of other iff other is a subset of this
     *
     *  \param[in] RHS Set to compare to
     *  \return true if this is a superset of other
     *
     */
    bool is_superset_of(const System& RHS) const;

    /** \brief Returns true if this set equals other
     *
     *   We define equality as having the same atoms, the same charge,
     *   the same multiplicity, the same mass, and the same number of electrons.
     *   We override MathSet's requirement for the same universes.
     *
     *   \param[in] RHS The other System to compare to
     *   \return True if this set equals other
     */
    bool operator==(const System& RHS)const;

    /** \brief Returns true if this does not equal other
     *
     *   Literally just negates the result of operator==()
     *
     *   \param[in] RHS The other System
     *   \return True if the sets are different
     *
     */
    bool operator!=(const System& RHS)const
    {
        return !(*this == RHS);
    }

    /*! \brief Return a subset of atoms in the system */
    System partition(SelectorFunc selector) const;

    ///@}

    /*! \name Basis Set-related functions
     */
    ///@{

    /*! \brief See if this system has a particular basis set
     *
     * Returns false if no atoms have the basis set
     */
    bool has_basis_set(const std::string & basislabel) const;

    /*! \brief Obtain a basis set with the given label
     */
    BasisSet get_basis_set(const std::string & basislabel) const;

    ///@}

    /*! \name General Manipulations
     *
     * These all return a new System
     */
    ///@{

    /*! \brief Perform a generic transformation to atoms in the system */
    System transform(TransformerFunc Transformer) const;

    /*! \brief Obtain the universe in use by this system
     */
    std::shared_ptr<const AtomSetUniverse> get_universe(void) const;

    /*! \brief Obtain the atoms from this system as a new universe
     *
     * The universe is not linked to this system in any way. Other information
     * (such as symmetry, etc) is obviously not copied.
     */
    AtomSetUniverse as_universe(void) const;

    ///@}
};

/*! \relates System
 *
 * \brief Finds the center of mass of \p sys
 *
 * Uses atomic masses (abundance-weighted isotope masses)
 */
Point center_of_mass(const System& sys);

/*! \relates System
 *
 *  \brief Finds the center of nuclear charge of \p sys
 */
Point center_of_nuclear_charge(const System& sys);

/*! \relates System
 *
 *  \brief translate \p Sys by \p vec
 *
 * \tparam VectorType A type corresponding to a VectorConcept
 */
template<typename VectorType>
System translate(const System& Sys,const VectorType & vec)
{
    return Sys.transform(std::bind(translate_point_copy<Atom, VectorType>,
            std::placeholders::_1, vec));
}

/*! \relates System
 *
 * \brief rotates the system point by point
 *
 *  Given a rotation matrix R, this function takes the point from the
 *  column space to the row space.
 *
 * \tparam VectorType A type corresponding to a MatrixConcept
 */
template<typename MatrixType>
System rotate(const System& Sys,const MatrixType & mat)
{
    return Sys.transform(std::bind(rotate_point_copy<Atom, MatrixType>,
            std::placeholders::_1, mat));
}

///Type of a distance matrix
typedef std::unordered_map<std::pair<Atom,Atom>,double> DistMat_t;

/*! \relates System
 *
 * \brief Returns the distance between each pair of atoms in \p sys
 */
DistMat_t get_distance(const System& sys);

///Type of a connectivity table
typedef std::unordered_map<Atom, std::unordered_set<Atom>> Conn_t;

/*! \relates System
 * \brief Returns connectivity data of \p sys, using covalent radii.
 *
 * Atoms are considered bonded if Tolerance*(sum of covRaddii) is greater than
 * distance
 */
Conn_t get_connectivity(const System& sys, double Tolerance = 1.20);

/** \relates System
 *
 * \brief Given a molecule that has been translated to the center of mass
 *         this function computes the inertia tensor for that system
 *
 *  The moment of inertia of a rigid rotating body comprised of \f$N\f$
 *  particles rotating about some axis is given by:
 *  \f[
 *     I=\sum_i^N m_iR_i^2,
 *  \f]
 *  where \f$m_i\f$ is the mass of the \f$i\f$-th particle and \f$R_i\f$ is
 *  the distance to the axis of rotation.  In most cases we instead know the
 *  distance to the origin, \f$r_i\f$.  If we assume that the axis of rotation passes
 *  through the origin we have a right triangle formed from \f$R_i\f$,
 *  \f$r_i\f$, and a unit vector in \f$n\f$ parallel with the rotation axis.
 *  Therefore we know:
 *  \f{align}{
 *    I=&\sum_i^N m_i\left[\left|r_i\right|\sin\left(\theta\right)\right]^2
 *     =&\sum_i^N m_i\left(r_i \times n\right)^2
 *  \f}
 *  where \f$\theta\f$ is the angle between \f$r_i\f$ and \f$n\f$.  In general,
 *  \f$n\f$ will not be parallel to any of the axes for which \f$r_i\f$ is
 *  defined.  We can get its projection onto those axes via the dot-product
 *  and consequentially,
 *  \f$n=\left[\cos\left(\alpha\right),\cos\left(\beta\right),\cos\left(\gamma\right)\right]\f$,
 *  where \f$\alpha,\beta\f$, and \f$\gamma\f$ are the angles between \f$n\f$ and
 *  the x,y, and z axes in the \f$r_i\f$ frame respectively.  After a little
 *  math we have:
 *  \f[
 *    r_i\times n=\left[r_{iy}\cos\left(\gamma\right)-
 *                      r_{iz}\cos\left(\beta\right),
 *                      r_{iz}\cos\left(\alpha\right)-
 *                      r_{ix}\cos\left(\gamma\right),
 *                      r_{ix}\cos\left(\beta\right)-
 *                      r_{iy}\cos\left(\alpha\right)\right]
 *  \f]
 *  Squaring this we get:
 *  \f[
 *    \left(r_i\times n\right)^2=r^2_{iy}\cos^2\left(\gamma\right)-
 *      2r_{iy}r_{iz}\cos\left(\beta\right)\cos\left(\gamma\right)+
 *      r^2_{iz}\cos^2\left(\beta\right)+
 *      r^2_{iz}\cos^2\left(\alpha\right)-
 *      r_{ix}r_{iz}\cos\left(\alpha\right)\cos\left(\gamma\right)+
 *      r^2_{ix}\cos^2\left(\gamma\right)+
 *      r^2_{ix}\cos^2\left(\beta\right)-
 *      r_{ix}r_{iy}\cos\left(\alpha\right)\cos\left(\beta\right)+
 *      r^2_{iy}\cos^2\left(\alpha\right)
 *  \f]
 *  Upon collecting \f$\cos\f$ terms:
 *  \f[
 *    \left(r_i\times n\right)^2=
 *      \left(r^2_{ix}+r^2_{iy}\right)\cos^2\left(\gamma\right)-
 *      2r_{iy}r_{iz}\cos\left(\beta\right)\cos\left(\gamma\right)+
 *      \left(r^2_{ix}+r^2_{iz}\right)\cos^2\left(\beta\right)-
 *      2r_{ix}r_{iz}\cos\left(\alpha\right)\cos\left(\gamma\right)-
 *      2r_{ix}r_{iy}\cos\left(\alpha\right)\cos\left(\beta\right)+
 *      \left(r^2_{iy}+r^2_{iz}\right)\cos^2\left(\alpha\right)
 *  \f]
 *  Defining:
 *  \f{eqnarray}{
 *     I_{xx}=&\sum_i^N m_i\left(r^2_{iy}+r^2_{iz}\right)\\
 *     I_{xy}=&-\sum_i^N m_ir_{ix}r_{iy}\\
 *     I_{xz}=&-\sum_i^N m_ir_{ix}r_{iz}\\
 *     I_{yy}=&\sum_i^N m_i\left(r^2_{ix}+r^2_{iz}\right)\\
 *     I_{yz}=&-\sum_i^N m_ir_{iy}r_{iz}\\
 *     I_{zz}=&\sum_i^Nm_i\left(r^2_{ix}+r^2_{iy}\right)
 *  \f}
 *  We can write:
 *  \f[
 *    I=\sum_i^Nm_i\left(r_i\times n\right)^2=
 *      I_{xx}\cos^2\left(\alpha\right)+
 *      I_{yy}\cos^2\left(\beta\right)+
 *      I_{zz}\cos^2\left(\gamma\right)+
 *      2I_{xy}\cos\left(\alpha\right)\cos\left(\beta\right)+
 *      2I_{xz}\cos\left(\alpha\right)\cos\left(\gamma\right)
 *      2I_{yz}\cos\left(\beta\right)\cos\left(\gamma\right)=
 *      n^T \mathbf{I} n,
 *  \f]
 *   where \f$\mathbf{I}\f$ is the inertia tensor.  Consequentially the
 *   inertial tensor is not simply the second moments of the mass distribution
 *   when their coordinates are expressed in terms of their initial coordinate
 *   system, but:
 *   \f[
 *      I_{pq}=\sum_i^Nm_ir^2_{i}\delta_{pq}-m_ir_{ip}r_{iq}
 *   \f]
 */
std::array<double,9> inertia_tensor(const System& Mol);

/** \relates System
 *  Prints a \mol to the ostream \p os
 *  \return the modified stream
 */
inline std::ostream& operator<<(std::ostream& os, const System& Mol)
{
    return Mol.print(os);
}

//! A map of systems (fragments, etc)
typedef std::map<std::string, System> SystemMap;

/** \relates System
 * Helper function that converts a system to Angstroms (for printing/debugging)
 *
 * \param [in] sys The System instance to convert to Angstroms
 * \return The same system, but in Angstroms
 */
System system_to_angstroms(const System& sys);

/** \relates System
 *
 *  We often want to move/manipulate one part of a system, this function is
 *  designed to facilitate that.  Given the \p full_system, the
 *  \p original_subsystem, and the \p new_subsystem this function returns a new
 *  full system where the original subsystem has been replaced by the new
 *  subsytem.  The returned system has a new Universe and is not affiliated with
 *  the any of the original systems.
 */
 inline System update_subsystem(const System& full_system,
         const System& original_subsystem,
         const System& new_subsystem)
 {
     size_t counter=0;
     return full_system.transform([&](const Atom& ai)
     {
         if(original_subsystem.count(ai))
             return *std::next(new_subsystem.begin(),counter++);
         else
             return ai;
     });
 }

///\name Operator overloads
///@{
/** \relates System
 *  \brief Makes \p lhs the union of itself and \p rhs.
 */
inline System& operator+=(System& lhs,const System& rhs)
{
    return lhs.union_assign(rhs);
}

/** \relates System
 *  \brief Makes \p lhs the intersection of itself and \p rhs.
 */
inline System& operator/=(System& lhs,const System& rhs)
{
    return lhs.intersection_assign(rhs);
}

/** \relates System
 *  \brief Makes \p lhs the set difference of itself and \p rhs.
 */
inline System& operator-=(System& lhs,const System& rhs)
{
    return lhs.difference_assign(rhs);
}

/** \relates System
 *  \brief returns the union of \p lhs and \p rhs.
 */
inline System operator+(const System& lhs,const System& rhs)
{
    return lhs.set_union(rhs);
}

/** \relates System
 *  \brief returns the intersection of \p lhs and \p rhs.
 */
inline System operator/(const System& lhs,const System& rhs)
{
    return lhs.intersection(rhs);
}

/** \relates System
 *  \brief returns the set difference of \p lhs and \p rhs.
 */
inline System operator-(const System& lhs,const System& rhs)
{
    return lhs.difference(rhs);
}

/** \relates System
 *  \brief returns true if \p lhs is a subset of \p rhs.
 */
inline bool operator<=(const System& lhs,const System& rhs)
{
    return lhs.is_subset_of(rhs);
}

/** \relates System
 *  \brief returns true if \p lhs is a proper subset of \p rhs.
 */
inline bool operator<(const System& lhs,const System& rhs)
{
    return lhs.is_proper_subset_of(rhs);
}

/** \relates System
 *  \brief returns true if \p lhs is a superset of \p rhs.
 */
inline bool operator>=(const System& lhs,const System& rhs)
{
    return lhs.is_superset_of(rhs);
}

/** \relates System
 *  \brief returns true if \p lhs is a proper superset of \p rhs.
 */
inline bool operator>(const System& lhs,const System& rhs)
{
    return lhs.is_proper_superset_of(rhs);
}
///@}

} // close namespace pulsar


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.net-->
<resources>
    <string name="app_name">Widget Calendário</string>
    <string name="today">Hoje</string>
    <string name="tomorrow">Amanhã</string>
    <string name="no_upcoming_events">Sem eventos futuros</string>
    <string name="widget_name">Calendário</string>
    <string name="open_prefs_desc">Configurações do widget calendário</string>
    <string name="add_event_desc">Adicionar novo evento no calendário</string>
    <string name="prefs_add_widget">Adicionar Widget</string>
    <string name="indicator_alarm">Indicador se um lembrete foi definido</string>
    <string name="indicator_recurring">Indicador se o evento é recorrente</string>
    <string name="no_title">(Sem título)</string>
    <string name="calendars_prefs">Calendários</string>
    <string name="calendars_prefs_desc">Selecionar os calendários visíveis</string>
    <string name="appearance_prefs">Aparência</string>
    <string name="appearance_prefs_desc">Ajustar a aparência do widget</string>
    <string name="appearance_text_size_title">Tamanho do texto</string>
    <string name="appearance_text_size_desc">Ajustar o tamanho do texto</string>
    <string name="appearance_text_size_very_small">Muito pequeno</string>
    <string name="appearance_text_size_small">Pequeno</string>
    <string name="appearance_text_size_medium">Médio</string>
    <string name="appearance_text_size_large">Grande</string>
    <string name="appearance_text_size_very_large">Muito grande</string>
    <string name="appearance_multiline_title_title">Título em múltiplas linhas</string>
    <string name="appearance_multiline_title_desc">Mostrar o título do evento em múltiplas linhas</string>
    <string name="appearance_date_format_desc">Mostrar as horas no formato am/pm ou no formato de 24 horas</string>
    <string name="appearance_date_format_title">Formato da data</string>
    <string name="appearance_date_format_auto">Automático</string>
    <string name="appearance_date_format_24">17:00</string>
    <string name="appearance_date_format_12">5:00 pm</string>
    <string name="appearance_display_header_title">Mostrar cabeçalho do widget</string>
    <string name="appearance_display_header_desc">Mostrar cabeçalho com data e configurações</string>
    <string name="appearance_display_header_warning">Ocultar o cabeçalho impede de voltar para as configurações.</string>
    <string name="appearance_group_color_title">Cores</string>
    <string name="appearance_background_color_title">Cor de fundo</string>
    <string name="appearance_background_color_desc">Ajustar a cor de fundo</string>
    <string name="appearance_day_header_alignment_desc">Definir o alinhamento do cabeçalho do dia</string>
    <string name="appearance_day_header_alignment_title">Alinhamento do cabeçalho do dia</string>
    <string name="appearance_day_header_alignment_left">Esquerda</string>
    <string name="appearance_day_header_alignment_center">Centro</string>
    <string name="appearance_day_header_alignment_right">Direita</string>
    <string name="appearance_header_theme_title">Sombra do cabeçalho do widget</string>
    <string name="appearance_header_theme_desc">Mostrar o cabeçalho do widget com sombra clara ou escura</string>
    <string name="appearance_entries_theme_title">Sombra do evento</string>
    <string name="appearance_entries_theme_desc">Mostrar o texto do evento com sombra clara ou escura</string>
    <string name="appearance_theme_black">Branco</string>
    <string name="appearance_theme_dark">Claro</string>
    <string name="appearance_theme_light">Escuro</string>
    <string name="appearance_theme_white">Preto</string>
    <string name="event_details_prefs">Eventos</string>
    <string name="event_details_prefs_desc">Configurar quais os detalhes a mostrar do evento</string>
    <string name="event_details_event_range_title">Intervalo de datas</string>
    <string name="event_details_event_range_desc">Configurar o número de eventos a mostrar</string>
    <string name="event_range_one_day">1 dia</string>
    <string name="event_range_one_week">1 semana</string>
    <string name="event_range_two_weeks">2 semanas</string>
    <string name="event_range_one_month">1 mês</string>
    <string name="event_range_two_months">2 meses</string>
    <string name="event_range_three_months">3 meses</string>
    <string name="event_range_six_months">6 meses</string>
    <string name="event_range_one_year">1 ano</string>
    <string name="event_details_show_end_time_title">Hora de fim</string>
    <string name="event_details_show_end_time_desc">Mostrar a hora de fim do evento</string>
    <string name="event_details_show_location_title">Mostrar localização</string>
    <string name="event_details_show_location_desc">Mostrar ou ocultar a localização do evento</string>
    <string name="event_details_fill_all_day_events_title">Preencher eventos que durem todo o dia</string>
    <string name="event_details_fill_all_day_events_desc">Mostrar uma entrada para cada dia, de um evento que dure todo o dia</string>
    <string name="event_details_indicators">Indicadores</string>
    <string name="event_details_indicate_alert_desc">Mostrar indicador de lembretes</string>
    <string name="event_details_indicate_alert_title">Lembretes</string>
    <string name="event_details_indicate_recurring_desc">Mostrar indicador de eventos recorrentes</string>
    <string name="event_details_indicate_recurring_title">Eventos recorrentes</string>
    <string name="feedback_prefs">Feedback</string>
    <string name="feedback_prefs_desc">Entrar em contacto connosco</string>
    <string name="feedback_github_desc">Fornecer feedback na página do projeto</string>
    <string name="feedback_github_title">Visitar a página do widget no Github</string>
    <string name="feedback_play_store_desc">Avaliar e comentar na Google Play Store</string>
    <string name="feedback_play_store_title">Visitar o widget na Google Play Store</string>
</resources>


text:
package edu.uci.ics.hyracks.storage.am.common.impls;

import edu.uci.ics.hyracks.storage.am.common.api.ITreeIndexTupleReference;
import edu.uci.ics.hyracks.storage.common.buffercache.ICachedPage;

public class NodeFrontier {
    public ICachedPage page;
    public int pageId;
    public ITreeIndexTupleReference lastTuple;

    public NodeFrontier(ITreeIndexTupleReference lastTuple) {
        this.lastTuple = lastTuple;
    }
}


text:
package io.crnk.client;

import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.MultivaluedMap;

import io.crnk.client.action.JerseyActionStubFactory;
import io.crnk.core.boot.CrnkProperties;
import io.crnk.rs.CrnkFeature;
import io.crnk.rs.JsonApiResponseFilter;
import io.crnk.rs.JsonapiExceptionMapperBridge;
import io.crnk.test.JerseyTestBase;
import io.crnk.test.mock.ClientTestModule;
import io.crnk.test.mock.repository.ProjectRepository;
import io.crnk.test.mock.repository.ProjectToTaskRepository;
import io.crnk.test.mock.repository.ScheduleRepositoryImpl;
import io.crnk.test.mock.repository.TaskRepository;
import io.crnk.test.mock.repository.TaskToProjectRepository;
import org.glassfish.jersey.jackson.JacksonFeature;
import org.glassfish.jersey.server.ResourceConfig;
import org.junit.Assert;
import org.junit.Before;

public abstract class AbstractClientTest extends JerseyTestBase {

	public CrnkClient client;

	protected TestApplication testApplication;

	@Before
	public void setup() {
		createClient();
		setupClient(client);

		cleanRepositories();

		Assert.assertNotNull(client.getActionStubFactory());
		Assert.assertNotNull(client.getModuleRegistry());
	}

	protected void createClient() {
		client = new CrnkClient(getBaseUri().toString());
		client.addModule(new ClientTestModule());
		// tag::jerseyStubFactory[]
		client.setActionStubFactory(JerseyActionStubFactory.newInstance());
		// end::jerseyStubFactory[]
		client.getHttpAdapter().setReceiveTimeout(10000000, TimeUnit.MILLISECONDS);
		client.getObjectMapper().findAndRegisterModules();
	}

	protected void setupClient(CrnkClient client) {

	}

	protected void cleanRepositories() {
		TaskRepository.clear();
		ProjectRepository.clear();
		TaskToProjectRepository.clear();
		ProjectToTaskRepository.clear();
		ScheduleRepositoryImpl.clear();
	}

	@Override
	protected TestApplication configure() {
		if (testApplication == null) {
			testApplication = new TestApplication();
		}
		return testApplication;
	}

	protected void setupFeature(CrnkTestFeature feature) {
		// nothing to do
	}

	/**
	 * Assert the specified header name has the specified value.
	 */
	protected void assertHasHeaderValue(String name, String value) {
		MultivaluedMap<String, String> headers = getLastReceivedHeaders();
		Assert.assertNotNull(headers);

		List<String> values = headers.get(name);
		Assert.assertNotNull(values);

		Assert.assertTrue(values.toString(), values.contains(value));
	}

	/**
	 * Clear the last received headers.
	 */
	protected void clearLastReceivedHeaders() {
		getTestFilter().clearLastReceivedHeaders();
	}

	/**
	 * Return the last received headers.
	 */
	private MultivaluedMap<String, String> getLastReceivedHeaders() {
		return getTestFilter().getLastReceivedHeaders();
	}

	/**
	 * Return the configured test filter.
	 */
	private TestRequestFilter getTestFilter() {
		return ((CrnkTestFeature) testApplication.getFeature()).getTestFilter();
	}

	@ApplicationPath("/")
	public class TestApplication extends ResourceConfig {

		private CrnkTestFeature feature;

		public TestApplication() {
			this(false, false);
		}

		public TestApplication(boolean jsonApiFilter, boolean serializeLinksAsObjects) {
			property(CrnkProperties.SERIALIZE_LINKS_AS_OBJECTS, Boolean.toString(serializeLinksAsObjects));

			feature = new CrnkTestFeature();
			feature.getObjectMapper().findAndRegisterModules();

			feature.addModule(new io.crnk.test.mock.TestModule());
			feature.addModule(new ClientTestModule());

			if (jsonApiFilter) {
				register(new JsonApiResponseFilter(feature));
				register(new JsonapiExceptionMapperBridge(feature));
				register(new JacksonFeature());
			}

			setupFeature(feature);

			register(feature);
		}

		public CrnkFeature getFeature() {
			return feature;
		}
	}
}


text:
/**
 * @file uint256_extensions.h
 *
 * This file provides helper to handle uint256 calculations.
 */

#ifndef BITCOIN_OMNICORE_UINT256_EXTENSIONS_H
#define BITCOIN_OMNICORE_UINT256_EXTENSIONS_H

#include <arith_uint256.h>

#include <assert.h>
#include <stdint.h>
#include <limits>

namespace mastercore {
namespace uint256_const {
//! The number 1 as uint256
static const arith_uint256 one(static_cast<uint64_t>(1));
//! The highest number in range of int64_t as uint256
static const arith_uint256 max_int64(static_cast<uint64_t>(std::numeric_limits<int64_t>::max()));
}

/**
 * Returns a mod n.
 */
inline arith_uint256 Modulo256(const arith_uint256& a, const arith_uint256& n)
{
    return (a - (n * (a / n)));
}

/**
 * Converts a positive primitive number to uint256.
 */
template<typename NumberT>
inline arith_uint256 ConvertTo256(const NumberT& number)
{
    assert(number >= 0);
    return arith_uint256(static_cast<uint64_t>(number));
}

/**
 * Converts an uint256 to int64_t.
 */
inline int64_t ConvertTo64(const arith_uint256& number)
{
    assert(number <= uint256_const::max_int64);
    return static_cast<int64_t>(number.GetLow64());
}

/**
 * Returns ceil(numerator / denominator).
 */
inline arith_uint256 DivideAndRoundUp(const arith_uint256& numerator, const arith_uint256& denominator)
{
    if (numerator == 0) {
        return arith_uint256(0);
    }
    return uint256_const::one + (numerator - uint256_const::one) / denominator;
}

} // namespace mastercore

#endif // BITCOIN_OMNICORE_UINT256_EXTENSIONS_H


text:
require 'nokogiri'

require_relative '../helpers/constants.rb'
require_relative '../objects/module'
require_relative 'system_reader.rb'

class ModuleReader

  # reads in all bases
  def self.read_bases
    return read_modules('base', BASES_DIR, BASE_SCHEMA_FILE, false)
  end

  # reads in all build modules
  def self.read_builds
    return read_modules('build', BUILDS_DIR, BUILDS_SCHEMA_FILE, true)
  end

  # reads in all vulnerability modules
  def self.read_vulnerabilities
    return read_modules('vulnerability', VULNERABILITIES_DIR, VULNERABILITY_SCHEMA_FILE, true)
  end

  # reads in all services
  def self.read_services
    return read_modules('service', SERVICES_DIR, SERVICE_SCHEMA_FILE, true)
  end

  # reads in all utilities
  def self.read_utilities
    return read_modules('utility', UTILITIES_DIR, UTILITY_SCHEMA_FILE, true)
  end

  # reads in all utilities
  def self.read_generators
    return read_modules('generator', GENERATORS_DIR, GENERATOR_SCHEMA_FILE, true)
  end

  # reads in all utilities
  def self.read_encoders
    return read_modules('encoder', ENCODERS_DIR, ENCODER_SCHEMA_FILE, true)
  end

  # reads in all networks
  def self.read_networks
    return read_modules('network', NETWORKS_DIR, NETWORK_SCHEMA_FILE, false)
  end

  # reads in xml files to create modules
  # @param [Object] module_type 'vulnerability', 'base', etc
  # @param [Object] modules_dir ROOT_DIR path leading to 'modules/'
  # @param [Object] schema_file the xml schema that defines this type of module
  # @param [Object] require_puppet whether this kind of HBCTF-Battlegrounds module has puppet code
  # @return [Object] the list of modules read
  def self.read_modules(module_type, modules_dir, schema_file, require_puppet)
    modules = []
    Dir.glob("#{modules_dir}**/**/HBCTF-Battlegrounds_metadata.xml").each do |file|
      module_path, module_filename = nil
      match = file.match(/#{ROOT_DIR}\/(.*?([^\/]*))\/HBCTF-Battlegrounds_metadata.xml/i)
      if match.captures.size == 2
        module_path, module_filename = match.captures
      else
        Print.err "Unexpected error extracting module path from #{file}"
        exit
      end

      Print.verbose "Reading #{module_type}: #{module_path}"
      doc, xsd = nil
      begin
        doc = Nokogiri::XML(File.read(file))
      rescue
        Print.err "Failed to read #{module_type} metadata file (#{file})"
        exit
      end

      # validate scenario XML against schema
      begin
        xsd = Nokogiri::XML::Schema(File.read(schema_file))
        xsd.validate(doc).each do |error|
          Print.err "Error in #{module_type} metadata file (#{file}):"
          Print.err '    ' + error.message
          exit
        end
      rescue Exception => e
        Print.err "Failed to validate #{module_type} metadata file (#{file}): against schema (#{schema_file})"
        Print.err e.message
        exit
      end

      # remove xml namespaces for ease of processing
      doc.remove_namespaces!

      new_module = Module.new(module_type)
      # save module path (and as an attribute for filtering)
      new_module.module_path = module_path
      new_module.attributes['module_path'] = [module_path]

      new_module.puppet_file = "#{ROOT_DIR}/#{module_path}/#{module_filename}.pp"
      new_module.puppet_other_path = "#{ROOT_DIR}/#{module_path}/manifests"

      # save executable path of any pre-calculation for outputs
      local = "#{module_path}#{MODULE_LOCAL_CALC_DIR}"
      if File.file?(local)
        new_module.local_calc_file = local
      end

      # check that the expected puppet files exist
      if require_puppet
        unless File.file?("#{new_module.puppet_file}")
          Print.err "Module #{module_path} missing required puppet init file (#{new_module.puppet_file})"
          exit
        end

        unless File.exists?("#{new_module.puppet_other_path}")
          Print.err "Module #{module_path} missing required puppet module manifests folder (#{new_module.puppet_other_path})"
          exit
        end
      end

      # for each element in the vulnerability
      doc.xpath("/#{module_type}/*").each do |module_doc|

        # new_module.attributes[module_doc.name] = module_doc.content

        # creates the array if null
        (new_module.attributes[module_doc.name] ||= []).push(module_doc.content)

      end

      # for each conflict in the module
      doc.xpath("/#{module_type}/conflict").each do |conflict_doc|
        conflict = {}
        conflict_doc.elements.each {|node|
          (conflict[node.name] ||= []).push(node.content)
        }
        new_module.conflicts.push(conflict)
      end

      # for each dependency in the module
      doc.xpath("/#{module_type}/requires").each do |requires_doc|
        require = {}
        requires_doc.elements.each {|node|
          (require[node.name] ||= []).push(node.content)
        }
        new_module.requires.push(require)
      end

      # for each default input
      doc.xpath("/#{module_type}/default_input").each do |inputs_doc|
        inputs_doc.xpath('descendant::vulnerability | descendant::service | descendant::utility | descendant::network | descendant::base | descendant::encoder | descendant::generator').each do |module_node|

          # create a selector module, which is a regular module instance used as a placeholder for matching requirements
          module_selector = Module.new(module_node.name)

          # create a unique id for tracking variables between modules
          module_selector.unique_id = "#{module_node.path}#{module_path}".gsub(/[^a-zA-Z0-9]/, '')
          # check if we need to be sending the module output to another module
          module_node.xpath('parent::input').each do |input|
            # Parent is input -- track that we need to send write value somewhere
            input.xpath('..').each do |input_parent|
              module_selector.write_output_variable = input.xpath('@into').to_s
              module_selector.write_to_module_with_id = "#{input_parent.path}#{module_path}".gsub(/[^a-zA-Z0-9]/, '')
            end
          end
          if module_node.xpath('parent::default_input').to_s != ''
            # input for this module -- track that we need to send write value to the module itself
            module_selector.write_output_variable = module_node.xpath('parent::default_input/@into').to_s

            module_selector.write_to_module_with_id = 'vulnerabilitydefaultinput'
          end

          # check if we are being passed an input *literal value*, into a module selector
          module_node.xpath('input/value').each do |input_value|
            variable = input_value.xpath('../@into').to_s
            value = input_value.text
            (module_selector.received_inputs[variable] ||= []).push(value)
          end

          into = module_node.xpath('ancestor::default_input/@into').to_s

          (new_module.default_inputs_selectors["#{into}"] ||= []).unshift(module_selector)

          module_node.xpath('@*').each do |attr|
            module_selector.attributes["#{attr.name}"] = [attr.text] unless attr.text.nil? || attr.text == ''
          end
          Print.verbose " #{module_node.name} (#{module_selector.unique_id}), selecting based on:"
          module_selector.attributes.each do |attr|
            if attr[0] && attr[1] && attr[0].to_s != "module_type"
              Print.verbose "  - #{attr[0].to_s} ~= #{attr[1].to_s}"
            end
          end
        end

        # check if we are being passed an input *literal value* -- to the containing module's default_value itself (as opposed to a module selector)
        inputs_doc.xpath('value').each do |input_value|
          variable = input_value.xpath('parent::default_input/@into').to_s
          value = input_value.text

          (new_module.default_inputs_literals[variable] ||= []).push(value)
        end
      end

      modules.push(new_module)
    end

    return modules
  end

end


text:
package com.buptnu.mediaplayer;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import net.micode.fileexplorer.R;

public class CategoryBar extends View {
    private static final String LOG_TAG = "CategoryBar";

    private static final int MARGIN = 12;

    private static final int ANI_TOTAL_FRAMES = 10;

    private static final int ANI_PERIOD = 100;
    private Timer timer;

    private class Category {
        public long value;

        public long tmpValue; // used for animation

        public long aniStep; // animation step

        public int resImg;
    }

    private ArrayList<Category> categories = new ArrayList<Category>();

    private long mFullValue;

    public void setFullValue(long value) {
        mFullValue = value;
    }

    public CategoryBar(Context context) {
        this(context, null);
    }

    public CategoryBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CategoryBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void addCategory(int categoryImg) {
        Category ca = new Category();
        ca.resImg = categoryImg;
        categories.add(ca);
    }

    public boolean setCategoryValue(int index, long value) {
        if (index < 0 || index >= categories.size())
            return false;
        categories.get(index).value = value;
        invalidate();
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        Drawable d = getDrawable(R.drawable.category_bar_empty);

        int width = getWidth() - MARGIN * 2;
        int height = getHeight() - MARGIN * 2;
        boolean isHorizontal = (width > height);

        Rect bounds = null;
        if ( isHorizontal )
            bounds = new Rect(MARGIN, 0, MARGIN + width, d.getIntrinsicHeight());
        else
            bounds = new Rect(0, MARGIN, d.getIntrinsicWidth(), MARGIN + height);

        int beginning = MARGIN;
        if ( !isHorizontal ) beginning += height;
        d.setBounds(bounds);
        d.draw(canvas);
        if (mFullValue != 0) {
            for (Category c : categories) {
                long value = (timer == null ? c.value : c.tmpValue);
                if ( isHorizontal ) {
                    int w = (int) (value * width / mFullValue);
                    if (w == 0)
                        continue;
                    bounds.left = beginning;
                    bounds.right = beginning + w;
                    d = getDrawable(c.resImg);
                    bounds.bottom = bounds.top + d.getIntrinsicHeight();
                    d.setBounds(bounds);
                    d.draw(canvas);
                    beginning += w;
                }
                else {
                    int h = (int) (value * height / mFullValue);
                    if (h == 0)
                        continue;
                    bounds.bottom = beginning;
                    bounds.top = beginning - h;
                    d = getDrawable(c.resImg);
                    bounds.right = bounds.left + d.getIntrinsicWidth();
                    d.setBounds(bounds);
                    d.draw(canvas);
                    beginning -= h;
                }
            }
        }
        if ( isHorizontal ) {
            bounds.left = 0;
            bounds.right = bounds.left + getWidth();
        }
        else {
            bounds.top = 0;
            bounds.bottom = bounds.top + getHeight();
        }
        d = getDrawable(R.drawable.category_bar_mask);
        d.setBounds(bounds);
        d.draw(canvas);
    }

    private Drawable getDrawable(int id) {
        return getContext().getResources().getDrawable(id);
    }

    private void stepAnimation() {
        if (timer == null)
            return;

        int finished = 0;
        for (Category c : categories) {
            c.tmpValue += c.aniStep;
            if (c.tmpValue >= c.value) {
                c.tmpValue = c.value;
                finished++;
                if (finished >= categories.size()) {
                    // stop animation
                    timer.cancel();
                    timer = null;
                    Log.v(LOG_TAG, "Animation stopped");
                    break;
                }
            }
        }

        postInvalidate();
    }

    synchronized public void startAnimation() {
        if (timer != null) {
            return;
        }

        Log.v(LOG_TAG, "startAnimation");

        for (Category c : categories) {
            c.tmpValue = 0;
            c.aniStep = c.value / ANI_TOTAL_FRAMES;
        }

        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {

            public void run() {
                stepAnimation();
            }

        }, 0, ANI_PERIOD);
    }
}