text:
/* Indexes
 *********/

Meteor.rooms._ensureIndex('name', {unique: 1});

/* Default server settings if null
 *********************************/

Meteor.startup(function () {
	if (Meteor.mrc.find({}).count() === 0) {
		mrc = Meteor.mrc.insert({
			sitename: 'MRC+', // Your site name
			privserver: false, // Prevents guests from seeing even default room.  Once signed in an admin must promote to use before use.
			guestrooms: false, // Can guests see rooms? (other than default room)
			guestchats: false, // Can guests use chat system?
			guestsuppo: false  // Can guests use support?
		});
	}

	if (Meteor.rooms.find({}).count() === 0) {
		Meteor.rooms.insert({name: "Main Room", droom: true, force: true, guests: true, invite: false, limits: false});
		Meteor.rooms.insert({name: "Staff Room", sroom: true, guests: false, invite: false, limits: {role: ['helper', 'admin']}});
		Meteor.rooms.insert({name: "Admin Room", aroom: true, guests: true, invite: false, limits: {role: ['admin']}});
	}
});

/* Observe Collections
 *********************/

Meteor.users.find({"status.online": true}).observe({
	added: function (user) {
		// user just came online
		var droom = Meteor.rooms.findOne({droom: true})._id;
		var status = Meteor.users.findOne({_id: user._id}).status;
		if (status.disc !== false) {
			Meteor.users.update({_id: user._id}, {$set: {'status.disc': false}});
			Meteor.messages.insert({date: new Date(), room: droom, join: true, user: user._id});
		}
	},
	removed: function (user) {
		// user just went offline
		var droom = Meteor.rooms.findOne({droom: true})._id;

		Meteor.setTimeout(function () {
			var status = Meteor.users.findOne({_id: user._id}).status;
			if (!status.online && !status.disc) {
				Meteor.users.update({_id: user._id}, {$set: {'status.disc': true}});
				Meteor.messages.insert({date: new Date(), room: droom, quit: true, user: user._id});
			}
		}, 10000);
	}
});

/* Publishes
 ***********/

// public list of rooms --- needs limiting to rooms you can see.
Meteor.publish("rooms", function () {
	return Meteor.rooms.find({});
});

// publish messages per room --- needs checking on access to room
Meteor.publish("roomMessages", function (room) {
	return Meteor.messages.find({room: room});
});

// usernames and profiles are public --- maybes needs limiting to only who's online (unless admin)
Meteor.publish('usernames', function () {
	return Meteor.users.find({}, {fields: {username: 1, role: 1, profile: 1}});
});

// user status
Meteor.publish("userStatus", function () {
	if (Roles.userIsInRole(this.userId, ['owner', 'admin'], 'server')) {
		return Meteor.users.find({"status.online": true}, {fields: {"status.online": 1, "status.idle": 1, "status.lastActivity": 1, "status.lastLogin": 1, "banned.expires": 1, "banned.reason": 1, "muted": 1}});
	} else {
		return Meteor.users.find({"status.online": true}, {fields: {"status.online": 1, "status.idle": 1, "status.lastActivity": 1, "banned.expires": 1, "banned.reason": 1, "muted": 1}});
	}
});

// Roles
Meteor.publish(null, function () {
	return Meteor.roles.find({});
});

// Social Media Info to Admins

// Give authorized users access to sensitive data by group
Meteor.publish('adminInfo', function () {
	if (Roles.userIsInRole(this.userId, ['owner', 'admin'], 'server')) {
		return Meteor.users.find({}, {fields: {services: 1, status: 1, roles: 1}});
	} else {
		this.stop();
		return;
	}
});


text:
package es.tid.pce.pcep.objects.tlvs;

import es.tid.pce.pcep.objects.MalformedPCEPObjectException;
import es.tid.pce.pcep.objects.ObjectParameters;

/**
 * GMPLS-CAPABILITY TLV, see draft-ietf-pce-gmpls-pcep-extensions-10.
 * Encoding: standard
 * TLV Type: non-standard (14, as per draft-ietf-pce-gmpls-pcep-extensions-10 )
 *
 * In addition to the IGP advertisement, a PCEP speaker should be able
   to discover the other peer GMPLS capabilities during the Open message
   exchange.  This capability is also useful to avoid misconfigurations.
   This document defines a new optional GMPLS-CAPABILITY TLV for use in
   the OPEN object to negotiate the GMPLS capability.  The inclusion of
   this TLV in the OPEN message indicates that the PCC/PCE support the
   PCEP extensions defined in the document.  A PCE that is able to
   support the GMPLS extensions defined in this document SHOULD include
   the GMPLS-CAPABILITY TLV on the OPEN message.  If the PCE does not
   include the GMPLS-CAPABILITY TLV in the OPEN message and PCC does
   include the TLV, it is RECOMMENDED that the PCC indicates a mismatch
   of capabilities.  Moreover , in case that the PCC does not receive
   the GMPLS-CAPABILITY TLV it is RECOMMENDED that the PCC does not make
   use of the objects and TLVs defined in this document.

   IANA has allocated value 14 from the "PCEP TLV Type Indicators" sub-
   registry, as documented in Section Section 5.3 ("New PCEP TLVs").
   The description is "GMPLS capable".  Its format is shown in the
   following figure.

    0                   1                   2                   3
    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |               Type=14       |             Length              |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
    |                             Flags                             |
    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

   No Flags are defined in this document, they are reserved for future
   use.
 *
 * @author ogondio
 *
 */
public class GMPLSCapabilityTLV extends PCEPTLV {

	public GMPLSCapabilityTLV(){
		this.setTLVType(ObjectParameters.PCEP_TLV_TYPE_GMPLS_CAPABILITY);

	}

	public GMPLSCapabilityTLV(byte[] bytes, int offset) throws MalformedPCEPObjectException{
		super(bytes,offset);
		decode();
	}

	public void decode(){
		//No flags defined so far
	}

	public void encode() {
		this.setTLVValueLength(4);
		this.tlv_bytes=new byte[this.getTotalTLVLength()];
		this.encodeHeader();
		this.tlv_bytes[4]=0x00;
		this.tlv_bytes[5]=0x00;
		this.tlv_bytes[6]=0x00;
		this.tlv_bytes[7]=0x00;

	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		return true;
	}

}

redpajama_set_name: RedPajamaGithub


text:
id: 5900f3941000cf542c50fea7
challengeType: 5
title: 'Problem 40: Champernowne"s constant'
videoUrl: ''
localeTitle: 'Problema 40: constante de Champernowne'
---

## Description

 Uma fração decimal irracional é criado pela concatenação dos inteiros positivos: 0,12345678910 1 112131415161718192021 ... Pode ser visto que o 12º dígito da parte fracionária é 1. Se d n representa o n th dígitos da parte fracionária, encontrar o valor da seguinte expressão. d 1 × d 10 × d 100 × d 1000 × d 10000 × d 100000 × d 1000000

## Instructions

## Tests

```yml
tests:
  - text: <code>champernownesConstant(100)</code> deve retornar 5.
    testString: 'assert.strictEqual(champernownesConstant(100), 5, "<code>champernownesConstant(100)</code> should return 5.");'
  - text: <code>champernownesConstant(1000)</code> deve retornar 15.
    testString: 'assert.strictEqual(champernownesConstant(1000), 15, "<code>champernownesConstant(1000)</code> should return 15.");'
  - text: <code>champernownesConstant(1000000)</code> deve retornar 210.
    testString: 'assert.strictEqual(champernownesConstant(1000000), 210, "<code>champernownesConstant(1000000)</code> should return 210.");'

```

## Challenge Seed

```js
function champernownesConstant(n) {
  // Good luck!
  return true;
}

champernownesConstant(100);

```

## Solution

```js
// solution required
```


text:
namespace DDDLite.CQRS.Messaging.InMemory
{
  using System;
  using System.Threading.Tasks;
  using DDDLite.CQRS.Commands;
  using DDDLite.CQRS.Messaging;

  public class InMemoryCommandBus : InMemoryMessageBus, ICommandSender
  {
    public Task SendAsync<TCommand>(TCommand command) where TCommand : class, ICommand
    {
      return base.CommitAsync(command);
    }
  }
}


text:
/*global describe, it*/
'use strict';

var should = require('should'),
  git = require('../lib/git');

require('mocha');

describe('gulp-gitmodified', function () {

  it('should have mockable which and exec', function (done) {
    var fnCalls = 0;
    git.which = function (app, cb) {
      ++fnCalls;
      app.should.equal('git');
      cb();
    };
    git.exec = function (app, args, extra, cb) {
      ++fnCalls;
      app.should.equal('git');
      cb(null, '');
    };
    git.getStatusByMatcher(new RegExp('^(M)\\s', 'i'), function (err) {
      should(err).equal(null);
      fnCalls.should.equal(2);
      done();
    });
  });

  it('should give error if git is not found on the system', function (done) {
    git.which = function (app, cb) {
      cb(new Error());
    };
    git.exec = function (app, args, extra, cb) {
      cb(null, '');
    };
    git.getStatusByMatcher(new RegExp('^(M)\\s', 'i'), function (err) {
      should(err.message).equal('git not found on your system.');
      done();
    });
  });

  it('should pass on cwd', function (done) {
    git.which = function (app, cb) {
      cb();
    };
    git.exec = function (app, args, extra, cb) {
      extra.cwd.should.equal('foo');
      done();
    };
    git.getStatusByMatcher(new RegExp('^(M)\\s', 'i'), 'foo', function (err) {
      should(err.message).equal('git not found on your system.');
      done();
    });
  });

  it('should return a file returned by git status', function (done) {
    git.which = function (app, cb) {
      cb();
    };
    git.exec = function (app, args, extra, cb) {
      cb(null, 'M index.js');
    };
    git.getStatusByMatcher(new RegExp('^(M)\\s', 'i'), function (err, data) {
      should.not.exist(err);
      should.exist(data);
      should.exist(data[0]);
      data[0].should.eql({
        mode: 'M',
        path: 'index.js'
      });
      done();
    });
  });

  it('should return several files from git status', function (done) {
    git.which = function (app, cb) {
      cb();
    };
    git.exec = function (app, args, extra, cb) {
      cb(null, 'M index.js\nM foo.js\nM bar.js');
    };
    git.getStatusByMatcher(new RegExp('^(M)\\s', 'i'), function (err, data) {
      should.not.exist(err);
      should.exist(data);
      should.exist(data[0]);
      data.length.should.equal(3);
      done();
    });
  });

  it('should return statused files which match pattern', function (done) {
    git.which = function (app, cb) {
      cb();
    };
    git.exec = function (app, args, extra, cb) {
      cb(null, 'M index.js\nD foo.js\nM bar.js');
    };
    git.getStatusByMatcher(new RegExp('^(M)\\s', 'i'), function (err, data) {
      should.not.exist(err);
      data.length.should.equal(2);
      data[0].should.eql({ mode: 'M', path: 'index.js' });
      data[1].should.eql({ mode: 'M', path: 'bar.js' });
      done();
    });
  });

  it('should return statused files which match complex pattern', function (done) {
    git.which = function (app, cb) {
      cb();
    };
    git.exec = function (app, args, extra, cb) {
      cb(null, 'M index.js\nD foo.js\nM bar.js\nA baz.js');
    };
    git.getStatusByMatcher(new RegExp('^(A|D)\\s', 'i'), function (err, data) {
      should.not.exist(err);
      data.length.should.equal(2);
      data[0].should.eql({ mode: 'D', path: 'foo.js' });
      data[1].should.eql({ mode: 'A', path: 'baz.js' });
      done();
    });
  });

  it('should return statused files which match complex pattern', function (done) {
    git.which = function (app, cb) {
      cb();
    };
    git.exec = function (app, args, extra, cb) {
      cb(null, 'C index.js\n?? foo.js\n  bar.js\n!! baz.js');
    };
    git.getStatusByMatcher(new RegExp('^(C|!!|\\?\\?)\\s', 'i'), function (err, data) {
      should.not.exist(err);
      data.length.should.equal(3);
      data[0].should.eql({ mode: 'C', path: 'index.js' });
      data[1].should.eql({ mode: '??', path: 'foo.js' });
      data[2].should.eql({ mode: '!!', path: 'baz.js' });
      done();
    });
  });

});


