text:
<?php
/**
 *
 * This file is part of the Aura for PHP.
 *
 * @license http://opensource.org/licenses/bsd-license.php BSD
 *
 */
namespace Aura\Router;

use ArrayObject;
use Closure;

/**
 *
 * Represents an individual route with a name, path, params, values, etc.
 *
 * In general, you should never need to instantiate a Route directly. Use the
 * RouteFactory instead, or the Router.
 *
 * @package Aura.Router
 *
 * @property-read string $name The route name.
 *
 * @property-read string $path The route path.
 *
 * @property-read array $values Default values for params.
 *
 * @property-read array $params The matched params.
 *
 * @property-read Regex $regex The regular expression for the route.
 *
 * @property-read array $tokens The regular expression for the route.
 *
 * @property-read ArrayObject $matches All params found during `isMatch()`.
 *
 * @property-read array $debug Debugging messages.
 *
 * @property-read callable $generate A callable for generating a link.
 *
 * @property-read string $wildcard The name of the wildcard param.
 *
 */
class Route extends AbstractSpec
{
    /**
     *
     * The route failed to match at isRoutableMatch().
     *
     * @const string
     *
     */
    const FAILED_ROUTABLE = 'FAILED_ROUTABLE';

    /**
     *
     * The route failed to match at isSecureMatch().
     *
     * @const string
     *
     */
    const FAILED_SECURE = 'FAILED_SECURE';

    /**
     *
     * The route failed to match at isRegexMatch().
     *
     * @const string
     *
     */
    const FAILED_REGEX = 'FAILED_REGEX';

    /**
     *
     * The route failed to match at isMethodMatch().
     *
     * @const string
     *
     */
    const FAILED_METHOD = 'FAILED_METHOD';

    /**
     *
     * The route failed to match at isAcceptMatch().
     *
     * @const string
     *
     */
    const FAILED_ACCEPT = 'FAILED_ACCEPT';

    /**
     *
     * The route failed to match at isServerMatch().
     *
     * @const string
     *
     */
    const FAILED_SERVER = 'FAILED_SERVER';

    /**
     *
     * The route failed to match at isCustomMatch().
     *
     * @const string
     *
     */
    const FAILED_CUSTOM = 'FAILED_CUSTOM';

    /**
     *
     * The name for this Route.
     *
     * @var string
     *
     */
    protected $name;

    /**
     *
     * The path for this Route with param tokens.
     *
     * @var string
     *
     */
    protected $path;

    /**
     *
     * Matched param values.
     *
     * @var array
     *
     */
    protected $params = array();

    /**
     *
     * A Regex object for the path.
     *
     * @var Regex
     *
     */
    protected $regex;

    /**
     *
     * All params found during the `isMatch()` process, both from the path
     * tokens and from matched server values.
     *
     * @var ArrayObject
     *
     * @see isMatch()
     *
     */
    protected $matches;

    /**
     *
     * Debugging information about why the route did not match.
     *
     * @var array
     *
     */
    protected $debug;

    /**
     *
     * The matching score for this route (+1 for each is*Match() that passes).
     *
     * @var int
     *
     */
    protected $score = 0;

    /**
     *
     * The failure code, if any, during matching.
     *
     * @var string
     *
     */
    protected $failed = null;

    /**
     *
     * Constructor.
     *
     * @param Regex $regex A regular expression support object.
     *
     * @param string $path The path for this Route with param token
     * placeholders.
     *
     * @param string $name The name for this route.
     *
     */
    public function __construct(Regex $regex, $path, $name = null)
    {
        $this->regex = $regex;
        $this->path = $path;
        $this->name = $name;
    }

    /**
     *
     * Magic read-only for all properties and spec keys.
     *
     * @param string $key The property to read from.
     *
     * @return mixed
     *
     */
    public function __get($key)
    {
        return $this->$key;
    }

    /**
     *
     * Magic isset() for all properties.
     *
     * @param string $key The property to check if isset().
     *
     * @return bool
     *
     */
    public function __isset($key)
    {
        return isset($this->$key);
    }

    /**
     *
     * Checks if a given path and server values are a match for this
     * Route.
     *
     * @param string $path The path to check against this Route.
     *
     * @param array $server A copy of $_SERVER so that this Route can check
     * against the server values.
     *
     * @param string $basepath A basepath to prefix to the route path.
     *
     * @return bool
     *
     */
    public function isMatch($path, array $server, $basepath = null)
    {
        $this->debug = array();
        $this->params = array();
        $this->score = 0;
        $this->failed = null;
        if ($this->isFullMatch($path, $server, $basepath)) {
            $this->setParams();
            return true;
        }
        return false;
    }

    /**
     *
     * Is the route a full match?
     *
     * @param string $path The path to check against this route
     *
     * @param array $server A copy of $_SERVER so that this Route can check
     * against the server values.
     *
     * @param string $basepath A basepath to prefix to the route path.
     *
     * @return bool
     *
     */
    protected function isFullMatch($path, array $server, $basepath = null)
    {
        return $this->isRoutableMatch()
            && $this->isSecureMatch($server)
            && $this->isRegexMatch($path, $basepath)
            && $this->isMethodMatch($server)
            && $this->isAcceptMatch($server)
            && $this->isServerMatch($server)
            && $this->isCustomMatch($server);
    }

    /**
     *
     * A partial match passed.
     *
     * @return bool
     *
     */
    protected function pass()
    {
        $this->score ++;
        return true;
    }

    /**
     *
     * A partial match failed.
     *
     * @param string $failed The reason of failure
     *
     * @param string $append
     *
     * @return bool
     *
     */
    protected function fail($failed, $append = null)
    {
        $this->debug[] = $failed . $append;
        $this->failed = $failed;
        return false;
    }

    /**
     *
     * Check whether a failure happened due to accept header
     *
     * @return bool
     *
     */
    public function failedAccept()
    {
        return $this->failed == self::FAILED_ACCEPT;
    }

    /**
     *
     * Check whether a failure happened due to http method
     *
     * @return bool
     *
     */
    public function failedMethod()
    {
        return $this->failed == self::FAILED_METHOD;
    }

    /**
     *
     * Check whether a failure happened due to route not match
     *
     * @return bool
     *
     */
    protected function isRoutableMatch()
    {
        if ($this->routable) {
            return $this->pass();
        }

        return $this->fail(self::FAILED_ROUTABLE);
    }

    /**
     *
     * Checks that the Route `$secure` matches the corresponding server values.
     *
     * @param array $server A copy of $_SERVER.
     *
     * @return bool True on a match, false if not.
     *
     */
    protected function isSecureMatch($server)
    {
        if ($this->secure === null) {
            return $this->pass();
        }

        if ($this->secure != $this->serverIsSecure($server)) {
            return $this->fail(self::FAILED_SECURE);
        }

        return $this->pass();
    }

    /**
     *
     * Check whether the server is in secure mode
     *
     * @param array $server
     *
     * @return bool
     *
     */
    protected function serverIsSecure($server)
    {
        return (isset($server['HTTPS']) && $server['HTTPS'] == 'on')
            || (isset($server['SERVER_PORT']) && $server['SERVER_PORT'] == 443);
    }

    /**
     *
     * Checks that the path matches the Route regex.
     *
     * @param string $path The path to match against.
     *
     * @param string $basepath A basepath to prefix to the route path.
     *
     * @return bool True on a match, false if not.
     *
     */
    protected function isRegexMatch($path, $basepath = null)
    {
        $regex = clone $this->regex;
        $match = $regex->match($this, $path, $basepath);
        if (! $match) {
            return $this->fail(self::FAILED_REGEX);
        }
        $this->matches = new ArrayObject($regex->getMatches());
        return $this->pass();
    }

    /**
     *
     * Is the requested method matching
     *
     * @param array $server
     *
     * @return bool
     *
     */
    protected function isMethodMatch($server)
    {
        if (! $this->method) {
            return $this->pass();
        }

        $pass = isset($server['REQUEST_METHOD'])
             && in_array($server['REQUEST_METHOD'], $this->method);

        return $pass
             ? $this->pass()
             : $this->fail(self::FAILED_METHOD);
    }

    /**
     *
     * Is the Accept header a match.
     *
     * @param array $server
     *
     * @return bool
     *
     */
    protected function isAcceptMatch($server)
    {
        if (! $this->accept || ! isset($server['HTTP_ACCEPT'])) {
            return $this->pass();
        }

        $header = str_replace(' ', '', $server['HTTP_ACCEPT']);

        if ($this->isAcceptMatchHeader('*/*', $header)) {
            return $this->pass();
        }

        foreach ($this->accept as $type) {
            if ($this->isAcceptMatchHeader($type, $header)) {
                return $this->pass();
            }
        }

        return $this->fail(self::FAILED_ACCEPT);
    }

    /**
     *
     * Is the accept method matching
     *
     * @param string $type
     *
     * @param string $header
     *
     * @return bool
     *
     */
    protected function isAcceptMatchHeader($type, $header)
    {
        list($type, $subtype) = explode('/', $type);
        $type = preg_quote($type);
        $subtype = preg_quote($subtype);
        $regex = "#$type/($subtype|\*)(;q=(\d\.\d))?#";

        $found = preg_match($regex, $header, $matches);
        if (! $found) {
            return false;
        }

        if (isset($matches[3])) {
            return $matches[3] !== '0.0';
        }

        return true;
    }

    /**
     *
     * Checks that $_SERVER values match their related regular expressions.
     *
     * @param array $server A copy of $_SERVER.
     *
     * @return bool True if they all match, false if not.
     *
     */
    protected function isServerMatch($server)
    {
        foreach ($this->server as $name => $regex) {
            $matches = $this->isServerMatchRegex($server, $name, $regex);
            if (! $matches) {
                return $this->fail(self::FAILED_SERVER, " ($name)");
            }
            $this->matches[$name] = $matches[$name];
        }

        return $this->pass();
    }

    /**
     *
     * Does a server key match a regex?
     *
     * @param array $server The server values.
     *
     * @param string $name The server key.
     *
     * @param string $regex The regex to match against.
     *
     * @return array
     *
     */
    protected function isServerMatchRegex($server, $name, $regex)
    {
        $value = isset($server[$name])
               ? $server[$name]
               : '';
        $regex = "#(?P<{$name}>{$regex})#";
        preg_match($regex, $value, $matches);
        return $matches;
    }

    /**
     *
     * Checks that the custom Route `$is_match` callable returns true, given
     * the server values.
     *
     * @param array $server A copy of $_SERVER.
     *
     * @return bool True on a match, false if not.
     *
     */
    protected function isCustomMatch($server)
    {
        if (! $this->is_match) {
            return $this->pass();
        }

        // attempt the match
        $result = call_user_func($this->is_match, $server, $this->matches);

        // did it match?
        if (! $result) {
            return $this->fail(self::FAILED_CUSTOM);
        }

        return $this->pass();
    }

    /**
     *
     * Sets the route params from the matched values.
     *
     * @return null
     *
     */
    protected function setParams()
    {
        $this->params = $this->values;
        $this->setParamsWithMatches();
        $this->setParamsWithWildcard();

    }

    /**
     *
     * Set the params with their matched values.
     *
     * @return null
     *
     */
    protected function setParamsWithMatches()
    {
        // populate the path matches into the route values. if the path match
        // is exactly an empty string, treat it as missing/unset. (this is
        // to support optional ".format" param values.)
        foreach ($this->matches as $key => $val) {
            if (is_string($key) && $val !== '') {
                $this->params[$key] = rawurldecode($val);
            }
        }
    }

    /**
     *
     * Set the wildcard param value.
     *
     * @return null
     *
     */
    protected function setParamsWithWildcard()
    {
        if (! $this->wildcard) {
            return;
        }

        if (empty($this->params[$this->wildcard])) {
            $this->params[$this->wildcard] = array();
            return;
        }

        $this->params[$this->wildcard] = array_map(
            'rawurldecode',
            explode('/', $this->params[$this->wildcard])
        );
    }
}


text:
// +build ignore

