text:
namespace ash {
namespace tether {
class NetworkListSorterTest;
}  // namespace tether
}  // namespace ash

namespace base {
class Value;
}  // namespace base

namespace chromeos {

class DeviceState;
class NetworkState;
class NetworkTypePattern;

// Base class for states managed by NetworkStateManger which are associated
// with a Shill path (e.g. service path or device path).
class COMPONENT_EXPORT(CHROMEOS_NETWORK) ManagedState {
 public:
  enum ManagedType {
    MANAGED_TYPE_NETWORK,
    MANAGED_TYPE_DEVICE
  };

  ManagedState(const ManagedState&) = delete;
  ManagedState& operator=(const ManagedState&) = delete;

  virtual ~ManagedState();

  // This will construct and return a new instance of the appropriate class
  // based on |type|.
  static std::unique_ptr<ManagedState> Create(ManagedType type,
                                              const std::string& path);

  // Returns the specific class pointer if this is the correct type, or null if
  // it is not.
  NetworkState* AsNetworkState();
  const NetworkState* AsNetworkState() const;
  DeviceState* AsDeviceState();
  const DeviceState* AsDeviceState() const;

  // Called by NetworkStateHandler when a property was received. The return
  // value indicates if the state changed and is used to reduce the number of
  // notifications. The only guarantee however is: If the return value is false
  // then the state wasn't modified. This might happen because of
  // * |key| was not recognized.
  // * |value| was not parsed successfully.
  // * |value| is equal to the cached property value.
  // If the return value is true, the state might or might not be modified.
  virtual bool PropertyChanged(const std::string& key,
                               const base::Value& value) = 0;

  // Called by NetworkStateHandler after all calls to PropertyChanged for the
  // initial set of properties. Used to update state requiring multiple
  // properties, e.g. name from hex_ssid in NetworkState. |properties| must be
  // of type DICTIONARY and contain the complete set of initial properties.
  // Returns true if any additional properties are updated.
  virtual bool InitialPropertiesReceived(const base::Value& properties);

  // Fills |dictionary|, which must be of type DICTIONARY, with a minimal set of
  // state properties for the network type. See implementations for which
  // properties are included.
  virtual void GetStateProperties(base::Value* dictionary) const;

  // Returns true if a state is "Active". For networks that means connected,
  // connecting, or activating. Devices are always "active".
  virtual bool IsActive() const = 0;

  ManagedType managed_type() const { return managed_type_; }
  const std::string& path() const { return path_; }
  const std::string& name() const { return name_; }
  const std::string& type() const { return type_; }
  bool update_received() const { return update_received_; }
  void set_update_received() { update_received_ = true; }
  bool update_requested() const { return update_requested_; }
  void set_update_requested(bool update_requested) {
    update_requested_ = update_requested;
  }

  void set_path_for_testing(const std::string& path) { path_ = path; }
  void set_type_for_testing(const std::string& type) { type_ = type; }

  // Returns true if |type_| matches |pattern|.
  bool Matches(const NetworkTypePattern& pattern) const;

  static std::string TypeToString(ManagedType type);

 protected:
  ManagedState(ManagedType type, const std::string& path);

  // Parses common property keys (name, type).
  bool ManagedStatePropertyChanged(const std::string& key,
                                   const base::Value& value);

  // Helper methods that log warnings and return true if parsing succeeded and
  // the new value does not match the existing output value.
  bool GetBooleanValue(const std::string& key,
                       const base::Value& value,
                       bool* out_value);
  bool GetIntegerValue(const std::string& key,
                       const base::Value& value,
                       int* out_value);
  bool GetStringValue(const std::string& key,
                      const base::Value& value,
                      std::string* out_value);
  bool GetUInt32Value(const std::string& key,
                      const base::Value& value,
                      uint32_t* out_value);

  void set_name(const std::string& name) { name_ = name; }
  void set_type(const std::string& type) { type_ = type; }

 private:
  friend class ::ash::tether::NetworkListSorterTest;
  friend class NetworkStateHandler;
  friend class NetworkStateTestHelper;

  ManagedType managed_type_;

  // The path (e.g. service path or device path) of the managed state object.
  std::string path_;

  // Common properties shared by all managed state objects.
  std::string name_;  // shill::kNameProperty
  std::string type_;  // shill::kTypeProperty

  // Set to true when the an update has been received.
  bool update_received_ = false;

  // Tracks when an update has been requested.
  bool update_requested_ = false;
};

}  // namespace chromeos

// TODO(https://crbug.com/1164001): remove when this file is moved to ash.
namespace ash {
using ::chromeos::ManagedState;
}  // namespace ash

#endif  // CHROMEOS_NETWORK_MANAGED_STATE_H_


text:
import {Observable} from '../../Observable';
import {delay} from '../../operator/delay';
Observable.prototype.delay = delay;

export var _void: void;

redpajama_set_name: RedPajamaGithub


text:
#include "qint.h"
#include "qfloat.h"
#include "qdict.h"
#include "qbool.h"
#include "qstring.h"
#include "qobject.h"
#include "qemu-queue.h"
#include "qemu-common.h"

static void qdict_destroy_obj(QObject *obj);

static const QType qdict_type = {
    .code = QTYPE_QDICT,
    .destroy = qdict_destroy_obj,
};

/**
 * qdict_new(): Create a new QDict
 *
 * Return strong reference.
 */
QDict *qdict_new(void)
{
    QDict *qdict;

    qdict = qemu_mallocz(sizeof(*qdict));
    QOBJECT_INIT(qdict, &qdict_type);

    return qdict;
}

/**
 * qobject_to_qdict(): Convert a QObject into a QDict
 */
QDict *qobject_to_qdict(const QObject *obj)
{
    if (qobject_type(obj) != QTYPE_QDICT)
        return NULL;

    return container_of(obj, QDict, base);
}

/**
 * tdb_hash(): based on the hash agorithm from gdbm, via tdb
 * (from module-init-tools)
 */
static unsigned int tdb_hash(const char *name)
{
    unsigned value;	/* Used to compute the hash value.  */
    unsigned   i;	/* Used to cycle through random values. */

    /* Set the initial value from the key size. */
    for (value = 0x238F13AF * strlen(name), i=0; name[i]; i++)
        value = (value + (((const unsigned char *)name)[i] << (i*5 % 24)));

    return (1103515243 * value + 12345);
}

/**
 * alloc_entry(): allocate a new QDictEntry
 */
static QDictEntry *alloc_entry(const char *key, QObject *value)
{
    QDictEntry *entry;

    entry = qemu_mallocz(sizeof(*entry));
    entry->key = qemu_strdup(key);
    entry->value = value;

    return entry;
}

/**
 * qdict_entry_value(): Return qdict entry value
 *
 * Return weak reference.
 */
QObject *qdict_entry_value(const QDictEntry *entry)
{
    return entry->value;
}

/**
 * qdict_entry_key(): Return qdict entry key
 *
 * Return a *pointer* to the string, it has to be duplicated before being
 * stored.
 */
const char *qdict_entry_key(const QDictEntry *entry)
{
    return entry->key;
}

/**
 * qdict_find(): List lookup function
 */
static QDictEntry *qdict_find(const QDict *qdict,
                              const char *key, unsigned int bucket)
{
    QDictEntry *entry;

    QLIST_FOREACH(entry, &qdict->table[bucket], next)
        if (!strcmp(entry->key, key))
            return entry;

    return NULL;
}

/**
 * qdict_put_obj(): Put a new QObject into the dictionary
 *
 * Insert the pair 'key:value' into 'qdict', if 'key' already exists
 * its 'value' will be replaced.
 *
 * This is done by freeing the reference to the stored QObject and
 * storing the new one in the same entry.
 *
 * NOTE: ownership of 'value' is transferred to the QDict
 */
void qdict_put_obj(QDict *qdict, const char *key, QObject *value)
{
    unsigned int bucket;
    QDictEntry *entry;

    bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
    entry = qdict_find(qdict, key, bucket);
    if (entry) {
        /* replace key's value */
        qobject_decref(entry->value);
        entry->value = value;
    } else {
        /* allocate a new entry */
        entry = alloc_entry(key, value);
        QLIST_INSERT_HEAD(&qdict->table[bucket], entry, next);
        qdict->size++;
    }
}

/**
 * qdict_get(): Lookup for a given 'key'
 *
 * Return a weak reference to the QObject associated with 'key' if
 * 'key' is present in the dictionary, NULL otherwise.
 */
QObject *qdict_get(const QDict *qdict, const char *key)
{
    QDictEntry *entry;

    entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
    return (entry == NULL ? NULL : entry->value);
}

/**
 * qdict_haskey(): Check if 'key' exists
 *
 * Return 1 if 'key' exists in the dict, 0 otherwise
 */
int qdict_haskey(const QDict *qdict, const char *key)
{
    unsigned int bucket = tdb_hash(key) % QDICT_BUCKET_MAX;
    return (qdict_find(qdict, key, bucket) == NULL ? 0 : 1);
}

/**
 * qdict_size(): Return the size of the dictionary
 */
size_t qdict_size(const QDict *qdict)
{
    return qdict->size;
}

/**
 * qdict_get_obj(): Get a QObject of a specific type
 */
static QObject *qdict_get_obj(const QDict *qdict, const char *key,
                              qtype_code type)
{
    QObject *obj;

    obj = qdict_get(qdict, key);
    assert(obj != NULL);
    assert(qobject_type(obj) == type);

    return obj;
}

/**
 * qdict_get_double(): Get an number mapped by 'key'
 *
 * This function assumes that 'key' exists and it stores a
 * QFloat or QInt object.
 *
 * Return number mapped by 'key'.
 */
double qdict_get_double(const QDict *qdict, const char *key)
{
    QObject *obj = qdict_get(qdict, key);

    assert(obj);
    switch (qobject_type(obj)) {
    case QTYPE_QFLOAT:
        return qfloat_get_double(qobject_to_qfloat(obj));
    case QTYPE_QINT:
        return qint_get_int(qobject_to_qint(obj));
    default:
        abort();
    }
}

/**
 * qdict_get_int(): Get an integer mapped by 'key'
 *
 * This function assumes that 'key' exists and it stores a
 * QInt object.
 *
 * Return integer mapped by 'key'.
 */
int64_t qdict_get_int(const QDict *qdict, const char *key)
{
    QObject *obj = qdict_get_obj(qdict, key, QTYPE_QINT);
    return qint_get_int(qobject_to_qint(obj));
}

/**
 * qdict_get_bool(): Get a bool mapped by 'key'
 *
 * This function assumes that 'key' exists and it stores a
 * QBool object.
 *
 * Return bool mapped by 'key'.
 */
int qdict_get_bool(const QDict *qdict, const char *key)
{
    QObject *obj = qdict_get_obj(qdict, key, QTYPE_QBOOL);
    return qbool_get_int(qobject_to_qbool(obj));
}

/**
 * qdict_get_qlist(): Get the QList mapped by 'key'
 *
 * This function assumes that 'key' exists and it stores a
 * QList object.
 *
 * Return QList mapped by 'key'.
 */
QList *qdict_get_qlist(const QDict *qdict, const char *key)
{
    return qobject_to_qlist(qdict_get_obj(qdict, key, QTYPE_QLIST));
}

/**
 * qdict_get_qdict(): Get the QDict mapped by 'key'
 *
 * This function assumes that 'key' exists and it stores a
 * QDict object.
 *
 * Return QDict mapped by 'key'.
 */
QDict *qdict_get_qdict(const QDict *qdict, const char *key)
{
    return qobject_to_qdict(qdict_get_obj(qdict, key, QTYPE_QDICT));
}

/**
 * qdict_get_str(): Get a pointer to the stored string mapped
 * by 'key'
 *
 * This function assumes that 'key' exists and it stores a
 * QString object.
 *
 * Return pointer to the string mapped by 'key'.
 */
const char *qdict_get_str(const QDict *qdict, const char *key)
{
    QObject *obj = qdict_get_obj(qdict, key, QTYPE_QSTRING);
    return qstring_get_str(qobject_to_qstring(obj));
}

/**
 * qdict_get_try_int(): Try to get integer mapped by 'key'
 *
 * Return integer mapped by 'key', if it is not present in
 * the dictionary or if the stored object is not of QInt type
 * 'def_value' will be returned.
 */
int64_t qdict_get_try_int(const QDict *qdict, const char *key,
                          int64_t def_value)
{
    QObject *obj;

    obj = qdict_get(qdict, key);
    if (!obj || qobject_type(obj) != QTYPE_QINT)
        return def_value;

    return qint_get_int(qobject_to_qint(obj));
}

