text:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Abp.Auditing;
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using Abp.Configuration.Startup;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Runtime.Session;
using Abp.Threading;
using Abp.UI;
using Abp.Web.Models;
using Kinare.FormSystem.Authorization;
using Kinare.FormSystem.Authorization.Roles;
using Kinare.FormSystem.Authorization.Users;
using Kinare.FormSystem.MultiTenancy;
using Kinare.FormSystem.Sessions;
using Kinare.FormSystem.Web.Controllers.Results;
using Kinare.FormSystem.Web.Models;
using Kinare.FormSystem.Web.Models.Account;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;

namespace Kinare.FormSystem.Web.Controllers
{
    public class AccountController : FormSystemControllerBase
    {
        private readonly TenantManager _tenantManager;
        private readonly UserManager _userManager;
        private readonly RoleManager _roleManager;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly IMultiTenancyConfig _multiTenancyConfig;
        private readonly LogInManager _logInManager;
        private readonly ISessionAppService _sessionAppService;
        private readonly ILanguageManager _languageManager;
        private readonly ITenantCache _tenantCache;

        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.GetOwinContext().Authentication;
            }
        }

        public AccountController(
            TenantManager tenantManager,
            UserManager userManager,
            RoleManager roleManager,
            IUnitOfWorkManager unitOfWorkManager,
            IMultiTenancyConfig multiTenancyConfig,
            LogInManager logInManager,
            ISessionAppService sessionAppService,
            ILanguageManager languageManager,
            ITenantCache tenantCache)
        {
            _tenantManager = tenantManager;
            _userManager = userManager;
            _roleManager = roleManager;
            _unitOfWorkManager = unitOfWorkManager;
            _multiTenancyConfig = multiTenancyConfig;
            _logInManager = logInManager;
            _sessionAppService = sessionAppService;
            _languageManager = languageManager;
            _tenantCache = tenantCache;
        }

        #region Login / Logout

        public ActionResult Login(string returnUrl = "")
        {
            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Request.ApplicationPath;
            }

            ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;

            return View(
                new LoginFormViewModel
                {
                    ReturnUrl = returnUrl,
                    IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled,
                    IsSelfRegistrationAllowed = IsSelfRegistrationEnabled(),
                    MultiTenancySide = AbpSession.MultiTenancySide
                });
        }

        [HttpPost]
        [DisableAuditing]
        public async Task<JsonResult> Login(LoginViewModel loginModel, string returnUrl = "", string returnUrlHash = "")
        {
            CheckModelState();

            var loginResult = await GetLoginResultAsync(
                loginModel.UsernameOrEmailAddress,
                loginModel.Password,
                GetTenancyNameOrNull()
            );

            await SignInAsync(loginResult.User, loginResult.Identity, loginModel.RememberMe);

            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                returnUrl = Request.ApplicationPath;
            }

            if (!string.IsNullOrWhiteSpace(returnUrlHash))
            {
                returnUrl = returnUrl + returnUrlHash;
            }

            return Json(new AjaxResponse { TargetUrl = returnUrl });
        }

        private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName)
        {
            var loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName);

            switch (loginResult.Result)
            {
                case AbpLoginResultType.Success:
                    return loginResult;
                default:
                    throw CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
            }
        }

        private async Task SignInAsync(User user, ClaimsIdentity identity = null, bool rememberMe = false)
        {
            if (identity == null)
            {
                identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
            }

            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
            AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = rememberMe }, identity);
        }

        private Exception CreateExceptionForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName)
        {
            switch (result)
            {
                case AbpLoginResultType.Success:
                    return new ApplicationException("Don't call this method with a success result!");
                case AbpLoginResultType.InvalidUserNameOrEmailAddress:
                case AbpLoginResultType.InvalidPassword:
                    return new UserFriendlyException(L("LoginFailed"), L("InvalidUserNameOrPassword"));
                case AbpLoginResultType.InvalidTenancyName:
                    return new UserFriendlyException(L("LoginFailed"), L("ThereIsNoTenantDefinedWithName{0}", tenancyName));
                case AbpLoginResultType.TenantIsNotActive:
                    return new UserFriendlyException(L("LoginFailed"), L("TenantIsNotActive", tenancyName));
                case AbpLoginResultType.UserIsNotActive:
                    return new UserFriendlyException(L("LoginFailed"), L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress));
                case AbpLoginResultType.UserEmailIsNotConfirmed:
                    return new UserFriendlyException(L("LoginFailed"), "UserEmailIsNotConfirmedAndCanNotLogin");
                case AbpLoginResultType.LockedOut:
                    return new UserFriendlyException(L("LoginFailed"), L("UserLockedOutMessage"));
                default: //Can not fall to default actually. But other result types can be added in the future and we may forget to handle it
                    Logger.Warn("Unhandled login fail reason: " + result);
                    return new UserFriendlyException(L("LoginFailed"));
            }
        }

        public ActionResult Logout()
        {
            AuthenticationManager.SignOut();
            return RedirectToAction("Login");
        }

        #endregion

        #region Register

        public ActionResult Register()
        {
            return RegisterView(new RegisterViewModel());
        }

        private ActionResult RegisterView(RegisterViewModel model)
        {
            ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;

            return View("Register", model);
        }

        private bool IsSelfRegistrationEnabled()
        {
            if (!AbpSession.TenantId.HasValue)
            {
                return false; //No registration enabled for host users!
            }

            return true;
        }

        [HttpPost]
        public virtual async Task<ActionResult> Register(RegisterViewModel model)
        {
            try
            {
                CheckModelState();

                //Create user
                var user = new User
                {
                    Name = model.Name,
                    Surname = model.Surname,
                    EmailAddress = model.EmailAddress,
                    IsActive = true
                };

                //Get external login info if possible
                ExternalLoginInfo externalLoginInfo = null;
                if (model.IsExternalLogin)
                {
                    externalLoginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
                    if (externalLoginInfo == null)
                    {
                        throw new ApplicationException("Can not external login!");
                    }

                    user.Logins = new List<UserLogin>
                    {
                        new UserLogin
                        {
                            LoginProvider = externalLoginInfo.Login.LoginProvider,
                            ProviderKey = externalLoginInfo.Login.ProviderKey
                        }
                    };

                    if (model.UserName.IsNullOrEmpty())
                    {
                        model.UserName = model.EmailAddress;
                    }

                    model.Password = Authorization.Users.User.CreateRandomPassword();

                    if (string.Equals(externalLoginInfo.Email, model.EmailAddress, StringComparison.InvariantCultureIgnoreCase))
                    {
                        user.IsEmailConfirmed = true;
                    }
                }
                else
                {
                    //Username and Password are required if not external login
                    if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
                    {
                        throw new UserFriendlyException(L("FormIsNotValidMessage"));
                    }
                }

                user.UserName = model.UserName;
                user.Password = new PasswordHasher().HashPassword(model.Password);

                //Switch to the tenant
                _unitOfWorkManager.Current.EnableFilter(AbpDataFilters.MayHaveTenant); //TODO: Needed?
                _unitOfWorkManager.Current.SetTenantId(AbpSession.GetTenantId());

                //Add default roles
                user.Roles = new List<UserRole>();
                foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
                {
                    user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
                }

                //Save user
                CheckErrors(await _userManager.CreateAsync(user));
                await _unitOfWorkManager.Current.SaveChangesAsync();

                //Directly login if possible
                if (user.IsActive)
                {
                    AbpLoginResult<Tenant, User> loginResult;
                    if (externalLoginInfo != null)
                    {
                        loginResult = await _logInManager.LoginAsync(externalLoginInfo.Login, GetTenancyNameOrNull());
                    }
                    else
                    {
                        loginResult = await GetLoginResultAsync(user.UserName, model.Password, GetTenancyNameOrNull());
                    }

                    if (loginResult.Result == AbpLoginResultType.Success)
                    {
                        await SignInAsync(loginResult.User, loginResult.Identity);
                        return Redirect(Url.Action("Index", "Home"));
                    }

                    Logger.Warn("New registered user could not be login. This should not be normally. login result: " + loginResult.Result);
                }

                //If can not login, show a register result page
                return View("RegisterResult", new RegisterResultViewModel
                {
                    TenancyName = GetTenancyNameOrNull(),
                    NameAndSurname = user.Name + " " + user.Surname,
                    UserName = user.UserName,
                    EmailAddress = user.EmailAddress,
                    IsActive = user.IsActive
                });
            }
            catch (UserFriendlyException ex)
            {
                ViewBag.IsMultiTenancyEnabled = _multiTenancyConfig.IsEnabled;
                ViewBag.ErrorMessage = ex.Message;

                return View("Register", model);
            }
        }

        #endregion

        #region External Login

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ChallengeResult(
                provider,
                Url.Action(
                    "ExternalLoginCallback",
                    "Account",
                    new
                    {
                        ReturnUrl = returnUrl
                    })
            );
        }

        public virtual async Task<ActionResult> ExternalLoginCallback(string returnUrl, string tenancyName = "")
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                return RedirectToAction("Login");
            }

            //Try to find tenancy name
            if (tenancyName.IsNullOrEmpty())
            {
                var tenants = await FindPossibleTenantsOfUserAsync(loginInfo.Login);
                switch (tenants.Count)
                {
                    case 0:
                        return await RegisterView(loginInfo);
                    case 1:
                        tenancyName = tenants[0].TenancyName;
                        break;
                    default:
                        return View("TenantSelection", new TenantSelectionViewModel
                        {
                            Action = Url.Action("ExternalLoginCallback", "Account", new { returnUrl }),
                            Tenants = tenants.MapTo<List<TenantSelectionViewModel.TenantInfo>>()
                        });
                }
            }

            var loginResult = await _logInManager.LoginAsync(loginInfo.Login, tenancyName);

            switch (loginResult.Result)
            {
                case AbpLoginResultType.Success:
                    await SignInAsync(loginResult.User, loginResult.Identity);

                    if (string.IsNullOrWhiteSpace(returnUrl))
                    {
                        returnUrl = Url.Action("Index", "Home");
                    }

                    return Redirect(returnUrl);
                case AbpLoginResultType.UnknownExternalLogin:
                    return await RegisterView(loginInfo, tenancyName);
                default:
                    throw CreateExceptionForFailedLoginAttempt(loginResult.Result, loginInfo.Email ?? loginInfo.DefaultUserName, tenancyName);
            }
        }

        private async Task<ActionResult> RegisterView(ExternalLoginInfo loginInfo, string tenancyName = null)
        {
            var name = loginInfo.DefaultUserName;
            var surname = loginInfo.DefaultUserName;

            var extractedNameAndSurname = TryExtractNameAndSurnameFromClaims(loginInfo.ExternalIdentity.Claims.ToList(), ref name, ref surname);

            var viewModel = new RegisterViewModel
            {
                EmailAddress = loginInfo.Email,
                Name = name,
                Surname = surname,
                IsExternalLogin = true
            };

            if (!tenancyName.IsNullOrEmpty() && extractedNameAndSurname)
            {
                return await Register(viewModel);
            }

            return RegisterView(viewModel);
        }

        protected virtual async Task<List<Tenant>> FindPossibleTenantsOfUserAsync(UserLoginInfo login)
        {
            List<User> allUsers;
            using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
            {
                allUsers = await _userManager.FindAllAsync(login);
            }

            return allUsers
                .Where(u => u.TenantId != null)
                .Select(u => AsyncHelper.RunSync(() => _tenantManager.FindByIdAsync(u.TenantId.Value)))
                .ToList();
        }

        private static bool TryExtractNameAndSurnameFromClaims(List<Claim> claims, ref string name, ref string surname)
        {
            string foundName = null;
            string foundSurname = null;

            var givennameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.GivenName);
            if (givennameClaim != null && !givennameClaim.Value.IsNullOrEmpty())
            {
                foundName = givennameClaim.Value;
            }

            var surnameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Surname);
            if (surnameClaim != null && !surnameClaim.Value.IsNullOrEmpty())
            {
                foundSurname = surnameClaim.Value;
            }

            if (foundName == null || foundSurname == null)
            {
                var nameClaim = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name);
                if (nameClaim != null)
                {
                    var nameSurName = nameClaim.Value;
                    if (!nameSurName.IsNullOrEmpty())
                    {
                        var lastSpaceIndex = nameSurName.LastIndexOf(' ');
                        if (lastSpaceIndex < 1 || lastSpaceIndex > (nameSurName.Length - 2))
                        {
                            foundName = foundSurname = nameSurName;
                        }
                        else
                        {
                            foundName = nameSurName.Substring(0, lastSpaceIndex);
                            foundSurname = nameSurName.Substring(lastSpaceIndex);
                        }
                    }
                }
            }

            if (!foundName.IsNullOrEmpty())
            {
                name = foundName;
            }

            if (!foundSurname.IsNullOrEmpty())
            {
                surname = foundSurname;
            }

            return foundName != null && foundSurname != null;
        }

        #endregion

        #region Common private methods

        private async Task<Tenant> GetActiveTenantAsync(string tenancyName)
        {
            var tenant = await _tenantManager.FindByTenancyNameAsync(tenancyName);
            if (tenant == null)
            {
                throw new UserFriendlyException(L("ThereIsNoTenantDefinedWithName{0}", tenancyName));
            }

            if (!tenant.IsActive)
            {
                throw new UserFriendlyException(L("TenantIsNotActive", tenancyName));
            }

            return tenant;
        }

        private string GetTenancyNameOrNull()
        {
            if (!AbpSession.TenantId.HasValue)
            {
                return null;
            }

            return _tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName;
        }

        #endregion

        #region Common Partial Views

        [ChildActionOnly]
        public PartialViewResult TenantChange()
        {
            var loginInformations = AsyncHelper.RunSync(() => _sessionAppService.GetCurrentLoginInformations());

            return PartialView("_TenantChange", new TenantChangeViewModel
            {
                Tenant = loginInformations.Tenant
            });
        }

        public async Task<PartialViewResult> TenantChangeModal()
        {
            var loginInfo = await _sessionAppService.GetCurrentLoginInformations();
            return PartialView("_TenantChangeModal", new TenantChangeModalViewModel
            {
                TenancyName = loginInfo.Tenant?.TenancyName
            });
        }

        [ChildActionOnly]
        public PartialViewResult _AccountLanguages()
        {
            var model = new LanguageSelectionViewModel
            {
                CurrentLanguage = _languageManager.CurrentLanguage,
                Languages = _languageManager.GetLanguages().Where(l => !l.IsDisabled).ToList()
                    .Where(l => !l.IsDisabled)
                    .ToList(),
                CurrentUrl = Request.Path
            };

            return PartialView("_AccountLanguages", model);
        }

        #endregion
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: chuxiaofeng
 * Date: 17/1/14
 * Time: 下午4:49
 */