/*
 * Minio Go Library for Amazon S3 Compatible Cloud Storage (C) 2015 Minio, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"fmt"

	"github.com/minio/minio-go"
)

func main() {
	// Note: YOUR-ACCESSKEYID, YOUR-SECRETACCESSKEY, my-bucketname and my-prefixname
	// are dummy values, please replace them with original values.

	// Requests are always secure (HTTPS) by default. Set secure=false to enable insecure (HTTP) access.
	// This boolean value is the last argument for New().

	// New returns an Amazon S3 compatible client object. API compatibility (v2 or v4) is automatically
	// determined based on the Endpoint value.
	s3Client, err := minio.New("s3.amazonaws.com", "YOUR-ACCESSKEYID", "YOUR-SECRETACCESSKEY", true)
	if err != nil {
		fmt.Println(err)
		return
	}

	// List 'N' number of objects from a bucket-name with a matching prefix.
	listObjectsN := func(bucket, prefix string, recursive bool, N int) (objsInfo []minio.ObjectInfo, err error) {
		// Create a done channel to control 'ListObjects' go routine.
		doneCh := make(chan struct{}, 1)

		// Free the channel upon return.
		defer close(doneCh)

		i := 1
		for object := range s3Client.ListObjects(bucket, prefix, recursive, doneCh) {
			if object.Err != nil {
				return nil, object.Err
			}
			i++
			// Verify if we have printed N objects.
			if i == N {
				// Indicate ListObjects go-routine to exit and stop
				// feeding the objectInfo channel.
				doneCh <- struct{}{}
			}
			objsInfo = append(objsInfo, object)
		}
		return objsInfo, nil
	}

	// List recursively first 100 entries for prefix 'my-prefixname'.
	recursive := true
	objsInfo, err := listObjectsN("my-bucketname", "my-prefixname", recursive, 100)
	if err != nil {
		fmt.Println(err)
	}

	// Print all the entries.
	fmt.Println(objsInfo)
}

redpajama_set_name: RedPajamaGithub


text: Movie App to test testing frameworks, e.g. Specta, Expecta, KIF.


text:
[instagram-private-api](../../README.md) / [responses](../../modules/responses.md) / MediaRepositoryCommentResponse

# Interface: MediaRepositoryCommentResponse

[responses](../../modules/responses.md).MediaRepositoryCommentResponse

## Table of contents

### Properties

- [comment](MediaRepositoryCommentResponse.md#comment)
- [status](MediaRepositoryCommentResponse.md#status)

## Properties

### comment

• **comment**: [`MediaRepositoryCommentResponseComment`](MediaRepositoryCommentResponseComment.md)

#### Defined in

[src/responses/media.repository.comment.response.ts:2](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/media.repository.comment.response.ts#L2)

___

### status

• **status**: `string`

#### Defined in

[src/responses/media.repository.comment.response.ts:3](https://github.com/Nerixyz/instagram-private-api/blob/b3351b9/src/responses/media.repository.comment.response.ts#L3)


text:
import argparse

from Bio.SeqIO.FastaIO import FastaIterator
import pandas as pd
from parsing import parse_fasta_mhc_dirs
parser = argparse.ArgumentParser()

parser.add_argument(
    "--input-dir",
    required = True,
    type = str,
    help = "Path to FASTA files containing MHC protein sequences"
)

parser.add_argument(
    "--output-file",
    type = str,
    help = "Path to output FASTA file"
)

parser.add_argument(
    "--min-length",
    type = int,
    help = "Minimum sequence length",
    default = 181,
)

parser.add_argument(
    "--exclude",
    type = str,
    help = "Exclude alleles which contain this substring",
    default = "",
)

if __name__ == '__main__':
    args = parser.parse_args()
    exclude_alleles = args.exclude.split(",")
    seqs = parse_fasta_mhc_dirs(
        [args.dir],
        min_length = args.min_length,
        exclude_alleles=exclude_alleles)

    assert len(seqs) > 0, "No sequences found in directory %s" % args.dir
    if args.output_file:
        with open(args.output_file, 'w') as f:
            for allele in sorted(seqs.keys()):
                seq = seqs[allele]
                f.write(">%s %d bp\n%s\n" % (allele, len(seq), seq))
    else:
        for k,v in sorted(seqs.iteritems()):
            print ">",k
            print v


text:
package io.gravitee.alerter.services.engine.contract.healthcheck.alert;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public class ConsecutiveFailureAlert extends HealthcheckAlert {

    private int failures;

    public int getFailures() {
        return failures;
    }

    public void setFailures(int failures) {
        this.failures = failures;
    }

    @Override
    public String toString() {
        return "ConsecutiveFailureAlert{" +
                "id='" + getId() + '\'' +
                ", date=" + getDate() +
                ", api='" + getApi() + '\'' +
                ", endpoint='" + getEndpoint() + '\'' +
                ", failures=" + failures +
                '}';
    }
}


text:
import * as actions from './actions'
import * as selectors from './selectors'
import * as constants from './constants'
import MainContainer from './components/PDFOptionsContainer'

export { default as reducer } from './reducer'
export { actions, selectors, constants }
export default MainContainer


text:
package stdoutmetric_test // import "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"

import (
	"context"
	"encoding/json"
	"io"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"go.opentelemetry.io/otel/exporters/stdout/stdoutmetric"
	"go.opentelemetry.io/otel/sdk/metric"
	"go.opentelemetry.io/otel/sdk/metric/aggregation"
	"go.opentelemetry.io/otel/sdk/metric/metricdata"
)

func testEncoderOption() stdoutmetric.Option {
	// Discard export output for testing.
	enc := json.NewEncoder(io.Discard)
	return stdoutmetric.WithEncoder(enc)
}

func testCtxErrHonored(factory func(*testing.T) func(context.Context) error) func(t *testing.T) {
	return func(t *testing.T) {
		t.Helper()
		ctx, cancel := context.WithCancel(context.Background())
		t.Cleanup(cancel)

		t.Run("DeadlineExceeded", func(t *testing.T) {
			innerCtx, innerCancel := context.WithTimeout(ctx, time.Nanosecond)
			t.Cleanup(innerCancel)
			<-innerCtx.Done()

			f := factory(t)
			assert.ErrorIs(t, f(innerCtx), context.DeadlineExceeded)
		})

		t.Run("Canceled", func(t *testing.T) {
			innerCtx, innerCancel := context.WithCancel(ctx)
			innerCancel()

			f := factory(t)
			assert.ErrorIs(t, f(innerCtx), context.Canceled)
		})

		t.Run("NoError", func(t *testing.T) {
			f := factory(t)
			assert.NoError(t, f(ctx))
		})
	}
}

func TestExporterHonorsContextErrors(t *testing.T) {
	t.Run("Shutdown", testCtxErrHonored(func(t *testing.T) func(context.Context) error {
		exp, err := stdoutmetric.New(testEncoderOption())
		require.NoError(t, err)
		return exp.Shutdown
	}))

	t.Run("ForceFlush", testCtxErrHonored(func(t *testing.T) func(context.Context) error {
		exp, err := stdoutmetric.New(testEncoderOption())
		require.NoError(t, err)
		return exp.ForceFlush
	}))

	t.Run("Export", testCtxErrHonored(func(t *testing.T) func(context.Context) error {
		exp, err := stdoutmetric.New(testEncoderOption())
		require.NoError(t, err)
		return func(ctx context.Context) error {
			var data metricdata.ResourceMetrics
			return exp.Export(ctx, data)
		}
	}))
}

func TestShutdownExporterReturnsShutdownErrorOnExport(t *testing.T) {
	var (
		data     metricdata.ResourceMetrics
		ctx      = context.Background()
		exp, err = stdoutmetric.New(testEncoderOption())
	)
	require.NoError(t, err)
	require.NoError(t, exp.Shutdown(ctx))
	assert.EqualError(t, exp.Export(ctx, data), "exporter shutdown")
}

func deltaSelector(metric.InstrumentKind) metricdata.Temporality {
	return metricdata.DeltaTemporality
}

func TestTemporalitySelector(t *testing.T) {
	exp, err := stdoutmetric.New(
		testEncoderOption(),
		stdoutmetric.WithTemporalitySelector(deltaSelector),
	)
	require.NoError(t, err)

	var unknownKind metric.InstrumentKind
	assert.Equal(t, metricdata.DeltaTemporality, exp.Temporality(unknownKind))
}

func dropSelector(metric.InstrumentKind) aggregation.Aggregation {
	return aggregation.Drop{}
}

func TestAggregationSelector(t *testing.T) {
	exp, err := stdoutmetric.New(
		testEncoderOption(),
		stdoutmetric.WithAggregationSelector(dropSelector),
	)
	require.NoError(t, err)

	var unknownKind metric.InstrumentKind
	assert.Equal(t, aggregation.Drop{}, exp.Aggregation(unknownKind))
}


text:
package cgeo.geocaching.filter;

import cgeo.geocaching.R;
import cgeo.geocaching.models.Geocache;

import android.support.annotation.NonNull;

import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.StringRes;

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

class TerrainFilter extends AbstractRangeFilter {

    private TerrainFilter(@StringRes final int name, final int terrain) {
        // do not inline the name constant. Android Lint has a bug which would lead to using the super super constructors
        // @StringRes annotation for the non-annotated terrain parameter of this constructor.
        super(name, terrain, Factory.TERRAIN_MAX);
    }

    protected TerrainFilter(final Parcel in) {
        super(in);
    }

    @Override
    public boolean accepts(@NonNull final Geocache cache) {
        final float terrain = cache.getTerrain();
        return rangeMin <= terrain && terrain < rangeMax;
    }

    public static class Factory implements IFilterFactory {
        private static final int TERRAIN_MIN = 1;
        private static final int TERRAIN_MAX = 7;

        @Override
        @NonNull
        public List<IFilter> getFilters() {
            final List<IFilter> filters = new ArrayList<>(TERRAIN_MAX);
            for (int terrain = TERRAIN_MIN; terrain <= TERRAIN_MAX; terrain++) {
                filters.add(new TerrainFilter(R.string.cache_terrain, terrain));
            }
            return filters;
        }
    }

    public static final Creator<TerrainFilter> CREATOR
            = new Parcelable.Creator<TerrainFilter>() {

        @Override
        public TerrainFilter createFromParcel(final Parcel in) {
            return new TerrainFilter(in);
        }

        @Override
        public TerrainFilter[] newArray(final int size) {
            return new TerrainFilter[size];
        }
    };
}


text:
package apple.coremedia.opaque;

import org.moe.natj.c.CRuntime;
import org.moe.natj.c.OpaquePtr;
import org.moe.natj.general.Pointer;
import org.moe.natj.general.ann.Generated;
import org.moe.natj.general.ann.Runtime;
import org.moe.natj.general.ptr.impl.OpaquePtrImpl;

@Generated
@Runtime(CRuntime.class)
public interface CMBufferQueueTriggerToken extends OpaquePtr {
    @Generated
    class Impl extends OpaquePtrImpl implements CMBufferQueueTriggerToken {
        @Generated
        protected Impl(Pointer peer) {
            super(peer);
        }
    }
}


text:
require 'rubygems'
require 'net/ldap'

module OpenNebula; end

class OpenNebula::LdapAuth
    def initialize(options)
        @options={
            :host => 'localhost',
            :port => 389,
            :user => nil,
            :password => nil,
            :base => nil,
            :auth_method => :simple,
            :user_field => 'cn',
            :user_group_field => 'dn',
            :group_field => 'member'
        }.merge(options)

        ops={}

        if @options[:user]
            ops[:auth] = {
                :method => @options[:auth_method],
                :username => @options[:user],
                :password => @options[:password]
            }
        end

        ops[:host]=@options[:host] if @options[:host]
        ops[:port]=@options[:port].to_i if @options[:port]
        ops[:encryption]=@options[:encryption] if @options[:encryption]

        @ldap=Net::LDAP.new(ops)
    end

    def find_user(name)
        begin
            result=@ldap.search(
                :base => @options[:base],
                :filter => "#{@options[:user_field]}=#{name}")

            if result && result.first
                [result.first.dn, result.first[@options[:user_group_field]]]
            else
                result=@ldap.search(:base => name)

                if result && result.first
                    [name, result.first[@options[:user_group_field]]]
                else
                    [nil, nil]
                end
            end
        rescue
            [nil, nil]
        end
    end

    def is_in_group?(user, group)
        result=@ldap.search(
                    :base   => group,
                    :filter => "(#{@options[:group_field]}=#{user.first})")

        if result && result.first
            true
        else
            false
        end
    end

    def authenticate(user, password)
        ldap=@ldap.clone

        auth={
            :method => @options[:auth_method],
            :username => user,
            :password => password
        }

        if ldap.bind(auth)
            true
        else
            false
        end
    end
end


text:
package com.opengamma.engine.marketdata;

import java.util.Set;

import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.util.ArgumentChecker;

/**
 * @deprecated probably not needed any more
 */