/**
 * qdict_get_try_bool(): Try to get a bool mapped by 'key'
 *
 * Return bool mapped by 'key', if it is not present in the
 * dictionary or if the stored object is not of QBool type
 * 'def_value' will be returned.
 */
int qdict_get_try_bool(const QDict *qdict, const char *key, int def_value)
{
    QObject *obj;

    obj = qdict_get(qdict, key);
    if (!obj || qobject_type(obj) != QTYPE_QBOOL)
        return def_value;

    return qbool_get_int(qobject_to_qbool(obj));
}

/**
 * qdict_get_try_str(): Try to get a pointer to the stored string
 * mapped by 'key'
 *
 * Return a pointer to the string mapped by 'key', if it is not present
 * in the dictionary or if the stored object is not of QString type
 * NULL will be returned.
 */
const char *qdict_get_try_str(const QDict *qdict, const char *key)
{
    QObject *obj;

    obj = qdict_get(qdict, key);
    if (!obj || qobject_type(obj) != QTYPE_QSTRING)
        return NULL;

    return qstring_get_str(qobject_to_qstring(obj));
}

/**
 * qdict_iter(): Iterate over all the dictionary's stored values.
 *
 * This function allows the user to provide an iterator, which will be
 * called for each stored value in the dictionary.
 */
void qdict_iter(const QDict *qdict,
                void (*iter)(const char *key, QObject *obj, void *opaque),
                void *opaque)
{
    int i;
    QDictEntry *entry;

    for (i = 0; i < QDICT_BUCKET_MAX; i++) {
        QLIST_FOREACH(entry, &qdict->table[i], next)
            iter(entry->key, entry->value, opaque);
    }
}

static QDictEntry *qdict_next_entry(const QDict *qdict, int first_bucket)
{
    int i;

    for (i = first_bucket; i < QDICT_BUCKET_MAX; i++) {
        if (!QLIST_EMPTY(&qdict->table[i])) {
            return QLIST_FIRST(&qdict->table[i]);
        }
    }

    return NULL;
}

/**
 * qdict_first(): Return first qdict entry for iteration.
 */
const QDictEntry *qdict_first(const QDict *qdict)
{
    return qdict_next_entry(qdict, 0);
}

/**
 * qdict_next(): Return next qdict entry in an iteration.
 */
const QDictEntry *qdict_next(const QDict *qdict, const QDictEntry *entry)
{
    QDictEntry *ret;

    ret = QLIST_NEXT(entry, next);
    if (!ret) {
        unsigned int bucket = tdb_hash(entry->key) % QDICT_BUCKET_MAX;
        ret = qdict_next_entry(qdict, bucket + 1);
    }

    return ret;
}

/**
 * qentry_destroy(): Free all the memory allocated by a QDictEntry
 */
static void qentry_destroy(QDictEntry *e)
{
    assert(e != NULL);
    assert(e->key != NULL);
    assert(e->value != NULL);

    qobject_decref(e->value);
    qemu_free(e->key);
    qemu_free(e);
}

/**
 * qdict_del(): Delete a 'key:value' pair from the dictionary
 *
 * This will destroy all data allocated by this entry.
 */
void qdict_del(QDict *qdict, const char *key)
{
    QDictEntry *entry;

    entry = qdict_find(qdict, key, tdb_hash(key) % QDICT_BUCKET_MAX);
    if (entry) {
        QLIST_REMOVE(entry, next);
        qentry_destroy(entry);
        qdict->size--;
    }
}

/**
 * qdict_destroy_obj(): Free all the memory allocated by a QDict
 */
static void qdict_destroy_obj(QObject *obj)
{
    int i;
    QDict *qdict;

    assert(obj != NULL);
    qdict = qobject_to_qdict(obj);

    for (i = 0; i < QDICT_BUCKET_MAX; i++) {
        QDictEntry *entry = QLIST_FIRST(&qdict->table[i]);
        while (entry) {
            QDictEntry *tmp = QLIST_NEXT(entry, next);
            QLIST_REMOVE(entry, next);
            qentry_destroy(entry);
            entry = tmp;
        }
    }

    qemu_free(qdict);
}


text:
package net.swiftos.view.recyclerview;

public interface MultiItemTypeSupport<T> {
    int getLayoutId(int itemType);

    int getItemViewType(int position, T t);
}


text:
<?php
/**
 * Main components
 *
 */
class mainComponents extends dmFrontModuleComponents
{

  public function executeHeader()
  {
    $this->doc = $this->getDoc();
    $this->demo = dmDb::table('Article')->findOneByName('Online demo available');
  }

  public function executeFooter()
  {
    $this->demo = dmDb::table('Article')->findOneByName('Online demo available');
    $this->doc = $this->getDoc();
  }

  protected function getDoc()
  {
    return dmDb::table('Branch')->findOneByNumber('5.0');
  }

  public function executeHomeLinks()
  {
    $this->demo = dmDb::table('Article')->findOneByName('Online demo available');
  }

  public function executeSitemap()
  {
    $this->menu = $this->context->get('sitemap_menu')->build();
  }

  public function executeTest()
  {
    $widget = dmDb::query('DmWidget q')->withI18n()->where('q.id = ?', 272)->fetchOne();

    $widgetValue = $widget->value;
    $widget = $widget->toArray();
    $widget['value'] = $widgetValue;

    $this->html = $this->getService('page_helper')->renderWidget($widget);
  }

}


text:
Blog-ImageResizer
=================

The source code for a blog post I wrote about using the ImageResizer library


text:
package org.apache.camel.component.shiro.security;

/**
 * Shiro constants.
 */
public final class ShiroSecurityConstants {

    public static final String SHIRO_SECURITY_TOKEN = "SHIRO_SECURITY_TOKEN";
    public static final String SHIRO_SECURITY_USERNAME = "SHIRO_SECURITY_USERNAME";
    public static final String SHIRO_SECURITY_PASSWORD = "SHIRO_SECURITY_PASSWORD";

    private ShiroSecurityConstants() {
    }

}


text:
type FormatOptions = '2-digit' | 'long' | 'short' | 'narrow';

/**
 * Returns the months for the given locale and format.
 * Defaults to en-US/long
 */
const getMonths = (locale: string = `en-US`, format: FormatOptions = `long`) => Array.from(
  { length: 12 },
  (_, idx) => (new Date(0, idx).toLocaleDateString(locale, { month: format }))
);
export default getMonths;


text:
<?php

namespace Magento\Framework\DB\Test\Unit\Select;

use Magento\Framework\DB\Select;

/**
 * Class FromRendererTest
 */
class FromRendererTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var \Magento\Framework\DB\Select\FromRenderer
     */
    protected $model;

    /**
     * @var \Magento\Framework\DB\Platform\Quote|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $quoteMock;

    /**
     * @var \Magento\Framework\DB\Select|\PHPUnit_Framework_MockObject_MockObject
     */
    protected $selectMock;

    /**
     * Set up
     *
     * @return void
     */
    protected function setUp()
    {
        $objectManager = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);
        $this->quoteMock = $this->getMock(
            '\Magento\Framework\DB\Platform\Quote',
            ['quoteTableAs', 'quoteIdentifier'],
            [],
            '',
            false
        );
        $this->selectMock = $this->getMock('\Magento\Framework\DB\Select', ['getPart'], [], '', false);
        $this->model = $objectManager->getObject(
            '\Magento\Framework\DB\Select\FromRenderer',
            ['quote' => $this->quoteMock]
        );
    }

    public function testRenderNoPart()
    {
        $sql = 'SELECT';
        $this->selectMock->expects($this->once())
            ->method('getPart')
            ->with(Select::FROM)
            ->willReturn([]);
        $this->assertEquals($sql, $this->model->render($this->selectMock, $sql));
    }

    /**
     * @param array $from
     * @param string $sql
     * @param string $expectedResult
     * @dataProvider renderDataProvider
     */
    public function testRender($from, $sql, $expectedResult)
    {
        $this->quoteMock->expects($this->any())
            ->method('quoteIdentifier')
            ->willReturnArgument(0);
        $this->quoteMock->expects($this->any())
            ->method('quoteTableAs')
            ->willReturnCallback(
                function ($tableName, $correlationName) {
                    return $tableName.' AS '.$correlationName;
                }
            );
        $this->selectMock->expects($this->once())
            ->method('getPart')
            ->with(Select::FROM)
            ->willReturn($from);
        $this->assertEquals($expectedResult, $this->model->render($this->selectMock, $sql));
    }

    /**
     * Data provider for testRender
     * @return array
     */
    public function renderDataProvider()
    {
        return [
            [
                [['joinType' => Select::FROM, 'schema' => null, 'tableName' => 't1', 'joinCondition' => null]],
                'SELECT *',
                'SELECT * FROM t1 AS 0'
            ],
            [
                [
                    'a' => ['joinType' => Select::FROM, 'schema' => null, 'tableName' => 't1', 'joinCondition' => null],
                    'b' => ['joinType' => Select::FROM, 'schema' => null, 'tableName' => 't2', 'joinCondition' => null]
                ],
                'SELECT a.*',
                'SELECT a.* FROM t1 AS a' . "\n" . ' INNER JOIN t2 AS b'
            ],
            [
                [
                    'a' => ['joinType' => Select::FROM, 'schema' => null, 'tableName' => 't1', 'joinCondition' => null],
                    'b' => [
                        'joinType' => Select::LEFT_JOIN,
                        'schema' => 'db',
                        'tableName' => 't2',
                        'joinCondition' => 't1.f1 = t2.f2'
                    ]
                ],
                'SELECT b.f2',
                'SELECT b.f2 FROM t1 AS a' . "\n" . ' LEFT JOIN db.t2 AS b ON t1.f1 = t2.f2'
            ]
        ];
    }
}


text:
/**
 * @fileOverview Defines the {@link CKEDITOR.lang} object, for the
 * Esperanto language.
 */

/**#@+
   @type String
   @example
*/

/**
 * Constains the dictionary of language entries.
 * @namespace
 */