text:
#include <sound/driver.h>
#include <linux/time.h>
#include <sound/core.h>
#include <sound/emu10k1.h>

/* Previously the voice allocator started at 0 every time.  The new voice
 * allocator uses a round robin scheme.  The next free voice is tracked in
 * the card record and each allocation begins where the last left off.  The
 * hardware requires stereo interleaved voices be aligned to an even/odd
 * boundary.  For multichannel voice allocation we ensure than the block of
 * voices does not cross the 32 voice boundary.  This simplifies the
 * multichannel support and ensures we can use a single write to the
 * (set|clear)_loop_stop registers.  Otherwise (for example) the voices would
 * get out of sync when pausing/resuming a stream.
 *							--rlrevell
 */

static int voice_alloc(struct snd_emu10k1 *emu, int type, int number,
		       struct snd_emu10k1_voice **rvoice)
{
	struct snd_emu10k1_voice *voice;
	int i, j, k, first_voice, last_voice, skip;

	*rvoice = NULL;
	first_voice = last_voice = 0;
	for (i = emu->next_free_voice, j = 0; j < NUM_G ; i += number, j += number) {
		// printk("i %d j %d next free %d!\n", i, j, emu->next_free_voice);
		i %= NUM_G;

		/* stereo voices must be even/odd */
		if ((number == 2) && (i % 2)) {
			i++;
			continue;
		}

		skip = 0;
		for (k = 0; k < number; k++) {
			voice = &emu->voices[(i+k) % NUM_G];
			if (voice->use) {
				skip = 1;
				break;
			}
		}
		if (!skip) {
			// printk("allocated voice %d\n", i);
			first_voice = i;
			last_voice = (i + number) % NUM_G;
			emu->next_free_voice = last_voice;
			break;
		}
	}

	if (first_voice == last_voice)
		return -ENOMEM;

	for (i = 0; i < number; i++) {
		voice = &emu->voices[(first_voice + i) % NUM_G];
		// printk("voice alloc - %i, %i of %i\n", voice->number, idx-first_voice+1, number);
		voice->use = 1;
		switch (type) {
		case EMU10K1_PCM:
			voice->pcm = 1;
			break;
		case EMU10K1_SYNTH:
			voice->synth = 1;
			break;
		case EMU10K1_MIDI:
			voice->midi = 1;
			break;
		case EMU10K1_EFX:
			voice->efx = 1;
			break;
		}
	}
	*rvoice = &emu->voices[first_voice];
	return 0;
}

int snd_emu10k1_voice_alloc(struct snd_emu10k1 *emu, int type, int number,
			    struct snd_emu10k1_voice **rvoice)
{
	unsigned long flags;
	int result;

	snd_assert(rvoice != NULL, return -EINVAL);
	snd_assert(number, return -EINVAL);

	spin_lock_irqsave(&emu->voice_lock, flags);
	for (;;) {
		result = voice_alloc(emu, type, number, rvoice);
		if (result == 0 || type == EMU10K1_SYNTH || type == EMU10K1_MIDI)
			break;

		/* free a voice from synth */
		if (emu->get_synth_voice) {
			result = emu->get_synth_voice(emu);
			if (result >= 0) {
				struct snd_emu10k1_voice *pvoice = &emu->voices[result];
				pvoice->interrupt = NULL;
				pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = pvoice->efx = 0;
				pvoice->epcm = NULL;
			}
		}
		if (result < 0)
			break;
	}
	spin_unlock_irqrestore(&emu->voice_lock, flags);

	return result;
}

EXPORT_SYMBOL(snd_emu10k1_voice_alloc);

int snd_emu10k1_voice_free(struct snd_emu10k1 *emu,
			   struct snd_emu10k1_voice *pvoice)
{
	unsigned long flags;

	snd_assert(pvoice != NULL, return -EINVAL);
	spin_lock_irqsave(&emu->voice_lock, flags);
	pvoice->interrupt = NULL;
	pvoice->use = pvoice->pcm = pvoice->synth = pvoice->midi = pvoice->efx = 0;
	pvoice->epcm = NULL;
	snd_emu10k1_voice_init(emu, pvoice->number);
	spin_unlock_irqrestore(&emu->voice_lock, flags);
	return 0;
}

EXPORT_SYMBOL(snd_emu10k1_voice_free);


text:
"""
CSV File Reader
"""

import csv
import os.path

from collections import defaultdict
from typing import Optional, Iterable, Dict, List

from ..errors import MetadataError
from ..model import Model, Entity, Property, Enumeration, EnumValue
from ..extensible import Reader
from ..utils import to_bool

PROPERTIES_FILE = "properties.csv"
ENTITIES_FILE = "entities.csv"
ENUMS_FILE = "enums.csv"
ENUM_VALUES_FILE = "enum_values.csv"

class CSVReader(Reader, name="csv"):

    model: Model

    def __init__(self, model: Optional[Model]=None) -> None:
        self.model = model or Model()

    def read_model(self, path: str) -> None:
        self.read_entities_file(os.path.join(path, ENTITIES_FILE))
        self.read_properties_file(os.path.join(path, PROPERTIES_FILE))
        self.read_enumerations_file(os.path.join(path, ENUMS_FILE))
        self.read_enum_values_file(os.path.join(path, ENUM_VALUES_FILE))

    def read_entities_file(self, filename: str) -> None:
        pass

    def read_properties_file(self, filename: str) -> None:
        with open(filename) as f:
            reader = csv.DictReader(f)
            self._read_property_rows(reader)

    def _property_from_row(self, row: Dict[str, str]) -> Property:
        name = row.get("name")
        if not name:
            raise MetadataError("Property in entity '{}' has no name"
                                .format(row.get("entity")))

        entity_name = row.get("entity")
        if not entity_name:
            raise MetadataError("Property '{}' has no entity."
                               .format(row.get("name")))

        try:
            tag = int(row["tag"])
        except TypeError:
            raise MetadataError("Invalid tag for property '{}.{}'"
                                .format(entity_name, name))

        # Empty string in CSV is interpreted None
        default: Optional[str] = row["default"] or None

        prop = Property(
            name=row["name"],
            tag=int(row["tag"]),
            raw_type=row["type"],
            label=row["label"],
            desc=row["description"],
            default=default,
            is_optional=to_bool(row["optional"]),
        )

        return prop

    def _read_property_rows(self, rows: Iterable[Dict[str,str]]) -> None:
        """Read properties from list of dictionaries where keys are
        meta-property names and values are meta-property values."""

        props: Dict[str,List[Property]]
        props = defaultdict(list)

        for row in rows:
            prop = self._property_from_row(row)
            entname = row["entity"]

            props[entname].append(prop)

        for entname, entprops in props.items():
            entity = Entity(name=entname, properties=entprops)
            self.model.add_entity(entity)

    def read_enumerations_file(self, filename: str) -> None:
        pass

    def read_enum_values_file(self, filename: str) -> None:
        # Enum file is optional
        if not os.path.isfile(filename):
            return

        with open(filename) as f:
            reader = csv.DictReader(f)
            self._read_enum_rows(reader)

    def _enum_value_from_row(self, row: Dict[str, str]) -> EnumValue:
        name = row.get("key")
        if not name:
            raise MetadataError("Enum value in enum '{}' has no key"
                                .format(row.get("enum")))

        enum_name = row.get("enum")
        if not enum_name:
            raise MetadataError("Key '{}' has no enum name."
                               .format(row.get("key")))

        try:
            value = int(row["value"])
        except TypeError:
            raise MetadataError("Invalid enum value '{}.{}'"
                                .format(enum_name, name))

        prop = EnumValue(
            key=row["key"],
            value=value,
            label=row["label"],
            desc=row["description"],
        )

        return prop

    def _read_enum_rows(self, rows: Iterable[Dict[str,str]]) -> None:
        """Read values of enums. Keys are: enum, key, value, label, desc."""

        values: Dict[str,List[EnumValue]]
        values = defaultdict(list)

        for row in rows:
            value = self._enum_value_from_row(row)
            enumname = row["enum"]

            values[enumname].append(value)

        for enumname, enumvalues in values.items():
            enum = Enumeration(name=enumname, values=enumvalues)
            self.model.add_enum(enum)


text:
<?php

namespace app\models;

use app\helpers\UserLogic;
use Yii;
use \app\core\models\Model;
use \yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;

/**
 * This is the model class for table "{{%api_month_detail}}".
 *
 * @property string $id
 * @property string $idvisit
 * @property string $mtime
 * @property string $visitor_datatype_9
 * @property string $visitor_datatype_10
 * @property string $visitor_datatype_12
 * @property string $visitor_datatype_11
 * @property string $updated_datatype_9
 * @property string $updated_datatype_10
 * @property string $updated_datatype_11
 * @property string $updated_datatype_12
 * @property string $visitor_username
 * @property integer $visitor_referrer
 * @property string $created_at
 * @property string $updated_at
 */