@Deprecated
/* package */ class UnderlyingSnapshot {

  private final MarketDataSnapshot _snapshot;
  private final Set<ValueRequirement> _requirements;

  /* package */ UnderlyingSnapshot(final MarketDataSnapshot snapshot, final Set<ValueRequirement> requirements) {
    ArgumentChecker.notNull(snapshot, "snapshot");
    ArgumentChecker.notNull(requirements, "requirements");
    _snapshot = snapshot;
    _requirements = requirements;
  }

  /* package */ MarketDataSnapshot getSnapshot() {
    return _snapshot;
  }

  /* package */ Set<ValueRequirement> getRequirements() {
    return _requirements;
  }
}


text:
package sandesha2.samples.userguide;

import java.io.File;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.sandesha2.client.SandeshaClient;
import org.apache.sandesha2.client.SandeshaClientConstants;
import org.apache.sandesha2.client.SequenceReport;

public class AsyncPingClient {

	private static final String applicationNamespaceName = "http://tempuri.org/";
	private static final String ping = "ping";
	private static final String Text = "Text";

	private String toIP = "127.0.0.1";

	private String toPort = "8070";

	private String toEPR = "http://" + toIP +  ":" + toPort + "/axis2/services/RMSampleService";

	private static String SANDESHA2_HOME = "<SANDESHA2_HOME>"; //Change this to ur path.

	private static String AXIS2_CLIENT_PATH = SANDESHA2_HOME + File.separator + "target" + File.separator +"repos" + File.separator + "client" + File.separator;   //this will be available after a maven build

	public static void main(String[] args) throws AxisFault {

		String axisClientRepo = null;
		if (args!=null && args.length>0)
			axisClientRepo = args[0];

		if (axisClientRepo!=null && !"".equals(axisClientRepo)) {
			AXIS2_CLIENT_PATH = axisClientRepo;
			SANDESHA2_HOME = "";
		}

		new AsyncPingClient().run();
	}