namespace Minimalism\Scheme\Value\Primitives;

use Minimalism\Scheme\Ast\Node;
use Minimalism\Scheme\Interpreter;
use Minimalism\Scheme\Scope;
use Minimalism\Scheme\Value\FloatType;
use Minimalism\Scheme\Value\FloatValue;
use Minimalism\Scheme\Value\IntType;
use Minimalism\Scheme\Value\IntValue;
use Minimalism\Scheme\Value\PrimFun;
use Minimalism\Scheme\Value\Type;
use Minimalism\Scheme\Value\Value;

class Mult extends PrimFun
{
    public function __construct()
    {
        parent::__construct("*", 2);
    }

    /**
     * @param Value[] $args Values
     * @param Node $location
     * @return FloatValue|IntValue
     */
    public function apply(array $args, Node $location)
    {
        list($v1, $v2) = $args;

        if ($v1 instanceof IntValue && $v2 instanceof IntValue) {
            return new IntValue($v1->value * $v2->value);
        }
        if ($v1 instanceof FloatValue && $v2 instanceof FloatValue) {
            return new FloatValue($v1->value * $v2->value);
        }
        if ($v1 instanceof FloatValue && $v2 instanceof IntValue) {
            return new FloatValue($v1->value * $v2->value);
        }
        if ($v1 instanceof IntValue && $v2 instanceof FloatValue) {
            return new FloatValue($v1->value * $v2->value);
        }

        Interpreter::abort("incorrect argument types for *: $v1, $v2", $location);
        return null;
    }