class ApiMonthDetail extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%api_month_detail}}';
    }

     /*
      * 更新时间
      */
     public function behaviors()
     {
         return [
             [
                 'class' => TimestampBehavior::className(),
             ],
         ];
     }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['idvisit', 'mtime', 'updated_datatype_10', 'updated_datatype_11', 'updated_datatype_12', 'updated_datatype_13', 'visitor_referrer', 'created_at', 'updated_at'], 'integer'],
            [[ 'visitor_datatype_10','visitor_datatype_11', 'visitor_datatype_12', 'visitor_datatype_13', 'visitor_username'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'idvisit' => 'Idvisit',
            'mtime' => 'Mtime',
            'viewMtime' => '月份',
            'visitor_datatype_10' => '投注总额',
            'visitor_datatype_11' => '优惠总额',
            'visitor_datatype_12' => '派彩总额',
            'visitor_datatype_13' => 'Visitor Datatype 13',

            'updated_datatype_10' => 'Updated Datatype 10',
            'updated_datatype_11' => 'Updated Datatype 11',
            'updated_datatype_12' => 'Updated Datatype 12',
            'updated_datatype_13' => 'Updated Datatype 13',

            'visitor_username' => '用户名',
            'visitor_referrer' => '来源',
            'viewVisitorReferrer' => '来源',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public static function xBatchInsert($array){
        return static::getDb()->createCommand()->batchInsert('api_month_detail', [
            'idvisit',
            'mtime',
            'visitor_username',
            "visitor_referrer",
            'created_at'
        ],$array)->execute();
    }

    public function getViewVisitorReferrer(){
        return UserLogic::$refEnum[$this->visitor_referrer]['txt'];
    }
    public function getViewMtime(){
        return date('Y-m',$this->mtime);
    }

}


text:
class qConvert : public qValue
{
public:
	qConvert(dt_BaseType * type, qValue * val, const qString &extrainfo="");
	qString print(int indent);
	virtual llvm::Value * BuildValue() ;
};


text:
import sys, os, pprint, random, cgi, json, time, datetime, pytz , hashlib, magic
from Kblog.models import *
try:
    import xml.etree.cElementTree as ET
except ImportError:
    import xml.etree.ElementTree as ET

reload(sys)
sys.setdefaultencoding('utf-8')
timeZone = pytz.timezone('Asia/Shanghai')
categoryRes = False
webInfo = False
navRes = False
themeConfs = False

def isset(v):
    try :
        type (eval(v))
    except :
        return  0
    else :
        return  1

def getThemePath():
	currTheme = Options.objects.get(name='theme')
	return 'themes/' + currTheme.value + '/'

def getWebInfo():
    global webInfo
    if webInfo == False:
        webInfo = retryGetWebInfo()
    return webInfo

def retryGetWebInfo():
    detail = Options.objects.exclude(name__contains='theme')
    newDetail = {}
    for val in detail:
        newDetail[val.name] = val.value
    return newDetail

def getNavList():
    global navRes
    if navRes == False:
        navRes = retryGetNavList()
	return navRes

def retryGetNavList():
	navList = Category.objects.filter(pid=0).all()
	return navList

def getCategoryList(countType=' '):
    global categoryRes
    if categoryRes == False:
        categoryRes = retryGetCategoryList(countType)
    return categoryRes

def retryGetCategoryList(countType):

	sql = 'SELECT category_id,name,pid,path,path||\'-\'||category_id AS bpath FROM "' + Meta.db_table + '_category" ORDER BY bpath'

	categoryList = Category.objects.raw(sql)
	categoryList = list(categoryList)

	for category in categoryList:
		countNbsp  = ''
		length     = int(len(category.bpath.split('-'))-2)*4

		for index in range(length):
			countNbsp += countType

		category.count = countNbsp

	return categoryList

def getProtocol(request):
	protocol = 'http://'
	if request.is_secure() == True:
		protocol = 'https://'
	return protocol

def checkLoginAdmin(userInfo):
	if (userInfo != False) and (userInfo['group'] == 'administrator'):
		return True
	else:
		return False

def getCurrTime():
    global timeZone
    return datetime.strftime(datetime.now(timeZone), '%Y-%m-%d %H:%M:%S')

def getTheme():
	currTheme = Options.objects.get(name='theme')
	return currTheme.value

def getThemesConfig():
    global themeConfs
    if themeConfs == False:
        themeConfs = scanThemesConfig()
    return themeConfs

def scanThemesConfig():
    index       = 0
    configList  = {}
    mydir       = os.path.split(os.path.realpath(__file__))[0] + '/../templates/themes/'

    for dirs in os.listdir(mydir):

        confPath = os.path.join(mydir, dirs)
        if os.path.isdir(confPath) and os.path.exists(confPath + '/config.xml'):

            try:
                tree = ET.parse(confPath + '/config.xml')
                root = tree.getroot()
            except Exception, e:
                print "Error:cannot parse file: config.xml"
                print e
                sys.exit(1)

            configList[index] = {}
            key = 0
            for child in root:
                configList[index][child.tag] = child.text
                key += 1

            index += 1
    return configList

def getSizeInNiceString(sizeInBytes):

    for (cutoff, label) in [(1024*1024*1024, 'GB'), (1024*1024, 'MB'), (1024, 'KB')]:

        if sizeInBytes >= cutoff:
            return '%.1f %s' % (sizeInBytes * 1.0 / cutoff, label)

    if sizeInBytes == 1:
        return '1 byte'
    else:
        bytes = '%.1f' % (sizeInBytes or 0,)
        return (bytes[:-2] if bytes.endswith('.0') else bytes) + ' bytes'

def message(msg='', url=''):
	return u"alert('" + msg + "');window.location.href='" + url + "';"


text:
package com.savoirtech.json.rules;

import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;

import com.savoirtech.json.JsonComparatorResult;
import com.savoirtech.json.model.JsonComparatorRuleSpecification;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;

import static org.junit.Assert.*;

/**
 * Verify operation of the JsonComparatorCompiledRule.
 *
 * Created by art on 5/10/16.
 */
public class JsonComparatorCompiledRuleTest {

  private JsonComparatorCompiledRule compiledRule;

  private JsonComparatorRuleSpecification ruleSpecification;
  private JsonComparatorRule mockRule;
  private RuleChildComparator mockChildComparator;

  private JsonElement templateEle;
  private JsonElement actualEle;

  /**
   * Setup common test data and interactions.
   */
  @Before
  public void setupTest() throws Exception {
    this.mockRule = Mockito.mock(JsonComparatorRule.class);
    this.mockChildComparator = Mockito.mock(RuleChildComparator.class);

    this.ruleSpecification = new JsonComparatorRuleSpecification();

    this.templateEle = new JsonPrimitive(1);
    this.actualEle = new JsonPrimitive(1);

    this.compiledRule = new JsonComparatorCompiledRule(this.mockRule, this.ruleSpecification);
  }

  @Test
  public void testGetRule() throws Exception {
    assertSame(this.mockRule, this.compiledRule.getRule());
  }

  @Test
  public void testGetRuleSpecification() throws Exception {
    assertSame(this.ruleSpecification, this.compiledRule.getSpecification());
  }

  /**
   * Verify operation of the compare method on the compiled rule.
   */
  @Test
  public void testCompare() throws Exception {
    //
    // Setup test data and interactions
    //
    JsonComparatorResult testResult = new JsonComparatorResult(true, true, null, null);
    Mockito.when(this.mockRule
                     .compare("x-path-x", this.templateEle, this.actualEle, this.ruleSpecification,
                              this.mockChildComparator)).thenReturn(testResult);

    //
    // Execute
    //
    JsonComparatorResult
        actualResult =
        this.compiledRule
            .compare("x-path-x", this.templateEle, this.actualEle, this.mockChildComparator);

    //
    // Verify
    //
    assertSame(testResult, actualResult);
  }
}


text:
/**
 * collect compoents needed.
 */

var Promise = require('bluebird');
var exports = module.exports = function(dependencies) {
    var compoents = dependencies.concat();

    return Promise

        .map(dependencies, function(remote) {
            return remote.getDependencies();
        })

        // flatten all.
        .then(function(all) {
            all.forEach(function(deps) {
                compoents.push.apply(compoents, deps);
            });

            return compoents;
        });
};


text:
module Opendata::Api::PackageShowFilter
  extend ActiveSupport::Concern
  include Opendata::Api

  private
    def package_show_check(id)

      id_messages = []
      id_messages << "Missing value" if id.blank?

      messages = {}
      messages[:name_or_id] = id_messages if id_messages.present?

      if messages.present?
        error = {__type: "Validation Error"}
        error = error.merge(messages)
      end

      return error
    end

  public
    def package_show
      help = t("opendata.api.package_show_help")

      id = params[:id]
      id = URI.decode(id) if id
      #use_default_schema = params[:use_default_schema]

      error = package_show_check(id)
      if error
        render json: {help: help, success: false, error: error} and return
      end

      datasets = Opendata::Dataset.site(@cur_site).and_public
      datasets = datasets.any_of({"id" => id}, {"name" => id}).order_by(name: 1)

      if datasets.count > 0
        res = {help: help, success: true, result: convert_package(datasets[0])}
      else
        res = {help: help, success: false}
        res[:error] = {message: "Not found", __type: "Not Found Error"}
      end

      render json: res
    end

end


text:
Technical Notes
===============

Essays on mathematical and implementation details.

.. toctree::
    :maxdepth: 2

    likelihood
    sigma
    api_structure


text:
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Audio.Track;
using osu.Framework.Testing;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.IO.Archives;
using osu.Game.Tests.Resources;
using osu.Game.Tests.Visual;

namespace osu.Game.Tests.Skins
{
    [HeadlessTest]
    public class TestSceneBeatmapSkinResources : OsuTestScene
    {
        [Resolved]
        private BeatmapManager beatmaps { get; set; }

        private WorkingBeatmap beatmap;

        [BackgroundDependencyLoader]
        private void load()
        {
            var imported = beatmaps.Import(new ZipArchiveReader(TestResources.OpenResource("Archives/ogg-beatmap.osz"))).Result;
            beatmap = beatmaps.GetWorkingBeatmap(imported.Beatmaps[0]);
            beatmap.LoadTrack();
        }

        [Test]
        public void TestRetrieveOggSample() => AddAssert("sample is non-null", () => beatmap.Skin.GetSample(new SampleInfo("sample")) != null);

        [Test]
        public void TestRetrieveOggTrack() => AddAssert("track is non-null", () => !(beatmap.Track is TrackVirtual));
    }
}


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

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.OverlayLayout;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.utils.Pool;

/** An implementation of the {@link Input} interface hooking a LWJGL panel for input.
 *
 * @author mzechner */
final public class LwjglInput implements Input {
	static public float keyRepeatInitialTime = 0.4f;
	static public float keyRepeatTime = 0.1f;

	List<KeyEvent> keyEvents = new ArrayList<KeyEvent>();
	List<TouchEvent> touchEvents = new ArrayList<TouchEvent>();
	boolean mousePressed = false;
	int mouseX, mouseY;
	int deltaX, deltaY;
	int pressedKeys = 0;
	boolean justTouched = false;
	Set<Integer> pressedButtons = new HashSet<Integer>();
	InputProcessor processor;
	char lastKeyCharPressed;
	float keyRepeatTimer;
	long currentEventTimeStamp;

	Pool<KeyEvent> usedKeyEvents = new Pool<KeyEvent>(16, 1000) {
		protected KeyEvent newObject () {
			return new KeyEvent();
		}
	};

	Pool<TouchEvent> usedTouchEvents = new Pool<TouchEvent>(16, 1000) {
		protected TouchEvent newObject () {
			return new TouchEvent();
		}
	};

	public LwjglInput () {
		Keyboard.enableRepeatEvents(false);
		Mouse.setClipMouseCoordinatesToWindow(false);
	}

	public float getAccelerometerX () {
		return 0;
	}

	public float getAccelerometerY () {
		return 0;
	}

	public float getAccelerometerZ () {
		return 0;
	}

	public void getTextInput (final TextInputListener listener, final String title, final String text) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run () {
				final String output = JOptionPane.showInputDialog(null, title, text);
				if (output != null)
					Gdx.app.postRunnable(new Runnable() {
						@Override
						public void run () {
							listener.input(output);
						}
					});
				else
					Gdx.app.postRunnable(new Runnable() {
						@Override
						public void run () {
							listener.canceled();
						}
					});
			}
		});
	}

	public void getPlaceholderTextInput (final TextInputListener listener, final String title, final String placeholder) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run () {
				JPanel panel = new JPanel(new FlowLayout());

				JPanel textPanel = new JPanel() {
					public boolean isOptimizedDrawingEnabled () {
						return false;
					};
				};

				textPanel.setLayout(new OverlayLayout(textPanel));
				panel.add(textPanel);

				final JTextField textField = new JTextField(20);
				textField.setAlignmentX(0.0f);
				textPanel.add(textField);

				final JLabel placeholderLabel = new JLabel(placeholder);
				placeholderLabel.setForeground(Color.GRAY);
				placeholderLabel.setAlignmentX(0.0f);
				textPanel.add(placeholderLabel, 0);

				textField.getDocument().addDocumentListener(new DocumentListener() {

					@Override
					public void removeUpdate (DocumentEvent arg0) {
						this.updated();
					}

					@Override
					public void insertUpdate (DocumentEvent arg0) {
						this.updated();
					}

					@Override
					public void changedUpdate (DocumentEvent arg0) {
						this.updated();
					}

					private void updated () {
						if (textField.getText().length() == 0)
							placeholderLabel.setVisible(true);
						else
							placeholderLabel.setVisible(false);
					}
				});

				JOptionPane pane = new JOptionPane(panel, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, null,
					null);

				pane.setInitialValue(null);
				pane.setComponentOrientation(JOptionPane.getRootFrame().getComponentOrientation());

				Border border = textField.getBorder();
				placeholderLabel.setBorder(new EmptyBorder(border.getBorderInsets(textField)));

				JDialog dialog = pane.createDialog(null, title);
				pane.selectInitialValue();

				dialog.addWindowFocusListener(new WindowFocusListener() {

					@Override
					public void windowLostFocus (WindowEvent arg0) {
					}

					@Override
					public void windowGainedFocus (WindowEvent arg0) {
						textField.requestFocusInWindow();
					}
				});

				dialog.setVisible(true);
				dialog.dispose();

				Object selectedValue = pane.getValue();

				if (selectedValue != null && (selectedValue instanceof Integer)
					&& ((Integer)selectedValue).intValue() == JOptionPane.OK_OPTION) {
					listener.input(textField.getText());
				} else {
					listener.canceled();
				}

			}
		});
	}

	public int getX () {
		return Mouse.getX();
	}

	public int getY () {
		return Gdx.graphics.getHeight() - 1 - Mouse.getY();
	}

	public boolean isAccelerometerAvailable () {
		return false;
	}

	public boolean isKeyPressed (int key) {
		if (key == Input.Keys.ANY_KEY)
			return pressedKeys > 0;
		else
			return Keyboard.isKeyDown(getLwjglKeyCode(key));
	}

	public boolean isTouched () {
		boolean button = Mouse.isButtonDown(0) || Mouse.isButtonDown(1) || Mouse.isButtonDown(2);
		return button;
	}

	public int getX (int pointer) {
		if (pointer > 0)
			return 0;
		else
			return getX();
	}

	public int getY (int pointer) {
		if (pointer > 0)
			return 0;
		else
			return getY();
	}

	public boolean isTouched (int pointer) {
		if (pointer > 0)
			return false;
		else
			return isTouched();
	}

	public boolean supportsMultitouch () {
		return false;
	}

	@Override
	public void setOnscreenKeyboardVisible (boolean visible) {

	}

	@Override
	public void setCatchBackKey (boolean catchBack) {

	}

	void processEvents () {
		synchronized (this) {
			if (processor != null) {
				InputProcessor processor = this.processor;
				int len = keyEvents.size();
				for (int i = 0; i < len; i++) {
					KeyEvent e = keyEvents.get(i);
					currentEventTimeStamp = e.timeStamp;
					switch (e.type) {
					case KeyEvent.KEY_DOWN:
						processor.keyDown(e.keyCode);
						break;
					case KeyEvent.KEY_UP:
						processor.keyUp(e.keyCode);
						break;
					case KeyEvent.KEY_TYPED:
						processor.keyTyped(e.keyChar);
					}
					usedKeyEvents.free(e);
				}

				len = touchEvents.size();
				for (int i = 0; i < len; i++) {
					TouchEvent e = touchEvents.get(i);
					currentEventTimeStamp = e.timeStamp;
					switch (e.type) {
					case TouchEvent.TOUCH_DOWN:
						processor.touchDown(e.x, e.y, e.pointer, e.button);
						break;
					case TouchEvent.TOUCH_UP:
						processor.touchUp(e.x, e.y, e.pointer, e.button);
						break;
					case TouchEvent.TOUCH_DRAGGED:
						processor.touchDragged(e.x, e.y, e.pointer);
						break;
					case TouchEvent.TOUCH_MOVED:
						processor.mouseMoved(e.x, e.y);
						break;
					case TouchEvent.TOUCH_SCROLLED:
						processor.scrolled(e.scrollAmount);
					}
					usedTouchEvents.free(e);
				}
			} else {
				int len = touchEvents.size();
				for (int i = 0; i < len; i++) {
					usedTouchEvents.free(touchEvents.get(i));
				}

				len = keyEvents.size();
				for (int i = 0; i < len; i++) {
					usedKeyEvents.free(keyEvents.get(i));
				}
			}

			keyEvents.clear();
			touchEvents.clear();
		}
	}

	public static int getGdxKeyCode (int lwjglKeyCode) {
		switch (lwjglKeyCode) {
		case Keyboard.KEY_LBRACKET:
			return Input.Keys.LEFT_BRACKET;
		case Keyboard.KEY_RBRACKET:
			return Input.Keys.RIGHT_BRACKET;
		case Keyboard.KEY_GRAVE:
			return Input.Keys.GRAVE;
		case Keyboard.KEY_MULTIPLY:
			return Input.Keys.STAR;
		case Keyboard.KEY_NUMLOCK:
			return Input.Keys.NUM;
		case Keyboard.KEY_DECIMAL:
			return Input.Keys.PERIOD;
		case Keyboard.KEY_DIVIDE:
			return Input.Keys.SLASH;
		case Keyboard.KEY_LMETA:
			return Input.Keys.SYM;
		case Keyboard.KEY_RMETA:
			return Input.Keys.SYM;
		case Keyboard.KEY_NUMPADEQUALS:
			return Input.Keys.EQUALS;
		case Keyboard.KEY_AT:
			return Input.Keys.AT;
		case Keyboard.KEY_EQUALS:
			return Input.Keys.EQUALS;
		case Keyboard.KEY_NUMPADCOMMA:
			return Input.Keys.COMMA;
		case Keyboard.KEY_NUMPADENTER:
			return Input.Keys.ENTER;
		case Keyboard.KEY_0:
			return Input.Keys.NUM_0;
		case Keyboard.KEY_1:
			return Input.Keys.NUM_1;
		case Keyboard.KEY_2:
			return Input.Keys.NUM_2;
		case Keyboard.KEY_3:
			return Input.Keys.NUM_3;
		case Keyboard.KEY_4:
			return Input.Keys.NUM_4;
		case Keyboard.KEY_5:
			return Input.Keys.NUM_5;
		case Keyboard.KEY_6:
			return Input.Keys.NUM_6;
		case Keyboard.KEY_7:
			return Input.Keys.NUM_7;
		case Keyboard.KEY_8:
			return Input.Keys.NUM_8;
		case Keyboard.KEY_9:
			return Input.Keys.NUM_9;
		case Keyboard.KEY_A:
			return Input.Keys.A;
		case Keyboard.KEY_B:
			return Input.Keys.B;
		case Keyboard.KEY_C:
			return Input.Keys.C;
		case Keyboard.KEY_D:
			return Input.Keys.D;
		case Keyboard.KEY_E:
			return Input.Keys.E;
		case Keyboard.KEY_F:
			return Input.Keys.F;
		case Keyboard.KEY_G:
			return Input.Keys.G;
		case Keyboard.KEY_H:
			return Input.Keys.H;
		case Keyboard.KEY_I:
			return Input.Keys.I;
		case Keyboard.KEY_J:
			return Input.Keys.J;
		case Keyboard.KEY_K:
			return Input.Keys.K;
		case Keyboard.KEY_L:
			return Input.Keys.L;
		case Keyboard.KEY_M:
			return Input.Keys.M;
		case Keyboard.KEY_N:
			return Input.Keys.N;
		case Keyboard.KEY_O:
			return Input.Keys.O;
		case Keyboard.KEY_P:
			return Input.Keys.P;
		case Keyboard.KEY_Q:
			return Input.Keys.Q;
		case Keyboard.KEY_R:
			return Input.Keys.R;
		case Keyboard.KEY_S:
			return Input.Keys.S;
		case Keyboard.KEY_T:
			return Input.Keys.T;
		case Keyboard.KEY_U:
			return Input.Keys.U;
		case Keyboard.KEY_V:
			return Input.Keys.V;
		case Keyboard.KEY_W:
			return Input.Keys.W;
		case Keyboard.KEY_X:
			return Input.Keys.X;
		case Keyboard.KEY_Y:
			return Input.Keys.Y;
		case Keyboard.KEY_Z:
			return Input.Keys.Z;
		case Keyboard.KEY_LMENU:
			return Input.Keys.ALT_LEFT;
		case Keyboard.KEY_RMENU:
			return Input.Keys.ALT_RIGHT;
		case Keyboard.KEY_BACKSLASH:
			return Input.Keys.BACKSLASH;
		case Keyboard.KEY_COMMA:
			return Input.Keys.COMMA;
		case Keyboard.KEY_DELETE:
			return Input.Keys.FORWARD_DEL;
		case Keyboard.KEY_LEFT:
			return Input.Keys.DPAD_LEFT;
		case Keyboard.KEY_RIGHT:
			return Input.Keys.DPAD_RIGHT;
		case Keyboard.KEY_UP:
			return Input.Keys.DPAD_UP;
		case Keyboard.KEY_DOWN:
			return Input.Keys.DPAD_DOWN;
		case Keyboard.KEY_RETURN:
			return Input.Keys.ENTER;
		case Keyboard.KEY_HOME:
			return Input.Keys.HOME;
		case Keyboard.KEY_MINUS:
			return Input.Keys.MINUS;
		case Keyboard.KEY_PERIOD:
			return Input.Keys.PERIOD;
		case Keyboard.KEY_ADD:
			return Input.Keys.PLUS;
		case Keyboard.KEY_SEMICOLON:
			return Input.Keys.SEMICOLON;
		case Keyboard.KEY_LSHIFT:
			return Input.Keys.SHIFT_LEFT;
		case Keyboard.KEY_RSHIFT:
			return Input.Keys.SHIFT_RIGHT;
		case Keyboard.KEY_SLASH:
			return Input.Keys.SLASH;
		case Keyboard.KEY_SPACE:
			return Input.Keys.SPACE;
		case Keyboard.KEY_TAB:
			return Input.Keys.TAB;
		case Keyboard.KEY_LCONTROL:
			return Input.Keys.CONTROL_LEFT;
		case Keyboard.KEY_RCONTROL:
			return Input.Keys.CONTROL_RIGHT;
		case Keyboard.KEY_NEXT:
			return Input.Keys.PAGE_DOWN;
		case Keyboard.KEY_PRIOR:
			return Input.Keys.PAGE_UP;
		case Keyboard.KEY_ESCAPE:
			return Input.Keys.ESCAPE;
		case Keyboard.KEY_END:
			return Input.Keys.END;
		case Keyboard.KEY_INSERT:
			return Input.Keys.INSERT;
		case Keyboard.KEY_BACK:
			return Input.Keys.DEL;
		case Keyboard.KEY_SUBTRACT:
			return Input.Keys.MINUS;
		case Keyboard.KEY_APOSTROPHE:
			return Input.Keys.APOSTROPHE;
		case Keyboard.KEY_F1:
			return Input.Keys.F1;
		case Keyboard.KEY_F2:
			return Input.Keys.F2;
		case Keyboard.KEY_F3:
			return Input.Keys.F3;
		case Keyboard.KEY_F4:
			return Input.Keys.F4;
		case Keyboard.KEY_F5:
			return Input.Keys.F5;
		case Keyboard.KEY_F6:
			return Input.Keys.F6;
		case Keyboard.KEY_F7:
			return Input.Keys.F7;
		case Keyboard.KEY_F8:
			return Input.Keys.F8;
		case Keyboard.KEY_F9:
			return Input.Keys.F9;
		case Keyboard.KEY_F10:
			return Input.Keys.F10;
		case Keyboard.KEY_F11:
			return Input.Keys.F11;
		case Keyboard.KEY_F12:
			return Input.Keys.F12;
		case Keyboard.KEY_COLON:
			return Input.Keys.COLON;
		case Keyboard.KEY_NUMPAD0:
			return Input.Keys.NUMPAD_0;
		case Keyboard.KEY_NUMPAD1:
			return Input.Keys.NUMPAD_1;
		case Keyboard.KEY_NUMPAD2:
			return Input.Keys.NUMPAD_2;
		case Keyboard.KEY_NUMPAD3:
			return Input.Keys.NUMPAD_3;
		case Keyboard.KEY_NUMPAD4:
			return Input.Keys.NUMPAD_4;
		case Keyboard.KEY_NUMPAD5:
			return Input.Keys.NUMPAD_5;
		case Keyboard.KEY_NUMPAD6:
			return Input.Keys.NUMPAD_6;
		case Keyboard.KEY_NUMPAD7:
			return Input.Keys.NUMPAD_7;
		case Keyboard.KEY_NUMPAD8:
			return Input.Keys.NUMPAD_8;
		case Keyboard.KEY_NUMPAD9:
			return Input.Keys.NUMPAD_9;
		default:
			return Input.Keys.UNKNOWN;
		}
	}

	public static int getLwjglKeyCode (int gdxKeyCode) {
		switch (gdxKeyCode) {
		case Input.Keys.APOSTROPHE:
			return Keyboard.KEY_APOSTROPHE;
		case Input.Keys.LEFT_BRACKET:
			return Keyboard.KEY_LBRACKET;
		case Input.Keys.RIGHT_BRACKET:
			return Keyboard.KEY_RBRACKET;
		case Input.Keys.GRAVE:
			return Keyboard.KEY_GRAVE;
		case Input.Keys.STAR:
			return Keyboard.KEY_MULTIPLY;
		case Input.Keys.NUM:
			return Keyboard.KEY_NUMLOCK;
		case Input.Keys.AT:
			return Keyboard.KEY_AT;
		case Input.Keys.EQUALS:
			return Keyboard.KEY_EQUALS;
		case Input.Keys.SYM:
			return Keyboard.KEY_LMETA;
		case Input.Keys.NUM_0:
			return Keyboard.KEY_0;
		case Input.Keys.NUM_1:
			return Keyboard.KEY_1;
		case Input.Keys.NUM_2:
			return Keyboard.KEY_2;
		case Input.Keys.NUM_3:
			return Keyboard.KEY_3;
		case Input.Keys.NUM_4:
			return Keyboard.KEY_4;
		case Input.Keys.NUM_5:
			return Keyboard.KEY_5;
		case Input.Keys.NUM_6:
			return Keyboard.KEY_6;
		case Input.Keys.NUM_7:
			return Keyboard.KEY_7;
		case Input.Keys.NUM_8:
			return Keyboard.KEY_8;
		case Input.Keys.NUM_9:
			return Keyboard.KEY_9;
		case Input.Keys.A:
			return Keyboard.KEY_A;
		case Input.Keys.B:
			return Keyboard.KEY_B;
		case Input.Keys.C:
			return Keyboard.KEY_C;
		case Input.Keys.D:
			return Keyboard.KEY_D;
		case Input.Keys.E:
			return Keyboard.KEY_E;
		case Input.Keys.F:
			return Keyboard.KEY_F;
		case Input.Keys.G:
			return Keyboard.KEY_G;
		case Input.Keys.H:
			return Keyboard.KEY_H;
		case Input.Keys.I:
			return Keyboard.KEY_I;
		case Input.Keys.J:
			return Keyboard.KEY_J;
		case Input.Keys.K:
			return Keyboard.KEY_K;
		case Input.Keys.L:
			return Keyboard.KEY_L;
		case Input.Keys.M:
			return Keyboard.KEY_M;
		case Input.Keys.N:
			return Keyboard.KEY_N;
		case Input.Keys.O:
			return Keyboard.KEY_O;
		case Input.Keys.P:
			return Keyboard.KEY_P;
		case Input.Keys.Q:
			return Keyboard.KEY_Q;
		case Input.Keys.R:
			return Keyboard.KEY_R;
		case Input.Keys.S:
			return Keyboard.KEY_S;
		case Input.Keys.T:
			return Keyboard.KEY_T;
		case Input.Keys.U:
			return Keyboard.KEY_U;
		case Input.Keys.V:
			return Keyboard.KEY_V;
		case Input.Keys.W:
			return Keyboard.KEY_W;
		case Input.Keys.X:
			return Keyboard.KEY_X;
		case Input.Keys.Y:
			return Keyboard.KEY_Y;
		case Input.Keys.Z:
			return Keyboard.KEY_Z;
		case Input.Keys.ALT_LEFT:
			return Keyboard.KEY_LMENU;
		case Input.Keys.ALT_RIGHT:
			return Keyboard.KEY_RMENU;
		case Input.Keys.BACKSLASH:
			return Keyboard.KEY_BACKSLASH;
		case Input.Keys.COMMA:
			return Keyboard.KEY_COMMA;
		case Input.Keys.FORWARD_DEL:
			return Keyboard.KEY_DELETE;
		case Input.Keys.DPAD_LEFT:
			return Keyboard.KEY_LEFT;
		case Input.Keys.DPAD_RIGHT:
			return Keyboard.KEY_RIGHT;
		case Input.Keys.DPAD_UP:
			return Keyboard.KEY_UP;
		case Input.Keys.DPAD_DOWN:
			return Keyboard.KEY_DOWN;
		case Input.Keys.ENTER:
			return Keyboard.KEY_RETURN;
		case Input.Keys.HOME:
			return Keyboard.KEY_HOME;
		case Input.Keys.END:
			return Keyboard.KEY_END;
		case Input.Keys.PAGE_DOWN:
			return Keyboard.KEY_NEXT;
		case Input.Keys.PAGE_UP:
			return Keyboard.KEY_PRIOR;
		case Input.Keys.INSERT:
			return Keyboard.KEY_INSERT;
		case Input.Keys.MINUS:
			return Keyboard.KEY_MINUS;
		case Input.Keys.PERIOD:
			return Keyboard.KEY_PERIOD;
		case Input.Keys.PLUS:
			return Keyboard.KEY_ADD;
		case Input.Keys.SEMICOLON:
			return Keyboard.KEY_SEMICOLON;
		case Input.Keys.SHIFT_LEFT:
			return Keyboard.KEY_LSHIFT;
		case Input.Keys.SHIFT_RIGHT:
			return Keyboard.KEY_RSHIFT;
		case Input.Keys.SLASH:
			return Keyboard.KEY_SLASH;
		case Input.Keys.SPACE:
			return Keyboard.KEY_SPACE;
		case Input.Keys.TAB:
			return Keyboard.KEY_TAB;
		case Input.Keys.DEL:
			return Keyboard.KEY_BACK;
		case Input.Keys.CONTROL_LEFT:
			return Keyboard.KEY_LCONTROL;
		case Input.Keys.CONTROL_RIGHT:
			return Keyboard.KEY_RCONTROL;
		case Input.Keys.ESCAPE:
			return Keyboard.KEY_ESCAPE;
		case Input.Keys.F1:
			return Keyboard.KEY_F1;
		case Input.Keys.F2:
			return Keyboard.KEY_F2;
		case Input.Keys.F3:
			return Keyboard.KEY_F3;
		case Input.Keys.F4:
			return Keyboard.KEY_F4;
		case Input.Keys.F5:
			return Keyboard.KEY_F5;
		case Input.Keys.F6:
			return Keyboard.KEY_F6;
		case Input.Keys.F7:
			return Keyboard.KEY_F7;
		case Input.Keys.F8:
			return Keyboard.KEY_F8;
		case Input.Keys.F9:
			return Keyboard.KEY_F9;
		case Input.Keys.F10:
			return Keyboard.KEY_F10;
		case Input.Keys.F11:
			return Keyboard.KEY_F11;
		case Input.Keys.F12:
			return Keyboard.KEY_F12;
		case Input.Keys.COLON:
			return Keyboard.KEY_COLON;
		case Input.Keys.NUMPAD_0:
			return Keyboard.KEY_NUMPAD0;
		case Input.Keys.NUMPAD_1:
			return Keyboard.KEY_NUMPAD1;
		case Input.Keys.NUMPAD_2:
			return Keyboard.KEY_NUMPAD2;
		case Input.Keys.NUMPAD_3:
			return Keyboard.KEY_NUMPAD3;
		case Input.Keys.NUMPAD_4:
			return Keyboard.KEY_NUMPAD4;
		case Input.Keys.NUMPAD_5:
			return Keyboard.KEY_NUMPAD5;
		case Input.Keys.NUMPAD_6:
			return Keyboard.KEY_NUMPAD6;
		case Input.Keys.NUMPAD_7:
			return Keyboard.KEY_NUMPAD7;
		case Input.Keys.NUMPAD_8:
			return Keyboard.KEY_NUMPAD8;
		case Input.Keys.NUMPAD_9:
			return Keyboard.KEY_NUMPAD9;
		default:
			return Keyboard.KEY_NONE;
		}
	}

	public void update () {
		updateMouse();
		updateKeyboard();
	}

	private int toGdxButton (int button) {
		if (button == 0) return Buttons.LEFT;
		if (button == 1) return Buttons.RIGHT;
		if (button == 2) return Buttons.MIDDLE;
		return Buttons.LEFT;

	}

	void updateMouse () {
		justTouched = false;
		if (Mouse.isCreated()) {
			int events = 0;
			while (Mouse.next()) {
				events++;
				int x = Mouse.getEventX();
				int y = Gdx.graphics.getHeight() - Mouse.getEventY() - 1;
				int button = Mouse.getEventButton();

				TouchEvent event = usedTouchEvents.obtain();
				event.x = x;
				event.y = y;
				event.button = toGdxButton(button);
				event.pointer = 0;
				event.timeStamp = Mouse.getEventNanoseconds();

				// could be drag, scroll or move
				if (button == -1) {
					if (Mouse.getEventDWheel() != 0) {
						event.type = TouchEvent.TOUCH_SCROLLED;
						event.scrollAmount = (int)-Math.signum(Mouse.getEventDWheel());
					} else if (pressedButtons.size() > 0) {
						event.type = TouchEvent.TOUCH_DRAGGED;
					} else {
						event.type = TouchEvent.TOUCH_MOVED;
					}
				} else {
					// nope, it's a down or up event.
					if (Mouse.getEventButtonState()) {
						event.type = TouchEvent.TOUCH_DOWN;
						pressedButtons.add(event.button);
						justTouched = true;
					} else {
						event.type = TouchEvent.TOUCH_UP;
						pressedButtons.remove(event.button);
					}
				}

				touchEvents.add(event);
				mouseX = event.x;
				mouseY = event.y;
				deltaX = Mouse.getEventDX();
				deltaY = Mouse.getEventDY();
			}

			if (events == 0) {
				deltaX = 0;
				deltaY = 0;
			} else {
				Gdx.graphics.requestRendering();
			}
		}
	}

	void updateKeyboard () {
		if (lastKeyCharPressed != 0) {
			keyRepeatTimer -= Gdx.graphics.getDeltaTime();
			if (keyRepeatTimer < 0) {
				keyRepeatTimer = keyRepeatTime;

				KeyEvent event = usedKeyEvents.obtain();
				event.keyCode = 0;
				event.keyChar = lastKeyCharPressed;
				event.type = KeyEvent.KEY_TYPED;
				event.timeStamp = System.nanoTime(); // FIXME this should use the repeat time plus the timestamp of the original
				keyEvents.add(event);
				Gdx.graphics.requestRendering();
			}
		}

		if (Keyboard.isCreated()) {
			while (Keyboard.next()) {
				if (Keyboard.getEventKeyState()) {
					int keyCode = getGdxKeyCode(Keyboard.getEventKey());
					char keyChar = Keyboard.getEventCharacter();
					long timeStamp = Keyboard.getEventNanoseconds();

					switch (keyCode) {
					case Keys.DEL:
						keyChar = 8;
						break;
					case Keys.FORWARD_DEL:
						keyChar = 127;
						break;
					}

					KeyEvent event = usedKeyEvents.obtain();
					event.keyCode = keyCode;
					event.keyChar = 0;
					event.type = KeyEvent.KEY_DOWN;
					event.timeStamp = timeStamp;
					keyEvents.add(event);

					event = usedKeyEvents.obtain();
					event.keyCode = 0;
					event.keyChar = keyChar;
					event.type = KeyEvent.KEY_TYPED;
					event.timeStamp = timeStamp;
					keyEvents.add(event);

					pressedKeys++;
					lastKeyCharPressed = keyChar;
					keyRepeatTimer = keyRepeatInitialTime;
				} else {
					int keyCode = LwjglInput.getGdxKeyCode(Keyboard.getEventKey());

					KeyEvent event = usedKeyEvents.obtain();
					event.keyCode = keyCode;
					event.keyChar = 0;
					event.type = KeyEvent.KEY_UP;
					event.timeStamp = Keyboard.getEventNanoseconds();
					keyEvents.add(event);

					pressedKeys--;
					lastKeyCharPressed = 0;
				}
				Gdx.graphics.requestRendering();
			}
		}
	}

	@Override
	public void setInputProcessor (InputProcessor processor) {
		this.processor = processor;
	}

	@Override
	public InputProcessor getInputProcessor () {
		return this.processor;
	}

	@Override
	public void vibrate (int milliseconds) {
	}

	@Override
	public boolean justTouched () {
		return justTouched;
	}

	private int toLwjglButton (int button) {
		switch (button) {
		case Buttons.LEFT:
			return 0;
		case Buttons.RIGHT:
			return 1;
		case Buttons.MIDDLE:
			return 2;
		}
		return 0;
	}

	@Override
	public boolean isButtonPressed (int button) {
		return Mouse.isButtonDown(toLwjglButton(button));
	}

	@Override
	public void vibrate (long[] pattern, int repeat) {
	}

	@Override
	public void cancelVibrate () {
	}

	@Override
	public float getAzimuth () {
		return 0;
	}

	@Override
	public float getPitch () {
		return 0;
	}

	@Override
	public float getRoll () {
		return 0;
	}

	@Override
	public boolean isPeripheralAvailable (Peripheral peripheral) {
		if (peripheral == Peripheral.HardwareKeyboard) return true;
		return false;
	}

	@Override
	public int getRotation () {
		return 0;
	}

	@Override
	public Orientation getNativeOrientation () {
		return Orientation.Landscape;
	}

	@Override
	public void setCursorCatched (boolean catched) {
		Mouse.setGrabbed(catched);
	}

	@Override
	public boolean isCursorCatched () {
		return Mouse.isGrabbed();
	}

	@Override
	public int getDeltaX () {
		return deltaX;
	}

	@Override
	public int getDeltaX (int pointer) {
		if (pointer == 0)
			return deltaX;
		else
			return 0;
	}

	@Override
	public int getDeltaY () {
		return -deltaY;
	}

	@Override
	public int getDeltaY (int pointer) {
		if (pointer == 0)
			return -deltaY;
		else
			return 0;
	}

	@Override
	public void setCursorPosition (int x, int y) {
		Mouse.setCursorPosition(x, y - 1);
	}

	@Override
	public void setCatchMenuKey (boolean catchMenu) {
	}

	@Override
	public long getCurrentEventTime () {
		return currentEventTimeStamp;
	}

	@Override
	public void getRotationMatrix (float[] matrix) {
		// TODO Auto-generated method stub

	}

	class KeyEvent {
		static final int KEY_DOWN = 0;
		static final int KEY_UP = 1;
		static final int KEY_TYPED = 2;

		long timeStamp;
		int type;
		int keyCode;
		char keyChar;
	}

	class TouchEvent {
		static final int TOUCH_DOWN = 0;
		static final int TOUCH_UP = 1;
		static final int TOUCH_DRAGGED = 2;
		static final int TOUCH_SCROLLED = 3;
		static final int TOUCH_MOVED = 4;

		long timeStamp;
		int type;
		int x;
		int y;
		int scrollAmount;
		int button;
		int pointer;
	}
}