CKEDITOR.lang['eo'] =
{
	/**
	 * The language reading direction. Possible values are "rtl" for
	 * Right-To-Left languages (like Arabic) and "ltr" for Left-To-Right
	 * languages (like English).
	 * @default 'ltr'
	 */
	dir : 'ltr',

	/*
	 * Screenreader titles. Please note that screenreaders are not always capable
	 * of reading non-English words. So be careful while translating it.
	 */
	editorTitle		: 'Rich text editor, %1', // MISSING

	// Toolbar buttons without dialogs.
	source			: 'Fonto',
	newPage			: 'Nova Paĝo',
	save			: 'Sekurigi',
	preview			: 'Vidigi Aspekton',
	cut				: 'Eltondi',
	copy			: 'Kopii',
	paste			: 'Interglui',
	print			: 'Presi',
	underline		: 'Substreko',
	bold			: 'Grasa',
	italic			: 'Kursiva',
	selectAll		: 'Elekti ĉion',
	removeFormat	: 'Forigi Formaton',
	strike			: 'Trastreko',
	subscript		: 'Subskribo',
	superscript		: 'Superskribo',
	horizontalrule	: 'Enmeti Horizonta Linio',
	pagebreak		: 'Insert Page Break for Printing', // MISSING
	unlink			: 'Forigi Ligilon',
	undo			: 'Malfari',
	redo			: 'Refari',

	// Common messages and labels.
	common :
	{
		browseServer	: 'Foliumi en la Servilo',
		url				: 'URL',
		protocol		: 'Protokolo',
		upload			: 'Alŝuti',
		uploadSubmit	: 'Sendu al Servilo',
		image			: 'Bildo',
		flash			: 'Flash', // MISSING
		form			: 'Formularo',
		checkbox		: 'Markobutono',
		radio		: 'Radiobutono',
		textField		: 'Teksta kampo',
		textarea		: 'Teksta Areo',
		hiddenField		: 'Kaŝita Kampo',
		button			: 'Butono',
		select	: 'Elekta Kampo',
		imageButton		: 'Bildbutono',
		notSet			: '<Defaŭlta>',
		id				: 'Id',
		name			: 'Nomo',
		langDir			: 'Skribdirekto',
		langDirLtr		: 'De maldekstro dekstren (LTR)',
		langDirRtl		: 'De dekstro maldekstren (RTL)',
		langCode		: 'Lingva Kodo',
		longDescr		: 'URL de Longa Priskribo',
		cssClass		: 'Klasoj de Stilfolioj',
		advisoryTitle	: 'Indika Titolo',
		cssStyle		: 'Stilo',
		ok				: 'Akcepti',
		cancel			: 'Rezigni',
		generalTab		: 'General', // MISSING
		advancedTab		: 'Speciala',
		validateNumberFailed	: 'This value is not a number.', // MISSING
		confirmNewPage	: 'Any unsaved changes to this content will be lost. Are you sure you want to load new page?', // MISSING
		confirmCancel	: 'Some of the options have been changed. Are you sure to close the dialog?', // MISSING

		// Put the voice-only part of the label in the span.
		unavailable		: '%1, unavailable' // MISSING
	},

	// Special char dialog.
	specialChar		:
	{
		toolbar		: 'Enmeti Specialan Signon',
		title		: 'Enmeti Specialan Signon'
	},

	// Link dialog.
	link :
	{
		toolbar		: 'Enmeti/Ŝanĝi Ligilon',
		menu		: 'Modifier Ligilon',
		title		: 'Ligilo',
		info		: 'Informoj pri la Ligilo',
		target		: 'Celo',
		upload		: 'Alŝuti',
		advanced	: 'Speciala',
		type		: 'Tipo de Ligilo',
		toAnchor	: 'Ankri en tiu ĉi paĝo',
		toEmail		: 'Retpoŝto',
		target		: 'Celo',
		targetNotSet	: '<Defaŭlta>',
		targetFrame	: '<kadro>',
		targetPopup	: '<ŝprucfenestro>',
		targetNew	: 'Nova Fenestro (_blank)',
		targetTop	: 'Plej Supra Fenestro (_top)',
		targetSelf	: 'Sama Fenestro (_self)',
		targetParent	: 'Gepatra Fenestro (_parent)',
		targetFrameName	: 'Nomo de Kadro',
		targetPopupName	: 'Nomo de Ŝprucfenestro',
		popupFeatures	: 'Atributoj de la Ŝprucfenestro',
		popupResizable	: 'Resizable', // MISSING
		popupStatusBar	: 'Statobreto',
		popupLocationBar	: 'Adresobreto',
		popupToolbar	: 'Ilobreto',
		popupMenuBar	: 'Menubreto',
		popupFullScreen	: 'Tutekrane (IE)',
		popupScrollBars	: 'Rulumlisteloj',
		popupDependent	: 'Dependa (Netscape)',
		popupWidth		: 'Larĝo',
		popupLeft		: 'Pozicio de Maldekstro',
		popupHeight		: 'Alto',
		popupTop		: 'Pozicio de Supro',
		id				: 'Id', // MISSING
		langDir			: 'Skribdirekto',
		langDirNotSet	: '<Defaŭlta>',
		langDirLTR		: 'De maldekstro dekstren (LTR)',
		langDirRTL		: 'De dekstro maldekstren (RTL)',
		acccessKey		: 'Fulmoklavo',
		name			: 'Nomo',
		langCode		: 'Skribdirekto',
		tabIndex		: 'Taba Ordo',
		advisoryTitle	: 'Indika Titolo',
		advisoryContentType	: 'Indika Enhavotipo',
		cssClasses		: 'Klasoj de Stilfolioj',
		charset			: 'Signaro de la Ligita Rimedo',
		styles			: 'Stilo',
		selectAnchor	: 'Elekti Ankron',
		anchorName		: 'Per Ankronomo',
		anchorId		: 'Per Elementidentigilo',
		emailAddress	: 'Retadreso',
		emailSubject	: 'Temlinio',
		emailBody		: 'Mesaĝa korpo',
		noAnchors		: '<Ne disponeblas ankroj en la dokumento>',
		noUrl			: 'Bonvolu entajpi la URL-on',
		noEmail			: 'Bonvolu entajpi la retadreson'
	},

	// Anchor dialog
	anchor :
	{
		toolbar		: 'Enmeti/Ŝanĝi Ankron',
		menu		: 'Ankraj Atributoj',
		title		: 'Ankraj Atributoj',
		name		: 'Ankra Nomo',
		errorName	: 'Bv tajpi la ankran nomon'
	},

	// Find And Replace Dialog
	findAndReplace :
	{
		title				: 'Find and Replace', // MISSING
		find				: 'Serĉi',
		replace				: 'Anstataŭigi',
		findWhat			: 'Serĉi:',
		replaceWith			: 'Anstataŭigi per:',
		notFoundMsg			: 'La celteksto ne estas trovita.',
		matchCase			: 'Kongruigi Usklecon',
		matchWord			: 'Tuta Vorto',
		matchCyclic			: 'Match cyclic', // MISSING
		replaceAll			: 'Anstataŭigi Ĉiun',
		replaceSuccessMsg	: '%1 occurrence(s) replaced.' // MISSING
	},

	// Table Dialog
	table :
	{
		toolbar		: 'Tabelo',
		title		: 'Atributoj de Tabelo',
		menu		: 'Atributoj de Tabelo',
		deleteTable	: 'Delete Table', // MISSING
		rows		: 'Linioj',
		columns		: 'Kolumnoj',
		border		: 'Bordero',
		align		: 'Ĝisrandigo',
		alignNotSet	: '<Defaŭlte>',
		alignLeft	: 'Maldekstre',
		alignCenter	: 'Centre',
		alignRight	: 'Dekstre',
		width		: 'Larĝo',
		widthPx		: 'Bitbilderoj',
		widthPc		: 'elcentoj',
		height		: 'Alto',
		cellSpace	: 'Interspacigo de Ĉeloj',
		cellPad		: 'Ĉirkaŭenhava Plenigado',
		caption		: 'Titolo',
		summary		: 'Summary', // MISSING
		headers		: 'Headers', // MISSING
		headersNone		: 'None', // MISSING
		headersColumn	: 'First column', // MISSING
		headersRow		: 'First Row', // MISSING
		headersBoth		: 'Both', // MISSING
		invalidRows		: 'Number of rows must be a number greater than 0.', // MISSING
		invalidCols		: 'Number of columns must be a number greater than 0.', // MISSING
		invalidBorder	: 'Border size must be a number.', // MISSING
		invalidWidth	: 'Table width must be a number.', // MISSING
		invalidHeight	: 'Table height must be a number.', // MISSING
		invalidCellSpacing	: 'Cell spacing must be a number.', // MISSING
		invalidCellPadding	: 'Cell padding must be a number.', // MISSING

		cell :
		{
			menu			: 'Cell', // MISSING
			insertBefore	: 'Insert Cell Before', // MISSING
			insertAfter		: 'Insert Cell After', // MISSING
			deleteCell		: 'Forigi Ĉelojn',
			merge			: 'Kunfandi Ĉelojn',
			mergeRight		: 'Merge Right', // MISSING
			mergeDown		: 'Merge Down', // MISSING
			splitHorizontal	: 'Split Cell Horizontally', // MISSING
			splitVertical	: 'Split Cell Vertically', // MISSING
			title			: 'Cell Properties', // MISSING
			cellType		: 'Cell Type', // MISSING
			rowSpan			: 'Rows Span', // MISSING
			colSpan			: 'Columns Span', // MISSING
			wordWrap		: 'Word Wrap', // MISSING
			hAlign			: 'Horizontal Alignment', // MISSING
			vAlign			: 'Vertical Alignment', // MISSING
			alignTop		: 'Top', // MISSING
			alignMiddle		: 'Middle', // MISSING
			alignBottom		: 'Bottom', // MISSING
			alignBaseline	: 'Baseline', // MISSING
			bgColor			: 'Background Color', // MISSING
			borderColor		: 'Border Color', // MISSING
			data			: 'Data', // MISSING
			header			: 'Header', // MISSING
			yes				: 'Yes', // MISSING
			no				: 'No', // MISSING
			invalidWidth	: 'Cell width must be a number.', // MISSING
			invalidHeight	: 'Cell height must be a number.', // MISSING
			invalidRowSpan	: 'Rows span must be a whole number.', // MISSING
			invalidColSpan	: 'Columns span must be a whole number.', // MISSING
			chooseColor : 'Choose' // MISSING
		},

		row :
		{
			menu			: 'Row', // MISSING
			insertBefore	: 'Insert Row Before', // MISSING
			insertAfter		: 'Insert Row After', // MISSING
			deleteRow		: 'Forigi Liniojn'
		},

		column :
		{
			menu			: 'Column', // MISSING
			insertBefore	: 'Insert Column Before', // MISSING
			insertAfter		: 'Insert Column After', // MISSING
			deleteColumn	: 'Forigi Kolumnojn'
		}
	},

	// Button Dialog.
	button :
	{
		title		: 'Butonaj Atributoj',
		text		: 'Teksto (Valoro)',
		type		: 'Tipo',
		typeBtn		: 'Button', // MISSING
		typeSbm		: 'Submit', // MISSING
		typeRst		: 'Reset' // MISSING
	},

	// Checkbox and Radio Button Dialogs.
	checkboxAndRadio :
	{
		checkboxTitle : 'Markobutonaj Atributoj',
		radioTitle	: 'Radiobutonaj Atributoj',
		value		: 'Valoro',
		selected	: 'Elektita'
	},

	// Form Dialog.
	form :
	{
		title		: 'Formularaj Atributoj',
		menu		: 'Formularaj Atributoj',
		action		: 'Ago',
		method		: 'Metodo',
		encoding	: 'Encoding', // MISSING
		target		: 'Celo',
		targetNotSet	: '<Defaŭlta>',
		targetNew	: 'Nova Fenestro (_blank)',
		targetTop	: 'Plej Supra Fenestro (_top)',
		targetSelf	: 'Sama Fenestro (_self)',
		targetParent	: 'Gepatra Fenestro (_parent)'
	},

	// Select Field Dialog.
	select :
	{
		title		: 'Atributoj de Elekta Kampo',
		selectInfo	: 'Select Info', // MISSING
		opAvail		: 'Elektoj Disponeblaj',
		value		: 'Valoro',
		size		: 'Grando',
		lines		: 'Linioj',
		chkMulti	: 'Permesi Plurajn Elektojn',
		opText		: 'Teksto',
		opValue		: 'Valoro',
		btnAdd		: 'Aldoni',
		btnModify	: 'Modifi',
		btnUp		: 'Supren',
		btnDown		: 'Malsupren',
		btnSetValue : 'Agordi kiel Elektitan Valoron',
		btnDelete	: 'Forigi'
	},

	// Textarea Dialog.
	textarea :
	{
		title		: 'Atributoj de Teksta Areo',
		cols		: 'Kolumnoj',
		rows		: 'Vicoj'
	},

	// Text Field Dialog.
	textfield :
	{
		title		: 'Atributoj de Teksta Kampo',
		name		: 'Nomo',
		value		: 'Valoro',
		charWidth	: 'Signolarĝo',
		maxChars	: 'Maksimuma Nombro da Signoj',
		type		: 'Tipo',
		typeText	: 'Teksto',
		typePass	: 'Pasvorto'
	},

	// Hidden Field Dialog.
	hidden :
	{
		title	: 'Atributoj de Kaŝita Kampo',
		name	: 'Nomo',
		value	: 'Valoro'
	},

	// Image Dialog.
	image :
	{
		title		: 'Atributoj de Bildo',
		titleButton	: 'Bildbutonaj Atributoj',
		menu		: 'Atributoj de Bildo',
		infoTab	: 'Informoj pri Bildo',
		btnUpload	: 'Sendu al Servilo',
		url		: 'URL',
		upload	: 'Alŝuti',
		alt		: 'Anstataŭiga Teksto',
		width		: 'Larĝo',
		height	: 'Alto',
		lockRatio	: 'Konservi Proporcion',
		resetSize	: 'Origina Grando',
		border	: 'Bordero',
		hSpace	: 'HSpaco',
		vSpace	: 'VSpaco',
		align		: 'Ĝisrandigo',
		alignLeft	: 'Maldekstre',
		alignAbsBottom: 'Abs Malsupre',
		alignAbsMiddle: 'Abs Centre',
		alignBaseline	: 'Je Malsupro de Teksto',
		alignBottom	: 'Malsupre',
		alignMiddle	: 'Centre',
		alignRight	: 'Dekstre',
		alignTextTop	: 'Je Supro de Teksto',
		alignTop	: 'Supre',
		preview	: 'Vidigi Aspekton',
		alertUrl	: 'Bonvolu tajpi la URL de la bildo',
		linkTab	: 'Link', // MISSING
		button2Img	: 'Do you want to transform the selected image button on a simple image?', // MISSING
		img2Button	: 'Do you want to transform the selected image on a image button?', // MISSING
		urlMissing : 'Image source URL is missing.' // MISSING
	},

	// Flash Dialog
	flash :
	{
		properties		: 'Flash Properties', // MISSING
		propertiesTab	: 'Properties', // MISSING
		title		: 'Flash Properties', // MISSING
		chkPlay		: 'Auto Play', // MISSING
		chkLoop		: 'Loop', // MISSING
		chkMenu		: 'Enable Flash Menu', // MISSING
		chkFull		: 'Allow Fullscreen', // MISSING
 		scale		: 'Scale', // MISSING
		scaleAll		: 'Show all', // MISSING
		scaleNoBorder	: 'No Border', // MISSING
		scaleFit		: 'Exact Fit', // MISSING
		access			: 'Script Access', // MISSING
		accessAlways	: 'Always', // MISSING
		accessSameDomain	: 'Same domain', // MISSING
		accessNever	: 'Never', // MISSING
		align		: 'Ĝisrandigo',
		alignLeft	: 'Maldekstre',
		alignAbsBottom: 'Abs Malsupre',
		alignAbsMiddle: 'Abs Centre',
		alignBaseline	: 'Je Malsupro de Teksto',
		alignBottom	: 'Malsupre',
		alignMiddle	: 'Centre',
		alignRight	: 'Dekstre',
		alignTextTop	: 'Je Supro de Teksto',
		alignTop	: 'Supre',
		quality		: 'Quality', // MISSING
		qualityBest		 : 'Best', // MISSING
		qualityHigh		 : 'High', // MISSING
		qualityAutoHigh	 : 'Auto High', // MISSING
		qualityMedium	 : 'Medium', // MISSING
		qualityAutoLow	 : 'Auto Low', // MISSING
		qualityLow		 : 'Low', // MISSING
		windowModeWindow	 : 'Window', // MISSING
		windowModeOpaque	 : 'Opaque', // MISSING
		windowModeTransparent	 : 'Transparent', // MISSING
		windowMode	: 'Window mode', // MISSING
		flashvars	: 'Variables for Flash', // MISSING
		bgcolor	: 'Fona Koloro',
		width	: 'Larĝo',
		height	: 'Alto',
		hSpace	: 'HSpaco',
		vSpace	: 'VSpaco',
		validateSrc : 'Bonvolu entajpi la URL-on',
		validateWidth : 'Width must be a number.', // MISSING
		validateHeight : 'Height must be a number.', // MISSING
		validateHSpace : 'HSpace must be a number.', // MISSING
		validateVSpace : 'VSpace must be a number.' // MISSING
	},

	// Speller Pages Dialog
	spellCheck :
	{
		toolbar			: 'Literumada Kontrolilo',
		title			: 'Spell Check', // MISSING
		notAvailable	: 'Sorry, but service is unavailable now.', // MISSING
		errorLoading	: 'Error loading application service host: %s.', // MISSING
		notInDic		: 'Ne trovita en la vortaro',
		changeTo		: 'Ŝanĝi al',
		btnIgnore		: 'Malatenti',
		btnIgnoreAll	: 'Malatenti Ĉiun',
		btnReplace		: 'Anstataŭigi',
		btnReplaceAll	: 'Anstataŭigi Ĉiun',
		btnUndo			: 'Malfari',
		noSuggestions	: '- Neniu propono -',
		progress		: 'Literumkontrolado daŭras...',
		noMispell		: 'Literumkontrolado finita: neniu fuŝo trovita',
		noChanges		: 'Literumkontrolado finita: neniu vorto ŝanĝita',
		oneChange		: 'Literumkontrolado finita: unu vorto ŝanĝita',
		manyChanges		: 'Literumkontrolado finita: %1 vortoj ŝanĝitaj',
		ieSpellDownload	: 'Literumada Kontrolilo ne instalita. Ĉu vi volas elŝuti ĝin nun?'
	},

	smiley :
	{
		toolbar	: 'Mienvinjeto',
		title	: 'Enmeti Mienvinjeton'
	},

	elementsPath :
	{
		eleTitle : '%1 element' // MISSING
	},

	numberedlist : 'Numera Listo',
	bulletedlist : 'Bula Listo',
	indent : 'Pligrandigi Krommarĝenon',
	outdent : 'Malpligrandigi Krommarĝenon',

	justify :
	{
		left : 'Maldekstrigi',
		center : 'Centrigi',
		right : 'Dekstrigi',
		block : 'Ĝisrandigi Ambaŭflanke'
	},

	blockquote : 'Blockquote', // MISSING

	clipboard :
	{
		title		: 'Interglui',
		cutError	: 'La sekurecagordo de via TTT-legilo ne permesas, ke la redaktilo faras eltondajn operaciojn. Bonvolu uzi la klavaron por tio (ctrl-X).',
		copyError	: 'La sekurecagordo de via TTT-legilo ne permesas, ke la redaktilo faras kopiajn operaciojn. Bonvolu uzi la klavaron por tio (ctrl-C).',
		pasteMsg	: 'Please paste inside the following box using the keyboard (Ctrl+V) and hit OK', // MISSING
		securityMsg	: 'Because of your browser security settings, the editor is not able to access your clipboard data directly. You are required to paste it again in this window.' // MISSING
	},

	pastefromword :
	{
		toolbar : 'Interglui el Word',
		title : 'Interglui el Word',
		advice : 'Please paste inside the following box using the keyboard (Ctrl+V) and hit OK.', // MISSING
		ignoreFontFace : 'Ignore Font Face definitions', // MISSING
		removeStyle : 'Remove Styles definitions' // MISSING
	},

	pasteText :
	{
		button : 'Interglui kiel Tekston',
		title : 'Interglui kiel Tekston'
	},

	templates :
	{
		button : 'Templates', // MISSING
		title : 'Content Templates', // MISSING
		insertOption: 'Replace actual contents', // MISSING
		selectPromptMsg: 'Please select the template to open in the editor', // MISSING
		emptyListMsg : '(No templates defined)' // MISSING
	},

	showBlocks : 'Show Blocks', // MISSING

	stylesCombo :
	{
		label : 'Stilo',
		voiceLabel : 'Styles', // MISSING
		panelVoiceLabel : 'Select a style', // MISSING
		panelTitle1 : 'Block Styles', // MISSING
		panelTitle2 : 'Inline Styles', // MISSING
		panelTitle3 : 'Object Styles' // MISSING
	},

	format :
	{
		label : 'Formato',
		voiceLabel : 'Format', // MISSING
		panelTitle : 'Formato',
		panelVoiceLabel : 'Select a paragraph format', // MISSING

		tag_p : 'Normala',
		tag_pre : 'Formatita',
		tag_address : 'Adreso',
		tag_h1 : 'Titolo 1',
		tag_h2 : 'Titolo 2',
		tag_h3 : 'Titolo 3',
		tag_h4 : 'Titolo 4',
		tag_h5 : 'Titolo 5',
		tag_h6 : 'Titolo 6',
		tag_div : 'Paragrafo (DIV)'
	},

	font :
	{
		label : 'Tiparo',
		voiceLabel : 'Font', // MISSING
		panelTitle : 'Tiparo',
		panelVoiceLabel : 'Select a font' // MISSING
	},

	fontSize :
	{
		label : 'Grando',
		voiceLabel : 'Font Size', // MISSING
		panelTitle : 'Grando',
		panelVoiceLabel : 'Select a font size' // MISSING
	},

	colorButton :
	{
		textColorTitle : 'Teksta Koloro',
		bgColorTitle : 'Fona Koloro',
		auto : 'Aŭtomata',
		more : 'Pli da Koloroj...'
	},

	colors :
	{
		'000' : 'Black',
		'800000' : 'Maroon',
		'8B4513' : 'Saddle Brown',
		'2F4F4F' : 'Dark Slate Gray',
		'008080' : 'Teal',
		'000080' : 'Navy',
		'4B0082' : 'Indigo',
		'696969' : 'Dim Gray',
		'B22222' : 'Fire Brick',
		'A52A2A' : 'Brown',
		'DAA520' : 'Golden Rod',
		'006400' : 'Dark Green',
		'40E0D0' : 'Turquoise',
		'0000CD' : 'Medium Blue',
		'800080' : 'Purple',
		'808080' : 'Gray',
		'F00' : 'Red',
		'FF8C00' : 'Dark Orange',
		'FFD700' : 'Gold',
		'008000' : 'Green',
		'0FF' : 'Cyan',
		'00F' : 'Blue',
		'EE82EE' : 'Violet',
		'A9A9A9' : 'Dark Gray',
		'FFA07A' : 'Light Salmon',
		'FFA500' : 'Orange',
		'FFFF00' : 'Yellow',
		'00FF00' : 'Lime',
		'AFEEEE' : 'Pale Turquoise',
		'ADD8E6' : 'Light Blue',
		'DDA0DD' : 'Plum',
		'D3D3D3' : 'Light Grey',
		'FFF0F5' : 'Lavender Blush',
		'FAEBD7' : 'Antique White',
		'FFFFE0' : 'Light Yellow',
		'F0FFF0' : 'Honeydew',
		'F0FFFF' : 'Azure',
		'F0F8FF' : 'Alice Blue',
		'E6E6FA' : 'Lavender',
		'FFF' : 'White'
	},

	scayt :
	{
		title : 'Spell Check As You Type', // MISSING
		enable : 'Enable SCAYT', // MISSING
		disable : 'Disable SCAYT', // MISSING
		about : 'About SCAYT', // MISSING
		toggle : 'Toggle SCAYT', // MISSING
		options : 'Options', // MISSING
		langs : 'Languages', // MISSING
		moreSuggestions : 'More suggestions', // MISSING
		ignore : 'Ignore', // MISSING
		ignoreAll : 'Ignore All', // MISSING
		addWord : 'Add Word', // MISSING
		emptyDic : 'Dictionary name should not be empty.', // MISSING
		optionsTab : 'Options', // MISSING
		languagesTab : 'Languages', // MISSING
		dictionariesTab : 'Dictionaries', // MISSING
		aboutTab : 'About' // MISSING
	},

	about :
	{
		title : 'About CKEditor', // MISSING
		dlgTitle : 'About CKEditor', // MISSING
		moreInfo : 'For licensing information please visit our web site:', // MISSING
		copy : 'Copyright © $1. All rights reserved.' // MISSING
	},

	maximize : 'Maximize', // MISSING
	minimize : 'Minimize', // MISSING

	fakeobjects :
	{
		anchor : 'Anchor', // MISSING
		flash : 'Flash Animation', // MISSING
		div : 'Page Break', // MISSING
		unknown : 'Unknown Object' // MISSING
	},

	resize : 'Drag to resize', // MISSING

	colordialog :
	{
		title : 'Select color', // MISSING
		highlight : 'Highlight', // MISSING
		selected : 'Selected', // MISSING
		clear : 'Clear' // MISSING
	}
};