    /**
     * @param Value[] $args Types
     * @param Node $location
     * @return IntType|FloatType
     */
    public function typecheck(array $args, Node $location)
    {
        list($v1, $v2) = $args;

        if ($v1 instanceof FloatType || $v2 instanceof FloatType) {
            return Type::$FLOAT;
        }
        if ($v1 instanceof IntType && $v2 instanceof IntType) {
            return Type::$INT;
        }

        Interpreter::abort("incorrect argument types for *: $v1, $v2", $location);
        return null;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <fragment
        android:layout_width="match_parent"
        android:id="@+id/choose_area_fragment"
        android:name="com.coolweather.anrdoid.ChooseAreaFragment"
        android:layout_height="match_parent"
        />

</FrameLayout>


text:
#include <common.h>
#include <config.h>
#include <asm/blackfin.h>
#include <asm/net.h>
#include <net.h>
#include <netdev.h>
#include <asm/gpio.h>

static void disable_external_watchdog(void)
{
#ifdef CONFIG_DNP5370_EXT_WD_DISABLE
	/* disable external HW watchdog with PH13 = WD1 = 1 */
	gpio_request(GPIO_PH13, "ext_wd");
	gpio_direction_output(GPIO_PH13, 1);
#endif
}

int checkboard(void)
{
	printf("Board: SSV DilNet DNP5370\n");
	return 0;
}

#ifdef CONFIG_BFIN_MAC
static void board_init_enetaddr(uchar *mac_addr)
{
#ifdef CONFIG_SYS_NO_FLASH
# define USE_MAC_IN_FLASH 0
#else
# define USE_MAC_IN_FLASH 1
#endif
	bool valid_mac = false;

	if (USE_MAC_IN_FLASH) {
		/* we cram the MAC in the last flash sector */
		uchar *board_mac_addr = (uchar *)0x202F0000;
		if (is_valid_ether_addr(board_mac_addr)) {
			memcpy(mac_addr, board_mac_addr, 6);
			valid_mac = true;
		}
	}

	if (!valid_mac) {
		puts("Warning: Generating 'random' MAC address\n");
		bfin_gen_rand_mac(mac_addr);
	}

	eth_setenv_enetaddr("ethaddr", mac_addr);
}

int board_eth_init(bd_t *bis)
{
	return bfin_EMAC_initialize(bis);
}
#endif

/* miscellaneous platform dependent initialisations */
int misc_init_r(void)
{
	disable_external_watchdog();

#ifdef CONFIG_BFIN_MAC
	uchar enetaddr[6];
	if (!eth_getenv_enetaddr("ethaddr", enetaddr))
		board_init_enetaddr(enetaddr);
#endif

#ifndef CONFIG_SYS_NO_FLASH
	/* we use the last sector for the MAC address / POST LDR */
	extern flash_info_t flash_info[];
	flash_protect(FLAG_PROTECT_SET, 0x202F0000, 0x202FFFFF, &flash_info[0]);
#endif

	return 0;
}


text:
A collector and writer of simple statistics.

We use it, for example, to generate a JSON file that tells us things such as as how often we miss a fetch from a pool or have to grow a supposedly fixed-length buffer.

```go
// Run every minute.
// Save output to stats.json, truncate the file each time
func init() {
  config := statsreg.Configure().
    Frequency(time.Minute).
    File("stats.json", true)
  sr := statsreg.New(config)

  // bp.Misses is a func() int64 that records how often a get
  // hit a drained pool
  sr.RegisterInt64("main_pool_misses", bp.Misses)

  // note that both debug.ReadGCStats() and runtime.NumGoroutine()
  // require fairly exclusive locks and, under load, you might
  // want to consider whether or not they should be on at all times
  // (for the record runtime.ReadMemStats() is much more intrusive)
  sr.RegisterInt64("gcs", func() int64 {
    stats := new(debug.GCStats) // import "runtime/debug"
    debug.ReadGCStats(stats)
    return stats.NumGC
  })
  sr.RegisterGeneric("goroutines", func() interface{} {
    return runtime.NumGoroutine() // import "runtime"
  })
}
```

## Functions
- `RegisterInt64(name string, provider func() int64)` - registers a provider that returns an int64
- `RegisterString(name string, provider func() string)` - registers a provider that returns an string
- `RegisterGeneric(name string, provider func() interface{})` - registers a provider that returns an interface{}. The value must be serializable using encoding/json
- `Remove(name string)` - removes the provider. Safe to call if it doesn't exist

Methods are thread-safe.

### Overwriting
By default, statsreg will log a message when registering an alread-registered name. This makes sense for static statistics (those registered at init). However, you may want to dynamically register statistics, sometimes with the same name. You can disable the logging by setting the global var `LogOverwrite` to `nil` (this is actually a function, so you could implement your own custom logging logic, but why?).


text:
package water;

import water.api.RequestServer;
import water.api.RestApiExtension;
import water.api.SchemaServer;
import water.util.Log;
import water.util.StringUtils;
import water.webserver.iface.RequestAuthExtension;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.ServiceLoader;

public class ExtensionManager {

  private static ExtensionManager extManager = new ExtensionManager();

  /** System property to force enable/disable named REST API extension */
  private static String PROP_TOGGLE_REST_EXT = H2O.OptArgs.SYSTEM_PROP_PREFIX + "ext.rest.toggle.";

  /** System property to force enable/disable named Core extension */
  private static String PROP_TOGGLE_CORE_EXT = H2O.OptArgs.SYSTEM_PROP_PREFIX + "ext.core.toggle.";

  private ExtensionManager(){
  }

  public static ExtensionManager getInstance(){
    return extManager;
  }

  private HashMap<String, AbstractH2OExtension> coreExtensions = new HashMap<>();
  private HashMap<String, RestApiExtension> restApiExtensions = new HashMap<>();
  private HashMap<String, H2OListenerExtension> listenerExtensions = new HashMap<>();
  private HashMap<String, RequestAuthExtension> authExtensions = new HashMap<>();
  private long registerCoreExtensionsMillis = 0;
  private long registerListenerExtensionsMillis = 0;
  private long registerAuthExtensionsMillis = 0;
  // Be paranoid and check that this doesn't happen twice.
  private boolean extensionsRegistered = false;
  private boolean restApiExtensionsRegistered = false;
  private boolean listenerExtensionsRegistered = false;
  private boolean authExtensionsRegistered = false;

  public StringBuilder makeExtensionReport(StringBuilder sb) {
    try {
      // Core
      String[] coreExts = getCoreExtensionNames().clone();
      for (int i = 0; i < coreExts.length; i++)
        if (! isCoreExtensionEnabled(coreExts[i]))
          coreExts[i] = coreExts[i] + "(disabled)";
      sb.append("Core Extensions: ").append(StringUtils.join(",", coreExts)).append("; ");
      // Rest
      String[] restExts = getRestApiExtensionNames().clone();
      for (int i = 0; i < restExts.length; i++) {
        RestApiExtension restExt = restApiExtensions.get(restExts[i]);
        if (restExt == null)
          restExts[i] = restExts[i] + "(???)";
        else if (! isEnabled(restExt))
          restExts[i] = restExts[i] + "(disabled)";
      }
      sb.append("Rest Extensions: ").append(StringUtils.join(",", restExts)).append("; ");
      // Listeners
      String[] listernerExts = getListenerExtensionNames();
      sb.append("Listener Extensions: ").append(StringUtils.join(",", listernerExts)).append("; ");
    } catch (Exception e) {
      Log.err("Failed to generate the extension report", e);
      sb.append(e.getMessage());
    }
    return sb;
  }

  public Collection<AbstractH2OExtension> getCoreExtensions() {
    return coreExtensions.values();
  }

  public boolean isCoreExtensionsEnabled(String extensionName){
    AbstractH2OExtension ext = coreExtensions.get(extensionName);
    return ext != null && ext.isEnabled();
  }

  /**
   * Register H2O extensions.
   * <p/>
   * Use SPI to find all classes that extends water.AbstractH2OExtension
   * and call H2O.addCoreExtension() for each.
   */
  public void registerCoreExtensions() {
    if (extensionsRegistered) {
      throw H2O.fail("Extensions already registered");
    }

    long before = System.currentTimeMillis();
    ServiceLoader<AbstractH2OExtension> extensionsLoader = ServiceLoader.load(AbstractH2OExtension.class);
    for (AbstractH2OExtension ext : extensionsLoader) {
      if (isEnabled(ext)) {
        ext.init();
        coreExtensions.put(ext.getExtensionName(), ext);
      }
    }
    extensionsRegistered = true;
    registerCoreExtensionsMillis = System.currentTimeMillis() - before;
  }

  public Collection<RestApiExtension> getRestApiExtensions(){
    return restApiExtensions.values();
  }

  private boolean areDependantCoreExtensionsEnabled(List<String> names){
    for(String name: names){
      AbstractH2OExtension ext = coreExtensions.get(name);
      if(ext == null || !ext.isEnabled()){
        return false;
      }
    }
    return true;
  }

  /**
   * Register REST API routes.
   *
   * Use reflection to find all classes that inherit from {@link water.api.AbstractRegister}
   * and call the register() method for each.
   *
   */
  public void registerRestApiExtensions() {
    if (restApiExtensionsRegistered) {
      throw H2O.fail("APIs already registered");
    }

    // Log core extension registrations here so the message is grouped in the right spot.
    for (AbstractH2OExtension e : getCoreExtensions()) {
      e.printInitialized();
    }
    Log.info("Registered " + coreExtensions.size() + " core extensions in: " + registerCoreExtensionsMillis + "ms");
    Log.info("Registered H2O core extensions: " + Arrays.toString(getCoreExtensionNames()));

    if(listenerExtensions.size() > 0) {
      Log.info("Registered: " + listenerExtensions.size() + " listener extensions in: " + registerListenerExtensionsMillis + "ms");
      Log.info("Registered Listeners extensions: " + Arrays.toString(getListenerExtensionNames()));
    }
    if(authExtensions.size() > 0) {
      Log.info("Registered: " + authExtensions.size() + " auth extensions in: " + registerAuthExtensionsMillis + "ms");
      Log.info("Registered Auth extensions: " + Arrays.toString(getAuthExtensionNames()));
    }
    long before = System.currentTimeMillis();
    RequestServer.DummyRestApiContext dummyRestApiContext = new RequestServer.DummyRestApiContext();
    ServiceLoader<RestApiExtension> restApiExtensionLoader = ServiceLoader.load(RestApiExtension.class);
    for (RestApiExtension r : restApiExtensionLoader) {
      try {
        if (isEnabled(r)) {
          r.registerEndPoints(dummyRestApiContext);
          r.registerSchemas(dummyRestApiContext);
          restApiExtensions.put(r.getName(), r);
        }
      } catch (Exception e) {
        Log.info("Cannot register extension: " + r + ". Skipping it...");
      }
    }

    restApiExtensionsRegistered = true;

    long registerApisMillis = System.currentTimeMillis() - before;
    Log.info("Registered: " + RequestServer.numRoutes() + " REST APIs in: " + registerApisMillis + "ms");
    Log.info("Registered REST API extensions: " + Arrays.toString(getRestApiExtensionNames()));

    // Register all schemas
    SchemaServer.registerAllSchemasIfNecessary(dummyRestApiContext.getAllSchemas());
  }

  private boolean isEnabled(RestApiExtension r) {
    String forceToggle = System.getProperty(PROP_TOGGLE_REST_EXT + r.getName());
    return forceToggle != null
           ? Boolean.valueOf(forceToggle)
           : areDependantCoreExtensionsEnabled(r.getRequiredCoreExtensions());
  }

  private boolean isEnabled(AbstractH2OExtension r) {
    String forceToggle = System.getProperty(PROP_TOGGLE_CORE_EXT + r.getExtensionName());
    return forceToggle != null
           ? Boolean.valueOf(forceToggle)
           : r.isEnabled();
  }

  private String[] getRestApiExtensionNames(){
    return restApiExtensions.keySet().toArray(new String[restApiExtensions.keySet().size()]);
  }

  private String[] getCoreExtensionNames(){
    return coreExtensions.keySet().toArray(new String[coreExtensions.keySet().size()]);
  }

  private String[] getListenerExtensionNames(){
    return listenerExtensions.keySet().toArray(new String[listenerExtensions.keySet().size()]);
  }

  private String[] getAuthExtensionNames(){
    return authExtensions.keySet().toArray(new String[authExtensions.keySet().size()]);
  }

  public boolean isCoreExtensionEnabled(String name) {
    if (coreExtensions.containsKey(name)) {
      return coreExtensions.get(name).isEnabled();
    } else {
      return false;
    }
  }

  /**
   * Register various listener extensions
   *
   * Use reflection to find all classes that inherit from {@link water.api.AbstractRegister}
   * and call the register() method for each.
   *
   */
  public void registerListenerExtensions() {
    if (listenerExtensionsRegistered) {
      throw H2O.fail("Listeners already registered");
    }

    long before = System.currentTimeMillis();
    ServiceLoader<H2OListenerExtension> extensionsLoader = ServiceLoader.load(H2OListenerExtension.class);
    for (H2OListenerExtension ext : extensionsLoader) {
      ext.init();
      listenerExtensions.put(ext.getName(), ext);
    }
    listenerExtensionsRegistered = true;
    registerListenerExtensionsMillis = System.currentTimeMillis() - before;
  }

  public Collection<H2OListenerExtension> getListenerExtensions(){
    return listenerExtensions.values();
  }

  public void registerAuthExtensions() {
    if (authExtensionsRegistered) {
      throw H2O.fail("Auth extensions already registered");
    }

    long before = System.currentTimeMillis();
    ServiceLoader<RequestAuthExtension> extensionsLoader = ServiceLoader.load(RequestAuthExtension.class);
    for (RequestAuthExtension ext : extensionsLoader) {
      authExtensions.put(ext.getClass().getName(), ext);
    }
    authExtensionsRegistered = true;
    registerAuthExtensionsMillis = System.currentTimeMillis() - before;
  }

  public Collection<RequestAuthExtension> getAuthExtensions(){
    return authExtensions.values();
  }

}


text:
import {Page, NavController, ViewController} from 'ionic-angular';

/*
  Generated class for the AddBankPage page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Page({
  templateUrl: 'build/pages/add-bank/add-bank.html',
})
export class AddBankPage {

  bank = {
    bank_no: "",
    bank_name: "",
    bank_owner: ""
  };

  constructor(public nav: NavController, public viewCtrl: ViewController) {

  }

  close() {
    this.viewCtrl.dismiss();
  }

  add(item) {
    this.viewCtrl.dismiss(JSON.stringify(item));
  }
}


text:
Mac show all hidden files

https://davidwalsh.name/show-hidden-files


text:
var flyd = require('flyd');

module.exports = flyd.curryN(2, function(dur, s) {
  var values = [];
  return flyd.stream([s], function(self) {
    setTimeout(function() {
      self(values = values.slice(1));
    }, dur);
    return (values = values.concat([s()]));
  });
});


text:
foam.CLASS({
  name: 'FOAMException',
  package: 'foam.core',
  implements: [ 'foam.core.Exception' ],
  javaExtends: 'RuntimeException',
  javaGenerateConvenienceConstructor: false,

  axioms: [
    {
      name: 'javaExtras',
      buildJavaClass: function(cls) {
        cls.extras.push(`
  public FOAMException(String message) {
    super(message);
    setMessage_(message);
    getHostname();
  }

  public FOAMException(Throwable cause) {
    super(cause);
    setMessage_(cause.getMessage());
    getHostname();
  }

  public FOAMException(String message, Throwable cause) {
    super(message, cause);
    setMessage_(message);
    getHostname();
  }
        `);
      }
    }
  ],

  properties: [
    {
      name: 'javaGenerateConvenienceConstructor',
      value: false,
      transient: true,
      visibility: 'HIDDEN'
    },
    {
      name: 'message_',
      class: 'String',
      visibility: 'RO'
    },
    {
      name: 'hostname',
      class: 'String',
      javaFactory: 'return System.getProperty("hostname", "localhost");',
      visibilty: 'RO'
    }
  ],

  methods: [
    {
      name: 'getMessage',
      type: 'String',
      javaCode: `
      String msg = getMessage_();
      if ( foam.util.SafetyUtil.isEmpty(msg) ) {
        return super.getMessage();
      }
      return msg;
      `
    },
    {
      name: 'toString',
      type: 'String',
      javaCode: `
      return "["+getHostname()+"],"+this.getClass().getName()+","+super.getMessage();
      `
    }
  ]
});


text:
package com.geewhiz.pacify.property.resolver;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.geewhiz.pacify.defect.Defect;

public class HashMapPropertyResolver extends BasePropertyResolver {

    Map<String, String> properties          = new HashMap<String, String>();
    List<String>        protectedProperties = new ArrayList<String>();

    private String      beginToken          = "%{";
    private String      endToken            = "}";

    public HashMapPropertyResolver() {
    }

    public HashMapPropertyResolver(String key, String value) {
        addProperty(key, value);
    }

    public HashMapPropertyResolver(Map<String, String> properties) {
        addAllProperties(properties);
    }

    public void addProperty(String key, String value) {
        if (key.startsWith("*")) {
            key = key.substring(1);
            protectedProperties.add(key);
        }
        properties.put(key, value);
    }

    public void addAllProperties(Map<String, String> properties) {
        for (String key : properties.keySet()) {
            addProperty(key, properties.get(key));
        }
    }

    @Override
    public boolean containsProperty(String key) {
        return properties.containsKey(key);
    }

    @Override
    public String getPropertyValue(String key) {
        return properties.get(key);
    }

    @Override
    public Set<String> getPropertyKeys() {
        return properties.keySet();
    }

    @Override
    public String getEncoding() {
        return "UTF-8";
    }

    @Override
    public String getPropertyResolverDescription() {
        return this.getClass().getSimpleName();
    }

    @Override
    public LinkedHashSet<Defect> checkForDuplicateEntry() {
        return new LinkedHashSet<Defect>();
    }

    @Override
    public String getBeginToken() {
        return beginToken;
    }

    @Override
    public String getEndToken() {
        return endToken;
    }

    @Override
    public boolean isProtectedProperty(String key) {
        return protectedProperties.contains(key);
    }

    public void setBeginToken(String beginToken) {
        this.beginToken = beginToken;
    }

    public void setEndToken(String endToken) {
        this.endToken = endToken;
    }

}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*================================================================================
	SplashScreen.cpp: Splash screen for game/editor startup
================================================================================*/

#include "CorePrivatePCH.h"
#include "Misc/App.h"
#include "EngineVersion.h"
#include "EngineBuildSettings.h"

#if WITH_EDITOR

#include <GL/glcorearb.h>
#include <GL/glext.h>
#include "SDL.h"
#include "SDL_thread.h"
#include "SDL_timer.h"

#include "ft2build.h"
#include FT_FREETYPE_H

/**
 * Splash screen functions and static globals
 */

struct Rect
{
	int32 Top;
	int32 Left;
	int32 Right;
	int32 Bottom;
};

struct SplashFont
{
	enum State
	{
		NotLoaded = 0,
		Loaded
	};

	FT_Face Face;
	int32 Status;
};

FT_Library FontLibrary;

SplashFont FontSmall;
SplashFont FontNormal;
SplashFont FontLarge;

static SDL_Thread *GSplashThread = nullptr;
static SDL_Window *GSplashWindow = nullptr;
static SDL_Renderer *GSplashRenderer = nullptr;
static SDL_Texture *GSplashTexture = nullptr;
static SDL_Surface *GSplashScreenImage = nullptr;
static SDL_Surface *GSplashIconImage = nullptr;
static SDL_Surface *message = nullptr;
static FText GSplashScreenAppName;
static FText GSplashScreenText[ SplashTextType::NumTextTypes ];
static Rect GSplashScreenTextRects[ SplashTextType::NumTextTypes ];
static FString GSplashPath;
static FString GIconPath;

static int32 SplashWidth = 0, SplashHeight = 0;
static unsigned char *ScratchSpace = nullptr;
/**
 * Used for communication with a splash thread.
 * Negative values -> thread is (or must be) stopped.
 * >= 0 -> thread is running
 * > 0 -> there is an update that necessitates (re)rendering the string.
 */
static volatile int32 ThreadState = -1;
static int32 SplashBPP = 0;

//////////////////////////////////
// the below GL subset is a hack, as in general using GL for that

// subset of GL functions
/** List all OpenGL entry points used by Unreal. */
#define ENUM_GL_ENTRYPOINTS(EnumMacro) \
	EnumMacro(PFNGLENABLEPROC, glEnable) \
	EnumMacro(PFNGLDISABLEPROC, glDisable) \
	EnumMacro(PFNGLCLEARPROC, glClear) \
	EnumMacro(PFNGLCLEARCOLORPROC, glClearColor) \
	EnumMacro(PFNGLDRAWARRAYSPROC, glDrawArrays) \
	EnumMacro(PFNGLGENBUFFERSARBPROC, glGenBuffers) \
	EnumMacro(PFNGLBINDBUFFERARBPROC, glBindBuffer) \
	EnumMacro(PFNGLBUFFERDATAARBPROC, glBufferData) \
	EnumMacro(PFNGLDELETEBUFFERSARBPROC, glDeleteBuffers) \
	EnumMacro(PFNGLMAPBUFFERARBPROC, glMapBuffer) \
	EnumMacro(PFNGLUNMAPBUFFERARBPROC, glDrawRangeElements) \
	EnumMacro(PFNGLBINDTEXTUREPROC, glBindTexture) \
	EnumMacro(PFNGLACTIVETEXTUREARBPROC, glActiveTexture) \
	EnumMacro(PFNGLTEXIMAGE2DPROC, glTexImage2D) \
	EnumMacro(PFNGLGENTEXTURESPROC, glGenTextures) \
	EnumMacro(PFNGLCREATESHADERPROC, glCreateShader) \
	EnumMacro(PFNGLSHADERSOURCEPROC, glShaderSource) \
	EnumMacro(PFNGLCOMPILESHADERPROC, glCompileShader) \
	EnumMacro(PFNGLGETSHADERINFOLOGPROC, glGetShaderInfoLog) \
	EnumMacro(PFNGLATTACHSHADERPROC, glAttachShader) \
	EnumMacro(PFNGLDETACHSHADERPROC, glDetachShader) \
	EnumMacro(PFNGLLINKPROGRAMPROC, glLinkProgram) \
	EnumMacro(PFNGLGETPROGRAMINFOLOGPROC, glGetProgramInfoLog) \
	EnumMacro(PFNGLUSEPROGRAMPROC, glUseProgram) \
	EnumMacro(PFNGLDELETESHADERPROC, glDeleteShader) \
	EnumMacro(PFNGLCREATEPROGRAMPROC,glCreateProgram) \
	EnumMacro(PFNGLDELETEPROGRAMPROC, glDeleteProgram) \
	EnumMacro(PFNGLGETSHADERIVPROC, glGetShaderiv) \
	EnumMacro(PFNGLGETPROGRAMIVPROC, glGetProgramiv) \
	EnumMacro(PFNGLGETUNIFORMLOCATIONPROC, glGetUniformLocation) \
	EnumMacro(PFNGLUNIFORM1FPROC, glUniform1f) \
	EnumMacro(PFNGLUNIFORM2FPROC, glUniform2f) \
	EnumMacro(PFNGLUNIFORM3FPROC, glUniform3f) \
	EnumMacro(PFNGLUNIFORM4FPROC, glUniform4f) \
	EnumMacro(PFNGLUNIFORM1IPROC, glUniform1i) \
	EnumMacro(PFNGLUNIFORMMATRIX4FVPROC, glUniformMatrix4fv) \
	EnumMacro(PFNGLVERTEXATTRIBPOINTERPROC, glVertexAttribPointer) \
	EnumMacro(PFNGLBINDATTRIBLOCATIONPROC, glBindAttribLocation) \
	EnumMacro(PFNGLENABLEVERTEXATTRIBARRAYPROC, glEnableVertexAttribArray) \
	EnumMacro(PFNGLDISABLEVERTEXATTRIBARRAYPROC, glDisableVertexAttribArray) \
	EnumMacro(PFNGLGETATTRIBLOCATIONPROC, glGetAttribLocation) \
	EnumMacro(PFNGLBINDVERTEXARRAYPROC, glBindVertexArray) \
	EnumMacro(PFNGLDELETEVERTEXARRAYSPROC, glDeleteVertexArrays) \
	EnumMacro(PFNGLGENVERTEXARRAYSPROC, glGenVertexArrays) \
	EnumMacro(PFNGLISVERTEXARRAYPROC, glIsVertexArray) \
	EnumMacro(PFNGLTEXPARAMETERIPROC, glTexParameteri)

#define DEFINE_GL_ENTRYPOINTS(Type,Func) Type Func = NULL;
namespace GLFuncPointers	// see explanation in OpenGLLinux.h why we need the namespace
{
	ENUM_GL_ENTRYPOINTS(DEFINE_GL_ENTRYPOINTS);
};

using namespace GLFuncPointers;

//////////////////////////////////

/**
 * Returns the current shader log for a GLSL shader
 */
static FString GetGLSLShaderLog( GLuint Shader )
{
	GLint Len;
	FString ShaderLog;

	glGetShaderiv(Shader, GL_INFO_LOG_LENGTH, &Len);

	if(Len > 0)
	{
		GLsizei ActualLen;
		GLchar *Log = new GLchar[Len];

		glGetShaderInfoLog(Shader, Len, &ActualLen, Log);

		ShaderLog = ANSI_TO_TCHAR( Log );

		delete[] Log;
	}

	return ShaderLog;
}

static FString GetGLSLProgramLog( GLuint Program )
{
	GLint Len;
	FString ProgramLog;
	glGetProgramiv( Program, GL_INFO_LOG_LENGTH, &Len );

	if( Len > 0 )
	{
		GLchar* Log = new GLchar[Len];

		GLsizei ActualLen;
		glGetProgramInfoLog( Program, Len, &ActualLen, Log );

		ProgramLog = ANSI_TO_TCHAR( Log );

		delete[] Log;
	}

	return ProgramLog;
}

//---------------------------------------------------------
static int CompileShaderFromString( const FString& Source, GLuint& ShaderID, GLenum ShaderType )
{
	// Create a new shader ID.
	ShaderID = glCreateShader( ShaderType );
	GLint CompileStatus = GL_FALSE;

	check( ShaderID );

	// Allocate a buffer big enough to store the string in ascii format
	ANSICHAR* Chars[2] = {nullptr};
	// pass the #define along to the shader
#if PLATFORM_USES_ES2
	Chars[0] = (ANSICHAR*)"#define PLATFORM_USES_ES2 1\n\n#define PLATFORM_LINUX 0\n";
#elif PLATFORM_LINUX
	Chars[0] = (ANSICHAR*)"#version 150\n\n#define PLATFORM_USES_ES2 0\n\n#define PLATFORM_LINUX 1\n";
#else
	Chars[0] = (ANSICHAR*)"#version 120\n\n#define PLATFORM_USES_ES2 0\n\n#define PLATFORM_LINUX 0\n";
#endif
	Chars[1] = new ANSICHAR[Source.Len()+1];
	FCStringAnsi::Strcpy(Chars[1], Source.Len() + 1, TCHAR_TO_ANSI(*Source));

	// give opengl the source code for the shader
	glShaderSource( ShaderID, 2, (const ANSICHAR**)Chars, NULL );
	delete[] Chars[1];

	// Compile the shader and check for success
	glCompileShader( ShaderID );

	glGetShaderiv( ShaderID, GL_COMPILE_STATUS, &CompileStatus );
	if( CompileStatus == GL_FALSE )
	{
		// The shader did not compile.  Display why it failed.
		FString Log = GetGLSLShaderLog( ShaderID );

		checkf(false, TEXT("Failed to compile shader: %s\n"), *Log );

		// Delete the shader since it failed.
		glDeleteShader( ShaderID );
		ShaderID = 0;
		return -1;
	}

	return 0;
}

//---------------------------------------------------------
static int CompileShaderFromFile( const FString& Filename, GLuint& ShaderID, GLenum ShaderType )
{
	// Load the file to a string
	FString Source;
	bool bFileFound = FFileHelper::LoadFileToString( Source, *Filename );
	check(bFileFound);

	return CompileShaderFromString(Source, ShaderID, ShaderType);
}

static int LinkShaders(GLuint& ShaderProgram, GLuint& VertexShader, GLuint& FragmentShader)
{
	// Create a new program id and attach the shaders
	ShaderProgram = glCreateProgram();
	glAttachShader( ShaderProgram, VertexShader );
	glAttachShader( ShaderProgram, FragmentShader );

	// Set up attribute locations for per vertex data
	glBindAttribLocation(ShaderProgram, 0, "InPosition");

	// Link the shaders
	glLinkProgram( ShaderProgram );

	// Check to see if linking succeeded
	GLint LinkStatus;
	glGetProgramiv( ShaderProgram, GL_LINK_STATUS, &LinkStatus );
	if( LinkStatus == GL_FALSE )
	{
		return -1;
	}

	return 0;
}

//---------------------------------------------------------
static int32 OpenFonts ( )
{
	FontSmall.Status = SplashFont::NotLoaded;
	FontNormal.Status = SplashFont::NotLoaded;
	FontLarge.Status = SplashFont::NotLoaded;

	if (FT_Init_FreeType(&FontLibrary))
	{
		UE_LOG(LogHAL, Error, TEXT("*** Unable to initialize font library."));
		return -1;
	}

	// small font face
	FString FontPath = FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Light.ttf");

	if (FT_New_Face(FontLibrary, TCHAR_TO_ANSI(*FontPath), 0, &FontSmall.Face))
	{
		UE_LOG(LogHAL, Error, TEXT("*** Unable to open small font face for splash screen."));
	}
	else
	{
		FT_Set_Pixel_Sizes(FontSmall.Face, 0, 10);
		FontSmall.Status = SplashFont::Loaded;
	}

	// normal font face
	FontPath = FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Regular.ttf");

	if (FT_New_Face(FontLibrary, TCHAR_TO_ANSI(*FontPath), 0, &FontNormal.Face))
	{
		UE_LOG(LogHAL, Error, TEXT("*** Unable to open normal font face for splash screen."));
	}
	else
	{
		FT_Set_Pixel_Sizes(FontNormal.Face, 0, 12);
		FontNormal.Status = SplashFont::Loaded;
	}

	// large font face
	FontPath = FPaths::EngineContentDir() / TEXT("Slate/Fonts/Roboto-Bold.ttf");

	if (FT_New_Face(FontLibrary, TCHAR_TO_ANSI(*FontPath), 0, &FontLarge.Face))
	{
		UE_LOG(LogHAL, Error, TEXT("*** Unable to open large font face for splash screen."));
	}
	else
	{
		FT_Set_Pixel_Sizes (FontLarge.Face, 0, 40);
		FontLarge.Status = SplashFont::Loaded;
	}

	return 0;
}

//---------------------------------------------------------
static void DrawCharacter(int32 penx, int32 peny, FT_GlyphSlot Glyph, int32 CurTypeIndex, float red, float green, float blue)
{

	// drawing boundaries
	int32 xmin = GSplashScreenTextRects[CurTypeIndex].Left;
	int32 xmax = GSplashScreenTextRects[CurTypeIndex].Right;
	int32 ymax = GSplashScreenTextRects[CurTypeIndex].Bottom;
	int32 ymin = GSplashScreenTextRects[CurTypeIndex].Top;

	// glyph dimensions
	int32 cwidth = Glyph->bitmap.width;
	int32 cheight = Glyph->bitmap.rows;
	int32 cpitch = Glyph->bitmap.pitch;

	unsigned char *pixels = Glyph->bitmap.buffer;

	// draw glyph raster to texture
	for (int y=0; y<cheight; y++)
	{
		for (int x=0; x<cwidth; x++)
		{
			// find pixel position in splash image
			int xpos = penx + x;
			int ypos = peny + y - (Glyph->metrics.horiBearingY >> 6);

			// make sure pixel is in drawing rectangle
			if (xpos < xmin || xpos >= xmax || ypos < ymin || ypos >= ymax)
				continue;

			// get index of pixel in glyph bitmap
			int32 src_idx = (y * cpitch) + x;
			int32 dst_idx = (ypos * SplashWidth + xpos) * SplashBPP;

			// write pixel
			float alpha = pixels[src_idx] / 255.0f;

			ScratchSpace[dst_idx] = ScratchSpace[dst_idx]*(1.0 - alpha) + alpha*red;
			dst_idx++;
			ScratchSpace[dst_idx] = ScratchSpace[dst_idx]*(1.0 - alpha) + alpha*green;
			dst_idx++;
			ScratchSpace[dst_idx] = ScratchSpace[dst_idx]*(1.0 - alpha) + alpha*blue;
		}
	}
}

//---------------------------------------------------------
static int RenderString (GLuint tex_idx)
{
	FT_UInt last_glyph = 0;
	FT_Vector kern;
	bool bRightJustify = false;
	float red, blue, green; // font color

	// clear the rendering scratch pad.
	FMemory::Memcpy(ScratchSpace, GSplashScreenImage->pixels, SplashWidth*SplashHeight*SplashBPP);

	// draw each type of string
	for (int CurTypeIndex=0; CurTypeIndex<SplashTextType::NumTextTypes; CurTypeIndex++)
	{
		SplashFont *Font;

		// initial pen position
		uint32 penx = GSplashScreenTextRects[ CurTypeIndex].Left;
		uint32 peny = GSplashScreenTextRects[ CurTypeIndex].Bottom;
		kern.x = 0;

		// Set font color and text position
		if (CurTypeIndex == SplashTextType::StartupProgress)
		{
			red = green = blue = 200.0f;
			Font = &FontSmall;
		}
		else if (CurTypeIndex == SplashTextType::VersionInfo1)
		{
			red = green = blue = 240.0f;
			Font = &FontNormal;
		}
		else if (CurTypeIndex == SplashTextType::GameName)
		{
			red = green = blue = 240.0f;
			Font = &FontLarge;
			penx = GSplashScreenTextRects[ CurTypeIndex].Right;
			bRightJustify = true;
		}
		else
		{
			red = green = blue = 160.0f;
			Font = &FontSmall;
		}

		// sanity check: make sure we have a font loaded.
		if (Font->Status == SplashFont::NotLoaded)
			continue;

		// adjust verticle pos to allow for descenders
		peny += Font->Face->descender >> 6;

		// convert strings to glyphs and place them in bitmap.
		FString Text = GSplashScreenText[CurTypeIndex].ToString();

		for (int i=0; i<Text.Len(); i++)
		{
			FT_ULong charcode;

			// fetch next glyph
			if (bRightJustify)
			{
				charcode = (Uint32)(Text[Text.Len() - i - 1]);
			}
			else
			{
				charcode = (Uint32)(Text[i]);
			}

			FT_UInt glyph_idx = FT_Get_Char_Index(Font->Face, charcode);
			FT_Load_Glyph(Font->Face, glyph_idx, FT_LOAD_DEFAULT);

			if (Font->Face->glyph->format != FT_GLYPH_FORMAT_BITMAP)
			{
				FT_Render_Glyph(Font->Face->glyph, FT_RENDER_MODE_NORMAL);
			}

			// pen advance and kerning
			if (bRightJustify)
			{
				if (last_glyph != 0)
				{
					FT_Get_Kerning(Font->Face, glyph_idx, last_glyph, FT_KERNING_DEFAULT, &kern);
				}

				penx -= (Font->Face->glyph->metrics.horiAdvance - kern.x) >> 6;
			}
			else
			{
				if (last_glyph != 0)
				{
					FT_Get_Kerning(Font->Face, last_glyph, glyph_idx, FT_KERNING_DEFAULT, &kern);
				}
			}

			last_glyph = glyph_idx;

			// draw character
			DrawCharacter(penx, peny, Font->Face->glyph,CurTypeIndex, red, green, blue);

			if (!bRightJustify)
			{
				penx += (Font->Face->glyph->metrics.horiAdvance - kern.x) >> 6;
			}
		}

		// store rendered text as texture
		glBindTexture(GL_TEXTURE_2D, tex_idx);

		bool bIsBGR = GSplashScreenImage->format->Rmask > GSplashScreenImage->format->Bmask;
		if (SplashBPP == 3)
		{
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
				GSplashScreenImage->w, GSplashScreenImage->h,
				0, bIsBGR ? GL_BGR : GL_RGB, GL_UNSIGNED_BYTE, ScratchSpace);
		}
		else
		{
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
				GSplashScreenImage->w, GSplashScreenImage->h,
				0, bIsBGR ? GL_BGRA : GL_RGBA, GL_UNSIGNED_BYTE, ScratchSpace);
		}
	}

