text:
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings         #-}
{-# LANGUAGE Rank2Types                #-}
{-# LANGUAGE TemplateHaskell           #-}
{-# LANGUAGE LambdaCase #-}

module StorePackage where

import qualified Codec.Archive.Tar                             as Tar

import           Control.Applicative
import           Control.Monad
import           Control.Monad.IO.Class
import           Control.Monad.Trans.Resource
import Control.Exception.Lifted

import           Data.Aeson                                    ((.:), (.=))
import qualified Data.Aeson                                    as JSON
import qualified Data.ByteString.Char8                         as S
import qualified Data.ByteString.Lazy.Char8                    as L
import           Data.Conduit
import qualified Data.Conduit.List                             as CL
import qualified Data.Conduit.Zlib                             as ZLib
import           Data.Function                                 (fix, on)
import qualified Data.HashMap.Strict                           as H
import           Data.List
import           Data.Maybe
import qualified Data.Text                                     as T
import qualified Data.Text.Encoding                            as T
import qualified Data.Vector                                   as V

import qualified Distribution.Package                          as D
import qualified Distribution.PackageDescription               as D
import qualified Distribution.PackageDescription.Configuration as D
import qualified Distribution.PackageDescription.Parse         as D
import qualified Distribution.Text                             as D

import           Network.HTTP.Client.TLS
import           Network.HTTP.Conduit

import           System.Environment

import Numeric
import Data.Time
import System.Locale
import System.IO

untar :: MonadThrow m => Conduit S.ByteString m Tar.Entry
untar = do
    s <- CL.consume
    loop $ Tar.read (L.fromChunks s)
  where
    loop (Tar.Next e es) = yield e >> loop es
    loop  Tar.Done       = return ()
    loop (Tar.Fail e)    = throwM e

isCabalFile :: Tar.Entry -> Bool
isCabalFile e = ".cabal" `isSuffixOf` Tar.entryPath e

normalFileContent :: Tar.EntryContent -> Maybe L.ByteString
normalFileContent (Tar.NormalFile c _) = Just c
normalFileContent _ = Nothing

resultMaybe :: D.ParseResult a -> Maybe a
resultMaybe (D.ParseOk _ a) = Just a
resultMaybe _ = Nothing

entryToPackageDescription :: (MonadBaseControl IO m, MonadIO m) => Request -> Manager
                          -> Conduit Tar.Entry m (D.PackageDescription, UTCTime)
entryToPackageDescription req mgr =
    CL.filter isCabalFile =$
    CL.mapMaybe (normalFileContent . Tar.entryContent) =$
    CL.mapMaybe (resultMaybe . D.parsePackageDescription . L.unpack) =$
    CL.map D.flattenPackageDescription =$
    CL.groupBy ((==) `on` (D.pkgName . D.package)) =$
    CL.map (maximumBy (compare `on` (D.pkgVersion . D.package))) =$
    CL.mapM (\pd -> (pd,) <$> getLastUploaded (D.display . D.pkgName $ D.package pd) req mgr)

pdToValue :: D.PackageDescription -> UTCTime -> Maybe [T.Text] -> JSON.Value
pdToValue p upl dpr = JSON.object
    [ "name"          .= name
    , "version"       .= (D.display . D.pkgVersion . D.package) p
    , "license"       .= (D.display . D.license) p
    , "copyright"     .= D.copyright p
    , "maintainer"    .= D.maintainer p
    , "author"        .= D.author p
    , "stability"     .= D.stability p
    , "homepage"      .= D.homepage p
    , "bugReports"    .= D.bugReports p
    , "synopsis"      .= D.synopsis p
    , "description"   .= (unescapeHtml . D.description) p
    , "category"      .= (splitCategory . D.category) p
    , "hasLibrary"    .= (isJust . D.library) p
    , "hasExecutable" .= (not . null . D.executables) p
    , "executables"   .= (map D.exeName . D.executables) p
    , "deprecated"    .= isJust dpr
    , "inFavourOf"    .= maybe [] id dpr
    , "lastUploaded"  .= upl
    , "ngram"         .= JSON.object
        [ "description" JSON..= (unescapeHtml . D.description) p
        , "synopsis"    JSON..= (unescapeHtml . D.synopsis) p
        , "name"        JSON..= name
        ]
    , "raw"           .= JSON.object
        [ "name"     .= name
        , "license"  .= (D.display . D.license) p
        , "category" .= (splitCategory . D.category) p
        ]
    ]
  where
    splitCategory = map T.strip . T.splitOn "," . T.pack
    name = (D.display . D.pkgName    . D.package) p

unescapeHtml :: String -> String
unescapeHtml = loop
  where
    loop []       = []
    loop ('&':cs) = unescape cs
    loop (c:cs)   = c : loop cs

    entities = H.fromList [("lt", '<'), ("gt", '>'), ("amp", '&'), ("quot", '"')]

    unescape cs = case break (== ';') cs of
        (_, [])      -> []
        ('#':x:hex, _:cs') | x `elem` ['x', 'X'] -> case readHex hex of
            [(n, [])] -> toEnum n : loop cs'
            _         -> loop cs'
        ('#':dec, _:cs') -> case reads dec of
            [(n, [])] -> toEnum n : loop cs'
            _         -> loop cs'
        (ent, _:cs') -> case H.lookup ent entities of
            Just c  -> c : loop cs'
            Nothing -> loop cs'

parseUrl' :: MonadThrow m => String -> m Request
parseUrl' s | '@' `notElem` s = parseUrl s
parseUrl' s0 = do
    let (proto, s1) = T.breakOnEnd "://" (T.pack s0)
        (user,  s2) = T.breakOnEnd ":" s1
        (pass,  s3) = T.breakOnEnd "@" s2
    req <- parseUrl . concat $ map T.unpack [proto, s3]
    return $ applyBasicAuth (T.encodeUtf8 $ T.init user) (T.encodeUtf8 $ T.init pass) req

defaultTime :: UTCTime
defaultTime = UTCTime (ModifiedJulianDay 0) 0

getLastUploaded :: (MonadIO m, MonadBaseControl IO m) => String -> Request -> Manager -> m UTCTime
getLastUploaded pkg req mgr = fmap (maybe defaultTime id . either (\(_ :: SomeException) -> Nothing) id) . try $
    parseTime defaultTimeLocale "%a %b %e %X %Z %Y" . L.unpack . responseBody <$>
    httpLbs req { path = S.pack $ "/package/" ++ pkg ++ "/upload-time" } mgr

sinkStoreElasticsearch :: (MonadThrow m, MonadIO m)
                       => Int -> Bool -> H.HashMap T.Text [T.Text] -> Request -> Manager
                       -> Consumer (D.PackageDescription, UTCTime) m ()
sinkStoreElasticsearch cs progress dpr req' mgr = do
    let req = req' { method = "POST" }
    fix $ \loop -> do
        chunk <- CL.take cs
        let cmd i = JSON.object ["index" .= JSON.object ["_id" .= (i :: String)]]
            body = L.unlines . map JSON.encode $ concatMap (\(p,upd) ->
                let pkg = D.display . D.pkgName $ D.package p in
                [ cmd pkg
                , pdToValue p upd (H.lookup (T.pack pkg) dpr)
                ]) chunk
        unless (null chunk) $ do
            _ <- liftIO $ httpLbs req { requestBody = RequestBodyLBS body } mgr
            when progress . liftIO $ putChar '.' >> hFlush stdout
            loop

newtype Deprecateds = Deprecateds { unDeprecateds :: H.HashMap T.Text [T.Text] }
instance JSON.FromJSON Deprecateds where
    parseJSON (JSON.Array a) = Deprecateds . H.fromList <$> mapM parseElem (mapMaybe fromObject (V.toList a))
      where
        fromObject (JSON.Object o) = Just o
        fromObject _ = Nothing
        parseElem o = (,) <$> o .: "deprecated-package" <*> o .: "in-favour-of"
    parseJSON _ = mzero

getDeprecateds :: (MonadThrow m, MonadIO m) => Manager -> m (H.HashMap T.Text [T.Text])
getDeprecateds mgr = do
    req <- parseUrl "http://hackage.haskell.org/packages/deprecated"
    res <- httpLbs req { requestHeaders = ("Accept", "application/json") : requestHeaders req } mgr
    maybe (fail "getDeprecateds: decode json failed.") return $
        unDeprecateds <$> (JSON.decode $ responseBody res)

storeElasticsearch :: (MonadBaseControl IO m, MonadThrow m, MonadIO m, MonadResource m)
                   => String -> String -> Manager -> m ()
storeElasticsearch url indexName mgr = do
    dpr   <- getDeprecateds mgr
    index <- parseUrl "http://hackage.haskell.org/packages/index.tar.gz"
    src   <- http index mgr
    req   <- parseUrl' url
    responseBody src $$+-
        ZLib.ungzip =$ untar =$ entryToPackageDescription index mgr =$
        sinkStoreElasticsearch 500 True dpr req { path = S.pack $ '/' : indexName ++ "/package/_bulk" } mgr

main :: IO ()
main = withManagerSettings tlsManagerSettings $ \mgr -> liftIO getArgs >>= \case
    [index, url] -> storeElasticsearch url index mgr
    _            -> liftIO $ putStrLn "USAGE: main INDEX ELASTICSEARCH_URL"


text:
NAMESPACE_MICROSOFT_XBOX_SERVICES_SOCIAL_MANAGER_BEGIN

/// <summary>
/// Represents a xbox social user containing social information
///</summary>
public ref class XboxSocialUser sealed
{
public:
    /// <summary>
    /// The Xbox user id
    /// </summary>
    DEFINE_PROP_GET_STR_OBJ_FROM_WCHAR_PTR(XboxUserId, xbox_user_id);

    /// <summary>
    /// Whether they are a favorite
    /// </summary>
    DEFINE_PROP_GET_OBJ(IsFavorite, is_favorite, bool);

    /// <summary>
    /// Whether the calling user is following them
    /// </summary>
    DEFINE_PROP_GET_OBJ(IsFollowingUser, is_following_user, bool);

    /// <summary>
    /// Whether they calling user is followed by this person
    /// </summary>
    DEFINE_PROP_GET_OBJ(IsFollowedByCaller, is_followed_by_caller, bool);

    /// <summary>
    /// The display name
    /// </summary>
    DEFINE_PROP_GET_STR_OBJ_FROM_WCHAR_PTR(DisplayName, display_name);

    /// <summary>
    /// The real name
    /// </summary>
    DEFINE_PROP_GET_STR_OBJ_FROM_WCHAR_PTR(RealName, real_name);

    /// <summary>
    /// The display picture uri
    /// </summary>
    DEFINE_PROP_GET_STR_OBJ_FROM_WCHAR_PTR(DisplayPicUrlRaw, display_pic_url_raw);

    /// <summary>
    /// Whether to use the players avatar
    /// </summary>
    DEFINE_PROP_GET_OBJ(UseAvatar, use_avatar, bool);

    /// <summary>
    /// The player's gamertag
    /// </summary>
    DEFINE_PROP_GET_STR_OBJ_FROM_WCHAR_PTR(Gamertag, gamertag);

    /// <summary>
    /// The player's gamerscore
    /// </summary>
    DEFINE_PROP_GET_STR_OBJ_FROM_WCHAR_PTR(Gamerscore, gamerscore);

    /// <summary>
    /// The user's presence record
    /// </summary>
    property Microsoft::Xbox::Services::Social::Manager::SocialManagerPresenceRecord^ PresenceRecord { Microsoft::Xbox::Services::Social::Manager::SocialManagerPresenceRecord^ get(); }

    /// <summary>
    /// Title history for the user
    /// </summary>
    property Microsoft::Xbox::Services::Social::Manager::TitleHistory^ TitleHistory { Microsoft::Xbox::Services::Social::Manager::TitleHistory^ get(); }

    /// <summary>
    /// Preferred color for the user
    /// </summary>
    property Microsoft::Xbox::Services::Social::Manager::PreferredColor^ PreferredColor { Microsoft::Xbox::Services::Social::Manager::PreferredColor^ get(); }

internal:
    XboxSocialUser(
        _In_ xbox::services::social::manager::xbox_social_user* cppObj
        );

private:
    Microsoft::Xbox::Services::Social::Manager::SocialManagerPresenceRecord^ m_presenceRecord;
    Microsoft::Xbox::Services::Social::Manager::PreferredColor^ m_preferredColor;
    Microsoft::Xbox::Services::Social::Manager::TitleHistory^ m_titleHistory;
    xbox::services::social::manager::xbox_social_user m_cppObj;
};

NAMESPACE_MICROSOFT_XBOX_SERVICES_SOCIAL_MANAGER_END

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Search — ReFlow 0.1 documentation</title>

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

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

    <link rel="top" title="ReFlow 0.1 documentation" href="index.html"/>

             ReFlow

                0.1

  <form id="rtd-search-form" class="wy-form" action="#" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

Introduction

Site Navigation

User Accounts & Permissions

Tutorials

Server Setup

Worker Setup

        ReFlow

Docs »

      Please activate JavaScript to enable the search
      functionality.

        © Copyright 2013, Scott White.

  Built with Sphinx using a theme provided by Read the Docs.


text:
    <title>HTTP 500 Internal Server Error</title>

The page cannot be displayed

    There was a problem with the page you are trying to reach
    and it cannot be displayed.

Please try the following:

Open the maxtimkovich.com home page, and then look for links to the information you want.

Click the  Refresh button, or try again later.

Click  Search to look for information on the Internet.

You can also see a list of related sites.

HTTP 500 - Internal server error

    Internet Explorer


text:
[![Project Status: Active - The project has reached a stable, usable state and is being actively developed.](http://www.repostatus.org/badges/latest/active.svg)](http://www.repostatus.org/#active)
[![Build Status](https://travis-ci.org/hjwylde/werewolf-slack.svg?branch=master)](https://travis-ci.org/hjwylde/werewolf-slack)
[![Release](https://img.shields.io/github/release/hjwylde/werewolf-slack.svg)](https://github.com/hjwylde/werewolf-slack/releases/latest)

A chat interface for playing [werewolf](https://github.com/hjwylde/werewolf) in
    [Slack](https://slack.com/).
Werewolf is a well known social party game, commonly also called Mafia.
See the [Wikipedia article](https://en.wikipedia.org/wiki/Mafia_(party_game)) for a rundown on its
    gameplay and history.

![Werewolf for Slack](https://raw.githubusercontent.com/hjwylde/werewolf-slack/master/.readme/werewolf-for-slack.png)

### Game description

Long has the woods been home to wild creatures, both kind and cruel.
Most have faces and are known to the inhabitants of Fougères in Brittany, France; but no-one from
    the village has yet to lay eyes on the merciless Werewolf.

Each night Werewolves attack the village and devour the innocent.
For centuries no-one knew how to fight this scourge, however recently a theory has taken ahold that
    mayhaps the Werewolves walk among the Villagers themselves...

Objective of the game:
For the Loners: complete their own objective.
For the Villagers: lynch all of the Werewolves.
For the Werewolves: devour all of the Villagers.

### Setup

#### Preparing Slack

Set up an Incoming Webhook [here](https://my.slack.com/services/new/incoming-webhook/).
Make note of the *webhook url*, we'll be using that soon.

Set up a Slash Command (`/werewolf` or similar)
    [here](https://my.slack.com/services/new/slash-commands/).
The Slash Command should perform a GET request to the server werewolf-slack is going to be hosted
    on.
Make note of the *token* here too.

#### Installing

Installing werewolf-slack is easiest done using either
    [Docker](https://www.docker.com/) (recommended),
    [stack](https://github.com/commercialhaskell/stack) or
    [Cabal](https://github.com/haskell/cabal).

**Using Docker:**

```bash
docker pull hjwylde/werewolf-slack-docker
```

**Using stack:**

```bash
stack install werewolf-slack werewolf
export PATH=$PATH:~/.local/bin
```

**Using Cabal:**

```bash
cabal-install werewolf-slack werewolf
export PATH=$PATH:~/.cabal/bin
```

#### Running

werewolf-slack is a simple web server that listens for events from the Slack Slash Command.
After receiving an event werewolf-slack forwards it on to the werewolf game engine and uses the
    Incoming Webhook to send back the response.

Running werewolf-slack is easiest done using either
    [Docker](https://www.docker.com/) (recommended) or
    the binary itself.
Make sure to add rules to your firewall for werewolf-slack's port.

**With Docker:**

```bash
docker run -d -p 80:80 hjwylde/werewolf-slack-docker -v TOKEN -u WEBHOOK_URL
```

**With werewolf-slack:**

```bash
werewolf-slack -v TOKEN -u WEBHOOK_URL &
```

#### Configuration

It is possible to also configure the port that werewolf-slack listens on. This is done via the
    `--port` (`-p`) option.

The default port is *80*.

### Usage

Type `/werewolf help` in your Slack channel to get going!


text:
using Rabbit.Components.Security.Permissions;
using Rabbit.Kernel.Extensions.Models;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Rabbit.Components.Security.Web
{
    /// <summary>
    /// 标准权限。
    /// </summary>
    public sealed class StandardPermissions : IPermissionProvider
    {
        #region Field

        /// <summary>
        /// 管理面板权限。
        /// </summary>
        public static readonly Permission AccessAdminPanel = new Permission { Name = "AccessAdminPanel", Description = "管理面板访问" };

        /// <summary>
        /// 前端访问权限。
        /// </summary>
        public static readonly Permission AccessFrontEnd = new Permission { Name = "AccessFrontEnd", Description = "前端访问" };

        /// <summary>
        /// 所有者。
        /// </summary>
        public static readonly Permission Owner = new Permission { Name = "Owner", Description = "租户所有者权限" };

        #endregion Field

        #region Implementation of IPermissionProvider

        /// <summary>
        /// 功能。
        /// </summary>
        public Feature Feature
        {
            get
            {
                return new Feature
                {
                    Descriptor = new FeatureDescriptor
                    {
                        Id = "Rabbit.Web",
                        Category = "Core",
                        Dependencies = Enumerable.Empty<string>(),
                        Description = string.Empty,
                        Extension = new ExtensionDescriptorEntry(new ExtensionDescriptor(), "Rabbit.Web", null, null)
                    },
                    ExportedTypes = Enumerable.Empty<Type>()
                };
            }
        }

        /// <summary>
        /// 获取许可集合。
        /// </summary>
        /// <returns>许可集合。</returns>
        public IEnumerable<Permission> GetPermissions()
        {
            return new[] {
                AccessAdminPanel,
                AccessFrontEnd,
                Owner
            };
        }

        /// <summary>
        /// 获取默认的立体许可集合。
        /// </summary>
        /// <returns>立体许可集合。</returns>
        public IEnumerable<PermissionStereotype> GetDefaultStereotypes()
        {
            return new[]
            {
                //管理员
                new PermissionStereotype {
                    Name = "Administrator",
                    Permissions = new[] {Owner, AccessAdminPanel}
                },
                //匿名用户
                new PermissionStereotype {
                    Name = "Anonymous",
                    Permissions = new[] {AccessFrontEnd}
                },
                //授权后的用户
                new PermissionStereotype
                {
                    Name = "Authenticated",
                    Permissions = new[] {AccessFrontEnd}
                }
            };
        }

        #endregion Implementation of IPermissionProvider
    }
}


text:
import { Component } from '@angular/core';

import { SkyKeyInfoLayoutType } from '../key-info-layout-type';

@Component({
  selector: 'sky-test-cmp',
  templateUrl: './key-info.component.fixture.html',
})
export class KeyInfoTestComponent {
  public layout: SkyKeyInfoLayoutType | undefined = 'vertical';
}


text:
package com.betfair.cougar.marshalling.impl.to;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class BarDelegateImpl implements BarDelegate {

	private double value;
	private Baz baz = new Baz(new BazDelegateImpl(15));

	public BarDelegateImpl(double i) {
		this.value = i;
	}

	@Override
	public Double getBarDouble() {
		return value;
	}

	@Override
	public void setBarDouble(Double marketBaseRate) {
		throw new IllegalArgumentException();

	}

	@Override
	public List<Baz> getBazList() {
		return Collections.singletonList(baz);
	}

	@Override
	public Set<Baz> getBazSet() {
		return Collections.singleton(baz);
	}

	@Override
	public void setBazList(List<Baz> bazs) {
		throw new IllegalArgumentException();

	}

	@Override
	public void setBazSet(Set<Baz> bazSet) {
		throw new IllegalArgumentException();

	}

	@Override
	public Baz[] getBazArray() {
		Baz[] baz = new Baz[4];
		baz[0] = this.baz;
		for (int i=1;i<baz.length;i++) {
			baz[i] = new Baz(new BazDelegateImpl(i));
		}
		return baz;
	}

	@Override
	public void setBazArray(Baz[] bazArray) {
		throw new IllegalArgumentException();
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:orientation="vertical"
              android:layout_margin="@dimen/element_padding_small"
              android:padding="@dimen/element_padding"
              android:background="@drawable/ic_dialog_bg"
        >

    <TextView
            android:id="@+id/title"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/default_text_string"
            android:textAppearance="?android:textAppearance"
            android:textStyle="bold"
            android:textAllCaps="true"
            android:textColor="@color/text_black"

            android:gravity="center"
            android:padding="@dimen/element_padding"
            />

    <TextView
            android:id="@+id/n0"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:padding="@dimen/element_padding"

            android:textColor="@color/text_black"
            android:text="@string/file_name_text"
            />

    <EditText
            android:id="@+id/name_edit"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"

            android:singleLine="true"
            android:textAppearance="?android:textAppearanceMedium"
            android:textColor="@color/text_black"

            android:background="@drawable/ic_edit_background"
            android:padding="@dimen/element_padding"
            android:inputType="text"
            />

    <TextView
            android:id="@+id/download"
            android:clickable="true"
            android:layout_width="fill_parent"
            android:text="@string/default_text_string"
            android:layout_height="wrap_content"

            android:gravity="center"
            android:textColor="@color/text_black"
            android:textStyle="bold"
            android:textAppearance="?android:textAppearance"
            android:textAllCaps="true"
            android:background="@drawable/all_image_button_press"
            android:layout_margin="@dimen/element_padding"
            android:padding="@dimen/element_padding_large"
            />
</LinearLayout>


text:
SHELL = /bin/sh

# V=0 quiet, V=1 verbose.  other values don't work.
V = 0
Q1 = $(V:1=)
Q = $(Q1:0=@)
ECHO1 = $(V:1=@ :)
ECHO = $(ECHO1:0=@ echo)
NULLCMD = :

#### Start of system configuration section. ####

srcdir = .
topdir = /Users/ftt.shujuan.cheong/.rvm/rubies/ruby-2.6.6/include/ruby-2.6.0
hdrdir = $(topdir)
arch_hdrdir = /Users/ftt.shujuan.cheong/.rvm/rubies/ruby-2.6.6/include/ruby-2.6.0/x86_64-darwin19
PATH_SEPARATOR = :
VPATH = $(srcdir):$(arch_hdrdir)/ruby:$(hdrdir)/ruby
prefix = $(DESTDIR)/Users/ftt.shujuan.cheong/.rvm/rubies/ruby-2.6.6
rubysitearchprefix = $(rubylibprefix)/$(sitearch)
rubyarchprefix = $(rubylibprefix)/$(arch)
rubylibprefix = $(libdir)/$(RUBY_BASE_NAME)
exec_prefix = $(prefix)
vendorarchhdrdir = $(vendorhdrdir)/$(sitearch)
sitearchhdrdir = $(sitehdrdir)/$(sitearch)
rubyarchhdrdir = $(rubyhdrdir)/$(arch)
vendorhdrdir = $(rubyhdrdir)/vendor_ruby
sitehdrdir = $(rubyhdrdir)/site_ruby
rubyhdrdir = $(includedir)/$(RUBY_VERSION_NAME)
vendorarchdir = $(vendorlibdir)/$(sitearch)
vendorlibdir = $(vendordir)/$(ruby_version)
vendordir = $(rubylibprefix)/vendor_ruby
sitearchdir = $(DESTDIR)./.gem.20210331-40779-yzkqrc
sitelibdir = $(DESTDIR)./.gem.20210331-40779-yzkqrc
sitedir = $(rubylibprefix)/site_ruby
rubyarchdir = $(rubylibdir)/$(arch)
rubylibdir = $(rubylibprefix)/$(ruby_version)
sitearchincludedir = $(includedir)/$(sitearch)
archincludedir = $(includedir)/$(arch)
sitearchlibdir = $(libdir)/$(sitearch)
archlibdir = $(libdir)/$(arch)
ridir = $(datarootdir)/$(RI_BASE_NAME)
mandir = $(datarootdir)/man
localedir = $(datarootdir)/locale
libdir = $(exec_prefix)/lib
psdir = $(docdir)
pdfdir = $(docdir)
dvidir = $(docdir)
htmldir = $(docdir)
infodir = $(datarootdir)/info
docdir = $(datarootdir)/doc/$(PACKAGE)
oldincludedir = $(SDKROOT)/usr/include
includedir = $(prefix)/include
runstatedir = $(localstatedir)/run
localstatedir = $(prefix)/var
sharedstatedir = $(prefix)/com
sysconfdir = $(prefix)/etc
datadir = $(datarootdir)
datarootdir = $(prefix)/share
libexecdir = $(exec_prefix)/libexec
sbindir = $(exec_prefix)/sbin
bindir = $(exec_prefix)/bin
archdir = $(rubyarchdir)

CC_WRAPPER =
CC = gcc
CXX = g++
LIBRUBY = $(LIBRUBY_SO)
LIBRUBY_A = lib$(RUBY_SO_NAME)-static.a
LIBRUBYARG_SHARED = -l$(RUBY_SO_NAME)
LIBRUBYARG_STATIC = -l$(RUBY_SO_NAME)-static -framework Security -framework Foundation $(MAINLIBS)
empty =
OUTFLAG = -o $(empty)
COUTFLAG = -o $(empty)
CSRCFLAG = $(empty)

RUBY_EXTCONF_H =
cflags   = $(optflags) $(debugflags) $(warnflags)
cxxflags = $(optflags) $(debugflags) $(warnflags)
optflags = -O3
debugflags = -ggdb3
warnflags = -Wall -Wextra -Wdeclaration-after-statement -Wdeprecated-declarations -Wdivision-by-zero -Wimplicit-function-declaration -Wimplicit-int -Wmisleading-indentation -Wpointer-arith -Wshorten-64-to-32 -Wwrite-strings -Wmissing-noreturn -Wno-constant-logical-operand -Wno-long-long -Wno-missing-field-initializers -Wno-overlength-strings -Wno-parentheses-equality -Wno-self-assign -Wno-tautological-compare -Wno-unused-parameter -Wno-unused-value -Wunused-variable -Wextra-tokens
cppflags =
CCDLFLAGS = -fno-common
CFLAGS   = $(CCDLFLAGS) $(cflags)  -fno-common -pipe $(ARCH_FLAG)
INCFLAGS = -I. -I$(arch_hdrdir) -I$(hdrdir)/ruby/backward -I$(hdrdir) -I$(srcdir)
DEFS     =
CPPFLAGS = -DHAVE_OPENSSL_SSL_H -DHAVE_OPENSSL_ERR_H -DWITH_SSL -DBUILD_FOR_RUBY -DHAVE_RB_THREAD_CALL_WITHOUT_GVL -DHAVE_RB_THREAD_FD_SELECT -DHAVE_TYPE_RB_FDSET_T -DHAVE_RB_WAIT_FOR_SINGLE_FD -DHAVE_RB_TIME_NEW -DHAVE_WRITEV -DOS_UNIX -DHAVE_SYS_EVENT_H -DHAVE_SYS_QUEUE_H -DHAVE_KQUEUE -DOS_DARWIN -DHAVE_CLOCK_GETTIME -DHAVE_CONST_CLOCK_MONOTONIC_RAW -DHAVE_CONST_CLOCK_MONOTONIC -DHAVE_MAKE_PAIR -I/usr/local/opt/libyaml/include -I/usr/local/opt/libksba/include -I/usr/local/opt/readline/include -I/usr/local/opt/zlib/include -I/usr/local/opt/openssl@1.1/include
CXXFLAGS = $(CCDLFLAGS) $(cxxflags) $(ARCH_FLAG)
ldflags  = -L. -fstack-protector-strong -L/usr/local/lib -L/usr/local/opt/libyaml/lib -L/usr/local/opt/libksba/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/zlib/lib -L/usr/local/opt/openssl@1.1/lib
dldflags = -Wl,-undefined,dynamic_lookup -Wl,-multiply_defined,suppress -L/usr/local/opt/libyaml/lib -L/usr/local/opt/libksba/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/zlib/lib -L/usr/local/opt/openssl@1.1/lib
ARCH_FLAG =
DLDFLAGS = $(ldflags) $(dldflags) $(ARCH_FLAG)
LDSHARED = $(CXX) -dynamic -bundle
LDSHAREDXX = $(CXX) -dynamic -bundle
AR = libtool -static
EXEEXT =

RUBY_INSTALL_NAME = $(RUBY_BASE_NAME)
RUBY_SO_NAME = ruby.2.6
RUBYW_INSTALL_NAME =
RUBY_VERSION_NAME = $(RUBY_BASE_NAME)-$(ruby_version)
RUBYW_BASE_NAME = rubyw
RUBY_BASE_NAME = ruby

arch = x86_64-darwin19
sitearch = $(arch)
ruby_version = 2.6.0
ruby = $(bindir)/$(RUBY_BASE_NAME)
RUBY = $(ruby)
ruby_headers = $(hdrdir)/ruby.h $(hdrdir)/ruby/backward.h $(hdrdir)/ruby/ruby.h $(hdrdir)/ruby/defines.h $(hdrdir)/ruby/missing.h $(hdrdir)/ruby/intern.h $(hdrdir)/ruby/st.h $(hdrdir)/ruby/subst.h $(arch_hdrdir)/ruby/config.h

RM = rm -f
RM_RF = $(RUBY) -run -e rm -- -rf
RMDIRS = rmdir -p
MAKEDIRS = /usr/local/opt/coreutils/bin/gmkdir -p
INSTALL = /usr/local/opt/coreutils/bin/ginstall -c
INSTALL_PROG = $(INSTALL) -m 0755
INSTALL_DATA = $(INSTALL) -m 644
COPY = cp
TOUCH = exit >

#### End of system configuration section. ####

preload =
libpath = . $(libdir) /usr/local/opt/libyaml/lib /usr/local/opt/libksba/lib /usr/local/opt/readline/lib /usr/local/opt/zlib/lib /usr/local/opt/openssl@1.1/lib
LIBPATH =  -L. -L$(libdir) -L/usr/local/opt/libyaml/lib -L/usr/local/opt/libksba/lib -L/usr/local/opt/readline/lib -L/usr/local/opt/zlib/lib -L/usr/local/opt/openssl@1.1/lib
DEFFILE =

CLEANFILES = mkmf.log
DISTCLEANFILES =
DISTCLEANDIRS =

extout =
extout_prefix =
target_prefix =
LOCAL_LIBS =
LIBS = $(LIBRUBYARG_SHARED)  -lcrypto -lssl
ORIG_SRCS = binder.cpp cmain.cpp ed.cpp em.cpp kb.cpp page.cpp pipe.cpp rubymain.cpp ssl.cpp
SRCS = $(ORIG_SRCS)
OBJS = binder.o cmain.o ed.o em.o kb.o page.o pipe.o rubymain.o ssl.o
HDRS = $(srcdir)/page.h $(srcdir)/binder.h $(srcdir)/ssl.h $(srcdir)/em.h $(srcdir)/project.h $(srcdir)/eventmachine.h $(srcdir)/ed.h
LOCAL_HDRS =
TARGET = rubyeventmachine
TARGET_NAME = rubyeventmachine
TARGET_ENTRY = Init_$(TARGET_NAME)
DLLIB = $(TARGET).bundle
EXTSTATIC =
STATIC_LIB =

TIMESTAMP_DIR = .
BINDIR        = $(bindir)
RUBYCOMMONDIR = $(sitedir)$(target_prefix)
RUBYLIBDIR    = $(sitelibdir)$(target_prefix)
RUBYARCHDIR   = $(sitearchdir)$(target_prefix)
HDRDIR        = $(rubyhdrdir)/ruby$(target_prefix)
ARCHHDRDIR    = $(rubyhdrdir)/$(arch)/ruby$(target_prefix)
TARGET_SO_DIR =
TARGET_SO     = $(TARGET_SO_DIR)$(DLLIB)
CLEANLIBS     = $(TARGET_SO)
CLEANOBJS     = *.o  *.bak

all:    $(DLLIB)
static: $(STATIC_LIB)
.PHONY: all install static install-so install-rb
.PHONY: clean clean-so clean-static clean-rb

clean-static::
clean-rb-default::
clean-rb::
clean-so::
clean: clean-so clean-static clean-rb-default clean-rb
		-$(Q)$(RM) $(CLEANLIBS) $(CLEANOBJS) $(CLEANFILES) .*.time

distclean-rb-default::
distclean-rb::
distclean-so::
distclean-static::
distclean: clean distclean-so distclean-static distclean-rb-default distclean-rb
		-$(Q)$(RM) Makefile $(RUBY_EXTCONF_H) conftest.* mkmf.log
		-$(Q)$(RM) core ruby$(EXEEXT) *~ $(DISTCLEANFILES)
		-$(Q)$(RMDIRS) $(DISTCLEANDIRS) 2> /dev/null || true

realclean: distclean
install: install-so install-rb

install-so: $(DLLIB) $(TIMESTAMP_DIR)/.sitearchdir.time
	$(INSTALL_PROG) $(DLLIB) $(RUBYARCHDIR)
clean-static::
	-$(Q)$(RM) $(STATIC_LIB)
install-rb: pre-install-rb do-install-rb install-rb-default
install-rb-default: pre-install-rb-default do-install-rb-default
pre-install-rb: Makefile
pre-install-rb-default: Makefile
do-install-rb:
do-install-rb-default:
pre-install-rb-default:
	@$(NULLCMD)
$(TIMESTAMP_DIR)/.sitearchdir.time:
	$(Q) $(MAKEDIRS) $(@D) $(RUBYARCHDIR)
	$(Q) $(TOUCH) $@

site-install: site-install-so site-install-rb
site-install-so: install-so
site-install-rb: install-rb

.SUFFIXES: .c .m .cc .mm .cxx .cpp .o .S

.cc.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<

.cc.S:
	$(ECHO) translating $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<

.mm.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<

.mm.S:
	$(ECHO) translating $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<

.cxx.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<

.cxx.S:
	$(ECHO) translating $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<

.cpp.o:
	$(ECHO) compiling $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<

.cpp.S:
	$(ECHO) translating $(<)
	$(Q) $(CXX) $(INCFLAGS) $(CPPFLAGS) $(CXXFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<

.c.o:
	$(ECHO) compiling $(<)
	$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<

.c.S:
	$(ECHO) translating $(<)
	$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<

.m.o:
	$(ECHO) compiling $(<)
	$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -c $(CSRCFLAG)$<

.m.S:
	$(ECHO) translating $(<)
	$(Q) $(CC) $(INCFLAGS) $(CPPFLAGS) $(CFLAGS) $(COUTFLAG)$@ -S $(CSRCFLAG)$<

$(TARGET_SO): $(OBJS) Makefile
	$(ECHO) linking shared-object $(DLLIB)
	-$(Q)$(RM) $(@)
	$(Q) $(LDSHAREDXX) -o $@ $(OBJS) $(LIBPATH) $(DLDFLAGS) $(LOCAL_LIBS) $(LIBS)
	$(Q) $(POSTLINK)

$(OBJS): $(HDRS) $(ruby_headers)


text:
// Copyright 2011-2014 Johann Duscher (a.k.a. Jonny Dee). All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
//    1. Redistributions of source code must retain the above copyright notice, this list of
//       conditions and the following disclaimer.
//
//    2. Redistributions in binary form must reproduce the above copyright notice, this list
//       of conditions and the following disclaimer in the documentation and/or other materials
//       provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY JOHANN DUSCHER ''AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those of the
// authors and should not be interpreted as representing official policies, either expressed
// or implied, of Johann Duscher.

#ifndef NZMQT_IMPL_HPP
#define NZMQT_IMPL_HPP

#include "nzmqt/nzmqt.hpp"

#include <QDebug>
#include <QMutexLocker>
#include <QSocketNotifier>
#include <QTimer>

#if defined(NZMQT_LIB)
// #pragma message("nzmqt is built as library")
 #define NZMQT_INLINE
#else
// #pragma message("nzmqt is built inline")
 #define NZMQT_INLINE inline
#endif

namespace nzmqt
{

/*
 * ZMQMessage
 */

NZMQT_INLINE ZMQMessage::ZMQMessage()
    : super()
{
}

NZMQT_INLINE ZMQMessage::ZMQMessage(size_t size_)
    : super(size_)
{
}

NZMQT_INLINE ZMQMessage::ZMQMessage(void* data_, size_t size_, free_fn *ffn_, void* hint_)
    : super(data_, size_, ffn_, hint_)
{
}

NZMQT_INLINE ZMQMessage::ZMQMessage(const QByteArray& b)
    : super(b.size())
{
    memcpy(data(), b.constData(), b.size());
}

NZMQT_INLINE void ZMQMessage::move(ZMQMessage* msg_)
{
    super::move(static_cast<zmq::message_t*>(msg_));
}

NZMQT_INLINE void ZMQMessage::copy(ZMQMessage* msg_)
{
    super::copy(msg_);
}

NZMQT_INLINE void ZMQMessage::clone(ZMQMessage* msg_)
{
    rebuild(msg_->size());
    memcpy(data(), msg_->data(), size());
}

NZMQT_INLINE QByteArray ZMQMessage::toByteArray()
{
    return QByteArray((const char *)data(), size());
}

/*
 * ZMQSocket
 */

NZMQT_INLINE ZMQSocket::ZMQSocket(ZMQContext* context_, Type type_)
    : qsuper(0)
    , zmqsuper(*context_, type_)
    , m_context(context_)
{
}

NZMQT_INLINE ZMQSocket::~ZMQSocket()
{
//    qDebug() << Q_FUNC_INFO << "Context:" << m_context;
    close();
}

NZMQT_INLINE void ZMQSocket::close()
{
//    qDebug() << Q_FUNC_INFO << "Context:" << m_context;
    if (m_context)
    {
        m_context->unregisterSocket(this);
        m_context = 0;
    }
    zmqsuper::close();
}

NZMQT_INLINE void ZMQSocket::setOption(Option optName_, const void *optionVal_, size_t optionValLen_)
{
    setsockopt(optName_, optionVal_, optionValLen_);
}

NZMQT_INLINE void ZMQSocket::setOption(Option optName_, const char* str_)
{
    setOption(optName_, str_, strlen(str_));
}

NZMQT_INLINE void ZMQSocket::setOption(Option optName_, const QByteArray& bytes_)
{
    setOption(optName_, bytes_.constData(), bytes_.size());
}

NZMQT_INLINE void ZMQSocket::setOption(Option optName_, qint32 value_)
{
    setOption(optName_, &value_, sizeof(value_));
}

NZMQT_INLINE void ZMQSocket::setOption(Option optName_, quint32 value_)
{
    setOption(optName_, &value_, sizeof(value_));
}

NZMQT_INLINE void ZMQSocket::setOption(Option optName_, qint64 value_)
{
    setOption(optName_, &value_, sizeof(value_));
}

NZMQT_INLINE void ZMQSocket::setOption(Option optName_, quint64 value_)
{
    setOption(optName_, &value_, sizeof(value_));
}

NZMQT_INLINE void ZMQSocket::getOption(Option option_, void *optval_, size_t *optvallen_) const
{
    const_cast<ZMQSocket*>(this)->getsockopt(option_, optval_, optvallen_);
}

NZMQT_INLINE void ZMQSocket::bindTo(const QString& addr_)
{
    bind(addr_.toLocal8Bit());
}

NZMQT_INLINE void ZMQSocket::bindTo(const char *addr_)
{
    bind(addr_);
}

NZMQT_INLINE void ZMQSocket::connectTo(const QString& addr_)
{
    zmqsuper::connect(addr_.toLocal8Bit());
}

NZMQT_INLINE void ZMQSocket::connectTo(const char* addr_)
{
    zmqsuper::connect(addr_);
}

NZMQT_INLINE bool ZMQSocket::sendMessage(ZMQMessage& msg_, SendFlags flags_)
{
    return send(msg_, flags_);
}

NZMQT_INLINE bool ZMQSocket::sendMessage(const QByteArray& bytes_, SendFlags flags_)
{
    ZMQMessage msg(bytes_);
    return send(msg, flags_);
}

NZMQT_INLINE bool ZMQSocket::sendMessage(const QList<QByteArray>& msg_, SendFlags flags_)
{
    int i;
    for (i = 0; i < msg_.size() - 1; i++)
    {
        if (!sendMessage(msg_[i], flags_ | SND_MORE))
            return false;
    }
    if (i < msg_.size())
        return sendMessage(msg_[i], flags_);

    return true;
}

NZMQT_INLINE bool ZMQSocket::receiveMessage(ZMQMessage* msg_, ReceiveFlags flags_)
{
    return recv(msg_, flags_);
}

NZMQT_INLINE QList<QByteArray> ZMQSocket::receiveMessage()
{
    QList<QByteArray> parts;

    ZMQMessage msg;
    while (receiveMessage(&msg))
    {
        parts += msg.toByteArray();
        msg.rebuild();

        if (!hasMoreMessageParts())
            break;
    }

    return parts;
}

NZMQT_INLINE QList< QList<QByteArray> > ZMQSocket::receiveMessages()
{
    QList< QList<QByteArray> > ret;

    QList<QByteArray> parts = receiveMessage();
    while (!parts.isEmpty())
    {
        ret += parts;

        parts = receiveMessage();
    }

    return ret;
}

NZMQT_INLINE qint32 ZMQSocket::fileDescriptor() const
{
    qint32 value;
    size_t size = sizeof(value);
    getOption(OPT_FD, &value, &size);
    return value;
}

NZMQT_INLINE ZMQSocket::Events ZMQSocket::events() const
{
    qint32 value;
    size_t size = sizeof(value);
    getOption(OPT_EVENTS, &value, &size);
    return static_cast<Events>(value);
}

// Returns true if there are more parts of a multi-part message
// to be received.
NZMQT_INLINE bool ZMQSocket::hasMoreMessageParts() const
{
    qint32 value;
    size_t size = sizeof(value);
    getOption(OPT_RCVMORE, &value, &size);
    return value;
}

NZMQT_INLINE void ZMQSocket::setIdentity(const char* nameStr_)
{
    setOption(OPT_IDENTITY, nameStr_);
}

NZMQT_INLINE void ZMQSocket::setIdentity(const QString& name_)
{
    setOption(OPT_IDENTITY, name_.toLocal8Bit());
}

NZMQT_INLINE void ZMQSocket::setIdentity(const QByteArray& name_)
{
    setOption(OPT_IDENTITY, const_cast<char*>(name_.constData()), name_.size());
}

NZMQT_INLINE QByteArray ZMQSocket::identity() const
{
    char idbuf[256];
    size_t size = sizeof(idbuf);
    getOption(OPT_IDENTITY, idbuf, &size);
    return QByteArray(idbuf, size);
}

NZMQT_INLINE void ZMQSocket::setLinger(int msec_)
{
    setOption(OPT_LINGER, msec_);
}

NZMQT_INLINE qint32 ZMQSocket::linger() const
{
    qint32 msec=-1;
    size_t size = sizeof(msec);
    getOption(OPT_LINGER, &msec, &size);
    return msec;
}

NZMQT_INLINE void ZMQSocket::subscribeTo(const char* filterStr_)
{
    setOption(OPT_SUBSCRIBE, filterStr_);
}

NZMQT_INLINE void ZMQSocket::subscribeTo(const QString& filter_)
{
    setOption(OPT_SUBSCRIBE, filter_.toLocal8Bit());
}

NZMQT_INLINE void ZMQSocket::subscribeTo(const QByteArray& filter_)
{
    setOption(OPT_SUBSCRIBE, filter_);
}

NZMQT_INLINE void ZMQSocket::unsubscribeFrom(const char* filterStr_)
{
    setOption(OPT_UNSUBSCRIBE, filterStr_);
}

NZMQT_INLINE void ZMQSocket::unsubscribeFrom(const QString& filter_)
{
    setOption(OPT_UNSUBSCRIBE, filter_.toLocal8Bit());
}

NZMQT_INLINE void ZMQSocket::unsubscribeFrom(const QByteArray& filter_)
{
    setOption(OPT_UNSUBSCRIBE, filter_);
}

/*
 * ZMQContext
 */

NZMQT_INLINE ZMQContext::ZMQContext(QObject* parent_, int io_threads_)
    : qsuper(parent_)
    , zmqsuper(io_threads_)
{
}

NZMQT_INLINE ZMQContext::~ZMQContext()
{
//    qDebug() << Q_FUNC_INFO << "Sockets:" << m_sockets;
    foreach (ZMQSocket* socket, m_sockets)
    {
        socket->m_context = 0;
        // As stated by 0MQ, close() must ONLY be called from the thread
        // owning the socket. So we use 'invokeMethod' which (hopefully)
        // results in a 'close' call from within the socket's thread.
        QMetaObject::invokeMethod(socket, "close");
    }
}

NZMQT_INLINE ZMQSocket* ZMQContext::createSocket(ZMQSocket::Type type_, QObject* parent_)
{
    ZMQSocket* socket = createSocketInternal(type_);
    registerSocket(socket);
    socket->setParent(parent_);
    return socket;
}

NZMQT_INLINE void ZMQContext::registerSocket(ZMQSocket* socket_)
{
    m_sockets.push_back(socket_);
}

NZMQT_INLINE void ZMQContext::unregisterSocket(ZMQSocket* socket_)
{
    Sockets::iterator soIt = m_sockets.begin();
    while (soIt != m_sockets.end())
    {
        if (*soIt == socket_)
        {
            m_sockets.erase(soIt);
            break;
        }
        ++soIt;
    }
}

NZMQT_INLINE const ZMQContext::Sockets& ZMQContext::registeredSockets() const
{
    return m_sockets;
}

/*
 * ZMQDevice
 */
/*
NZMQT_INLINE ZMQDevice::ZMQDevice(Type type, ZMQSocket* frontend, ZMQSocket* backend)
    : type_(type)
    , frontend_(frontend)
    , backend_(backend)
{
}

NZMQT_INLINE void ZMQDevice::run()
{
    zmq::device(type_, *frontend_, *backend_);
}
*/

/*
 * PollingZMQSocket
 */

NZMQT_INLINE PollingZMQSocket::PollingZMQSocket(PollingZMQContext* context_, Type type_)
    : super(context_, type_)
{
}

NZMQT_INLINE void PollingZMQSocket::onMessageReceived(const QList<QByteArray>& message)
{
    emit messageReceived(message);
}

/*
 * PollingZMQContext
 */

NZMQT_INLINE PollingZMQContext::PollingZMQContext(QObject* parent_, int io_threads_)
    : super(parent_, io_threads_)
    , m_pollItemsMutex(QMutex::Recursive)
    , m_interval(NZMQT_POLLINGZMQCONTEXT_DEFAULT_POLLINTERVAL)
    , m_stopped(false)
{
    setAutoDelete(false);
}

NZMQT_INLINE void PollingZMQContext::setInterval(int interval_)
{
    m_interval = interval_;
}

NZMQT_INLINE int PollingZMQContext::getInterval() const
{
    return m_interval;
}

NZMQT_INLINE void PollingZMQContext::start()
{
    m_stopped = false;
    QTimer::singleShot(0, this, SLOT(run()));
}

NZMQT_INLINE void PollingZMQContext::stop()
{
    m_stopped = true;
}

NZMQT_INLINE bool PollingZMQContext::isStopped() const
{
    return m_stopped;
}

NZMQT_INLINE void PollingZMQContext::run()
{
    if (m_stopped)
        return;

    try
    {
        poll();
    }
    catch (const ZMQException& ex)
    {
        qWarning("Exception during poll: %s", ex.what());
        emit pollError(ex.num(), ex.what());
    }

    if (!m_stopped)
        QTimer::singleShot(m_interval, this, SLOT(run()));
}

NZMQT_INLINE void PollingZMQContext::poll(long timeout_)
{
    int cnt;
    do {
        QMutexLocker lock(&m_pollItemsMutex);

        if (m_pollItems.empty())
            return;

        cnt = zmq::poll(&m_pollItems[0], m_pollItems.size(), timeout_);
        Q_ASSERT_X(cnt >= 0, Q_FUNC_INFO, "A value < 0 should be reflected by an exception.");
        if (0 == cnt)
            return;

        PollItems::iterator poIt = m_pollItems.begin();
        ZMQContext::Sockets::const_iterator soIt = registeredSockets().begin();
        int i = 0;
        while (i < cnt && poIt != m_pollItems.end())
        {
            if (poIt->revents & ZMQSocket::EVT_POLLIN)
            {
                PollingZMQSocket* socket = static_cast<PollingZMQSocket*>(*soIt);
                QList<QByteArray> message = socket->receiveMessage();
                socket->onMessageReceived(message);
                i++;
            }
            ++soIt;
            ++poIt;
        }
    } while (cnt > 0);
}

NZMQT_INLINE PollingZMQSocket* PollingZMQContext::createSocketInternal(ZMQSocket::Type type_)
{
    return new PollingZMQSocket(this, type_);
}

NZMQT_INLINE void PollingZMQContext::registerSocket(ZMQSocket* socket_)
{
    pollitem_t pollItem = { *socket_, 0, ZMQSocket::EVT_POLLIN, 0 };

    QMutexLocker lock(&m_pollItemsMutex);

    m_pollItems.push_back(pollItem);

    super::registerSocket(socket_);
}

NZMQT_INLINE void PollingZMQContext::unregisterSocket(ZMQSocket* socket_)
{
    QMutexLocker lock(&m_pollItemsMutex);

    PollItems::iterator poIt = m_pollItems.begin();
    ZMQContext::Sockets::const_iterator soIt = registeredSockets().begin();
    while (soIt != registeredSockets().end())
    {
        if (*soIt == socket_)
        {
            m_pollItems.erase(poIt);
            break;
        }
        ++soIt;
        ++poIt;
    }

    super::unregisterSocket(socket_);
}

/*
 * SocketNotifierZMQSocket
 */

NZMQT_INLINE SocketNotifierZMQSocket::SocketNotifierZMQSocket(ZMQContext* context_, Type type_)
    : super(context_, type_)
    , socketNotifyRead_(0)
//    , socketNotifyWrite_(0)
{
    int fd = fileDescriptor();

    socketNotifyRead_ = new QSocketNotifier(fd, QSocketNotifier::Read, this);
    QObject::connect(socketNotifyRead_, SIGNAL(activated(int)), this, SLOT(socketReadActivity()));

//    socketNotifyWrite_ = new QSocketNotifier(fd, QSocketNotifier::Write, this);
//    socketNotifyWrite_->setEnabled(false);
//    QObject::connect(socketNotifyWrite_, SIGNAL(activated(int)), this, SLOT(socketWriteActivity()));
}

//NZMQT_INLINE bool SocketNotifierZMQSocket::sendMessage(const QByteArray& bytes_, SendFlags flags_)
//{
//    bool result = super::sendMessage(bytes_, flags_);
//
//    if (!result)
//        socketNotifyWrite_->setEnabled(true);
//
//    return result;
//}

NZMQT_INLINE void SocketNotifierZMQSocket::socketReadActivity()
{
    socketNotifyRead_->setEnabled(false);

    while(events() & EVT_POLLIN)
    {
        QList<QByteArray> message = receiveMessage();
        emit messageReceived(message);
    }

    socketNotifyRead_->setEnabled(true);
}

//NZMQT_INLINE void SocketNotifierZMQSocket::socketWriteActivity()
//{
//    if(events() == 0)
//    {
//        socketNotifyWrite_->setEnabled(false);
//    }
//}

/*
 * SocketNotifierZMQContext
 */

NZMQT_INLINE SocketNotifierZMQContext::SocketNotifierZMQContext(QObject* parent_, int io_threads_)
    : super(parent_, io_threads_)
{
}

NZMQT_INLINE void SocketNotifierZMQContext::start()
{
}

NZMQT_INLINE void SocketNotifierZMQContext::stop()
{
}

NZMQT_INLINE bool SocketNotifierZMQContext::isStopped() const
{
    return false;
}

NZMQT_INLINE SocketNotifierZMQSocket* SocketNotifierZMQContext::createSocketInternal(ZMQSocket::Type type_)
{
    return new SocketNotifierZMQSocket(this, type_);
}

}

#endif // NZMQT_IMPL_HPP


text:
namespace dp
{
extern std::string const kDefaultSymbolsTexture;

class HWTextureAllocator;

class TextureManager
{
public:
  class BaseRegion
  {
  public:
    BaseRegion();
    void SetResourceInfo(ref_ptr<Texture::ResourceInfo> info);
    void SetTexture(ref_ptr<Texture> texture);
    ref_ptr<Texture> GetTexture() const { return m_texture; }
    bool IsValid() const;

    m2::PointF GetPixelSize() const;
    float GetPixelHeight() const;
    m2::RectF const & GetTexRect() const;

  protected:
    ref_ptr<Texture::ResourceInfo> m_info;
    ref_ptr<Texture> m_texture;
  };

  class SymbolRegion : public BaseRegion {};

  class GlyphRegion : public BaseRegion
  {
  public:
    GlyphRegion();

    float GetOffsetX() const;
    float GetOffsetY() const;
    float GetAdvanceX() const;
    float GetAdvanceY() const;
  };

  class StippleRegion : public BaseRegion
  {
  public:
    StippleRegion() : BaseRegion() {}

    uint32_t GetMaskPixelLength() const;
    uint32_t GetPatternPixelLength() const;
  };

  class ColorRegion : public BaseRegion
  {
  public:
    ColorRegion() : BaseRegion() {}
  };

  struct Params
  {
    std::string m_resPostfix;
    double m_visualScale = 1.0;
    std::string m_colors;
    std::string m_patterns;
    GlyphManager::Params m_glyphMngParams;
  };

  explicit TextureManager(ref_ptr<GlyphGenerator> glyphGenerator);
  void Release();

  void Init(Params const & params);
  void OnSwitchMapStyle();

  void GetSymbolRegion(std::string const & symbolName, SymbolRegion & region);
  bool HasSymbolRegion(std::string const & symbolName) const;

  typedef buffer_vector<uint8_t, 8> TStipplePattern;
  void GetStippleRegion(TStipplePattern const & pen, StippleRegion & region);
  void GetColorRegion(Color const & color, ColorRegion & region);

  using TMultilineText = buffer_vector<strings::UniString, 4>;
  using TGlyphsBuffer = buffer_vector<GlyphRegion, 128>;
  using TMultilineGlyphsBuffer = buffer_vector<TGlyphsBuffer, 4>;

  void GetGlyphRegions(TMultilineText const & text, int fixedHeight, TMultilineGlyphsBuffer & buffers);
  void GetGlyphRegions(strings::UniString const & text, int fixedHeight, TGlyphsBuffer & regions);
  // This method must be called only on Frontend renderer's thread.
  bool AreGlyphsReady(strings::UniString const & str, int fixedHeight) const;

  // On some devices OpenGL driver can't resolve situation when we upload to a texture on a thread
  // and use this texture to render on another thread. By this we move UpdateDynamicTextures call
  // into render thread. If you implement some kind of dynamic texture, you must synchronize UploadData
  // and index creation operations.
  bool UpdateDynamicTextures();

  ref_ptr<Texture> GetSymbolsTexture() const;
  ref_ptr<Texture> GetTrafficArrowTexture() const;
  ref_ptr<Texture> GetHatchingTexture() const;
  ref_ptr<Texture> GetSMAAAreaTexture() const;
  ref_ptr<Texture> GetSMAASearchTexture() const;

private:
  struct GlyphGroup
  {
    GlyphGroup()
      : m_startChar(0), m_endChar(0), m_texture(nullptr)
    {}

    GlyphGroup(strings::UniChar const & start, strings::UniChar const & end)
      : m_startChar(start), m_endChar(end), m_texture(nullptr)
    {}

    strings::UniChar m_startChar;
    strings::UniChar m_endChar;
    ref_ptr<Texture> m_texture;
  };

  struct HybridGlyphGroup
  {
    HybridGlyphGroup()
      : m_texture(nullptr)
    {}

    std::set<std::pair<strings::UniChar, int>> m_glyphs;
    ref_ptr<Texture> m_texture;
  };

  uint32_t m_maxTextureSize;
  uint32_t m_maxGlypsCount;

  ref_ptr<Texture> AllocateGlyphTexture();
  void GetRegionBase(ref_ptr<Texture> tex, TextureManager::BaseRegion & region, Texture::Key const & key);

  void GetGlyphsRegions(ref_ptr<FontTexture> tex, strings::UniString const & text,
                        int fixedHeight, TGlyphsBuffer & regions);

  size_t FindGlyphsGroup(strings::UniChar const & c) const;
  size_t FindGlyphsGroup(strings::UniString const & text) const;
  size_t FindGlyphsGroup(TMultilineText const & text) const;

  size_t FindHybridGlyphsGroup(strings::UniString const & text, int fixedHeight);
  size_t FindHybridGlyphsGroup(TMultilineText const & text, int fixedHeight);

  uint32_t GetNumberOfUnfoundCharacters(strings::UniString const & text, int fixedHeight,
                                        HybridGlyphGroup const & group) const;

  void MarkCharactersUsage(strings::UniString const & text, int fixedHeight, HybridGlyphGroup & group);
  // It's a dummy method to support generic code.
  void MarkCharactersUsage(strings::UniString const & text, int fixedHeight, GlyphGroup & group) {}

  template<typename TGlyphGroup>
  void FillResultBuffer(strings::UniString const & text, int fixedHeight, TGlyphGroup & group,
                        TGlyphsBuffer & regions)
  {
    if (group.m_texture == nullptr)
      group.m_texture = AllocateGlyphTexture();

    GetGlyphsRegions(group.m_texture, text, fixedHeight, regions);
  }

  template<typename TGlyphGroup>
  void FillResults(strings::UniString const & text, int fixedHeight, TGlyphsBuffer & buffers,
                   TGlyphGroup & group)
  {
    MarkCharactersUsage(text, fixedHeight, group);
    FillResultBuffer<TGlyphGroup>(text, fixedHeight, group, buffers);
  }

  template<typename TGlyphGroup>
  void FillResults(TMultilineText const & text, int fixedHeight, TMultilineGlyphsBuffer & buffers,
                   TGlyphGroup & group)
  {
     buffers.resize(text.size());
     for (size_t i = 0; i < text.size(); ++i)
     {
       strings::UniString const & str = text[i];
       TGlyphsBuffer & buffer = buffers[i];
       FillResults<TGlyphGroup>(str, fixedHeight, buffer, group);
     }
  }

  template<typename TText, typename TBuffer>
  void CalcGlyphRegions(TText const & text, int fixedHeight, TBuffer & buffers)
  {
    size_t const groupIndex = FindGlyphsGroup(text);
    bool useHybridGroup = false;
    if (fixedHeight < 0 && groupIndex != GetInvalidGlyphGroup())
    {
      GlyphGroup & group = m_glyphGroups[groupIndex];
      uint32_t const absentGlyphs = GetAbsentGlyphsCount(group.m_texture, text, fixedHeight);
      if (group.m_texture == nullptr || group.m_texture->HasEnoughSpace(absentGlyphs))
        FillResults<GlyphGroup>(text, fixedHeight, buffers, group);
      else
        useHybridGroup = true;
    }
    else
    {
      useHybridGroup = true;
    }

    if (useHybridGroup)
    {
      size_t const hybridGroupIndex = FindHybridGlyphsGroup(text, fixedHeight);
      ASSERT(hybridGroupIndex != GetInvalidGlyphGroup(), ());
      HybridGlyphGroup & group = m_hybridGlyphGroups[hybridGroupIndex];
      FillResults<HybridGlyphGroup>(text, fixedHeight, buffers, group);
    }
  }

  uint32_t GetAbsentGlyphsCount(ref_ptr<Texture> texture, strings::UniString const & text,
                                int fixedHeight) const;
  uint32_t GetAbsentGlyphsCount(ref_ptr<Texture> texture, TMultilineText const & text,
                                int fixedHeight) const;

  void UpdateGlyphTextures();
  bool HasAsyncRoutines() const;

  static constexpr size_t GetInvalidGlyphGroup();

private:
  ref_ptr<GlyphGenerator> m_glyphGenerator;
  std::string m_resPostfix;
  std::vector<drape_ptr<Texture>> m_symbolTextures;
  drape_ptr<Texture> m_stipplePenTexture;
  drape_ptr<Texture> m_colorTexture;
  std::list<drape_ptr<Texture>> m_glyphTextures;
  mutable std::mutex m_glyphTexturesMutex;

  drape_ptr<Texture> m_trafficArrowTexture;
  drape_ptr<Texture> m_hatchingTexture;
  drape_ptr<Texture> m_smaaAreaTexture;
  drape_ptr<Texture> m_smaaSearchTexture;

  drape_ptr<GlyphManager> m_glyphManager;
  drape_ptr<HWTextureAllocator> m_textureAllocator;

  buffer_vector<GlyphGroup, 64> m_glyphGroups;
  buffer_vector<HybridGlyphGroup, 4> m_hybridGlyphGroups;

  my::Timer m_uploadTimer;
  std::atomic_flag m_nothingToUpload;
  std::mutex m_calcGlyphsMutex;
};
}  // namespace dp


text:
package cz.auderis.stats.histogram;

public class EnumHistogramClassifier<T extends Enum<T>> implements HistogramClassifier<T, T> {

	@Override
	public T classify(T sampleValue) {
		return sampleValue;
	}

	@Override
	public Histogram<T> createHistogram(Class<T> sampleClass) {
		if (null == sampleClass) {
			throw new NullPointerException();
		} else if (!sampleClass.isEnum()) {
			throw new IllegalArgumentException("not an enum class");
		}
		return new EnumHistogram<T>(sampleClass);
	}

}


text:
using System;
using System.Collections.Generic;
using Lucene.Net.Analysis.Util;

namespace org.apache.lucene.analysis.util
{

	///
	/// Abstract parent class for analysis factories that create <seealso cref="CharFilter"/>
	/// instances.
	///
	public abstract class CharFilterFactory : AbstractAnalysisFactory
	{

	  private static readonly AnalysisSPILoader<CharFilterFactory> loader = new AnalysisSPILoader<CharFilterFactory>(typeof(CharFilterFactory));

	  ///
	  /// looks up a charfilter by name from context classpath
	  public static CharFilterFactory forName(string name, IDictionary<string, string> args)
	  {
		return loader.newInstance(name, args);
	  }

	  ///
	  /// looks up a charfilter class by name from context classpath
	  public static Type lookupClass(string name)
	  {
		return loader.lookupClass(name);
	  }

	  ///
	  /// returns a list of all available charfilter names
	  public static HashSet<string> availableCharFilters()
	  {
		return loader.availableServices();
	  }

	  ///
	  /// Reloads the factory list from the given <seealso cref="ClassLoader"/>.
	  /// Changes to the factories are visible after the method ends, all
	  /// iterators (<seealso cref="#availableCharFilters()"/>,...) stay consistent.
	  ///
	  /// <para>NOTE: Only new factories are added, existing ones are
	  /// never removed or replaced.
	  ///
	  /// </para>
	  /// <para>This method is expensive and should only be called for discovery
	  /// of new factories on the given classpath/classloader!
	  /// </para>
	  ///
	  public static void reloadCharFilters(ClassLoader classloader)
	  {
		loader.reload(classloader);
	  }

	  ///
	  /// Initialize this factory via a set of key-value pairs.
	  ///
	  protected internal CharFilterFactory(IDictionary<string, string> args) : base(args)
	  {
	  }

	  ///
	  /// Wraps the given Reader with a CharFilter.
	  public abstract Reader create(Reader input);
	}

}


text:
char initBaseEnv();

extern Env *baseEnv;


text:
package cover

import (
	"fmt"
	"log"
	"math"
	"sort"
	"strconv"
	"strings"
)

// Builds a constraint matrix for a sudoku of the given dimension.
// The constraint matrix can then be used by the DLX algorithm.
func SudokuConstraintMatrix(dim int) (matrix [][]int, headers []string) {
	// small dim, 3 for classic sudoku
	sdim := int(math.Sqrt(float64(dim)))
	// big dim, 81 for classic sudoku
	bdim := dim * dim
	rowCount := bdim * dim
	colCount := bdim * 4
	log.Printf("Building sparse matrix of %dx%d\n", rowCount, colCount)
	// constraint matrix headers
	// constraint order is existence, row, col, block
	headers = make([]string, colCount)
	for i, j := 0, 0; i < colCount; i++ {
		j = i % bdim
		if i < bdim {
			// constraint 1: existence
			headers[i] = fmt.Sprintf("%v,%v", i/dim, i%dim)
		} else if i < 2*bdim {
			// constraint 2: row
			headers[i] = fmt.Sprintf("%vr%v", j%dim+1, j/dim)
		} else if i < 3*bdim {
			// constraint 3: column
			headers[i] = fmt.Sprintf("%vc%v", j%dim+1, j/dim)
		} else {
			// constraint 4: block
			headers[i] = fmt.Sprintf("%vb%v", j%dim+1, j/dim)
		}
	}
	// constraint matrix
	matrix = make([][]int, rowCount)
	for i := 0; i < rowCount; i++ {
		matrix[i] = make([]int, colCount)
		digit := i%dim + 1
		dcell := i / dim
		drow := i / bdim
		dcol := (i / dim) % dim
		dblock := drow/sdim*sdim + dcol/sdim
		matrix[i][dcell] = digit
		matrix[i][bdim+drow*dim+i%dim] = digit
		matrix[i][bdim+bdim+i%bdim] = digit
		matrix[i][bdim+bdim+bdim+dblock*dim+i%dim] = digit
	}
	return
}

type SudokuSolver struct {
	*Solver
	Dim int
}

// Since the constraint matrix for a sudoku only depends on its size, this constructor
// encapsulate the matrix creation so that only the sudoku size is needed.
func NewSudokuSolver(dim int) *SudokuSolver {
	m, h := SudokuConstraintMatrix(dim)
	s := SudokuSolver{&Solver{matrix: NewSparseMatrix(m, h)}, dim}
	return &s
}

// Translates the initial grid to a map of digit => cells.
// This enables the solver to safely initialize the matrix before
// actually running the DLX algorithm.
// The trick is to search only in the columns of the 1st constraint (existence)
// and start from the biggest digit. This way, the number of steps to find the correct
// row does not change and the digit can be found in a single column.
func (s *SudokuSolver) gridToCover(sudoku [][]int) map[int][]string {
	dim := len(sudoku)
	init := map[int][]string{}
	for i := 0; i < dim; i++ {
		for j := 0; j < dim; j++ {
			digit := sudoku[i][j]
			if digit > 0 {
				_, ok := init[digit]
				if !ok {
					init[digit] = make([]string, 0)
				}
				init[digit] = append(init[digit], fmt.Sprintf("%v,%v", i, j))
			}
		}
	}
	return init
}
func (s *SudokuSolver) coverToGrid(nodes []*Node) (x int, y int, digit int) {
	for _, n := range nodes {
		if n != nil {
			if strings.ContainsAny(n.Col.Name, "r & c & b") {
				digit, _ = strconv.Atoi(fmt.Sprintf("%c", n.Col.Name[0]))
			} else {
				xy := strings.Split(n.Col.Name, ",")
				x, _ = strconv.Atoi(xy[0])
				y, _ = strconv.Atoi(xy[1])
			}
		}
	}
	return
}
func (s *SudokuSolver) Eureka(O *Solution) {
	grid := make([][]int, s.Dim)
	for i := 0; i < s.Dim; i++ {
		grid[i] = make([]int, s.Dim)
	}
	for _, n := range *O {
		nodes := make([]*Node, 4)
		nodes = append(nodes, n)
		for m := n.Right; n != m; m = m.Right {
			nodes = append(nodes, m)
		}
		x, y, digit := s.coverToGrid(nodes)
		grid[x][y] = digit
	}
	sdim := int(math.Sqrt(float64(s.Dim)))
	delim := "+" + strings.Repeat(strings.Repeat("-", sdim*2+1)+"+", sdim)
	for i, line := range grid {
		if i%sdim == 0 {
			fmt.Println(delim)
		}
		for j, cell := range line {
			if j%sdim == 0 {
				if j > 0 {
					fmt.Print(" ")
				}
				fmt.Print("|")
			}
			fmt.Print(" ", cell)
		}
		fmt.Print(" |\n")
	}
	fmt.Println(delim)
}
func (s *SudokuSolver) Solve(sudoku [][]int) *Solution {
	partial := s.gridToCover(sudoku)
	// Iterate through the digits from biggest to smallest.
	keys := make([]int, 0, len(partial))
	for key, _ := range partial {
		keys = append(keys, key)
	}
	sort.Sort(sort.Reverse(sort.IntSlice(keys)))
	// log.Println("Initial config is", partial)
	O := new(Solution)
	k := 0
	m := s.matrix
	for _, digit := range keys {
		for _, c := range partial[digit] {
			// Find the column for existence constraint, so that all the digits are available inside.
			n := m.Col(c)
			n.Cover()
			// Move down by <digit> nodes to find the row to include in the solution.
			for j := 0; j < digit; j++ {
				n = n.Down
			}
			O.Set(k, n)
			for o := n.Right; o != n; o = o.Right {
				o.Col.Cover()
			}
			k++
		}
	}
	// fmt.Printf("Initial solution is\n%v", O)
	s.matrix.Search(O, k, s)
	return O
}


text:
package io.luna.game.model.mob.inter;

import io.luna.game.model.mob.Player;
import io.luna.net.msg.out.WalkableInterfaceMessageWriter;

/**
 * An {@link AbstractInterface} implementation that opens a walkable interface.
 *
 * @author lare96 <http://github.org/lare96>
 */
public class WalkableInterface extends AbstractInterface {

    /**
     * Creates a new {@link WalkableInterface}.
     *
     * @param id The interface identifier.
     */
    public WalkableInterface(int id) {
        super(id, InterfaceType.WALKABLE);
    }

    @Override
    public final void open(Player player) {
        int id = unsafeGetId();
        player.queue(new WalkableInterfaceMessageWriter(id));
    }

    @Override
    public final boolean isAutoClose(Player player) {
        return false;
    }
}


text:
namespace ppx {
namespace grfx {
namespace vk {

namespace {
uint32_t GetQueueFamilyIndexForMask(const std::vector<VkQueueFamilyProperties>& queueFamilies, const uint32_t mask)
{
    const uint32_t count = CountU32(queueFamilies);
    for (uint32_t i = 0; i < count; ++i) {
        if ((queueFamilies[i].queueFlags & kAllQueueMask) == mask) {
            return i;
        }
    }
    return PPX_VALUE_IGNORED;
}

template <size_t Size>
uint32_t GetQueueFamilyIndexByPreferences(const std::vector<VkQueueFamilyProperties>& queueFamilies, const std::array<uint32_t, Size>& masks)
{
    for (uint32_t mask : masks) {
        uint32_t index = GetQueueFamilyIndexForMask(queueFamilies, mask);
        if (index != PPX_VALUE_IGNORED) {
            return index;
        }
    }
    return PPX_VALUE_IGNORED;
}
} // namespace

Result Gpu::CreateApiObjects(const grfx::internal::GpuCreateInfo* pCreateInfo)
{
    if (IsNull(pCreateInfo->pApiObject)) {
        return ppx::ERROR_UNEXPECTED_NULL_ARGUMENT;
    }

    mGpu = static_cast<VkPhysicalDevice>(pCreateInfo->pApiObject);

    vkGetPhysicalDeviceProperties(mGpu, &mGpuProperties);

    vkGetPhysicalDeviceFeatures(mGpu, &mGpuFeatures);

    uint32_t count = 0;
    vkGetPhysicalDeviceQueueFamilyProperties(mGpu, &count, nullptr);
    if (count > 0) {
        mQueueFamilies.resize(count);
        vkGetPhysicalDeviceQueueFamilyProperties(mGpu, &count, mQueueFamilies.data());
    }

    mDeviceName     = mGpuProperties.deviceName;
    mDeviceVendorId = static_cast<grfx::VendorId>(mGpuProperties.deviceID);

    return ppx::SUCCESS;
}

void Gpu::DestroyApiObjects()
{
    if (mGpu) {
        mGpu.Reset();
    }
}

float Gpu::GetTimestampPeriod() const
{
    return mGpuProperties.limits.timestampPeriod;
}

uint32_t Gpu::GetQueueFamilyCount() const
{
    uint32_t count = CountU32(mQueueFamilies);
    return count;
}

uint32_t Gpu::GetGraphicsQueueFamilyIndex() const
{
    constexpr std::array<uint32_t, 4> masks = {
        VK_QUEUE_GRAPHICS_BIT,
        VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_TRANSFER_BIT,
        VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT,
        VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT};
    return GetQueueFamilyIndexByPreferences(mQueueFamilies, masks);
}

uint32_t Gpu::GetComputeQueueFamilyIndex() const
{
    constexpr std::array<uint32_t, 4> masks = {
        VK_QUEUE_COMPUTE_BIT,
        VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT,
        VK_QUEUE_COMPUTE_BIT | VK_QUEUE_GRAPHICS_BIT,
        VK_QUEUE_COMPUTE_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_TRANSFER_BIT};
    return GetQueueFamilyIndexByPreferences(mQueueFamilies, masks);
}

uint32_t Gpu::GetTransferQueueFamilyIndex() const
{
    constexpr std::array<uint32_t, 4> masks = {
        VK_QUEUE_TRANSFER_BIT,
        VK_QUEUE_TRANSFER_BIT | VK_QUEUE_COMPUTE_BIT,
        VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT,
        VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT};
    return GetQueueFamilyIndexByPreferences(mQueueFamilies, masks);
}

uint32_t Gpu::GetGraphicsQueueCount() const
{
    uint32_t count = 0;
    uint32_t index = GetGraphicsQueueFamilyIndex();
    if (index != PPX_VALUE_IGNORED) {
        count = mQueueFamilies[index].queueCount;
    }
    return count;
}

uint32_t Gpu::GetComputeQueueCount() const
{
    uint32_t count = 0;
    uint32_t index = GetComputeQueueFamilyIndex();
    if (index != PPX_VALUE_IGNORED) {
        count = mQueueFamilies[index].queueCount;
    }
    return count;
}

uint32_t Gpu::GetTransferQueueCount() const
{
    uint32_t count = 0;
    uint32_t index = GetTransferQueueFamilyIndex();
    if (index != PPX_VALUE_IGNORED) {
        count = mQueueFamilies[index].queueCount;
    }
    return count;
}

} // namespace vk
} // namespace grfx
} // namespace ppx


text:
"""Script that invokes protoc to generate code for .proto files."""

import argparse
import logging
import os
from pathlib import Path
import subprocess
import sys
import tempfile
from typing import Callable, Dict, List, Optional, Tuple, Union

# Make sure dependencies are optional, since this script may be run when
# installing Python package dependencies through GN.
try:
    from pw_cli.log import install as setup_logging
except ImportError:
    from logging import basicConfig as setup_logging  # type: ignore

_LOG = logging.getLogger(__name__)

_COMMON_FLAGS = ('--experimental_allow_proto3_optional', )

def _argument_parser() -> argparse.ArgumentParser:
    """Registers the script's arguments on an argument parser."""

    parser = argparse.ArgumentParser(description=__doc__)

    parser.add_argument('--language',
                        required=True,
                        choices=DEFAULT_PROTOC_ARGS,
                        help='Output language')
    parser.add_argument('--plugin-path',
                        type=Path,
                        help='Path to the protoc plugin')
    parser.add_argument('--include-file',
                        type=argparse.FileType('r'),
                        help='File containing additional protoc include paths')
    parser.add_argument('--out-dir',
                        type=Path,
                        required=True,
                        help='Output directory for generated code')
    parser.add_argument('--compile-dir',
                        type=Path,
                        required=True,
                        help='Root path for compilation')
    parser.add_argument('--sources',
                        type=Path,
                        nargs='+',
                        help='Input protobuf files')

    return parser

def protoc_pwpb_args(args: argparse.Namespace,
                     include_paths: List[str]) -> Tuple[str, ...]:
    return _COMMON_FLAGS + (
        '--plugin',
        f'protoc-gen-custom={args.plugin_path}',
        f'--custom_opt=-I{args.compile_dir}',
        *[f'--custom_opt=-I{include_path}' for include_path in include_paths],
        '--custom_out',
        args.out_dir,
    )

def protoc_pwpb_rpc_args(args: argparse.Namespace,
                         _include_paths: List[str]) -> Tuple[str, ...]:
    return _COMMON_FLAGS + (
        '--plugin',
        f'protoc-gen-custom={args.plugin_path}',
        '--custom_out',
        args.out_dir,
    )

def protoc_go_args(args: argparse.Namespace,
                   _include_paths: List[str]) -> Tuple[str, ...]:
    return _COMMON_FLAGS + (
        '--go_out',
        f'plugins=grpc:{args.out_dir}',
    )

def protoc_nanopb_args(args: argparse.Namespace,
                       _include_paths: List[str]) -> Tuple[str, ...]:
    # nanopb needs to know of the include path to parse *.options files
    return _COMMON_FLAGS + (
        '--plugin',
        f'protoc-gen-nanopb={args.plugin_path}',
        # nanopb_opt provides the flags to use for nanopb_out. Windows doesn't
        # like when you merge the two using the `flag,...:out` syntax. Use
        # Posix-style paths since backslashes on Windows are treated like
        # escape characters.
        f'--nanopb_opt=-I{args.compile_dir.as_posix()}',
        f'--nanopb_out={args.out_dir}',
    )

def protoc_nanopb_rpc_args(args: argparse.Namespace,
                           _include_paths: List[str]) -> Tuple[str, ...]:
    return _COMMON_FLAGS + (
        '--plugin',
        f'protoc-gen-custom={args.plugin_path}',
        '--custom_out',
        args.out_dir,
    )

def protoc_raw_rpc_args(args: argparse.Namespace,
                        _include_paths: List[str]) -> Tuple[str, ...]:
    return _COMMON_FLAGS + (
        '--plugin',
        f'protoc-gen-custom={args.plugin_path}',
        '--custom_out',
        args.out_dir,
    )

def protoc_python_args(args: argparse.Namespace,
                       _include_paths: List[str]) -> Tuple[str, ...]:
    return _COMMON_FLAGS + (
        '--python_out',
        args.out_dir,
        '--mypy_out',
        args.out_dir,
    )

_DefaultArgsFunction = Callable[[argparse.Namespace, List[str]], Tuple[str,
                                                                       ...]]

# Default additional protoc arguments for each supported language.
# TODO(frolv): Make these overridable with a command-line argument.
DEFAULT_PROTOC_ARGS: Dict[str, _DefaultArgsFunction] = {
    'go': protoc_go_args,
    'nanopb': protoc_nanopb_args,
    'nanopb_rpc': protoc_nanopb_rpc_args,
    'pwpb': protoc_pwpb_args,
    'pwpb_rpc': protoc_pwpb_rpc_args,
    'python': protoc_python_args,
    'raw_rpc': protoc_raw_rpc_args,
}

# Languages that protoc internally supports.
BUILTIN_PROTOC_LANGS = ('go', 'python')

def main() -> int:
    """Runs protoc as configured by command-line arguments."""

    parser = _argument_parser()
    args = parser.parse_args()

    if args.plugin_path is None and args.language not in BUILTIN_PROTOC_LANGS:
        parser.error(
            f'--plugin-path is required for --language {args.language}')

    args.out_dir.mkdir(parents=True, exist_ok=True)

    include_paths: List[str] = []
    if args.include_file:
        include_paths = [line.strip() for line in args.include_file]

    wrapper_script: Optional[Path] = None

    # On Windows, use a .bat version of the plugin if it exists or create a .bat
    # wrapper to use if none exists.
    if os.name == 'nt' and args.plugin_path:
        if args.plugin_path.with_suffix('.bat').exists():
            args.plugin_path = args.plugin_path.with_suffix('.bat')
            _LOG.debug('Using Batch plugin %s', args.plugin_path)
        else:
            with tempfile.NamedTemporaryFile('w', suffix='.bat',
                                             delete=False) as file:
                file.write(f'@echo off\npython {args.plugin_path.resolve()}\n')

            args.plugin_path = wrapper_script = Path(file.name)
            _LOG.debug('Using generated plugin wrapper %s', args.plugin_path)

    cmd: Tuple[Union[str, Path], ...] = (
        'protoc',
        f'-I{args.compile_dir}',
        *[f'-I{include_path}' for include_path in include_paths],
        *DEFAULT_PROTOC_ARGS[args.language](args, include_paths),
        *args.sources,
    )

    try:
        process = subprocess.run(cmd,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)
    finally:
        if wrapper_script:
            wrapper_script.unlink()

    if process.returncode != 0:
        _LOG.error('Protocol buffer compilation failed!\n%s',
                   ' '.join(str(c) for c in cmd))
        sys.stderr.buffer.write(process.stdout)
        sys.stderr.flush()

    return process.returncode

if __name__ == '__main__':
    setup_logging()
    sys.exit(main())


text:
from jaeger_client.metrics import MetricsFactory
from collections import defaultdict
from prometheus_client import Counter, Gauge

class PrometheusMetricsFactory(MetricsFactory):
    """
    Provides metrics backed by Prometheus
    """
    def __init__(self, namespace=''):
        self._cache = defaultdict(object)
        self._namespace = namespace

    def _get_tag_name_list(self, tags):
        if tags is None:
            return []
        tag_name_list = []
        for key in tags.keys():
            tag_name_list.append(key)
        return tag_name_list

    def _get_metric(self, metric, name, label_name_list):
        cache_key = name + ''.join(label_name_list)
        if self._cache.get(cache_key) is None:
            self._cache[cache_key] = metric(name=name, documentation=name,
                                            labelnames=label_name_list, namespace=self._namespace)
        return self._cache[cache_key]

    def create_counter(self, name, tags=None):
        label_name_list = self._get_tag_name_list(tags)
        counter = self._get_metric(Counter, name, label_name_list)
        if tags is not None and len(tags) > 0:
            counter = counter.labels(**tags)

        def increment(value):
            counter.inc(value)
        return increment

    def create_gauge(self, name, tags=None):
        label_name_list = self._get_tag_name_list(tags)
        gauge = self._get_metric(Gauge, name, label_name_list)
        if tags is not None and len(tags) > 0:
            gauge = gauge.labels(**tags)

        def update(value):
            gauge.set(value)
        return update


text:
class RemoveStripeIdFromUser < ActiveRecord::Migration
  def up
    remove_column :users, :stripe_id
  end

  def down
    add_column :users, :stripe_id, :string
  end
end


text:
<?php

namespace AppBundle\Command;

use AppBundle\Entity\Infraccion;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Finder\Finder;

class UpdateCoordenadasCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('muni:infraccion:updatecoordenadas')
            ->setDescription('Actualizar coordenadas de las infracciones')
        ;
    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var EntityManager $manager */
        $manager = $this->getContainer()->get('doctrine.orm.default_entity_manager');
        $repo = $manager->getRepository(Infraccion::class);

        $finder = new Finder();

        $finder->files()->name('coordenadas.csv')->in('src/AppBundle/Resources');

        foreach($finder as $file) {
            $path = $file->getRealpath();
        }

        $csv = file_get_contents($path);
        $csv = trim($csv);

        $lines = explode(PHP_EOL, $csv);

        foreach ($lines as $line) {

            $data = explode(',', $line);
            /** @var Infraccion $infraccion */
            $infraccion = $repo->findOneBy(['nroActa' => $data[0]]);

            if ($infraccion) {
                $infraccion->setLat($data[1]);
                $infraccion->setLon($data[2]);

                $manager->persist($infraccion);
                $manager->flush();
            }
        }

    }
}


text:
\documentclass[12pt,english]{report}
\usepackage{umlthesistemplate}
\title{A Human-Centric Approach to \\Autonomous Robot Failures}
\author{Daniel J. Brooks}
\pastdegrees{B.S. West Virginia University (2009) \and M.S. University of Massachusetts Lowell (2014)}
\degree{Doctor of Philosophy}
\department{Computer Science}
\university{University of Massachusetts Lowell}
\majorprofessor{Dr. Holly A. Yanco}
\majorproftitle{Dissertation Chair}
\members{Dr. Jill Drury \and Dr. Aaron Steinfeld}
\date{ 20 April, 2017}
%\abstract{ \input{abstract.tex} }
%\acknowledgments{ \input{ack.tex} }
%\includetoc
%\maketitle
\includeapproval

\begin{document}
\end{document}


text:
<code_scheme name="TR" version="173">
  <JavaCodeStyleSettings>
    <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
    <option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
    <option name="PACKAGES_TO_USE_IMPORT_ON_DEMAND">
      <value />
    </option>
    <option name="IMPORT_LAYOUT_TABLE">
      <value>
        <package name="" withSubpackages="true" static="true" />
        <emptyLine />
        <package name="javax" withSubpackages="true" static="false" />
        <package name="java" withSubpackages="true" static="false" />
        <emptyLine />
        <package name="" withSubpackages="true" static="false" />
      </value>
    </option>
  </JavaCodeStyleSettings>
  <codeStyleSettings language="JAVA">
    <option name="RIGHT_MARGIN" value="150" />
    <option name="KEEP_BLANK_LINES_IN_DECLARATIONS" value="1" />
    <option name="KEEP_BLANK_LINES_IN_CODE" value="1" />
    <option name="KEEP_BLANK_LINES_BEFORE_RBRACE" value="1" />
    <option name="BLANK_LINES_BEFORE_PACKAGE" value="1" />
    <option name="BLANK_LINES_AFTER_CLASS_HEADER" value="1" />
    <option name="SPACE_BEFORE_ARRAY_INITIALIZER_LBRACE" value="true" />
    <option name="SPACE_BEFORE_ANNOTATION_ARRAY_INITIALIZER_LBRACE" value="true" />
    <option name="BINARY_OPERATION_SIGN_ON_NEXT_LINE" value="true" />
    <option name="IF_BRACE_FORCE" value="3" />
    <option name="DOWHILE_BRACE_FORCE" value="3" />
    <option name="WHILE_BRACE_FORCE" value="3" />
    <option name="FOR_BRACE_FORCE" value="3" />
    <indentOptions>
      <option name="CONTINUATION_INDENT_SIZE" value="4" />
    </indentOptions>
  </codeStyleSettings>
</code_scheme>


text:
package ma.glasnost.orika.impl.generator;

import ma.glasnost.orika.metadata.Property;
import ma.glasnost.orika.metadata.Type;

public class MapEntryRef extends VariableRef {

	public enum EntryPart {
		KEY {{
		    this.prototype = new Property.Builder()
                .name("key")
                .expression("key")
                .getter("getKey()")
                .setter("setKey(%s)")
                .build();

		}},
		VALUE {{
			this.prototype = new Property.Builder()
			    .name("value")
			    .expression("value")
			    .getter("getValue()")
			    .setter("setValue(%s)")
			    .build();
		}};

		protected Property prototype;

		Property newProperty(Type<?> type) {
			return prototype.copy(type);
		}
	}

	public MapEntryRef(Type<?> type, String name, EntryPart entryPart) {
		super(entryPart.newProperty(type), name);
	}

	protected String getter() {
		return VariableRef.getGetter(property(), name);
	}

	protected String setter() {
		return VariableRef.getSetter(property(), name);
	}

}


text:
import fileinput
import subprocess
import re
from datetime import date

# Number of days of log files to read
numdays = 7

# Find the current total number of log files
p = subprocess.Popen('ls /opt/zimbra/log/access_log* | wc -l', shell=True, stdout=subprocess.PIPE)
numlogfiles = p.stdout.read()

# Get the list of log files to read
lscmdfmt = 'ls /opt/zimbra/log/access_log* | tail -%d | head -%d'
if numlogfiles > numdays:
    lscmd = lscmdfmt % (numdays + 1, numdays)
else:
    lscmd = lscmdfmt % (numdays, numlogfiles - 1)
p = subprocess.Popen(lscmd, shell=True, stdout=subprocess.PIPE)

resultmap = {}

for file in p.stdout.readlines():
    file = file.rstrip()
    subprocess.call('echo Reading %s ..' % file, shell=True)
    for line in fileinput.input([file]):
        l = line.split('"')
        if len(l) < 7:
            continue
        ua = l[5].rstrip()
        if not re.match('(zm.*|ZCS.*|zclient.*|.*ZCB.*|Jakarta.*|curl.*|-)', ua) is None:
            continue
        requrl = l[1]
        if not re.match('(.*/zimbraAdmin.*|.*/service/admin.*)', requrl) is None:
            continue
        result = l[2].split()[0]
        if result != '200':
            continue
        ip = line.split('-')[0].rstrip()
        if (ip == '127.0.0.1' or ip == '::1'):
            continue
        key = ua, ip
        curval = resultmap.get(key)
        if curval is None:
            resultmap[key] = 1
        else:
            resultmap[key] = curval + 1

reportfile = '/opt/zimbra/zmstat/client_usage_report_%s.csv' % (date.today().isoformat())
subprocess.call('rm -f %s' % reportfile, shell=True)
csv = open(reportfile, 'w')
subprocess.call('echo Writing %s ..' % reportfile, shell=True)
csv.write('"user_agent","client_IP","req_count"\n')
for key, value in resultmap.iteritems():
    csv.write('"%s","%s","%s"\n' % (key[0], key[1], value))
csv.close()


text:
<?php
define('WP_ADMIN', TRUE);

if ( defined('ABSPATH') )
	require_once(ABSPATH . 'wp-load.php');
else
	require_once('../wp-load.php');

require_once(ABSPATH . 'wp-admin/includes/admin.php');

if ( !wp_validate_auth_cookie() )
	wp_die(__('Cheatin’ uh?'));

nocache_headers();

do_action('admin_init');

$action = 'admin_post';
if ( !empty($_REQUEST['action']) )
	$action .= '_' . $_REQUEST['action'];

do_action($action);

?>


text:
var utils = require('./utils')

/**
 * Creates a notification message on the page
 * @param config object containing the properties: ...
 */
var Banner =  function(config) {

    this.closeJSHook = 'js-close';

    this.defaults = {
        close: 'Close',
        theme: 'grey'
    };

    this.config = utils.extend(this.defaults, config);

    this.init();
};

Banner.prototype = {
    init: function() {
        this.idfy();

        if(!this.checkIfBannerHasBeenSeen()) {
            this.html = this.createBanner();
            this.bindEvents();
        }
    },

    idfy: function() {
        if (this.config.id) {
            this.id = this.config.id = this.config.id.replace(/ /g,'-');
        }
    },

    checkIfBannerHasBeenSeen: function () {
        return (utils.getCookie(this.config.id) == "seen");
    },

    bindEvents: function () {
        var self = this;

        this.showBannerListener = function() {
            self.showBanner();
        }

        document.addEventListener('DOMContentLoaded', self.showBannerListener);

        this.deleteBannerListener = function() {
            self.deleteBanner();
        };

        var close = this.html.querySelector("." + this.closeJSHook);
        close.addEventListener('click', self.deleteBannerListener);
    },

    unbindEvents: function() {
        if (document.removeEventListener) {
            document.removeEventListener('DOMContentLoaded', this.showBannerListener);
        } // else it's old IE

        var close = this.html.querySelector("." + this.closeJSHook);
        close.removeEventListener('click', this.deleteBannerListener);
    },

    createBanner: function() {
        var banner = document.createElement('div');
        banner.className = 'skycom banner';

        if(this.config.theme) {
            banner.className = this.setBannerTheme(banner.className);
        }

        var content = document.createElement('div');
        content.className = 'banner__content';
        banner.appendChild(content);

        var closeButton = this.createCloseButton();
        content.appendChild(closeButton);

        if (this.config.theme.toLowerCase() === 'warning') {
            var icon = document.createElement('i');
            icon.className = 'sprite-warning';
            content.appendChild(icon);
            content.className += ' skycom-message-offset';
        }

        var header = document.createElement('h2');
        header.className = 'banner__heading';
        header.appendChild(document.createTextNode(this.config.header))
        content.appendChild(header);

        var message = document.createElement('p');
        message.className = 'banner__message';
        message.innerHTML = this.config.message; // TODO: don't allow HTML in config.message
        content.appendChild(message);

        if (this.config.action) {
            var primaryAction = this.createActionLink(this.config.action, this.config.callback);
            content.appendChild(primaryAction);
        }

        if (this.config.secondaryAction) {
            var secondaryAction = this.createActionLink(this.config.secondaryAction, this.config.secondaryActionCallback);
            content.appendChild(secondaryAction);
        }

        return banner;
    },

    setBannerTheme: function(bannerClass) {
        return bannerClass + " banner--" + this.config.theme;
    },

    createActionLink: function(message, callBackOrAction) {

        var link = document.createElement('a');

        link.className = 'banner__action';
        var icon = document.createElement('i');
        icon.className = 'skycon-chevron';

        link.appendChild(icon);
        link.appendChild(document.createTextNode(message));

        if(callBackOrAction) {
            if(typeof callBackOrAction== 'function') {
                link.addEventListener('click', callBackOrAction);
            } else {
                link.href = callBackOrAction;
            }
        }

        return link;
    },

    createCloseButton: function() {
        var link = document.createElement('a');
        link.className = 'js-close banner__close';
        link.appendChild(document.createTextNode(this.config.close));
        var icon = document.createElement('i');
//        icon.className = this.config.theme === 'blue' ? 'sprite-close-dark' : 'sprite-close-light';
        icon.className = "skycon-close";
        link.appendChild(icon);
        return link;
    },

    showBanner: function() {
        var parent = document.body;
        parent.insertBefore(this.html, parent.firstChild);
    },

    deleteBanner: function () {
        this.unbindEvents();

        if(this.config.remember) {
            this.remember();
        }

        document.body.removeChild(this.html);
    },

    remember: function() {

        var cookieConfig = {
                domain: (location.hostname.match(/sky.com/)) ? 'sky.com' : '',
                path: '/',
                expires: this.config.remember || ''
            };

        utils.setCookie(this.config.id, 'seen', cookieConfig);

    }
};

module.exports  = Banner;


text:
/*
 * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
 * Use is subject to license terms.
 */
/*
 * This file is part of Lustre, http://www.lustre.org/
 * Lustre is a trademark of Sun Microsystems, Inc.
 *
 * lnet/selftest/timer.h
 *
 * Author: Isaac Huang <isaac@clusterfs.com>
 */
#ifndef __SELFTEST_TIMER_H__
#define __SELFTEST_TIMER_H__

typedef struct {
	struct list_head stt_list;
	unsigned long    stt_expires;
	void             (*stt_func) (void *);
	void             *stt_data;
} stt_timer_t;

void stt_add_timer(stt_timer_t *timer);
int stt_del_timer(stt_timer_t *timer);
int stt_startup(void);
void stt_shutdown(void);

#endif /* __SELFTEST_TIMER_H__ */


text:
<?php

     // Redirect to Main index, we wont show our PHP-Files
     $hostname = $_SERVER['HTTP_HOST'];
     $path = dirname($_SERVER['PHP_SELF']);

     header('Location: http://'.$hostname.($path == '/' ? '' : $path).'/../index.php');
?>


text:
using System;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Net.Mail;
using System.Net.Mime;
using RazorEngine.Text;

namespace Essential.Templating.Razor.Email.Helpers
{
    public static class ResourceTemplateHelperExtensions
    {
        public static IEncodedString Link(this ResourceTemplateHelper helper, string path, string contentId, string mediaType,
            TransferEncoding transferEncoding, CultureInfo culture = null)
        {
            Contract.Requires<ArgumentNullException>(helper != null);
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(path));
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(contentId));
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(mediaType));

            var resource = helper.Get(path, culture);
            if (resource == null)
            {
                var message = string.Format("Resource [{0}] was not found.", contentId);
                throw new TemplateHelperException(message);
            }
            var linkedResource = new LinkedResource(resource, mediaType)
            {
                TransferEncoding = transferEncoding,
                ContentId = contentId
            };
            helper.AddLinkedResource(linkedResource);
            var renderedResult = new RawString(string.Format("cid:{0}", contentId));
            return renderedResult;
        }
    }
}


text:
'use strict';

// Development versions are default
global.isProd = false;

// Current working directory
var cwd = process.cwd();

var runSequence = require('run-sequence');

// Gulp & Plugins
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

var concat = $.concat;
var templateCache = $.angularTemplatecache;

// Styles
var sass = require('gulp-sass');
var minifycss = require('gulp-minify-css');

// Scripts
var jshint = require('gulp-jshint');
var browserify = require('browserify');
var stylish = require('jshint-stylish');
var source = require('vinyl-source-stream');
var ngannotate = require('browserify-ngannotate');

// Testing
var karma = require('karma');
var protractor = require('gulp-protractor').protractor;
var webdriver = require('gulp-protractor').webdriver;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

// Dev Server
var superstatic = require('superstatic');

gulp.task('webdriver-update', webdriverUpdate);
gulp.task('webdriver', webdriver);

gulp.task('jshint', function() {
  return gulp.src('./src/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter(stylish));
});

gulp.task('styles', function() {
  return gulp.src('testapp/styles/main.scss')
    .pipe(sass({
      sourceComments: global.isProd ? 'none' : 'map',
      sourceMap: 'sass',
      outputStyle: global.isProd ? 'compressed' : 'nested'
    }))
    .pipe($.if(global.isProd, minifycss()))
    .pipe(gulp.dest('testapp'));
});

gulp.task('build-module', ['jshint'], function() {
  return browserify({
    entries: ['./src/main.js'],
    debug: global.isProd ? false : true,
    insertGlobals: true,
    transform: ngannotate
  })
  .bundle()
  .pipe(source('ng-firebase-auth.js'))
  .pipe(gulp.dest('testapp'))
  .pipe(gulp.dest('dist'))
  .pipe($.if(global.isProd, $.rename('ng-firebase-auth.min.js')))
  .pipe($.if(global.isProd, $.streamify($.uglify())))
  .pipe(gulp.dest('dist'));
});

gulp.task('build-testapp', function() {
  return browserify({
    entries: ['./testapp/scripts/main.js'],
    debug: true,
    insertGlobals: true,
    transform: ngannotate
  })
  .bundle()
  .pipe(source('bundle.js'))
  .pipe(gulp.dest('testapp'));
});

gulp.task('test', function(done) {
  return karma.server.start({
    configFile: cwd + '/karma.conf.js'
  }, done);
});

gulp.task('protractor', ['webdriver-update', 'webdriver' ], function() {
  return gulp.src('test/e2e/**/*.js')
    .pipe(protractor({
        configFile: './protractor.conf.js',
    }))
    .on('error', function(err) {
      // Make sure failed tests cause gulp to exit non-zero
      throw err;
    });
});

gulp.task('watch', function() {
  gulp.watch('src/**/*.js', ['build-testapp']);
  gulp.watch('testapp/scripts/**/*.js', ['build-testapp']);
  return gulp.watch('testapp/styles/**/*.scss', ['styles']);
});

gulp.task('server', function(next) {
  var server = superstatic({
    logger: {
      info: function(msg) {
        console.log('Info:', msg);
      },
      error: function(msg) {
        console.error('Error:', msg);
      }
    },
    port: 4000,
    config: 'divshot.json'
  });
  server.listen(function() {
    console.log('Server running on port ' + server.port);
  });
  next();
});

gulp.task('prod', function() {
  global.isProd = true;
  return runSequence('build-module');
});

gulp.task('build', function() {
  return runSequence('build-module', 'build-testapp', 'styles');
});

gulp.task('default', function() {
  return runSequence('build', 'watch', 'server');
});


text:
propertiesify [![Built with Grunt](https://cdn.gruntjs.com/builtwith.png)](http://gruntjs.com/) [![Build Status](https://travis-ci.org/bealearts/propertiesify.svg)](https://travis-ci.org/bealearts/propertiesify) [![npm version](https://badge.fury.io/js/propertiesify.svg)](http://badge.fury.io/js/propertiesify)
=============
A [Browserify](https://github.com/substack/node-browserify) transform which allows .properties files to be required.

Enables .property files to be required into a module as a JS object hash. Useful for loading localisation resource bundles or configuration.

## Installation
Using [`npm`](http://npmjs.org/) as a development dependency
```shell
npm install propertiesify --save-dev
```

## Configuration

propertiesify uses the [properties](https://www.npmjs.com/package/properties) module and supports the same ```options``` object.

All properties are supported, apart from ```path``` which will be ignored.

## Usage

in ```example/locales/en_US.properties```
```java
# en_US
TITLE=Example App
```

in ```example/main.js```
```js
var resources = require('./locals/en_US.properties');

console.log(resources.TITLE);	// Outputs: 'Example App'
```

### Transform with the API
```js
var browserify = require('browserify');
var fs = require('fs');
var b = browserify('example/main.js');
b.transform('propertiesify');
b.bundle().pipe(fs.createWriteStream('bundle.js'));
```
### Transform with CML

```shell
browserify example/main.js -t propertiesify > bundle.js
```