text:
package vn.gcall.gcall2.Helpers;

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by This PC on 16/05/2016.
 * Manage the log in session and check first time run
 */
public class SessionManager {
    private static final String PREF_NAME="GCALL";
    private static final String CHECK_FIRST_TIME="FIRST_TIME";
    int PRIVATE_MODE=0;

    public void setStringPreferences(Context context,String key,String value){
        SharedPreferences.Editor editor= context.getSharedPreferences(PREF_NAME,PRIVATE_MODE).edit();
        editor.putString(key,value);
        editor.commit();
    }
    public void setBoolPreferences(Context context, String key, Boolean value){
        SharedPreferences.Editor editor= context.getSharedPreferences(PREF_NAME,PRIVATE_MODE).edit();
        editor.putBoolean(key,value);
        editor.commit();
    }

    public String getStringPreferences(Context context, String key){
        SharedPreferences pref= context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
        String result=pref.getString(key,"");
        return result;
    }

    public Boolean getBoolPreferences(Context context, String key){
        SharedPreferences pref= context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);
        Boolean result=pref.getBoolean(key,false);
        return result;
    }

    public void deleteSession(Context context){
        SharedPreferences.Editor editor=context.getSharedPreferences(PREF_NAME,PRIVATE_MODE).edit();
        editor.clear();
        editor.commit();

    }

    public void setFirtTimeLunch(Context context,boolean isFirstTime){
        SharedPreferences.Editor editor=context.getSharedPreferences(CHECK_FIRST_TIME,PRIVATE_MODE).edit();
        editor.putBoolean("FIRST_TIME_RUN",isFirstTime);
        editor.commit();
    }

    public boolean isFirtTimeLunch(Context context){
        return context.getSharedPreferences(CHECK_FIRST_TIME,PRIVATE_MODE).getBoolean("FIRST_TIME_RUN",true);
    }
}


text:
layout: post
title:      "Varyscary - Final project"
date:       2019-02-27 23:16:17 +0000
permalink:  varyscary_-_final_project
---

Varyscary is a single page web app built with React, Redux, and Rails that allows users to create custom monsters.