	return 0;
}

/** Helper function to init resources used by the splash thread */
bool LinuxSplash_InitSplashResources()
{
	if (!FPlatformMisc::PlatformInitMultimedia()) //	will not initialize more than once
	{
		UE_LOG(LogInit, Warning, TEXT("LinuxSplash_InitSplashResources() : PlatformInitMultimedia() failed, there will be no splash."));
		return false;
	}

	// load splash .bmp image
	GSplashScreenImage = SDL_LoadBMP(TCHAR_TO_UTF8(*GSplashPath));

	if (GSplashScreenImage == nullptr)
	{
		UE_LOG(LogHAL, Warning, TEXT("LinuxSplash_InitSplashResources() : Could not load splash BMP! SDL_Error: %s"), UTF8_TO_TCHAR(SDL_GetError()));
		return false;
	}

	// create splash window
	GSplashWindow = SDL_CreateWindow(NULL,
									SDL_WINDOWPOS_CENTERED,
									SDL_WINDOWPOS_CENTERED,
									GSplashScreenImage->w,
									GSplashScreenImage->h,
									SDL_WINDOW_BORDERLESS | SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN
									);
	if (GSplashWindow == nullptr)
	{
		UE_LOG(LogHAL, Error, TEXT("LinuxSplash_InitSplashResources() : Splash screen window could not be created! SDL_Error: %s"), UTF8_TO_TCHAR(SDL_GetError()));
		return -1;
	}

	SDL_SetWindowTitle( GSplashWindow, TCHAR_TO_UTF8(*GSplashScreenAppName.ToString()) );

	GSplashIconImage = SDL_LoadBMP(TCHAR_TO_UTF8(*(FString(FPlatformProcess::BaseDir()) / GIconPath)));

	if (GSplashIconImage != nullptr)
	{
		SDL_SetWindowIcon(GSplashWindow, GSplashIconImage);
	}
	else
	{
		UE_LOG(LogHAL, Warning, TEXT("LinuxSplash_InitSplashResources() : Splash icon could not be created! SDL_Error: %s"), UTF8_TO_TCHAR(SDL_GetError()));
		return false;
	}

	return true;
}