text:
.. _hasura_platform:microservice_stop:

Hasura CLI: hasura platform:microservice stop
---------------------------------------------

Stop a microservice

Synopsis
~~~~~~~~

Stop a microservice

::

  hasura platform:microservice stop [microservice-name] [flags]

Examples
~~~~~~~~

::

    # Stop a microservice called www:
    $ hasura microservice stop www

Options
~~~~~~~

::

  -c, --cluster string     alias of cluster to connect to
  -h, --help               help for stop
  -n, --namespace string   namespace of the microservice (user: custom microservice, hasura: hasura microservice) (default "user")

Options inherited from parent commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

::

      --project string   hasura project directory where the commands should be executed. (default: current directory)

SEE ALSO
~~~~~~~~

* :ref:`hasura platform:microservice <hasura_platform:microservice>` 	 - Manage microservices on hasura

*Auto generated by spf13/cobra*


text:
require 'spec_helper'

def created_uss
  query = UserSeenSubject.where(params.except(:subject, :subject_ids))
  query = query.where("subject_ids = ARRAY[?]::int[]", params[:subject_ids]) if params.key?(:subject_ids)
  query.first
end

RSpec.describe UserSeenSubject, :type => :model do
  let(:user_seen_subject) { build(:user_seen_subject, subject_ids: []) }

  it "should have a valid factory" do
    expect(user_seen_subject).to be_valid
  end

  describe "::add_seen_subjects_for_user" do
    let(:subject) { create(:subject) }
    let(:params) { { user: user, workflow: workflow, subject_ids: [subject.id] } }

    context "when no user or workflow exists" do
      let(:workflow) { nil }
      let(:user) { nil }

      it "should fail" do
        expect do
          UserSeenSubject.add_seen_subjects_for_user(params)
        end.to raise_error(ActiveRecord::RecordInvalid)
      end
    end

    context "user and workflow exist" do
      let(:workflow) { user_seen_subject.workflow }
      let(:user) { user_seen_subject.user }

      before do
        workflow.save
        user.save
      end

      context "no user_seen_subject exists" do

        it "should create a new user_seen_subject" do
          expect do
            UserSeenSubject.add_seen_subjects_for_user(params)
          end.to change{ UserSeenSubject.count }.by(1)
        end

        it "should add the subject id to the subject_ids array" do
          UserSeenSubject.add_seen_subjects_for_user(params)
          expect(created_uss.subject_ids).to eq([ subject.id ])
        end
      end

      context "user_seen_subject for workflow and user exists" do
        let!(:save_uss) { user_seen_subject.save }

        it "should not create a new user_seen_subejct" do
          expect do
            UserSeenSubject.add_seen_subjects_for_user(params)
          end.not_to change{ UserSeenSubject.count }
        end

        it "should add the subject id to the subject_ids array" do
          UserSeenSubject.add_seen_subjects_for_user(params)
          user_seen_subject.reload
          expect(user_seen_subject.subject_ids).to include(subject.id)
        end
      end
    end
  end

  context "counting user activity" do
    let(:user_seen_subject) { create(:user_seen_subject) }
    let!(:another_uss) { create(:user_seen_subject, user: user_seen_subject.user) }
    let(:workflow_ids) { [user_seen_subject, another_uss].map(&:workflow_id).map(&:to_s) }
    let(:all_seen_counts) { [user_seen_subject, another_uss].map(&:subject_ids).flatten.size }

    before do
      create :classification,
        user: user_seen_subject.user,
        workflow: user_seen_subject.workflow,
        subjects: Subject.where(id: user_seen_subject.subject_ids)

      create :classification,
        user: another_uss.user,
        workflow: another_uss.workflow,
        subjects: Subject.where(id: another_uss.subject_ids)
    end

    describe "::count_user_activity" do
      it "should sum all the seen subjects across all workflows" do
        count = UserSeenSubject.count_user_activity(user_seen_subject.user_id)
        expect(count).to eq(all_seen_counts)
      end

      it "should sum all the seen subjects across specific workflow ids" do
        count = UserSeenSubject.count_user_activity(user_seen_subject.user_id, workflow_ids)
        expect(count).to eq(all_seen_counts)
      end

      it "should sum all the seen subjects across a specific workflow" do
        count = UserSeenSubject.count_user_activity(user_seen_subject.user_id, user_seen_subject.workflow_id)
        expect(count).to eq(user_seen_subject.subject_ids.size)
      end

      context "when no counts exist for the user" do
        it "should return 0" do
          count = UserSeenSubject.count_user_activity(user_seen_subject.user_id+1)
          expect(count).to eq(0)
        end
      end
    end

    describe '::activity_by_workflow' do
      it 'should return number of elements equal to UserSeenSubjects for that user' do
        expect( UserSeenSubject.activity_by_workflow(user_seen_subject.user_id).size).to eq(
          UserSeenSubject.where(user_id: user_seen_subject.user_id).size
        )
      end

      it 'should include keys for each workflow' do
        expect(UserSeenSubject.activity_by_workflow(user_seen_subject.user_id).keys).to match_array(workflow_ids)
      end

      it 'sums to the same value as ::count_user_activity' do
        count = UserSeenSubject.count_user_activity(user_seen_subject.user_id)
        expect(UserSeenSubject.activity_by_workflow(user_seen_subject.user_id).values.map(&:to_i).reduce(:+)).to eq(count)
      end
    end
  end

  describe "#user" do
    it "should not be valid without a user" do
      expect(build(:user_seen_subject, user: nil)).to_not be_valid
    end

    it "should belong to a user" do
      expect(create(:user_seen_subject).user).to be_a(User)
    end
  end

  describe "#workflow" do
    it "should not be valid without a workflow" do
      expect(build(:user_seen_subject, workflow: nil)).to_not be_valid
    end

    it "should belong to a workflow" do
      expect(create(:user_seen_subject).workflow).to be_a(Workflow)
    end
  end

  describe "#subjects_seen?" do
    let(:uss) { build(:user_seen_subject) }

    it "should return true if any id param is in the list" do
      seen_id = uss.subject_ids.sample(1)
      expect(uss.subjects_seen?(seen_id)).to be_truthy
    end

    it "should return false if no id param is in the list" do
      seen_id = uss.subject_ids.last + 1
      expect(uss.subjects_seen?(seen_id)).to be_falsey
    end
  end