I'll briefly walk through and explain a few of the app's features starting with the monster creation page. The create page allows users to select from a bunch of pre-designed individual features to combine into a complete monster. Users can select different bodies, faces, eyes, headwear, etc. Each individual feature is just a react component that contains an SVG.

```
export const BodyCircle = (props) => {
  return (
    <svg xmlns={XMLNS} viewBox='-115.5 -115.5 375 375'>
      <circle fill={props.fillColor}
        stroke={props.strokeColor}
        strokeDasharray={props.strokeDasharray}
        strokeWidth={props.strokeWidth}
        cx='72' cy='72' r='72' />
    </svg>
  )
}
```

When a user selects a feature, I store the feature's component name in a Redux store. I use this redux store to display a preview of the monster, and, ultimately, save the monster's feature component names to the database.

```
monsterName: '',
monsterTags: [],
monsterFeatures: {
	body: {
		type: 'BodyCircle',
		hoverType: null,
		fillColor: '#000000'
	},
	face: {
		type: null,
		hoverType: null,
		fillColor: '#ffffff'
	},
	headwear: {
		type: null,
		hoverType: null,
		fillColor: '#000000'
	},
	...
}
```

There is also the option to create a randomized monster instead of selecting each feature. For the randomize function, I import all of the feature component names and make arrays for each category (bodies, faces, eyes, etc.) that contain these names as strings. When the randomize button is pressed I dispatch an action that selects a random index from each array and pushes the feature name at that index to the Redux store.

```
export const randomizeMonster = () => {
  const getRandomInt = max => Math.floor(Math.random() * max)
  const color1 = randomize.colors[getRandomInt(randomize.colors.length)]
  const color2 = randomize.colors[getRandomInt(randomize.colors.length)]
  return {
    type: actionTypes.RANDOMIZE_MONSTER,
    bodyType: randomize.bodies[getRandomInt(randomize.bodies.length)],
    bodyColor: color1,
    faceType: randomize.faces[getRandomInt(randomize.faces.length)],
    headwearType: randomize.headwear[getRandomInt(randomize.headwear.length)],
    headwearColor: color2,
	...
	}
}
```

Next up is the explore page. The explore page allows users to browse monsters. Users can search by tags and monster names as well as sort based on creation date and popularity.  The explore page initially loads 50 monsters, and an additional 50 monsters each time a 'Load more' button is pressed so that there isn't a long initial page load time. I achieved this using a limit and offset on the back end which I pass as params.

```
case params[:sort_by]
	when 'newest'
		@monsters = Monster.monsters_since(params[:since])
		.order(created_at: :desc).limit(params[:limit])
		.offset(params[:offset]).includes(:user, :liked_by, :tags)
		@monsters = sort_monsters(@monsters, params)
	when 'oldest'
		@monsters = Monster.monsters_since(params[:since])
		.order(created_at: :asc).limit(params[:limit])
		.offset(params[:offset]).includes(:user, :liked_by, :tags)
		@monsters = sort_monsters(@monsters, params)
		...
```

I also append the selected sort method and/or search term to the explore page's URL so that users can bookmark and link directly to a pre-sorted or filtered monster list.

E.g.
> /monsters?sort_by=newest&search=green

The back end is a pretty standard api-only rails app generated using the --api flag.

```
rails new my_api --api
```

For authentication, I'm using a JSON Web Token implemented via the Knock ruby gem. If the user's credentials are correct then I return a JSON Web Token via my user_token_controller that I store in the browser's local storage. I then require this JWT for authentication every time a user tries to access a protected route.


text:
var TYPES = require('./formWidgetTypes');

module.exports = {
  formData: {
    experimentName: `${Math.round(1000 * Math.random())} random tones`,
    introPage: 'In this experiment, you will first evaluate **as many tones as you would like**, then you will complete a demographic survey.',
    interTestPage: 'Thanks for your evaluation! Here\'s another one.',
    postTestPage: 'Now you will complete a demographic survey',
    endPage: 'Thank you for completing this experiment! [Fork me on GitHub](https://github.com/conundrumer/musicpsych)',
    stimulus: 'randomIntervals',
    instruments: [
      'sine',
      'synth'
    ]
    // instruments: 'sine'
  },
  participantForms: [{
    name: 'gender',
    question: 'What is your gender?',
    type: TYPES.CHOICE,
    choices: ['Male', 'Female']
  }, {
    name: 'age',
    question: 'What is your age?',
    type: TYPES.NUMBER,
    min: 0,
    max: 120
  }, {
    name: 'musical',
    question: 'Are you a trained musician?',
    type: TYPES.BOOLEAN
  }],
  testForms: [{
    name: 'valence',
    question: 'Are these tones conveying positive or negative feelings?',
    type: TYPES.BIPOLAR,
    dimension1: 'negative',
    dimension2: 'positive'
  }, {
    name: 'tension',
    question: 'How tense do you think these tones are? Are they calm and relaxed or tense and agitated?',
    type: TYPES.BIPOLAR,
    dimension1: 'calm',
    dimension2: 'tense'
  }]
};


text:
package com.stelianmorariu.wearme;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class WearService extends Service {
    public static final int MSG_REGISTER = 332;
    public static final int MSG_UNREGISTER = 333;
    public static final int MSG_TIMER = 334;
    private static final String LOG_TAG = WearService.class.getSimpleName();

    private final Messenger mMessenger = new Messenger(new IncomingMessageHandler());
    private Messenger mClientMessenger = null;
    private long mSavedSessionDuration;
    private ScheduledExecutorService mScheduler;
    private ScheduledFuture<?> mTimerTask;
    private Runnable mTimeTicker = new Runnable() {
        @Override
        public void run() {
            mSavedSessionDuration += 1000;
            sendDuration();
        }
    };

    public WearService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mScheduler = Executors.newSingleThreadScheduledExecutor();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    private void sendDuration() {
        try {
            if (mClientMessenger != null) {
                Message msg = Message.obtain(null, MSG_TIMER);
                msg.obj = mSavedSessionDuration;
                mClientMessenger.send(msg);
            }
        } catch (RemoteException ex) {
            Log.e(LOG_TAG, ex.toString());
        }
    }

    private class IncomingMessageHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_REGISTER:
                    mClientMessenger = msg.replyTo;
                    mTimerTask = mScheduler.scheduleAtFixedRate(mTimeTicker, 0, 1000, TimeUnit.MILLISECONDS);
                    break;
                case MSG_UNREGISTER:
                    mTimerTask.cancel(true);
                    mClientMessenger = null;
                    break;

                default:
                    super.handleMessage(msg);
            }
        }
    }
}


text:
#include "translatedialog.h"

QT_BEGIN_NAMESPACE

TranslateDialog::TranslateDialog(QWidget *parent)
  : QDialog(parent)
{
    m_ui.setupUi(this);
    connect(m_ui.findNxt, SIGNAL(clicked()), this, SLOT(emitFindNext()));
    connect(m_ui.translate, SIGNAL(clicked()), this, SLOT(emitTranslateAndFindNext()));
    connect(m_ui.translateAll, SIGNAL(clicked()), this, SLOT(emitTranslateAll()));
    connect(m_ui.ledFindWhat, SIGNAL(textChanged(QString)), SLOT(verifyText()));
    connect(m_ui.ckMatchCase, SIGNAL(toggled(bool)), SLOT(verifyText()));
}

void TranslateDialog::showEvent(QShowEvent *)
{
    verifyText();
    m_ui.ledFindWhat->setFocus();
}

void TranslateDialog::verifyText()
{
    QString text = m_ui.ledFindWhat->text();
    bool canFind = !text.isEmpty();
    bool hit = false;
    if (canFind)
        emit requestMatchUpdate(hit);
    m_ui.findNxt->setEnabled(canFind);
    m_ui.translate->setEnabled(canFind && hit);
    m_ui.translateAll->setEnabled(canFind);
}

void TranslateDialog::emitFindNext()
{
    emit activated(Skip);
}

void TranslateDialog::emitTranslateAndFindNext()
{
    emit activated(Translate);
}

void TranslateDialog::emitTranslateAll()
{
    emit activated(TranslateAll);
}

QT_END_NAMESPACE


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.CodeRefactorings.LambdaSimplifier
{
    // Disabled due to: https://github.com/dotnet/roslyn/issues/5835 & https://github.com/dotnet/roslyn/pull/6642
    // [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.SimplifyLambda)]
    internal partial class LambdaSimplifierCodeRefactoringProvider : CodeRefactoringProvider
    {
        public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
        {
            var (document, textSpan, cancellationToken) = context;
            if (cancellationToken.IsCancellationRequested)
            {
                return;
            }

            if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
            {
                return;
            }

            var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);

            var lambda = await context.TryGetRelevantNodeAsync<LambdaExpressionSyntax>().ConfigureAwait(false);
            if (lambda == null)
            {
                return;
            }

            if (!CanSimplify(semanticDocument, lambda as SimpleLambdaExpressionSyntax, cancellationToken) &&
                !CanSimplify(semanticDocument, lambda as ParenthesizedLambdaExpressionSyntax, cancellationToken))
            {
                return;
            }

            context.RegisterRefactoring(
                new MyCodeAction(
                    CSharpFeaturesResources.Simplify_lambda_expression,
                    c => SimplifyLambdaAsync(document, lambda, c)),
                lambda.Span);

            context.RegisterRefactoring(
                new MyCodeAction(
                    CSharpFeaturesResources.Simplify_all_occurrences,
                    c => SimplifyAllLambdasAsync(document, c)),
                lambda.Span);
        }

        private static async Task<Document> SimplifyLambdaAsync(
            Document document,
            SyntaxNode lambda,
            CancellationToken cancellationToken)
        {
            var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
            var rewriter = new Rewriter(semanticDocument, n => n == lambda, cancellationToken);
            var result = rewriter.Visit(semanticDocument.Root);
            return document.WithSyntaxRoot(result);
        }

        private static async Task<Document> SimplifyAllLambdasAsync(
            Document document,
            CancellationToken cancellationToken)
        {
            var semanticDocument = await SemanticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false);
            var rewriter = new Rewriter(semanticDocument, n => true, cancellationToken);
            var result = rewriter.Visit(semanticDocument.Root);
            return document.WithSyntaxRoot(result);
        }

        private static bool CanSimplify(
            SemanticDocument document,
            SimpleLambdaExpressionSyntax node,
            CancellationToken cancellationToken)
        {
            if (node == null)
            {
                return false;
            }

            var paramName = node.Parameter.Identifier;
            var invocation = TryGetInvocationExpression(node.Body);
            return CanSimplify(document, node, new List<SyntaxToken>() { paramName }, invocation, cancellationToken);
        }

        private static bool CanSimplify(
            SemanticDocument document,
            ParenthesizedLambdaExpressionSyntax node,
            CancellationToken cancellationToken)
        {
            if (node == null)
            {
                return false;
            }

            var paramNames = node.ParameterList.Parameters.Select(p => p.Identifier).ToList();
            var invocation = TryGetInvocationExpression(node.Body);
            return CanSimplify(document, node, paramNames, invocation, cancellationToken);
        }

        private static bool CanSimplify(
           SemanticDocument document,
            ExpressionSyntax lambda,
            List<SyntaxToken> paramNames,
            InvocationExpressionSyntax invocation,
            CancellationToken cancellationToken)
        {
            if (invocation == null)
            {
                return false;
            }

            if (invocation.ArgumentList.Arguments.Count != paramNames.Count)
            {
                return false;
            }

            for (var i = 0; i < paramNames.Count; i++)
            {
                var argument = invocation.ArgumentList.Arguments[i];
                if (argument.NameColon != null ||
                    argument.RefOrOutKeyword.Kind() != SyntaxKind.None ||
                    !argument.Expression.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax identifierName))
                {
                    return false;
                }

                if (identifierName.Identifier.ValueText != paramNames[i].ValueText)
                {
                    return false;
                }
            }

            var semanticModel = document.SemanticModel;
            var lambdaSemanticInfo = semanticModel.GetSymbolInfo(lambda, cancellationToken);
            var invocationSemanticInfo = semanticModel.GetSymbolInfo(invocation, cancellationToken);
            if (lambdaSemanticInfo.Symbol == null ||
                invocationSemanticInfo.Symbol == null)
            {
                // Don't offer this if there are any errors or ambiguities.
                return false;
            }
            if (!(lambdaSemanticInfo.Symbol is IMethodSymbol lambdaMethod) || !(invocationSemanticInfo.Symbol is IMethodSymbol invocationMethod))
            {
                return false;
            }

            // TODO(cyrusn): Handle extension methods as well.
            if (invocationMethod.IsExtensionMethod)
            {
                return false;
            }

            // Check if any of the parameter is of Type Dynamic
            foreach (var parameter in lambdaMethod.Parameters)
            {
                if (parameter.Type != null && parameter.Type.Kind == SymbolKind.DynamicType)
                {
                    return false;
                }
            }

            // Check if the parameter and return types match between the lambda and the
            // invocation.  Note: return types can be covariant and argument types can be
            // contravariant.
            if (lambdaMethod.ReturnsVoid != invocationMethod.ReturnsVoid ||
                lambdaMethod.Parameters.Length != invocationMethod.Parameters.Length)
            {
                return false;
            }

            if (!lambdaMethod.ReturnsVoid)
            {
                // Return type has to be covariant.
                var conversion = document.SemanticModel.Compilation.ClassifyConversion(
                    invocationMethod.ReturnType, lambdaMethod.ReturnType);
                if (!conversion.IsIdentityOrImplicitReference())
                {
                    return false;
                }
            }

            // Parameter types have to be contravariant.
            for (var i = 0; i < lambdaMethod.Parameters.Length; i++)
            {
                var conversion = document.SemanticModel.Compilation.ClassifyConversion(
                    lambdaMethod.Parameters[i].Type, invocationMethod.Parameters[i].Type);

                if (!conversion.IsIdentityOrImplicitReference())
                {
                    return false;
                }
            }

            if (WouldCauseAmbiguity(lambda, invocation, semanticModel, cancellationToken))
            {
                return false;
            }

            // Looks like something we can simplify.
            return true;
        }

        // Ensure that if we replace the invocation with its expression that its expression will
        // bind unambiguously.  This can happen with awesome cases like:
#if false
    static void Goo<T>(T x) where T : class { }
    static void Bar(Action<int> x) { }
    static void Bar(Action<string> x) { }
    static void Main()
    {
        Bar(x => Goo(x)); // error CS0121: The call is ambiguous between the following methods or properties: 'A.Bar(System.Action<int>)' and 'A.Bar(System.Action<string>)'
    }
#endif
        private static bool WouldCauseAmbiguity(
            ExpressionSyntax lambda,
            InvocationExpressionSyntax invocation,
            SemanticModel oldSemanticModel,
            CancellationToken cancellationToken)
        {
            var annotation = new SyntaxAnnotation();

            // In order to check if there will be a problem, we actually make the change, fork the
            // compilation, and then verify that the new expression bound unambiguously.
            var oldExpression = invocation.Expression.WithAdditionalAnnotations(annotation);
            var oldCompilation = oldSemanticModel.Compilation;
            var oldTree = oldSemanticModel.SyntaxTree;
            var oldRoot = oldTree.GetRoot(cancellationToken);

            var newRoot = oldRoot.ReplaceNode(lambda, oldExpression);

            var newTree = oldTree.WithRootAndOptions(newRoot, oldTree.Options);

            var newCompilation = oldCompilation.ReplaceSyntaxTree(oldTree, newTree);
            var newExpression = newTree.GetRoot(cancellationToken).GetAnnotatedNodesAndTokens(annotation).First().AsNode();
            var newSemanticModel = newCompilation.GetSemanticModel(newTree);

            var info = newSemanticModel.GetSymbolInfo(newExpression, cancellationToken);

            return info.CandidateReason != CandidateReason.None;
        }

        private static InvocationExpressionSyntax TryGetInvocationExpression(
            SyntaxNode lambdaBody)
        {
            if (lambdaBody is ExpressionSyntax exprBody)
            {
                return exprBody.WalkDownParentheses() as InvocationExpressionSyntax;
            }
            else if (lambdaBody is BlockSyntax block)
            {
                if (block.Statements.Count == 1)
                {
                    var statement = block.Statements.First();
                    if (statement is ReturnStatementSyntax returnStatement)
                    {
                        return returnStatement.Expression.WalkDownParentheses() as InvocationExpressionSyntax;
                    }
                    else if (statement is ExpressionStatementSyntax exprStatement)
                    {
                        return exprStatement.Expression.WalkDownParentheses() as InvocationExpressionSyntax;
                    }
                }
            }

            return null;
        }

        private class MyCodeAction : CodeAction.DocumentChangeAction
        {
            public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
                : base(title, createChangedDocument)
            {
            }
        }
    }
}


text:
package com.badlogic.gdx.backends.android;

import java.text.NumberFormat;
import java.text.ParseException;

import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;
import android.opengl.GLSurfaceView.EGLConfigChooser;
import android.opengl.GLSurfaceView.Renderer;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager.LayoutParams;

import com.badlogic.gdx.Application;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Graphics;
import com.badlogic.gdx.LifecycleListener;
import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20;
import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceView20API18;
import com.badlogic.gdx.backends.android.surfaceview.GLSurfaceViewAPI18;
import com.badlogic.gdx.backends.android.surfaceview.GdxEglConfigChooser;
import com.badlogic.gdx.backends.android.surfaceview.ResolutionStrategy;
import com.badlogic.gdx.graphics.Cubemap;
import com.badlogic.gdx.graphics.Cursor;
import com.badlogic.gdx.graphics.Cursor.SystemCursor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.GL30;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.TextureArray;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.graphics.glutils.GLVersion;
import com.badlogic.gdx.graphics.glutils.ShaderProgram;
import com.badlogic.gdx.math.WindowedMean;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.GdxRuntimeException;
import com.badlogic.gdx.utils.SnapshotArray;

/** An implementation of {@link Graphics} for Android.
 *
 * @author mzechner */
public class AndroidGraphics implements Graphics, Renderer {

	private static final String LOG_TAG = "AndroidGraphics";

	/** When {@link AndroidFragmentApplication#onPause()} or {@link AndroidApplication#onPause()} call
	 * {@link AndroidGraphics#pause()} they <b>MUST</b> enforce continuous rendering. If not, {@link #onDrawFrame(GL10)} will not
	 * be called in the GLThread while {@link #pause()} is sleeping in the Android UI Thread which will cause the
	 * {@link AndroidGraphics#pause} variable never be set to false. As a result, the {@link AndroidGraphics#pause()} method will
	 * kill the current process to avoid ANR */
	static volatile boolean enforceContinuousRendering = false;

	final View view;
	int width;
	int height;
	AndroidApplicationBase app;
	GL20 gl20;
	GL30 gl30;
	EGLContext eglContext;
	GLVersion glVersion;
	String extensions;

	protected long lastFrameTime = System.nanoTime();
	protected float deltaTime = 0;
	protected long frameStart = System.nanoTime();
	protected long frameId = -1;
	protected int frames = 0;
	protected int fps;
	protected WindowedMean mean = new WindowedMean(5);

	volatile boolean created = false;
	volatile boolean running = false;
	volatile boolean pause = false;
	volatile boolean resume = false;
	volatile boolean destroy = false;

	private float ppiX = 0;
	private float ppiY = 0;
	private float ppcX = 0;
	private float ppcY = 0;
	private float density = 1;

	protected final AndroidApplicationConfiguration config;
	private BufferFormat bufferFormat = new BufferFormat(5, 6, 5, 0, 16, 0, 0, false);
	private boolean isContinuous = true;

	public AndroidGraphics (AndroidApplicationBase application, AndroidApplicationConfiguration config,
		ResolutionStrategy resolutionStrategy) {
		this(application, config, resolutionStrategy, true);
	}

	public AndroidGraphics (AndroidApplicationBase application, AndroidApplicationConfiguration config,
		ResolutionStrategy resolutionStrategy, boolean focusableView) {
		AndroidGL20.init();
		this.config = config;
		this.app = application;
		view = createGLSurfaceView(application, resolutionStrategy);
		preserveEGLContextOnPause();
		if (focusableView) {
			view.setFocusable(true);
			view.setFocusableInTouchMode(true);
		}
	}

	protected void preserveEGLContextOnPause () {
		int sdkVersion = android.os.Build.VERSION.SDK_INT;
		if ((sdkVersion >= 11 && view instanceof GLSurfaceView20) || view instanceof GLSurfaceView20API18) {
			try {
				view.getClass().getMethod("setPreserveEGLContextOnPause", boolean.class).invoke(view, true);
			} catch (Exception e) {
				Gdx.app.log(LOG_TAG, "Method GLSurfaceView.setPreserveEGLContextOnPause not found");
			}
		}
	}