/** Helper function to tear down resources used by the splash thread */
void LinuxSplash_TearDownSplashResources()
{
	SDL_DestroyWindow(GSplashWindow);
	GSplashWindow = nullptr;

	SDL_FreeSurface(GSplashIconImage);
	GSplashIconImage = nullptr;

	SDL_FreeSurface(GSplashScreenImage);
	GSplashScreenImage = nullptr;

	// do not deinit SDL here
}

/**
 * Thread function that actually creates the window and
 * renders its contents.
 */
static int StartSplashScreenThread(void *ptr)
{
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 2 );
	SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute( SDL_GL_SHARE_WITH_CURRENT_CONTEXT, 0 );

	SDL_GLContext Context = SDL_GL_CreateContext( GSplashWindow );

	if (Context == NULL)
	{
		UE_LOG(LogHAL, Error, TEXT("Splash screen SDL_GL_CreateContext failed: %s"), UTF8_TO_TCHAR(SDL_GetError()));
		return -1;
	}

	// Initialize all entry points required by Unreal.
	#define GET_GL_ENTRYPOINTS(Type,Func) GLFuncPointers::Func = reinterpret_cast<Type>(SDL_GL_GetProcAddress(#Func));
	ENUM_GL_ENTRYPOINTS(GET_GL_ENTRYPOINTS);

	if (SDL_GL_MakeCurrent( GSplashWindow, Context ) != 0)
	{
		UE_LOG(LogHAL, Error, TEXT("Splash screen SDL_GL_MakeCurrent failed: %s"), UTF8_TO_TCHAR(SDL_GetError()));
		return -1;
	}

	// Initialize Shaders, Programs, etc.
	GLuint VertexShader 	= 0;
	GLuint FragmentShader 	= 0;
	GLuint ShaderProgram	= 0;
	GLuint SplashTextureID 	= 0;

	// Compile Vertex and Fragment Shaders from file.
	if (CompileShaderFromFile( FString::Printf( TEXT("%sShaders/StandaloneRenderer/OpenGL/SplashVertexShader.glsl"), *FPaths::EngineDir()), VertexShader, GL_VERTEX_SHADER) < 0)
	{
		UE_LOG(LogHAL, Error, TEXT("Splash screen CompileShaderFromFile failed."));
		return -1;
	}

	if (CompileShaderFromFile(FString::Printf( TEXT("%sShaders/StandaloneRenderer/OpenGL/SplashFragmentShader.glsl"), *FPaths::EngineDir()), FragmentShader, GL_FRAGMENT_SHADER) < 0)
	{
		UE_LOG(LogHAL, Error, TEXT("Splash screen CompileShaderFromFile failed."));
		return -1;
	}

	// Create Shader Program and link it.
	if(LinkShaders(ShaderProgram, VertexShader, FragmentShader) < 0)
	{
		FString Log = GetGLSLProgramLog( ShaderProgram );
		UE_LOG(LogHAL, Error, TEXT("Failed to link GLSL program: %s"), *Log);
	}

	// Returns the reference to the Splash Texture from the Shader.
	SplashTextureID = glGetUniformLocation( ShaderProgram, "SplashTexture" );

	// Create Vertex Array Object. We need that to be conform with OpenGL 3.2+ spec.
	GLuint VertexArrayObject;
	glGenVertexArrays(1, &VertexArrayObject);
	glBindVertexArray(VertexArrayObject);

	// Create Vertex Buffer and upload data.
	GLuint VertexBuffer;
	glGenBuffers(1, &VertexBuffer);
	glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);
	float screen_vertex [] =
	{
		-1.0, -1.0f,
		-1.0f, 1.0f,
		1.0f, 1.0f,

		1.0f, 1.0f,
		1.0f, -1.0f,
		-1.0f, -1.0f
	};
	glBufferData(GL_ARRAY_BUFFER, sizeof(float)*12, (GLvoid*)screen_vertex, GL_DYNAMIC_DRAW );

	// create texture slot
	GLuint texture;
	glGenTextures(1, &texture);
	glActiveTexture(GL_TEXTURE0);
	glBindTexture(GL_TEXTURE_2D, texture);

	// set filtering
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// load splash image as texture in opengl
	bool bIsBGR = GSplashScreenImage->format->Rmask > GSplashScreenImage->format->Bmask;
	if (GSplashScreenImage->format->BytesPerPixel == 3)
	{
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
			GSplashScreenImage->w, GSplashScreenImage->h,
			0, bIsBGR ? GL_BGR : GL_RGB, GL_UNSIGNED_BYTE, GSplashScreenImage->pixels);
	}
	else if (GSplashScreenImage->format->BytesPerPixel == 4)
	{
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
			GSplashScreenImage->w, GSplashScreenImage->h,
			0, bIsBGR ? GL_BGRA : GL_RGBA, GL_UNSIGNED_BYTE, GSplashScreenImage->pixels);
	}
	else
	{
		UE_LOG(LogHAL, Warning, TEXT("Splash BMP image has unsupported format"));
		return -1;
	}

	// remember bmp stats
	SplashWidth = GSplashScreenImage->w;
	SplashHeight =  GSplashScreenImage->h;
	SplashBPP = GSplashScreenImage->format->BytesPerPixel;

	if (SplashWidth <= 0 || SplashHeight <= 0)
	{
		UE_LOG(LogHAL, Warning, TEXT("Invalid splash image dimensions."));
		return -1;
	}

	// allocate scratch space for rendering text
	ScratchSpace = reinterpret_cast<unsigned char *>(FMemory::Malloc(SplashHeight*SplashWidth*SplashBPP));

	// Setup bounds for game name
	GSplashScreenTextRects[ SplashTextType::GameName ].Top = 0;
	GSplashScreenTextRects[ SplashTextType::GameName ].Bottom = 50;
	GSplashScreenTextRects[ SplashTextType::GameName ].Left = 12;
	GSplashScreenTextRects[ SplashTextType::GameName ].Right = SplashWidth - 12;

	// Setup bounds for version info text 1
	GSplashScreenTextRects[ SplashTextType::VersionInfo1 ].Top = SplashHeight - 60;
	GSplashScreenTextRects[ SplashTextType::VersionInfo1 ].Bottom = SplashHeight - 40;
	GSplashScreenTextRects[ SplashTextType::VersionInfo1 ].Left = 10;
	GSplashScreenTextRects[ SplashTextType::VersionInfo1 ].Right = SplashWidth - 10;

	// Setup bounds for copyright info text
	if (GIsEditor)
	{
		GSplashScreenTextRects[ SplashTextType::CopyrightInfo ].Top = SplashHeight - 44;
		GSplashScreenTextRects[ SplashTextType::CopyrightInfo ].Bottom = SplashHeight - 24;
	}
	else
	{
		GSplashScreenTextRects[ SplashTextType::CopyrightInfo ].Top = SplashHeight - 16;
		GSplashScreenTextRects[ SplashTextType::CopyrightInfo ].Bottom = SplashHeight - 6;
	}

	GSplashScreenTextRects[ SplashTextType::CopyrightInfo ].Left = 10;
	GSplashScreenTextRects[ SplashTextType::CopyrightInfo ].Right = SplashWidth - 20;

	// Setup bounds for startup progress text
	GSplashScreenTextRects[ SplashTextType::StartupProgress ].Top = SplashHeight - 20;
	GSplashScreenTextRects[ SplashTextType::StartupProgress ].Bottom = SplashHeight;
	GSplashScreenTextRects[ SplashTextType::StartupProgress ].Left = 10;
	GSplashScreenTextRects[ SplashTextType::StartupProgress ].Right = SplashWidth - 20;

	OpenFonts();

	glDisable(GL_DEPTH_TEST);

	// drawing loop
	while (ThreadState >= 0)
	{
		SDL_Event event;
		// Poll events otherwise the window will get dark or
		// on some Desktops it will complain that the thread
		// does not work anymore.
		while (SDL_PollEvent(&event))
		{
			// intentionally empty
		}

		SDL_Delay(300);

		// Activate Shader Program, Texture etc.
		glBindVertexArray(VertexArrayObject);
		glBindBuffer(GL_ARRAY_BUFFER, VertexBuffer);
		glUseProgram(ShaderProgram);
		glActiveTexture(GL_TEXTURE0);
		glUniform1i(SplashTextureID, 0);

		if (ThreadState > 0)
		{
			RenderString(texture);
			ThreadState--;
		}

		// Set stream positions and draw.
		glEnableVertexAttribArray(0);
		glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
		glDrawArrays(GL_TRIANGLES, 0, 6);

		// Disable Shader Program, VAO, VBO etc.
		glDisableVertexAttribArray(0);
		glUseProgram(0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glBindVertexArray(0);

		SDL_GL_SwapWindow( GSplashWindow );
	}

	// clean up
	glDeleteBuffers(1, &VertexBuffer);
	glDeleteVertexArrays(1, &VertexArrayObject);
	glDetachShader(ShaderProgram, VertexShader);
	glDetachShader(ShaderProgram, FragmentShader);
	glDeleteShader(VertexShader);
	glDeleteShader(FragmentShader);
	glDeleteProgram(ShaderProgram);

	if (ScratchSpace)
	{
		FMemory::Free(ScratchSpace);
		ScratchSpace = NULL;
	}

	if (FontSmall.Status == SplashFont::Loaded)
	{
		FT_Done_Face(FontSmall.Face);
	}

	if (FontNormal.Status == SplashFont::Loaded)
	{
		FT_Done_Face(FontNormal.Face);
	}

	if (FontLarge.Status == SplashFont::Loaded)
	{
		FT_Done_Face(FontLarge.Face);
	}

	FT_Done_FreeType(FontLibrary);

	SDL_GL_DeleteContext(Context);
	FMemory::Free(ScratchSpace);

	// set the thread state to -1 to let the caller know we're done (FIXME: can be done without busy-loops)
	ThreadState = -1;

	return 0;
}