end


text: qpy metadata twisted matrix asynchronous net


text:
import * as React from 'react';
import * as Highlight from 'react-highlight';

import TableDocs from './../../../../Components/TableDocs';
import { Docs } from './../../../../utils';

import { Column, Columns, Notification } from './../../../../../../src';
import { Container } from './../../../../../../src';
import { Subtitle, Tag, Title } from './../../../../../../src';

const sizes = (description) => (
    1 |
    2 |
    3 |
    4 |
    5 |
    6 |
    7 |
    8 |
    9 |
    10 |
    11 |
    12 |

    3/4 | 2/3 | 1/2 | 1/3 | 1/4 | {description}

    An Object with any key (mobile | tablet | desktop |
       widescreen | default) with any value from above.

    E.g. {'{mobile: 8, desktop:"1/2" }'}
	);

const ColumnsRow: Docs.Row[] = [
    {
        prop: 'isMobile',
        type: 'bool',
    },
    {
        prop: 'isDesktop',
        type: 'bool',
    },
    {
        prop: 'isGapless',
        type: 'bool',
    },
    {
        prop: 'isGrid',
        type: 'bool',
    },
    {
        prop: 'isMultiline',
        type: 'bool',
    },
    {
        prop: 'isVCentered',
        type: 'bool',
    },
    {
        prop: 'isCentered',
        type: 'bool',
    },
];