	protected View createGLSurfaceView (AndroidApplicationBase application, final ResolutionStrategy resolutionStrategy) {
		if (!checkGL20()) throw new GdxRuntimeException("Libgdx requires OpenGL ES 2.0");

		EGLConfigChooser configChooser = getEglConfigChooser();
		int sdkVersion = android.os.Build.VERSION.SDK_INT;
		if (sdkVersion <= 10 && config.useGLSurfaceView20API18) {
			GLSurfaceView20API18 view = new GLSurfaceView20API18(application.getContext(), resolutionStrategy);
			if (configChooser != null)
				view.setEGLConfigChooser(configChooser);
			else
				view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil);
			view.setRenderer(this);
			return view;
		} else {
			GLSurfaceView20 view = new GLSurfaceView20(application.getContext(), resolutionStrategy, config.useGL30 ? 3 : 2);
			if (configChooser != null)
				view.setEGLConfigChooser(configChooser);
			else
				view.setEGLConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil);
			view.setRenderer(this);
			return view;
		}
	}

	public void onPauseGLSurfaceView () {
		if (view != null) {
			if (view instanceof GLSurfaceViewAPI18) ((GLSurfaceViewAPI18)view).onPause();
			if (view instanceof GLSurfaceView) ((GLSurfaceView)view).onPause();
		}
	}

	public void onResumeGLSurfaceView () {
		if (view != null) {
			if (view instanceof GLSurfaceViewAPI18) ((GLSurfaceViewAPI18)view).onResume();
			if (view instanceof GLSurfaceView) ((GLSurfaceView)view).onResume();
		}
	}

	protected EGLConfigChooser getEglConfigChooser () {
		return new GdxEglConfigChooser(config.r, config.g, config.b, config.a, config.depth, config.stencil, config.numSamples);
	}

	private void updatePpi () {
		DisplayMetrics metrics = new DisplayMetrics();
		app.getWindowManager().getDefaultDisplay().getMetrics(metrics);

		ppiX = metrics.xdpi;
		ppiY = metrics.ydpi;
		ppcX = metrics.xdpi / 2.54f;
		ppcY = metrics.ydpi / 2.54f;
		density = metrics.density;
	}

	protected boolean checkGL20 () {
		EGL10 egl = (EGL10)EGLContext.getEGL();
		EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);

		int[] version = new int[2];
		egl.eglInitialize(display, version);

		int EGL_OPENGL_ES2_BIT = 4;
		int[] configAttribs = {EGL10.EGL_RED_SIZE, 4, EGL10.EGL_GREEN_SIZE, 4, EGL10.EGL_BLUE_SIZE, 4, EGL10.EGL_RENDERABLE_TYPE,
			EGL_OPENGL_ES2_BIT, EGL10.EGL_NONE};

		EGLConfig[] configs = new EGLConfig[10];
		int[] num_config = new int[1];
		egl.eglChooseConfig(display, configAttribs, configs, 10, num_config);
		egl.eglTerminate(display);
		return num_config[0] > 0;
	}

	/** {@inheritDoc} */
	@Override
	public GL20 getGL20 () {
		return gl20;
	}

	/** {@inheritDoc} */
	@Override
	public void setGL20 (GL20 gl20) {
		this.gl20 = gl20;
		if (gl30 == null) {
			Gdx.gl = gl20;
			Gdx.gl20 = gl20;
		}
	}

	/** {@inheritDoc} */
	@Override
	public boolean isGL30Available () {
		return gl30 != null;
	}

	/** {@inheritDoc} */
	@Override
	public GL30 getGL30 () {
		return gl30;
	}

	/** {@inheritDoc} */
	@Override
	public void setGL30 (GL30 gl30) {
		this.gl30 = gl30;
		if (gl30 != null) {
			this.gl20 = gl30;

			Gdx.gl = gl20;
			Gdx.gl20 = gl20;
			Gdx.gl30 = gl30;
		}
	}

	/** {@inheritDoc} */
	@Override
	public int getHeight () {
		return height;
	}

	/** {@inheritDoc} */
	@Override
	public int getWidth () {
		return width;
	}

	@Override
	public int getBackBufferWidth () {
		return width;
	}

	@Override
	public int getBackBufferHeight () {
		return height;
	}

	/** This instantiates the GL10, GL11 and GL20 instances. Includes the check for certain devices that pretend to support GL11 but
	 * fuck up vertex buffer objects. This includes the pixelflinger which segfaults when buffers are deleted as well as the
	 * Motorola CLIQ and the Samsung Behold II.
	 *
	 * @param gl */
	private void setupGL (javax.microedition.khronos.opengles.GL10 gl) {
		String versionString = gl.glGetString(GL10.GL_VERSION);
		String vendorString = gl.glGetString(GL10.GL_VENDOR);
		String rendererString = gl.glGetString(GL10.GL_RENDERER);
		glVersion = new GLVersion(Application.ApplicationType.Android, versionString, vendorString, rendererString);
		if (config.useGL30 && glVersion.getMajorVersion() > 2) {
			if (gl30 != null) return;
			gl20 = gl30 = new AndroidGL30();

			Gdx.gl = gl30;
			Gdx.gl20 = gl30;
			Gdx.gl30 = gl30;
		} else {
			if (gl20 != null) return;
			gl20 = new AndroidGL20();

			Gdx.gl = gl20;
			Gdx.gl20 = gl20;
		}

		Gdx.app.log(LOG_TAG, "OGL renderer: " + gl.glGetString(GL10.GL_RENDERER));
		Gdx.app.log(LOG_TAG, "OGL vendor: " + gl.glGetString(GL10.GL_VENDOR));
		Gdx.app.log(LOG_TAG, "OGL version: " + gl.glGetString(GL10.GL_VERSION));
		Gdx.app.log(LOG_TAG, "OGL extensions: " + gl.glGetString(GL10.GL_EXTENSIONS));
	}

	@Override
	public void onSurfaceChanged (javax.microedition.khronos.opengles.GL10 gl, int width, int height) {
		this.width = width;
		this.height = height;
		updatePpi();
		gl.glViewport(0, 0, this.width, this.height);
		if (created == false) {
			app.getApplicationListener().create();
			created = true;
			synchronized (this) {
				running = true;
			}
		}
		app.getApplicationListener().resize(width, height);
	}

	@Override
	public void onSurfaceCreated (javax.microedition.khronos.opengles.GL10 gl, EGLConfig config) {
		eglContext = ((EGL10)EGLContext.getEGL()).eglGetCurrentContext();
		setupGL(gl);
		logConfig(config);
		updatePpi();

		Mesh.invalidateAllMeshes(app);
		Texture.invalidateAllTextures(app);
		Cubemap.invalidateAllCubemaps(app);
		TextureArray.invalidateAllTextureArrays(app);
		ShaderProgram.invalidateAllShaderPrograms(app);
		FrameBuffer.invalidateAllFrameBuffers(app);

		logManagedCachesStatus();

		Display display = app.getWindowManager().getDefaultDisplay();
		this.width = display.getWidth();
		this.height = display.getHeight();
		this.mean = new WindowedMean(5);
		this.lastFrameTime = System.nanoTime();

		gl.glViewport(0, 0, this.width, this.height);
	}

	private void logConfig (EGLConfig config) {
		EGL10 egl = (EGL10)EGLContext.getEGL();
		EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
		int r = getAttrib(egl, display, config, EGL10.EGL_RED_SIZE, 0);
		int g = getAttrib(egl, display, config, EGL10.EGL_GREEN_SIZE, 0);
		int b = getAttrib(egl, display, config, EGL10.EGL_BLUE_SIZE, 0);
		int a = getAttrib(egl, display, config, EGL10.EGL_ALPHA_SIZE, 0);
		int d = getAttrib(egl, display, config, EGL10.EGL_DEPTH_SIZE, 0);
		int s = getAttrib(egl, display, config, EGL10.EGL_STENCIL_SIZE, 0);
		int samples = Math.max(getAttrib(egl, display, config, EGL10.EGL_SAMPLES, 0),
			getAttrib(egl, display, config, GdxEglConfigChooser.EGL_COVERAGE_SAMPLES_NV, 0));
		boolean coverageSample = getAttrib(egl, display, config, GdxEglConfigChooser.EGL_COVERAGE_SAMPLES_NV, 0) != 0;

		Gdx.app.log(LOG_TAG, "framebuffer: (" + r + ", " + g + ", " + b + ", " + a + ")");
		Gdx.app.log(LOG_TAG, "depthbuffer: (" + d + ")");
		Gdx.app.log(LOG_TAG, "stencilbuffer: (" + s + ")");
		Gdx.app.log(LOG_TAG, "samples: (" + samples + ")");
		Gdx.app.log(LOG_TAG, "coverage sampling: (" + coverageSample + ")");

		bufferFormat = new BufferFormat(r, g, b, a, d, s, samples, coverageSample);
	}

	int[] value = new int[1];

	private int getAttrib (EGL10 egl, EGLDisplay display, EGLConfig config, int attrib, int defValue) {
		if (egl.eglGetConfigAttrib(display, config, attrib, value)) {
			return value[0];
		}
		return defValue;
	}

	Object synch = new Object();

	void resume () {
		synchronized (synch) {
			running = true;
			resume = true;
		}
	}

	void pause () {
		synchronized (synch) {
			if (!running) return;
			running = false;
			pause = true;
			while (pause) {
				try {
					// TODO: fix deadlock race condition with quick resume/pause.
					// Temporary workaround:
					// Android ANR time is 5 seconds, so wait up to 4 seconds before assuming
					// deadlock and killing process. This can easily be triggered by opening the
					// Recent Apps list and then double-tapping the Recent Apps button with
					// ~500ms between taps.
					synch.wait(4000);
					if (pause) {
						// pause will never go false if onDrawFrame is never called by the GLThread
						// when entering this method, we MUST enforce continuous rendering
						Gdx.app.error(LOG_TAG, "waiting for pause synchronization took too long; assuming deadlock and killing");
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				} catch (InterruptedException ignored) {
					Gdx.app.log(LOG_TAG, "waiting for pause synchronization failed!");
				}
			}
		}
	}

	void destroy () {
		synchronized (synch) {
			running = false;
			destroy = true;

			while (destroy) {
				try {
					synch.wait();
				} catch (InterruptedException ex) {
					Gdx.app.log(LOG_TAG, "waiting for destroy synchronization failed!");
				}
			}
		}
	}

	@Override
	public void onDrawFrame (javax.microedition.khronos.opengles.GL10 gl) {
		long time = System.nanoTime();
		deltaTime = (time - lastFrameTime) / 1000000000.0f;
		lastFrameTime = time;

		// After pause deltaTime can have somewhat huge value that destabilizes the mean, so let's cut it off
		if (!resume) {
			mean.addValue(deltaTime);
		} else {
			deltaTime = 0;
		}

		boolean lrunning = false;
		boolean lpause = false;
		boolean ldestroy = false;
		boolean lresume = false;

		synchronized (synch) {
			lrunning = running;
			lpause = pause;
			ldestroy = destroy;
			lresume = resume;

			if (resume) {
				resume = false;
			}

			if (pause) {
				pause = false;
				synch.notifyAll();
			}

			if (destroy) {
				destroy = false;
				synch.notifyAll();
			}
		}

		if (lresume) {
			SnapshotArray<LifecycleListener> lifecycleListeners = app.getLifecycleListeners();
			synchronized (lifecycleListeners) {
				LifecycleListener[] listeners = lifecycleListeners.begin();
				for (int i = 0, n = lifecycleListeners.size; i < n; ++i) {
					listeners[i].resume();
				}
				lifecycleListeners.end();
			}
			app.getApplicationListener().resume();
			Gdx.app.log(LOG_TAG, "resumed");
		}

		if (lrunning) {
			synchronized (app.getRunnables()) {
				app.getExecutedRunnables().clear();
				app.getExecutedRunnables().addAll(app.getRunnables());
				app.getRunnables().clear();
			}

			for (int i = 0; i < app.getExecutedRunnables().size; i++) {
				try {
					app.getExecutedRunnables().get(i).run();
				} catch (Throwable t) {
					t.printStackTrace();
				}
			}
			app.getInput().processEvents();
			frameId++;
			app.getApplicationListener().render();
		}

		if (lpause) {
			SnapshotArray<LifecycleListener> lifecycleListeners = app.getLifecycleListeners();
			synchronized (lifecycleListeners) {
				LifecycleListener[] listeners = lifecycleListeners.begin();
				for (int i = 0, n = lifecycleListeners.size; i < n; ++i) {
					listeners[i].pause();
				}
			}
			app.getApplicationListener().pause();
			Gdx.app.log(LOG_TAG, "paused");
		}

		if (ldestroy) {
			SnapshotArray<LifecycleListener> lifecycleListeners = app.getLifecycleListeners();
			synchronized (lifecycleListeners) {
				LifecycleListener[] listeners = lifecycleListeners.begin();
				for (int i = 0, n = lifecycleListeners.size; i < n; ++i) {
					listeners[i].dispose();
				}
			}
			app.getApplicationListener().dispose();
			Gdx.app.log(LOG_TAG, "destroyed");
		}

		if (time - frameStart > 1000000000) {
			fps = frames;
			frames = 0;
			frameStart = time;
		}
		frames++;
	}

	@Override
	public long getFrameId () {
		return frameId;
	}

	/** {@inheritDoc} */
	@Override
	public float getDeltaTime () {
		return mean.getMean() == 0 ? deltaTime : mean.getMean();
	}

	@Override
	public float getRawDeltaTime () {
		return deltaTime;
	}

	/** {@inheritDoc} */
	@Override
	public GraphicsType getType () {
		return GraphicsType.AndroidGL;
	}

	/** {@inheritDoc} */
	@Override
	public GLVersion getGLVersion () {
		return glVersion;
	}

	/** {@inheritDoc} */
	@Override
	public int getFramesPerSecond () {
		return fps;
	}

	public void clearManagedCaches () {
		Mesh.clearAllMeshes(app);
		Texture.clearAllTextures(app);
		Cubemap.clearAllCubemaps(app);
		TextureArray.clearAllTextureArrays(app);
		ShaderProgram.clearAllShaderPrograms(app);
		FrameBuffer.clearAllFrameBuffers(app);

		logManagedCachesStatus();
	}

	protected void logManagedCachesStatus () {
		Gdx.app.log(LOG_TAG, Mesh.getManagedStatus());
		Gdx.app.log(LOG_TAG, Texture.getManagedStatus());
		Gdx.app.log(LOG_TAG, Cubemap.getManagedStatus());
		Gdx.app.log(LOG_TAG, ShaderProgram.getManagedStatus());
		Gdx.app.log(LOG_TAG, FrameBuffer.getManagedStatus());
	}

	public View getView () {
		return view;
	}

	@Override
	public float getPpiX () {
		return ppiX;
	}

	@Override
	public float getPpiY () {
		return ppiY;
	}

	@Override
	public float getPpcX () {
		return ppcX;
	}

	@Override
	public float getPpcY () {
		return ppcY;
	}

	@Override
	public float getDensity () {
		return density;
	}

	@Override
	public boolean supportsDisplayModeChange () {
		return false;
	}

	@Override
	public boolean setFullscreenMode (DisplayMode displayMode) {
		return false;
	}

	@Override
	public Monitor getPrimaryMonitor () {
		return new AndroidMonitor(0, 0, "Primary Monitor");
	}

	@Override
	public Monitor getMonitor () {
		return getPrimaryMonitor();
	}

	@Override
	public Monitor[] getMonitors () {
		return new Monitor[] { getPrimaryMonitor() };
	}

	@Override
	public DisplayMode[] getDisplayModes (Monitor monitor) {
		return getDisplayModes();
	}

	@Override
	public DisplayMode getDisplayMode (Monitor monitor) {
		return getDisplayMode();
	}

	@Override
	public DisplayMode[] getDisplayModes () {
		return new DisplayMode[] {getDisplayMode()};
	}

	@Override
	public boolean setWindowedMode (int width, int height) {
		return false;
	}

	@Override
	public void setTitle (String title) {

	}

	@Override
	public void setUndecorated (boolean undecorated) {
		final int mask = (undecorated) ? 1 : 0;
		app.getApplicationWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, mask);
	}

	@Override
	public void setResizable (boolean resizable) {

	}

	@Override
	public DisplayMode getDisplayMode () {
		DisplayMetrics metrics = new DisplayMetrics();
		app.getWindowManager().getDefaultDisplay().getMetrics(metrics);
		return new AndroidDisplayMode(metrics.widthPixels, metrics.heightPixels, 0, 0);
	}

	@Override
	public BufferFormat getBufferFormat () {
		return bufferFormat;
	}

	@Override
	public void setVSync (boolean vsync) {
	}

	@Override
	public boolean supportsExtension (String extension) {
		if (extensions == null) extensions = Gdx.gl.glGetString(GL10.GL_EXTENSIONS);
		return extensions.contains(extension);
	}

	@Override
	public void setContinuousRendering (boolean isContinuous) {
		if (view != null) {
			// ignore setContinuousRendering(false) while pausing
			this.isContinuous = enforceContinuousRendering || isContinuous;
			int renderMode = this.isContinuous ? GLSurfaceView.RENDERMODE_CONTINUOUSLY : GLSurfaceView.RENDERMODE_WHEN_DIRTY;
			if (view instanceof GLSurfaceViewAPI18) ((GLSurfaceViewAPI18)view).setRenderMode(renderMode);
			if (view instanceof GLSurfaceView) ((GLSurfaceView)view).setRenderMode(renderMode);
			mean.clear();
		}
	}

	@Override
	public boolean isContinuousRendering () {
		return isContinuous;
	}

	@Override
	public void requestRendering () {
		if (view != null) {
			if (view instanceof GLSurfaceViewAPI18) ((GLSurfaceViewAPI18)view).requestRender();
			if (view instanceof GLSurfaceView) ((GLSurfaceView)view).requestRender();
		}
	}

	@Override
	public boolean isFullscreen () {
		return true;
	}

	@Override
	public Cursor newCursor (Pixmap pixmap, int xHotspot, int yHotspot) {
		return null;
	}

	@Override
	public void setCursor (Cursor cursor) {
	}

	@Override
	public void setSystemCursor (SystemCursor systemCursor) {
	}

	private class AndroidDisplayMode extends DisplayMode {
		protected AndroidDisplayMode (int width, int height, int refreshRate, int bitsPerPixel) {
			super(width, height, refreshRate, bitsPerPixel);
		}
	}

	private class AndroidMonitor extends Monitor {
		public AndroidMonitor (int virtualX, int virtualY, String name) {
			super(virtualX, virtualY, name);
		}
	}
}