/**
 * Finds a usable splash pathname for the given filename
 *
 * @param SplashFilename Name of the desired splash name ("Splash.bmp")
 * @param OutPath String containing the path to the file, if this function returns true
 *
 * @return true if a splash screen was found
 */
static bool GetSplashPath(const TCHAR* SplashFilename, const TCHAR* IconFilename, bool& OutIsCustom)
{
	// first look in game's splash directory
	GSplashPath = FPaths::GameContentDir() + TEXT("Splash/") + SplashFilename;
	GIconPath = FPaths::GameContentDir() + TEXT("Splash/") + IconFilename;
	OutIsCustom = true;

	// if this was found, then we're done
	if (IFileManager::Get().FileSize(*GSplashPath) != -1)
	{
		return true;
	}

	// next look in Engine/Splash
	GSplashPath = FPaths::ConvertRelativePathToFull(FPaths::EngineContentDir() + TEXT("Splash/") + SplashFilename);
	GIconPath = FPaths::EngineContentDir() + TEXT("Splash/") + IconFilename;
	OutIsCustom = false;

	// if this was found, then we're done
	if (IFileManager::Get().FileSize(*GSplashPath) != -1)
	{
		return true;
	}

	// if not found yet, then return failure
	return false;
}
#endif //WITH_EDITOR

/**
 * Sets the text displayed on the splash screen (for startup/loading progress)
 *
 * @param	InType		Type of text to change
 * @param	InText		Text to display
 */
static void StartSetSplashText( const SplashTextType::Type InType, const FText& InText )
{
#if WITH_EDITOR
	// Update splash text
	GSplashScreenText[ InType ] = InText;
#endif
}

/**
 * Open a splash screen if there's not one already and if it's not disabled.
 *
 */
void FLinuxPlatformSplash::Show( )
{
#if WITH_EDITOR
	// need to do a splash screen?
	if(GSplashThread || FParse::Param(FCommandLine::Get(),TEXT("NOSPLASH")) == true)
	{
		return;
	}

	// decide on which splash screen to show
	const FText GameName = FText::FromString(FApp::GetGameName());

	const TCHAR* SplashImage = GIsEditor ? ( GameName.IsEmpty() ? TEXT("EdSplashDefault.bmp") : TEXT("EdSplash.bmp") ) : ( GameName.IsEmpty() ? TEXT("SplashDefault.bmp") : TEXT("Splash.bmp") );
	// TODO: add an icon
	//const TCHAR* IconImage = GIsEditor ? ( GameName.IsEmpty() ? TEXT("EdIconDefault.bmp") : TEXT("EdIcon.bmp") ) : ( GameName.IsEmpty() ? TEXT("IconDefault.bmp") : TEXT("Icon.bmp") );
	const TCHAR* IconImage = GIsEditor ? ( GameName.IsEmpty() ? TEXT("EdSplashDefault.bmp") : TEXT("EdSplash.bmp") ) : ( GameName.IsEmpty() ? TEXT("SplashDefault.bmp") : TEXT("Splash.bmp") );

	// make sure a splash was found
	bool IsCustom;

	if ( GetSplashPath(SplashImage, IconImage, IsCustom) == false )
	{
		UE_LOG(LogHAL, Warning, TEXT("Splash screen image not found."));
	}

	// Don't set the game name if the splash screen is custom.
	if ( !IsCustom )
	{
		StartSetSplashText( SplashTextType::GameName, GameName );
	}

	// In the editor, we'll display loading info
	if( GIsEditor )
	{
		// Set initial startup progress info
		{
			StartSetSplashText( SplashTextType::StartupProgress,
				NSLOCTEXT("UnrealEd", "SplashScreen_InitialStartupProgress", "Loading..." ) );
		}

		// Set version info
		{
			const FText Version = FText::FromString( GEngineVersion.ToString( FEngineBuildSettings::IsPerforceBuild() ? EVersionComponent::Branch : EVersionComponent::Patch ) );

			FText VersionInfo;
			FText AppName;
			if( GameName.IsEmpty() )
			{
				VersionInfo = FText::Format( NSLOCTEXT( "UnrealEd", "UnrealEdTitleWithVersionNoGameName_F", "Unreal Editor {0}" ), Version );
				AppName = NSLOCTEXT( "UnrealEd", "UnrealEdTitleNoGameName_F", "Unreal Editor" );
			}
			else
			{
				VersionInfo = FText::Format( NSLOCTEXT( "UnrealEd", "UnrealEdTitleWithVersion_F", "Unreal Editor {0}  -  {1}" ), Version, GameName );
				AppName = FText::Format( NSLOCTEXT( "UnrealEd", "UnrealEdTitle_F", "Unreal Editor - {0}" ), GameName );
			}

			StartSetSplashText( SplashTextType::VersionInfo1, VersionInfo );

			// Change the window text (which will be displayed in the taskbar)
			GSplashScreenAppName = AppName;
		}

		// Display copyright information in editor splash screen
		{
			const FText CopyrightInfo = NSLOCTEXT( "UnrealEd", "SplashScreen_CopyrightInfo", "Copyright \x00a9 1998-2015   Epic Games, Inc.   All rights reserved." );
			StartSetSplashText( SplashTextType::CopyrightInfo, CopyrightInfo );
		}
	}

	// init splash LinuxSplash_InitSplashResources
	if (!LinuxSplash_InitSplashResources())
	{
		return;
	}

	// Create rendering thread to display splash
	GSplashThread = SDL_CreateThread(StartSplashScreenThread, "StartSplashScreenThread", (void *)NULL);

	if (GSplashThread == nullptr)
	{
		UE_LOG(LogHAL, Error, TEXT("Splash screen SDL_CreateThread failed: %s"), UTF8_TO_TCHAR(SDL_GetError()));
	}
	else
	{
		SDL_DetachThread(GSplashThread);
		ThreadState = 1;
	}
#endif //WITH_EDITOR
}

/**
* Done with splash screen. Close it and clean up.
*/
void FLinuxPlatformSplash::Hide()
{
#if WITH_EDITOR
	// signal thread it's time to quit
	if (ThreadState >= 0)	// if there's a thread at all...
	{
		ThreadState = -99;
		// wait for the thread to be done before tearing it tearing it down (it will set the ThreadState to 0)
		while (ThreadState != -1)
		{
			// busy loop!
			FPlatformProcess::Sleep(0.01f);
		}

		// tear down resources that thread used
		LinuxSplash_TearDownSplashResources();
	}

	GSplashThread = nullptr;
#endif
}

/**
* Sets the text displayed on the splash screen (for startup/loading progress)
*
* @param	InType		Type of text to change
* @param	InText		Text to display
*/
void FLinuxPlatformSplash::SetSplashText( const SplashTextType::Type InType, const TCHAR* InText )
{
#if WITH_EDITOR
	// We only want to bother drawing startup progress in the editor, since this information is
	// not interesting to an end-user (also, it's not usually localized properly.)

	if (InType == SplashTextType::CopyrightInfo || GIsEditor)
	{
		bool bWasUpdated = false;
		{
			// Update splash text
			if (FCString::Strcmp( InText, *GSplashScreenText[ InType ].ToString() ) != 0)
			{
				GSplashScreenText[ InType ] = FText::FromString( InText );
				bWasUpdated = true;
			}
		}

		if (bWasUpdated && GSplashThread && ThreadState >= 0)
		{
			ThreadState++;
		}
	}
#endif //WITH_EDITOR
}


text:
import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import { Icon, Constants } from 'seek-asia-style-guide/react';
import styles from './ActionTray.less';
import _get from 'lodash/get';

const actionTrayLink = ({ linkUrl, activeTab, tabName, menuOpen, brandStyles, showFlag, handleToggleMenu, linkRenderer, title, iconName }) => {
  if (showFlag) {
    return activeTab === tabName ? (

        <Icon
          title={title}
          type={iconName}
          className={classnames(styles.svg, {
            [brandStyles.activeActionTrayIcon]: !menuOpen
          })}
          size="normal"
        />

    ) : (

        {
          linkRenderer({
            href: linkUrl,
            className: styles.actionTrayLink,
            children: <Icon title={title} type={iconName} svgClassName={styles.svg} size="normal" />
          })
        }

    );
  }
  return null;
};