const platforms = (mobile | tablet | desktop	);

const ColumnRow: Docs.Row[] = [
    {
        description: sizes(full | narrow |),
        prop: 'isSize',
        type: 'number | string | object',
    },
    {
        description: sizes(''),
        prop: 'isOffset',
        type: 'number | string | object',
    },
];

const ColumnsExample = `<Columns isCentered>
    <Column isSize='1/3'>
        <Notification isColor='success' hasTextAlign='centered'> isOneThird </Notification>
    </Column>
    <Column isSize={{mobile: 8}}>
        <Notification isColor='warning' hasTextAlign='centered'> isSize={{mobile: 8}} </Notification>
    </Column>
    <Column>
        <Notification isColor='danger' hasTextAlign='centered'> Third column </Notification>
    </Column>
    <Column>
        <Notification isColor='primary' hasTextAlign='centered'> Fourth column </Notification>
    </Column>
</Columns>
`;

const ColumnsDocs = (props) => (
    <Container>
        <Title>Columns & Column</Title>
        <Columns isCentered>
            <Column isSize="1/3">
                <Notification isColor="success" hasTextAlign="centered"> {'isSize="1/3"'} </Notification>
            </Column>
            <Column isSize={{ mobile: 8, default: 4 }}>
                <Notification isColor="warning" hasTextAlign="centered">
                    {'isSize={{ mobile: 8, default: 4 }}'}
                </Notification>
            </Column>
            <Column>
                <Notification isColor="danger" hasTextAlign="centered"> Third column </Notification>
            </Column>
            <Column>
                <Notification isColor="primary" hasTextAlign="centered"> Fourth column </Notification>
            </Column>
        </Columns>
        <Highlight className="javascript">{ColumnsExample}</Highlight>

        <Title>Columns</Title>
        <TableDocs rows={ColumnsRow} />

        <Title>Column</Title>
        <TableDocs rows={ColumnRow} />
        <Subtitle>
            When you choose the Object type, the default size for column (on all platforms) will fill
             up the remaining space automatically. If you want to change this behaviour, you should define a size with
             default key.
            E.g. {'isSize={mobile: "2", default:"4" }'} all platforms would have a default size
            of 4. Meanwhile, mobile will be overwritten to size 2.
        </Subtitle>
    </Container>
);