text:
export interface IInferAllOptions {
  /**
   * Enforces to clear junction tree cache before inferring all network. Default: false
   */
  force?: boolean;
  /**
   * The results value precision. Default: 4
   */
  precision?: number;
}


text:
package alien4cloud.ui.form;

public class GenericFormConstants {

    public GenericFormConstants() {
    }

    public static final String SUGGESTION_KEY = "_suggestion";
    public static final String CONTENT_TYPE_KEY = "_contentType";
    public static final String TYPE_KEY = "_type";
    public static final String PROPERTY_TYPE_KEY = "_propertyType";
    public static final String ORDER_KEY = "_order";
    public static final String IMPLEMENTATIONS_KEY = "_implementationTypes";
    public static final String TOSCA_DEFINITION_KEY = "_definition";
    public static final String LABEL_KEY = "_label";

    public static final String TOSCA_TYPE = "tosca";
    public static final String COMPLEX_TYPE = "complex";
    public static final String ABSTRACT_TYPE = "abstract";
    public static final String MAP_TYPE = "map";
    public static final String ARRAY_TYPE = "array";
    public static final String NUMBER_TYPE = "number";
    public static final String BOOLEAN_TYPE = "boolean";
    public static final String STRING_TYPE = "string";
    public static final String DATE_TYPE = "date";
    public static final String VALID_VALUES_KEY = "_validValues";
    public static final String NOT_NULL_KEY = "_notNull";
    public static final String IS_PASSWORD_KEY = "_isPassword";
}


text:
@extends('cpanel::layouts')

@section('header')

Users

@stop

@section('breadcrumb')
@parent

        Users

Edit

@stop

@section('content')

        <?php
        $option = array(
            'route' => array('cpanel.users.update',$user->id),
            'method' => 'put',
            'class' => 'form-horizontal'
        );
        ?>
        {{ Form::model($user,$option) }}

Edit User "{{ $user->first_name }} {{ $user->last_name }}"

                            User Credentials

                            User Permissions

                                    First Name

                                        {{ Form::text('first_name',null,array('class'=>'form-control','placeholder'=>'First Name')) }}

                                    Last Name

                                        {{ Form::text('last_name',null,array('class'=>'form-control','placeholder'=>'Last Name')) }}

                                    Email

                                        {{ Form::email('email',null,array('class'=>'form-control','placeholder'=>'Email')) }}

                                    Password

                                        {{ Form::password('password',array('class'=>'form-control','placeholder'=>'Password')) }}
                                        leave blank to keep the same password

                                    Confirm Password

                                        {{ Form::password('password_confirmation',array('class'=>'form-control','placeholder'=>'Confirm Password')) }}
                                        leave blank to keep the same password

                                    Groups

                                        <select id="groups" name="groups[]" class="select2 form-control" multiple="true">
                                            @foreach($groups as $group)
                                            @if( in_array( $group->id, Input::old('groups', array())) or in_array($group->id, $userGroupsId) )
                                            <option selected="selected" value="{{ $group->id }}">{{ $group->name }}</option>
                                            @else
                                            <option value="{{ $group->id }}">{{ $group->name }}</option>
                                            @endif
                                            @endforeach
                                        </select>

                                        <button type="submit" class="btn btn-primary">Submit</button>

Permissions set here will override groups permissions

                            @include('cpanel::users.permissions_form')

        {{Form::close()}}

@stop


text:
{% extends 'site_signin.html' %}
{% load i18n %}

{% block title %}{% trans "Change password" %}{% endblock %}

{% block content_title %}
{% blocktrans with user.username as username %}Account » {{ username }}{% endblocktrans %}
{% endblock %}

{% block content %}

    <form action="" method="post" id="password_change_form">

{% trans 'View profile' %}

{% trans "Edit profile" %}

{% trans "Change password" %}

      <fieldset>
        <legend>{% trans "Change Password" %}</legend>
        {% csrf_token %}
        {{ form.as_p }}
      </fieldset>
      <input type="submit" value="{% trans "Change password" %}" />
    </form>

{% endblock %}


text:
package co.cask.cdap.data2.datafabric.dataset.type;

import co.cask.cdap.proto.DatasetModuleMeta;
import com.google.common.base.Objects;

import java.io.IOException;
import javax.annotation.Nullable;

/**
 * Simply returns the same {@link ClassLoader} for every dataset module. The assumption is that the
 * classloader has access to any dataset module that may be created.
 * This is true for a Program {@link ClassLoader} for example. Closing the given classloader is left to the caller.
 * It will not be closed when this class is closed.
 */
public class ConstantClassLoaderProvider implements DatasetClassLoaderProvider {
  private final ClassLoader classLoader;

  public ConstantClassLoaderProvider() {
    this(null);
  }

  public ConstantClassLoaderProvider(@Nullable ClassLoader classLoader) {
    this.classLoader = classLoader == null ?
      Objects.firstNonNull(Thread.currentThread().getContextClassLoader(), getClass().getClassLoader()) :
      classLoader;
  }

  @Override
  public ClassLoader get(DatasetModuleMeta moduleMeta, ClassLoader parentClassLoader) throws IOException {
    return classLoader;
  }

  @Override
  public void close() throws IOException {
    // no-op
    // closing the given classloader is left to the caller instead of this class
    // consider the case when a Program ClassLoader is being used, and this provider is used to instantiate
    // a dataset. Even though this provider can be closed, the program may not be finished and may still need
    // the classloader to load new classes later on.
  }
}


text:
class CFont;
class CHpBar : public CUI
{
public:
	CHpBar();
	virtual ~CHpBar();
	//

public:
	virtual HRESULT Initialize(void);
	virtual int Update(void);
	virtual void Render(void);
	void UpdateBufferToHp(void);

public:
	virtual HRESULT AddComponent(void);

public:
	CFont* m_pFont;
public:
	static CHpBar* Create();

};


text:
<?php

namespace ShopwareAdapter\ServiceBus\QueryHandler\Language;

use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;
use Shopware\Models\Shop\Locale;
use ShopwareAdapter\ResponseParser\Language\LanguageResponseParserInterface;
use ShopwareAdapter\ShopwareAdapter;
use SystemConnector\ServiceBus\Query\FetchTransferObjectQuery;
use SystemConnector\ServiceBus\Query\QueryInterface;
use SystemConnector\ServiceBus\QueryHandler\QueryHandlerInterface;
use SystemConnector\ServiceBus\QueryType;
use SystemConnector\TransferObject\Language\Language;

class FetchAllLanguagesQueryHandler implements QueryHandlerInterface
{
    /**
     * @var EntityRepository
     */
    private $repository;

    /**
     * @var LanguageResponseParserInterface
     */
    private $responseParser;

    public function __construct(
        EntityManagerInterface $entityManager,
        LanguageResponseParserInterface $responseParser
    ) {
        $this->repository = $entityManager->getRepository(Locale::class);
        $this->responseParser = $responseParser;
    }

    /**
     * {@inheritdoc}
     */
    public function supports(QueryInterface $query): bool
    {
        return $query instanceof FetchTransferObjectQuery &&
            $query->getAdapterName() === ShopwareAdapter::NAME &&
            $query->getObjectType() === Language::TYPE &&
            $query->getQueryType() === QueryType::ALL;
    }

    /**
     * {@inheritdoc}
     */
    public function handle(QueryInterface $query)
    {
        $elements = $this->createLocalesQuery()->getArrayResult();

        foreach ($elements as $element) {
            $result = $this->responseParser->parse($element);

            if (null === $result) {
                continue;
            }

            yield $result;
        }
    }

    /**
     * @return Query
     */
    private function createLocalesQuery(): Query
    {
        $queryBuilder = $this->repository->createQueryBuilder('locales');
        $queryBuilder->select([
            'locales.id as id',
            'locales.language as name',
            'locales.locale as locale',
        ]);

        $objectQuery = $queryBuilder->getQuery();
        $objectQuery->execute();

        return $objectQuery;
    }
}


text:
/**
 *
 */
package ac.victor.java.conferenceplanner.tests;

import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.regex.Pattern;

import org.junit.Test;

import ac.victor.java.conferenceplanner.Talk;
import ac.victor.java.conferenceplanner.exceptions.FileFormatException;
import ac.victor.java.conferenceplanner.utils.InputParserUtil;

/**
 * @author victor
 */

public class InputParserUtilTest {

	@Test
	public void testParseInputIntoTalks() {
		Talk t1 = new Talk("T1", 10);
		Talk t2 = new Talk("T2", 10);

		ArrayList<Talk> talkList = new ArrayList<Talk>(2);
		talkList.add(t1);
		talkList.add(t2);

		final Pattern pattern = Pattern.compile("something");

		try {
			assertEquals(talkList, InputParserUtil.parseFile("test_small.input"));
		} catch (FileFormatException e) {
			e.printStackTrace();
		}
	}

}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>HE_Mesh: wblut.hemesh.HET_MeshGraph.Node Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

HE_Mesh
    6.0.1

Main Page

Packages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

Public Member Functions |
Public Attributes |
List of all members

wblut.hemesh.HET_MeshGraph.Node Class Reference

   Inheritance diagram for wblut.hemesh.HET_MeshGraph.Node:

  <map id="wblut.hemesh.HET_MeshGraph.Node_map" name="wblut.hemesh.HET_MeshGraph.Node_map">
</map>

Public Member Functions

 	Node (final int id, final WB_Coord pos)

String 	toString ()

int 	compareTo (final Node other)

void 	reset ()

Public Attributes

final int 	index

List< Edge > 	neighbors

double 	distanceToSource = Double.POSITIVE_INFINITY

Node 	previous

double 	x

Constructor & Destructor Documentation

          wblut.hemesh.HET_MeshGraph.Node.Node
          (
          final int
          id,

          final WB_Coord
          pos

          )

Parameters

id

pos

References wblut.geom.WB_Coord.xd(), wblut.geom.WB_Coord.yd(), and wblut.geom.WB_Coord.zd().

Member Function Documentation

          int wblut.hemesh.HET_MeshGraph.Node.compareTo
          (
          final Node
          other	)

References wblut.hemesh.HET_MeshGraph.Node.distanceToSource.

          void wblut.hemesh.HET_MeshGraph.Node.reset
          (
          	)

          String wblut.hemesh.HET_MeshGraph.Node.toString
          (
          	)

References wblut.hemesh.HET_MeshGraph.Node.index.

Member Data Documentation

          double wblut.hemesh.HET_MeshGraph.Node.distanceToSource = Double.POSITIVE_INFINITY

          final int wblut.hemesh.HET_MeshGraph.Node.index

          List<Edge> wblut.hemesh.HET_MeshGraph.Node.neighbors

          Node wblut.hemesh.HET_MeshGraph.Node.previous

          double wblut.hemesh.HET_MeshGraph.Node.x

The documentation for this class was generated from the following file:

src/hemesh_tools/wblut/hemesh/HET_MeshGraph.java

wblut

hemesh

HET_MeshGraph

Node

Generated on Tue Dec 19 2017 21:20:58 for HE_Mesh by

     1.8.10