actionTrayLink.propTypes = {
  linkUrl: PropTypes.string,
  activeTab: PropTypes.string,
  tabName: PropTypes.string,
  menuOpen: PropTypes.bool,
  showFlag: PropTypes.bool.isRequired,
  brandStyles: PropTypes.object.isRequired,
  handleToggleMenu: PropTypes.func,
  baseUrl: PropTypes.string.isRequired,
  linkRenderer: PropTypes.func,
  title: PropTypes.string,
  iconName: PropTypes.string
};

const ActionTray = ({ brandStyles, headerMessage, handleToggleMenu, activeTab, menuOpen, showTray = true, showHome = true, showSearch = true, showMenu = true, baseUrl, country, linkRenderer }) => {
  const actionTrayLinkProps = {
    brandStyles,
    activeTab,
    menuOpen,
    handleToggleMenu,
    linkRenderer
  };
  const { ACTIVE_TAB_HOME, ACTIVE_TAB_SEARCH } = Constants;
  if (showTray) {
    return (

        {actionTrayLink({ showFlag: showHome, iconName: 'home', linkUrl: baseUrl + _get(headerMessage, 'homeUrl'), tabName: ACTIVE_TAB_HOME, ...actionTrayLinkProps })}
        { country === 'hk' ?
          actionTrayLink({ showFlag: showSearch, iconName: 'search', linkUrl: baseUrl + _get(headerMessage, 'searchUrl'), title: 'Search HK Jobs', tabName: ACTIVE_TAB_SEARCH, ...actionTrayLinkProps }) :
          actionTrayLink({ showFlag: showSearch, iconName: 'search', linkUrl: baseUrl + _get(headerMessage, 'searchUrl'), tabName: ACTIVE_TAB_SEARCH, ...actionTrayLinkProps })
        }
        {showMenu && (

            <Icon type="menu" className={classnames(styles.svg, { [brandStyles.activeActionTrayIcon]: menuOpen })} size="normal" />

        )}

    );
  }
  return null;
};

ActionTray.propTypes = {
  brandStyles: PropTypes.object.isRequired,
  headerMessage: PropTypes.object.isRequired,
  handleToggleMenu: PropTypes.func.isRequired,
  activeTab: PropTypes.string,
  menuOpen: PropTypes.bool,
  showTray: PropTypes.bool,
  showHome: PropTypes.bool,
  showSearch: PropTypes.bool,
  showMenu: PropTypes.bool,
  baseUrl: PropTypes.string,
  linkRenderer: PropTypes.func,
  country: PropTypes.string
};

export default ActionTray;


text:
#if NET471 || NETCOREAPP3_1_OR_GREATER
namespace JavaScriptEngineSwitcher.Tests.NiL
{
	public class MultithreadingTests : MultithreadingTestsBase
	{
		protected override string EngineName
		{
			get { return "NiLJsEngine"; }
		}
	}
}
#endif


text:
<?php declare(strict_types=1);

namespace Common\Components\FlashMessages;

use Nette\Localization\ITranslator;
use Nette\Localization\message;
use Nette\Localization\plural;
use Nette\SmartObject;

class NullTranslator implements ITranslator
{
    use SmartObject;

    /**
     * Translates the given string.
     * @param  string   message
     * @param  int      plural count
     * @return string
     */
    function translate($message, $count = null): string
    {
        return $message;
    }

}


text:
class CreateMenus < ActiveRecord::Migration
  def up
    create_table :menus do |t|
      t.string :name
      t.string :path
      t.integer :parent_id
      t.integer :position
      t.timestamps
    end
    Menu.create_translation_table! :name => :string, :path => :string
  end

  def down
    drop_table :menus
    Menu.drop_translation_table!
  end
end


text:
require 'helper'

class Nanoc::LFTP::FilterTest < Minitest::Test

  def test_deploy
    rsync = Nanoc::LFTP::Deployer.new(
      'output',
      dst_host: 'ftp://example.com:123',
      dst_path: '/foo/path with spaces/subdir')

    def rsync.run_shell_cmd(args)
      @shell_cms_args = args
    end

    rsync.run
    assert_equal(
      [ 'lftp', '-e', 'mirror --reverse output/ /foo/path\ with\ spaces/subdir ; quit', 'ftp://example.com:123' ],
      rsync.instance_eval { @shell_cms_args }
    )
  end

end


text:
define('ace/theme/monoindustrial', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {

exports.isDark = true;
exports.cssClass = "ace-monoindustrial";
exports.cssText = "/* THIS THEME WAS AUTOGENERATED BY Theme.tmpl.css (UUID: EEA328BA-54E5-49DC-81F3-1F25BF8AF163) */\
.ace-monoindustrial .ace_gutter {\
background: #e8e8e8;\
color: #333;\
}\
.ace-monoindustrial .ace_print-margin {\
width: 1px;\
background: #e8e8e8;\
}\
.ace-monoindustrial {\
background-color: #222C28;\
color: #FFFFFF;\
}\
.ace-monoindustrial .ace_cursor {\
color: #FFFFFF;\
}\
.ace-monoindustrial .ace_marker-layer .ace_selection {\
background: rgba(145, 153, 148, 0.40);\
}\
.ace-monoindustrial.ace_multiselect .ace_selection.ace_start {\
box-shadow: 0 0 3px 0px #222C28;\
border-radius: 2px;\
}\
.ace-monoindustrial .ace_marker-layer .ace_step {\
background: rgb(198, 219, 174);\
}\
.ace-monoindustrial .ace_marker-layer .ace_bracket {\
margin: -1px 0 0 -1px;\
border: 1px solid rgba(102, 108, 104, 0.50);\
}\
.ace-monoindustrial .ace_marker-layer .ace_active-line {\
background: rgba(12, 13, 12, 0.25);\
}\
.ace-monoindustrial .ace_gutter-active-line {\
background-color: rgba(12, 13, 12, 0.25);\
}\
.ace-monoindustrial .ace_marker-layer .ace_selected-word {\
border: 1px solid rgba(145, 153, 148, 0.40);\
}\
.ace-monoindustrial .ace_fold {\
background-color: #A8B3AB;\
border-color: #FFFFFF;\
}\
.ace-monoindustrial .ace_keyword{color:#A39E64;}.ace-monoindustrial .ace_keyword.ace_operator{color:#A8B3AB;}.ace-monoindustrial .ace_constant{color:#E98800;}.ace-monoindustrial .ace_constant.ace_numeric{color:#E98800;}.ace-monoindustrial .ace_support.ace_function{color:#588E60;}.ace-monoindustrial .ace_support.ace_constant{color:#C87500;}.ace-monoindustrial .ace_support.ace_class{color:#5778B6;}.ace-monoindustrial .ace_support.ace_type{color:#5778B6;}.ace-monoindustrial .ace_storage{color:#C23B00;}.ace-monoindustrial .ace_invalid{color:#FFFFFF;\
background-color:rgba(153, 0, 0, 0.68);}.ace-monoindustrial .ace_comment{color:#666C68;\
background-color:#151C19;}.ace-monoindustrial .ace_variable{color:#A8B3AB;}.ace-monoindustrial .ace_variable.ace_language{color:#648BD2;}.ace-monoindustrial .ace_variable.ace_parameter{color:#648BD2;}.ace-monoindustrial .ace_entity.ace_other.ace_attribute-name{color:#909993;}.ace-monoindustrial .ace_entity.ace_name.ace_function{color:#A8B3AB;}.ace-monoindustrial .ace_entity.ace_name{color:#5778B6;}.ace-monoindustrial .ace_entity.ace_name.ace_tag{color:#A65EFF;}";

var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});


text:
package com.jjzcru.luft.presentation.internal.di.components;

import android.support.v7.app.AppCompatActivity;

import com.jjzcru.luft.presentation.internal.di.PerActivity;
import com.jjzcru.luft.presentation.internal.di.modules.ActivityModule;

import dagger.Component;

@PerActivity
@Component(dependencies = AppComponent.class, modules = ActivityModule.class)
interface ActivityComponent {
    AppCompatActivity activity();
}


text:
package com.linecorp.armeria.server.grpc;

import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

import java.util.Set;

import javax.annotation.Nullable;

import com.google.common.collect.ImmutableSet;
import com.google.protobuf.ByteString;

import com.linecorp.armeria.common.HttpRequest;
import com.linecorp.armeria.common.HttpResponse;
import com.linecorp.armeria.common.RequestContext;
import com.linecorp.armeria.common.SerializationFormat;
import com.linecorp.armeria.common.grpc.GrpcSerializationFormats;
import com.linecorp.armeria.internal.grpc.ArmeriaMessageFramer;
import com.linecorp.armeria.server.PathMapping;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.ServerConfig;
import com.linecorp.armeria.server.ServiceWithPathMappings;
import com.linecorp.armeria.server.encoding.HttpEncodingService;
import com.linecorp.armeria.unsafe.grpc.GrpcUnsafeBufferUtil;

import io.grpc.BindableService;
import io.grpc.CompressorRegistry;
import io.grpc.DecompressorRegistry;
import io.grpc.ServerServiceDefinition;

/**
 * Constructs a {@link GrpcService} to serve gRPC services from within Armeria.
 */
public final class GrpcServiceBuilder {

    private static final Set<SerializationFormat> DEFAULT_SUPPORTED_SERIALIZATION_FORMATS =
            ImmutableSet.of(GrpcSerializationFormats.PROTO, GrpcSerializationFormats.PROTO_WEB);

    private final HandlerRegistry.Builder registryBuilder = new HandlerRegistry.Builder();

    @Nullable
    private DecompressorRegistry decompressorRegistry;

    @Nullable
    private CompressorRegistry compressorRegistry;

    private Set<SerializationFormat> supportedSerializationFormats = DEFAULT_SUPPORTED_SERIALIZATION_FORMATS;

    private int maxInboundMessageSizeBytes = GrpcService.NO_MAX_INBOUND_MESSAGE_SIZE;

    private int maxOutboundMessageSizeBytes = ArmeriaMessageFramer.NO_MAX_OUTBOUND_MESSAGE_SIZE;

    private boolean enableUnframedRequests;

    private boolean unsafeWrapRequestBuffers;

    /**
     * Adds a gRPC {@link ServerServiceDefinition} to this {@link GrpcServiceBuilder}, such as
     * what's returned by {@link BindableService#bindService()}.
     */
    public GrpcServiceBuilder addService(ServerServiceDefinition service) {
        registryBuilder.addService(requireNonNull(service, "service"));
        return this;
    }

    /**
     * Adds a gRPC {@link BindableService} to this {@link GrpcServiceBuilder}. Most gRPC service
     * implementations are {@link BindableService}s.
     */
    public GrpcServiceBuilder addService(BindableService bindableService) {
        return addService(bindableService.bindService());
    }

    /**
     * Sets the {@link DecompressorRegistry} to use when decompressing messages. If not set, will use
     * the default, which supports gzip only.
     */
    public GrpcServiceBuilder decompressorRegistry(DecompressorRegistry registry) {
        decompressorRegistry = requireNonNull(registry, "registry");
        return this;
    }

    /**
     * Sets the {@link CompressorRegistry} to use when compressing messages. If not set, will use the
     * default, which supports gzip only.
     */
    public GrpcServiceBuilder compressorRegistry(CompressorRegistry registry) {
        compressorRegistry = requireNonNull(registry, "registry");
        return this;
    }

    /**
     * Sets the {@link SerializationFormat}s supported by this server. If not set, defaults to supporting binary
     * protobuf formats. Enabling JSON can be useful, e.g., when migrating existing JSON services to gRPC.
     */
    public GrpcServiceBuilder supportedSerializationFormats(SerializationFormat... formats) {
        return supportedSerializationFormats(ImmutableSet.copyOf(requireNonNull(formats, "formats")));
    }

    /**
     * Sets the {@link SerializationFormat}s supported by this server. If not set, defaults to supporting binary
     * protobuf formats. JSON formats are currently very inefficient and not recommended for use in production.
     *
     *
TODO(anuraaga): Use faster JSON marshalling.
     */
    public GrpcServiceBuilder supportedSerializationFormats(Iterable<SerializationFormat> formats) {
        requireNonNull(formats, "formats");
        for (SerializationFormat format : formats) {
            if (!GrpcSerializationFormats.isGrpc(format)) {
                throw new IllegalArgumentException("Not a gRPC serialization format: " + format);
            }
        }
        supportedSerializationFormats = ImmutableSet.copyOf(formats);
        return this;
    }