	private void run () throws AxisFault {
		if ("<SANDESHA2_HOME>".equals(SANDESHA2_HOME)){
			System.out.println("ERROR: Please change <SANDESHA2_HOME> to your Sandesha2 installation directory.");
			return;
		}

		String axis2_xml = AXIS2_CLIENT_PATH + "client_axis2.xml";
		ConfigurationContext configContext = ConfigurationContextFactory.createConfigurationContextFromFileSystem(AXIS2_CLIENT_PATH,axis2_xml);

		ServiceClient serviceClient = new ServiceClient (configContext,null);
//		serviceClient.engageModule(new QName ("sandesha2"));

		Options clientOptions = new Options ();

//		clientOptions.setProperty(MessageContextConstants.CHUNKED,Constants.VALUE_FALSE);   //uncomment this to send messages without chunking.
//		clientOptions.setSoapVersionURI(SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);   //uncomment this to send messages in SOAP 1.2
//		clientOptions.setProperty(SandeshaClient.RM_SPEC_VERSION,Sandesha2Constants.SPEC_VERSIONS.v1_1);  //uncomment this to send the messages according to the v1_1 spec.

		clientOptions.setTo(new EndpointReference (toEPR));

		EndpointReference endpoint = 	serviceClient.getMyEPR(Constants.TRANSPORT_HTTP);
		clientOptions.setProperty(SandeshaClientConstants.AcksTo,endpoint.getAddress());

		clientOptions.setTransportInProtocol(Constants.TRANSPORT_HTTP);
		clientOptions.setAction("urn:wsrm:Ping");

		String sequenceKey = "sequence2";
		clientOptions.setProperty(SandeshaClientConstants.SEQUENCE_KEY,sequenceKey);

		serviceClient.setOptions(clientOptions);

		serviceClient.fireAndForget(getPingOMBlock("ping1"));
		serviceClient.fireAndForget(getPingOMBlock("ping2"));

		clientOptions.setProperty(SandeshaClientConstants.LAST_MESSAGE, "true");
		serviceClient.fireAndForget(getPingOMBlock("ping3"));

		boolean complete = false;
		while (!complete) {
			SequenceReport sequenceReport = SandeshaClient.getOutgoingSequenceReport(serviceClient);
			if (sequenceReport!=null && sequenceReport .getCompletedMessages().size()==3)
				complete = true;
			else {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		serviceClient.cleanup();
	}

	private static OMElement getPingOMBlock(String text) {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		OMNamespace namespace = fac.createOMNamespace(applicationNamespaceName,"ns1");
		OMElement pingElem = fac.createOMElement(ping, namespace);
		OMElement textElem = fac.createOMElement(Text, namespace);

		textElem.setText(text);
		pingElem.addChild(textElem);

		return pingElem;
	}

}


text:
module ValidationProfiler
  module Rules
    class DateValidationRule < ValidationProfiler::Rules::ValidationRule

      def error_message(field, attributes = {}, parent = nil)

        field_name = field.to_s
        if parent != nil
          field_name = "#{parent.to_s}.#{field.to_s}"
        end

        #check if a custom error message has been specified in the attributes
        if attributes[:message] == nil
          #no custom error message has been specified so create the default message.
          "#{field_name} is not a valid date"
        else
          attributes[:message]
        end
      end

      def validate(obj, field, attributes = {}, parent = nil)

        #attempt to get the field value from the object
        field_value = get_field_value(obj, field)

        if !is_required?(field_value, attributes)
          return true
        end

        begin
          Date.parse(field_value)
        rescue => e
          return false
        end

        return true

      end

    end
  end
end


text:
package net.compitek.javakit.service;/**
 * Created by Evgene on 05.06.2015.
 */

import net.compitek.javakit.database.dao.CompanyDao;
import net.compitek.javakit.database.domain.Company;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CompanyService extends AbstractEntityService<Long,Company,CompanyDao>{
    private static final Logger log = Logger.getLogger(CompanyService.class);

    @Autowired
    CompanyDao companyDao;

    @Override
    protected CompanyDao getDao() {
        return companyDao;
    }

    @Override
    protected Class<Company> getEntityClass() {
        return Company.class;
    }
}


text:
import configureStore from './noteStore';
import storage from '../libs/storage';

const APP_STORAGE = 'kanban_app';
const store = configureStore(storage.get(APP_STORAGE) || {});

store.subscribe(() => {
  if(!storage.get('debug')) {
    storage.set(APP_STORAGE, store.getState());
  }
});

export default store;


text:
using System.Collections.Generic;
using System.Windows.Data;
using FluentAssertions;
using Metrolib.Converters;
using NUnit.Framework;

namespace Metrolib.Test.Converters
{
	[TestFixture]
	public sealed class UInt64ToStringConverterTest
		: AbstractNumberToStringConverterTest
	{
		private UInt64ToStringConverter _converter;

		[OneTimeSetUp]
		public void OneTimeSetUp()
		{
			_converter = new UInt64ToStringConverter();
		}

		public static IEnumerable<string> InvalidInputs
		{
			get
			{
				return new[]
				{
					"",
					"f",
					"42.",
					".1211"
				};
			}
		}

		protected override IValueConverter Converter
		{
			get { return _converter; }
		}

		[Test]
		public new void TestConvert1()
		{
			_converter.Convert((ulong) 42, null, null, null).Should().Be("42");
		}

		[Test]
		public new void TestConvertBack2()
		{
			_converter.ConvertBack("42", typeof(ulong), null, null).Should().Be((ulong) 42);
		}

		[Test]
		public void TestConvertBack3()
		{
			_converter.ConvertBack("42", typeof(ulong?), null, null).Should().Be((ulong) 42);
		}

		[Test]
		public void TestConvertBack4([ValueSource(nameof(InvalidInputs))] string invalidInput)
		{
			_converter.ConvertBack(invalidInput, typeof(ulong), null, null)
				.Should().Be(Binding.DoNothing, "because the user hasn't finished his input");
		}
	}
}


text:
var express = require('express');
var passport = require('passport');
var mongoose = require('mongoose');
var app = express();
var server = require('http').Server(app);
var morgan = require('morgan');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var methodOverride = require('method-override');
app.use(bodyParser.urlencoded({'extended':'true'}));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(morgan('dev'));
app.use(cookieParser());
app.use(bodyParser.urlencoded({
	'extended': 'true'
}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(passport.initialize());
app.use(passport.session());
app.set('view cache', true);

var sd = {
	fse: require('fs-extra'),
	fs: require('fs'),
	path: require('path'),
	request: require('request'),
	_isEndOfStr: function(str, strCheck){
		var length = strCheck.length;
		return str.slice(str.length-length).toLowerCase()==strCheck.toLowerCase();
	}
};
var waits = [];
sd._wait_next = function(){
	if(waits.length>0){
		waits.pop();
	}
	if(waits.length>0) waits[waits.length-1]();
}
sd._wait = function(funcs){
	waits.unshift(funcs);
	if(waits.length==1) waits[0]();
}
sd._getFiles = function(srcpath) {
	return sd.fs.readdirSync(srcpath).filter(function(file) {
		return sd.fs.statSync(sd.path.join(srcpath, file)).isFile();
	});
}
sd.theme = sd.fse.readJsonSync(process.cwd()+'/theme.json', {throws: false});
require(__dirname + '/serve')(app, sd);
require(__dirname + '/bridge')(app, sd);

var session = require('express-session');
var store;
var sessionMiddleware = session({
	key: 'express.sid.'+sd.theme.prefix,
	secret: 'thisIsCoolSecretFromWaWFramework'+sd.theme.prefix,
	resave: false,
	saveUninitialized: true,
	cookie: {
		maxAge: 365 * 24 * 60 * 60 * 1000
	},
	rolling: true,
	store: store
});
app.use(sessionMiddleware);

server.listen(sd.theme.port||8080);
console.log("App listening on port " + (sd.theme.port||8080) );


text:
Vimpressionist aims to be a Vim distribution for your GNU/Linux environment. It provides comprehensive and well-documented dotfiles for the main command-line software you might need. With Vimpressionist, you will have Vim-optimized key bindings and the same look & feel everywhere thanks to the [Archery](https://github.com/Badacadabra/vim-archery) colorscheme.

## Installation

Coming soon...

## Universal key mappings

These basic Vim mappings are often used:

| key         | action                    |
|:-----------:|:--------------------------|
| `h`         | Go left                   |
| `j`         | Go down                   |
| `k`         | Go up                     |
| `l`         | Go right                  |
| `gg`        | Jump to beginning         |
| `G`         | Jump to end               |
| `w`         | Save                      |
| `d`         | Delete                    |
| `q` or `ZZ` | Quit                      |
| `:`         | Enter command mode        |
| `!`         | Use shell                 |
| `/`         | Search forward            |
| `?`         | Search backward or help   |
| `CTRL-L`    | Refresh                   |
| `CTRL-E`    | Scroll one line down      |
| `CTRL-Y`    | Scroll one line up        |
| `CTRL-D`    | Scroll half page down     |
| `CTRL-U`    | Scroll half page up       |
| `CTRL-F`    | Scroll one page down      |
| `CTRL-B`    | Scroll one page up        |
| `CTRL-O`    | Go back                   |
| `CTRL-I`    | Go forth                  |

Key mappings defined in Vimpressionist have been carefully optimized to be Vim-like as much as possible. You can try to guess them while using an application, but you can of course refer to the appropriate configuration file directly.

## Available software

Thanks to all contributors who have built these nice text-based applications over the years!

---

### calcurse

> **Category:** Calendar & Scheduling application

> **GitHub:**   [https://github.com/lfos/calcurse](https://github.com/lfos/calcurse)

> **Website:**  [http://calcurse.org/](http://calcurse.org/)

![calcurse](_screenshots/calcurse.png)

---

### cmus

> **Category:** Music player

> **GitHub:**   [https://github.com/cmus/cmus](https://github.com/cmus/cmus)

> **Website:**  [https://cmus.github.io/](https://cmus.github.io/)

![cmus](_screenshots/cmus.png)

---

### feh

> **Category:** Image viewer

> **GitHub:**   [https://github.com/derf/feh](https://github.com/derf/feh)

> **Website:**  [https://feh.finalrewind.org/](https://feh.finalrewind.org/)

![feh](_screenshots/feh.png)

---

### i3

> **Category:** Tiling window manager

> **GitHub:**   [https://github.com/i3/i3](https://github.com/i3/i3)

> **Website:**  [http://i3wm.org/](http://i3wm.org/)

![i3](_screenshots/i3.png)

---

### Mutt

> **Category:** Email client

> **GitHub:** [https://github.com/neomutt/neomutt](https://github.com/neomutt/neomutt)

> **Website:** [http://www.mutt.org/](http://www.mutt.org/)

![mutt](_screenshots/mutt.png)

---

### Newsbeuter

> **Category:** RSS/Atom feed reader

> **GitHub:**   [https://github.com/akrennmair/newsbeuter](https://github.com/akrennmair/newsbeuter)

> **Website:**  [http://newsbeuter.org/](http://newsbeuter.org/)

![newsbeuter](_screenshots/newsbeuter.png)

---

### Termite

> **Category:** Terminal emulator

> **GitHub:**   [https://github.com/thestinger/termite](https://github.com/thestinger/termite)

> **Website:**  N/A

![termite](_screenshots/termite.png)

---

### Tig

> **Category:** Git interface

> **GitHub:**   [https://github.com/jonas/tig](https://github.com/jonas/tig)

> **Website:**  [https://jonas.github.io/tig/](https://jonas.github.io/tig/)

![tig](_screenshots/tig.png)

---

### Vifm

> **Category:** File manager

> **GitHub:**   [https://github.com/vifm/vifm](https://github.com/vifm/vifm)

> **Website:**  [https://vifm.info/](https://vifm.info/)

![vifm](_screenshots/vifm.png)

---

### Vim

> **Category:** Text editor

> **GitHub:**   [https://github.com/vim/vim](https://github.com/vim/vim)

> **Website:**  [http://www.vim.org/](http://www.vim.org/)

![vim](_screenshots/vim.png)

---

### W3M

> **Category:** Pager & Web browser

> **GitHub:**   N/A

> **Website:**  [http://w3m.sourceforge.net/](http://w3m.sourceforge.net/)

![w3m](_screenshots/w3m.png)

---

### WeeChat

> **Category:** Chat client

> **GitHub:**   [https://github.com/weechat/weechat](https://github.com/weechat/weechat)

> **Website:**  [https://weechat.org/](https://weechat.org/)

![weechat](_screenshots/weechat.png)

---

### Zathura

> **Category:** Document viewer

> **GitHub:**   N/A

> **Website:**  [https://pwmt.org/projects/zathura/](https://pwmt.org/projects/zathura/)

![zathura](_screenshots/zathura.png)


text:
function [hr] = yr2hr(yr)
% Convert time from Julian years (365.25 days) to hours.
% Chad Greene 2012
hr = yr*8766;


text:
using namespace GafferScene;
using namespace Gaffer;
using namespace IECore;
using namespace std;

namespace
{

// Special value used at the end of `rootSizes`,
// to indicate that there are roots at descendant
// locations.
const int g_descendantRoots = numeric_limits<int>::max();

} // namespace

GAFFER_NODE_DEFINE_TYPE( PathFilter );

size_t PathFilter::g_firstPlugIndex = 0;

PathFilter::PathFilter( const std::string &name )
	:	Filter( name )
{
	storeIndexOfNextChild( g_firstPlugIndex );
	addChild( new StringVectorDataPlug( "paths", Plug::In, new StringVectorData ) );
	addChild( new FilterPlug( "roots" ) );
	addChild( new PathMatcherDataPlug( "__pathMatcher", Plug::Out, new PathMatcherData ) );
	addChild( new IntVectorDataPlug( "__rootSizes", Plug::Out, new IntVectorData() ) );

	plugDirtiedSignal().connect( boost::bind( &PathFilter::plugDirtied, this, ::_1 ) );
}

PathFilter::~PathFilter()
{
}

Gaffer::StringVectorDataPlug *PathFilter::pathsPlug()
{
	return getChild<Gaffer::StringVectorDataPlug>( g_firstPlugIndex );
}

const Gaffer::StringVectorDataPlug *PathFilter::pathsPlug() const
{
	return getChild<Gaffer::StringVectorDataPlug>( g_firstPlugIndex );
}

FilterPlug *PathFilter::rootsPlug()
{
	return getChild<FilterPlug>( g_firstPlugIndex + 1 );
}

const FilterPlug *PathFilter::rootsPlug() const
{
	return getChild<FilterPlug>( g_firstPlugIndex + 1 );
}

Gaffer::PathMatcherDataPlug *PathFilter::pathMatcherPlug()
{
	return getChild<PathMatcherDataPlug>( g_firstPlugIndex + 2 );
}

const Gaffer::PathMatcherDataPlug *PathFilter::pathMatcherPlug() const
{
	return getChild<PathMatcherDataPlug>( g_firstPlugIndex + 2 );
}

Gaffer::IntVectorDataPlug *PathFilter::rootSizesPlug()
{
	return getChild<IntVectorDataPlug>( g_firstPlugIndex + 3 );
}

const Gaffer::IntVectorDataPlug *PathFilter::rootSizesPlug() const
{
	return getChild<IntVectorDataPlug>( g_firstPlugIndex + 3 );
}

void PathFilter::plugDirtied( const Gaffer::Plug *plug )
{
	if( plug == pathsPlug() )
	{
		//\todo: share this logic with Switch::variesWithContext()
		Plug* sourcePlug = pathsPlug()->source();
		if( sourcePlug->direction() == Plug::Out && IECore::runTimeCast<const ComputeNode>( sourcePlug->node() ) )
		{
			// pathsPlug() is receiving data from a plug whose value is context varying, meaning
			// we need to use the intermediate pathMatcherPlug() in computeMatch() instead:

			m_pathMatcher = nullptr;
		}
		else
		{
			// pathsPlug() value is not context varying, meaning we can save on graph evaluations
			// by just precomputing it here and directly using it in computeMatch():

			ConstStringVectorDataPtr paths = pathsPlug()->getValue();
			m_pathMatcher = new PathMatcherData;
			m_pathMatcher->writable().init( paths->readable().begin(), paths->readable().end() );
		}
	}
}

void PathFilter::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const
{
	Filter::affects( input, outputs );

	if( input == pathsPlug() )
	{
		outputs.push_back( pathMatcherPlug() );
	}
	else if( input == rootsPlug() )
	{
		outputs.push_back( rootSizesPlug() );
	}
	else if( input == pathMatcherPlug() || input == rootSizesPlug() )
	{
		outputs.push_back( outPlug() );
	}

	if( input->parent<ScenePlug>() )
	{
		rootsPlug()->sceneAffects( input, outputs );
	}
}

void PathFilter::hash( const Gaffer::ValuePlug *output, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	Filter::hash( output, context, h );

	if( output == pathMatcherPlug() )
	{
		pathsPlug()->hash( h );
	}
	else if( output == rootSizesPlug() )
	{
		hashRootSizes( context, h );
	}
}

void PathFilter::compute( Gaffer::ValuePlug *output, const Gaffer::Context *context ) const
{
	if( output == pathMatcherPlug() )
	{
		ConstStringVectorDataPtr paths = pathsPlug()->getValue();
		PathMatcherDataPtr pathMatcherData = new PathMatcherData;
		pathMatcherData->writable().init( paths->readable().begin(), paths->readable().end() );
		static_cast<PathMatcherDataPlug *>( output )->setValue( pathMatcherData );
		return;
	}
	else if( output == rootSizesPlug() )
	{
		static_cast<IntVectorDataPlug *>( output )->setValue( computeRootSizes( context ) );
		return;
	}

	Filter::compute( output, context );
}

void PathFilter::hashMatch( const ScenePlug *scene, const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	const ScenePlug::ScenePath *path = context->getIfExists<ScenePlug::ScenePath>( ScenePlug::scenePathContextName );

	if( !path )
	{
		// This is a special case used by the Prune and Isolate nodes
		// to request a hash representing the effects of the filter
		// across the entire scene. Although it duplicates some logic
		// from the case below it is deliberately kept separate to
		// emphasise its different role. Ideally we would separate this
		// out into a specific query of some sort.
		if( rootsPlug()->getInput() )
		{
			rootsPlug()->hash( h );
		}
		if( m_pathMatcher )
		{
			m_pathMatcher->hash( h );
		}
		else
		{
			ScenePlug::GlobalScope globalScope( context );
			pathMatcherPlug()->hash( h );
		}
		return;
	}

	// Standard case

	h.append( path->data(), path->size() );

	if( m_pathMatcher )
	{
		m_pathMatcher->hash( h );
	}
	else
	{
		ScenePlug::GlobalScope globalScope( context );
		pathMatcherPlug()->hash( h );
	}

	if( rootsPlug()->getInput() )
	{
		rootSizesPlug()->hash( h );
	}
}

unsigned PathFilter::computeMatch( const ScenePlug *scene, const Gaffer::Context *context ) const
{
	const ScenePlug::ScenePath &path = context->get<ScenePlug::ScenePath>( ScenePlug::scenePathContextName );

	ConstPathMatcherDataPtr pathMatcherData;
	if( !m_pathMatcher )
	{
		ScenePlug::GlobalScope globalScope( context );
		pathMatcherData = pathMatcherPlug()->getValue();
	}
	const PathMatcher &pathMatcher = pathMatcherData ? pathMatcherData->readable() : m_pathMatcher->readable();

	if( !rootsPlug()->getInput() )
	{
		return pathMatcher.match( path );
	}

	ConstIntVectorDataPtr rootSizes = rootSizesPlug()->getValue();
	ScenePlug::ScenePath relativePath = path;
	unsigned result = PathMatcher::NoMatch;

	size_t previousRootSize = 0;
	for( const int rootSize : rootSizes->readable() )
	{
		if( rootSize == g_descendantRoots )
		{
			if( !pathMatcher.isEmpty() )
			{
				result |= PathMatcher::DescendantMatch;
			}
			break;
		}
		relativePath.erase( relativePath.begin(), relativePath.begin() + rootSize - previousRootSize );
		result |= pathMatcher.match( relativePath );
		previousRootSize = rootSize;
	}

	return result;
}

void PathFilter::hashRootSizes( const Gaffer::Context *context, IECore::MurmurHash &h ) const
{
	const ScenePlug::ScenePath &path = context->get<ScenePlug::ScenePath>( ScenePlug::scenePathContextName );
	if( path.size() )
	{
		ScenePlug::ScenePath parentPath( path.begin(), path.begin() + path.size() - 1 );
		ScenePlug::PathScope parentScope( context, &parentPath );
		rootSizesPlug()->hash( h );
	}
	rootsPlug()->hash( h );
	h.append( (uint64_t)path.size() );
}

ConstIntVectorDataPtr PathFilter::computeRootSizes( const Gaffer::Context *context ) const
{
	const ScenePlug::ScenePath &path = context->get<ScenePlug::ScenePath>( ScenePlug::scenePathContextName );

	// Start with the root sizes from our parent.

	ConstIntVectorDataPtr parentRootSizes;
	if( path.size() )
	{
		ScenePlug::ScenePath parentPath( path.begin(), path.begin() + path.size() - 1 );
		ScenePlug::PathScope parentScope( context, &parentPath );
		parentRootSizes = rootSizesPlug()->getValue();
		// If the parent has no descendant roots, then we already have
		// all the roots we need.
		if( !parentRootSizes->readable().size() || parentRootSizes->readable().back() != g_descendantRoots )
		{
			return parentRootSizes;
		}
	}

	// Then figure out if there is a new root here,
	// and if there are still any descendant roots.

	const unsigned m = rootsPlug()->getValue();

	IntVectorDataPtr resultData = new IntVectorData();
	auto &result = resultData->writable();
	if( parentRootSizes )
	{
		result = parentRootSizes->readable();
		assert( result.back() == g_descendantRoots );
		result.pop_back();
	}

	if( m & PathMatcher::ExactMatch )
	{
		result.push_back( path.size() );
	}

	if( m & PathMatcher::DescendantMatch )
	{
		result.push_back( g_descendantRoots );
	}

	return resultData;
}


text:
package org.apache.tinkerpop.gremlin.groovy.jsr223.customizer;

import org.apache.tinkerpop.gremlin.groovy.CompilerCustomizerProvider;
import org.apache.tinkerpop.gremlin.structure.util.ElementHelper;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.customizers.CompilationCustomizer;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Allows configurations to be directly supplied to a groovy {@code CompilerConfiguration} when a
 * {@link org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine} is initialized, providing fine-grained
 * control over its internals.
 *
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class ConfigurationCustomizerProvider implements CompilerCustomizerProvider {

    private final Map<String,Object> properties;

    /**
     * Creates a new instance using configuration values specified
     */
    public ConfigurationCustomizerProvider(final Object... keyValues) {
        if (null == keyValues || keyValues.length == 0)
            throw new IllegalArgumentException("ConfigurationCustomizerProvider must have key/values specified");

        if (keyValues.length % 2 != 0)
            throw new IllegalArgumentException("The keyValues must have an even number of values");

        properties = ElementHelper.asMap(keyValues);
    }

    /**
     * Creates a new instance using configuration values specified
     */
    public ConfigurationCustomizerProvider(final Map<String,Object> keyValues) {
        properties = keyValues;
    }

    public CompilerConfiguration applyCustomization(final CompilerConfiguration compilerConfiguration) {
        final Class<CompilerConfiguration> clazz = CompilerConfiguration.class;
        final List<Method> methods = Arrays.asList(clazz.getMethods());
        for (Map.Entry<String,Object> entry : properties.entrySet()) {
            final Method method = methods.stream().filter(m -> m.getName().equals("set" + entry.getKey())).findFirst()
                   .orElseThrow(() -> new IllegalStateException("Invalid setting [" + entry.getKey() + "] for CompilerConfiguration"));

            try {
                method.invoke(compilerConfiguration, entry.getValue());
            } catch (Exception ex) {
                throw new IllegalStateException(ex);
            }
        }

        return compilerConfiguration;
    }

    @Override
    public CompilationCustomizer create() {
        throw new UnsupportedOperationException("This is a marker implementation that does not create a CompilationCustomizer instance");
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="IdProvider" IDEtalkID="C8D1F16365CE397C681671A04B388A3B" />
  <component name="ProjectRootManager" version="2" languageLevel="JDK_1_6" assert-keyword="true" jdk-15="true" project-jdk-name="GHC 7.6.3" project-jdk-type="GHC">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>


text:
/* (c) Atinea Sp z o. o.
 *  Stamp: nianio lang
 */
#pragma once
#include "c_rt_lib.h"
void generator_js0__const__init();
ImmT generator_js0generate(ImmT ___nl__0,ImmT ___nl__1);
ImmT generator_js0generate0ptr(int _num, ImmT *_tab);


text:
#pragma once
#include <aws/lightsail/Lightsail_EXPORTS.h>
#include <aws/lightsail/LightsailRequest.h>
#include <aws/lightsail/model/PortInfo.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Lightsail
{
namespace Model
{

  /**
   */
  class AWS_LIGHTSAIL_API CloseInstancePublicPortsRequest : public LightsailRequest
  {
  public:
    CloseInstancePublicPortsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "CloseInstancePublicPorts"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
An object to describe the ports to close for the specified instance.

     */
    inline const PortInfo& GetPortInfo() const{ return m_portInfo; }

    /**
     *
An object to describe the ports to close for the specified instance.

     */
    inline bool PortInfoHasBeenSet() const { return m_portInfoHasBeenSet; }

    /**
     *
An object to describe the ports to close for the specified instance.

     */
    inline void SetPortInfo(const PortInfo& value) { m_portInfoHasBeenSet = true; m_portInfo = value; }

    /**
     *
An object to describe the ports to close for the specified instance.

     */
    inline void SetPortInfo(PortInfo&& value) { m_portInfoHasBeenSet = true; m_portInfo = std::move(value); }

    /**
     *
An object to describe the ports to close for the specified instance.

     */
    inline CloseInstancePublicPortsRequest& WithPortInfo(const PortInfo& value) { SetPortInfo(value); return *this;}

    /**
     *
An object to describe the ports to close for the specified instance.

     */
    inline CloseInstancePublicPortsRequest& WithPortInfo(PortInfo&& value) { SetPortInfo(std::move(value)); return *this;}

    /**
     *
The name of the instance for which to close ports.

     */
    inline const Aws::String& GetInstanceName() const{ return m_instanceName; }

    /**
     *
The name of the instance for which to close ports.

     */
    inline bool InstanceNameHasBeenSet() const { return m_instanceNameHasBeenSet; }

    /**
     *
The name of the instance for which to close ports.

     */
    inline void SetInstanceName(const Aws::String& value) { m_instanceNameHasBeenSet = true; m_instanceName = value; }

    /**
     *
The name of the instance for which to close ports.

     */
    inline void SetInstanceName(Aws::String&& value) { m_instanceNameHasBeenSet = true; m_instanceName = std::move(value); }

    /**
     *
The name of the instance for which to close ports.

     */
    inline void SetInstanceName(const char* value) { m_instanceNameHasBeenSet = true; m_instanceName.assign(value); }

    /**
     *
The name of the instance for which to close ports.

     */
    inline CloseInstancePublicPortsRequest& WithInstanceName(const Aws::String& value) { SetInstanceName(value); return *this;}

    /**
     *
The name of the instance for which to close ports.

     */
    inline CloseInstancePublicPortsRequest& WithInstanceName(Aws::String&& value) { SetInstanceName(std::move(value)); return *this;}

    /**
     *
The name of the instance for which to close ports.

     */
    inline CloseInstancePublicPortsRequest& WithInstanceName(const char* value) { SetInstanceName(value); return *this;}

  private:

    PortInfo m_portInfo;
    bool m_portInfoHasBeenSet = false;

    Aws::String m_instanceName;
    bool m_instanceNameHasBeenSet = false;
  };

} // namespace Model
} // namespace Lightsail
} // namespace Aws


text: ERB but worse.


text:
title: 'Starbursts'
excerpt: 'Logo for a kids soccer team'
coverImage: '/assets/blog/starbursts/cover.jpg'
date: '2022-08-15T05:35:07.322Z'
author:
  name: Stuart Tett
  picture: '/assets/blog/authors/stuart.jpg'
ogImage:
  url: '/assets/blog/starbursts/cover.jpg'
imagesOnly: true
---


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package estructurasdedatos.cap2.arreglos;

/**
 *
 * @author tusk
 */
public class Matriz {

    int tFilas =3;
    int tColumnas = 3;
    int [][] matriz;

    public Matriz(int nFilas, int nColumnas) {
        this.tColumnas = nColumnas;
        this.tFilas = nFilas;
        this.matriz = new int [nFilas][nColumnas];
    }
    // Se utiliza la metodologia CRUD
    //CRUD: Insertar
    public void insertar (int Fila, int Columna, int dato){

        if (tFilas< Fila || tColumnas < Columna){

            System.out.println("ERROR: Nuemro no correcto");

        }else {
            this.matriz[Fila][Columna]= dato;
        }
    }   //CRUD: Listar
    public void listar (){

        for (int i = 0; i<tFilas; i++){
            for (int j = 0;j<=tColumnas;j++){
                System.out.println(this.matriz[i][j]);
            }
        }
    } //CRUD: Buscar
    public int buscar (int Fila,int Columna){

        if (tFilas<Fila || tColumnas<Columna || Fila < 0 || Columna < 0){
            System.out.println("ERROR: Dato no es correcto");
        }else{
            return this.matriz[Fila][Columna];
        }
        return 0;
    } //CRUD: Actualizar
    public int actualizar (int dato, int Fila,int Columna){

        if (tFilas<Fila || tColumnas<Columna || Fila < 0 || Columna < 0){

            System.out.println("ERROR: Dato no es correcto");
        }else{
            this.matriz[Fila][Columna]= dato;
        }
        return 0;
    } //CRUD: Eliminar
    public void eliminar (int Fila,int Columna){

        if (Fila>tFilas || Columna> tColumnas || Fila<0 || Columna<0){

                    System.out.println("ERROR: Dato no es correcto");
        }else{
            this.matriz[Fila][Columna]= 0;
            }
    }
}


text:
AC.Controller = function() {

	var
		eventHandlers = [],

		currentView = null,

		loadingView = null,
		homeView = null,
		portfolioView = null,
		aboutView = null,
		newsView = null,
		contactView = null,

		/*
		 * init
		 * @private
		 */
		init = function() {

			_initEventHandlers();
			_initNav();
			_initLang();
			_initModal();

			if ( Modernizr.touch )
				_initMobile();
		},

		/*
		 * init event handler
		 * @private
		 */
		_initEventHandlers = function() {

			_.each( AC.Events, function(customEvent) {
				eventHandlers[customEvent] = _show;
			});

			AC.EventManager.bind(eventHandlers);
		},

		/*
		 * init navigation links
		 * @private
		 */
		_initNav = function() {

			$("body").delegate('a[rel=nav], nav a:not(.external), .mobile-nav a:not(.open)', "click", function(e){
				e.preventDefault();

				if ( Modernizr.touch ) $("html").removeClass("show-menu");
				AC.AppRouter.navigate($(this).attr("href"), true);
			});
		},

		/*
		 * init language links
		 * @private
		 */
		_initLang = function() {

			$('.lang').on("click", function(e){
				e.preventDefault();

				AC.Lang = $(this).data("lang");
				AC.Utils.eraseCookie("acm_lang");
				AC.Utils.createCookie("acm_lang", AC.Lang, 365);
				window.location.reload();
			});
		},

		/*
		 * init modal boxes
		 * @private
		 */
		_initModal = function () {

			// console.log("init modal");

			$("body").delegate('[rel=modal]', "click", function(e){
				e.preventDefault();
				$($(this).attr("href")).modal({
					overlayClose : true,
					opacity : 60
				});
			});
		},

		/*
		 * init modal boxes
		 * @private
		 */
		_initMobile = function () {

			$(".open").on("click", function(e){
				e.preventDefault();
				$("html").toggleClass("show-menu");
			});
		},

		/*
		 * display Page
		 * @private
		 */
		displayPage = function ( callbackEvent, hideFirst, urlData ) {

			var fragment = Backbone.history.fragment.split("/")[0];
			$("nav .selected, .mobile-nav .selected").removeClass("selected");
			$("nav a[href='/" + fragment + "'], .mobile-nav a[href='/" + fragment + "']").addClass("selected");

			if ( currentView && hideFirst ) {

				currentView.hide( function() {
					displayPage(callbackEvent, false, urlData);

					if ( !_.isUndefined(_gaq) ) {
						_gaq.push(['_trackPageview', '/'+Backbone.history.fragment ]);
					}
				});

			} else {

				AC.EventManager.trigger( AC.Events.APP_LOADING );
				AC.DataManager.check( callbackEvent, urlData );
			}
		},

		/*
		 * show the page
		 * @private
		 */
		_show = function ( e, urlData ) {

			var view;

			switch ( e.type ) {

				case AC.Events.APP_LOADING :
					if ( !loadingView ) loadingView = new AC.View.Loading();
					view = loadingView;
				break;

				case AC.Events.SHOW_HOME :
					if ( !homeView ) {
						homeView = new AC.View.Home();
					}
					view = homeView;
				break;

				case AC.Events.SHOW_ABOUT :
					if ( !aboutView ) {
						aboutView = new AC.View.About();
					}
					view = aboutView;
				break;

				case AC.Events.SHOW_PORTFOLIO :
					if ( !portfolioView ) {
						portfolioView = new AC.View.Portfolio();
					}
					portfolioView.update(urlData.slug, urlData.imgIndex );
					view = portfolioView;
				break;

				case AC.Events.SHOW_CONTACT :
					if ( !contactView ) {
						contactView = new AC.View.Contact();
					}
					view = contactView;
				break;

				case AC.Events.SHOW_NEWS :
					if ( !newsView ) {
						newsView = new AC.View.News();
					}
					view = newsView;
				break;

			}

			view.render();
			currentView = view;
		};

	init();
	return {
		displayPage : displayPage
	};
};


text:
using System.Collections.Generic;

namespace CPFT.CremulParser.Cremul
{
    public class Message
    {
        public int MessageIndex { get; set; }
        public CremulHeader Header { get; set; }
        public List<Line> Lines { get; set; }
        public int NumberOfLines { get; set; }

        public Message(int messageNumber, string[] segments, ParserHelper helper)
        {
            MessageIndex = messageNumber;
            Header = new CremulHeader(segments, helper);
            Lines = new List<Line>();
            NumberOfLines = helper.number_of_lines_in_message(segments);
            var lineSegmentPos = helper.next_line_segment_index(segments, 0);
            for (int i = 0; i < NumberOfLines; i++)
            {
                Lines.Add(new Line(i + 1, segments, lineSegmentPos, helper));
                lineSegmentPos = helper.next_line_segment_index(segments, lineSegmentPos + 1);
            }
        }
    }
}


text:
package org.jbehave.example.spring.security.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.SessionFactory;
import org.jbehave.example.spring.security.domain.Organization;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("organizationDao")
public class OrganizationDaoImpl implements OrganizationDao {

  @Autowired
  private SessionFactory sessionFactory;

  @Override
  @Transactional
  public Organization load(Long id) {
    return (Organization) sessionFactory.getCurrentSession().load(Organization.class, id);
  }

  @Override
  @Transactional
  public Organization persist(Organization organization) {
    sessionFactory.getCurrentSession().saveOrUpdate(organization);
    return organization;
  }

  @Override
  @SuppressWarnings("unchecked")
  @Transactional
  public Organization findByName(String orgName) {
    List<Organization> query = sessionFactory.getCurrentSession()
            .createQuery("from Organization where name = :name")
		    .setParameter("name", orgName)
            .list();
    if (query.size() == 1) {
      return query.get(0);
    }
    return null;
  }

}


text:
require 'cheffish'
require 'chef/resource/lwrp_base'
require 'chef/run_list/run_list_item'

class Chef
  class Resource
    class ChefGroup < Chef::Resource::LWRPBase
      self.resource_name = 'chef_group'

      actions :create, :delete, :nothing
      default_action :create

      # Grab environment from with_environment
      def initialize(*args)
        super
        chef_server run_context.cheffish.current_chef_server
        @users = []
        @clients = []
        @groups = []
        @remove_users = []
        @remove_clients = []
        @remove_groups = []
      end

      attribute :name, :kind_of => String, :regex => Cheffish::NAME_REGEX, :name_attribute => true
      def users(*users)
        users.size == 0 ? @users : (@users |= users.flatten)
      end
      def clients(*clients)
        clients.size == 0 ? @clients : (@clients |= clients.flatten)
      end
      def groups(*groups)
        groups.size == 0 ? @groups : (@groups |= groups.flatten)
      end
      def remove_users(*remove_users)
        remove_users.size == 0 ? @remove_users : (@remove_users |= remove_users.flatten)
      end
      def remove_clients(*remove_clients)
        remove_clients.size == 0 ? @remove_clients : (@remove_clients |= remove_clients.flatten)
      end
      def remove_groups(*remove_groups)
        remove_groups.size == 0 ? @remove_groups : (@remove_groups |= remove_groups.flatten)
      end

      # Specifies that this is a complete specification for the environment (i.e. attributes you don't specify will be
      # reset to their defaults)
      attribute :complete, :kind_of => [TrueClass, FalseClass]

      attribute :raw_json, :kind_of => Hash
      attribute :chef_server, :kind_of => Hash
    end
  end
end


text:
var EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  var envConfig = require('./config/environment')(process.env.EMBER_ENV);

  var options = {
    fingerprint: {
      exclude: ['teams-logo', 'leagues-logo'],
      enabled: envConfig.APP.fingerprintEnabled || false
    },
    sassOptions: {
      includePaths: ['bower_components/materialize/sass']
    },
    dotEnv: {
      clientAllowedKeys: ['APP_HOSTNAME', 'NEW_RELIC_LICENSE_KEY', 'NEW_RELIC_APPLICATION_ID'],
      path: '../../.env'
    }
  };

  var app = new EmberApp(defaults, options);

  if (process.env.NEW_RELIC_BROWSER_LICENSE_KEY && process.env.NEW_RELIC_BROWSER_APPLICATION_ID) {
    app.options['inlineContent'] = {
      'new-relic': {
        file: './new-relic.js',
        postProcess: function (content) {
          return content
            .replace(/\{\{NEW_RELIC_BROWSER_LICENSE_KEY\}\}/g, process.env.NEW_RELIC_BROWSER_LICENSE_KEY)
            .replace(/\{\{NEW_RELIC_BROWSER_APPLICATION_ID\}\}/g, process.env.NEW_RELIC_BROWSER_APPLICATION_ID);
        }
      }
    }
  }

  return app.toTree();
};


text:
package appmanager

import (
	"bytes"
	"fmt"
	"net/url"
	"reflect"
	"sort"
	"strconv"
	"strings"
	"sync"

	log "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger"

	routeapi "github.com/openshift/origin/pkg/route/api"
	"k8s.io/client-go/pkg/apis/extensions/v1beta1"
)

const httpRedirectIRuleName = "http_redirect_irule"
const abDeploymentPathIRuleName = "ab_deployment_path_irule"
const sslPassthroughIRuleName = "openshift_passthrough_irule"

// Internal data group for passthrough routes to map server names to pools.
const passthroughHostsDgName = "ssl_passthrough_servername_dg"

// Internal data group for reencrypt routes.
const reencryptHostsDgName = "ssl_reencrypt_servername_dg"

// Internal data group for reencrypt routes that maps the host name to the
// server ssl profile.
const reencryptServerSslDgName = "ssl_reencrypt_serverssl_dg"

// Internal data group for https redirect
const httpsRedirectDgName = "https_redirect_dg"

// Internal data group for ab deployment routes.
const abDeploymentDgName = "ab_deployment_dg"

// DataGroup flattening.
type FlattenConflictFunc func(key, oldVal, newVal string) string

var groupFlattenFuncMap = map[string]FlattenConflictFunc{
	passthroughHostsDgName:   flattenConflictWarn,
	reencryptHostsDgName:     flattenConflictWarn,
	reencryptServerSslDgName: flattenConflictWarn,
	httpsRedirectDgName:      flattenConflictConcat,
	abDeploymentDgName:       flattenConflictConcat,
}

func (r Rules) Len() int { return len(r) }
func (r Rules) Less(i, j int) bool {
	iApprootRedirect := strings.Contains(r[i].Name, "app-root-redirect-rule")
	iApprootForward := strings.Contains(r[i].Name, "app-root-forward-rule")
	iUrlrewrite := strings.Contains(r[i].Name, "url-rewrite-rule")

	jApprootRedirect := strings.Contains(r[j].Name, "app-root-redirect-rule")
	jApprootForward := strings.Contains(r[j].Name, "app-root-forward-rule")
	jUrlrewrite := strings.Contains(r[j].Name, "url-rewrite-rule")

	if iApprootRedirect && !jApprootRedirect {
		return false
	}
	if !iApprootRedirect && jApprootRedirect {
		return true
	}
	if iApprootForward && !jApprootForward {
		return false
	}
	if !iApprootForward && jApprootForward {
		return true
	}
	if iUrlrewrite && !jUrlrewrite {
		return false
	}
	if !iUrlrewrite && jUrlrewrite {
		return true
	}

	if r[i].FullURI == r[j].FullURI {
		if len(r[j].Actions) > 0 && r[j].Actions[0].Reset {
			return false
		}
		return true
	}

	return r[i].FullURI < r[j].FullURI
}
func (r Rules) Swap(i, j int) {
	r[i], r[j] = r[j], r[i]
	r[i].Ordinal = i
	r[j].Ordinal = j
}

type Routes []*routeapi.Route

func createPathSegmentConditions(u *url.URL) []*condition {
	var c []*condition
	path := strings.TrimPrefix(u.EscapedPath(), "/")
	segments := strings.Split(path, "/")
	for i, v := range segments {
		c = append(c, &condition{
			Equals:      true,
			HTTPURI:     true,
			PathSegment: true,
			Name:        strconv.Itoa(i + 1),
			Index:       i + 1,
			Request:     true,
			Values:      []string{v},
		})
	}
	return c
}

func createRule(uri, poolName, partition, ruleName string) (*Rule, error) {
	_u := "scheme://" + uri
	_u = strings.TrimSuffix(_u, "/")
	u, err := url.Parse(_u)
	if nil != err {
		return nil, err
	}
	var b bytes.Buffer
	b.WriteRune('/')
	b.WriteString(partition)
	b.WriteRune('/')
	b.WriteString(poolName)

	a := action{
		Forward: true,
		Name:    "0",
		Pool:    b.String(),
		Request: true,
	}

	var c []*condition
	if true == strings.HasPrefix(uri, "*.") {
		c = append(c, &condition{
			EndsWith: true,
			Host:     true,
			HTTPHost: true,
			Name:     "0",
			Index:    0,
			Request:  true,
			Values:   []string{strings.TrimPrefix(u.Host, "*")},
		})
	} else if u.Host != "" {
		c = append(c, &condition{
			Equals:   true,
			Host:     true,
			HTTPHost: true,
			Name:     "0",
			Index:    0,
			Request:  true,
			Values:   []string{u.Host},
		})
	}
	if 0 != len(u.EscapedPath()) {
		c = append(c, createPathSegmentConditions(u)...)
	}

	rl := Rule{
		Name:       ruleName,
		FullURI:    uri,
		Actions:    []*action{&a},
		Conditions: c,
	}

	log.Debugf("Configured rule: %v", rl)
	return &rl, nil
}

func createPolicy(rls Rules, policyName, partition string) *Policy {
	plcy := Policy{
		Controls:  []string{"forwarding"},
		Legacy:    true,
		Name:      policyName,
		Partition: partition,
		Requires:  []string{"http"},
		Rules:     Rules{},
		Strategy:  "/Common/first-match",
	}

	plcy.Rules = rls

	// Check for the existence of the TCP field in the conditions.
	// This would indicate that a whitelist rule is in the policy
	// and that we need to add the "tcp" requirement to the policy.
	requiresTcp := false
	for _, x := range rls {
		for _, c := range x.Conditions {
			if c.Tcp == true {
				requiresTcp = true
			}
		}
	}

	// Add the tcp requirement if needed; indicated by the presence
	// of the TCP field.
	if requiresTcp {
		plcy.Requires = append(plcy.Requires, "tcp")
	}

	log.Debugf("Configured policy: %v", plcy)
	return &plcy
}

func processIngressRules(
	ing *v1beta1.IngressSpec,
	urlRewriteMap map[string]string,
	whitelistSourceRanges []string,
	appRootMap map[string]string,
	pools []Pool,
	partition string,
) (*Rules, map[string]string, map[string][]string) {
	var err error
	var uri, poolName string
	var rl *Rule
	var urlRewriteRules []*Rule
	var appRootRules []*Rule

	rlMap := make(ruleMap)
	wildcards := make(ruleMap)
	urlRewriteRefs := make(map[string]string)
	appRootRefs := make(map[string][]string)

	for _, rule := range ing.Rules {
		if nil != rule.IngressRuleValue.HTTP {
			for _, path := range rule.IngressRuleValue.HTTP.Paths {
				uri = rule.Host + path.Path
				for _, pool := range pools {
					if path.Backend.ServiceName == pool.ServiceName {
						poolName = pool.Name
					}
				}
				if poolName == "" {
					continue
				}
				ruleName := formatIngressRuleName(rule.Host, path.Path, poolName)
				// This blank name gets overridden by an ordinal later on
				rl, err = createRule(uri, poolName, partition, ruleName)
				if nil != err {
					log.Warningf("Error configuring rule: %v", err)
					return nil, nil, nil
				}
				if true == strings.HasPrefix(uri, "*.") {
					wildcards[uri] = rl
				} else {
					rlMap[uri] = rl
				}

				// Process url-rewrite annotation
				if urlRewriteTargetedVal, ok := urlRewriteMap[uri]; ok == true {
					urlRewriteRule := processURLRewrite(uri, urlRewriteTargetedVal, multiServiceIngressType)
					urlRewriteRules = append(urlRewriteRules, urlRewriteRule)
					urlRewriteRefs[poolName] = urlRewriteRule.Name
				}

				// Process app-root annotation
				if appRootTargetedVal, ok := appRootMap[rule.Host]; ok == true {
					appRootRulePair := processAppRoot(uri, appRootTargetedVal, fmt.Sprintf("/%s/%s", partition, poolName), multiServiceIngressType)
					appRootRules = append(appRootRules, appRootRulePair...)
					if len(appRootRulePair) == 2 {
						appRootRefs[poolName] = append(appRootRefs[poolName], appRootRulePair[0].Name)
						appRootRefs[poolName] = append(appRootRefs[poolName], appRootRulePair[1].Name)
					}
				}
				poolName = ""
			}
		}
	}

	var wg sync.WaitGroup
	wg.Add(2)
	sortrules := func(r ruleMap, rls *Rules, ordinal int) {
		for _, v := range r {
			*rls = append(*rls, v)
		}
		sort.Sort(sort.Reverse(*rls))
		for _, v := range *rls {
			v.Ordinal = ordinal
			ordinal++
		}
		wg.Done()
	}

	rls := Rules{}
	go sortrules(rlMap, &rls, 0)

	w := Rules{}
	go sortrules(wildcards, &w, len(rlMap))

	wg.Wait()

	rls = append(rls, w...)

	if len(appRootRules) != 0 {
		rls = append(rls, appRootRules...)
	}
	if len(urlRewriteRules) != 0 {
		rls = append(rls, urlRewriteRules...)
	}

	if len(whitelistSourceRanges) != 0 {
		// Add whitelist entries to each rule.
		//
		// Whitelist rules are added as other conditions on the rule so that
		// the whitelist is actually enforced. The whitelist entries cannot
		// be separate rules because of the matching strategy that is used.
		//
		// The matching strategy used is first-match. Therefore, if the
		// whitelist were a separate rule, and they did not match, then
		// further rules will be processed and this is not what the function
		// of a whitelist should be.
		//
		// Whitelists should be used to *prevent* access. So they need to be
		// a separate condition of *each* rule.
		for _, x := range rls {
			cond := condition{
				Tcp:     true,
				Address: true,
				Matches: true,
				Name:    "0",
				Values:  whitelistSourceRanges,
			}
			x.Conditions = append(x.Conditions, &cond)
		}
	}

	return &rls, urlRewriteRefs, appRootRefs
}

func httpRedirectIRule(port int32) string {
	// The key in the data group is the host name or * to match all.
	// The data is a list of paths for the host delimited by '|' or '/' for all.
	iRuleCode := fmt.Sprintf(`
		when HTTP_REQUEST {
			# Look for exact match for host name
			set paths [class match -value [HTTP::host] equals https_redirect_dg]
			if {$paths == ""} {
				# See if there's an entry that matches all hosts
				set paths [class match -value "*" equals https_redirect_dg]
			}
			if {$paths != ""} {
				set redir 0
				foreach s [split $paths "|"] {
					# See if the request path starts with the prefix
					append prefix "^" $s "($|/)"
					if {[HTTP::path] matches_regex $prefix} {
						set redir 1
						break
					}
				}
				if {$redir == 1} {
					HTTP::redirect https://[getfield [HTTP::host] ":" 1]:%d[HTTP::uri]
				}
			}
		}`, port)

	return iRuleCode
}

func selectPoolIRuleFunc() string {
	iRuleFunc := fmt.Sprintf(`
		proc select_ab_pool {path default_pool } {
			set last_slash [string length $path]
			set ab_class "/%s/ab_deployment_dg"
			while {$last_slash >= 0} {
				if {[class match $path equals $ab_class]} then {
					break
				}
				set last_slash [string last "/" $path $last_slash]
				incr last_slash -1
				set path [string range $path 0 $last_slash]
			}

			if {$last_slash >= 0} {
				set ab_rule [class match -value $path equals $ab_class]
				if {$ab_rule != ""} then {
					set weight_selection [expr {rand()}]
					set service_rules [split $ab_rule ";"]
					foreach service_rule $service_rules {
						set fields [split $service_rule ","]
						set pool_name [lindex $fields 0]
						set weight [expr {double([lindex $fields 1])}]
						if {$weight_selection <= $weight} then {
							return $pool_name
						}
					}
				}
				# If we had a match, but all weights were 0 then
				# retrun a 503 (Service Unavailable)
				HTTP::respond 503
			}
			return $default_pool
		}`, DEFAULT_PARTITION)

	return iRuleFunc
}

func abDeploymentPathIRule() string {
	// For all A/B deployments that include a path.
	// The key in the data group is the specific route (host/path) to examine.
	// The data is a list of pool/weight pairs delimited by ';'. The pair values
	// are delineated by ','. Finally, the weight value is normalized between
	// 0.0 and 1.0 and the pairs should be listed in ascending order or weight
	// values.
	iRuleCode := fmt.Sprintf("%s\n\n%s", selectPoolIRuleFunc(), `
		when HTTP_REQUEST priority 200 {
			set path [string tolower [HTTP::host]][HTTP::path]
			set selected_pool [call select_ab_pool $path ""]
			if {$selected_pool != ""} then {
				pool $selected_pool
				event disable
			}
		}`)

	return iRuleCode
}

func sslPassthroughIRule() string {
	iRule := fmt.Sprintf(`
		when CLIENT_ACCEPTED {
			TCP::collect
		}

		when CLIENT_DATA {
			# Byte 0 is the content type.
			# Bytes 1-2 are the TLS version.
			# Bytes 3-4 are the TLS payload length.
			# Bytes 5-$tls_payload_len are the TLS payload.
			binary scan [TCP::payload] cSS tls_content_type tls_version tls_payload_len

			switch $tls_version {
				"769" -
				"770" -
				"771" {
					# Content type of 22 indicates the TLS payload contains a handshake.
					if { $tls_content_type == 22 } {
						# Byte 5 (the first byte of the handshake) indicates the handshake
						# record type, and a value of 1 signifies that the handshake record is
						# a ClientHello.
						binary scan [TCP::payload] @5c tls_handshake_record_type
						if { $tls_handshake_record_type == 1 } {
							# Bytes 6-8 are the handshake length (which we ignore).
							# Bytes 9-10 are the TLS version (which we ignore).
							# Bytes 11-42 are random data (which we ignore).

							# Byte 43 is the session ID length.  Following this are three
							# variable-length fields which we shall skip over.
							set record_offset 43

							# Skip the session ID.
							binary scan [TCP::payload] @${record_offset}c tls_session_id_len
							incr record_offset [expr {1 + $tls_session_id_len}]

							# Skip the cipher_suites field.
							binary scan [TCP::payload] @${record_offset}S tls_cipher_suites_len
							incr record_offset [expr {2 + $tls_cipher_suites_len}]

							# Skip the compression_methods field.
							binary scan [TCP::payload] @${record_offset}c tls_compression_methods_len
							incr record_offset [expr {1 + $tls_compression_methods_len}]

							# Get the number of extensions, and store the extensions.
							binary scan [TCP::payload] @${record_offset}S tls_extensions_len
							incr record_offset 2
							binary scan [TCP::payload] @${record_offset}a* tls_extensions

							for { set extension_start 0 }
									{ $tls_extensions_len - $extension_start == abs($tls_extensions_len - $extension_start) }
									{ incr extension_start 4 } {
								# Bytes 0-1 of the extension are the extension type.
								# Bytes 2-3 of the extension are the extension length.
								binary scan $tls_extensions @${extension_start}SS extension_type extension_len

								# Extension type 00 is the ServerName extension.
								if { $extension_type == "00" } {
									# Bytes 4-5 of the extension are the SNI length (we ignore this).

									# Byte 6 of the extension is the SNI type.
									set sni_type_offset [expr {$extension_start + 6}]
									binary scan $tls_extensions @${sni_type_offset}S sni_type

									# Type 0 is host_name.
									if { $sni_type == "0" } {
										# Bytes 7-8 of the extension are the SNI data (host_name)
										# length.
										set sni_len_offset [expr {$extension_start + 7}]
										binary scan $tls_extensions @${sni_len_offset}S sni_len

										# Bytes 9-$sni_len are the SNI data (host_name).
										set sni_start [expr {$extension_start + 9}]
										binary scan $tls_extensions @${sni_start}A${sni_len} tls_servername
									}
								}

								incr extension_start $extension_len
							}

							if { [info exists tls_servername] } {
								set servername_lower [string tolower $tls_servername]
								SSL::disable serverside
								set dflt_pool ""
								set passthru_class "/%[1]s/ssl_passthrough_servername_dg"
								set reencrypt_class "/%[1]s/ssl_reencrypt_servername_dg"
								if { [class exists $passthru_class] } {
									set dflt_pool [class match -value $servername_lower equals $passthru_class]
									if { not ($dflt_pool equals "") } {
										SSL::disable
										HTTP::disable
									}
								}
								elseif { [class exists $reencrypt_class] } {
									set dflt_pool [class match -value $servername_lower equals $reencrypt_class]
									if { not ($dflt_pool equals "") } {
										SSL::enable serverside
									}
								}
								set ab_class "/%[1]s/ab_deployment_dg"
								if { not [class exists $ab_class] } {
									if { $dflt_pool == "" } then {
										log local0.debug "Failed to find pool for $servername_lower"
									} else {
										pool $dflt_pool
									}
								} else {
									set selected_pool [call select_ab_pool $servername_lower $dflt_pool]
									if { $selected_pool == "" } then {
										log local0.debug "Failed to find pool for $servername_lower"
									} else {
										pool $selected_pool
									}
								}
							}
						}
					}
				}
			}

			TCP::release
		}

		when SERVER_CONNECTED {
			set svrssl_class "/%[1]s/ssl_reencrypt_serverssl_dg"
			if { [class exists $svrssl_class] } {
				set profile [class match -value $servername_lower equals $svrssl_class]
				if { not ($profile equals "") } {
					SSL::profile $profile
				}
			}
		}`, DEFAULT_PARTITION)

	iRuleCode := fmt.Sprintf("%s\n\n%s", selectPoolIRuleFunc(), iRule)

	return iRuleCode
}

// Update a specific datagroup for passthrough routes, indicating if
// something had changed.
func (appMgr *Manager) updatePassthroughRouteDataGroups(
	partition string,
	namespace string,
	poolName string,
	hostName string,
) (bool, error) {

	changed := false
	key := nameRef{
		Name:      passthroughHostsDgName,
		Partition: partition,
	}

	appMgr.intDgMutex.Lock()
	defer appMgr.intDgMutex.Unlock()
	nsHostDg, found := appMgr.intDgMap[key]
	if false == found {
		return false, fmt.Errorf("Internal Data-group /%s/%s does not exist.",
			partition, passthroughHostsDgName)
	}

	hostDg, found := nsHostDg[namespace]
	if !found {
		hostDg = &InternalDataGroup{}
		nsHostDg[namespace] = hostDg
	}
	if hostDg.AddOrUpdateRecord(hostName, poolName) {
		changed = true
	}

	return changed, nil
}

// Update a data group map based on a passthrough route object.
func updateDataGroupForPassthroughRoute(
	route *routeapi.Route,
	partition string,
	namespace string,
	dgMap InternalDataGroupMap,
) {
	hostName := route.Spec.Host
	svcName := getRouteCanonicalServiceName(route)
	poolName := formatRoutePoolName(route.ObjectMeta.Namespace, svcName)
	updateDataGroup(dgMap, passthroughHostsDgName,
		partition, namespace, hostName, poolName)
}

// Update a data group map based on a reencrypt route object.
func updateDataGroupForReencryptRoute(
	route *routeapi.Route,
	partition string,
	namespace string,
	dgMap InternalDataGroupMap,
) {
	hostName := route.Spec.Host
	svcName := getRouteCanonicalServiceName(route)
	poolName := formatRoutePoolName(route.ObjectMeta.Namespace, svcName)
	updateDataGroup(dgMap, reencryptHostsDgName,
		partition, namespace, hostName, poolName)
}

// Update a data group map based on a alternativeBackends route object.
// (ignore an service with a 0 weight value)
func updateDataGroupForABRoute(
	route *routeapi.Route,
	svcName string,
	partition string,
	namespace string,
	dgMap InternalDataGroupMap,
) {
	if !isRouteABDeployment(route) {
		return
	}

	weightTotal := 0
	svcs := getRouteServices(route)
	for _, svc := range svcs {
		weightTotal = weightTotal + svc.weight
	}

	path := route.Spec.Path
	tls := route.Spec.TLS
	if tls != nil {
		// We don't support path-based A/B for pass-thru and re-encrypt
		switch tls.Termination {
		case routeapi.TLSTerminationPassthrough:
			path = ""
		case routeapi.TLSTerminationReencrypt:
			path = ""
		}
	}
	key := route.Spec.Host + path

	if weightTotal == 0 {
		// If all services have 0 weight, openshift requires a 503 to be returned
		// (see https://docs.openshift.com/container-platform/3.6/architecture
		//  /networking/routes.html#alternateBackends)
		updateDataGroup(dgMap, abDeploymentDgName, partition, namespace, key, "")
	} else {
		// Place each service in a segment between 0.0 and 1.0 that corresponds to
		// it's ratio percentage.  The order does not matter in regards to which
		// service is listed first, but the list must be in ascending order.
		var entries []string
		runningWeightTotal := 0
		for _, svc := range svcs {
			if svc.weight == 0 {
				continue
			}
			runningWeightTotal = runningWeightTotal + svc.weight
			weightedSliceThreshold := float64(runningWeightTotal) / float64(weightTotal)
			pool := formatRoutePoolName(route.ObjectMeta.Namespace, svc.name)
			entry := fmt.Sprintf("%s,%4.3f", pool, weightedSliceThreshold)
			entries = append(entries, entry)
		}
		value := strings.Join(entries, ";")
		updateDataGroup(dgMap, abDeploymentDgName,
			partition, namespace, key, value)
	}
}

// Add or update a data group record
func updateDataGroup(
	intDgMap InternalDataGroupMap,
	name string,
	partition string,
	namespace string,
	key string,
	value string,
) {
	mapKey := nameRef{
		Name:      name,
		Partition: partition,
	}
	nsDg, found := intDgMap[mapKey]
	if !found {
		nsDg = make(DataGroupNamespaceMap)
		intDgMap[mapKey] = nsDg
	}
	dg, found := nsDg[namespace]
	if found {
		dg.AddOrUpdateRecord(key, value)
	} else {
		newDg := InternalDataGroup{
			Name:      name,
			Partition: partition,
		}
		newDg.AddOrUpdateRecord(key, value)
		nsDg[namespace] = &newDg
	}
}

// Update the appMgr datagroup cache for routes, indicating if something
// had changed by updating 'stats', which should rewrite the config.
func (appMgr *Manager) syncDataGroups(
	stats *vsSyncStats,
	dgMap InternalDataGroupMap,
	namespace string,
) {
	appMgr.intDgMutex.Lock()
	defer appMgr.intDgMutex.Unlock()

	// Add new or modified data group records
	for mapKey, grp := range dgMap {
		nsDg, found := appMgr.intDgMap[mapKey]
		if found {
			if !reflect.DeepEqual(nsDg[namespace], grp[namespace]) {
				// current namespace records aren't equal
				nsDg[namespace] = grp[namespace]
				stats.dgUpdated += 1
			}
		} else {
			appMgr.intDgMap[mapKey] = grp
		}
	}

	// Remove non-existent data group records (those that are currently
	// defined, but aren't part of the new set)
	for mapKey, nsDg := range appMgr.intDgMap {
		_, found := dgMap[mapKey]
		if !found {
			_, found := nsDg[namespace]
			if found {
				delete(nsDg, namespace)
				if len(nsDg) == 0 {
					delete(appMgr.intDgMap, mapKey)
				}
				stats.dgUpdated += 1
			}
		}
	}
}

// Finds which IRules have no data groups for them
func (appMgr *Manager) syncIRules() {
	// Verify which data groups are still in use
	type iruleRef struct {
		https       bool
		ab          bool
		passthrough bool
		reencrypt   bool
	}
	var iRef iruleRef
	for mapKey, _ := range appMgr.intDgMap {
		switch mapKey.Name {
		case httpsRedirectDgName:
			iRef.https = true
		case abDeploymentDgName:
			iRef.ab = true
		case passthroughHostsDgName:
			iRef.passthrough = true
		case reencryptHostsDgName:
			iRef.reencrypt = true
		case reencryptServerSslDgName:
			iRef.reencrypt = true
		}
	}
	// Delete any IRules for datagroups that are gone
	if !iRef.https {
		// http redirect rule may have a port appended, so find it
		for irule, _ := range appMgr.irulesMap {
			if strings.HasPrefix(irule.Name, httpRedirectIRuleName) {
				appMgr.deleteIRule(irule.Name)
			}
		}
	}
	if !iRef.ab {
		appMgr.deleteIRule(abDeploymentPathIRuleName)
	}
	if !iRef.passthrough && !iRef.reencrypt {
		appMgr.deleteIRule(sslPassthroughIRuleName)
	}
}

// Deletes an IRule from the IRules map, and dereferences it from a Virtual
func (appMgr *Manager) deleteIRule(rule string) {
	ref := nameRef{
		Name:      rule,
		Partition: DEFAULT_PARTITION,
	}
	delete(appMgr.irulesMap, ref)
	fullName := joinBigipPath(DEFAULT_PARTITION, rule)
	for _, cfg := range appMgr.resources.GetAllResources() {
		if cfg.MetaData.ResourceType == "configmap" ||
			cfg.MetaData.ResourceType == "iapp" {
			continue
		}
		cfg.Virtual.RemoveIRule(fullName)
	}
}

func (slice Routes) Len() int {
	return len(slice)
}

func (slice Routes) Less(i, j int) bool {
	return (slice[i].Spec.Host < slice[j].Spec.Host) ||
		(slice[i].Spec.Host == slice[j].Spec.Host &&
			slice[i].Spec.Path < slice[j].Spec.Path)
}

func (slice Routes) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

func (appInf *appInformer) getOrderedRoutes(namespace string) (Routes, error) {
	routeByIndex, err := appInf.routeInformer.GetIndexer().ByIndex(
		"namespace", namespace)
	var routes Routes
	for _, obj := range routeByIndex {
		route := obj.(*routeapi.Route)
		routes = append(routes, route)
	}
	sort.Sort(routes)
	return routes, err
}

func NewServiceFwdRuleMap() ServiceFwdRuleMap {
	return make(ServiceFwdRuleMap)
}

// key is namespace/serviceName, data is map of host to paths.
type ServiceFwdRuleMap map[serviceQueueKey]HostFwdRuleMap

// key is fqdn host name, data is map of paths.
type HostFwdRuleMap map[string]FwdRuleMap

// key is path regex, data unused. Using a map as go doesn't have a set type.
type FwdRuleMap map[string]bool

func (sfrm ServiceFwdRuleMap) AddEntry(ns, svc, host, path string) {
	if path == "" {
		path = "/"
	}
	sKey := serviceQueueKey{Namespace: ns, ServiceName: svc}
	hfrm, found := sfrm[sKey]
	if !found {
		hfrm = make(HostFwdRuleMap)
		sfrm[sKey] = hfrm
	}
	frm, found := hfrm[host]
	if !found {
		frm = make(FwdRuleMap)
		hfrm[host] = frm
	}
	if _, found = frm[path]; !found {
		frm[path] = true
	}
}

func (sfrm ServiceFwdRuleMap) AddToDataGroup(dgMap DataGroupNamespaceMap) {
	// Multiple service keys may reference the same host, so flatten those first
	for skey, hostMap := range sfrm {
		nsGrp, found := dgMap[skey.Namespace]
		if !found {
			nsGrp = &InternalDataGroup{
				Name:      httpsRedirectDgName,
				Partition: DEFAULT_PARTITION,
			}
			dgMap[skey.Namespace] = nsGrp
		}
		for host, pathMap := range hostMap {
			paths := []string{}
			for path, _ := range pathMap {
				paths = append(paths, path)
			}
			// Need to sort the paths to have consistent ordering
			sort.Strings(paths)
			var buf bytes.Buffer
			for i, path := range paths {
				if i > 0 {
					buf.WriteString("|")
				}
				buf.WriteString(path)
			}
			nsGrp.AddOrUpdateRecord(host, buf.String())
		}
	}
}

func flattenConflictWarn(key, oldVal, newVal string) string {
	fmt.Printf("Found mismatch for key '%v' old value: '%v' new value: '%v'\n", key, oldVal, newVal)
	return oldVal
}

func flattenConflictConcat(key, oldVal, newVal string) string {
	// Tokenize both values and add to a map to ensure uniqueness
	pathMap := make(map[string]bool)
	for _, token := range strings.Split(oldVal, "|") {
		pathMap[token] = true
	}
	for _, token := range strings.Split(newVal, "|") {
		pathMap[token] = true
	}

	// Convert back to an array
	paths := []string{}
	for path, _ := range pathMap {
		paths = append(paths, path)
	}

	// Sort the paths to have consistent ordering
	sort.Strings(paths)

	// Write back out to a delimited string
	var buf bytes.Buffer
	for i, path := range paths {
		if i > 0 {
			buf.WriteString("|")
		}
		buf.WriteString(path)
	}

	return buf.String()
}

func (dgnm DataGroupNamespaceMap) FlattenNamespaces() *InternalDataGroup {

	// Try to be efficient in these common cases.
	if len(dgnm) == 0 {
		// No namespaces.
		return nil
	} else if len(dgnm) == 1 {
		// Only 1 namespace, just return its dg - no flattening needed.
		for _, dg := range dgnm {
			return dg
		}
	}

	// Use a map to identify duplicates across namespaces
	var partition, name string
	flatMap := make(map[string]string)
	for _, dg := range dgnm {
		if partition == "" {
			partition = dg.Partition
		}
		if name == "" {
			name = dg.Name
		}
		for _, rec := range dg.Records {
			item, found := flatMap[rec.Name]
			if found {
				if item != rec.Data {
					conflictFunc, ok := groupFlattenFuncMap[dg.Name]
					if !ok {
						log.Warningf("No DataGroup conflict handler defined for '%v'",
							dg.Name)
						conflictFunc = flattenConflictWarn
					}
					newVal := conflictFunc(rec.Name, item, rec.Data)
					flatMap[rec.Name] = newVal
				}
			} else {
				flatMap[rec.Name] = rec.Data
			}
		}
	}

	// Create a new datagroup to hold the flattened results
	newDg := InternalDataGroup{
		Partition: partition,
		Name:      name,
	}
	for name, data := range flatMap {
		newDg.AddOrUpdateRecord(name, data)
	}

	return &newDg
}


text:
package com.admarvel.android.admarvelmologiqadapter;

import android.content.Context;
import com.admarvel.android.ads.internal.Version;
import com.admarvel.android.ads.internal.mediation.AdMarvelAnalyticsAdapter;
import com.mologiq.analytics.MologiqAnalytics;
import java.lang.ref.WeakReference;
import java.util.Map;

public class AdMarvelMologiqAdapter extends AdMarvelAnalyticsAdapter {
    private final WeakReference contextReference;

    public AdMarvelMologiqAdapter(Context context) {
        super(context);
        this.contextReference = new WeakReference(context);
    }

    public void enableAppInstallCheck(boolean z) {
        Context context = (Context) this.contextReference.get();
        if (context != null && Version.getAndroidSDKVersion() >= 8) {
            MologiqAnalytics.getInstance(context).enableAppInstallCheck(context, z);
        }
    }

    public String getAdapterAnalyticsVersion() {
        return "1.4.4 2015-09-10";
    }

    public String getAdapterAnalyticsVersionNumber() {
        return "1.4.4";
    }

    public Map getEnhancedTargetParams(String str, Map map) {
        Context context = (Context) this.contextReference.get();
        return context != null ? Version.getAndroidSDKVersion() >= 8 ? MologiqAnalytics.getInstance(context).getEnhancedTargetParams(str, map) : map : null;
    }

    public void onAdClick(String str, int i, Map map, String str2, String str3) {
        Context context = (Context) this.contextReference.get();
        if (context != null && Version.getAndroidSDKVersion() >= 8) {
            MologiqAnalytics.getInstance(context).onAdClick(str, i, map, str2, str3);
        }
    }

    public void onFailedToReceiveAd(String str, int i, Map map, String str2) {
        Context context = (Context) this.contextReference.get();
        if (context != null && Version.getAndroidSDKVersion() >= 8) {
            MologiqAnalytics.getInstance(context).onFailedToReceiveAd(str, i, map, str2);
        }
    }

    public void onReceiveAd(String str, int i, Map map, String str2) {
        Context context = (Context) this.contextReference.get();
        if (context != null && Version.getAndroidSDKVersion() >= 8) {
            MologiqAnalytics.getInstance(context).onReceiveAd(str, i, map, str2);
        }
    }

    public void pause() {
        Context context = (Context) this.contextReference.get();
        if (context != null && Version.getAndroidSDKVersion() >= 8) {
            MologiqAnalytics.getInstance(context).onPause();
        }
    }

    public void resume() {
        Context context = (Context) this.contextReference.get();
        if (context != null && Version.getAndroidSDKVersion() >= 8) {
            MologiqAnalytics.getInstance(context).onResume();
        }
    }

    public void start() {
        Context context = (Context) this.contextReference.get();
        if (context != null && Version.getAndroidSDKVersion() >= 8) {
            MologiqAnalytics.getInstance(context).onStart();
        }
    }

    public void stop() {
        Context context = (Context) this.contextReference.get();
        if (context != null && Version.getAndroidSDKVersion() >= 8) {
            MologiqAnalytics.getInstance(context).onStop();
        }
    }
}