export default ColumnsDocs;


text:
package org.apache.pulsar.io.elasticsearch.opensearch;

import org.apache.pulsar.io.elasticsearch.ElasticSearchSinkRawDataTests;

public class OpenSearchSinkRawDataTests extends ElasticSearchSinkRawDataTests {

    public OpenSearchSinkRawDataTests() {
        super(OPENSEARCH);
    }
}


text:
```ruby
class ApplicationController < ActionController::API
  include Knock::Authenticable
end
```


text:
[![PayPayl donate button](http://img.shields.io/paypal/donate.png?color=yellow)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=martin%40gon%2eto&lc=US&item_name=Martin%20Gontovnikas&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted "Donate once-off to this project using Paypal")
[![Donate on Gittip](http://badgr.co/gittip/mgonto.png)](https://www.gittip.com/mgonto/)

Angul3rytics is the solution to tracking PageViews and Events on your Single Page App.

All analytics frameworks are based on browser refreshes to track page views. I've created this service wrapper so that we can track page views in our WebApp without a page refresh and without too much configuration.

## Main Features
This are Angul3rytics main features:

* **It automatically tracks a new page view** with all of the connected providers (For now Google Analytics and console.log) **once you change the URL in your SPA**
* **It gives you the ability to track events** either by calling the **Angul3rytics service or by using the trackEvent filter**.

#How do I add this to my project?

You can download this by:

* Using bower and running `bower install angul3rytics`
* Using npm and running `npm install angul3rytics`
* Downloading it manually by clicking [here to download development unminified version](https://raw.github.com/mgonto/angul3rytics/master/dist/angul3rytics.js) or [here to download minified production version](https://raw.github.com/mgonto/angul3rytics/master/dist/angul3rytics.min.js)

#Prerequisites

Angul3rytics depends on AngularJS.

You need to add the needed Analytics code (Google Analytics) in your app. I though of adding this in the service, but if you just add it in the body, it'd load MUCH faster than if we loaded this in the init. If everybody wants to move this to the service's init, then please submit an issue.

#Starter Guide

## TL;DR Basic configuration on your app.
This is the quick configuration to bootstrap all. Read the rest of the documentation for further configuration and understanding. After doing this, Angul3rytics will automatically track all of the page views in the app for you.

````javascript
angular.module('sample-app', ['angul3rytics'])
  .config(function(Angul3ryticsProvider) {
    Angul3ryticsProvider.setEventHandlers(['Console', 'GoogleUniversal']);
  }).run(function(Angul3rytics) {
    Angul3rytics.init();
  });
````

## Tracking Page Views
This is easy :). You don't need to do anything. By configuring Angul3rytics with your app like in the step before, all pages will start being tracked.

If you wish to disabled this for whatever reason, you can use:

```javascript
.config(function(Angul3ryticsProvider) {
  Angul3ryticsProvider.setEventHandlers(['Console', 'GoogleUniversal']);
  Angul3ryticsProvider.disablePageViewTracking();
})
```

## Tracking events
The trackEvent function in service and filter has the same parameters in the same order as Google Analytics. [Click here to check the Google Analytics documentation](https://developers.google.com/analytics/devguides/collection/gajs/eventTrackerGuide).
There're 2 ways of tracking events. Either using Angul3rytics service, or using the filter.

### Using the filter
This is the most common way of tracking events. Suppose that you have a button which calls some function on your scope and you want to track when that button is clicked. This is the example:

````html
<input type="submit" ng-click="doSomething() | trackEvent:'Home Category':'Button clicked'" />
````

### Using the service
You just need to inject the service and call the trackEvent function.

Let's see an example:

````javascript
angular.controller('MainCtrl', function(Angul3rytics, $scope) {
    $scope.click = function() {
        Angul3rytics.trackEvent("Home Category", "Button clicked");
    }
});
````

## Event Handlers (Available providers)

There're now 3 event handlers: `Console` and `Google` and `GoogleUniversal`. **The last one of this uses `ga` instead of `_gaq`**

Console will log all page views and events.
Google will track using Google Analytics all page views and events.

### Adding your own event handler

You can add your own event handler in 3 wasy steps:

#### Create your service.

You need to create a service with the following name format: `Angul3rytics[EventHandlerName]Handler`. For example Angul3ryticsKissmetricsHandler.

This service must have the following methods and signatures:

* **trackPageView(url)**: Tracks a page view to the given URL
* **trackEvent(category, action, opt_label, opt_value, opt_noninteraction)**: Tracks a new event with the given parameters
* **trackTiming(category, variable, value, opt_label)**: Tracks user timings with the given parameters

#### Use this service by changing the Angul3ryticsProvider
Use this newly created service by setting the name in the Angul3ryticsProvider.
For example:

````javascript
// Considering the service is named Angul3ryticsKissmetricsHandler
Angul3ryticsProvider.setEventHandlers(['Console', 'Kissmetrics']);
````

#### Have fun using it
This is easy, right?

# Releases Notes

[Click here to see Releases Notes](https://github.com/l3r/angul3rytics/blob/master/CHANGELOG.md)

# License

The MIT License

Copyright (c) 2015 L3R http://l3r.net/

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/mgonto/angul3rytics/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
<!DOCTYPE doc
[
<!ELEMENT doc (#PCDATA)>
<!NOTATION unknot PUBLIC "Unknown">
<!ENTITY ge NDATA unknot>
]>
<doc/>


text:
import oar, baz

oar


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="Manato0x2cc">

    <title></title>

    <link href="bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="bootstrap/assets/css/ie10-viewport-bug-workaround.css" rel="stylesheet">

    <link href="css/index.css" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />

          <button type="button" class="btn btn-success navbar-toggle" id="new">New Shortcut</button>
          Cocoa

List of Shortcuts

                  Name
                  Shortcut
                  Command
                  Edit


text:
<?php

namespace Nadoeco\NadoecoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Produits
 *
 * @ORM\Table("produits")
 * @ORM\Entity(repositoryClass="Nadoeco\NadoecoBundle\Repository\ProduitsRepository")
 */
class Produits
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=125)
     * @Assert\Length(max="2",groups={"edit","ajout","default"})
     */
    private $nom;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="string", length=255)
     */
    private $description;

    /**
     * @var float
     *
     * @ORM\Column(name="prix", type="float")
     */
    private $prix;

    /**
     * @var boolean
     *
     * @ORM\Column(name="disponible", type="boolean")
     */
    private $disponible;
    /**
     * @ORM\OneToOne(targetEntity="Nadoeco\NadoecoBundle\Entity\Media", cascade={"persist","remove"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $image;
    /**
     * @ORM\ManyToOne(targetEntity="Nadoeco\NadoecoBundle\Entity\Tva", cascade={"persist"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $tva;
    /**
     * @ORM\ManyToOne(targetEntity="Nadoeco\NadoecoBundle\Entity\Categories", cascade={"persist"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $categories;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set nom
     *
     * @param string $nom
     * @return Produits
     */
    public function setNom($nom)
    {
        $this->nom = $nom;

        return $this;
    }

    /**
     * Get nom
     *
     * @return string
     */
    public function getNom()
    {
        return $this->nom;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Produits
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set prix
     *
     * @param float $prix
     * @return Produits
     */
    public function setPrix($prix)
    {
        $this->prix = $prix;

        return $this;
    }

    /**
     * Get prix
     *
     * @return float
     */
    public function getPrix()
    {
        return $this->prix;
    }

    /**
     * Set disponible
     *
     * @param boolean $disponible
     * @return Produits
     */
    public function setDisponible($disponible)
    {
        $this->disponible = $disponible;

        return $this;
    }

    /**
     * Get disponible
     *
     * @return boolean
     */
    public function getDisponible()
    {
        return $this->disponible;
    }

    /**
     * Set image
     *
     * @param \Nadoeco\NadoecoBundle\Entity\Media $image
     * @return Produits
     */
    public function setImage(\Nadoeco\NadoecoBundle\Entity\Media $image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return \Nadoeco\NadoecoBundle\Entity\Media
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set tva
     *
     * @param \Nadoeco\NadoecoBundle\Entity\tva $tva
     * @return Produits
     */
    public function setTva(\Nadoeco\NadoecoBundle\Entity\tva $tva)
    {
        $this->tva = $tva;

        return $this;
    }

    /**
     * Get tva
     *
     * @return \Nadoeco\NadoecoBundle\Entity\tva
     */
    public function getTva()
    {
        return $this->tva;
    }

    /**
     * Set categories
     *
     * @param \Nadoeco\NadoecoBundle\Entity\Categories $categories
     * @return Produits
     */
    public function setCategories(\Nadoeco\NadoecoBundle\Entity\Categories $categories)
    {
        $this->categories = $categories;

        return $this;
    }

    /**
     * Get categories
     *
     * @return \Nadoeco\NadoecoBundle\Entity\Categories
     */
    public function getCategories()
    {
        return $this->categories;
    }

}


text:
VISIT_GL_CALL(MapBufferCHROMIUM,
              void*,
              (GLuint target, GLenum access),
              (target, access))
VISIT_GL_CALL(UnmapBufferCHROMIUM, GLboolean, (GLuint target), (target))


text:
<?php

use ElkArte\Http\Headers;
use ElkArte\Util;

/**
 * Dumps the database.
 *
 * What it does:
 *
 * - It writes all of the database to standard output.
 * - It uses gzip compression if compress is set in the URL/post data.
 * - It may possibly time out, and mess up badly if you were relying on it. :P
 * - The data dumped depends on whether "struct" and "data" are passed.
 * - It is called from ManageMaintenance.controller.php.
 */
function DumpDatabase2()
{
	global $db_name, $scripturl, $modSettings, $db_prefix, $db_show_debug;

	// We'll need a db to dump :P
	$database = database();

	// We don't need debug when dumping the database
	$modSettings['disableQueryCheck'] = true;
	$db_show_debug = false;

	// You can't dump nothing!
	if (!isset($_REQUEST['struct']) && !isset($_REQUEST['data']))
	{
		$_REQUEST['data'] = true;
	}

	// Attempt to stop from dying...
	detectServer()->setTimeLimit(600);
	$time_limit = ini_get('max_execution_time');
	$start_time = time();

	// @todo ... fail on not getting the requested memory?
	detectServer()->setMemoryLimit('256M');
	$memory_limit = memoryReturnBytes(ini_get('memory_limit')) / 4;
	$current_used_memory = 0;
	$db_backup = '';
	$output_function = 'un_compressed';
	$headers = Headers::instance();

	@ob_end_clean();

	// Start saving the output... (don't do it otherwise for memory reasons.)
	if (isset($_REQUEST['compress']) && function_exists('gzencode'))
	{
		$output_function = 'gzencode';

		// Send faked headers so it will just save the compressed output as a gzip.
		$headers
			->removeHeader('all')
			->contentType('application/x-gzip', '')
			->header('Accept-Ranges', 'bytes');

		// The file extension will include .gz...
		$extension = '.sql.gz';
	}
	else
	{
		// Get rid of the gzipping already being done.
		if (!empty($modSettings['enableCompressedOutput']))
		{
			@ob_end_clean();
		}
		// If we can, clean anything already sent from the output buffer...
		elseif (ob_get_length() != 0)
		{
			ob_clean();
		}

		// Tell the client to save this file, even though it's text.
		$headers
			->removeHeader('all')
			->contentType('application/octet-stream', '');

		// This time the extension should just be .sql.
		$extension = '.sql';
	}

	// This should turn off the session URL parser.
	$scripturl = '';

	// Send the proper headers to let them download this file.
	$filename = $db_name . '-' . (empty($_REQUEST['struct']) ? 'data' : (empty($_REQUEST['data']) ? 'structure' : 'complete')) . '_' . Util::strftime('%Y-%m-%d') . $extension . '"';

	$headers
		->header('Content-Disposition', 'attachment; filename="' . $filename . '"')
		->header('Cache-Control', 'private')
		->header('Connection', 'close')
		->sendHeaders();

	// This makes things simpler when using it so very very often.
	$crlf = "\r\n";

	// SQL Dump Header.
	$db_chunks =
		'-- ==========================================================' . $crlf .
		'--' . $crlf .
		'-- Database dump of tables in `' . $db_name . '`' . $crlf .
		'-- ' . standardTime(time(), false) . $crlf .
		'--' . $crlf .
		'-- ==========================================================' . $crlf .
		$crlf;

	// Get all tables in the database....for our installation
	$real_prefix = preg_match('~^(`?)(.+?)\\1\\.(.*?)$~', $db_prefix, $match) === 1 ? $match[3] : $db_prefix;
	$tables = $database->list_tables(false, $real_prefix . '%');

	// Dump each table.
	foreach ($tables as $tableName)
	{
		// Are we dumping the structures?
		if (isset($_REQUEST['struct']))
		{
			$db_chunks .=
				$crlf .
				'--' . $crlf .
				'-- Table structure for table `' . $tableName . '`' . $crlf .
				'--' . $crlf .
				$crlf .
				$database->table_sql($tableName) . ';' . $crlf;
		}
		// This is needed to speedup things later
		else
		{
			$database->table_sql($tableName);
		}

		// How about the data?
		if (!isset($_REQUEST['data']) || substr($tableName, -10) === 'log_errors')
		{
			continue;
		}

		$first_round = true;
		$close_table = false;

		// Are there any rows in this table?
		while (($get_rows = $database->insert_sql($tableName, $first_round)))
		{
			if (empty($get_rows))
			{
				break;
			}

			// Time is what we need here!
			if (function_exists('apache_reset_timeout'))
			{
				@apache_reset_timeout();
			}
			elseif (!empty($time_limit) && (((int) $start_time + (int) $time_limit - 20) > time()))
			{
				$start_time = time();
				detectServer()->setTimeLimit(150);
			}

			// for the first pass, start the output with a custom line...
			if ($first_round)
			{
				$db_chunks .=
					$crlf .
					'--' . $crlf .
					'-- Dumping data in `' . $tableName . '`' . $crlf .
					'--' . $crlf .
					$crlf;
				$first_round = false;
			}
			$db_chunks .= $get_rows;
			$current_used_memory += Util::strlen($db_chunks);

			$db_backup .= $db_chunks;
			unset($db_chunks);
			$db_chunks = '';
			if ($current_used_memory > $memory_limit)
			{
				echo $output_function($db_backup);
				$current_used_memory = 0;

				// This is probably redundant
				unset($db_backup);
				$db_backup = '';
			}
			$close_table = true;
		}

		// No rows to get - skip it.
		if ($close_table)
		{
			$db_backup .=
				'-- --------------------------------------------------------' . $crlf;
		}
	}

	// write the last line
	$db_backup .= $crlf . '-- Done' . $crlf;

	echo $output_function($db_backup);

	exit;
}

/**
 * Dummy/helper function, it simply returns the string passed as argument
 *
 * @param string $string - string to uncompress
 *
 * @return string
 */
function un_compressed($string = '')
{
	return $string;
}


text:
published: true
title: XXe dimanche après la Pentecôte
---
**Dimanche 23 octobre 2022, messe de 18h30**

![tristesse.jpg]({{site.baseurl}}/images/tristesse.jpg)

*Super flumina Babylonis illic sedimus et flevimus, dum recordaremur tui, Sion.*
Au bord des fleuves de Babylone, nous étions assis et nous pleurions, nous souvenant de toi, Sion.

**Introït : Omnia, quae fecisti nobis**

**Graduel : Oculi omnium**
faux-bourdon du 7e ton

**Alleluia : Paratum cor meum**
verset en faux-bourdon du 3e ton - Johannes Martini

**Offertoire : Super flumina Babylonis**
faux-bourdon du 2e ton

**Communion : Memento**
alternance polyphonique d'H.Isaac 1450-1517 *Choralis Constantinus*

**Au dernier évangile : Salve Regina**

**Sortie : Deo gratias**
d'après Antoine de Févin 1470-1517


text: <!DOCTYPE html>


text:
package com.tce.oauth2.spring.client;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import com.tce.oauth2.spring.client.services.UrlService;

/**
 *
 * @author Titouan COMPIEGNE
 *
 */
@SpringBootApplication
public class Application {

	@Bean
	public RestTemplate restTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.setMessageConverters(getMessageConverters());
		return restTemplate;
	}

	@Bean(name = "urlService")
	public UrlService urlService() {
		return new UrlService();
	}

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

	private List<HttpMessageConverter<?>> getMessageConverters() {
		List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
		converters.add(new MappingJackson2HttpMessageConverter());
		return converters;
	}

}


text:
package com.tr4android.support.extension.typeface;

import android.content.Context;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Environment;
import android.support.v4.util.LruCache;
import android.util.Log;

import java.util.HashMap;

/**
 * Compatibility class that implements backwards support for the text styles recommended
 * in the Typography section of the Material Design guidelines on all devices back to API level 7.
 * If Typeface detection is enabled TypefaceCompat will respect custom system typefaces while still maintaining
 * the newest default typeface (Roboto) on all devices back to API level 14.
 *
 * @since 0.1.1
 * @deprecated Use downloadable fonts
 * or FontsContractCompat
 * instead.
 */
@Deprecated
public class TypefaceCompat {
    private static final HashMap<String, String> FONT_FAMILY_FILE_PREFIX = new HashMap<>();
    private static final String[] STYLE_SUFFIX = new String[]{"Regular", "Bold", "Italic", "BoldItalic"};
    private static final String TTF_SUFFIX = ".ttf";

    private static final int TYPEFACE_CACHE_MAX_SIZE = 8;
    private static final LruCache<String, Typeface> TYPEFACE_CACHE = new LruCache<>(TYPEFACE_CACHE_MAX_SIZE);

    private static final String SYSTEM_ROBOTO_REGULAR_FILE_PATH = Environment.getRootDirectory() + "/fonts/Roboto-Regular.ttf";

    private static boolean mIsUsingDefaultFont = true; // boolean indicating whether user wants the device to use its default font or not
    private static boolean mTypefaceDetectionEnabled = true;

    private static boolean mInitialized;

    static {
        FONT_FAMILY_FILE_PREFIX.put("sans-serif", "Roboto-");
        FONT_FAMILY_FILE_PREFIX.put("sans-serif-light", "Roboto-Light");
        FONT_FAMILY_FILE_PREFIX.put("sans-serif-thin", "Roboto-Thin");
        FONT_FAMILY_FILE_PREFIX.put("sans-serif-condensed", "RobotoCondensed-");
        FONT_FAMILY_FILE_PREFIX.put("sans-serif-medium", "Roboto-Medium");
        FONT_FAMILY_FILE_PREFIX.put("sans-serif-black", "Roboto-Black");
        FONT_FAMILY_FILE_PREFIX.put("sans-serif-condensed-light", "RobotoCondensed-Light");
    }

    @Deprecated
    private static void initialize() {
        Log.w("TypefaceCompat", "TypefaceCompat is deprecated. Use downloadable fonts or FontsContractCompat instead.");
        if (mTypefaceDetectionEnabled && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            Typeface roboto = Typeface.createFromFile(SYSTEM_ROBOTO_REGULAR_FILE_PATH);
            if (roboto != null) {
                mIsUsingDefaultFont = TypefaceUtils.sameAs(roboto, Typeface.SANS_SERIF);
            }
        }
        mInitialized = true;
    }

    /**
     * Use {@link #setTypefaceDetectionEnabled(boolean)} instead.
     *
     * @param typefaceDetectionEnabled True if the used system typeface should be automatically detected and behavior properly adjusted.
     *                                 This makes sure that the newer Roboto typefaces are only used if no custom typefaces are applied by the system.
     * @see #setTypefaceDetectionEnabled(boolean)
     * @since 0.1.1
     * @deprecated Use {@link #setTypefaceDetectionEnabled(boolean)} instead.
     */
    @Deprecated
    public static void initialize(boolean typefaceDetectionEnabled) {
        setTypefaceDetectionEnabled(typefaceDetectionEnabled);
    }

    /**
     * Set whether the typeface detection should be enabled. By default typeface detection is enabled.
     * If typeface detection is enabled it will respect custom system typefaces.
     *

     * Note: This only works starting with API level 14 and comes with a small performance penalty.
     *
     * @param typefaceDetectionEnabled True if the used system typeface should be automatically detected and behavior properly adjusted.
     *                                 This makes sure that the newer Roboto typefaces are only used if no custom typefaces are applied by the system.
     * @since 0.4.1
     * @deprecated
     */
    @Deprecated
    public static void setTypefaceDetectionEnabled(boolean typefaceDetectionEnabled) {
        mTypefaceDetectionEnabled = typefaceDetectionEnabled;
        initialize();
    }

    /**
     * Creates a typeface object that best matches the specified typeface and the specified style.
     * Use this call if you want to pick a new style from the same family of an typeface object.
     * If family is null, this selects from the default font's family.
     *
     * @param ctx        A context.
     * @param familyName May be null. The name of the font family.
     * @param style      The style (normal, bold, italic) of the typeface, e.g. NORMAL, BOLD, ITALIC, BOLD_ITALIC.
     * @return The best matching typeface.
     * @since 0.1.1
     * @deprecated
     */
    @Deprecated
    public static Typeface create(Context ctx, String familyName, int style) {
        if (!mInitialized) initialize();
        if (isSupported(familyName) || familyName == null) {
            boolean styleAfterwards = false;
            String fileName = FONT_FAMILY_FILE_PREFIX.get(familyName == null ? "sans-serif" : familyName);
            if (fileName.endsWith("-")) {
                // All styles are supported.
                fileName += STYLE_SUFFIX[style];
            } else {
                switch (style) {
                    case Typeface.NORMAL:
                        break;
                    case Typeface.BOLD:
                    case Typeface.BOLD_ITALIC:
                        // These styles are not supported by default. Therefore force style after retrieving normal font.
                        styleAfterwards = true;
                        break;
                    case Typeface.ITALIC:
                        fileName += STYLE_SUFFIX[style];
                        break;
                }
            }
            fileName += TTF_SUFFIX;
            // Retrieve Typeface from cache.
            Typeface tf = TYPEFACE_CACHE.get(fileName);
            if (tf == null) {
                // Create Typeface and cache it for later.
                String fontPath = "fonts/" + fileName;
                tf = Typeface.createFromAsset(ctx.getAssets(), fontPath);
                if (tf != null) {
                    TYPEFACE_CACHE.put(fileName, tf);
                }
            }
            if (tf != null) {
                return styleAfterwards ? Typeface.create(tf, style) : tf;
            }
        }
        // Let the default implementation of Typeface try.
        return Typeface.create(familyName, style);
    }

    /**
     * Checks if a certain font family is supported.
     *
     * @param familyName The name of the font family.
     * @return True if the font family is supported. False otherwise.
     * @since 0.1.1
     * @deprecated
     */
    @Deprecated
    public static boolean isSupported(String familyName) {
        if (!mInitialized) initialize();
        return FONT_FAMILY_FILE_PREFIX.containsKey(familyName) && mIsUsingDefaultFont && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP;
    }
}