    /**
     * Sets the maximum size in bytes of an individual incoming message. If not set, will use
     * {@link ServerConfig#defaultMaxRequestLength}. To support long-running RPC streams, it is recommended to
     * set {@link ServerConfig#defaultMaxRequestLength} and {@link ServerConfig#defaultRequestTimeoutMillis} to
     * very high values and set this to the expected limit of individual messages in the stream.
     */
    public GrpcServiceBuilder setMaxInboundMessageSizeBytes(int maxInboundMessageSizeBytes) {
        checkArgument(maxInboundMessageSizeBytes > 0,
                      "maxInboundMessageSizeBytes must be >0");
        this.maxInboundMessageSizeBytes = maxInboundMessageSizeBytes;
        return this;
    }

    /**
     * Sets the maximum size in bytes of an individual outgoing message. If not set, all messages will be sent.
     * This can be a safety valve to prevent overflowing network connections with large messages due to business
     * logic bugs.
     */
    public GrpcServiceBuilder setMaxOutboundMessageSizeBytes(int maxOutboundMessageSizeBytes) {
        checkArgument(maxOutboundMessageSizeBytes > 0,
                      "maxOutboundMessageSizeBytes must be >0");
        this.maxOutboundMessageSizeBytes = maxOutboundMessageSizeBytes;
        return this;
    }

    /**
     * Sets whether the service handles requests not framed using the gRPC wire protocol. Such requests should
     * only have the serialized message as the request content, and the response content will only have the
     * serialized response message. Supporting unframed requests can be useful, for example, when migrating an
     * existing service to gRPC.
     *
     *
Limitations:
     *

     *
Only unary methods (single request, single response) are supported.

     *

     *         Message compression is not supported.
     *         {@link HttpEncodingService} should be used instead for
     *         transport level encoding.
     *

     *

     */
    public GrpcServiceBuilder enableUnframedRequests(boolean enableUnframedRequests) {
        this.enableUnframedRequests = enableUnframedRequests;
        return this;
    }

    /**
     * Enables unsafe retention of request buffers. Can improve performance when working with very large
     * (i.e., several megabytes) payloads.
     *
     *
DISCLAIMER: Do not use this if you don't know what you are doing. It is very easy to
     * introduce memory leaks when using this method. You will probably spend much time debugging memory leaks
     * during development if this is enabled. You will probably spend much time debugging memory leaks in
     * production if this is enabled. You probably don't want to do this and should turn back now.
     *
     *
When enabled, the reference-counted buffer received from the client will be stored into
     * {@link RequestContext} instead of being released. All {@link ByteString} in a
     * protobuf message will reference sections of this buffer instead of having their own copies. When done
     * with a request message, call {@link GrpcUnsafeBufferUtil#releaseBuffer(Object, RequestContext)}
     * with the message and the request's context to release the buffer. The message must be the same
     * reference as what was passed to the service stub - a message with the same contents will not
     * work. If {@link GrpcUnsafeBufferUtil#releaseBuffer(Object, RequestContext)} is not called, the memory
     * will be leaked.
     */
    public GrpcServiceBuilder unsafeWrapRequestBuffers(boolean unsafeWrapRequestBuffers) {
        this.unsafeWrapRequestBuffers = unsafeWrapRequestBuffers;
        return this;
    }

    /**
     * Constructs a new {@link GrpcService} that can be bound to
     * {@link ServerBuilder}. It is recommended to bind the service to a server
     * using {@link ServerBuilder#service(ServiceWithPathMappings)} to mount all
     * service paths without interfering with other services.
     */
    public ServiceWithPathMappings<HttpRequest, HttpResponse> build() {
        final HandlerRegistry handlerRegistry = registryBuilder.build();
        final GrpcService grpcService = new GrpcService(
                handlerRegistry,
                handlerRegistry
                      .methods()
                      .keySet()
                      .stream()
                      .map(path -> PathMapping.ofExact('/' + path))
                      .collect(ImmutableSet.toImmutableSet()),
                firstNonNull(decompressorRegistry, DecompressorRegistry.getDefaultInstance()),
                firstNonNull(compressorRegistry, CompressorRegistry.getDefaultInstance()),
                supportedSerializationFormats,
                maxOutboundMessageSizeBytes,
                unsafeWrapRequestBuffers,
                maxInboundMessageSizeBytes);
        return enableUnframedRequests ? grpcService.decorate(UnframedGrpcService::new) : grpcService;
    }
}


text:
/*

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 */

module.exports = angular.module('trafficPortal.dates', [])
    .controller('DatesController', require('./DatesController'))


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Lichenes Neotropici (Neumarkt), Fascicle <b>X</b> (nos 401-450) 15 (1988)

#### Original name
Tephromela tropica Kalb

### Remarks
null


text:
package org.wildfly.common.codec;

/**
 * An exception which indicates that decoding has failed due to invalid or truncated input.
 */
public class DecodeException extends IllegalArgumentException {

    private static final long serialVersionUID = 5823281980783313991L;

    /**
     * Constructs a new {@code DecodeException} instance.  The message is left blank ({@code null}), and no cause is
     * specified.
     */
    public DecodeException() {
    }

    /**
     * Constructs a new {@code DecodeException} instance with an initial message.  No cause is specified.
     *
     * @param msg the message
     */
    public DecodeException(final String msg) {
        super(msg);
    }

    /**
     * Constructs a new {@code DecodeException} instance with an initial cause.  If a non-{@code null} cause is
     * specified, its message is used to initialize the message of this {@code DecodeException}; otherwise the message
     * is left blank ({@code null}).
     *
     * @param cause the cause
     */
    public DecodeException(final Throwable cause) {
        super(cause);
    }

    /**
     * Constructs a new {@code DecodeException} instance with an initial message and cause.
     *
     * @param msg the message
     * @param cause the cause
     */
    public DecodeException(final String msg, final Throwable cause) {
        super(msg, cause);
    }
}


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>ansible.plugins.cache.memcached.CacheModule</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

ansible

        Package ansible ::
        Package plugins ::
        Package cache ::
        Module memcached ::
        Class CacheModule

[hide private]

[frames] | no frames]

Class CacheModule

source code

          object --+
                   |
base.BaseCacheModule --+
                       |
                      CacheModule

        Instance Methods
        [hide private]

          __init__(self,
        *args,
        **kwargs)

      x.__init__(...) initializes x; see help(type(x)) for signature

            source code

          _make_key(self,
        key)

            source code

          _expire_keys(self)

            source code

          get(self,
        key)

            source code

          set(self,
        key,
        value)

            source code

          keys(self)

            source code

          contains(self,
        key)

            source code

          delete(self,
        key)

            source code

          flush(self)

            source code

          copy(self)

            source code

          __getstate__(self)

            source code

          __setstate__(self,
        data)

            source code

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

        Class Variables
        [hide private]

        __abstractmethods__ = frozenset([])

Inherited from base.BaseCacheModule (private):
      _abc_cache,
      _abc_negative_cache,
      _abc_negative_cache_version,
      _abc_registry,
      _display

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(self,
        *args,
        **kwargs)

(Constructor)

  	source code

x.__init__(...) initializes x; see help(type(x)) for signature

Overrides:
        object.__init__

(inherited documentation)

get(self,
        key)

  	source code

Overrides:
        base.BaseCacheModule.get

set(self,
        key,
        value)

  	source code

Overrides:
        base.BaseCacheModule.set

keys(self)

  	source code

Overrides:
        base.BaseCacheModule.keys

contains(self,
        key)

  	source code

Overrides:
        base.BaseCacheModule.contains

delete(self,
        key)

  	source code

Overrides:
        base.BaseCacheModule.delete

flush(self)

  	source code

Overrides:
        base.BaseCacheModule.flush

copy(self)

  	source code

Overrides:
        base.BaseCacheModule.copy

         Home

         Trees

         Indices

         Help

ansible

    Generated by Epydoc 3.0.1 on Fri Jul 29 13:11:38 2016

      http://epydoc.sourceforge.net


text:
import CustomError from '../src/errors/CustomError';
import assert from 'assert';

describe('CustomError', () => {
	describe('#constructor()', () => {
		it('should return an instance of the CustomError class', () => {
			const err = new CustomError();
			assert(err instanceof CustomError);
		});
		it('should extend the base Error class', () => {
			const err = new CustomError();
			assert(err instanceof Error);
		});
		it('can be thrown', () => {
			const err = new CustomError('foobar');
			try {
				throw err;
				assert(false, 'Should never get to this point');
			}
			catch (result) {
				assert.equal(result, err, 'Error caught');
			}
		});
		it('should accept an error message', () => {
			try {
				throw new CustomError('foobar');
			}
			catch (err) {
				assert.equal(err.message, 'foobar', 'Messages match');
			}
		});
	});
});


text:
require "spec_helper"

describe Rdm::Handlers::DiffPackageHandler do
  include ExampleProjectHelper
  include GitCommandsHelper

  subject { described_class }

  context "::handle" do
    before { initialize_example_project }
    after  { reset_example_project }

    context "when git changes present" do
      context "for package without dependencies" do
        before do
          git_initialize_repository(example_project_path)
          git_commit_changes(example_project_path)

          File.open(File.join(example_project_path, 'server/package/new_server.rb'), 'w') { |f| f.write '' }

          git_index_changes(example_project_path)
        end

        it "returns only modified packages" do
          expect(subject.handle(path: example_project_path, revision: 'HEAD')).to match(["server"])
        end
      end

      context "for package with dependencies" do
        before do
          git_initialize_repository(example_project_path)
          git_commit_changes(example_project_path)

          File.open(File.join(example_project_path, 'domain/core/package/core/new_service.rb'), 'w') do |f|
            f.write <<~EOF
              class Core::NewService
              end
            EOF
          end
        end

        it "returns array of modified and dependend packages for indexed changes" do
          git_index_changes(example_project_path)

          expect(subject.handle(path: example_project_path, revision: 'HEAD')).to match(["core", "server", "web"].sort)
        end
      end

      context "for file without package" do
        before do
          git_initialize_repository(example_project_path)
          git_commit_changes(example_project_path)

          File.open(File.join(example_project_path, 'domain/missing_package_class.rb'), 'w') do |f|
            f.write <<~EOF
              class MissingPackageClass
              end
            EOF
          end
        end

        it "returns empty array" do
          git_index_changes(example_project_path)

          expect(subject.handle(path: example_project_path, revision: 'HEAD')).to eq([])
        end
      end
    end

    context "when git repository is not initialized" do
      it "raises Rdm::Errors::GitRepositoryNotInitialized error" do
        expect{
          subject.handle(path: example_project_path, revision: 'HEAD')
        }.to raise_error(Rdm::Errors::GitRepositoryNotInitialized)
      end
    end
  end
end


text:
.PHONY: docs clean build

VERSION := 0.2.11
PYTHON ?= python
BUILD_ARGS ?=
SPHINX ?= sphinx-build
DOCS_OUTPUT=docs/
PYTHON_BUILD_DIR:=$(shell $(PYTHON) -c "import distutils.util; import sys; print(distutils.util.get_platform() + '-' + sys.version[0:3])")
BUILD_DIR:=lib.$(PYTHON_BUILD_DIR)
BUILD_STAMP:=$(BUILD_DIR)/build
SRCFILES := src/*.c src/*.h src/*.py
EXAMPLES := examples/*.py
TESTS := tests/*.py

what:
	@echo "make targets:"
	@echo
	@echo " tarball    : build source tarball"
	@echo " docs       : generate documentation (requires sphinx)"
	@echo " clean      : remove build files"
	@echo
	@echo "To build pyaudio, run:"
	@echo
	@echo "   python setup.py install"

clean:
	@rm -rf build dist MANIFEST $(DOCS_OUTPUT) src/*.pyc

######################################################################
# Documentation
######################################################################

build: build/$(BUILD_STAMP)

build/$(BUILD_STAMP): $(SRCFILES)
	$(PYTHON) setup.py build $(BUILD_ARGS)
	touch $@

docs: build
	PYTHONPATH=build/$(BUILD_DIR) $(SPHINX) -b html sphinx/ $(DOCS_OUTPUT)

######################################################################
# Source Tarball
######################################################################
tarball: $(SRCFILES) $(EXAMPLES) $(TESTS) MANIFEST.in
	@$(PYTHON) setup.py sdist